diff --git a/CMakeLists.txt b/CMakeLists.txt index 1382f146a..7a57b1391 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -46,10 +46,10 @@ IF(MSVC) ENDIF() # "MP" is build with all cores. - SET(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MP${N} /utf-8") - SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MP${N} /utf-8") - SET(CMAKE_CXX_FLAGS_MINSIZEREL "${CMAKE_CXX_FLAGS_MINSIZEREL} /MP${N} /utf-8" ) - SET(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} /MP${N} /utf-8" ) + SET(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MP${N} /utf-8 /std:c++17") + SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MP${N} /utf-8 /std:c++17") + SET(CMAKE_CXX_FLAGS_MINSIZEREL "${CMAKE_CXX_FLAGS_MINSIZEREL} /MP${N} /utf-8 /std:c++17" ) + SET(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} /MP${N} /utf-8 /std:c++17" ) SET(MEGAGLEST_DATA_INSTALL_PATH "${CMAKE_INSTALL_PREFIX}/" CACHE STRING "The installation path for data files ${COMMON_INFO_ABOUT_PATH}") SET(MEGAGLEST_INI_INSTALL_PATH "${MEGAGLEST_DATA_INSTALL_PATH}" CACHE STRING "Install path for ini files") @@ -251,16 +251,16 @@ size_t stack_depth = backtrace(stack_addrs, max_depth); IF(NOT MSVC) # Debug compiler flags - SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g3") + SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g3 -std=c++17") # Release compiler flags - SET(CMAKE_CXX_FLAGS_RELEASE "-O3 ${CMAKE_CXX_FLAGS_RELEASE} -O3 ") + SET(CMAKE_CXX_FLAGS_RELEASE "-O3 ${CMAKE_CXX_FLAGS_RELEASE} -O3 -std=c++17") IF(NOT CMAKE_GENERATOR STREQUAL Xcode) SET(CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS_RELEASE} -s") ## Strip binary ENDIF() # Release with debug info compiler flags - SET(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O3 ${CMAKE_CXX_FLAGS_RELWITHDEBINFO} -g -O3 ") + SET(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O3 ${CMAKE_CXX_FLAGS_RELWITHDEBINFO} -g -O3 -std=c++17") # Release minimum size compiler flags IF(NOT CMAKE_GENERATOR STREQUAL Xcode) diff --git a/source/g3d_viewer/main.cpp b/source/g3d_viewer/main.cpp index ecee638bd..d4cb7cc08 100644 --- a/source/g3d_viewer/main.cpp +++ b/source/g3d_viewer/main.cpp @@ -13,34 +13,34 @@ #include -#include "model_gl.h" -#include "graphics_interface.h" -#include "util.h" +#include "common_scoped_ptr.h" +#include "config.h" #include "conversion.h" +#include "game_constants.h" +#include "graphics_interface.h" +#include "model_gl.h" #include "platform_common.h" +#include "util.h" #include "xml_parser.h" #include +#include #include -#include "config.h" -#include "game_constants.h" #include -#include -#include "common_scoped_ptr.h" #ifndef WIN32 #include #endif #ifndef WIN32 - #define stricmp strcasecmp - #define strnicmp strncasecmp - #define _strnicmp strncasecmp +#define stricmp strcasecmp +#define strnicmp strncasecmp +#define _strnicmp strncasecmp #endif #if wxCHECK_VERSION(2, 9, 1) - #define WX2CHR(x) (x.mb_str()) +#define WX2CHR(x) (x.mb_str()) #else - #define WX2CHR(x) (wxConvCurrent->cWX2MB(x)) +#define WX2CHR(x) (wxConvCurrent->cWX2MB(x)) #endif using namespace Shared::Platform; @@ -59,547 +59,643 @@ const char *folderDelimiter = "\\"; const char *folderDelimiter = "/"; #endif -//int GameConstants::updateFps= 40; -//int GameConstants::cameraFps= 100; +// int GameConstants::updateFps= 40; +// int GameConstants::cameraFps= 100; -const string g3dviewerVersionString= "v3.13-dev"; +const string g3dviewerVersionString = "v3.13-dev"; // Because g3d should always support alpha transparency string fileFormat = "png"; -namespace Glest { namespace Game { +namespace Glest { +namespace Game { string getGameReadWritePath(const string &lookupKey) { - string path = ""; - if(path == "" && getenv("GLESTHOME") != NULL) { - path = safeCharPtrCopy(getenv("GLESTHOME"),8096); - if(path != "" && EndsWith(path, "/") == false && EndsWith(path, "\\") == false) { - path += "/"; - } - - //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] path to be used for read/write files [%s]\n",__FILE__,__FUNCTION__,__LINE__,path.c_str()); + string path = ""; + if (path == "" && getenv("GLESTHOME") != NULL) { + path = safeCharPtrCopy(getenv("GLESTHOME"), 8096); + if (path != "" && EndsWith(path, "/") == false && + EndsWith(path, "\\") == false) { + path += "/"; } - return path; + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] + // path to be used for read/write files + // [%s]\n",__FILE__,__FUNCTION__,__LINE__,path.c_str()); + } + + return path; } -}} +} // namespace Game +} // namespace Glest -namespace Shared{ namespace G3dViewer{ +namespace Shared { +namespace G3dViewer { // =============================================== // class Global functions // =============================================== -wxString ToUnicode(const char* str) { - return wxString(str, wxConvUTF8); -} +wxString ToUnicode(const char *str) { return wxString(str, wxConvUTF8); } -wxString ToUnicode(const string& str) { - return wxString(str.c_str(), wxConvUTF8); +wxString ToUnicode(const string &str) { + return wxString(str.c_str(), wxConvUTF8); } -const wxChar *GAME_ARGS[] = { - wxT("--help"), - wxT("--auto-screenshot"), - wxT("--load-unit"), - wxT("--load-model"), - wxT("--load-model-animation-value"), - wxT("--load-particle"), - wxT("--load-projectile-particle"), - wxT("--load-splash-particle"), - wxT("--load-particle-loop-value"), - wxT("--zoom-value"), - wxT("--rotate-x-value"), - wxT("--rotate-y-value"), - wxT("--screenshot-format"), - wxT("--verbose"), +const wxChar *GAME_ARGS[] = { + wxT("--help"), + wxT("--auto-screenshot"), + wxT("--load-unit"), + wxT("--load-model"), + wxT("--load-model-animation-value"), + wxT("--load-particle"), + wxT("--load-projectile-particle"), + wxT("--load-splash-particle"), + wxT("--load-particle-loop-value"), + wxT("--zoom-value"), + wxT("--rotate-x-value"), + wxT("--rotate-y-value"), + wxT("--screenshot-format"), + wxT("--verbose"), }; enum GAME_ARG_TYPE { - GAME_ARG_HELP = 0, - GAME_ARG_AUTO_SCREENSHOT, - GAME_ARG_LOAD_UNIT, - GAME_ARG_LOAD_MODEL, - GAME_ARG_LOAD_MODEL_ANIMATION_VALUE, - GAME_ARG_LOAD_PARTICLE, - GAME_ARG_LOAD_PARTICLE_PROJECTILE, - GAME_ARG_LOAD_PARTICLE_SPLASH, - GAME_ARG_LOAD_PARTICLE_LOOP_VALUE, - GAME_ARG_ZOOM_VALUE, - GAME_ARG_ROTATE_X_VALUE, - GAME_ARG_ROTATE_Y_VALUE, - GAME_ARG_SCREENSHOT_FORMAT, - GAME_ARG_VERBOSE, + GAME_ARG_HELP = 0, + GAME_ARG_AUTO_SCREENSHOT, + GAME_ARG_LOAD_UNIT, + GAME_ARG_LOAD_MODEL, + GAME_ARG_LOAD_MODEL_ANIMATION_VALUE, + GAME_ARG_LOAD_PARTICLE, + GAME_ARG_LOAD_PARTICLE_PROJECTILE, + GAME_ARG_LOAD_PARTICLE_SPLASH, + GAME_ARG_LOAD_PARTICLE_LOOP_VALUE, + GAME_ARG_ZOOM_VALUE, + GAME_ARG_ROTATE_X_VALUE, + GAME_ARG_ROTATE_Y_VALUE, + GAME_ARG_SCREENSHOT_FORMAT, + GAME_ARG_VERBOSE, }; -bool hasCommandArgument(int argc, wxChar** argv,const string &argName, - int *foundIndex=NULL, int startLookupIndex=1, - bool useArgParamLen=false) { - bool result = false; - - if(foundIndex != NULL) { - *foundIndex = -1; - } - size_t compareLen = strlen(argName.c_str()); - - for(int idx = startLookupIndex; idx < argc; idx++) { - const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(argv[idx]); - //printf("tmp_buf [%s]\n",(const char *)tmp_buf); - if(useArgParamLen == true) { - compareLen = strlen(tmp_buf); - } - if(_strnicmp(argName.c_str(),tmp_buf,compareLen) == 0) { - result = true; - if(foundIndex != NULL) { - *foundIndex = idx; - } - - break; - } - } - return result; +bool hasCommandArgument(int argc, wxChar **argv, const string &argName, + int *foundIndex = NULL, int startLookupIndex = 1, + bool useArgParamLen = false) { + bool result = false; + + if (foundIndex != NULL) { + *foundIndex = -1; + } + size_t compareLen = strlen(argName.c_str()); + + for (int idx = startLookupIndex; idx < argc; idx++) { + const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(argv[idx]); + // printf("tmp_buf [%s]\n",(const char *)tmp_buf); + if (useArgParamLen == true) { + compareLen = strlen(tmp_buf); + } + if (_strnicmp(argName.c_str(), tmp_buf, compareLen) == 0) { + result = true; + if (foundIndex != NULL) { + *foundIndex = idx; + } + + break; + } + } + return result; } void printParameterHelp(const char *argv0, bool foundInvalidArgs) { - if(foundInvalidArgs == true) { - printf("\n"); - } - - // "================================================================================" - printf("\n%s %s, [Using %s]\n",extractFileFromDirectoryPath(argv0).c_str(),g3dviewerVersionString.c_str(),(const char *)wxConvCurrent->cWX2MB(wxVERSION_STRING)); - - printf("\nDisplays glest 3D-models and unit/projectile/splash particle systems.\n"); - printf("\nRotate with left mouse button. Zoom with right mouse button or mousewheel."); - printf("\nUse ctrl to load more than one particle system."); - printf("\nPress R to restart particles, this also reloads all files if they are changed."); - - //printf("\n\noptionally you may use any of the following:\n"); - printf("\n\n%s [G3D FILE], usage",extractFileFromDirectoryPath(argv0).c_str()); - printf("\n\nCommandline Parameter: Description:"); - printf("\n\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"); - printf("\n\n%s \t\tDisplays this help text.",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_HELP])); - - // "================================================================================" - printf("\n\n%s=x \t\tAuto load the unit / skill information specified",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_UNIT])); - printf("\n\n \tin path/filename x."); - printf("\n\n \tWhere x is a g3d filename to load separated with a"); - printf("\n\n \tcomma and one or more skill names to try loading."); - printf("\n\n \texample:"); - printf("\n\n \t%s %s=techs/megapack/factions/",extractFileFromDirectoryPath(argv0).c_str(),(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_UNIT])); - printf("\n\n \ttech/units/battle_machine,attack_skill,stop_skill"); - - printf("\n\n%s=x \tAuto load the model specified in path/filename x.",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL])); - printf("\n\n \tWhere x is a g3d filename to load."); - printf("\n\n \texample:"); - printf("\n\n \t%s %s=techs/megapack/factions/",extractFileFromDirectoryPath(argv0).c_str(),(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL])); - printf("\n\n \ttech/units/battle_machine/models/battle_machine_dying.g3d"); - - printf("\n\n%s=x ",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL_ANIMATION_VALUE])); - printf("\n\n \tAnimation value when loading a model."); - printf("\n\n \tWhere x is a decimal value from -1.0 to 1.0"); - printf("\n\n \texample:"); - printf("\n\n \t%s %s=0.5",extractFileFromDirectoryPath(argv0).c_str(),(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL_ANIMATION_VALUE])); - - // "================================================================================" - printf("\n\n%s=x \tAutomatically takes a screenshot of the items you",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_AUTO_SCREENSHOT])); - printf("\n\n \tare loading."); - printf("\n\n \tWhere x is a comma-delimited list of one or more"); - printf("\n\n \t of the optional settings:"); - printf("\n\n \t transparent, enable_grid, enable_wireframe,"); - printf("\n\n \t enable_normals, disable_grid, disable_wireframe,"); - printf("\n\n \t disable_normals, saveas-, resize-wxh"); - printf("\n\n \texample:"); - printf("\n\n \t%s %s=transparent,",extractFileFromDirectoryPath(argv0).c_str(),(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_AUTO_SCREENSHOT])); - printf("\n\n \tdisable_grid,saveas-test.png,resize-800x600"); - printf("\n\n \t%s=techs/megapack/factions/tech/units/",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL])); - printf("\n\n \tbattle_machine/models/battle_machine_dying.g3d"); - - // "================================================================================" - printf("\n\n%s=x \tAuto load the particle specified in path/filename x.",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE])); - printf("\n\n \tWhere x is a Particle XML filename to load."); - printf("\n\n \texample:"); - printf("\n\n \t%s %s=techs/megapack/factions/",extractFileFromDirectoryPath(argv0).c_str(),(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE])); - printf("\n\n \tpersian/units/genie/glow_particles.xml"); - - printf("\n\n%s=x ",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_PROJECTILE])); - printf("\n\n \tAuto load the projectile particle specified in"); - printf("\n\n \tpath/filename x."); - printf("\n\n \tWhere x is a Projectile Particle Definition XML"); - printf("\n\n \t filename to load."); - printf("\n\n \texample:"); - printf("\n\n \t%s %s=techs/megapack/",extractFileFromDirectoryPath(argv0).c_str(),(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_PROJECTILE])); - printf("\n\n \tfactions/persian/units/genie/particle_proj.xml"); - - printf("\n\n%s=x ",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_SPLASH])); - printf("\n\n \tAuto load the splash particle specified in"); - printf("\n\n \tpath/filename x."); - printf("\n\n \tWhere x is a Splash Particle Definition XML"); - printf("\n\n \t filename to load."); - printf("\n\n \texample:"); - printf("\n\n \t%s %s=techs/megapack/",extractFileFromDirectoryPath(argv0).c_str(),(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_SPLASH])); - printf("\n\n \tfactions/persian/units/genie/particle_splash.xml"); - - printf("\n\n%s=x ",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_LOOP_VALUE])); - printf("\n\n \tParticle loop value when loading one or more"); - printf("\n\n \tparticles."); - printf("\n\n \tWhere x is an integer value from 1 to particle count."); - printf("\n\n \texample:"); - printf("\n\n \t%s %s=25",extractFileFromDirectoryPath(argv0).c_str(),(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_LOOP_VALUE])); - - printf("\n\n%s=x \tZoom value when loading a model.",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ZOOM_VALUE])); - printf("\n\n \tWhere x is a decimal value from 0.1 to 10.0"); - printf("\n\n \texample:"); - printf("\n\n \t%s %s=4.2",extractFileFromDirectoryPath(argv0).c_str(),(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ZOOM_VALUE])); - - printf("\n\n%s=x \tX Coordinate Rotation value when loading a model.",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_X_VALUE])); - printf("\n\n \tWhere x is a decimal value from -10.0 to 10.0"); - printf("\n\n \texample:"); - printf("\n\n \t%s %s=2.2",extractFileFromDirectoryPath(argv0).c_str(),(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_X_VALUE])); - - printf("\n\n%s=x \tY Coordinate Rotation value when loading a model.",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_Y_VALUE])); - printf("\n\n \tWhere x is a decimal value from -10.0 to 10.0"); - printf("\n\n \texample:"); - printf("\n\n \t%s %s=2.2",extractFileFromDirectoryPath(argv0).c_str(),(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_Y_VALUE])); - - printf("\n\n%s=x \tSpecify which image format to use for screenshots.",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_SCREENSHOT_FORMAT])); - printf("\n\n \tWhere x is one of the following supported formats:"); - printf("\n\n \t png,jpg,tga,bmp"); - printf("\n\n \t*NOTE: png is the default (and supports transparency)"); - printf("\n\n \texample:"); - printf("\n\n \t%s %s=jpg",extractFileFromDirectoryPath(argv0).c_str(),(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_SCREENSHOT_FORMAT])); - - printf("\n\n"); + if (foundInvalidArgs == true) { + printf("\n"); + } + + // "================================================================================" + printf("\n%s %s, [Using %s]\n", extractFileFromDirectoryPath(argv0).c_str(), + g3dviewerVersionString.c_str(), + (const char *)wxConvCurrent->cWX2MB(wxVERSION_STRING)); + + printf("\nDisplays glest 3D-models and unit/projectile/splash particle " + "systems.\n"); + printf("\nRotate with left mouse button. Zoom with right mouse button or " + "mousewheel."); + printf("\nUse ctrl to load more than one particle system."); + printf("\nPress R to restart particles, this also reloads all files if they " + "are changed."); + + // printf("\n\noptionally you may use any of the following:\n"); + printf("\n\n%s [G3D FILE], usage", + extractFileFromDirectoryPath(argv0).c_str()); + printf("\n\nCommandline Parameter: Description:"); + printf("\n\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - " + "- - - -"); + printf("\n\n%s \t\tDisplays this help text.", + (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_HELP])); + + // "================================================================================" + printf("\n\n%s=x \t\tAuto load the unit / skill information specified", + (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_UNIT])); + printf("\n\n \tin path/filename x."); + printf("\n\n \tWhere x is a g3d filename to load " + "separated with a"); + printf("\n\n \tcomma and one or more skill names to try " + "loading."); + printf("\n\n \texample:"); + printf("\n\n \t%s %s=techs/megapack/factions/", + extractFileFromDirectoryPath(argv0).c_str(), + (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_UNIT])); + printf("\n\n " + "\ttech/units/battle_machine,attack_skill,stop_skill"); + + printf("\n\n%s=x \tAuto load the model specified in path/filename x.", + (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL])); + printf("\n\n \tWhere x is a g3d filename to load."); + printf("\n\n \texample:"); + printf("\n\n \t%s %s=techs/megapack/factions/", + extractFileFromDirectoryPath(argv0).c_str(), + (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL])); + printf("\n\n " + "\ttech/units/battle_machine/models/battle_machine_dying.g3d"); + + printf("\n\n%s=x ", (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_LOAD_MODEL_ANIMATION_VALUE])); + printf("\n\n \tAnimation value when loading a model."); + printf( + "\n\n \tWhere x is a decimal value from -1.0 to 1.0"); + printf("\n\n \texample:"); + printf("\n\n \t%s %s=0.5", + extractFileFromDirectoryPath(argv0).c_str(), + (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_LOAD_MODEL_ANIMATION_VALUE])); + + // "================================================================================" + printf( + "\n\n%s=x \tAutomatically takes a screenshot of the items you", + (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_AUTO_SCREENSHOT])); + printf("\n\n \tare loading."); + printf("\n\n \tWhere x is a comma-delimited list of one " + "or more"); + printf("\n\n \t of the optional settings:"); + printf("\n\n \t transparent, enable_grid, " + "enable_wireframe,"); + printf("\n\n \t enable_normals, disable_grid, " + "disable_wireframe,"); + printf("\n\n \t disable_normals, saveas-, " + "resize-wxh"); + printf("\n\n \texample:"); + printf( + "\n\n \t%s %s=transparent,", + extractFileFromDirectoryPath(argv0).c_str(), + (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_AUTO_SCREENSHOT])); + printf( + "\n\n \tdisable_grid,saveas-test.png,resize-800x600"); + printf("\n\n \t%s=techs/megapack/factions/tech/units/", + (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL])); + printf("\n\n " + "\tbattle_machine/models/battle_machine_dying.g3d"); + + // "================================================================================" + printf( + "\n\n%s=x \tAuto load the particle specified in path/filename x.", + (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE])); + printf( + "\n\n \tWhere x is a Particle XML filename to load."); + printf("\n\n \texample:"); + printf( + "\n\n \t%s %s=techs/megapack/factions/", + extractFileFromDirectoryPath(argv0).c_str(), + (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE])); + printf("\n\n \tpersian/units/genie/glow_particles.xml"); + + printf("\n\n%s=x ", (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_LOAD_PARTICLE_PROJECTILE])); + printf("\n\n \tAuto load the projectile particle " + "specified in"); + printf("\n\n \tpath/filename x."); + printf("\n\n \tWhere x is a Projectile Particle " + "Definition XML"); + printf("\n\n \t filename to load."); + printf("\n\n \texample:"); + printf("\n\n \t%s %s=techs/megapack/", + extractFileFromDirectoryPath(argv0).c_str(), + (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_LOAD_PARTICLE_PROJECTILE])); + printf("\n\n " + "\tfactions/persian/units/genie/particle_proj.xml"); + + printf("\n\n%s=x ", (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_LOAD_PARTICLE_SPLASH])); + printf( + "\n\n \tAuto load the splash particle specified in"); + printf("\n\n \tpath/filename x."); + printf( + "\n\n \tWhere x is a Splash Particle Definition XML"); + printf("\n\n \t filename to load."); + printf("\n\n \texample:"); + printf("\n\n \t%s %s=techs/megapack/", + extractFileFromDirectoryPath(argv0).c_str(), + (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_LOAD_PARTICLE_SPLASH])); + printf("\n\n " + "\tfactions/persian/units/genie/particle_splash.xml"); + + printf("\n\n%s=x ", (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_LOAD_PARTICLE_LOOP_VALUE])); + printf("\n\n \tParticle loop value when loading one or " + "more"); + printf("\n\n \tparticles."); + printf("\n\n \tWhere x is an integer value from 1 to " + "particle count."); + printf("\n\n \texample:"); + printf("\n\n \t%s %s=25", + extractFileFromDirectoryPath(argv0).c_str(), + (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_LOAD_PARTICLE_LOOP_VALUE])); + + printf("\n\n%s=x \tZoom value when loading a model.", + (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ZOOM_VALUE])); + printf( + "\n\n \tWhere x is a decimal value from 0.1 to 10.0"); + printf("\n\n \texample:"); + printf("\n\n \t%s %s=4.2", + extractFileFromDirectoryPath(argv0).c_str(), + (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ZOOM_VALUE])); + + printf( + "\n\n%s=x \tX Coordinate Rotation value when loading a model.", + (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_X_VALUE])); + printf("\n\n \tWhere x is a decimal value from -10.0 to " + "10.0"); + printf("\n\n \texample:"); + printf( + "\n\n \t%s %s=2.2", + extractFileFromDirectoryPath(argv0).c_str(), + (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_X_VALUE])); + + printf( + "\n\n%s=x \tY Coordinate Rotation value when loading a model.", + (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_Y_VALUE])); + printf("\n\n \tWhere x is a decimal value from -10.0 to " + "10.0"); + printf("\n\n \texample:"); + printf( + "\n\n \t%s %s=2.2", + extractFileFromDirectoryPath(argv0).c_str(), + (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_Y_VALUE])); + + printf("\n\n%s=x \tSpecify which image format to use for screenshots.", + (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_SCREENSHOT_FORMAT])); + printf("\n\n \tWhere x is one of the following supported " + "formats:"); + printf("\n\n \t png,jpg,tga,bmp"); + printf("\n\n \t*NOTE: png is the default (and supports " + "transparency)"); + printf("\n\n \texample:"); + printf("\n\n \t%s %s=jpg", + extractFileFromDirectoryPath(argv0).c_str(), + (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_SCREENSHOT_FORMAT])); + + printf("\n\n"); } bool autoScreenShotAndExit = false; vector autoScreenShotParams; -std::pair overrideSize(0,0); +std::pair overrideSize(0, 0); // =============================================== // class MainWindow // =============================================== -const string MainWindow::winHeader= "G3D viewer " + g3dviewerVersionString; +const string MainWindow::winHeader = "G3D viewer " + g3dviewerVersionString; const float defaultspeed = 0.025f; -MainWindow::MainWindow( std::pair > unitToLoad, - const string modelPath, - const string particlePath, - const string projectileParticlePath, - const string splashParticlePath, - float defaultAnimation, - int defaultParticleLoopStart, - float defaultZoom,float defaultXRot, float defaultYRot, - string appPath) - : wxFrame(NULL, -1, ToUnicode(winHeader), - wxPoint(Renderer::windowX, Renderer::windowY), - wxSize(Renderer::windowW, Renderer::windowH)), - glCanvas(NULL), - renderer(NULL), - timer(NULL), - menu(NULL), - fileDialog(NULL), - colorPicker(NULL), - model(NULL), - initTextureManager(true), - startupSettingsInited(false) +MainWindow::MainWindow(std::pair> unitToLoad, + const string modelPath, const string particlePath, + const string projectileParticlePath, + const string splashParticlePath, float defaultAnimation, + int defaultParticleLoopStart, float defaultZoom, + float defaultXRot, float defaultYRot, string appPath) + : wxFrame(NULL, -1, ToUnicode(winHeader), + wxPoint(Renderer::windowX, Renderer::windowY), + wxSize(Renderer::windowW, Renderer::windowH)), + glCanvas(NULL), renderer(NULL), timer(NULL), menu(NULL), fileDialog(NULL), + colorPicker(NULL), model(NULL), initTextureManager(true), + startupSettingsInited(false) { - this->appPath = appPath; - Properties::setApplicationPath(executable_path(appPath)); + this->appPath = appPath; + Properties::setApplicationPath(executable_path(appPath)); #ifndef NO_APPIMAGE - Properties::setAppDirPath(); + Properties::setAppDirPath(); #ifdef APPIMAGE_NODATA - Properties::setAppimageDirPath(); + Properties::setAppimageDirPath(); #endif #endif - lastanim = 0; - model= NULL; + lastanim = 0; + model = NULL; - Config &config = Config::getInstance(); + Config &config = Config::getInstance(); - isControlKeyPressed = false; + isControlKeyPressed = false; - initGlCanvas(); + initGlCanvas(); #if wxCHECK_VERSION(2, 9, 1) #else - glCanvas->SetCurrent(); + glCanvas->SetCurrent(); #endif - unitPath = unitToLoad; - - if(modelPath != "") { - this->modelPathList.push_back(modelPath); - printf("Startup Adding model [%s] list size " MG_SIZE_T_SPECIFIER "\n",modelPath.c_str(),this->modelPathList.size()); - } - if(particlePath != "") { - this->particlePathList.push_back(particlePath); - } - if(projectileParticlePath != "") { - this->particleProjectilePathList.push_back(projectileParticlePath); - } - if(splashParticlePath != "") { - this->particleSplashPathList.push_back(splashParticlePath); - } - - resetAnimation = false; - anim = defaultAnimation; - particleLoopStart = defaultParticleLoopStart; - resetAnim = anim; - resetParticleLoopStart = particleLoopStart; - rotX= defaultXRot; - rotY= defaultYRot; - zoom= defaultZoom; - playerColor= Renderer::pcRed; - - speed= defaultspeed; - - //getGlPlatformExtensions(); - menu= new wxMenuBar(); - - //menu - menuFile= new wxMenu(); - menuFile->Append(miFileLoad, wxT("&Load G3d model\tCtrl+L"), wxT("Load 3D model")); - menuFile->Append(miFileLoadParticleXML, wxT("Load &Particle XML\tCtrl+P"), wxT("Press ctrl before menu for keeping current particles")); - menuFile->Append(miFileLoadProjectileParticleXML, wxT("Load Pro&jectile Particle XML\tCtrl+J"), wxT("Press ctrl before menu for keeping current projectile particles")); - menuFile->Append(miFileLoadSplashParticleXML, wxT("Load &Splash Particle XML\tCtrl+S"), wxT("Press ctrl before menu for keeping current splash particles")); - menuFile->Append(miFileClearAll, wxT("&Clear All\tCtrl+C")); - menuFile->AppendCheckItem(miFileToggleScreenshotTransparent, wxT("&Transparent Screenshots\tCtrl+T")); - menuFile->Append(miFileSaveScreenshot, wxT("Sa&ve a Screenshot\tCtrl+V")); - menuFile->AppendSeparator(); - menuFile->Append(wxID_EXIT); - menu->Append(menuFile, wxT("&File")); - - //mode - menuMode= new wxMenu(); - menuMode->AppendCheckItem(miModeNormals, wxT("&Normals")); - menuMode->AppendCheckItem(miModeWireframe, wxT("&Wireframe")); - menuMode->AppendCheckItem(miModeGrid, wxT("&Grid")); - menu->Append(menuMode, wxT("&Mode")); - - //mode - menuSpeed= new wxMenu(); - menuSpeed->Append(miSpeedSlower, wxT("&Slower\t-")); - menuSpeed->Append(miSpeedFaster, wxT("&Faster\t+")); - menuSpeed->AppendSeparator(); - menuSpeed->Append(miRestart, wxT("&Restart particles\tR"), wxT("Restart particle animations, this also reloads model and particle files if they are changed")); - menu->Append(menuSpeed, wxT("&Speed")); - - //custom color - menuCustomColor= new wxMenu(); - menuCustomColor->Append(miChangeBackgroundColor, wxT("Change Background Color")); - menuCustomColor->AppendCheckItem(miColorRed, wxT("&Red\t0")); - menuCustomColor->AppendCheckItem(miColorBlue, wxT("&Blue\t1")); - menuCustomColor->AppendCheckItem(miColorGreen, wxT("&Green\t2")); - menuCustomColor->AppendCheckItem(miColorYellow, wxT("&Yellow\t3")); - menuCustomColor->AppendCheckItem(miColorWhite, wxT("&White\t4")); - menuCustomColor->AppendCheckItem(miColorCyan, wxT("&Cyan\t5")); - menuCustomColor->AppendCheckItem(miColorOrange, wxT("&Orange\t6")); - menuCustomColor->AppendCheckItem(miColorMagenta, wxT("&Pink\t7")); // it is called Pink everywhere else so... - menu->Append(menuCustomColor, wxT("&Custom Color")); - - menuMode->Check(miModeGrid, true); - menuCustomColor->Check(miColorRed, true); - - SetMenuBar(menu); - - //misc - backBrightness= 0.3f; - gridBrightness= 1.0f; - lightBrightness= 0.3f; - lastX= 0; - lastY= 0; - - statusbarText=""; - CreateStatusBar(); - - this->Layout(); - - wxInitAllImageHandlers(); + unitPath = unitToLoad; + + if (modelPath != "") { + this->modelPathList.push_back(modelPath); + printf("Startup Adding model [%s] list size " MG_SIZE_T_SPECIFIER "\n", + modelPath.c_str(), this->modelPathList.size()); + } + if (particlePath != "") { + this->particlePathList.push_back(particlePath); + } + if (projectileParticlePath != "") { + this->particleProjectilePathList.push_back(projectileParticlePath); + } + if (splashParticlePath != "") { + this->particleSplashPathList.push_back(splashParticlePath); + } + + resetAnimation = false; + anim = defaultAnimation; + particleLoopStart = defaultParticleLoopStart; + resetAnim = anim; + resetParticleLoopStart = particleLoopStart; + rotX = defaultXRot; + rotY = defaultYRot; + zoom = defaultZoom; + playerColor = Renderer::pcRed; + + speed = defaultspeed; + + // getGlPlatformExtensions(); + menu = new wxMenuBar(); + + // menu + menuFile = new wxMenu(); + menuFile->Append(miFileLoad, wxT("&Load G3d model\tCtrl+L"), + wxT("Load 3D model")); + menuFile->Append(miFileLoadParticleXML, wxT("Load &Particle XML\tCtrl+P"), + wxT("Press ctrl before menu for keeping current particles")); + menuFile->Append( + miFileLoadProjectileParticleXML, + wxT("Load Pro&jectile Particle XML\tCtrl+J"), + wxT("Press ctrl before menu for keeping current projectile particles")); + menuFile->Append( + miFileLoadSplashParticleXML, wxT("Load &Splash Particle XML\tCtrl+S"), + wxT("Press ctrl before menu for keeping current splash particles")); + menuFile->Append(miFileClearAll, wxT("&Clear All\tCtrl+C")); + menuFile->AppendCheckItem(miFileToggleScreenshotTransparent, + wxT("&Transparent Screenshots\tCtrl+T")); + menuFile->Append(miFileSaveScreenshot, wxT("Sa&ve a Screenshot\tCtrl+V")); + menuFile->AppendSeparator(); + menuFile->Append(wxID_EXIT); + menu->Append(menuFile, wxT("&File")); + + // mode + menuMode = new wxMenu(); + menuMode->AppendCheckItem(miModeNormals, wxT("&Normals")); + menuMode->AppendCheckItem(miModeWireframe, wxT("&Wireframe")); + menuMode->AppendCheckItem(miModeGrid, wxT("&Grid")); + menu->Append(menuMode, wxT("&Mode")); + + // mode + menuSpeed = new wxMenu(); + menuSpeed->Append(miSpeedSlower, wxT("&Slower\t-")); + menuSpeed->Append(miSpeedFaster, wxT("&Faster\t+")); + menuSpeed->AppendSeparator(); + menuSpeed->Append(miRestart, wxT("&Restart particles\tR"), + wxT("Restart particle animations, this also reloads model " + "and particle files if they are changed")); + menu->Append(menuSpeed, wxT("&Speed")); + + // custom color + menuCustomColor = new wxMenu(); + menuCustomColor->Append(miChangeBackgroundColor, + wxT("Change Background Color")); + menuCustomColor->AppendCheckItem(miColorRed, wxT("&Red\t0")); + menuCustomColor->AppendCheckItem(miColorBlue, wxT("&Blue\t1")); + menuCustomColor->AppendCheckItem(miColorGreen, wxT("&Green\t2")); + menuCustomColor->AppendCheckItem(miColorYellow, wxT("&Yellow\t3")); + menuCustomColor->AppendCheckItem(miColorWhite, wxT("&White\t4")); + menuCustomColor->AppendCheckItem(miColorCyan, wxT("&Cyan\t5")); + menuCustomColor->AppendCheckItem(miColorOrange, wxT("&Orange\t6")); + menuCustomColor->AppendCheckItem( + miColorMagenta, + wxT("&Pink\t7")); // it is called Pink everywhere else so... + menu->Append(menuCustomColor, wxT("&Custom Color")); + + menuMode->Check(miModeGrid, true); + menuCustomColor->Check(miColorRed, true); + + SetMenuBar(menu); + + // misc + backBrightness = 0.3f; + gridBrightness = 1.0f; + lightBrightness = 0.3f; + lastX = 0; + lastY = 0; + + statusbarText = ""; + CreateStatusBar(); + + this->Layout(); + + wxInitAllImageHandlers(); #ifdef WIN32 #if defined(__MINGW32__) - wxIcon icon(ToUnicode("IDI_ICON1")); + wxIcon icon(ToUnicode("IDI_ICON1")); #else - wxIcon icon(L"IDI_ICON1"); + wxIcon icon(L"IDI_ICON1"); #endif #else - wxIcon icon; - string iniFilePath = extractDirectoryPathFromFile(config.getFileName(false)); - string icon_file = iniFilePath + "g3dviewer.ico"; - std::ifstream testFile(icon_file.c_str()); - if(testFile.good()) { - testFile.close(); - icon.LoadFile(ToUnicode(icon_file.c_str()),wxBITMAP_TYPE_ICO); - } + wxIcon icon; + string iniFilePath = extractDirectoryPathFromFile(config.getFileName(false)); + string icon_file = iniFilePath + "g3dviewer.ico"; + std::ifstream testFile(icon_file.c_str()); + if (testFile.good()) { + testFile.close(); + icon.LoadFile(ToUnicode(icon_file.c_str()), wxBITMAP_TYPE_ICO); + } #endif - SetIcon(icon); - - fileDialog = new wxFileDialog(this); - if(modelPath != "") { - fileDialog->SetPath(ToUnicode(modelPath)); - } - string userData = config.getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - string defaultPath = userData + "techs/"; - fileDialog->SetDirectory(ToUnicode(defaultPath.c_str())); - - - if(glCanvas != NULL) { - glCanvas->SetFocus(); - } - - // For windows register g3d file extension to launch this app + SetIcon(icon); + + fileDialog = new wxFileDialog(this); + if (modelPath != "") { + fileDialog->SetPath(ToUnicode(modelPath)); + } + string userData = config.getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + string defaultPath = userData + "techs/"; + fileDialog->SetDirectory(ToUnicode(defaultPath.c_str())); + + if (glCanvas != NULL) { + glCanvas->SetFocus(); + } + + // For windows register g3d file extension to launch this app #if defined(WIN32) && !defined(__MINGW32__) - // example from: http://stackoverflow.com/questions/1387769/create-registry-entry-to-associate-file-extension-with-application-in-c - //[HKEY_CURRENT_USER\Software\Classes\blergcorp.blergapp.v1\shell\open\command] - //@="c:\path\to\app.exe \"%1\"" - //[HKEY_CURRENT_USER\Software\Classes\.blerg] - //@="blergcorp.blergapp.v1" - - //Open the registry key. - wstring subKey = L"Software\\Classes\\megaglest.g3d\\shell\\open\\command"; - HKEY keyHandle; - DWORD dwDisposition; - RegCreateKeyEx(HKEY_CURRENT_USER,subKey.c_str(),0, NULL, 0, KEY_ALL_ACCESS, NULL, &keyHandle, &dwDisposition); - //Set the value. - auto_ptr wstr(Ansi2WideString(appPath.c_str())); - - wstring launchApp = wstring(wstr.get()) + L" \"%1\""; - DWORD len = (launchApp.size() + 1) * sizeof(wchar_t); - RegSetValueEx(keyHandle, NULL, 0, REG_SZ, (PBYTE)launchApp.c_str(), len); - RegCloseKey(keyHandle); - - subKey = L"Software\\Classes\\.g3d"; - RegCreateKeyEx(HKEY_CURRENT_USER,subKey.c_str(),0, NULL, 0, KEY_ALL_ACCESS, NULL, &keyHandle, &dwDisposition); - //Set the value. - launchApp = L"megaglest.g3d"; - len = (launchApp.size() + 1) * sizeof(wchar_t); - RegSetValueEx(keyHandle, NULL, 0, REG_SZ, (PBYTE)launchApp.c_str(), len); - RegCloseKey(keyHandle); + // example from: + // http://stackoverflow.com/questions/1387769/create-registry-entry-to-associate-file-extension-with-application-in-c + //[HKEY_CURRENT_USER\Software\Classes\blergcorp.blergapp.v1\shell\open\command] + //@="c:\path\to\app.exe \"%1\"" + //[HKEY_CURRENT_USER\Software\Classes\.blerg] + //@="blergcorp.blergapp.v1" + + // Open the registry key. + wstring subKey = L"Software\\Classes\\megaglest.g3d\\shell\\open\\command"; + HKEY keyHandle; + DWORD dwDisposition; + RegCreateKeyEx(HKEY_CURRENT_USER, subKey.c_str(), 0, NULL, 0, KEY_ALL_ACCESS, + NULL, &keyHandle, &dwDisposition); + // Set the value. + auto_ptr wstr(Ansi2WideString(appPath.c_str())); + + wstring launchApp = wstring(wstr.get()) + L" \"%1\""; + DWORD len = (launchApp.size() + 1) * sizeof(wchar_t); + RegSetValueEx(keyHandle, NULL, 0, REG_SZ, (PBYTE)launchApp.c_str(), len); + RegCloseKey(keyHandle); + + subKey = L"Software\\Classes\\.g3d"; + RegCreateKeyEx(HKEY_CURRENT_USER, subKey.c_str(), 0, NULL, 0, KEY_ALL_ACCESS, + NULL, &keyHandle, &dwDisposition); + // Set the value. + launchApp = L"megaglest.g3d"; + len = (launchApp.size() + 1) * sizeof(wchar_t); + RegSetValueEx(keyHandle, NULL, 0, REG_SZ, (PBYTE)launchApp.c_str(), len); + RegCloseKey(keyHandle); #endif } void MainWindow::setupTimer() { - timer = new wxTimer(this); - timer->Start(100); + timer = new wxTimer(this); + timer->Start(100); } void MainWindow::setupStartupSettings() { - //printf("In setupStartupSettings #1\n"); - if(glCanvas == NULL) { - initGlCanvas(); + // printf("In setupStartupSettings #1\n"); + if (glCanvas == NULL) { + initGlCanvas(); #if wxCHECK_VERSION(2, 9, 1) #else - glCanvas->SetCurrent(); + glCanvas->SetCurrent(); #endif + } + glCanvas->setCurrentGLContext(); + // printf("In setupStartupSettings #2\n"); + + GLuint err = glewInit(); + if (GLEW_OK != err) { + fprintf(stderr, "Error [main]: glewInit failed: %s\n", + glewGetErrorString(err)); + // return 1; + throw std::runtime_error((char *)glewGetErrorString(err)); + } + + renderer = Renderer::getInstance(); + + for (unsigned int i = 0; i < autoScreenShotParams.size(); ++i) { + if (autoScreenShotParams[i] == "transparent") { + printf("Screenshot option [%s]\n", autoScreenShotParams[i].c_str()); + menuFile->Check(miFileToggleScreenshotTransparent, true); + float alpha = 0.0f; + renderer->setAlphaColor(alpha); + } + if (autoScreenShotParams[i] == "enable_grid") { + printf("Screenshot option [%s]\n", autoScreenShotParams[i].c_str()); + menuMode->Check(miModeGrid, true); + if (renderer->getGrid() == false) { + renderer->toggleGrid(); + } + } + if (autoScreenShotParams[i] == "enable_wireframe") { + printf("Screenshot option [%s]\n", autoScreenShotParams[i].c_str()); + menuMode->Check(miModeWireframe, true); + if (renderer->getWireframe() == false) { + renderer->toggleWireframe(); + } + } + if (autoScreenShotParams[i] == "enable_normals") { + printf("Screenshot option [%s]\n", autoScreenShotParams[i].c_str()); + menuMode->Check(miModeNormals, true); + if (renderer->getNormals() == false) { + renderer->toggleNormals(); + } + } + if (autoScreenShotParams[i] == "disable_grid") { + printf("Screenshot option [%s]\n", autoScreenShotParams[i].c_str()); + menuMode->Check(miModeGrid, false); + if (renderer->getGrid() == true) { + renderer->toggleGrid(); + } + } + if (autoScreenShotParams[i] == "enable_wireframe") { + printf("Screenshot option [%s]\n", autoScreenShotParams[i].c_str()); + menuMode->Check(miModeWireframe, false); + if (renderer->getWireframe() == true) { + renderer->toggleWireframe(); + } + } + if (autoScreenShotParams[i] == "enable_normals") { + printf("Screenshot option [%s]\n", autoScreenShotParams[i].c_str()); + menuMode->Check(miModeNormals, false); + if (renderer->getNormals() == true) { + renderer->toggleNormals(); + } + } + } + renderer->init(); - } - glCanvas->setCurrentGLContext(); - //printf("In setupStartupSettings #2\n"); - - GLuint err = glewInit(); - if (GLEW_OK != err) { - fprintf(stderr, "Error [main]: glewInit failed: %s\n", glewGetErrorString(err)); - //return 1; - throw std::runtime_error((char *)glewGetErrorString(err)); - } - - renderer= Renderer::getInstance(); - - for(unsigned int i = 0; i < autoScreenShotParams.size(); ++i) { - if(autoScreenShotParams[i] == "transparent") { - printf("Screenshot option [%s]\n",autoScreenShotParams[i].c_str()); - menuFile->Check(miFileToggleScreenshotTransparent,true); - float alpha = 0.0f; - renderer->setAlphaColor(alpha); - } - if(autoScreenShotParams[i] == "enable_grid") { - printf("Screenshot option [%s]\n",autoScreenShotParams[i].c_str()); - menuMode->Check(miModeGrid,true); - if(renderer->getGrid() == false) { - renderer->toggleGrid(); - } - } - if(autoScreenShotParams[i] == "enable_wireframe") { - printf("Screenshot option [%s]\n",autoScreenShotParams[i].c_str()); - menuMode->Check(miModeWireframe,true); - if(renderer->getWireframe() == false) { - renderer->toggleWireframe(); - } - } - if(autoScreenShotParams[i] == "enable_normals") { - printf("Screenshot option [%s]\n",autoScreenShotParams[i].c_str()); - menuMode->Check(miModeNormals,true); - if(renderer->getNormals() == false) { - renderer->toggleNormals(); - } - } - if(autoScreenShotParams[i] == "disable_grid") { - printf("Screenshot option [%s]\n",autoScreenShotParams[i].c_str()); - menuMode->Check(miModeGrid,false); - if(renderer->getGrid() == true) { - renderer->toggleGrid(); - } - } - if(autoScreenShotParams[i] == "enable_wireframe") { - printf("Screenshot option [%s]\n",autoScreenShotParams[i].c_str()); - menuMode->Check(miModeWireframe,false); - if(renderer->getWireframe() == true) { - renderer->toggleWireframe(); - } - } - if(autoScreenShotParams[i] == "enable_normals") { - printf("Screenshot option [%s]\n",autoScreenShotParams[i].c_str()); - menuMode->Check(miModeNormals,false); - if(renderer->getNormals() == true) { - renderer->toggleNormals(); - } - } - } - renderer->init(); - - onMenuRestartNoEvent(); + onMenuRestartNoEvent(); } -MainWindow::~MainWindow(){ - delete timer; - timer = NULL; +MainWindow::~MainWindow() { + delete timer; + timer = NULL; - delete fileDialog; - fileDialog = NULL; + delete fileDialog; + fileDialog = NULL; - //delete model; - //model = NULL; - if(renderer) renderer->end(); + // delete model; + // model = NULL; + if (renderer) + renderer->end(); - delete renderer; - renderer = NULL; - - if(glCanvas) { - glCanvas->Destroy(); - } - glCanvas = NULL; + delete renderer; + renderer = NULL; + if (glCanvas) { + glCanvas->Destroy(); + } + glCanvas = NULL; } -void MainWindow::initGlCanvas(){ - if(glCanvas == NULL) { - int args[] = { WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_MIN_ALPHA, 8, 0 }; // to prevent flicker - glCanvas = new GlCanvas(this, args); - } +void MainWindow::initGlCanvas() { + if (glCanvas == NULL) { + int args[] = {WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_MIN_ALPHA, 8, + 0}; // to prevent flicker + glCanvas = new GlCanvas(this, args); + } } void MainWindow::init() { @@ -609,1395 +705,1617 @@ void MainWindow::init() { #elif wxCHECK_VERSION(2, 9, 1) #else - glCanvas->SetCurrent(); - //printf("setcurrent #2\n"); + glCanvas->SetCurrent(); + // printf("setcurrent #2\n"); #endif } void MainWindow::onPaint(wxPaintEvent &event) { - if(!IsShown()) { - event.Skip(); - return; - } + if (!IsShown()) { + event.Skip(); + return; + } - onPaintNoEvent( ); + onPaintNoEvent(); } -void MainWindow::onPaintNoEvent( ) { - bool isFirstWindowShownEvent = !startupSettingsInited ; - if(startupSettingsInited == false) { - startupSettingsInited = true; - setupStartupSettings(); - } - glCanvas->setCurrentGLContext(); - - static float autoScreenshotRender = -1; - if(autoScreenShotAndExit == true && autoScreenshotRender >= 0) { - anim = autoScreenshotRender; - } - // notice that we use GetSize() here and not GetClientSize() because - // the latter doesn't return correct results for the minimized windows - // (at least not under Windows) - int viewportW = GetClientSize().x; - int viewportH = GetClientSize().y; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%d x %d\n",viewportW,viewportH); - - if(viewportW == 0 && viewportH == 0) { - printf("#1 %d x %d\n",viewportW,viewportH); - - viewportW = GetSize().x; - viewportH = GetSize().y; - - if(viewportH > 0) { - //viewportH -= menu->GetSize().y; - viewportH -= 22; - } +void MainWindow::onPaintNoEvent() { + bool isFirstWindowShownEvent = !startupSettingsInited; + if (startupSettingsInited == false) { + startupSettingsInited = true; + setupStartupSettings(); + } + glCanvas->setCurrentGLContext(); + + static float autoScreenshotRender = -1; + if (autoScreenShotAndExit == true && autoScreenshotRender >= 0) { + anim = autoScreenshotRender; + } + // notice that we use GetSize() here and not GetClientSize() because + // the latter doesn't return correct results for the minimized windows + // (at least not under Windows) + int viewportW = GetClientSize().x; + int viewportH = GetClientSize().y; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("%d x %d\n", viewportW, viewportH); + + if (viewportW == 0 && viewportH == 0) { + printf("#1 %d x %d\n", viewportW, viewportH); + + viewportW = GetSize().x; + viewportH = GetSize().y; + + if (viewportH > 0) { + // viewportH -= menu->GetSize().y; + viewportH -= 22; + } - printf("#2 %d x %d\n",viewportW,viewportH); - } + printf("#2 %d x %d\n", viewportW, viewportH); + } #if defined(WIN32) - renderer->reset(viewportW, viewportH, playerColor); + renderer->reset(viewportW, viewportH, playerColor); #else - renderer->reset(viewportW, viewportH, playerColor); + renderer->reset(viewportW, viewportH, playerColor); #endif - renderer->transform(rotX, rotY, zoom); - renderer->renderGrid(); + renderer->transform(rotX, rotY, zoom); + renderer->renderGrid(); + + // printf("anim [%f] particleLoopStart [%d]\n",anim,particleLoopStart); - //printf("anim [%f] particleLoopStart [%d]\n",anim,particleLoopStart); + string statusTextValue = + statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY); + GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str())); - string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY); - GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str())); + renderer->renderTheModel(model, anim); - renderer->renderTheModel(model, anim); + int updateLoops = particleLoopStart; + particleLoopStart = 1; - int updateLoops = particleLoopStart; - particleLoopStart = 1; + if (resetAnimation == true || ((anim - lastanim) >= defaultspeed * 2)) { + // printf("anim [%f] [%f] [%f]\n",anim,lastanim,speed); - if(resetAnimation == true || ((anim - lastanim) >= defaultspeed*2)) { - //printf("anim [%f] [%f] [%f]\n",anim,lastanim,speed); + for (int i = 0; i < updateLoops; ++i) { + renderer->updateParticleManager(); + } + } - for(int i=0; i< updateLoops; ++i) { - renderer->updateParticleManager(); - } - } + renderer->renderParticleManager(); - renderer->renderParticleManager(); - - if(isFirstWindowShownEvent) { - this->Refresh(); - glCanvas->Refresh(); - glCanvas->SetFocus(); - } + if (isFirstWindowShownEvent) { + this->Refresh(); + glCanvas->Refresh(); + glCanvas->SetFocus(); + } - bool haveLoadedParticles = (particleProjectilePathList.empty() == false || particleSplashPathList.empty() == false); + bool haveLoadedParticles = (particleProjectilePathList.empty() == false || + particleSplashPathList.empty() == false); - if(autoScreenShotAndExit == true && viewportW > 0 && viewportH > 0) { - printf("Auto exiting app...\n"); - fflush(stdout); + if (autoScreenShotAndExit == true && viewportW > 0 && viewportH > 0) { + printf("Auto exiting app...\n"); + fflush(stdout); - autoScreenShotAndExit = false; + autoScreenShotAndExit = false; - saveScreenshot(); - Close(); - return; - } - - glCanvas->SwapBuffers(); + saveScreenshot(); + Close(); + return; + } - if(autoScreenShotAndExit == true && viewportW == 0 && viewportH == 0) { - autoScreenshotRender = anim; + glCanvas->SwapBuffers(); - printf("Auto exiting desired but waiting for w x h > 0...\n"); + if (autoScreenShotAndExit == true && viewportW == 0 && viewportH == 0) { + autoScreenshotRender = anim; - return; - } - if((modelPathList.empty() == false) && resetAnimation && haveLoadedParticles) { - if(anim >= resetAnim && resetAnim > 0) { - printf("RESETTING EVERYTHING [%f][%f]...\n",anim,resetAnim); - fflush(stdout); + printf("Auto exiting desired but waiting for w x h > 0...\n"); - resetAnimation = false; - particleLoopStart = resetParticleLoopStart; + return; + } + if ((modelPathList.empty() == false) && resetAnimation && + haveLoadedParticles) { + if (anim >= resetAnim && resetAnim > 0) { + printf("RESETTING EVERYTHING [%f][%f]...\n", anim, resetAnim); + fflush(stdout); - if(unitPath.first != "") { - //onMenuFileClearAll(event); + resetAnimation = false; + particleLoopStart = resetParticleLoopStart; - modelPathList.clear(); - particlePathList.clear(); - particleProjectilePathList.clear(); - particleSplashPathList.clear(); // as above - } - onMenuRestartNoEvent(); - } - } - else if(modelPathList.empty() == true && haveLoadedParticles) { - if(renderer->hasActiveParticleSystem(ParticleSystem::pst_ProjectileParticleSystem) == false && - renderer->hasActiveParticleSystem(ParticleSystem::pst_SplashParticleSystem) == false) { + if (unitPath.first != "") { + // onMenuFileClearAll(event); - printf("RESETTING PARTICLES...\n"); - fflush(stdout); + modelPathList.clear(); + particlePathList.clear(); + particleProjectilePathList.clear(); + particleSplashPathList.clear(); // as above + } + onMenuRestartNoEvent(); + } + } else if (modelPathList.empty() == true && haveLoadedParticles) { + if (renderer->hasActiveParticleSystem( + ParticleSystem::pst_ProjectileParticleSystem) == false && + renderer->hasActiveParticleSystem( + ParticleSystem::pst_SplashParticleSystem) == false) { - resetAnimation = false; - anim = 0.f; - particleLoopStart = resetParticleLoopStart; + printf("RESETTING PARTICLES...\n"); + fflush(stdout); - onMenuRestartNoEvent(); - } - } + resetAnimation = false; + anim = 0.f; + particleLoopStart = resetParticleLoopStart; - lastanim = anim; + onMenuRestartNoEvent(); + } + } + + lastanim = anim; } -void MainWindow::onClose(wxCloseEvent &event){ - // release memory first (from onMenuFileClearAll) +void MainWindow::onClose(wxCloseEvent &event) { + // release memory first (from onMenuFileClearAll) - //printf("OnClose START\n"); - //fflush(stdout); + // printf("OnClose START\n"); + // fflush(stdout); - modelPathList.clear(); - particlePathList.clear(); - particleProjectilePathList.clear(); - particleSplashPathList.clear(); // as above + modelPathList.clear(); + particlePathList.clear(); + particleProjectilePathList.clear(); + particleSplashPathList.clear(); // as above - if(timer) timer->Stop(); + if (timer) + timer->Stop(); - unitParticleSystems.clear(); - unitParticleSystemTypes.clear(); + unitParticleSystems.clear(); + unitParticleSystemTypes.clear(); - projectileParticleSystems.clear(); - projectileParticleSystemTypes.clear(); - splashParticleSystems.clear(); // as above - splashParticleSystemTypes.clear(); + projectileParticleSystems.clear(); + projectileParticleSystemTypes.clear(); + splashParticleSystems.clear(); // as above + splashParticleSystemTypes.clear(); - //delete model; - //model = NULL; - if(renderer) renderer->end(); + // delete model; + // model = NULL; + if (renderer) + renderer->end(); - //printf("OnClose about to END\n"); - //fflush(stdout); + // printf("OnClose about to END\n"); + // fflush(stdout); - delete timer; - timer = NULL; + delete timer; + timer = NULL; - //delete model; - //model = NULL; + // delete model; + // model = NULL; - delete renderer; - renderer = NULL; + delete renderer; + renderer = NULL; - //delete glCanvas; - if(glCanvas) { - glCanvas->Destroy(); - } - glCanvas = NULL; + // delete glCanvas; + if (glCanvas) { + glCanvas->Destroy(); + } + glCanvas = NULL; - this->Destroy(); + this->Destroy(); } // for the mousewheel void MainWindow::onMouseWheelDown(wxMouseEvent &event) { - try { - zoom*= 1.1f; - zoom= clamp(zoom, 0.1f, 10.0f); - - string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY); - GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str())); - - onPaintNoEvent(); - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } + try { + zoom *= 1.1f; + zoom = clamp(zoom, 0.1f, 10.0f); + + string statusTextValue = + statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY); + GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str())); + + onPaintNoEvent(); + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } } void MainWindow::onMouseWheelUp(wxMouseEvent &event) { - try { - zoom*= 0.90909f; - zoom= clamp(zoom, 0.1f, 10.0f); - - string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY); - GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str())); - - onPaintNoEvent(); - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } + try { + zoom *= 0.90909f; + zoom = clamp(zoom, 0.1f, 10.0f); + + string statusTextValue = + statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY); + GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str())); + + onPaintNoEvent(); + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } } +void MainWindow::onMouseMove(wxMouseEvent &event) { + try { + int x = event.GetX(); + int y = event.GetY(); + + if (event.LeftIsDown()) { + rotX += clamp(lastX - x, -10, 10); + rotY += clamp(lastY - y, -10, 10); + + string statusTextValue = + statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY); + GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str())); + + onPaintNoEvent(); + } else if (event.RightIsDown()) { + zoom *= 1.0f + (lastX - x + lastY - y) / 100.0f; + zoom = clamp(zoom, 0.1f, 10.0f); + + string statusTextValue = + statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY); + GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str())); + + onPaintNoEvent(); + } -void MainWindow::onMouseMove(wxMouseEvent &event){ - try { - int x= event.GetX(); - int y= event.GetY(); - + lastX = x; + lastY = y; + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } +} - if(event.LeftIsDown()){ - rotX+= clamp(lastX-x, -10, 10); - rotY+= clamp(lastY-y, -10, 10); +void MainWindow::onMenuFileLoad(wxCommandEvent &event) { + try { + // string fileName; + fileDialog->SetWildcard(wxT("G3D files (*.g3d)|*.g3d;*.G3D")); + fileDialog->SetMessage(wxT("Selecting Glest Model for current view.")); - string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY); - GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str())); + if (fileDialog->ShowModal() == wxID_OK) { + modelPathList.clear(); + string file; + file = (const char *)wxFNCONV(fileDialog->GetPath().c_str()); - onPaintNoEvent(); - } - else if(event.RightIsDown()){ - zoom*= 1.0f+(lastX-x+lastY-y)/100.0f; - zoom= clamp(zoom, 0.1f, 10.0f); + // loadModel((const char*)wxFNCONV(fileDialog->GetPath().c_str())); + loadModel(file); + } + isControlKeyPressed = false; + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } +} - string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY); - GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str())); +void MainWindow::onMenuFileLoadParticleXML(wxCommandEvent &event) { + try { + // string fileName; + fileDialog->SetWildcard(wxT("XML files (*.xml)|*.xml")); + + if (isControlKeyPressed == true) { + fileDialog->SetMessage( + wxT("Adding Mega-Glest particle to current view.")); + } else { + fileDialog->SetMessage( + wxT("Selecting Mega-Glest particle for current view.")); + } - onPaintNoEvent(); - } + if (fileDialog->ShowModal() == wxID_OK) { + // string path = (const char*)wxFNCONV(fileDialog->GetPath().c_str()); + string file; + file = (const char *)wxFNCONV(fileDialog->GetPath().c_str()); - lastX= x; - lastY= y; - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } + loadParticle(file); + } + isControlKeyPressed = false; + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } } -void MainWindow::onMenuFileLoad(wxCommandEvent &event){ - try { - //string fileName; - fileDialog->SetWildcard(wxT("G3D files (*.g3d)|*.g3d;*.G3D")); - fileDialog->SetMessage(wxT("Selecting Glest Model for current view.")); - - if(fileDialog->ShowModal()==wxID_OK){ - modelPathList.clear(); - string file; - file = (const char*)wxFNCONV(fileDialog->GetPath().c_str()); - - //loadModel((const char*)wxFNCONV(fileDialog->GetPath().c_str())); - loadModel(file); - } - isControlKeyPressed = false; - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } -} +void MainWindow::onMenuFileLoadProjectileParticleXML(wxCommandEvent &event) { + try { + // string fileName; + fileDialog->SetWildcard(wxT("XML files (*.xml)|*.xml")); + + if (isControlKeyPressed == true) { + fileDialog->SetMessage( + wxT("Adding Mega-Glest projectile particle to current view.")); + } else { + fileDialog->SetMessage( + wxT("Selecting Mega-Glest projectile particle for current view.")); + } -void MainWindow::onMenuFileLoadParticleXML(wxCommandEvent &event){ - try { - //string fileName; - fileDialog->SetWildcard(wxT("XML files (*.xml)|*.xml")); - - if(isControlKeyPressed == true) { - fileDialog->SetMessage(wxT("Adding Mega-Glest particle to current view.")); - } - else { - fileDialog->SetMessage(wxT("Selecting Mega-Glest particle for current view.")); - } - - if(fileDialog->ShowModal()==wxID_OK){ - //string path = (const char*)wxFNCONV(fileDialog->GetPath().c_str()); - string file; - file = (const char*)wxFNCONV(fileDialog->GetPath().c_str()); - - loadParticle(file); - } - isControlKeyPressed = false; - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } -} + if (fileDialog->ShowModal() == wxID_OK) { + // string path = (const char*)wxFNCONV(fileDialog->GetPath().c_str()); + string file; + file = (const char *)wxFNCONV(fileDialog->GetPath().c_str()); -void MainWindow::onMenuFileLoadProjectileParticleXML(wxCommandEvent &event){ - try { - //string fileName; - fileDialog->SetWildcard(wxT("XML files (*.xml)|*.xml")); - - if(isControlKeyPressed == true) { - fileDialog->SetMessage(wxT("Adding Mega-Glest projectile particle to current view.")); - } - else { - fileDialog->SetMessage(wxT("Selecting Mega-Glest projectile particle for current view.")); - } - - if(fileDialog->ShowModal()==wxID_OK){ - //string path = (const char*)wxFNCONV(fileDialog->GetPath().c_str()); - string file; - file = (const char*)wxFNCONV(fileDialog->GetPath().c_str()); - - loadProjectileParticle(file); - } - isControlKeyPressed = false; - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } + loadProjectileParticle(file); + } + isControlKeyPressed = false; + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } } -void MainWindow::onMenuFileLoadSplashParticleXML(wxCommandEvent &event){ - try { - //string fileName; - fileDialog->SetWildcard(wxT("XML files (*.xml)|*.xml")); - - if(isControlKeyPressed == true) { - fileDialog->SetMessage(wxT("Adding Mega-Glest splash particle to current view.")); - } - else { - fileDialog->SetMessage(wxT("Selecting Mega-Glest splash particle for current view.")); - } - - if(fileDialog->ShowModal()==wxID_OK){ - //string path = (const char*)wxFNCONV(fileDialog->GetPath().c_str()); - string file; - file = (const char*)wxFNCONV(fileDialog->GetPath().c_str()); - - loadSplashParticle(file); - } - isControlKeyPressed = false; - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } -} // is it possible to join loadParticle(), loadProjectileParticle() and loadSplashParticle() to one method? +void MainWindow::onMenuFileLoadSplashParticleXML(wxCommandEvent &event) { + try { + // string fileName; + fileDialog->SetWildcard(wxT("XML files (*.xml)|*.xml")); + + if (isControlKeyPressed == true) { + fileDialog->SetMessage( + wxT("Adding Mega-Glest splash particle to current view.")); + } else { + fileDialog->SetMessage( + wxT("Selecting Mega-Glest splash particle for current view.")); + } + if (fileDialog->ShowModal() == wxID_OK) { + // string path = (const char*)wxFNCONV(fileDialog->GetPath().c_str()); + string file; + file = (const char *)wxFNCONV(fileDialog->GetPath().c_str()); + + loadSplashParticle(file); + } + isControlKeyPressed = false; + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } +} // is it possible to join loadParticle(), loadProjectileParticle() and + // loadSplashParticle() to one method? void MainWindow::OnChangeColor(wxCommandEvent &event) { - try { - //wxColour color = colorPicker->GetColour(); - wxColourData data; - data.SetChooseFull(true); - for (int i = 0; i < 16; i++) - { - wxColour colour(i*16, i*16, i*16); - data.SetCustomColour(i, colour); - } - - wxColourDialog dialog(this, &data); - if (dialog.ShowModal() == wxID_OK) - { - wxColourData retData = dialog.GetColourData(); - wxColour col = retData.GetColour(); - renderer->setBackgroundColor(col.Red()/255.0f, col.Green()/255.0f, col.Blue()/255.0f); - } - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } + try { + // wxColour color = colorPicker->GetColour(); + wxColourData data; + data.SetChooseFull(true); + for (int i = 0; i < 16; i++) { + wxColour colour(i * 16, i * 16, i * 16); + data.SetCustomColour(i, colour); + } + + wxColourDialog dialog(this, &data); + if (dialog.ShowModal() == wxID_OK) { + wxColourData retData = dialog.GetColourData(); + wxColour col = retData.GetColour(); + renderer->setBackgroundColor(col.Red() / 255.0f, col.Green() / 255.0f, + col.Blue() / 255.0f); + } + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } } void MainWindow::onMenumFileToggleScreenshotTransparent(wxCommandEvent &event) { - try { - float alpha = (event.IsChecked() == true ? 0.0f : 1.0f); - renderer->setAlphaColor(alpha); - //printf("alpha = %f\n",alpha); - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } + try { + float alpha = (event.IsChecked() == true ? 0.0f : 1.0f); + renderer->setAlphaColor(alpha); + // printf("alpha = %f\n",alpha); + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } } void MainWindow::saveScreenshot() { - try { - int autoSaveScreenshotIndex = -1; - for(unsigned int i = 0; i < autoScreenShotParams.size(); ++i) { - if(_strnicmp(autoScreenShotParams[i].c_str(),"saveas-",7) == 0) { - printf("Screenshot option [%s]\n",autoScreenShotParams[i].c_str()); - autoSaveScreenshotIndex = i; - break; - } - } - if(autoSaveScreenshotIndex >= 0) { - string saveAsFilename = autoScreenShotParams[autoSaveScreenshotIndex]; - saveAsFilename.erase(0,7); + try { + int autoSaveScreenshotIndex = -1; + for (unsigned int i = 0; i < autoScreenShotParams.size(); ++i) { + if (_strnicmp(autoScreenShotParams[i].c_str(), "saveas-", 7) == 0) { + printf("Screenshot option [%s]\n", autoScreenShotParams[i].c_str()); + autoSaveScreenshotIndex = i; + break; + } + } + if (autoSaveScreenshotIndex >= 0) { + string saveAsFilename = autoScreenShotParams[autoSaveScreenshotIndex]; + saveAsFilename.erase(0, 7); #ifdef WIN32 - FILE*f = _wfopen(utf8_decode(saveAsFilename).c_str(), L"rb"); + FILE *f = _wfopen(utf8_decode(saveAsFilename).c_str(), L"rb"); #else - FILE *f= fopen(saveAsFilename.c_str(), "rb"); + FILE *f = fopen(saveAsFilename.c_str(), "rb"); #endif - if(f == NULL) { - renderer->saveScreen(saveAsFilename.c_str(),&overrideSize); - } - else { - if(f) { - fclose(f); - } - } - } - else { - //string screenShotsPath = extractDirectoryPathFromFile(appPath) + string("screens/"); - string userData = Config::getInstance().getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - string screenShotsPath = userData + string("screens/"); - printf("screenShotsPath [%s]\n",screenShotsPath.c_str()); - - if(isdir(screenShotsPath.c_str()) == false) { - createDirectoryPaths(screenShotsPath); - } - - string path = screenShotsPath; - if(isdir(path.c_str()) == true) { - //Config &config= Config::getInstance(); - //string fileFormat = config.getString("ScreenShotFileType","jpg"); - - for(int i=0; i < 5000; ++i) { - path = screenShotsPath; - path += string("screen") + intToStr(i) + string(".") + fileFormat; + if (f == NULL) { + renderer->saveScreen(saveAsFilename.c_str(), &overrideSize); + } else { + if (f) { + fclose(f); + } + } + } else { + // string screenShotsPath = extractDirectoryPathFromFile(appPath) + + // string("screens/"); + string userData = Config::getInstance().getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + string screenShotsPath = userData + string("screens/"); + printf("screenShotsPath [%s]\n", screenShotsPath.c_str()); + + if (isdir(screenShotsPath.c_str()) == false) { + createDirectoryPaths(screenShotsPath); + } + + string path = screenShotsPath; + if (isdir(path.c_str()) == true) { + // Config &config= Config::getInstance(); + // string fileFormat = config.getString("ScreenShotFileType","jpg"); + + for (int i = 0; i < 5000; ++i) { + path = screenShotsPath; + path += string("screen") + intToStr(i) + string(".") + fileFormat; #ifdef WIN32 - FILE*f= _wfopen(utf8_decode(path).c_str(), L"rb"); + FILE *f = _wfopen(utf8_decode(path).c_str(), L"rb"); #else - FILE *f= fopen(path.c_str(), "rb"); + FILE *f = fopen(path.c_str(), "rb"); #endif - if(f == NULL) { - renderer->saveScreen(path,&overrideSize); - break; - } - else { - if(f) { - fclose(f); - } - } - } - } - } - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } + if (f == NULL) { + renderer->saveScreen(path, &overrideSize); + break; + } else { + if (f) { + fclose(f); + } + } + } + } + } + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } } void MainWindow::onMenuFileSaveScreenshot(wxCommandEvent &event) { - saveScreenshot(); + saveScreenshot(); } void MainWindow::onMenuFileClearAll(wxCommandEvent &event) { - try { - //printf("Start onMenuFileClearAll\n"); - //fflush(stdout); - - modelPathList.clear(); - particlePathList.clear(); - particleProjectilePathList.clear(); - particleSplashPathList.clear(); // as above - - if(timer) timer->Stop(); - if(renderer) renderer->end(); - - unitParticleSystems.clear(); - unitParticleSystemTypes.clear(); - - projectileParticleSystems.clear(); - projectileParticleSystemTypes.clear(); - splashParticleSystems.clear(); // as above - splashParticleSystemTypes.clear(); - - //delete model; - //model = NULL; - if(model != NULL && renderer != NULL) renderer->endModel(rsGlobal, model); - model = NULL; - - loadUnit("",""); - loadModel(""); - loadParticle(""); - loadProjectileParticle(""); - loadSplashParticle(""); // as above - - GetStatusBar()->SetStatusText(ToUnicode(statusbarText.c_str())); - isControlKeyPressed = false; - - //printf("END onMenuFileClearAll\n"); - //fflush(stdout); - - if(timer) timer->Start(100); - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } + try { + // printf("Start onMenuFileClearAll\n"); + // fflush(stdout); + + modelPathList.clear(); + particlePathList.clear(); + particleProjectilePathList.clear(); + particleSplashPathList.clear(); // as above + + if (timer) + timer->Stop(); + if (renderer) + renderer->end(); + + unitParticleSystems.clear(); + unitParticleSystemTypes.clear(); + + projectileParticleSystems.clear(); + projectileParticleSystemTypes.clear(); + splashParticleSystems.clear(); // as above + splashParticleSystemTypes.clear(); + + // delete model; + // model = NULL; + if (model != NULL && renderer != NULL) + renderer->endModel(rsGlobal, model); + model = NULL; + + loadUnit("", ""); + loadModel(""); + loadParticle(""); + loadProjectileParticle(""); + loadSplashParticle(""); // as above + + GetStatusBar()->SetStatusText(ToUnicode(statusbarText.c_str())); + isControlKeyPressed = false; + + // printf("END onMenuFileClearAll\n"); + // fflush(stdout); + + if (timer) + timer->Start(100); + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } } -void MainWindow::onMenuFileExit(wxCommandEvent &event) { - Close(); -} +void MainWindow::onMenuFileExit(wxCommandEvent &event) { Close(); } void MainWindow::loadUnit(string path, string skillName) { - if(path != "" && fileExists(path) == true) { - // std::cout << "Clearing list..." << std::endl; - this->unitPath.first = path; - this->unitPath.second.push_back(skillName); - } - - try{ - if(this->unitPath.first != "") { - if(timer) timer->Stop(); - if(renderer) renderer->end(); - - string titlestring = winHeader; - - string unitPath = this->unitPath.first; - string dir = unitPath; - string name= lastDir(dir); - string path= dir + "/" + name + ".xml"; - - titlestring = unitPath + " - "+ titlestring; - - std::string unitXML = path; - - string skillModelFile = ""; - string skillParticleFile = ""; - string skillParticleProjectileFile = ""; - string skillParticleSplashFile = ""; - bool fileFound = fileExists(unitXML); - - printf("Loading unit from file [%s] fileFound = %d\n",unitXML.c_str(),fileFound); - - if(fileFound == true) { - XmlTree xmlTree; - xmlTree.load(unitXML,Properties::getTagReplacementValues()); - const XmlNode *unitNode= xmlTree.getRootNode(); - - bool foundSkillName = false; - for(unsigned int skillIdx = 0; foundSkillName == false && skillIdx < this->unitPath.second.size(); ++skillIdx) { - string lookipForSkillName = this->unitPath.second[skillIdx]; - - const XmlNode *skillsNode= unitNode->getChild("skills"); - for(unsigned int i = 0; foundSkillName == false && i < skillsNode->getChildCount(); ++i) { - const XmlNode *sn= skillsNode->getChild("skill", i); - //const XmlNode *typeNode= sn->getChild("type"); - const XmlNode *nameNode= sn->getChild("name"); - string skillXmlName = nameNode->getAttribute("value")->getRestrictedValue(); - if(skillXmlName == lookipForSkillName) { - printf("Found skill [%s]\n",lookipForSkillName.c_str()); - foundSkillName = true; - - if(sn->getChild("animation") != NULL) { - skillModelFile = sn->getChild("animation")->getAttribute("path")->getRestrictedValue(unitPath + '/'); - printf("Found skill model [%s]\n",skillModelFile.c_str()); - } - - if(sn->hasChild("particles") == true) { - const XmlNode *particlesNode= sn->getChild("particles"); - //for(int j = 0; particlesNode != NULL && particlesNode->getAttribute("value")->getRestrictedValue() == "true" && - // j < particlesNode->getChildCount(); ++j) { - if(particlesNode != NULL && particlesNode->getAttribute("value")->getRestrictedValue() == "true" && - particlesNode->hasChild("particle-file") == true) { - const XmlNode *pf= particlesNode->getChild("particle-file"); - if(pf != NULL) { - skillParticleFile = unitPath + '/' + pf->getAttribute("path")->getRestrictedValue(); - printf("Found skill particle [%s]\n",skillParticleFile.c_str()); - } - } - } - if(sn->hasChild("projectile") == true) { - const XmlNode *particlesProjectileNode= sn->getChild("projectile"); - //for(int j = 0; particlesProjectileNode != NULL && particlesProjectileNode->getAttribute("value")->getRestrictedValue() == "true" && - // j < particlesProjectileNode->getChildCount(); ++j) { - if(particlesProjectileNode != NULL && particlesProjectileNode->getAttribute("value")->getRestrictedValue() == "true" && - particlesProjectileNode->hasChild("particle") == true) { - const XmlNode *pf= particlesProjectileNode->getChild("particle"); - if(pf != NULL && pf->getAttribute("value")->getRestrictedValue() == "true") { - skillParticleProjectileFile = unitPath + '/' + pf->getAttribute("path")->getRestrictedValue(); - printf("Found skill skill projectile particle [%s]\n",skillParticleProjectileFile.c_str()); - } - } - } - if(sn->hasChild("splash") == true) { - const XmlNode *particlesSplashNode= sn->getChild("splash"); - //for(int j = 0; particlesSplashNode != NULL && particlesSplashNode->getAttribute("value")->getRestrictedValue() == "true" && - // j < particlesSplashNode->getChildCount(); ++j) { - if(particlesSplashNode != NULL && particlesSplashNode->getAttribute("value")->getRestrictedValue() == "true" && - particlesSplashNode->hasChild("particle") == true) { - const XmlNode *pf= particlesSplashNode->getChild("particle"); - if(pf != NULL && pf->getAttribute("value")->getRestrictedValue() == "true") { - skillParticleSplashFile = unitPath + '/' + pf->getAttribute("path")->getRestrictedValue(); - printf("Found skill skill splash particle [%s]\n",skillParticleSplashFile.c_str()); - } - } - } - } - } - } - - if(skillModelFile != "") { - this->modelPathList.push_back(skillModelFile); - printf("Added skill model [%s]\n",skillModelFile.c_str()); - } - if(skillParticleFile != "") { - this->particlePathList.push_back(skillParticleFile); - printf("Added skill particle [%s]\n",skillParticleFile.c_str()); - } - if(skillParticleProjectileFile != "") { - this->particleProjectilePathList.push_back(skillParticleProjectileFile); - printf("Added skill projectile particle [%s]\n",skillParticleProjectileFile.c_str()); - } - if(skillParticleSplashFile != "") { - this->particleSplashPathList.push_back(skillParticleSplashFile); - printf("Added skill splash particle [%s]\n",skillParticleSplashFile.c_str()); - } - } - SetTitle(ToUnicode(titlestring)); - } - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Not a Mega-Glest particle XML file, or broken"), wxOK | wxICON_ERROR).ShowModal(); - } + if (path != "" && fileExists(path) == true) { + // std::cout << "Clearing list..." << std::endl; + this->unitPath.first = path; + this->unitPath.second.push_back(skillName); + } + + try { + if (this->unitPath.first != "") { + if (timer) + timer->Stop(); + if (renderer) + renderer->end(); + + string titlestring = winHeader; + + string unitPath = this->unitPath.first; + string dir = unitPath; + string name = lastDir(dir); + string path = dir + "/" + name + ".xml"; + + titlestring = unitPath + " - " + titlestring; + + std::string unitXML = path; + + string skillModelFile = ""; + string skillParticleFile = ""; + string skillParticleProjectileFile = ""; + string skillParticleSplashFile = ""; + bool fileFound = fileExists(unitXML); + + printf("Loading unit from file [%s] fileFound = %d\n", unitXML.c_str(), + fileFound); + + if (fileFound == true) { + XmlTree xmlTree; + xmlTree.load(unitXML, Properties::getTagReplacementValues()); + const XmlNode *unitNode = xmlTree.getRootNode(); + + bool foundSkillName = false; + for (unsigned int skillIdx = 0; + foundSkillName == false && skillIdx < this->unitPath.second.size(); + ++skillIdx) { + string lookipForSkillName = this->unitPath.second[skillIdx]; + + const XmlNode *skillsNode = unitNode->getChild("skills"); + for (unsigned int i = 0; + foundSkillName == false && i < skillsNode->getChildCount(); + ++i) { + const XmlNode *sn = skillsNode->getChild("skill", i); + // const XmlNode *typeNode= sn->getChild("type"); + const XmlNode *nameNode = sn->getChild("name"); + string skillXmlName = + nameNode->getAttribute("value")->getRestrictedValue(); + if (skillXmlName == lookipForSkillName) { + printf("Found skill [%s]\n", lookipForSkillName.c_str()); + foundSkillName = true; + + if (sn->getChild("animation") != NULL) { + skillModelFile = sn->getChild("animation") + ->getAttribute("path") + ->getRestrictedValue(unitPath + '/'); + printf("Found skill model [%s]\n", skillModelFile.c_str()); + } + + if (sn->hasChild("particles") == true) { + const XmlNode *particlesNode = sn->getChild("particles"); + // for(int j = 0; particlesNode != NULL && + // particlesNode->getAttribute("value")->getRestrictedValue() == + // "true" && j < particlesNode->getChildCount(); ++j) { + if (particlesNode != NULL && + particlesNode->getAttribute("value") + ->getRestrictedValue() == "true" && + particlesNode->hasChild("particle-file") == true) { + const XmlNode *pf = particlesNode->getChild("particle-file"); + if (pf != NULL) { + skillParticleFile = + unitPath + '/' + + pf->getAttribute("path")->getRestrictedValue(); + printf("Found skill particle [%s]\n", + skillParticleFile.c_str()); + } + } + } + if (sn->hasChild("projectile") == true) { + const XmlNode *particlesProjectileNode = + sn->getChild("projectile"); + // for(int j = 0; particlesProjectileNode != NULL && + // particlesProjectileNode->getAttribute("value")->getRestrictedValue() + // == "true" && j < + // particlesProjectileNode->getChildCount(); + //++j) { + if (particlesProjectileNode != NULL && + particlesProjectileNode->getAttribute("value") + ->getRestrictedValue() == "true" && + particlesProjectileNode->hasChild("particle") == true) { + const XmlNode *pf = + particlesProjectileNode->getChild("particle"); + if (pf != NULL && + pf->getAttribute("value")->getRestrictedValue() == + "true") { + skillParticleProjectileFile = + unitPath + '/' + + pf->getAttribute("path")->getRestrictedValue(); + printf("Found skill skill projectile particle [%s]\n", + skillParticleProjectileFile.c_str()); + } + } + } + if (sn->hasChild("splash") == true) { + const XmlNode *particlesSplashNode = sn->getChild("splash"); + // for(int j = 0; particlesSplashNode != NULL && + // particlesSplashNode->getAttribute("value")->getRestrictedValue() + // == "true" && j < particlesSplashNode->getChildCount(); + // ++j) { + if (particlesSplashNode != NULL && + particlesSplashNode->getAttribute("value") + ->getRestrictedValue() == "true" && + particlesSplashNode->hasChild("particle") == true) { + const XmlNode *pf = particlesSplashNode->getChild("particle"); + if (pf != NULL && + pf->getAttribute("value")->getRestrictedValue() == + "true") { + skillParticleSplashFile = + unitPath + '/' + + pf->getAttribute("path")->getRestrictedValue(); + printf("Found skill skill splash particle [%s]\n", + skillParticleSplashFile.c_str()); + } + } + } + } + } + } + + if (skillModelFile != "") { + this->modelPathList.push_back(skillModelFile); + printf("Added skill model [%s]\n", skillModelFile.c_str()); + } + if (skillParticleFile != "") { + this->particlePathList.push_back(skillParticleFile); + printf("Added skill particle [%s]\n", skillParticleFile.c_str()); + } + if (skillParticleProjectileFile != "") { + this->particleProjectilePathList.push_back( + skillParticleProjectileFile); + printf("Added skill projectile particle [%s]\n", + skillParticleProjectileFile.c_str()); + } + if (skillParticleSplashFile != "") { + this->particleSplashPathList.push_back(skillParticleSplashFile); + printf("Added skill splash particle [%s]\n", + skillParticleSplashFile.c_str()); + } + } + SetTitle(ToUnicode(titlestring)); + } + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), + ToUnicode("Not a Mega-Glest particle XML file, or broken"), + wxOK | wxICON_ERROR) + .ShowModal(); + } } void MainWindow::loadModel(string path) { - try { - if(path != "" && fileExists(path) == true) { - this->modelPathList.push_back(path); - printf("Adding model [%s] list size " MG_SIZE_T_SPECIFIER "\n",path.c_str(),this->modelPathList.size()); - } + try { + if (path != "" && fileExists(path) == true) { + this->modelPathList.push_back(path); + printf("Adding model [%s] list size " MG_SIZE_T_SPECIFIER "\n", + path.c_str(), this->modelPathList.size()); + } - string titlestring=winHeader; - for(unsigned int idx =0; idx < this->modelPathList.size(); idx++) { - string modelPath = this->modelPathList[idx]; + string titlestring = winHeader; + for (unsigned int idx = 0; idx < this->modelPathList.size(); idx++) { + string modelPath = this->modelPathList[idx]; + + // printf("Loading model [%s] %u of " MG_SIZE_T_SPECIFIER + // "\n",modelPath.c_str(),idx, this->modelPathList.size()); + + if (timer) + timer->Stop(); + // delete model; + if (model != NULL && renderer != NULL) + renderer->endModel(rsGlobal, model); + model = NULL; + model = renderer ? renderer->newModel(rsGlobal, modelPath) : NULL; + + statusbarText = getModelInfo(); + string statusTextValue = + statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY); + GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str())); + if (timer) + timer->Start(100); + titlestring = + extractFileFromDirectoryPath(modelPath) + " - " + titlestring; + } + SetTitle(ToUnicode(titlestring)); + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } +} - //printf("Loading model [%s] %u of " MG_SIZE_T_SPECIFIER "\n",modelPath.c_str(),idx, this->modelPathList.size()); +void MainWindow::loadParticle(string path) { + if (timer) + timer->Stop(); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] about to load [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, path.c_str()); + if (path != "" && fileExists(path) == true) { + renderer->end(); + unitParticleSystems.clear(); + unitParticleSystemTypes.clear(); + + if (isControlKeyPressed == true) { + // std::cout << "Adding to list..." << std::endl; + this->particlePathList.push_back(path); + } else { + // std::cout << "Clearing list..." << std::endl; + this->particlePathList.clear(); + this->particlePathList.push_back(path); + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] added file [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, path.c_str()); + } + + try { + if (this->particlePathList.empty() == false) { + string titlestring = winHeader; + for (unsigned int idx = 0; idx < this->particlePathList.size(); idx++) { + string particlePath = this->particlePathList[idx]; + string dir = extractDirectoryPathFromFile(particlePath); + + size_t pos = dir.find_last_of(folderDelimiter); + if (pos == dir.length() - 1 && dir.length() > 0) { + dir.erase(dir.length() - 1); + } - if(timer) timer->Stop(); - //delete model; - if(model != NULL && renderer != NULL) renderer->endModel(rsGlobal, model); - model = NULL; - model = renderer? renderer->newModel(rsGlobal, modelPath): NULL; + particlePath = extractFileFromDirectoryPath(particlePath); + titlestring = particlePath + " - " + titlestring; + + std::string unitXML = + dir + folderDelimiter + extractFileFromDirectoryPath(dir) + ".xml"; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] looking for unit XML [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, unitXML.c_str()); + + // int size = -1; + // int height = -1; + int size = 0; + int height = 0; + + if (fileExists(unitXML) == true) { + { + XmlTree xmlTree; + xmlTree.load(unitXML, Properties::getTagReplacementValues()); + const XmlNode *unitNode = xmlTree.getRootNode(); + const XmlNode *parametersNode = unitNode->getChild("parameters"); + // size + size = parametersNode->getChild("size") + ->getAttribute("value") + ->getIntValue(); + // height + height = parametersNode->getChild("height") + ->getAttribute("value") + ->getIntValue(); + } + + // std::cout << "About to load [" << particlePath << "] from [" << dir + // << "] unit [" << unitXML << "]" << std::endl; + } else { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] unit XML NOT FOUND [%s] using default " + "position values\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, unitXML.c_str()); + + size = 1; + height = 1; + } - statusbarText = getModelInfo(); - string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY); - GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str())); - if(timer) timer->Start(100); - titlestring = extractFileFromDirectoryPath(modelPath) + " - "+ titlestring; + std::map>> loadedFileList; + UnitParticleSystemType *unitParticleSystemType = + new UnitParticleSystemType(); + unitParticleSystemType->load( + NULL, dir, + dir + folderDelimiter + + particlePath, // ### if we knew which particle it was, we could + // be more accurate + renderer, loadedFileList, "g3dviewer", ""); + unitParticleSystemTypes.push_back(unitParticleSystemType); + + for (std::vector::const_iterator it = + unitParticleSystemTypes.begin(); + it != unitParticleSystemTypes.end(); ++it) { + UnitParticleSystem *ups = new UnitParticleSystem(200); + + ups->setParticleType((*it)); + (*it)->setValues(ups); + if (size > 0) { + // getCurrVectorFlat() + Vec3f(0.f, type->getHeight()/2.f, 0.f); + Vec3f vec = Vec3f(0.f, height / 2.f, 0.f); + ups->setPos(vec); + } + // ups->setFactionColor(getFaction()->getTexture()->getPixmap()->getPixel3f(0,0)); + ups->setFactionColor(renderer->getPlayerColorTexture(playerColor) + ->getPixmap() + ->getPixel3f(0, 0)); + unitParticleSystems.push_back(ups); + renderer->manageParticleSystem(ups); + + ups->setVisible(true); } - SetTitle(ToUnicode(titlestring)); + + if (path != "" && fileExists(path) == true) { + renderer->initModelManager(); + if (initTextureManager) { + renderer->initTextureManager(); + } + } + } + SetTitle(ToUnicode(titlestring)); } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), + ToUnicode("Not a Mega-Glest particle XML file, or broken"), + wxOK | wxICON_ERROR) + .ShowModal(); + } + if (timer) + timer->Start(100); } -void MainWindow::loadParticle(string path) { - if(timer) timer->Stop(); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] about to load [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,path.c_str()); - if(path != "" && fileExists(path) == true) { - renderer->end(); - unitParticleSystems.clear(); - unitParticleSystemTypes.clear(); - - if(isControlKeyPressed == true) { - // std::cout << "Adding to list..." << std::endl; - this->particlePathList.push_back(path); - } - else { - // std::cout << "Clearing list..." << std::endl; - this->particlePathList.clear(); - this->particlePathList.push_back(path); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] added file [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,path.c_str()); - } - - try { - if(this->particlePathList.empty() == false) { - string titlestring=winHeader; - for(unsigned int idx = 0; idx < this->particlePathList.size(); idx++) { - string particlePath = this->particlePathList[idx]; - string dir= extractDirectoryPathFromFile(particlePath); - - size_t pos = dir.find_last_of(folderDelimiter); - if(pos == dir.length() - 1 && dir.length() > 0) { - dir.erase(dir.length() -1); - } - - particlePath= extractFileFromDirectoryPath(particlePath); - titlestring = particlePath + " - "+ titlestring; - - std::string unitXML = dir + folderDelimiter + extractFileFromDirectoryPath(dir) + ".xml"; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] looking for unit XML [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,unitXML.c_str()); - - //int size = -1; - //int height = -1; - int size = 0; - int height= 0; - - if(fileExists(unitXML) == true) { - { - XmlTree xmlTree; - xmlTree.load(unitXML,Properties::getTagReplacementValues()); - const XmlNode *unitNode= xmlTree.getRootNode(); - const XmlNode *parametersNode= unitNode->getChild("parameters"); - //size - size= parametersNode->getChild("size")->getAttribute("value")->getIntValue(); - //height - height= parametersNode->getChild("height")->getAttribute("value")->getIntValue(); - } - - // std::cout << "About to load [" << particlePath << "] from [" << dir << "] unit [" << unitXML << "]" << std::endl; - } - else { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] unit XML NOT FOUND [%s] using default position values\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,unitXML.c_str()); - - size = 1; - height= 1; - } - - std::map > > loadedFileList; - UnitParticleSystemType *unitParticleSystemType = new UnitParticleSystemType(); - unitParticleSystemType->load(NULL, dir, dir + folderDelimiter + particlePath, //### if we knew which particle it was, we could be more accurate - renderer,loadedFileList,"g3dviewer",""); - unitParticleSystemTypes.push_back(unitParticleSystemType); - - for(std::vector::const_iterator it= unitParticleSystemTypes.begin(); it != unitParticleSystemTypes.end(); ++it) { - UnitParticleSystem *ups= new UnitParticleSystem(200); - - ups->setParticleType((*it)); - (*it)->setValues(ups); - if(size > 0) { - //getCurrVectorFlat() + Vec3f(0.f, type->getHeight()/2.f, 0.f); - Vec3f vec = Vec3f(0.f, height / 2.f, 0.f); - ups->setPos(vec); - } - //ups->setFactionColor(getFaction()->getTexture()->getPixmap()->getPixel3f(0,0)); - ups->setFactionColor(renderer->getPlayerColorTexture(playerColor)->getPixmap()->getPixel3f(0,0)); - unitParticleSystems.push_back(ups); - renderer->manageParticleSystem(ups); +void MainWindow::loadProjectileParticle(string path) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] about to load [%s] " + "particleProjectilePathList.size() = " MG_SIZE_T_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, path.c_str(), this->particleProjectilePathList.size()); + + if (timer) + timer->Stop(); + if (path != "" && fileExists(path) == true) { + renderer->end(); + projectileParticleSystems.clear(); + projectileParticleSystemTypes.clear(); + + if (isControlKeyPressed == true) { + // std::cout << "Adding to list..." << std::endl; + this->particleProjectilePathList.push_back(path); + } else { + // std::cout << "Clearing list..." << std::endl; + this->particleProjectilePathList.clear(); + this->particleProjectilePathList.push_back(path); + } + } + + try { + if (this->particleProjectilePathList.empty() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("this->particleProjectilePathList.size() = " MG_SIZE_T_SPECIFIER + "\n", + this->particleProjectilePathList.size()); + + string titlestring = winHeader; + for (unsigned int idx = 0; idx < this->particleProjectilePathList.size(); + idx++) { + string particlePath = this->particleProjectilePathList[idx]; + string dir = extractDirectoryPathFromFile(particlePath); + + size_t pos = dir.find_last_of(folderDelimiter); + if (pos == dir.length() - 1) { + dir.erase(dir.length() - 1); + } - ups->setVisible(true); - } + particlePath = extractFileFromDirectoryPath(particlePath); + titlestring = particlePath + " - " + titlestring; + + std::string unitXML = + dir + folderDelimiter + extractFileFromDirectoryPath(dir) + ".xml"; + + int size = 1; + int height = 1; + + if (fileExists(unitXML) == true) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] loading [%s] idx = %u\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, unitXML.c_str(), idx); + + XmlTree xmlTree; + xmlTree.load(unitXML, Properties::getTagReplacementValues()); + const XmlNode *unitNode = xmlTree.getRootNode(); + const XmlNode *parametersNode = unitNode->getChild("parameters"); + // size + size = parametersNode->getChild("size") + ->getAttribute("value") + ->getIntValue(); + // height + height = parametersNode->getChild("height") + ->getAttribute("value") + ->getIntValue(); + } - if(path != "" && fileExists(path) == true) { - renderer->initModelManager(); - if(initTextureManager) { - renderer->initTextureManager(); - } - } + // std::cout << "About to load [" << particlePath << "] from [" << dir + // << "] unit [" << unitXML << "]" << std::endl; - } - SetTitle(ToUnicode(titlestring)); - } - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Not a Mega-Glest particle XML file, or broken"), wxOK | wxICON_ERROR).ShowModal(); - } - if(timer) timer->Start(100); -} + string particleFile = dir + folderDelimiter + particlePath; + { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] loading [%s] idx = %u\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, particleFile.c_str(), idx); + XmlTree xmlTree; + xmlTree.load(particleFile, Properties::getTagReplacementValues()); + // const XmlNode *particleSystemNode= xmlTree.getRootNode(); -void MainWindow::loadProjectileParticle(string path) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] about to load [%s] particleProjectilePathList.size() = " MG_SIZE_T_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,path.c_str(),this->particleProjectilePathList.size()); - - if(timer) timer->Stop(); - if(path != "" && fileExists(path) == true) { - renderer->end(); - projectileParticleSystems.clear(); - projectileParticleSystemTypes.clear(); - - if(isControlKeyPressed == true) { - // std::cout << "Adding to list..." << std::endl; - this->particleProjectilePathList.push_back(path); - } - else { - // std::cout << "Clearing list..." << std::endl; - this->particleProjectilePathList.clear(); - this->particleProjectilePathList.push_back(path); - } - } - - try { - if(this->particleProjectilePathList.empty() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("this->particleProjectilePathList.size() = " MG_SIZE_T_SPECIFIER "\n",this->particleProjectilePathList.size()); - - string titlestring=winHeader; - for(unsigned int idx = 0; idx < this->particleProjectilePathList.size(); idx++) { - string particlePath = this->particleProjectilePathList[idx]; - string dir= extractDirectoryPathFromFile(particlePath); - - size_t pos = dir.find_last_of(folderDelimiter); - if(pos == dir.length()-1) { - dir.erase(dir.length() -1); - } - - particlePath= extractFileFromDirectoryPath(particlePath); - titlestring = particlePath + " - "+ titlestring; - - std::string unitXML = dir + folderDelimiter + extractFileFromDirectoryPath(dir) + ".xml"; - - int size = 1; - int height = 1; - - if(fileExists(unitXML) == true) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] loading [%s] idx = %u\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,unitXML.c_str(),idx); - - XmlTree xmlTree; - xmlTree.load(unitXML,Properties::getTagReplacementValues()); - const XmlNode *unitNode= xmlTree.getRootNode(); - const XmlNode *parametersNode= unitNode->getChild("parameters"); - //size - size= parametersNode->getChild("size")->getAttribute("value")->getIntValue(); - //height - height= parametersNode->getChild("height")->getAttribute("value")->getIntValue(); - } - - // std::cout << "About to load [" << particlePath << "] from [" << dir << "] unit [" << unitXML << "]" << std::endl; - - string particleFile = dir + folderDelimiter + particlePath; - { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] loading [%s] idx = %u\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,particleFile.c_str(),idx); - XmlTree xmlTree; - xmlTree.load(particleFile,Properties::getTagReplacementValues()); - //const XmlNode *particleSystemNode= xmlTree.getRootNode(); - - // std::cout << "Loaded successfully, loading values..." << std::endl; - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] loading [%s] idx = %u\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,particleFile.c_str(),idx); - std::map > > loadedFileList; - ParticleSystemTypeProjectile *projectileParticleSystemType= new ParticleSystemTypeProjectile(); - projectileParticleSystemType->load(NULL, dir, //### we don't know if there are overrides in the unit XML - particleFile,renderer, loadedFileList, - "g3dviewer",""); - - // std::cout << "Values loaded, about to read..." << std::endl; - - projectileParticleSystemTypes.push_back(projectileParticleSystemType); - - for(std::vector::const_iterator it= projectileParticleSystemTypes.begin(); - it != projectileParticleSystemTypes.end(); ++it) { - - ProjectileParticleSystem *ps = (*it)->create(NULL); - - if(size > 0) { - Vec3f vec = Vec3f(0.f, height / 2.f, 0.f); - //ps->setPos(vec); - - Vec3f vec2 = Vec3f(size * 2.f, height * 2.f, height * 2.f); - ps->setPath(vec, vec2); - } - ps->setFactionColor(renderer->getPlayerColorTexture(playerColor)->getPixmap()->getPixel3f(0,0)); - - projectileParticleSystems.push_back(ps); - - ps->setVisible(true); - renderer->manageParticleSystem(ps); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] loaded [%s] idx = %u\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,particleFile.c_str(),idx); - } - SetTitle(ToUnicode(titlestring)); - - if(path != "" && fileExists(path) == true) { - renderer->initModelManager(); - if(initTextureManager) { - renderer->initTextureManager(); - } - } - } - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Not a Mega-Glest projectile particle XML file, or broken"), wxOK | wxICON_ERROR).ShowModal(); - } - if(timer) timer->Start(100); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] after load [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,path.c_str()); + // std::cout << "Loaded successfully, loading values..." << std::endl; + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] loading [%s] idx = %u\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, particleFile.c_str(), idx); + std::map>> loadedFileList; + ParticleSystemTypeProjectile *projectileParticleSystemType = + new ParticleSystemTypeProjectile(); + projectileParticleSystemType->load( + NULL, + dir, // ### we don't know if there are overrides in the unit XML + particleFile, renderer, loadedFileList, "g3dviewer", ""); + + // std::cout << "Values loaded, about to read..." << std::endl; + + projectileParticleSystemTypes.push_back(projectileParticleSystemType); + + for (std::vector::const_iterator it = + projectileParticleSystemTypes.begin(); + it != projectileParticleSystemTypes.end(); ++it) { + + ProjectileParticleSystem *ps = (*it)->create(NULL); + + if (size > 0) { + Vec3f vec = Vec3f(0.f, height / 2.f, 0.f); + // ps->setPos(vec); + + Vec3f vec2 = Vec3f(size * 2.f, height * 2.f, height * 2.f); + ps->setPath(vec, vec2); + } + ps->setFactionColor(renderer->getPlayerColorTexture(playerColor) + ->getPixmap() + ->getPixel3f(0, 0)); + + projectileParticleSystems.push_back(ps); + + ps->setVisible(true); + renderer->manageParticleSystem(ps); + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] loaded [%s] idx = %u\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, particleFile.c_str(), idx); + } + SetTitle(ToUnicode(titlestring)); + + if (path != "" && fileExists(path) == true) { + renderer->initModelManager(); + if (initTextureManager) { + renderer->initTextureManager(); + } + } + } + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog( + NULL, ToUnicode(e.what()), + ToUnicode("Not a Mega-Glest projectile particle XML file, or broken"), + wxOK | wxICON_ERROR) + .ShowModal(); + } + if (timer) + timer->Start(100); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] after load [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, path.c_str()); } -void MainWindow::loadSplashParticle(string path) { // uses ParticleSystemTypeSplash::load (and own list...) - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] about to load [%s] particleSplashPathList.size() = " MG_SIZE_T_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,path.c_str(),this->particleSplashPathList.size()); - - if(timer) timer->Stop(); - if(path != "" && fileExists(path) == true) { - renderer->end(); - splashParticleSystems.clear(); - splashParticleSystemTypes.clear(); - - if(isControlKeyPressed == true) { - // std::cout << "Adding to list..." << std::endl; - this->particleSplashPathList.push_back(path); - } - else { - // std::cout << "Clearing list..." << std::endl; - this->particleSplashPathList.clear(); - this->particleSplashPathList.push_back(path); - } - } - - try { - if(this->particleSplashPathList.empty() == false) { - string titlestring=winHeader; - for(unsigned int idx = 0; idx < this->particleSplashPathList.size(); idx++) { - string particlePath = this->particleSplashPathList[idx]; - string dir= extractDirectoryPathFromFile(particlePath); - - size_t pos = dir.find_last_of(folderDelimiter); - if(pos == dir.length()-1) { - dir.erase(dir.length() -1); - } - - particlePath= extractFileFromDirectoryPath(particlePath); - titlestring = particlePath + " - "+ titlestring; - - std::string unitXML = dir + folderDelimiter + extractFileFromDirectoryPath(dir) + ".xml"; - - int size = 1; - //int height = 1; - - if(fileExists(unitXML) == true) { - XmlTree xmlTree; - xmlTree.load(unitXML,Properties::getTagReplacementValues()); - const XmlNode *unitNode= xmlTree.getRootNode(); - const XmlNode *parametersNode= unitNode->getChild("parameters"); - //size - size= parametersNode->getChild("size")->getAttribute("value")->getIntValue(); - //height - //height= parametersNode->getChild("height")->getAttribute("value")->getIntValue(); - } - - // std::cout << "About to load [" << particlePath << "] from [" << dir << "] unit [" << unitXML << "]" << std::endl; - - { - XmlTree xmlTree; - xmlTree.load(dir + folderDelimiter + particlePath,Properties::getTagReplacementValues()); - //const XmlNode *particleSystemNode= xmlTree.getRootNode(); - // std::cout << "Loaded successfully, loading values..." << std::endl; - } - - std::map > > loadedFileList; - ParticleSystemTypeSplash *splashParticleSystemType= new ParticleSystemTypeSplash(); - splashParticleSystemType->load(NULL, dir, dir + folderDelimiter + particlePath,renderer, //### we don't know if there are overrides in the unit XML - loadedFileList,"g3dviewer",""); // <---- only that must be splash... - - // std::cout << "Values loaded, about to read..." << std::endl; - - splashParticleSystemTypes.push_back(splashParticleSystemType); - - //ParticleSystemTypeSplash - for(std::vector::const_iterator it= splashParticleSystemTypes.begin(); it != splashParticleSystemTypes.end(); ++it) { - - SplashParticleSystem *ps = (*it)->create(NULL); - - if(size > 0) { - //Vec3f vec = Vec3f(0.f, height / 2.f, 0.f); - //ps->setPos(vec); - - //Vec3f vec2 = Vec3f(size * 2.f, height * 2.f, height * 2.f); // <------- removed relative projectile - //ps->setPath(vec, vec2); // <------- removed relative projectile - } - ps->setFactionColor(renderer->getPlayerColorTexture(playerColor)->getPixmap()->getPixel3f(0,0)); - - splashParticleSystems.push_back(ps); - - ps->setVisible(true); - renderer->manageParticleSystem(ps); - } - } - SetTitle(ToUnicode(titlestring)); - - if(path != "" && fileExists(path) == true) { - renderer->initModelManager(); - if(initTextureManager) { - renderer->initTextureManager(); - } - } - } - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Not a Mega-Glest projectile particle XML file, or broken"), wxOK | wxICON_ERROR).ShowModal(); - } - if(timer) timer->Start(100); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] after load [%s] particleSplashPathList.size() = " MG_SIZE_T_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,path.c_str(),this->particleSplashPathList.size()); +void MainWindow::loadSplashParticle( + string path) { // uses ParticleSystemTypeSplash::load (and own list...) + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] about to load [%s] " + "particleSplashPathList.size() = " MG_SIZE_T_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, path.c_str(), this->particleSplashPathList.size()); + + if (timer) + timer->Stop(); + if (path != "" && fileExists(path) == true) { + renderer->end(); + splashParticleSystems.clear(); + splashParticleSystemTypes.clear(); + + if (isControlKeyPressed == true) { + // std::cout << "Adding to list..." << std::endl; + this->particleSplashPathList.push_back(path); + } else { + // std::cout << "Clearing list..." << std::endl; + this->particleSplashPathList.clear(); + this->particleSplashPathList.push_back(path); + } + } + + try { + if (this->particleSplashPathList.empty() == false) { + string titlestring = winHeader; + for (unsigned int idx = 0; idx < this->particleSplashPathList.size(); + idx++) { + string particlePath = this->particleSplashPathList[idx]; + string dir = extractDirectoryPathFromFile(particlePath); + + size_t pos = dir.find_last_of(folderDelimiter); + if (pos == dir.length() - 1) { + dir.erase(dir.length() - 1); + } + + particlePath = extractFileFromDirectoryPath(particlePath); + titlestring = particlePath + " - " + titlestring; + + std::string unitXML = + dir + folderDelimiter + extractFileFromDirectoryPath(dir) + ".xml"; + + int size = 1; + // int height = 1; + + if (fileExists(unitXML) == true) { + XmlTree xmlTree; + xmlTree.load(unitXML, Properties::getTagReplacementValues()); + const XmlNode *unitNode = xmlTree.getRootNode(); + const XmlNode *parametersNode = unitNode->getChild("parameters"); + // size + size = parametersNode->getChild("size") + ->getAttribute("value") + ->getIntValue(); + // height + // height= + // parametersNode->getChild("height")->getAttribute("value")->getIntValue(); + } + + // std::cout << "About to load [" << particlePath << "] from [" << dir + // << "] unit [" << unitXML << "]" << std::endl; + + { + XmlTree xmlTree; + xmlTree.load(dir + folderDelimiter + particlePath, + Properties::getTagReplacementValues()); + // const XmlNode *particleSystemNode= xmlTree.getRootNode(); + // std::cout << "Loaded successfully, loading values..." << + // std::endl; + } + + std::map>> loadedFileList; + ParticleSystemTypeSplash *splashParticleSystemType = + new ParticleSystemTypeSplash(); + splashParticleSystemType->load( + NULL, dir, dir + folderDelimiter + particlePath, + renderer, // ### we don't know if there are overrides in the unit + // XML + loadedFileList, "g3dviewer", + ""); // <---- only that must be splash... + + // std::cout << "Values loaded, about to read..." << std::endl; + + splashParticleSystemTypes.push_back(splashParticleSystemType); + + // ParticleSystemTypeSplash + for (std::vector::const_iterator it = + splashParticleSystemTypes.begin(); + it != splashParticleSystemTypes.end(); ++it) { + + SplashParticleSystem *ps = (*it)->create(NULL); + + if (size > 0) { + // Vec3f vec = Vec3f(0.f, height / 2.f, 0.f); + // ps->setPos(vec); + + // Vec3f vec2 = Vec3f(size * 2.f, height * 2.f, height * 2.f); // + // <------- removed relative projectile ps->setPath(vec, vec2); // + // <------- removed relative projectile + } + ps->setFactionColor(renderer->getPlayerColorTexture(playerColor) + ->getPixmap() + ->getPixel3f(0, 0)); + + splashParticleSystems.push_back(ps); + + ps->setVisible(true); + renderer->manageParticleSystem(ps); + } + } + SetTitle(ToUnicode(titlestring)); + + if (path != "" && fileExists(path) == true) { + renderer->initModelManager(); + if (initTextureManager) { + renderer->initTextureManager(); + } + } + } + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog( + NULL, ToUnicode(e.what()), + ToUnicode("Not a Mega-Glest projectile particle XML file, or broken"), + wxOK | wxICON_ERROR) + .ShowModal(); + } + if (timer) + timer->Start(100); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] after load [%s] particleSplashPathList.size() " + "= " MG_SIZE_T_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, path.c_str(), this->particleSplashPathList.size()); } -void MainWindow::onMenuModeNormals(wxCommandEvent &event){ - try { - renderer->toggleNormals(); - menuMode->Check(miModeNormals, renderer->getNormals()); - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } +void MainWindow::onMenuModeNormals(wxCommandEvent &event) { + try { + renderer->toggleNormals(); + menuMode->Check(miModeNormals, renderer->getNormals()); + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } } -void MainWindow::onMenuModeWireframe(wxCommandEvent &event){ - try { - renderer->toggleWireframe(); - menuMode->Check(miModeWireframe, renderer->getWireframe()); - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } +void MainWindow::onMenuModeWireframe(wxCommandEvent &event) { + try { + renderer->toggleWireframe(); + menuMode->Check(miModeWireframe, renderer->getWireframe()); + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } } -void MainWindow::onMenuModeGrid(wxCommandEvent &event){ - try { - renderer->toggleGrid(); - menuMode->Check(miModeGrid, renderer->getGrid()); - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } +void MainWindow::onMenuModeGrid(wxCommandEvent &event) { + try { + renderer->toggleGrid(); + menuMode->Check(miModeGrid, renderer->getGrid()); + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } } -void MainWindow::onMenuSpeedSlower(wxCommandEvent &event){ - try { - speed /= 1.5f; - if(speed < 0) { - speed = 0; - } - - string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY); - GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str())); - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } +void MainWindow::onMenuSpeedSlower(wxCommandEvent &event) { + try { + speed /= 1.5f; + if (speed < 0) { + speed = 0; + } + + string statusTextValue = + statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY); + GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str())); + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } } -void MainWindow::onMenuSpeedFaster(wxCommandEvent &event){ - try { - speed *= 1.5f; - if(speed > 1) { - speed = 1; - } - - string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0 ) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY); - GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str())); - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } +void MainWindow::onMenuSpeedFaster(wxCommandEvent &event) { + try { + speed *= 1.5f; + if (speed > 1) { + speed = 1; + } + + string statusTextValue = + statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY); + GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str())); + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } } // set menu checkboxes to what player color is used void MainWindow::onMenuColorRed(wxCommandEvent &event) { - try { - playerColor= Renderer::pcRed; - menuCustomColor->Check(miColorRed, true); - menuCustomColor->Check(miColorBlue, false); - menuCustomColor->Check(miColorGreen, false); - menuCustomColor->Check(miColorYellow, false); - menuCustomColor->Check(miColorWhite, false); - menuCustomColor->Check(miColorCyan, false); - menuCustomColor->Check(miColorOrange, false); - menuCustomColor->Check(miColorMagenta, false); - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } + try { + playerColor = Renderer::pcRed; + menuCustomColor->Check(miColorRed, true); + menuCustomColor->Check(miColorBlue, false); + menuCustomColor->Check(miColorGreen, false); + menuCustomColor->Check(miColorYellow, false); + menuCustomColor->Check(miColorWhite, false); + menuCustomColor->Check(miColorCyan, false); + menuCustomColor->Check(miColorOrange, false); + menuCustomColor->Check(miColorMagenta, false); + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } } void MainWindow::onMenuColorBlue(wxCommandEvent &event) { - try { - playerColor= Renderer::pcBlue; - menuCustomColor->Check(miColorRed, false); - menuCustomColor->Check(miColorBlue, true); - menuCustomColor->Check(miColorGreen, false); - menuCustomColor->Check(miColorYellow, false); - menuCustomColor->Check(miColorWhite, false); - menuCustomColor->Check(miColorCyan, false); - menuCustomColor->Check(miColorOrange, false); - menuCustomColor->Check(miColorMagenta, false); - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } + try { + playerColor = Renderer::pcBlue; + menuCustomColor->Check(miColorRed, false); + menuCustomColor->Check(miColorBlue, true); + menuCustomColor->Check(miColorGreen, false); + menuCustomColor->Check(miColorYellow, false); + menuCustomColor->Check(miColorWhite, false); + menuCustomColor->Check(miColorCyan, false); + menuCustomColor->Check(miColorOrange, false); + menuCustomColor->Check(miColorMagenta, false); + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } } void MainWindow::onMenuColorGreen(wxCommandEvent &event) { - try { - playerColor= Renderer::pcGreen; - menuCustomColor->Check(miColorRed, false); - menuCustomColor->Check(miColorBlue, false); - menuCustomColor->Check(miColorGreen, true); - menuCustomColor->Check(miColorYellow, false); - menuCustomColor->Check(miColorWhite, false); - menuCustomColor->Check(miColorCyan, false); - menuCustomColor->Check(miColorOrange, false); - menuCustomColor->Check(miColorMagenta, false); - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } + try { + playerColor = Renderer::pcGreen; + menuCustomColor->Check(miColorRed, false); + menuCustomColor->Check(miColorBlue, false); + menuCustomColor->Check(miColorGreen, true); + menuCustomColor->Check(miColorYellow, false); + menuCustomColor->Check(miColorWhite, false); + menuCustomColor->Check(miColorCyan, false); + menuCustomColor->Check(miColorOrange, false); + menuCustomColor->Check(miColorMagenta, false); + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } } void MainWindow::onMenuColorYellow(wxCommandEvent &event) { - try { - playerColor= Renderer::pcYellow; - menuCustomColor->Check(miColorRed, false); - menuCustomColor->Check(miColorBlue, false); - menuCustomColor->Check(miColorGreen, false); - menuCustomColor->Check(miColorYellow, true); - menuCustomColor->Check(miColorWhite, false); - menuCustomColor->Check(miColorCyan, false); - menuCustomColor->Check(miColorOrange, false); - menuCustomColor->Check(miColorMagenta, false); - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } + try { + playerColor = Renderer::pcYellow; + menuCustomColor->Check(miColorRed, false); + menuCustomColor->Check(miColorBlue, false); + menuCustomColor->Check(miColorGreen, false); + menuCustomColor->Check(miColorYellow, true); + menuCustomColor->Check(miColorWhite, false); + menuCustomColor->Check(miColorCyan, false); + menuCustomColor->Check(miColorOrange, false); + menuCustomColor->Check(miColorMagenta, false); + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } } void MainWindow::onMenuColorWhite(wxCommandEvent &event) { - try { - playerColor= Renderer::pcWhite; - menuCustomColor->Check(miColorRed, false); - menuCustomColor->Check(miColorBlue, false); - menuCustomColor->Check(miColorGreen, false); - menuCustomColor->Check(miColorYellow, false); - menuCustomColor->Check(miColorWhite, true); - menuCustomColor->Check(miColorCyan, false); - menuCustomColor->Check(miColorOrange, false); - menuCustomColor->Check(miColorMagenta, false); - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } + try { + playerColor = Renderer::pcWhite; + menuCustomColor->Check(miColorRed, false); + menuCustomColor->Check(miColorBlue, false); + menuCustomColor->Check(miColorGreen, false); + menuCustomColor->Check(miColorYellow, false); + menuCustomColor->Check(miColorWhite, true); + menuCustomColor->Check(miColorCyan, false); + menuCustomColor->Check(miColorOrange, false); + menuCustomColor->Check(miColorMagenta, false); + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } } void MainWindow::onMenuColorCyan(wxCommandEvent &event) { - try { - playerColor= Renderer::pcCyan; - menuCustomColor->Check(miColorRed, false); - menuCustomColor->Check(miColorBlue, false); - menuCustomColor->Check(miColorGreen, false); - menuCustomColor->Check(miColorYellow, false); - menuCustomColor->Check(miColorWhite, false); - menuCustomColor->Check(miColorCyan, true); - menuCustomColor->Check(miColorOrange, false); - menuCustomColor->Check(miColorMagenta, false); - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } + try { + playerColor = Renderer::pcCyan; + menuCustomColor->Check(miColorRed, false); + menuCustomColor->Check(miColorBlue, false); + menuCustomColor->Check(miColorGreen, false); + menuCustomColor->Check(miColorYellow, false); + menuCustomColor->Check(miColorWhite, false); + menuCustomColor->Check(miColorCyan, true); + menuCustomColor->Check(miColorOrange, false); + menuCustomColor->Check(miColorMagenta, false); + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } } void MainWindow::onMenuColorOrange(wxCommandEvent &event) { - try { - playerColor= Renderer::pcOrange; - menuCustomColor->Check(miColorRed, false); - menuCustomColor->Check(miColorBlue, false); - menuCustomColor->Check(miColorGreen, false); - menuCustomColor->Check(miColorYellow, false); - menuCustomColor->Check(miColorWhite, false); - menuCustomColor->Check(miColorCyan, false); - menuCustomColor->Check(miColorOrange, true); - menuCustomColor->Check(miColorMagenta, false); - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } + try { + playerColor = Renderer::pcOrange; + menuCustomColor->Check(miColorRed, false); + menuCustomColor->Check(miColorBlue, false); + menuCustomColor->Check(miColorGreen, false); + menuCustomColor->Check(miColorYellow, false); + menuCustomColor->Check(miColorWhite, false); + menuCustomColor->Check(miColorCyan, false); + menuCustomColor->Check(miColorOrange, true); + menuCustomColor->Check(miColorMagenta, false); + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } } void MainWindow::onMenuColorMagenta(wxCommandEvent &event) { - try { - playerColor= Renderer::pcMagenta; - menuCustomColor->Check(miColorRed, false); - menuCustomColor->Check(miColorBlue, false); - menuCustomColor->Check(miColorGreen, false); - menuCustomColor->Check(miColorYellow, false); - menuCustomColor->Check(miColorWhite, false); - menuCustomColor->Check(miColorCyan, false); - menuCustomColor->Check(miColorOrange, false); - menuCustomColor->Check(miColorMagenta, true); - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } + try { + playerColor = Renderer::pcMagenta; + menuCustomColor->Check(miColorRed, false); + menuCustomColor->Check(miColorBlue, false); + menuCustomColor->Check(miColorGreen, false); + menuCustomColor->Check(miColorYellow, false); + menuCustomColor->Check(miColorWhite, false); + menuCustomColor->Check(miColorCyan, false); + menuCustomColor->Check(miColorOrange, false); + menuCustomColor->Check(miColorMagenta, true); + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } } - void MainWindow::onTimer(wxTimerEvent &event) { - anim = anim + speed; - if(anim > 1.0f){ - anim -= 1.f; - resetAnimation = true; - } + anim = anim + speed; + if (anim > 1.0f) { + anim -= 1.f; + resetAnimation = true; + } - onPaintNoEvent(); + onPaintNoEvent(); } string MainWindow::getModelInfo() { - string str; + string str; - if(model != NULL) { - str+= "Meshes: "+intToStr(model->getMeshCount()); - str+= ", Vertices: "+intToStr(model->getVertexCount()); - str+= ", Triangles: "+intToStr(model->getTriangleCount()); - str+= ", Version: "+intToStr(model->getFileVersion()); - } + if (model != NULL) { + str += "Meshes: " + intToStr(model->getMeshCount()); + str += ", Vertices: " + intToStr(model->getVertexCount()); + str += ", Triangles: " + intToStr(model->getTriangleCount()); + str += ", Version: " + intToStr(model->getFileVersion()); + } - return str; + return str; } void MainWindow::onKeyDown(wxKeyEvent &e) { - try { - // std::cout << "e.ControlDown() = " << e.ControlDown() << " e.GetKeyCode() = " << e.GetKeyCode() << " isCtrl = " << (e.GetKeyCode() == WXK_CONTROL) << std::endl; - - // Note: This ctrl-key handling is buggy since it never resets when ctrl is released later, so I reset it at end of loadcommands for now. - if(e.ControlDown() == true || e.GetKeyCode() == WXK_CONTROL) { - isControlKeyPressed = true; - } - else { - isControlKeyPressed = false; - } - - // std::cout << "isControlKeyPressed = " << isControlKeyPressed << std::endl; - - - // here also because + and - hotkeys don't work for numpad automaticly - if (e.GetKeyCode() == 388) { - speed *= 1.5f; //numpad+ - if(speed > 1.0) { - speed = 1.0; - } - - string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY); - GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str())); - - } - else if (e.GetKeyCode() == 390) { - speed /= 1.5f; //numpad- - if(speed < 0) { - speed = 0; - } - string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY); - GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str())); - } - else if (e.GetKeyCode() == 'W') { - glClearColor(0.6f, 0.6f, 0.6f, 1.0f); //w key //backgroundcolor constant 0.3 -> 0.6 - - } - - // some posibility to adjust brightness: - /* - else if (e.GetKeyCode() == 322) { // Ins - Grid - gridBrightness += 0.1f; if (gridBrightness >1.0) gridBrightness =1.0; - } - else if (e.GetKeyCode() == 127) { // Del - gridBrightness -= 0.1f; if (gridBrightness <0) gridBrightness =0; - } - */ - else if (e.GetKeyCode() == 313) { // Home - Background - backBrightness += 0.1f; if (backBrightness >1.0) backBrightness=1.0; - glClearColor(backBrightness, backBrightness, backBrightness, 1.0f); - } - else if (e.GetKeyCode() == 312) { // End - backBrightness -= 0.1f; if (backBrightness<0) backBrightness=0; - glClearColor(backBrightness, backBrightness, backBrightness, 1.0f); - } - else if (e.GetKeyCode() == 366) { // PgUp - Lightning of model - lightBrightness += 0.1f; if (lightBrightness >1.0) lightBrightness =1.0; - Vec4f ambientNEW= Vec4f(lightBrightness, lightBrightness, lightBrightness, 1.0f); - glLightfv(GL_LIGHT0,GL_AMBIENT, ambientNEW.ptr()); - } - else if (e.GetKeyCode() == 367) { // pgDn - lightBrightness -= 0.1f; if (lightBrightness <0) lightBrightness =0; - Vec4f ambientNEW= Vec4f(lightBrightness, lightBrightness, lightBrightness, 1.0f); - glLightfv(GL_LIGHT0,GL_AMBIENT, ambientNEW.ptr()); - } - - std::cout << "pressed " << e.GetKeyCode() << std::endl; - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } + try { + // std::cout << "e.ControlDown() = " << e.ControlDown() << " e.GetKeyCode() + // = " << e.GetKeyCode() << " isCtrl = " << (e.GetKeyCode() == WXK_CONTROL) + // << std::endl; + + // Note: This ctrl-key handling is buggy since it never resets when ctrl is + // released later, so I reset it at end of loadcommands for now. + if (e.ControlDown() == true || e.GetKeyCode() == WXK_CONTROL) { + isControlKeyPressed = true; + } else { + isControlKeyPressed = false; + } + + // std::cout << "isControlKeyPressed = " << isControlKeyPressed << + // std::endl; + + // here also because + and - hotkeys don't work for numpad automaticly + if (e.GetKeyCode() == 388) { + speed *= 1.5f; // numpad+ + if (speed > 1.0) { + speed = 1.0; + } + + string statusTextValue = + statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY); + GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str())); + + } else if (e.GetKeyCode() == 390) { + speed /= 1.5f; // numpad- + if (speed < 0) { + speed = 0; + } + string statusTextValue = + statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY); + GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str())); + } else if (e.GetKeyCode() == 'W') { + glClearColor(0.6f, 0.6f, 0.6f, + 1.0f); // w key //backgroundcolor constant 0.3 -> 0.6 + + } + + // some posibility to adjust brightness: + /* + else if (e.GetKeyCode() == 322) { // Ins - Grid + gridBrightness += 0.1f; if (gridBrightness >1.0) gridBrightness + =1.0; + } + else if (e.GetKeyCode() == 127) { // Del + gridBrightness -= 0.1f; if (gridBrightness <0) gridBrightness =0; + } + */ + else if (e.GetKeyCode() == 313) { // Home - Background + backBrightness += 0.1f; + if (backBrightness > 1.0) + backBrightness = 1.0; + glClearColor(backBrightness, backBrightness, backBrightness, 1.0f); + } else if (e.GetKeyCode() == 312) { // End + backBrightness -= 0.1f; + if (backBrightness < 0) + backBrightness = 0; + glClearColor(backBrightness, backBrightness, backBrightness, 1.0f); + } else if (e.GetKeyCode() == 366) { // PgUp - Lightning of model + lightBrightness += 0.1f; + if (lightBrightness > 1.0) + lightBrightness = 1.0; + Vec4f ambientNEW = + Vec4f(lightBrightness, lightBrightness, lightBrightness, 1.0f); + glLightfv(GL_LIGHT0, GL_AMBIENT, ambientNEW.ptr()); + } else if (e.GetKeyCode() == 367) { // pgDn + lightBrightness -= 0.1f; + if (lightBrightness < 0) + lightBrightness = 0; + Vec4f ambientNEW = + Vec4f(lightBrightness, lightBrightness, lightBrightness, 1.0f); + glLightfv(GL_LIGHT0, GL_AMBIENT, ambientNEW.ptr()); + } + + std::cout << "pressed " << e.GetKeyCode() << std::endl; + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } } void MainWindow::onMenuRestart(wxCommandEvent &event) { - onMenuRestartNoEvent(); + onMenuRestartNoEvent(); } void MainWindow::onMenuRestartNoEvent() { - try { - // std::cout << "pressed R (restart particle animation)" << std::endl; - if(timer) timer->Stop(); - if(renderer) renderer->end(); - - unitParticleSystems.clear(); - unitParticleSystemTypes.clear(); - projectileParticleSystems.clear(); - projectileParticleSystemTypes.clear(); - splashParticleSystems.clear(); // as above - splashParticleSystemTypes.clear(); - - loadUnit("", ""); - loadModel(""); - loadParticle(""); - loadProjectileParticle(""); - loadSplashParticle(""); // as above - - renderer->initModelManager(); - if(initTextureManager) { - renderer->initTextureManager(); - } - if(timer) timer->Start(100); - } - catch(std::runtime_error &e) { - std::cout << e.what() << std::endl; - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal(); - } + try { + // std::cout << "pressed R (restart particle animation)" << std::endl; + if (timer) + timer->Stop(); + if (renderer) + renderer->end(); + + unitParticleSystems.clear(); + unitParticleSystemTypes.clear(); + projectileParticleSystems.clear(); + projectileParticleSystemTypes.clear(); + splashParticleSystems.clear(); // as above + splashParticleSystemTypes.clear(); + + loadUnit("", ""); + loadModel(""); + loadParticle(""); + loadProjectileParticle(""); + loadSplashParticle(""); // as above + + renderer->initModelManager(); + if (initTextureManager) { + renderer->initTextureManager(); + } + if (timer) + timer->Start(100); + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), + wxOK | wxICON_ERROR) + .ShowModal(); + } } BEGIN_EVENT_TABLE(MainWindow, wxFrame) - EVT_TIMER(-1, MainWindow::onTimer) - EVT_CLOSE(MainWindow::onClose) - EVT_MENU(miFileLoad, MainWindow::onMenuFileLoad) - EVT_MENU(miFileLoadParticleXML, MainWindow::onMenuFileLoadParticleXML) - EVT_MENU(miFileLoadProjectileParticleXML, MainWindow::onMenuFileLoadProjectileParticleXML) - EVT_MENU(miFileLoadSplashParticleXML, MainWindow::onMenuFileLoadSplashParticleXML) - EVT_MENU(miFileClearAll, MainWindow::onMenuFileClearAll) - EVT_MENU(miFileToggleScreenshotTransparent, MainWindow::onMenumFileToggleScreenshotTransparent) - EVT_MENU(miFileSaveScreenshot, MainWindow::onMenuFileSaveScreenshot) - EVT_MENU(wxID_EXIT, MainWindow::onMenuFileExit) - - EVT_MENU(miModeWireframe, MainWindow::onMenuModeWireframe) - EVT_MENU(miModeNormals, MainWindow::onMenuModeNormals) - EVT_MENU(miModeGrid, MainWindow::onMenuModeGrid) - - EVT_MENU(miSpeedFaster, MainWindow::onMenuSpeedFaster) - EVT_MENU(miSpeedSlower, MainWindow::onMenuSpeedSlower) - EVT_MENU(miRestart, MainWindow::onMenuRestart) - - EVT_MENU(miColorRed, MainWindow::onMenuColorRed) - EVT_MENU(miColorBlue, MainWindow::onMenuColorBlue) - EVT_MENU(miColorGreen, MainWindow::onMenuColorGreen) - EVT_MENU(miColorYellow, MainWindow::onMenuColorYellow) - EVT_MENU(miColorWhite, MainWindow::onMenuColorWhite) - EVT_MENU(miColorCyan, MainWindow::onMenuColorCyan) - EVT_MENU(miColorOrange, MainWindow::onMenuColorOrange) - EVT_MENU(miColorMagenta, MainWindow::onMenuColorMagenta) - - EVT_MENU(miChangeBackgroundColor, MainWindow::OnChangeColor) +EVT_TIMER(-1, MainWindow::onTimer) +EVT_CLOSE(MainWindow::onClose) +EVT_MENU(miFileLoad, MainWindow::onMenuFileLoad) +EVT_MENU(miFileLoadParticleXML, MainWindow::onMenuFileLoadParticleXML) +EVT_MENU(miFileLoadProjectileParticleXML, + MainWindow::onMenuFileLoadProjectileParticleXML) +EVT_MENU(miFileLoadSplashParticleXML, + MainWindow::onMenuFileLoadSplashParticleXML) +EVT_MENU(miFileClearAll, MainWindow::onMenuFileClearAll) +EVT_MENU(miFileToggleScreenshotTransparent, + MainWindow::onMenumFileToggleScreenshotTransparent) +EVT_MENU(miFileSaveScreenshot, MainWindow::onMenuFileSaveScreenshot) +EVT_MENU(wxID_EXIT, MainWindow::onMenuFileExit) + +EVT_MENU(miModeWireframe, MainWindow::onMenuModeWireframe) +EVT_MENU(miModeNormals, MainWindow::onMenuModeNormals) +EVT_MENU(miModeGrid, MainWindow::onMenuModeGrid) + +EVT_MENU(miSpeedFaster, MainWindow::onMenuSpeedFaster) +EVT_MENU(miSpeedSlower, MainWindow::onMenuSpeedSlower) +EVT_MENU(miRestart, MainWindow::onMenuRestart) + +EVT_MENU(miColorRed, MainWindow::onMenuColorRed) +EVT_MENU(miColorBlue, MainWindow::onMenuColorBlue) +EVT_MENU(miColorGreen, MainWindow::onMenuColorGreen) +EVT_MENU(miColorYellow, MainWindow::onMenuColorYellow) +EVT_MENU(miColorWhite, MainWindow::onMenuColorWhite) +EVT_MENU(miColorCyan, MainWindow::onMenuColorCyan) +EVT_MENU(miColorOrange, MainWindow::onMenuColorOrange) +EVT_MENU(miColorMagenta, MainWindow::onMenuColorMagenta) + +EVT_MENU(miChangeBackgroundColor, MainWindow::OnChangeColor) END_EVENT_TABLE() // ===================================================== @@ -2006,79 +2324,84 @@ END_EVENT_TABLE() void translateCoords(wxWindow *wnd, int &x, int &y) { #ifdef WIN32 - int cx, cy; - wnd->GetPosition(&cx, &cy); - x += cx; - y += cy; + int cx, cy; + wnd->GetPosition(&cx, &cy); + x += cx; + y += cy; #endif } // to prevent flicker -GlCanvas::GlCanvas(MainWindow * mainWindow, int *args) +GlCanvas::GlCanvas(MainWindow *mainWindow, int *args) #if wxCHECK_VERSION(2, 9, 1) - : wxGLCanvas(mainWindow, wxID_ANY, args, wxDefaultPosition, mainWindow->GetClientSize(), wxFULL_REPAINT_ON_RESIZE, wxT("GLCanvas")) { - this->context = new wxGLContext(this); + : wxGLCanvas(mainWindow, wxID_ANY, args, wxDefaultPosition, + mainWindow->GetClientSize(), wxFULL_REPAINT_ON_RESIZE, + wxT("GLCanvas")) { + this->context = new wxGLContext(this); #else - : wxGLCanvas(mainWindow, -1, wxDefaultPosition, wxDefaultSize, 0, wxT("GLCanvas"), args) { - this->context = NULL; + : wxGLCanvas(mainWindow, -1, wxDefaultPosition, wxDefaultSize, 0, + wxT("GLCanvas"), args) { + this->context = NULL; #endif - this->mainWindow = mainWindow; + this->mainWindow = mainWindow; } GlCanvas::~GlCanvas() { - if(this->context) { - delete this->context; - } - this->context = NULL; + if (this->context) { + delete this->context; + } + this->context = NULL; } void GlCanvas::setCurrentGLContext() { #if wxCHECK_VERSION(3, 0, 0) - //printf("Setting glcontext 3x!\n"); - - //if(!IsShown()) {} - if(this->context == NULL) { - //printf("Make new ctx!\n"); - this->context = new wxGLContext(this); - //printf("Set ctx [%p]\n",this->context); - } + // printf("Setting glcontext 3x!\n"); + + // if(!IsShown()) {} + if (this->context == NULL) { + // printf("Make new ctx!\n"); + this->context = new wxGLContext(this); + // printf("Set ctx [%p]\n",this->context); + } #elif wxCHECK_VERSION(2, 9, 1) - //printf("Setting glcontext 29x!\n"); + // printf("Setting glcontext 29x!\n"); - //if(!IsShown()) {} - if(this->context == NULL) { - this->context = new wxGLContext(this); - //printf("Set ctx [%p]\n",this->context); - } + // if(!IsShown()) {} + if (this->context == NULL) { + this->context = new wxGLContext(this); + // printf("Set ctx [%p]\n",this->context); + } #endif - //printf("Set ctx [%p]\n",this->context); - if(this->context) { - wxGLCanvas::SetCurrent(*this->context); - //printf("Set ctx2 [%p]\n",this->context); - } + // printf("Set ctx [%p]\n",this->context); + if (this->context) { + wxGLCanvas::SetCurrent(*this->context); + // printf("Set ctx2 [%p]\n",this->context); + } } // for the mousewheel void GlCanvas::onMouseWheel(wxMouseEvent &event) { - if(event.GetWheelRotation()>0) mainWindow->onMouseWheelDown(event); - else mainWindow->onMouseWheelUp(event); + if (event.GetWheelRotation() > 0) + mainWindow->onMouseWheelDown(event); + else + mainWindow->onMouseWheelUp(event); } -void GlCanvas::onMouseMove(wxMouseEvent &event){ - mainWindow->onMouseMove(event); +void GlCanvas::onMouseMove(wxMouseEvent &event) { + mainWindow->onMouseMove(event); } void GlCanvas::onKeyDown(wxKeyEvent &event) { - int x, y; - event.GetPosition(&x, &y); - translateCoords(this, x, y); - mainWindow->onKeyDown(event); + int x, y; + event.GetPosition(&x, &y); + translateCoords(this, x, y); + mainWindow->onKeyDown(event); } -void GlCanvas::OnSize(wxSizeEvent&event) { +void GlCanvas::OnSize(wxSizeEvent &event) { - //printf("OnSize %dx%d\n",event.m_size.GetWidth(),event.m_size.GetHeight()); - Update(); + // printf("OnSize %dx%d\n",event.m_size.GetWidth(),event.m_size.GetHeight()); + Update(); } // EVT_SPIN_DOWN(GlCanvas::onMouseDown) @@ -2087,10 +2410,10 @@ void GlCanvas::OnSize(wxSizeEvent&event) { // EVT_MIDDLE_UP(GlCanvas::onMouseWheel) BEGIN_EVENT_TABLE(GlCanvas, wxGLCanvas) - EVT_MOUSEWHEEL(GlCanvas::onMouseWheel) - EVT_MOTION(GlCanvas::onMouseMove) - EVT_KEY_DOWN(GlCanvas::onKeyDown) - EVT_SIZE(GlCanvas::OnSize) +EVT_MOUSEWHEEL(GlCanvas::onMouseWheel) +EVT_MOTION(GlCanvas::onMouseMove) +EVT_KEY_DOWN(GlCanvas::onKeyDown) +EVT_SIZE(GlCanvas::OnSize) END_EVENT_TABLE() // =============================================== @@ -2098,468 +2421,542 @@ END_EVENT_TABLE() // =============================================== bool App::OnInit() { - SystemFlags::VERBOSE_MODE_ENABLED = false; + SystemFlags::VERBOSE_MODE_ENABLED = false; -#if defined(wxMAJOR_VERSION) && defined(wxMINOR_VERSION) && defined(wxRELEASE_NUMBER) && defined(wxSUBRELEASE_NUMBER) - printf("Using wxWidgets version [%d.%d.%d.%d]\n",wxMAJOR_VERSION,wxMINOR_VERSION,wxRELEASE_NUMBER,wxSUBRELEASE_NUMBER); +#if defined(wxMAJOR_VERSION) && defined(wxMINOR_VERSION) && \ + defined(wxRELEASE_NUMBER) && defined(wxSUBRELEASE_NUMBER) + printf("Using wxWidgets version [%d.%d.%d.%d]\n", wxMAJOR_VERSION, + wxMINOR_VERSION, wxRELEASE_NUMBER, wxSUBRELEASE_NUMBER); #endif - string modelPath=""; - string particlePath=""; - string projectileParticlePath=""; - string splashParticlePath=""; + string modelPath = ""; + string particlePath = ""; + string projectileParticlePath = ""; + string splashParticlePath = ""; - - bool foundInvalidArgs = false; - const int knownArgCount = sizeof(GAME_ARGS) / sizeof(GAME_ARGS[0]); - for(int idx = 1; idx < argc; ++idx) { + bool foundInvalidArgs = false; + const int knownArgCount = sizeof(GAME_ARGS) / sizeof(GAME_ARGS[0]); + for (int idx = 1; idx < argc; ++idx) { #if wxCHECK_VERSION(2, 9, 1) - const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(argv[idx].wc_str()); + const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(argv[idx].wc_str()); #else - const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(argv[idx]); + const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(argv[idx]); #endif -if( hasCommandArgument(knownArgCount, (wxChar**)&GAME_ARGS[0], (const char *)tmp_buf, NULL, 0, true) == false && - argv[idx][0] == '-') { - foundInvalidArgs = true; - - printf("\nInvalid argument: %s",(const char*)tmp_buf); - } - } + if (hasCommandArgument(knownArgCount, (wxChar **)&GAME_ARGS[0], + (const char *)tmp_buf, NULL, 0, true) == false && + argv[idx][0] == '-') { + foundInvalidArgs = true; - if(foundInvalidArgs == true || - hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_HELP])) == true) { - printParameterHelp(static_cast(WX2CHR(argv[0])), foundInvalidArgs); - return false; + printf("\nInvalid argument: %s", (const char *)tmp_buf); } - - if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_VERBOSE])) == true) { - SystemFlags::VERBOSE_MODE_ENABLED = true; + } + + if (foundInvalidArgs == true || + hasCommandArgument(argc, argv, + (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_HELP])) == true) { + printParameterHelp(static_cast(WX2CHR(argv[0])), + foundInvalidArgs); + return false; + } + + if (hasCommandArgument(argc, argv, + (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_VERBOSE])) == true) { + SystemFlags::VERBOSE_MODE_ENABLED = true; + } + + if (hasCommandArgument(argc, argv, + (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_AUTO_SCREENSHOT])) == true) { + autoScreenShotAndExit = true; + + const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_AUTO_SCREENSHOT]); + // printf("param = [%s]\n",(const char*)param); + + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, string((const char *)param) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, (const char *)param, &foundParamIndIndex); } - - if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_AUTO_SCREENSHOT])) == true) { - autoScreenShotAndExit = true; - - const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_AUTO_SCREENSHOT]); - //printf("param = [%s]\n",(const char*)param); - - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string((const char*)param) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,(const char*)param,&foundParamIndIndex); - } - //printf("foundParamIndIndex = %d\n",foundParamIndIndex); + // printf("foundParamIndIndex = %d\n",foundParamIndIndex); #if wxCHECK_VERSION(2, 9, 1) - string options = argv[foundParamIndIndex].ToStdString(); + string options = argv[foundParamIndIndex].ToStdString(); #else - string options = (const char *)wxConvCurrent->cWX2MB(argv[foundParamIndIndex]); + string options = + (const char *)wxConvCurrent->cWX2MB(argv[foundParamIndIndex]); #endif - vector paramPartTokens; - Tokenize(options,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string optionsValue = paramPartTokens[1]; + vector paramPartTokens; + Tokenize(options, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string optionsValue = paramPartTokens[1]; - autoScreenShotParams.clear(); - Tokenize(optionsValue,autoScreenShotParams,","); + autoScreenShotParams.clear(); + Tokenize(optionsValue, autoScreenShotParams, ","); - for(unsigned int i = 0; i < autoScreenShotParams.size(); ++i) { + for (unsigned int i = 0; i < autoScreenShotParams.size(); ++i) { #ifdef WIN32 - auto_ptr wstr(Ansi2WideString(autoScreenShotParams[i].c_str())); - autoScreenShotParams[i] = utf8_encode(wstr.get()); + auto_ptr wstr( + Ansi2WideString(autoScreenShotParams[i].c_str())); + autoScreenShotParams[i] = utf8_encode(wstr.get()); #endif - if(_strnicmp(autoScreenShotParams[i].c_str(),"resize-",7) == 0) { - printf("Screenshot option [%s]\n",autoScreenShotParams[i].c_str()); - - string resize = autoScreenShotParams[i]; - resize = resize.erase(0,7); - vector values; - Tokenize(resize,values,"x"); - overrideSize.first = strToInt(values[0]); - overrideSize.second = strToInt(values[1]); - - Renderer::windowX= 0; - Renderer::windowY= 0; - Renderer::windowW = overrideSize.first; - Renderer::windowH = overrideSize.second + 25; - } - } - } - } - - std::pair > unitToLoad; - if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_UNIT])) == true) { - const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_UNIT]); - //printf("param = [%s]\n",(const char*)param); + if (_strnicmp(autoScreenShotParams[i].c_str(), "resize-", 7) == 0) { + printf("Screenshot option [%s]\n", autoScreenShotParams[i].c_str()); - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string((const char*)param) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,(const char*)param,&foundParamIndIndex); - } - //printf("foundParamIndIndex = %d\n",foundParamIndIndex); - string customPath = static_cast(WX2CHR(argv[foundParamIndIndex])); - vector paramPartTokens; - Tokenize(customPath,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string customPathValue = paramPartTokens[1]; - std::vector delimitedList; - Tokenize(customPathValue,delimitedList,","); - - if(delimitedList.size() >= 2) { - unitToLoad.first = delimitedList[0]; - #ifdef WIN32 - auto_ptr wstr(Ansi2WideString(unitToLoad.first.c_str())); - unitToLoad.first = utf8_encode(wstr.get()); - #endif - - for(unsigned int i = 1; i < delimitedList.size(); ++i) { - string value = delimitedList[i]; - #ifdef WIN32 - auto_ptr wstr(Ansi2WideString(value.c_str())); - value = utf8_encode(wstr.get()); - #endif - - unitToLoad.second.push_back(value); - } - } - else { - printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", static_cast(WX2CHR(argv[foundParamIndIndex])), (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - printParameterHelp(WX2CHR(argv[0]),false); - return false; - } + string resize = autoScreenShotParams[i]; + resize = resize.erase(0, 7); + vector values; + Tokenize(resize, values, "x"); + overrideSize.first = strToInt(values[0]); + overrideSize.second = strToInt(values[1]); + Renderer::windowX = 0; + Renderer::windowY = 0; + Renderer::windowW = overrideSize.first; + Renderer::windowH = overrideSize.second + 25; } - else { - printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", static_cast(WX2CHR(argv[foundParamIndIndex])),(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - printParameterHelp(WX2CHR(argv[0]),false); - return false; - } + } } - - if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL])) == true && - hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL_ANIMATION_VALUE])) == false) { - const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL]); - //printf("param = [%s]\n",(const char*)param); - - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string((const char*)param) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,(const char*)param,&foundParamIndIndex); - } - //printf("foundParamIndIndex = %d\n",foundParamIndIndex); - string customPath = (const char*)WX2CHR(argv[foundParamIndIndex]); - vector paramPartTokens; - Tokenize(customPath,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string customPathValue = paramPartTokens[1]; - modelPath = customPathValue; - #ifdef WIN32 - auto_ptr wstr(Ansi2WideString(modelPath.c_str())); - modelPath = utf8_encode(wstr.get()); - #endif - - } - else { - printf("\nInvalid path specified on commandline [%s] value [%s]\n\n",(const char*)WX2CHR(argv[foundParamIndIndex]),(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - printParameterHelp(WX2CHR(argv[0]),false); - return false; - } + } + + std::pair> unitToLoad; + if (hasCommandArgument(argc, argv, + (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_LOAD_UNIT])) == true) { + const wxWX2MBbuf param = + (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_UNIT]); + // printf("param = [%s]\n",(const char*)param); + + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, string((const char *)param) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, (const char *)param, &foundParamIndIndex); } + // printf("foundParamIndIndex = %d\n",foundParamIndIndex); + string customPath = + static_cast(WX2CHR(argv[foundParamIndIndex])); + vector paramPartTokens; + Tokenize(customPath, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string customPathValue = paramPartTokens[1]; + std::vector delimitedList; + Tokenize(customPathValue, delimitedList, ","); + + if (delimitedList.size() >= 2) { + unitToLoad.first = delimitedList[0]; +#ifdef WIN32 + auto_ptr wstr(Ansi2WideString(unitToLoad.first.c_str())); + unitToLoad.first = utf8_encode(wstr.get()); +#endif - if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE])) == true && - hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_LOOP_VALUE])) == false) { - const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE]); - //printf("param = [%s]\n",(const char*)param); + for (unsigned int i = 1; i < delimitedList.size(); ++i) { + string value = delimitedList[i]; +#ifdef WIN32 + auto_ptr wstr(Ansi2WideString(value.c_str())); + value = utf8_encode(wstr.get()); +#endif - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string((const char*)param) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,(const char*)param,&foundParamIndIndex); - } - //printf("foundParamIndIndex = %d\n",foundParamIndIndex); - string customPath = (const char*)WX2CHR(argv[foundParamIndIndex]); - vector paramPartTokens; - Tokenize(customPath,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string customPathValue = paramPartTokens[1]; - particlePath = customPathValue; - #ifdef WIN32 - auto_ptr wstr(Ansi2WideString(particlePath.c_str())); - particlePath = utf8_encode(wstr.get()); - #endif - } - else { - printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", (const char*)WX2CHR(argv[foundParamIndIndex]),(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - printParameterHelp(WX2CHR(argv[0]),false); - return false; + unitToLoad.second.push_back(value); } + } else { + printf( + "\nInvalid path specified on commandline [%s] value [%s]\n\n", + static_cast(WX2CHR(argv[foundParamIndIndex])), + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + printParameterHelp(WX2CHR(argv[0]), false); + return false; + } + + } else { + printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", + static_cast(WX2CHR(argv[foundParamIndIndex])), + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + printParameterHelp(WX2CHR(argv[0]), false); + return false; } - - if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_PROJECTILE])) == true) { - const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_PROJECTILE]); - //printf("param = [%s]\n",(const char*)param); - - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string((const char*)param) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,(const char*)param,&foundParamIndIndex); - } - //printf("foundParamIndIndex = %d\n",foundParamIndIndex); - string customPath = (const char*)WX2CHR(argv[foundParamIndIndex]); - vector paramPartTokens; - Tokenize(customPath,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string customPathValue = paramPartTokens[1]; - projectileParticlePath = customPathValue; - #ifdef WIN32 - auto_ptr wstr(Ansi2WideString(projectileParticlePath.c_str())); - projectileParticlePath = utf8_encode(wstr.get()); - #endif - } - else { - printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", (const char*)WX2CHR(argv[foundParamIndIndex]),(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - printParameterHelp(WX2CHR(argv[0]),false); - return false; - } + } + + if (hasCommandArgument(argc, argv, + (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_LOAD_MODEL])) == true && + hasCommandArgument(argc, argv, + (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_LOAD_MODEL_ANIMATION_VALUE])) == + false) { + const wxWX2MBbuf param = + (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL]); + // printf("param = [%s]\n",(const char*)param); + + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, string((const char *)param) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, (const char *)param, &foundParamIndIndex); } + // printf("foundParamIndIndex = %d\n",foundParamIndIndex); + string customPath = (const char *)WX2CHR(argv[foundParamIndIndex]); + vector paramPartTokens; + Tokenize(customPath, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string customPathValue = paramPartTokens[1]; + modelPath = customPathValue; +#ifdef WIN32 + auto_ptr wstr(Ansi2WideString(modelPath.c_str())); + modelPath = utf8_encode(wstr.get()); +#endif - if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_SPLASH])) == true) { - const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_SPLASH]); - //printf("param = [%s]\n",(const char*)param); - - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string((const char*)param) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,(const char*)param,&foundParamIndIndex); - } - //printf("foundParamIndIndex = %d\n",foundParamIndIndex); - string customPath = (const char*)WX2CHR(argv[foundParamIndIndex]); - vector paramPartTokens; - Tokenize(customPath,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string customPathValue = paramPartTokens[1]; - splashParticlePath = customPathValue; - #ifdef WIN32 - auto_ptr wstr(Ansi2WideString(splashParticlePath.c_str())); - splashParticlePath = utf8_encode(wstr.get()); - #endif - } - else { - printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", (const char*)WX2CHR(argv[foundParamIndIndex]),(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - printParameterHelp(WX2CHR(argv[0]),false); - return false; - } + } else { + printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", + (const char *)WX2CHR(argv[foundParamIndIndex]), + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + printParameterHelp(WX2CHR(argv[0]), false); + return false; } - - float newAnimValue = 0.0f; - if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL_ANIMATION_VALUE])) == true) { - const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL_ANIMATION_VALUE]); - - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string((const char*)param) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,(const char*)param,&foundParamIndIndex); - } - //printf("foundParamIndIndex = %d\n",foundParamIndIndex); - string value = (const char*)WX2CHR(argv[foundParamIndIndex]); - vector paramPartTokens; - Tokenize(value,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - newAnimValue = strToFloat(paramPartTokens[1]); - printf("newAnimValue = %f\n",newAnimValue); - } - else { - printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", (const char*)WX2CHR(argv[foundParamIndIndex]),(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - printParameterHelp(WX2CHR(argv[0]),false); - return false; - } + } + + if (hasCommandArgument(argc, argv, + (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_LOAD_PARTICLE])) == true && + hasCommandArgument(argc, argv, + (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_LOAD_PARTICLE_LOOP_VALUE])) == + false) { + const wxWX2MBbuf param = + (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE]); + // printf("param = [%s]\n",(const char*)param); + + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, string((const char *)param) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, (const char *)param, &foundParamIndIndex); } - - int newParticleLoopValue = 1; - if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_LOOP_VALUE])) == true) { - const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_LOOP_VALUE]); - - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string((const char*)param) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,(const char*)param,&foundParamIndIndex); - } - //printf("foundParamIndIndex = %d\n",foundParamIndIndex); - string value = (const char*)WX2CHR(argv[foundParamIndIndex]); - vector paramPartTokens; - Tokenize(value,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - newParticleLoopValue = strToInt(paramPartTokens[1]); - //printf("newParticleLoopValue = %d\n",newParticleLoopValue); - } - else { - printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", (const char*)WX2CHR(argv[foundParamIndIndex]),(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - printParameterHelp(WX2CHR(argv[0]),false); - return false; - } + // printf("foundParamIndIndex = %d\n",foundParamIndIndex); + string customPath = (const char *)WX2CHR(argv[foundParamIndIndex]); + vector paramPartTokens; + Tokenize(customPath, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string customPathValue = paramPartTokens[1]; + particlePath = customPathValue; +#ifdef WIN32 + auto_ptr wstr(Ansi2WideString(particlePath.c_str())); + particlePath = utf8_encode(wstr.get()); +#endif + } else { + printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", + (const char *)WX2CHR(argv[foundParamIndIndex]), + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + printParameterHelp(WX2CHR(argv[0]), false); + return false; } - - float newZoomValue = 1.0f; - if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ZOOM_VALUE])) == true) { - const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ZOOM_VALUE]); - - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string((const char*)param) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,(const char*)param,&foundParamIndIndex); - } - //printf("foundParamIndIndex = %d\n",foundParamIndIndex); - string value = (const char*)WX2CHR(argv[foundParamIndIndex]); - vector paramPartTokens; - Tokenize(value,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - newZoomValue = strToFloat(paramPartTokens[1]); - //printf("newAnimValue = %f\n",newAnimValue); - } - else { - printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", (const char*)WX2CHR(argv[foundParamIndIndex]),(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - printParameterHelp(WX2CHR(argv[0]),false); - return false; - } + } + + if (hasCommandArgument(argc, argv, + (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_LOAD_PARTICLE_PROJECTILE])) == + true) { + const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_LOAD_PARTICLE_PROJECTILE]); + // printf("param = [%s]\n",(const char*)param); + + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, string((const char *)param) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, (const char *)param, &foundParamIndIndex); } - - float newXRotValue = 0.0f; - if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_X_VALUE])) == true) { - const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_X_VALUE]); - - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string((const char*)param) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,(const char*)param,&foundParamIndIndex); - } - //printf("foundParamIndIndex = %d\n",foundParamIndIndex); - string value = (const char*)WX2CHR(argv[foundParamIndIndex]); - vector paramPartTokens; - Tokenize(value,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - newXRotValue = strToFloat(paramPartTokens[1]); - //printf("newAnimValue = %f\n",newAnimValue); - } - else { - printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", (const char*)WX2CHR(argv[foundParamIndIndex]),(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - printParameterHelp(WX2CHR(argv[0]),false); - return false; - } + // printf("foundParamIndIndex = %d\n",foundParamIndIndex); + string customPath = (const char *)WX2CHR(argv[foundParamIndIndex]); + vector paramPartTokens; + Tokenize(customPath, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string customPathValue = paramPartTokens[1]; + projectileParticlePath = customPathValue; +#ifdef WIN32 + auto_ptr wstr(Ansi2WideString(projectileParticlePath.c_str())); + projectileParticlePath = utf8_encode(wstr.get()); +#endif + } else { + printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", + (const char *)WX2CHR(argv[foundParamIndIndex]), + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + printParameterHelp(WX2CHR(argv[0]), false); + return false; } - - float newYRotValue = 0.0f; - if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_Y_VALUE])) == true) { - const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_Y_VALUE]); - - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string((const char*)param) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,(const char*)param,&foundParamIndIndex); - } - //printf("foundParamIndIndex = %d\n",foundParamIndIndex); - string value = static_cast(WX2CHR(argv[foundParamIndIndex])); - vector paramPartTokens; - Tokenize(value,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - newYRotValue = strToFloat(paramPartTokens[1]); - //printf("newAnimValue = %f\n",newAnimValue); - } - else { - printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", static_cast(WX2CHR(argv[foundParamIndIndex])),(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - printParameterHelp(WX2CHR(argv[0]),false); - return false; - } + } + + if (hasCommandArgument(argc, argv, + (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_LOAD_PARTICLE_SPLASH])) == + true) { + const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_LOAD_PARTICLE_SPLASH]); + // printf("param = [%s]\n",(const char*)param); + + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, string((const char *)param) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, (const char *)param, &foundParamIndIndex); } - - if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_SCREENSHOT_FORMAT])) == true) { - const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_SCREENSHOT_FORMAT]); - - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string((const char*)param) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,(const char*)param,&foundParamIndIndex); - } - //printf("foundParamIndIndex = %d\n",foundParamIndIndex); - string value = static_cast(WX2CHR(argv[foundParamIndIndex])); - vector paramPartTokens; - Tokenize(value,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - fileFormat = paramPartTokens[1]; - } - else { - printf("\nInvalid value specified on commandline [%s] value [%s]\n\n", static_cast(WX2CHR(argv[foundParamIndIndex])), (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - printParameterHelp(WX2CHR(argv[0]),false); - return false; - } + // printf("foundParamIndIndex = %d\n",foundParamIndIndex); + string customPath = (const char *)WX2CHR(argv[foundParamIndIndex]); + vector paramPartTokens; + Tokenize(customPath, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string customPathValue = paramPartTokens[1]; + splashParticlePath = customPathValue; +#ifdef WIN32 + auto_ptr wstr(Ansi2WideString(splashParticlePath.c_str())); + splashParticlePath = utf8_encode(wstr.get()); +#endif + } else { + printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", + (const char *)WX2CHR(argv[foundParamIndIndex]), + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + printParameterHelp(WX2CHR(argv[0]), false); + return false; } - - if(argc == 2 && argv[1][0] != '-') { - modelPath = static_cast(WX2CHR(argv[1])); - } - -//#if defined(__MINGW32__) -// const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(wxFNCONV(argv[0])); -// appPath = tmp_buf; -//#else -// appPath = wxFNCONV(argv[0]); -//#endif -// printf("appPath [%s]\n",argv[0]); - - wxString exe_path = wxStandardPaths::Get().GetExecutablePath(); - //wxString path_separator = wxFileName::GetPathSeparator(); - //exe_path = exe_path.BeforeLast(path_separator[0]); - //exe_path += path_separator; - string appPath(static_cast(WX2CHR(exe_path))); - -//#else -// appPath = wxFNCONV(exe_path); -//#endif - -// printf("#2 appPath [%s]\n",appPath.c_str()); - - mainWindow= new MainWindow( unitToLoad, - modelPath, - particlePath, - projectileParticlePath, - splashParticlePath, - newAnimValue, - newParticleLoopValue, - newZoomValue, - newXRotValue, - newYRotValue, - appPath); - if(autoScreenShotAndExit == true) { + } + + float newAnimValue = 0.0f; + if (hasCommandArgument(argc, argv, + (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_LOAD_MODEL_ANIMATION_VALUE])) == + true) { + const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_LOAD_MODEL_ANIMATION_VALUE]); + + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, string((const char *)param) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, (const char *)param, &foundParamIndIndex); + } + // printf("foundParamIndIndex = %d\n",foundParamIndIndex); + string value = (const char *)WX2CHR(argv[foundParamIndIndex]); + vector paramPartTokens; + Tokenize(value, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + newAnimValue = strToFloat(paramPartTokens[1]); + printf("newAnimValue = %f\n", newAnimValue); + } else { + printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", + (const char *)WX2CHR(argv[foundParamIndIndex]), + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + printParameterHelp(WX2CHR(argv[0]), false); + return false; + } + } + + int newParticleLoopValue = 1; + if (hasCommandArgument(argc, argv, + (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_LOAD_PARTICLE_LOOP_VALUE])) == + true) { + const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_LOAD_PARTICLE_LOOP_VALUE]); + + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, string((const char *)param) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, (const char *)param, &foundParamIndIndex); + } + // printf("foundParamIndIndex = %d\n",foundParamIndIndex); + string value = (const char *)WX2CHR(argv[foundParamIndIndex]); + vector paramPartTokens; + Tokenize(value, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + newParticleLoopValue = strToInt(paramPartTokens[1]); + // printf("newParticleLoopValue = %d\n",newParticleLoopValue); + } else { + printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", + (const char *)WX2CHR(argv[foundParamIndIndex]), + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + printParameterHelp(WX2CHR(argv[0]), false); + return false; + } + } + + float newZoomValue = 1.0f; + if (hasCommandArgument(argc, argv, + (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_ZOOM_VALUE])) == true) { + const wxWX2MBbuf param = + (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ZOOM_VALUE]); + + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, string((const char *)param) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, (const char *)param, &foundParamIndIndex); + } + // printf("foundParamIndIndex = %d\n",foundParamIndIndex); + string value = (const char *)WX2CHR(argv[foundParamIndIndex]); + vector paramPartTokens; + Tokenize(value, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + newZoomValue = strToFloat(paramPartTokens[1]); + // printf("newAnimValue = %f\n",newAnimValue); + } else { + printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", + (const char *)WX2CHR(argv[foundParamIndIndex]), + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + printParameterHelp(WX2CHR(argv[0]), false); + return false; + } + } + + float newXRotValue = 0.0f; + if (hasCommandArgument(argc, argv, + (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_ROTATE_X_VALUE])) == true) { + const wxWX2MBbuf param = + (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_X_VALUE]); + + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, string((const char *)param) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, (const char *)param, &foundParamIndIndex); + } + // printf("foundParamIndIndex = %d\n",foundParamIndIndex); + string value = (const char *)WX2CHR(argv[foundParamIndIndex]); + vector paramPartTokens; + Tokenize(value, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + newXRotValue = strToFloat(paramPartTokens[1]); + // printf("newAnimValue = %f\n",newAnimValue); + } else { + printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", + (const char *)WX2CHR(argv[foundParamIndIndex]), + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + printParameterHelp(WX2CHR(argv[0]), false); + return false; + } + } + + float newYRotValue = 0.0f; + if (hasCommandArgument(argc, argv, + (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_ROTATE_Y_VALUE])) == true) { + const wxWX2MBbuf param = + (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_Y_VALUE]); + + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, string((const char *)param) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, (const char *)param, &foundParamIndIndex); + } + // printf("foundParamIndIndex = %d\n",foundParamIndIndex); + string value = static_cast(WX2CHR(argv[foundParamIndIndex])); + vector paramPartTokens; + Tokenize(value, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + newYRotValue = strToFloat(paramPartTokens[1]); + // printf("newAnimValue = %f\n",newAnimValue); + } else { + printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", + static_cast(WX2CHR(argv[foundParamIndIndex])), + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + printParameterHelp(WX2CHR(argv[0]), false); + return false; + } + } + + if (hasCommandArgument(argc, argv, + (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_SCREENSHOT_FORMAT])) == true) { + const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB( + GAME_ARGS[GAME_ARG_SCREENSHOT_FORMAT]); + + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, string((const char *)param) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, (const char *)param, &foundParamIndIndex); + } + // printf("foundParamIndIndex = %d\n",foundParamIndIndex); + string value = static_cast(WX2CHR(argv[foundParamIndIndex])); + vector paramPartTokens; + Tokenize(value, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + fileFormat = paramPartTokens[1]; + } else { + printf("\nInvalid value specified on commandline [%s] value [%s]\n\n", + static_cast(WX2CHR(argv[foundParamIndIndex])), + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + printParameterHelp(WX2CHR(argv[0]), false); + return false; + } + } + + if (argc == 2 && argv[1][0] != '-') { + modelPath = static_cast(WX2CHR(argv[1])); + } + + // #if defined(__MINGW32__) + // const wxWX2MBbuf tmp_buf = + // wxConvCurrent->cWX2MB(wxFNCONV(argv[0])); appPath = tmp_buf; #else + // appPath = wxFNCONV(argv[0]); #endif printf("appPath + // [%s]\n",argv[0]); + + wxString exe_path = wxStandardPaths::Get().GetExecutablePath(); + // wxString path_separator = wxFileName::GetPathSeparator(); + // exe_path = exe_path.BeforeLast(path_separator[0]); + // exe_path += path_separator; + string appPath(static_cast(WX2CHR(exe_path))); + + // #else + // appPath = wxFNCONV(exe_path); + // #endif + + // printf("#2 appPath [%s]\n",appPath.c_str()); + + mainWindow = new MainWindow(unitToLoad, modelPath, particlePath, + projectileParticlePath, splashParticlePath, + newAnimValue, newParticleLoopValue, newZoomValue, + newXRotValue, newYRotValue, appPath); + if (autoScreenShotAndExit == true) { #if !defined(WIN32) - mainWindow->Iconize(true); -#endif - } - mainWindow->Show(); - mainWindow->init(); - mainWindow->Update(); - mainWindow->setupTimer(); - - return true; + mainWindow->Iconize(true); +#endif + } + mainWindow->Show(); + mainWindow->init(); + mainWindow->Update(); + mainWindow->setupTimer(); + + return true; } -int App::MainLoop(){ - try{ - return wxApp::MainLoop(); - } - catch(const exception &e){ - wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Exception"), wxOK | wxICON_ERROR).ShowModal(); - return 1; - } - return 0; +int App::MainLoop() { + try { + return wxApp::MainLoop(); + } catch (const exception &e) { + wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Exception"), + wxOK | wxICON_ERROR) + .ShowModal(); + return 1; + } + return 0; } -int App::OnExit(){ - SystemFlags::Close(); - SystemFlags::SHUTDOWN_PROGRAM_MODE=true; +int App::OnExit() { + SystemFlags::Close(); + SystemFlags::SHUTDOWN_PROGRAM_MODE = true; - return 0; + return 0; } -}}//end namespace +} // namespace G3dViewer +} // namespace Shared IMPLEMENT_APP_CONSOLE(Shared::G3dViewer::App) diff --git a/source/g3d_viewer/main.h b/source/g3d_viewer/main.h index 16f591678..4bd309a63 100644 --- a/source/g3d_viewer/main.h +++ b/source/g3d_viewer/main.h @@ -13,26 +13,27 @@ #define _SHADER_G3DVIEWER_MAIN_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include #include -#include +#include #include -//#include +#include +// #include #include -#include "renderer.h" -#include "util.h" #include "particle_type.h" +#include "renderer.h" #include "unit_particle_type.h" +#include "util.h" using std::string; using namespace Glest::Game; -namespace Shared{ namespace G3dViewer{ +namespace Shared { +namespace G3dViewer { class GlCanvas; @@ -40,197 +41,196 @@ class GlCanvas; // class MainWindow // =============================== -class MainWindow: public wxFrame{ +class MainWindow : public wxFrame { private: - DECLARE_EVENT_TABLE() + DECLARE_EVENT_TABLE() public: - static const string versionString; - static const string winHeader; - - enum MenuId{ - miFileLoad, - miFileLoadParticleXML, - miFileLoadProjectileParticleXML, - miFileLoadSplashParticleXML, - miFileClearAll, - miFileToggleScreenshotTransparent, - miFileSaveScreenshot, - miModeWireframe, - miModeNormals, - miModeGrid, - miSpeedSlower, - miSpeedFaster, - miRestart, - miChangeBackgroundColor, - miColorRed, - miColorBlue, - miColorGreen, - miColorYellow, - miColorWhite, - miColorCyan, - miColorOrange, - miColorMagenta - }; + static const string versionString; + static const string winHeader; + + enum MenuId { + miFileLoad, + miFileLoadParticleXML, + miFileLoadProjectileParticleXML, + miFileLoadSplashParticleXML, + miFileClearAll, + miFileToggleScreenshotTransparent, + miFileSaveScreenshot, + miModeWireframe, + miModeNormals, + miModeGrid, + miSpeedSlower, + miSpeedFaster, + miRestart, + miChangeBackgroundColor, + miColorRed, + miColorBlue, + miColorGreen, + miColorYellow, + miColorWhite, + miColorCyan, + miColorOrange, + miColorMagenta + }; private: - GlCanvas *glCanvas; - Renderer *renderer; + GlCanvas *glCanvas; + Renderer *renderer; - wxTimer *timer; + wxTimer *timer; - wxMenuBar *menu; - wxMenu *menuFile; - wxMenu *menuMode; - wxMenu *menuSpeed; - wxMenu *menuCustomColor; - wxFileDialog *fileDialog; + wxMenuBar *menu; + wxMenu *menuFile; + wxMenu *menuMode; + wxMenu *menuSpeed; + wxMenu *menuCustomColor; + wxFileDialog *fileDialog; - wxColourDialog *colorPicker; + wxColourDialog *colorPicker; - Model *model; + Model *model; - std::pair > unitPath; - std::vector modelPathList; - std::vector particlePathList; - std::vector particleProjectilePathList; - std::vector particleSplashPathList; // as above + std::pair> unitPath; + std::vector modelPathList; + std::vector particlePathList; + std::vector particleProjectilePathList; + std::vector particleSplashPathList; // as above - bool resetAnimation; - float resetAnim; - int resetParticleLoopStart; + bool resetAnimation; + float resetAnim; + int resetParticleLoopStart; - float speed; - float anim; - float lastanim; - int particleLoopStart; - float rotX, rotY, zoom; - float backBrightness, gridBrightness, lightBrightness; - int lastX, lastY; - Renderer::PlayerColor playerColor; - bool initTextureManager; + float speed; + float anim; + float lastanim; + int particleLoopStart; + float rotX, rotY, zoom; + float backBrightness, gridBrightness, lightBrightness; + int lastX, lastY; + Renderer::PlayerColor playerColor; + bool initTextureManager; - std::vector unitParticleSystemTypes; - std::vector unitParticleSystems; + std::vector unitParticleSystemTypes; + std::vector unitParticleSystems; - std::vector projectileParticleSystemTypes; - std::vector projectileParticleSystems; - std::vector splashParticleSystemTypes; // as above - std::vector splashParticleSystems; - string statusbarText; + std::vector projectileParticleSystemTypes; + std::vector projectileParticleSystems; + std::vector splashParticleSystemTypes; // as above + std::vector splashParticleSystems; + string statusbarText; - bool isControlKeyPressed; + bool isControlKeyPressed; - string appPath; + string appPath; - bool startupSettingsInited; + bool startupSettingsInited; - void initGlCanvas(); - void loadUnit(string path, string skillName); - void loadModel(string path); - void loadParticle(string path); - void loadProjectileParticle(string path); - void loadSplashParticle(string path); + void initGlCanvas(); + void loadUnit(string path, string skillName); + void loadModel(string path); + void loadParticle(string path); + void loadProjectileParticle(string path); + void loadSplashParticle(string path); - void saveScreenshot(); + void saveScreenshot(); public: - MainWindow( std::pair > unitToLoad, - const string modelPath,const string particlePath, - const string projectileParticlePath,const string splashParticlePath, - float defaultAnimation,int defaultParticleLoopStart, - float defaultZoom,float defaultXRot, float defaultYRot, - string appPath); - ~MainWindow(); - void init(); - - void Notify(); - - void onPaintNoEvent(); - void onPaint(wxPaintEvent &event); - void onClose(wxCloseEvent &event); - void onMenuFileLoad(wxCommandEvent &event); - void onMenuFileLoadParticleXML(wxCommandEvent &event); - void onMenuFileLoadProjectileParticleXML(wxCommandEvent &event); - void onMenuFileLoadSplashParticleXML(wxCommandEvent &event); - void onMenuFileClearAll(wxCommandEvent &event); - void onMenumFileToggleScreenshotTransparent(wxCommandEvent &event); - void onMenuFileSaveScreenshot(wxCommandEvent &event); - void onMenuFileExit(wxCommandEvent &event); - void onMenuModeNormals(wxCommandEvent &event); - void onMenuModeWireframe(wxCommandEvent &event); - void onMenuModeGrid(wxCommandEvent &event); - void onMenuSpeedSlower(wxCommandEvent &event); - void onMenuSpeedFaster(wxCommandEvent &event); - void onMenuRestart(wxCommandEvent &event); - void onMenuRestartNoEvent(); - void OnChangeColor(wxCommandEvent &event); - void onMenuColorRed(wxCommandEvent &event); - void onMenuColorBlue(wxCommandEvent &event); - void onMenuColorGreen(wxCommandEvent &event); - void onMenuColorYellow(wxCommandEvent &event); - void onMenuColorWhite(wxCommandEvent &event); - void onMenuColorCyan(wxCommandEvent &event); - void onMenuColorOrange(wxCommandEvent &event); - void onMenuColorMagenta(wxCommandEvent &event); - void onMouseWheelDown(wxMouseEvent &event); - void onMouseWheelUp(wxMouseEvent &event); - void onMouseMove(wxMouseEvent &event); - void onTimer(wxTimerEvent &event); - - void onKeyDown(wxKeyEvent &e); - - string getModelInfo(); - - void setupTimer(); - void setupStartupSettings(); + MainWindow(std::pair> unitToLoad, + const string modelPath, const string particlePath, + const string projectileParticlePath, + const string splashParticlePath, float defaultAnimation, + int defaultParticleLoopStart, float defaultZoom, float defaultXRot, + float defaultYRot, string appPath); + ~MainWindow(); + void init(); + + void Notify(); + + void onPaintNoEvent(); + void onPaint(wxPaintEvent &event); + void onClose(wxCloseEvent &event); + void onMenuFileLoad(wxCommandEvent &event); + void onMenuFileLoadParticleXML(wxCommandEvent &event); + void onMenuFileLoadProjectileParticleXML(wxCommandEvent &event); + void onMenuFileLoadSplashParticleXML(wxCommandEvent &event); + void onMenuFileClearAll(wxCommandEvent &event); + void onMenumFileToggleScreenshotTransparent(wxCommandEvent &event); + void onMenuFileSaveScreenshot(wxCommandEvent &event); + void onMenuFileExit(wxCommandEvent &event); + void onMenuModeNormals(wxCommandEvent &event); + void onMenuModeWireframe(wxCommandEvent &event); + void onMenuModeGrid(wxCommandEvent &event); + void onMenuSpeedSlower(wxCommandEvent &event); + void onMenuSpeedFaster(wxCommandEvent &event); + void onMenuRestart(wxCommandEvent &event); + void onMenuRestartNoEvent(); + void OnChangeColor(wxCommandEvent &event); + void onMenuColorRed(wxCommandEvent &event); + void onMenuColorBlue(wxCommandEvent &event); + void onMenuColorGreen(wxCommandEvent &event); + void onMenuColorYellow(wxCommandEvent &event); + void onMenuColorWhite(wxCommandEvent &event); + void onMenuColorCyan(wxCommandEvent &event); + void onMenuColorOrange(wxCommandEvent &event); + void onMenuColorMagenta(wxCommandEvent &event); + void onMouseWheelDown(wxMouseEvent &event); + void onMouseWheelUp(wxMouseEvent &event); + void onMouseMove(wxMouseEvent &event); + void onTimer(wxTimerEvent &event); + + void onKeyDown(wxKeyEvent &e); + + string getModelInfo(); + + void setupTimer(); + void setupStartupSettings(); }; // ===================================================== // class GlCanvas // ===================================================== -class GlCanvas: public wxGLCanvas { +class GlCanvas : public wxGLCanvas { private: - DECLARE_EVENT_TABLE() + DECLARE_EVENT_TABLE() public: - GlCanvas(MainWindow *mainWindow, int *args); - ~GlCanvas(); + GlCanvas(MainWindow *mainWindow, int *args); + ~GlCanvas(); - void onMouseWheel(wxMouseEvent &event); - void onMouseMove(wxMouseEvent &event); - void onPaint(wxPaintEvent &event); - void onKeyDown(wxKeyEvent &event); - void OnSize(wxSizeEvent&); - void setCurrentGLContext(); + void onMouseWheel(wxMouseEvent &event); + void onMouseMove(wxMouseEvent &event); + void onPaint(wxPaintEvent &event); + void onKeyDown(wxKeyEvent &event); + void OnSize(wxSizeEvent &); + void setCurrentGLContext(); + + wxGLContext *getCtx() { return context; } - wxGLContext * getCtx() { return context; } private: - MainWindow *mainWindow; - wxGLContext *context; + MainWindow *mainWindow; + wxGLContext *context; }; - // =============================== // class App // =============================== -class App: public wxApp{ +class App : public wxApp { private: - MainWindow *mainWindow; + MainWindow *mainWindow; public: - App() : wxApp() { - mainWindow = NULL; - } - virtual ~App() {} - virtual bool OnInit(); - virtual int MainLoop(); - virtual int OnExit(); + App() : wxApp() { mainWindow = NULL; } + virtual ~App() {} + virtual bool OnInit(); + virtual int MainLoop(); + virtual int OnExit(); }; -}}//end namespace +} // namespace G3dViewer +} // namespace Shared DECLARE_APP(Shared::G3dViewer::App) diff --git a/source/g3d_viewer/renderer.cpp b/source/g3d_viewer/renderer.cpp index fb9673dc1..2534f3a51 100644 --- a/source/g3d_viewer/renderer.cpp +++ b/source/g3d_viewer/renderer.cpp @@ -11,81 +11,82 @@ #include "renderer.h" +#include "config.h" #include "graphics_factory_gl.h" #include "graphics_interface.h" -#include "config.h" #include "platform_common.h" -//#include +// #include using namespace Shared::Graphics; using namespace Shared::Graphics::Gl; using namespace Glest::Game; using namespace Shared::Util; -namespace Shared{ namespace G3dViewer{ +namespace Shared { +namespace G3dViewer { -int Renderer::windowX= 100; -int Renderer::windowY= 100; -int Renderer::windowW= 640; -int Renderer::windowH= 480; +int Renderer::windowX = 100; +int Renderer::windowY = 100; +int Renderer::windowW = 640; +int Renderer::windowH = 480; // =============================================== // class MeshCallbackTeamColor // =============================================== -void MeshCallbackTeamColor::execute(const Mesh *mesh){ +void MeshCallbackTeamColor::execute(const Mesh *mesh) { - //team color - if(mesh->getCustomTexture() && teamTexture!=NULL){ - //texture 0 - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); + // team color + if (mesh->getCustomTexture() && teamTexture != NULL) { + // texture 0 + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); - //set color to interpolation - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_INTERPOLATE); + // set color to interpolation + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_INTERPOLATE); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_TEXTURE); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_TEXTURE); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_TEXTURE1); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_TEXTURE1); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB, GL_TEXTURE); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_ALPHA); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB, GL_TEXTURE); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_ALPHA); - //set alpha to 1 - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_TEXTURE); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA); + // set alpha to 1 + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_TEXTURE); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA); - //texture 1 - glActiveTexture(GL_TEXTURE1); - glMultiTexCoord2f(GL_TEXTURE1, 0.f, 0.f); - glEnable(GL_TEXTURE_2D); + // texture 1 + glActiveTexture(GL_TEXTURE1); + glMultiTexCoord2f(GL_TEXTURE1, 0.f, 0.f); + glEnable(GL_TEXTURE_2D); - glBindTexture(GL_TEXTURE_2D, static_cast(teamTexture)->getHandle()); - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); + glBindTexture(GL_TEXTURE_2D, + static_cast(teamTexture)->getHandle()); + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE); + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PRIMARY_COLOR); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PRIMARY_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_PREVIOUS); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_PREVIOUS); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR); - //set alpha to 1 - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_PRIMARY_COLOR); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA); + // set alpha to 1 + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_PRIMARY_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA); - glActiveTexture(GL_TEXTURE0); - } - else{ - glActiveTexture(GL_TEXTURE1); - glDisable(GL_TEXTURE_2D); - glActiveTexture(GL_TEXTURE0); - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - } + glActiveTexture(GL_TEXTURE0); + } else { + glActiveTexture(GL_TEXTURE1); + glDisable(GL_TEXTURE_2D); + glActiveTexture(GL_TEXTURE0); + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + } } // =============================================== @@ -93,463 +94,471 @@ void MeshCallbackTeamColor::execute(const Mesh *mesh){ // =============================================== Renderer::Renderer() { - normals= false; - wireframe= false; - grid= true; - modelRenderer = NULL; - textureManager = NULL; - particleRenderer = NULL; - modelManager = NULL; - width=0; - height=0; - red = 0.3f; - green = 0.3f; - blue = 0.3f; - alpha = 1.0f; - - customTextureRed=NULL; - customTextureBlue=NULL; - customTextureGreen=NULL; - customTextureYellow=NULL; - customTextureWhite=NULL; - customTextureCyan=NULL; - customTextureOrange=NULL; - customTextureMagenta=NULL; - particleManager=NULL; + normals = false; + wireframe = false; + grid = true; + modelRenderer = NULL; + textureManager = NULL; + particleRenderer = NULL; + modelManager = NULL; + width = 0; + height = 0; + red = 0.3f; + green = 0.3f; + blue = 0.3f; + alpha = 1.0f; + + customTextureRed = NULL; + customTextureBlue = NULL; + customTextureGreen = NULL; + customTextureYellow = NULL; + customTextureWhite = NULL; + customTextureCyan = NULL; + customTextureOrange = NULL; + customTextureMagenta = NULL; + particleManager = NULL; } Renderer::~Renderer() { - delete modelRenderer; - delete textureManager; - delete particleRenderer; - - //resources - delete particleManager; - delete modelManager; - - if(GraphicsInterface::getInstance().getFactory() != NULL) { - delete GraphicsInterface::getInstance().getFactory(); - GraphicsInterface::getInstance().setFactory(NULL); - } + delete modelRenderer; + delete textureManager; + delete particleRenderer; + + // resources + delete particleManager; + delete modelManager; + + if (GraphicsInterface::getInstance().getFactory() != NULL) { + delete GraphicsInterface::getInstance().getFactory(); + GraphicsInterface::getInstance().setFactory(NULL); + } } -Renderer * Renderer::getInstance() { - static Renderer * renderer = new Renderer(); - return renderer; +Renderer *Renderer::getInstance() { + static Renderer *renderer = new Renderer(); + return renderer; } void Renderer::transform(float rotX, float rotY, float zoom) { - assertGl(); + assertGl(); - glMatrixMode(GL_MODELVIEW); - glRotatef(rotY, 1.0f, 0.0f, 0.0f); - glRotatef(rotX, 0.0f, 1.0f, 0.0f); - glScalef(zoom, zoom, zoom); - Vec4f pos(-8.0f, 5.0f, 10.0f, 0.0f); - glLightfv(GL_LIGHT0,GL_POSITION, pos.ptr()); + glMatrixMode(GL_MODELVIEW); + glRotatef(rotY, 1.0f, 0.0f, 0.0f); + glRotatef(rotX, 0.0f, 1.0f, 0.0f); + glScalef(zoom, zoom, zoom); + Vec4f pos(-8.0f, 5.0f, 10.0f, 0.0f); + glLightfv(GL_LIGHT0, GL_POSITION, pos.ptr()); - assertGl(); + assertGl(); } void Renderer::checkGlCaps() { - if(glActiveTexture == NULL) { - string message; - - message += "Your system supports OpenGL version \""; - message += getGlVersion() + string("\"\n"); - message += "MegaGlest needs a version that supports\n"; - message += "glActiveTexture (OpenGL 1.3) or the ARB_multitexture extension."; - - throw megaglest_runtime_error(message.c_str()); - } - - //opengl 1.3 - //if(!isGlVersionSupported(1, 3, 0)) { - if(glewIsSupported("GL_VERSION_1_3") == false) { - string message; - - message += "Your system supports OpenGL version \""; - message += getGlVersion() + string("\"\n"); - message += "MegaGlest needs at least version 1.3 to work\n"; - message += "You may solve this problem by installing your latest video card drivers"; - - throw megaglest_runtime_error(message.c_str()); - } - - //opengl 1.4 or extension - //if(isGlVersionSupported(1, 4, 0) == false) { - if(glewIsSupported("GL_VERSION_1_4") == false) { - checkExtension("GL_ARB_texture_env_crossbar", "MegaGlest"); - } + if (glActiveTexture == NULL) { + string message; + + message += "Your system supports OpenGL version \""; + message += getGlVersion() + string("\"\n"); + message += "MegaGlest needs a version that supports\n"; + message += + "glActiveTexture (OpenGL 1.3) or the ARB_multitexture extension."; + + throw megaglest_runtime_error(message.c_str()); + } + + // opengl 1.3 + // if(!isGlVersionSupported(1, 3, 0)) { + if (glewIsSupported("GL_VERSION_1_3") == false) { + string message; + + message += "Your system supports OpenGL version \""; + message += getGlVersion() + string("\"\n"); + message += "MegaGlest needs at least version 1.3 to work\n"; + message += "You may solve this problem by installing your latest video " + "card drivers"; + + throw megaglest_runtime_error(message.c_str()); + } + + // opengl 1.4 or extension + // if(isGlVersionSupported(1, 4, 0) == false) { + if (glewIsSupported("GL_VERSION_1_4") == false) { + checkExtension("GL_ARB_texture_env_crossbar", "MegaGlest"); + } } void Renderer::checkExtension(const string &extension, const string &msg) { - if(isGlExtensionSupported(extension.c_str()) == false) { - string str= "OpenGL extension not supported: " + extension + ", required for " + msg; - throw megaglest_runtime_error(str); - } + if (isGlExtensionSupported(extension.c_str()) == false) { + string str = "OpenGL extension not supported: " + extension + + ", required for " + msg; + throw megaglest_runtime_error(str); + } } -Texture2D * Renderer::getNewTexture2D() { - Texture2D *newTexture = textureManager->newTexture2D(); - return newTexture; +Texture2D *Renderer::getNewTexture2D() { + Texture2D *newTexture = textureManager->newTexture2D(); + return newTexture; } -Model * Renderer::newModel(ResourceScope rs,const string &path,bool deletePixMapAfterLoad,std::map > > *loadedFileList, string *sourceLoader) { - return modelManager->newModel(path,deletePixMapAfterLoad,loadedFileList,sourceLoader); +Model *Renderer::newModel( + ResourceScope rs, const string &path, bool deletePixMapAfterLoad, + std::map>> *loadedFileList, + string *sourceLoader) { + return modelManager->newModel(path, deletePixMapAfterLoad, loadedFileList, + sourceLoader); } -void Renderer::endModel(ResourceScope rs,Model *model) { - modelManager->endModel(model); +void Renderer::endModel(ResourceScope rs, Model *model) { + modelManager->endModel(model); } void Renderer::init() { - assertGl(); - - GraphicsFactory *gf= GraphicsInterface::getInstance().getFactory(); - if(gf == NULL) { - gf= new GraphicsFactoryGl(); - GraphicsInterface::getInstance().setFactory(gf); - } - - Config &config = Config::getInstance(); - if(config.getBool("CheckGlCaps")){ - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - checkGlCaps(); - } - - if(glActiveTexture == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Error: glActiveTexture == NULL\nglActiveTexture is only supported if the GL version is 1.3 or greater,\nor if the ARB_multitexture extension is supported!"); - throw megaglest_runtime_error(szBuf); - } - - modelRenderer= gf->newModelRenderer(); - textureManager= gf->newTextureManager(); - particleRenderer= gf->newParticleRenderer(); - - //resources - particleManager= gf->newParticleManager(); - - modelManager = gf->newModelManager(); - modelManager->setTextureManager(textureManager); - - //red tex - customTextureRed= textureManager->newTexture2D(); - customTextureRed->getPixmap()->init(1, 1, 3); - customTextureRed->getPixmap()->setPixel(0, 0, Vec3f(1.f, 0.f, 0.f)); - - //blue tex - customTextureBlue= textureManager->newTexture2D(); - customTextureBlue->getPixmap()->init(1, 1, 3); - customTextureBlue->getPixmap()->setPixel(0, 0, Vec3f(0.f, 0.f, 1.f)); - - //green tex - customTextureGreen= textureManager->newTexture2D(); - customTextureGreen->getPixmap()->init(1, 1, 3); - customTextureGreen->getPixmap()->setPixel(0, 0, Vec3f(0.f, 0.5f, 0.f)); - - //yellow tex - customTextureYellow= textureManager->newTexture2D(); - customTextureYellow->getPixmap()->init(1, 1, 3); - customTextureYellow->getPixmap()->setPixel(0, 0, Vec3f(1.f, 1.f, 0.f)); - - //white tex - customTextureWhite= textureManager->newTexture2D(); - customTextureWhite->getPixmap()->init(1, 1, 3); - customTextureWhite->getPixmap()->setPixel(0, 0, Vec3f(1.f, 1.f, 1.f)); - - //cyan tex - customTextureCyan= textureManager->newTexture2D(); - customTextureCyan->getPixmap()->init(1, 1, 3); - customTextureCyan->getPixmap()->setPixel(0, 0, Vec3f(0.f, 1.f, 0.8f)); - - //orange tex - customTextureOrange= textureManager->newTexture2D(); - customTextureOrange->getPixmap()->init(1, 1, 3); - customTextureOrange->getPixmap()->setPixel(0, 0, Vec3f(1.f, 0.5f, 0.f)); - - //magenta tex - customTextureMagenta= textureManager->newTexture2D(); - customTextureMagenta->getPixmap()->init(1, 1, 3); - customTextureMagenta->getPixmap()->setPixel(0, 0, Vec3f(1.f, 0.5f, 1.f)); - - glClearColor(red, green, blue, alpha); //backgroundcolor constant 0.3 - //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - - /* once the GL context is valid : */ - //GLint alpha_bits; - //glGetIntegerv(GL_ALPHA_BITS, &alpha_bits); - //printf("#1 The framebuffer uses %d bit(s) per the alpha component\n", alpha_bits); - - glEnable(GL_TEXTURE_2D); - glFrontFace(GL_CW); - glEnable(GL_CULL_FACE); - glEnable(GL_DEPTH_TEST); - glEnable(GL_ALPHA_TEST); - //glAlphaFunc(GL_GREATER, 0.5f); - glAlphaFunc(GL_GREATER, 0.0f); - glEnable(GL_LIGHTING); - glEnable(GL_LIGHT0); - - Vec4f diffuse= Vec4f(1.0f, 1.0f, 1.0f, 1.0f); - Vec4f ambient= Vec4f(0.3f, 0.3f, 0.3f, 1.0f); - Vec4f specular= Vec4f(0.1f, 0.1f, 0.1f, 1.0f); - - glLightfv(GL_LIGHT0,GL_AMBIENT, ambient.ptr()); - glLightfv(GL_LIGHT0,GL_DIFFUSE, diffuse.ptr()); - glLightfv(GL_LIGHT0,GL_SPECULAR, specular.ptr()); - - glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); - glEnable(GL_COLOR_MATERIAL); - - assertGl(); + assertGl(); + + GraphicsFactory *gf = GraphicsInterface::getInstance().getFactory(); + if (gf == NULL) { + gf = new GraphicsFactoryGl(); + GraphicsInterface::getInstance().setFactory(gf); + } + + Config &config = Config::getInstance(); + if (config.getBool("CheckGlCaps")) { + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + checkGlCaps(); + } + + if (glActiveTexture == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "Error: glActiveTexture == NULL\nglActiveTexture is only " + "supported if the GL version is 1.3 or greater,\nor if the " + "ARB_multitexture extension is supported!"); + throw megaglest_runtime_error(szBuf); + } + + modelRenderer = gf->newModelRenderer(); + textureManager = gf->newTextureManager(); + particleRenderer = gf->newParticleRenderer(); + + // resources + particleManager = gf->newParticleManager(); + + modelManager = gf->newModelManager(); + modelManager->setTextureManager(textureManager); + + // red tex + customTextureRed = textureManager->newTexture2D(); + customTextureRed->getPixmap()->init(1, 1, 3); + customTextureRed->getPixmap()->setPixel(0, 0, Vec3f(1.f, 0.f, 0.f)); + + // blue tex + customTextureBlue = textureManager->newTexture2D(); + customTextureBlue->getPixmap()->init(1, 1, 3); + customTextureBlue->getPixmap()->setPixel(0, 0, Vec3f(0.f, 0.f, 1.f)); + + // green tex + customTextureGreen = textureManager->newTexture2D(); + customTextureGreen->getPixmap()->init(1, 1, 3); + customTextureGreen->getPixmap()->setPixel(0, 0, Vec3f(0.f, 0.5f, 0.f)); + + // yellow tex + customTextureYellow = textureManager->newTexture2D(); + customTextureYellow->getPixmap()->init(1, 1, 3); + customTextureYellow->getPixmap()->setPixel(0, 0, Vec3f(1.f, 1.f, 0.f)); + + // white tex + customTextureWhite = textureManager->newTexture2D(); + customTextureWhite->getPixmap()->init(1, 1, 3); + customTextureWhite->getPixmap()->setPixel(0, 0, Vec3f(1.f, 1.f, 1.f)); + + // cyan tex + customTextureCyan = textureManager->newTexture2D(); + customTextureCyan->getPixmap()->init(1, 1, 3); + customTextureCyan->getPixmap()->setPixel(0, 0, Vec3f(0.f, 1.f, 0.8f)); + + // orange tex + customTextureOrange = textureManager->newTexture2D(); + customTextureOrange->getPixmap()->init(1, 1, 3); + customTextureOrange->getPixmap()->setPixel(0, 0, Vec3f(1.f, 0.5f, 0.f)); + + // magenta tex + customTextureMagenta = textureManager->newTexture2D(); + customTextureMagenta->getPixmap()->init(1, 1, 3); + customTextureMagenta->getPixmap()->setPixel(0, 0, Vec3f(1.f, 0.5f, 1.f)); + + glClearColor(red, green, blue, alpha); // backgroundcolor constant 0.3 + // glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + /* once the GL context is valid : */ + // GLint alpha_bits; + // glGetIntegerv(GL_ALPHA_BITS, &alpha_bits); + // printf("#1 The framebuffer uses %d bit(s) per the alpha component\n", + // alpha_bits); + + glEnable(GL_TEXTURE_2D); + glFrontFace(GL_CW); + glEnable(GL_CULL_FACE); + glEnable(GL_DEPTH_TEST); + glEnable(GL_ALPHA_TEST); + // glAlphaFunc(GL_GREATER, 0.5f); + glAlphaFunc(GL_GREATER, 0.0f); + glEnable(GL_LIGHTING); + glEnable(GL_LIGHT0); + + Vec4f diffuse = Vec4f(1.0f, 1.0f, 1.0f, 1.0f); + Vec4f ambient = Vec4f(0.3f, 0.3f, 0.3f, 1.0f); + Vec4f specular = Vec4f(0.1f, 0.1f, 0.1f, 1.0f); + + glLightfv(GL_LIGHT0, GL_AMBIENT, ambient.ptr()); + glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse.ptr()); + glLightfv(GL_LIGHT0, GL_SPECULAR, specular.ptr()); + + glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); + glEnable(GL_COLOR_MATERIAL); + + assertGl(); } void Renderer::reset(int w, int h, PlayerColor playerColor) { - assertGl(); - - width=w; - height=h; - - //glClearColor(red, green, blue, alpha); //backgroundcolor constant 0.3 - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - - /* once the GL context is valid : */ - //GLint alpha_bits; - //glGetIntegerv(GL_ALPHA_BITS, &alpha_bits); - //printf("#2 The framebuffer uses %d bit(s) per the alpha component\n", alpha_bits); - - glViewport(0, 0, w, h); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - gluPerspective(60.0f, static_cast(w)/h, 1.0f, 200.0f); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - glTranslatef(0, -1.5, -5); - - Texture2D *customTexture=NULL; - switch(playerColor) { - case pcRed: - customTexture= customTextureRed; - break; - case pcBlue: - customTexture= customTextureBlue; - break; - case pcGreen: - customTexture= customTextureGreen; - break; - case pcYellow: - customTexture= customTextureYellow; - break; - case pcWhite: - customTexture= customTextureWhite; - break; - case pcCyan: - customTexture= customTextureCyan; - break; - case pcOrange: - customTexture= customTextureOrange; - break; - case pcMagenta: - customTexture= customTextureMagenta; - break; - default: - assert(false); - break; - } - meshCallbackTeamColor.setTeamTexture(customTexture); - - if(wireframe) { - glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); - glDisable(GL_TEXTURE_2D); - glDisable(GL_LIGHTING); - glDisable(GL_LIGHT0); - } - else { - glEnable(GL_TEXTURE_2D); - glEnable(GL_LIGHTING); - glEnable(GL_LIGHT0); - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); - } - - assertGl(); + assertGl(); + + width = w; + height = h; + + // glClearColor(red, green, blue, alpha); //backgroundcolor constant 0.3 + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + /* once the GL context is valid : */ + // GLint alpha_bits; + // glGetIntegerv(GL_ALPHA_BITS, &alpha_bits); + // printf("#2 The framebuffer uses %d bit(s) per the alpha component\n", + // alpha_bits); + + glViewport(0, 0, w, h); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + gluPerspective(60.0f, static_cast(w) / h, 1.0f, 200.0f); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glTranslatef(0, -1.5, -5); + + Texture2D *customTexture = NULL; + switch (playerColor) { + case pcRed: + customTexture = customTextureRed; + break; + case pcBlue: + customTexture = customTextureBlue; + break; + case pcGreen: + customTexture = customTextureGreen; + break; + case pcYellow: + customTexture = customTextureYellow; + break; + case pcWhite: + customTexture = customTextureWhite; + break; + case pcCyan: + customTexture = customTextureCyan; + break; + case pcOrange: + customTexture = customTextureOrange; + break; + case pcMagenta: + customTexture = customTextureMagenta; + break; + default: + assert(false); + break; + } + meshCallbackTeamColor.setTeamTexture(customTexture); + + if (wireframe) { + glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); + glDisable(GL_TEXTURE_2D); + glDisable(GL_LIGHTING); + glDisable(GL_LIGHT0); + } else { + glEnable(GL_TEXTURE_2D); + glEnable(GL_LIGHTING); + glEnable(GL_LIGHT0); + glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); + } + + assertGl(); } void Renderer::renderGrid() { - if(grid) { - float i=0; - - assertGl(); - - glPushAttrib(GL_ENABLE_BIT); - glDisable(GL_TEXTURE_2D); - glDisable(GL_LIGHTING); - - glBegin(GL_LINES); - glColor3f(1.0f, 1.0f, 1.0f); // gridcolor constant - for(i=-10.0f; i<=10.0f; i+=1.0f) { - glVertex3f(i, 0.0f, 10.0f); - glVertex3f(i, 0.0f, -10.0f); - } - for(i=-10.0f; i<=10.0f; i+=1.0f) { - glVertex3f(10.f, 0.0f, i); - glVertex3f(-10.f, 0.0f, i); - } - glEnd(); - - glPopAttrib(); - - assertGl(); - } + if (grid) { + float i = 0; + + assertGl(); + + glPushAttrib(GL_ENABLE_BIT); + glDisable(GL_TEXTURE_2D); + glDisable(GL_LIGHTING); + + glBegin(GL_LINES); + glColor3f(1.0f, 1.0f, 1.0f); // gridcolor constant + for (i = -10.0f; i <= 10.0f; i += 1.0f) { + glVertex3f(i, 0.0f, 10.0f); + glVertex3f(i, 0.0f, -10.0f); + } + for (i = -10.0f; i <= 10.0f; i += 1.0f) { + glVertex3f(10.f, 0.0f, i); + glVertex3f(-10.f, 0.0f, i); + } + glEnd(); + + glPopAttrib(); + + assertGl(); + } } -void Renderer::toggleNormals() { - normals= normals? false: true; -} +void Renderer::toggleNormals() { normals = normals ? false : true; } -void Renderer::toggleWireframe() { - wireframe= wireframe? false: true; -} +void Renderer::toggleWireframe() { wireframe = wireframe ? false : true; } -void Renderer::toggleGrid() { - grid= grid? false: true; -} +void Renderer::toggleGrid() { grid = grid ? false : true; } void Renderer::renderTheModel(Model *model, float f) { - if(model != NULL){ - modelRenderer->begin(true, true, !wireframe, false, &meshCallbackTeamColor); - model->updateInterpolationData(f, true); - modelRenderer->render(model); - - if(normals) { - glPushAttrib(GL_ENABLE_BIT); - glDisable(GL_LIGHTING); - glDisable(GL_TEXTURE_2D); - glColor3f(1.0f, 1.0f, 1.0f); //normalscolor constant - modelRenderer->renderNormalsOnly(model); - glPopAttrib(); - } - - modelRenderer->end(); - } + if (model != NULL) { + modelRenderer->begin(true, true, !wireframe, false, &meshCallbackTeamColor); + model->updateInterpolationData(f, true); + modelRenderer->render(model); + + if (normals) { + glPushAttrib(GL_ENABLE_BIT); + glDisable(GL_LIGHTING); + glDisable(GL_TEXTURE_2D); + glColor3f(1.0f, 1.0f, 1.0f); // normalscolor constant + modelRenderer->renderNormalsOnly(model); + glPopAttrib(); + } + + modelRenderer->end(); + } } void Renderer::manageParticleSystem(ParticleSystem *particleSystem) { - particleManager->manage(particleSystem); + particleManager->manage(particleSystem); } -void Renderer::updateParticleManager() { - particleManager->update(); -} +void Renderer::updateParticleManager() { particleManager->update(); } -bool Renderer::hasActiveParticleSystem(ParticleSystem::ParticleSystemType type) const { - return particleManager->hasActiveParticleSystem(type); +bool Renderer::hasActiveParticleSystem( + ParticleSystem::ParticleSystemType type) const { + return particleManager->hasActiveParticleSystem(type); } void Renderer::renderParticleManager() { - glPushAttrib(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); - glDepthFunc(GL_LESS); - particleRenderer->renderManager(particleManager, modelRenderer); - glPopAttrib(); + glPushAttrib(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); + glDepthFunc(GL_LESS); + particleRenderer->renderManager(particleManager, modelRenderer); + glPopAttrib(); } -Texture2D * Renderer::getPlayerColorTexture(PlayerColor playerColor) { - Texture2D *customTexture=NULL; - switch(playerColor){ - case pcRed: - customTexture= customTextureRed; - break; - case pcBlue: - customTexture= customTextureBlue; - break; - case pcGreen: - customTexture= customTextureGreen; - break; - case pcYellow: - customTexture= customTextureYellow; - break; - case pcWhite: - customTexture= customTextureWhite; - break; - case pcCyan: - customTexture= customTextureCyan; - break; - case pcOrange: - customTexture= customTextureOrange; - break; - case pcMagenta: - customTexture= customTextureMagenta; - break; - default: - throw megaglest_runtime_error("Unknown playercolor: " + intToStr(playerColor)); - break; - } - - return customTexture; +Texture2D *Renderer::getPlayerColorTexture(PlayerColor playerColor) { + Texture2D *customTexture = NULL; + switch (playerColor) { + case pcRed: + customTexture = customTextureRed; + break; + case pcBlue: + customTexture = customTextureBlue; + break; + case pcGreen: + customTexture = customTextureGreen; + break; + case pcYellow: + customTexture = customTextureYellow; + break; + case pcWhite: + customTexture = customTextureWhite; + break; + case pcCyan: + customTexture = customTextureCyan; + break; + case pcOrange: + customTexture = customTextureOrange; + break; + case pcMagenta: + customTexture = customTextureMagenta; + break; + default: + throw megaglest_runtime_error("Unknown playercolor: " + + intToStr(playerColor)); + break; + } + + return customTexture; } -void Renderer::initTextureManager() { - textureManager->init(); -} +void Renderer::initTextureManager() { textureManager->init(); } -void Renderer::initModelManager() { - modelManager->init(); -} +void Renderer::initModelManager() { modelManager->init(); } void Renderer::end() { - //delete resources - //textureManager->end(); - particleManager->end(); - modelManager->end(); + // delete resources + // textureManager->end(); + particleManager->end(); + modelManager->end(); } void Renderer::setBackgroundColor(float red, float green, float blue) { - this->red = red; - this->green = green; - this->blue = blue; - - glClearColor(red, green, blue, alpha); //backgroundcolor constant 0.3 - //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - - /* once the GL context is valid : */ - //GLint alpha_bits; - //glGetIntegerv(GL_ALPHA_BITS, &alpha_bits); - //printf("#3 The framebuffer uses %d bit(s) per the alpha component\n", alpha_bits); + this->red = red; + this->green = green; + this->blue = blue; + + glClearColor(red, green, blue, alpha); // backgroundcolor constant 0.3 + // glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + /* once the GL context is valid : */ + // GLint alpha_bits; + // glGetIntegerv(GL_ALPHA_BITS, &alpha_bits); + // printf("#3 The framebuffer uses %d bit(s) per the alpha component\n", + // alpha_bits); } void Renderer::setAlphaColor(float alpha) { - this->alpha= alpha; + this->alpha = alpha; - glClearColor(red, green, blue, alpha); //backgroundcolor constant 0.3 - //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glClearColor(red, green, blue, alpha); // backgroundcolor constant 0.3 + // glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - /* once the GL context is valid : */ - //GLint alpha_bits; - //glGetIntegerv(GL_ALPHA_BITS, &alpha_bits); - //printf("#3.1 The framebuffer uses %d bit(s) per the alpha component\n", alpha_bits); + /* once the GL context is valid : */ + // GLint alpha_bits; + // glGetIntegerv(GL_ALPHA_BITS, &alpha_bits); + // printf("#3.1 The framebuffer uses %d bit(s) per the alpha component\n", + // alpha_bits); } -void Renderer::saveScreen(const string &path,std::pair *overrideSize) { - Pixmap2D *pixmapScreenShot = new Pixmap2D(width, height, 4); - //glFinish(); +void Renderer::saveScreen(const string &path, + std::pair *overrideSize) { + Pixmap2D *pixmapScreenShot = new Pixmap2D(width, height, 4); + // glFinish(); - glPixelStorei(GL_PACK_ALIGNMENT, 1); + glPixelStorei(GL_PACK_ALIGNMENT, 1); - glReadPixels(0, 0, pixmapScreenShot->getW(), pixmapScreenShot->getH(), - GL_RGBA, GL_UNSIGNED_BYTE, pixmapScreenShot->getPixels()); + glReadPixels(0, 0, pixmapScreenShot->getW(), pixmapScreenShot->getH(), + GL_RGBA, GL_UNSIGNED_BYTE, pixmapScreenShot->getPixels()); - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - //if(overrideSize != NULL && overrideSize->first > 0 && overrideSize->second > 0) { - // pixmapScreenShot->Scale(GL_RGBA,overrideSize->first,overrideSize->second); - //} + // if(overrideSize != NULL && overrideSize->first > 0 && overrideSize->second + // > 0) { + // pixmapScreenShot->Scale(GL_RGBA,overrideSize->first,overrideSize->second); + // } - pixmapScreenShot->save(path); - delete pixmapScreenShot; + pixmapScreenShot->save(path); + delete pixmapScreenShot; } -}}//end namespace +} // namespace G3dViewer +} // namespace Shared diff --git a/source/g3d_viewer/renderer.h b/source/g3d_viewer/renderer.h index f9a881461..57ec846c1 100644 --- a/source/g3d_viewer/renderer.h +++ b/source/g3d_viewer/renderer.h @@ -13,54 +13,55 @@ #define _SHADER_G3DVIEWER_RENDERER_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include "model_renderer.h" -#include "texture_manager.h" #include "model.h" +#include "model_renderer.h" #include "texture.h" +#include "texture_manager.h" -#include "particle_renderer.h" -#include "model_manager.h" #include "graphics_interface.h" +#include "model_manager.h" +#include "particle_renderer.h" -//#include "model_manager.h" -//#include "graphics_factory_gl.h" +// #include "model_manager.h" +// #include "graphics_factory_gl.h" -using Shared::Graphics::ModelRenderer; -using Shared::Graphics::TextureManager; -using Shared::Graphics::ModelManager; using Shared::Graphics::Model; -using Shared::Graphics::Texture2D; -using Shared::Graphics::ParticleRenderer; +using Shared::Graphics::ModelManager; +using Shared::Graphics::ModelRenderer; using Shared::Graphics::ParticleManager; +using Shared::Graphics::ParticleRenderer; using Shared::Graphics::ParticleSystem; -//#include "model_renderer.h" +using Shared::Graphics::Texture2D; +using Shared::Graphics::TextureManager; +// #include "model_renderer.h" -using Shared::Graphics::MeshCallback; using Shared::Graphics::Mesh; +using Shared::Graphics::MeshCallback; using Shared::Graphics::Texture; using namespace Shared::Graphics; -namespace Shared{ namespace G3dViewer{ +namespace Shared { +namespace G3dViewer { // =============================================== // class MeshCallbackTeamColor // =============================================== -class MeshCallbackTeamColor: public MeshCallback{ +class MeshCallbackTeamColor : public MeshCallback { private: - const Texture *teamTexture; + const Texture *teamTexture; public: - MeshCallbackTeamColor() : MeshCallback() { - teamTexture = NULL; - } - void setTeamTexture(const Texture *teamTexture) {this->teamTexture= teamTexture;} - virtual void execute(const Mesh *mesh); + MeshCallbackTeamColor() : MeshCallback() { teamTexture = NULL; } + void setTeamTexture(const Texture *teamTexture) { + this->teamTexture = teamTexture; + } + virtual void execute(const Mesh *mesh); }; // =============================== @@ -69,98 +70,103 @@ class MeshCallbackTeamColor: public MeshCallback{ class Renderer : public RendererInterface { public: - static int windowX; - static int windowY; - static int windowW; - static int windowH; + static int windowX; + static int windowY; + static int windowW; + static int windowH; public: - enum PlayerColor{ - pcRed, - pcBlue, - pcGreen, - pcYellow, - pcWhite, - pcCyan, - pcOrange, - pcMagenta - }; + enum PlayerColor { + pcRed, + pcBlue, + pcGreen, + pcYellow, + pcWhite, + pcCyan, + pcOrange, + pcMagenta + }; private: - bool wireframe; - bool normals; - bool grid; - - int width; - int height; - - ModelRenderer *modelRenderer; - TextureManager *textureManager; - ParticleRenderer *particleRenderer; - - ParticleManager *particleManager; - ModelManager *modelManager; - - Texture2D *customTextureRed; - Texture2D *customTextureBlue; - Texture2D *customTextureGreen; - Texture2D *customTextureYellow; - Texture2D *customTextureWhite; - Texture2D *customTextureCyan; - Texture2D *customTextureOrange; - Texture2D *customTextureMagenta; - MeshCallbackTeamColor meshCallbackTeamColor; - - float red; - float green; - float blue; - float alpha; - - Renderer(); - void checkGlCaps(); - void checkExtension(const string &extension, const string &msg); + bool wireframe; + bool normals; + bool grid; + + int width; + int height; + + ModelRenderer *modelRenderer; + TextureManager *textureManager; + ParticleRenderer *particleRenderer; + + ParticleManager *particleManager; + ModelManager *modelManager; + + Texture2D *customTextureRed; + Texture2D *customTextureBlue; + Texture2D *customTextureGreen; + Texture2D *customTextureYellow; + Texture2D *customTextureWhite; + Texture2D *customTextureCyan; + Texture2D *customTextureOrange; + Texture2D *customTextureMagenta; + MeshCallbackTeamColor meshCallbackTeamColor; + + float red; + float green; + float blue; + float alpha; + + Renderer(); + void checkGlCaps(); + void checkExtension(const string &extension, const string &msg); public: - virtual ~Renderer(); - static Renderer *getInstance(); + virtual ~Renderer(); + static Renderer *getInstance(); - void init(); - void reset(int w, int h, PlayerColor playerColor); - void transform(float rotX, float rotY, float zoom); - void renderGrid(); + void init(); + void reset(int w, int h, PlayerColor playerColor); + void transform(float rotX, float rotY, float zoom); + void renderGrid(); - bool getNormals() const {return normals;} - bool getWireframe() const {return wireframe;} - bool getGrid() const {return grid;} + bool getNormals() const { return normals; } + bool getWireframe() const { return wireframe; } + bool getGrid() const { return grid; } - void toggleNormals(); - void toggleWireframe(); - void toggleGrid(); + void toggleNormals(); + void toggleWireframe(); + void toggleGrid(); - void renderTheModel(Model *model, float f); + void renderTheModel(Model *model, float f); - void manageParticleSystem(ParticleSystem *particleSystem); - void updateParticleManager(); - void renderParticleManager(); - Texture2D *getPlayerColorTexture(PlayerColor playerColor); + void manageParticleSystem(ParticleSystem *particleSystem); + void updateParticleManager(); + void renderParticleManager(); + Texture2D *getPlayerColorTexture(PlayerColor playerColor); - Texture2D * getNewTexture2D(); + Texture2D *getNewTexture2D(); - Model *newModel(ResourceScope rs,const string &path,bool deletePixMapAfterLoad=false,std::map > > *loadedFileList=NULL, string *sourceLoader=NULL); - void endModel(ResourceScope rs,Model *model); - Texture2D *newTexture2D(ResourceScope rs) { return getNewTexture2D(); } + Model *newModel( + ResourceScope rs, const string &path, bool deletePixMapAfterLoad = false, + std::map>> *loadedFileList = NULL, + string *sourceLoader = NULL); + void endModel(ResourceScope rs, Model *model); + Texture2D *newTexture2D(ResourceScope rs) { return getNewTexture2D(); } - void initTextureManager(); - void initModelManager(); + void initTextureManager(); + void initModelManager(); - void end(); + void end(); - void setBackgroundColor(float red, float green, float blue); - void setAlphaColor(float alpha); - void saveScreen(const string &path,std::pair *overrideSize); - bool hasActiveParticleSystem(ParticleSystem::ParticleSystemType typeName) const; + void setBackgroundColor(float red, float green, float blue); + void setAlphaColor(float alpha); + void saveScreen(const string &path, std::pair *overrideSize); + bool + hasActiveParticleSystem(ParticleSystem::ParticleSystemType typeName) const; }; -}}//end namespace +} // namespace G3dViewer +} // namespace Shared #endif diff --git a/source/glest_game/ai/ai.cpp b/source/glest_game/ai/ai.cpp index d29808693..775ca7449 100644 --- a/source/glest_game/ai/ai.cpp +++ b/source/glest_game/ai/ai.cpp @@ -12,224 +12,238 @@ #include "ai.h" #include "ai_interface.h" #include "ai_rule.h" -#include "unit_type.h" -#include "unit.h" -#include "map.h" #include "faction_type.h" #include "leak_dumper.h" +#include "map.h" +#include "unit.h" +#include "unit_type.h" using namespace Shared::Graphics; using namespace Shared::Util; -namespace Glest { namespace Game { +namespace Glest { +namespace Game { -Task::Task() { - taskClass = tcProduce; -} +Task::Task() { taskClass = tcProduce; } -//void Task::saveGame(XmlNode *rootNode) const { +// void Task::saveGame(XmlNode *rootNode) const { // std::map mapTagReplacements; // XmlNode *taskNode = rootNode->addChild("Task"); -//} +// } // ===================================================== // class ProduceTask // ===================================================== ProduceTask::ProduceTask() : Task() { - taskClass= tcProduce; - unitType= NULL; - resourceType= NULL; - unitClass = ucWarrior; + taskClass = tcProduce; + unitType = NULL; + resourceType = NULL; + unitClass = ucWarrior; } ProduceTask::ProduceTask(UnitClass unitClass) : Task() { - taskClass= tcProduce; - this->unitClass= unitClass; - unitType= NULL; - resourceType= NULL; + taskClass = tcProduce; + this->unitClass = unitClass; + unitType = NULL; + resourceType = NULL; } ProduceTask::ProduceTask(const UnitType *unitType) : Task() { - taskClass= tcProduce; - this->unitType= unitType; - resourceType= NULL; - unitClass = ucWarrior; + taskClass = tcProduce; + this->unitType = unitType; + resourceType = NULL; + unitClass = ucWarrior; } ProduceTask::ProduceTask(const ResourceType *resourceType) : Task() { - taskClass= tcProduce; - unitType= NULL; - unitClass = ucWarrior; - this->resourceType= resourceType; + taskClass = tcProduce; + unitType = NULL; + unitClass = ucWarrior; + this->resourceType = resourceType; } -string ProduceTask::toString() const{ - string str= "Produce "; - if(unitType!=NULL){ - str+= unitType->getName(false); - } - return str; +string ProduceTask::toString() const { + string str = "Produce "; + if (unitType != NULL) { + str += unitType->getName(false); + } + return str; } void ProduceTask::saveGame(XmlNode *rootNode) const { - std::map mapTagReplacements; - XmlNode *taskNode = rootNode->addChild("Task"); - taskNode->addAttribute("taskClass",intToStr(taskClass), mapTagReplacements); - XmlNode *produceTaskNode = taskNode->addChild("ProduceTask"); - -// UnitClass unitClass; - produceTaskNode->addAttribute("unitClass",intToStr(unitClass), mapTagReplacements); -// const UnitType *unitType; - if(unitType != NULL) { - produceTaskNode->addAttribute("unitType",unitType->getName(false), mapTagReplacements); - } -// const ResourceType *resourceType; - if(resourceType != NULL) { - produceTaskNode->addAttribute("resourceType",resourceType->getName(false), mapTagReplacements); - } + std::map mapTagReplacements; + XmlNode *taskNode = rootNode->addChild("Task"); + taskNode->addAttribute("taskClass", intToStr(taskClass), mapTagReplacements); + XmlNode *produceTaskNode = taskNode->addChild("ProduceTask"); + + // UnitClass unitClass; + produceTaskNode->addAttribute("unitClass", intToStr(unitClass), + mapTagReplacements); + // const UnitType *unitType; + if (unitType != NULL) { + produceTaskNode->addAttribute("unitType", unitType->getName(false), + mapTagReplacements); + } + // const ResourceType *resourceType; + if (resourceType != NULL) { + produceTaskNode->addAttribute("resourceType", resourceType->getName(false), + mapTagReplacements); + } } -ProduceTask * ProduceTask::loadGame(const XmlNode *rootNode, Faction *faction) { - const XmlNode *produceTaskNode = rootNode->getChild("ProduceTask"); - - ProduceTask *newTask = new ProduceTask(); - // UnitClass unitClass; - newTask->unitClass = static_cast(produceTaskNode->getAttribute("unitClass")->getIntValue()); - // const UnitType *unitType; - if(produceTaskNode->hasAttribute("unitType")) { - string unitTypeName = produceTaskNode->getAttribute("unitType")->getValue(); - newTask->unitType = faction->getType()->getUnitType(unitTypeName); - } - // const ResourceType *resourceType; - if(produceTaskNode->hasAttribute("resourceType")) { - string resourceTypeName = produceTaskNode->getAttribute("resourceType")->getValue(); - newTask->resourceType = faction->getTechTree()->getResourceType(resourceTypeName); - } - - return newTask; +ProduceTask *ProduceTask::loadGame(const XmlNode *rootNode, Faction *faction) { + const XmlNode *produceTaskNode = rootNode->getChild("ProduceTask"); + + ProduceTask *newTask = new ProduceTask(); + // UnitClass unitClass; + newTask->unitClass = static_cast( + produceTaskNode->getAttribute("unitClass")->getIntValue()); + // const UnitType *unitType; + if (produceTaskNode->hasAttribute("unitType")) { + string unitTypeName = produceTaskNode->getAttribute("unitType")->getValue(); + newTask->unitType = faction->getType()->getUnitType(unitTypeName); + } + // const ResourceType *resourceType; + if (produceTaskNode->hasAttribute("resourceType")) { + string resourceTypeName = + produceTaskNode->getAttribute("resourceType")->getValue(); + newTask->resourceType = + faction->getTechTree()->getResourceType(resourceTypeName); + } + + return newTask; } // ===================================================== // class BuildTask // ===================================================== BuildTask::BuildTask() { - taskClass= tcBuild; - this->unitType= NULL; - resourceType= NULL; - forcePos= false; + taskClass = tcBuild; + this->unitType = NULL; + resourceType = NULL; + forcePos = false; } -BuildTask::BuildTask(const UnitType *unitType){ - taskClass= tcBuild; - this->unitType= unitType; - resourceType= NULL; - forcePos= false; +BuildTask::BuildTask(const UnitType *unitType) { + taskClass = tcBuild; + this->unitType = unitType; + resourceType = NULL; + forcePos = false; } -BuildTask::BuildTask(const ResourceType *resourceType){ - taskClass= tcBuild; - unitType= NULL; - this->resourceType= resourceType; - forcePos= false; +BuildTask::BuildTask(const ResourceType *resourceType) { + taskClass = tcBuild; + unitType = NULL; + this->resourceType = resourceType; + forcePos = false; } -BuildTask::BuildTask(const UnitType *unitType, const Vec2i &pos){ - taskClass= tcBuild; - this->unitType= unitType; - resourceType= NULL; - forcePos= true; - this->pos= pos; +BuildTask::BuildTask(const UnitType *unitType, const Vec2i &pos) { + taskClass = tcBuild; + this->unitType = unitType; + resourceType = NULL; + forcePos = true; + this->pos = pos; } -string BuildTask::toString() const{ - string str= "Build "; - if(unitType!=NULL){ - str+= unitType->getName(false); - } - return str; +string BuildTask::toString() const { + string str = "Build "; + if (unitType != NULL) { + str += unitType->getName(false); + } + return str; } void BuildTask::saveGame(XmlNode *rootNode) const { - std::map mapTagReplacements; - XmlNode *taskNode = rootNode->addChild("Task"); - taskNode->addAttribute("taskClass",intToStr(taskClass), mapTagReplacements); - XmlNode *buildTaskNode = taskNode->addChild("BuildTask"); - -// const UnitType *unitType; - if(unitType != NULL) { - buildTaskNode->addAttribute("unitType",unitType->getName(false), mapTagReplacements); - } -// const ResourceType *resourceType; - if(resourceType != NULL) { - buildTaskNode->addAttribute("resourceType",resourceType->getName(), mapTagReplacements); - } -// bool forcePos; - buildTaskNode->addAttribute("forcePos",intToStr(forcePos), mapTagReplacements); -// Vec2i pos; - buildTaskNode->addAttribute("pos",pos.getString(), mapTagReplacements); + std::map mapTagReplacements; + XmlNode *taskNode = rootNode->addChild("Task"); + taskNode->addAttribute("taskClass", intToStr(taskClass), mapTagReplacements); + XmlNode *buildTaskNode = taskNode->addChild("BuildTask"); + + // const UnitType *unitType; + if (unitType != NULL) { + buildTaskNode->addAttribute("unitType", unitType->getName(false), + mapTagReplacements); + } + // const ResourceType *resourceType; + if (resourceType != NULL) { + buildTaskNode->addAttribute("resourceType", resourceType->getName(), + mapTagReplacements); + } + // bool forcePos; + buildTaskNode->addAttribute("forcePos", intToStr(forcePos), + mapTagReplacements); + // Vec2i pos; + buildTaskNode->addAttribute("pos", pos.getString(), mapTagReplacements); } -BuildTask * BuildTask::loadGame(const XmlNode *rootNode, Faction *faction) { - const XmlNode *buildTaskNode = rootNode->getChild("BuildTask"); - - BuildTask *newTask = new BuildTask(); - if(buildTaskNode->hasAttribute("unitType")) { - string unitTypeName = buildTaskNode->getAttribute("unitType")->getValue(); - newTask->unitType = faction->getType()->getUnitType(unitTypeName); - } - if(buildTaskNode->hasAttribute("resourceType")) { - string resourceTypeName = buildTaskNode->getAttribute("resourceType")->getValue(); - newTask->resourceType = faction->getTechTree()->getResourceType(resourceTypeName); - } - - newTask->forcePos = buildTaskNode->getAttribute("forcePos")->getIntValue() != 0; - newTask->pos = Vec2i::strToVec2(buildTaskNode->getAttribute("pos")->getValue()); - - return newTask; +BuildTask *BuildTask::loadGame(const XmlNode *rootNode, Faction *faction) { + const XmlNode *buildTaskNode = rootNode->getChild("BuildTask"); + + BuildTask *newTask = new BuildTask(); + if (buildTaskNode->hasAttribute("unitType")) { + string unitTypeName = buildTaskNode->getAttribute("unitType")->getValue(); + newTask->unitType = faction->getType()->getUnitType(unitTypeName); + } + if (buildTaskNode->hasAttribute("resourceType")) { + string resourceTypeName = + buildTaskNode->getAttribute("resourceType")->getValue(); + newTask->resourceType = + faction->getTechTree()->getResourceType(resourceTypeName); + } + + newTask->forcePos = + buildTaskNode->getAttribute("forcePos")->getIntValue() != 0; + newTask->pos = + Vec2i::strToVec2(buildTaskNode->getAttribute("pos")->getValue()); + + return newTask; } // ===================================================== // class UpgradeTask // ===================================================== UpgradeTask::UpgradeTask() { - taskClass= tcUpgrade; - this->upgradeType= NULL; + taskClass = tcUpgrade; + this->upgradeType = NULL; } -UpgradeTask::UpgradeTask(const UpgradeType *upgradeType){ - taskClass= tcUpgrade; - this->upgradeType= upgradeType; +UpgradeTask::UpgradeTask(const UpgradeType *upgradeType) { + taskClass = tcUpgrade; + this->upgradeType = upgradeType; } -string UpgradeTask::toString() const{ - string str= "Build "; - if(upgradeType!=NULL){ - str+= upgradeType->getName(); - } - return str; +string UpgradeTask::toString() const { + string str = "Build "; + if (upgradeType != NULL) { + str += upgradeType->getName(); + } + return str; } void UpgradeTask::saveGame(XmlNode *rootNode) const { - std::map mapTagReplacements; - XmlNode *taskNode = rootNode->addChild("Task"); - taskNode->addAttribute("taskClass",intToStr(taskClass), mapTagReplacements); - XmlNode *upgradeTaskNode = taskNode->addChild("UpgradeTask"); - - if(upgradeType != NULL) { - //upgradeType->saveGame(upgradeTaskNode); - upgradeTaskNode->addAttribute("upgradeType",upgradeType->getName(), mapTagReplacements); - } + std::map mapTagReplacements; + XmlNode *taskNode = rootNode->addChild("Task"); + taskNode->addAttribute("taskClass", intToStr(taskClass), mapTagReplacements); + XmlNode *upgradeTaskNode = taskNode->addChild("UpgradeTask"); + + if (upgradeType != NULL) { + // upgradeType->saveGame(upgradeTaskNode); + upgradeTaskNode->addAttribute("upgradeType", upgradeType->getName(), + mapTagReplacements); + } } -UpgradeTask * UpgradeTask::loadGame(const XmlNode *rootNode, Faction *faction) { - const XmlNode *upgradeTaskNode = rootNode->getChild("UpgradeTask"); +UpgradeTask *UpgradeTask::loadGame(const XmlNode *rootNode, Faction *faction) { + const XmlNode *upgradeTaskNode = rootNode->getChild("UpgradeTask"); - UpgradeTask *newTask = new UpgradeTask(); - if(upgradeTaskNode->hasAttribute("upgradeType")) { - string upgradeTypeName = upgradeTaskNode->getAttribute("upgradeType")->getValue(); - newTask->upgradeType = faction->getType()->getUpgradeType(upgradeTypeName); - } - return newTask; + UpgradeTask *newTask = new UpgradeTask(); + if (upgradeTaskNode->hasAttribute("upgradeType")) { + string upgradeTypeName = + upgradeTaskNode->getAttribute("upgradeType")->getValue(); + newTask->upgradeType = faction->getType()->getUpgradeType(upgradeTypeName); + } + return newTask; } // ===================================================== @@ -237,1084 +251,1350 @@ UpgradeTask * UpgradeTask::loadGame(const XmlNode *rootNode, Faction *faction) { // ===================================================== void Ai::init(AiInterface *aiInterface, int useStartLocation) { - this->aiInterface= aiInterface; - - Faction *faction = this->aiInterface->getMyFaction(); - if(faction->getAIBehaviorStaticOverideValue(aibsvcMaxBuildRadius) != INT_MAX) { - maxBuildRadius = faction->getAIBehaviorStaticOverideValue(aibsvcMaxBuildRadius); - //printf("Discovered overriden static value for AI, maxBuildRadius = %d\n",maxBuildRadius); - } - if(faction->getAIBehaviorStaticOverideValue(aibsvcMinMinWarriors) != INT_MAX) { - minMinWarriors = faction->getAIBehaviorStaticOverideValue(aibsvcMinMinWarriors); - //printf("Discovered overriden static value for AI, minMinWarriors = %d\n",minMinWarriors); - } - if(faction->getAIBehaviorStaticOverideValue(aibsvcMinMinWarriorsExpandCpuEasy) != INT_MAX) { - minMinWarriorsExpandCpuEasy = faction->getAIBehaviorStaticOverideValue(aibsvcMinMinWarriorsExpandCpuEasy); - //printf("Discovered overriden static value for AI, minMinWarriorsExpandCpuEasy = %d\n",minMinWarriorsExpandCpuEasy); - } - if(faction->getAIBehaviorStaticOverideValue(aibsvcMinMinWarriorsExpandCpuMega) != INT_MAX) { - minMinWarriorsExpandCpuMega = faction->getAIBehaviorStaticOverideValue(aibsvcMinMinWarriorsExpandCpuMega); - //printf("Discovered overriden static value for AI, minMinWarriorsExpandCpuMega = %d\n",minMinWarriorsExpandCpuMega); - } - if(faction->getAIBehaviorStaticOverideValue(aibsvcMinMinWarriorsExpandCpuUltra) != INT_MAX) { - minMinWarriorsExpandCpuUltra = faction->getAIBehaviorStaticOverideValue(aibsvcMinMinWarriorsExpandCpuUltra); - //printf("Discovered overriden static value for AI, minMinWarriorsExpandCpuUltra = %d\n",minMinWarriorsExpandCpuUltra); - } - if(faction->getAIBehaviorStaticOverideValue(aibsvcMinMinWarriorsExpandCpuNormal) != INT_MAX) { - minMinWarriorsExpandCpuNormal = faction->getAIBehaviorStaticOverideValue(aibsvcMinMinWarriorsExpandCpuNormal); - //printf("Discovered overriden static value for AI, minMinWarriorsExpandCpuNormal = %d\n",minMinWarriorsExpandCpuNormal); - } - if(faction->getAIBehaviorStaticOverideValue(aibsvcMaxMinWarriors) != INT_MAX) { - maxMinWarriors = faction->getAIBehaviorStaticOverideValue(aibsvcMaxMinWarriors); - //printf("Discovered overriden static value for AI, maxMinWarriors = %d\n",maxMinWarriors); - } - if(faction->getAIBehaviorStaticOverideValue(aibsvcMaxExpansions) != INT_MAX) { - maxExpansions = faction->getAIBehaviorStaticOverideValue(aibsvcMaxExpansions); - //printf("Discovered overriden static value for AI, maxExpansions = %d\n",maxExpansions); - } - if(faction->getAIBehaviorStaticOverideValue(aibsvcVillageRadius) != INT_MAX) { - villageRadius = faction->getAIBehaviorStaticOverideValue(aibsvcVillageRadius); - //printf("Discovered overriden static value for AI, villageRadius = %d\n",villageRadius); - } - if(faction->getAIBehaviorStaticOverideValue(aibsvcScoutResourceRange) != INT_MAX) { - scoutResourceRange = faction->getAIBehaviorStaticOverideValue(aibsvcScoutResourceRange); - //printf("Discovered overriden static value for AI, scoutResourceRange = %d\n",scoutResourceRange); - } - if(faction->getAIBehaviorStaticOverideValue(aibsvcMinWorkerAttackersHarvesting) != INT_MAX) { - minWorkerAttackersHarvesting = faction->getAIBehaviorStaticOverideValue(aibsvcMinWorkerAttackersHarvesting); - //printf("Discovered overriden static value for AI, scoutResourceRange = %d\n",scoutResourceRange); - } - if(faction->getAIBehaviorStaticOverideValue(aibsvcMinBuildSpacing) != INT_MAX) { - minBuildSpacing = faction->getAIBehaviorStaticOverideValue(aibsvcMinBuildSpacing); - //printf("Discovered overriden static value for AI, scoutResourceRange = %d\n",scoutResourceRange); - } - - if(useStartLocation == -1) { - startLoc = random.randRange(0, aiInterface->getMapMaxPlayers()-1); - } - else { - startLoc = useStartLocation; - } - minWarriors= minMinWarriors; - randomMinWarriorsReached= false; - //add ai rules - aiRules.clear(); - aiRules.push_back(new AiRuleWorkerHarvest(this)); - aiRules.push_back(new AiRuleRefreshHarvester(this)); - aiRules.push_back(new AiRuleScoutPatrol(this)); - aiRules.push_back(new AiRuleUnBlock(this)); - aiRules.push_back(new AiRuleReturnBase(this)); - aiRules.push_back(new AiRuleMassiveAttack(this)); - aiRules.push_back(new AiRuleAddTasks(this)); - aiRules.push_back(new AiRuleProduceResourceProducer(this)); - aiRules.push_back(new AiRuleBuildOneFarm(this)); - aiRules.push_back(new AiRuleProduce(this)); - aiRules.push_back(new AiRuleBuild(this)); - aiRules.push_back(new AiRuleUpgrade(this)); - aiRules.push_back(new AiRuleExpand(this)); - aiRules.push_back(new AiRuleRepair(this)); - aiRules.push_back(new AiRuleRepair(this)); + this->aiInterface = aiInterface; + + Faction *faction = this->aiInterface->getMyFaction(); + if (faction->getAIBehaviorStaticOverideValue(aibsvcMaxBuildRadius) != + INT_MAX) { + maxBuildRadius = + faction->getAIBehaviorStaticOverideValue(aibsvcMaxBuildRadius); + // printf("Discovered overriden static value for AI, maxBuildRadius = + // %d\n",maxBuildRadius); + } + if (faction->getAIBehaviorStaticOverideValue(aibsvcMinMinWarriors) != + INT_MAX) { + minMinWarriors = + faction->getAIBehaviorStaticOverideValue(aibsvcMinMinWarriors); + // printf("Discovered overriden static value for AI, minMinWarriors = + // %d\n",minMinWarriors); + } + if (faction->getAIBehaviorStaticOverideValue( + aibsvcMinMinWarriorsExpandCpuEasy) != INT_MAX) { + minMinWarriorsExpandCpuEasy = faction->getAIBehaviorStaticOverideValue( + aibsvcMinMinWarriorsExpandCpuEasy); + // printf("Discovered overriden static value for AI, + // minMinWarriorsExpandCpuEasy = %d\n",minMinWarriorsExpandCpuEasy); + } + if (faction->getAIBehaviorStaticOverideValue( + aibsvcMinMinWarriorsExpandCpuMega) != INT_MAX) { + minMinWarriorsExpandCpuMega = faction->getAIBehaviorStaticOverideValue( + aibsvcMinMinWarriorsExpandCpuMega); + // printf("Discovered overriden static value for AI, + // minMinWarriorsExpandCpuMega = %d\n",minMinWarriorsExpandCpuMega); + } + if (faction->getAIBehaviorStaticOverideValue( + aibsvcMinMinWarriorsExpandCpuUltra) != INT_MAX) { + minMinWarriorsExpandCpuUltra = faction->getAIBehaviorStaticOverideValue( + aibsvcMinMinWarriorsExpandCpuUltra); + // printf("Discovered overriden static value for AI, + // minMinWarriorsExpandCpuUltra = %d\n",minMinWarriorsExpandCpuUltra); + } + if (faction->getAIBehaviorStaticOverideValue( + aibsvcMinMinWarriorsExpandCpuNormal) != INT_MAX) { + minMinWarriorsExpandCpuNormal = faction->getAIBehaviorStaticOverideValue( + aibsvcMinMinWarriorsExpandCpuNormal); + // printf("Discovered overriden static value for AI, + // minMinWarriorsExpandCpuNormal = %d\n",minMinWarriorsExpandCpuNormal); + } + if (faction->getAIBehaviorStaticOverideValue(aibsvcMaxMinWarriors) != + INT_MAX) { + maxMinWarriors = + faction->getAIBehaviorStaticOverideValue(aibsvcMaxMinWarriors); + // printf("Discovered overriden static value for AI, maxMinWarriors = + // %d\n",maxMinWarriors); + } + if (faction->getAIBehaviorStaticOverideValue(aibsvcMaxExpansions) != + INT_MAX) { + maxExpansions = + faction->getAIBehaviorStaticOverideValue(aibsvcMaxExpansions); + // printf("Discovered overriden static value for AI, maxExpansions = + // %d\n",maxExpansions); + } + if (faction->getAIBehaviorStaticOverideValue(aibsvcVillageRadius) != + INT_MAX) { + villageRadius = + faction->getAIBehaviorStaticOverideValue(aibsvcVillageRadius); + // printf("Discovered overriden static value for AI, villageRadius = + // %d\n",villageRadius); + } + if (faction->getAIBehaviorStaticOverideValue(aibsvcScoutResourceRange) != + INT_MAX) { + scoutResourceRange = + faction->getAIBehaviorStaticOverideValue(aibsvcScoutResourceRange); + // printf("Discovered overriden static value for AI, scoutResourceRange = + // %d\n",scoutResourceRange); + } + if (faction->getAIBehaviorStaticOverideValue( + aibsvcMinWorkerAttackersHarvesting) != INT_MAX) { + minWorkerAttackersHarvesting = faction->getAIBehaviorStaticOverideValue( + aibsvcMinWorkerAttackersHarvesting); + // printf("Discovered overriden static value for AI, scoutResourceRange = + // %d\n",scoutResourceRange); + } + if (faction->getAIBehaviorStaticOverideValue(aibsvcMinBuildSpacing) != + INT_MAX) { + minBuildSpacing = + faction->getAIBehaviorStaticOverideValue(aibsvcMinBuildSpacing); + // printf("Discovered overriden static value for AI, scoutResourceRange = + // %d\n",scoutResourceRange); + } + + if (useStartLocation == -1) { + startLoc = random.randRange(0, aiInterface->getMapMaxPlayers() - 1); + } else { + startLoc = useStartLocation; + } + minWarriors = minMinWarriors; + randomMinWarriorsReached = false; + // add ai rules + aiRules.clear(); + aiRules.push_back(new AiRuleWorkerHarvest(this)); + aiRules.push_back(new AiRuleRefreshHarvester(this)); + aiRules.push_back(new AiRuleScoutPatrol(this)); + aiRules.push_back(new AiRuleUnBlock(this)); + aiRules.push_back(new AiRuleReturnBase(this)); + aiRules.push_back(new AiRuleMassiveAttack(this)); + aiRules.push_back(new AiRuleAddTasks(this)); + aiRules.push_back(new AiRuleProduceResourceProducer(this)); + aiRules.push_back(new AiRuleBuildOneFarm(this)); + aiRules.push_back(new AiRuleProduce(this)); + aiRules.push_back(new AiRuleBuild(this)); + aiRules.push_back(new AiRuleUpgrade(this)); + aiRules.push_back(new AiRuleExpand(this)); + aiRules.push_back(new AiRuleRepair(this)); + aiRules.push_back(new AiRuleRepair(this)); } Ai::~Ai() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] deleting AI aiInterface [%p]\n",__FILE__,__FUNCTION__,__LINE__,aiInterface); - deleteValues(tasks.begin(), tasks.end()); - tasks.clear(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] deleting AI aiInterface [%p]\n",__FILE__,__FUNCTION__,__LINE__,aiInterface); - - deleteValues(aiRules.begin(), aiRules.end()); - aiRules.clear(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] deleting AI aiInterface [%p]\n",__FILE__,__FUNCTION__,__LINE__,aiInterface); - - aiInterface = NULL; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] deleting AI aiInterface [%p]\n", __FILE__, + __FUNCTION__, __LINE__, aiInterface); + deleteValues(tasks.begin(), tasks.end()); + tasks.clear(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] deleting AI aiInterface [%p]\n", __FILE__, + __FUNCTION__, __LINE__, aiInterface); + + deleteValues(aiRules.begin(), aiRules.end()); + aiRules.clear(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] deleting AI aiInterface [%p]\n", __FILE__, + __FUNCTION__, __LINE__, aiInterface); + + aiInterface = NULL; } -RandomGen* Ai::getRandom() { -// if(Thread::isCurrentThreadMainThread() == false) { -// throw megaglest_runtime_error("Invalid access to AI random from outside main thread current id = " + -// intToStr(Thread::getCurrentThreadId()) + " main = " + intToStr(Thread::getMainThreadId())); -// } - return &random; +RandomGen *Ai::getRandom() { + // if(Thread::isCurrentThreadMainThread() == false) { + // throw megaglest_runtime_error("Invalid access to AI random from + // outside main thread current id = " + + // intToStr(Thread::getCurrentThreadId()) + //+ " main = " + intToStr(Thread::getMainThreadId())); + // } + return &random; } void Ai::update() { - Chrono chrono; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [START]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis()); - - if(aiInterface->getMyFaction()->getFirstSwitchTeamVote() != NULL) { - const SwitchTeamVote *vote = aiInterface->getMyFaction()->getFirstSwitchTeamVote(); - aiInterface->getMyFaction()->setCurrentSwitchTeamVoteFactionIndex(vote->factionIndex); - - factionSwitchTeamRequestCount[vote->factionIndex]++; - int factionSwitchTeamRequestCountCurrent = factionSwitchTeamRequestCount[vote->factionIndex]; - - //int allowJoinTeam = random.randRange(0, 100); - //srand(time(NULL) + aiInterface->getMyFaction()->getIndex()); - Chrono seed(true); - srand((unsigned int)seed.getCurTicks() + aiInterface->getMyFaction()->getIndex()); - - int allowJoinTeam = rand() % 100; - - SwitchTeamVote *voteResult = aiInterface->getMyFaction()->getSwitchTeamVote(vote->factionIndex); - voteResult->voted = true; - voteResult->allowSwitchTeam = false; - - const GameSettings *settings = aiInterface->getWorld()->getGameSettings(); - - // If AI player already lost game they cannot vote - if(aiInterface->getWorld()->factionLostGame(aiInterface->getFactionIndex()) == true) { - voteResult->allowSwitchTeam = true; - } - else { - // Can only ask the AI player 2 times max per game - if(factionSwitchTeamRequestCountCurrent <= 2) { - // x% chance the AI will answer yes - if(settings->getAiAcceptSwitchTeamPercentChance() >= 100) { - voteResult->allowSwitchTeam = true; - } - else if(settings->getAiAcceptSwitchTeamPercentChance() <= 0) { - voteResult->allowSwitchTeam = false; - } - else { - voteResult->allowSwitchTeam = (allowJoinTeam >= (100 - settings->getAiAcceptSwitchTeamPercentChance())); - } - } - } - - char szBuf[8096]=""; - snprintf(szBuf,8096,"AI for faction# %d voted %s [%d] CountCurrent [%d] PercentChance [%d]",aiInterface->getMyFaction()->getIndex(),(voteResult->allowSwitchTeam ? "Yes" : "No"),allowJoinTeam,factionSwitchTeamRequestCountCurrent,settings->getAiAcceptSwitchTeamPercentChance()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] %s\n",__FILE__,__FUNCTION__,__LINE__,szBuf); - - aiInterface->printLog(3, szBuf); - - aiInterface->giveCommandSwitchTeamVote(aiInterface->getMyFaction(),voteResult); - } - - //process ai rules - for(unsigned int ruleIdx = 0; ruleIdx < aiRules.size(); ++ruleIdx) { - AiRule *rule = aiRules[ruleIdx]; - if(rule == NULL) { - throw megaglest_runtime_error("rule == NULL"); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [ruleIdx = %d]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),ruleIdx); - - if((aiInterface->getTimer() % (rule->getTestInterval() * GameConstants::updateFps / 1000)) == 0) { - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [ruleIdx = %d, before rule->test()]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),ruleIdx); - - //printf("Testing AI Faction # %d RULE Name[%s]\n",aiInterface->getFactionIndex(),rule->getName().c_str()); - - if(rule->test()) { - if(outputAIBehaviourToConsole()) printf("\n\nYYYYY Executing AI Faction # %d RULE Name[%s]\n\n",aiInterface->getFactionIndex(),rule->getName().c_str()); + Chrono chrono; + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) + chrono.start(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld [START]\n", + __FILE__, __FUNCTION__, __LINE__, + chrono.getMillis()); + + if (aiInterface->getMyFaction()->getFirstSwitchTeamVote() != NULL) { + const SwitchTeamVote *vote = + aiInterface->getMyFaction()->getFirstSwitchTeamVote(); + aiInterface->getMyFaction()->setCurrentSwitchTeamVoteFactionIndex( + vote->factionIndex); + + factionSwitchTeamRequestCount[vote->factionIndex]++; + int factionSwitchTeamRequestCountCurrent = + factionSwitchTeamRequestCount[vote->factionIndex]; + + // int allowJoinTeam = random.randRange(0, 100); + // srand(time(NULL) + aiInterface->getMyFaction()->getIndex()); + Chrono seed(true); + srand((unsigned int)seed.getCurTicks() + + aiInterface->getMyFaction()->getIndex()); + + int allowJoinTeam = rand() % 100; + + SwitchTeamVote *voteResult = + aiInterface->getMyFaction()->getSwitchTeamVote(vote->factionIndex); + voteResult->voted = true; + voteResult->allowSwitchTeam = false; + + const GameSettings *settings = aiInterface->getWorld()->getGameSettings(); + + // If AI player already lost game they cannot vote + if (aiInterface->getWorld()->factionLostGame( + aiInterface->getFactionIndex()) == true) { + voteResult->allowSwitchTeam = true; + } else { + // Can only ask the AI player 2 times max per game + if (factionSwitchTeamRequestCountCurrent <= 2) { + // x% chance the AI will answer yes + if (settings->getAiAcceptSwitchTeamPercentChance() >= 100) { + voteResult->allowSwitchTeam = true; + } else if (settings->getAiAcceptSwitchTeamPercentChance() <= 0) { + voteResult->allowSwitchTeam = false; + } else { + voteResult->allowSwitchTeam = + (allowJoinTeam >= + (100 - settings->getAiAcceptSwitchTeamPercentChance())); + } + } + } - aiInterface->printLog(3, intToStr(1000 * aiInterface->getTimer() / GameConstants::updateFps) + ": Executing rule: " + rule->getName() + '\n'); + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "AI for faction# %d voted %s [%d] CountCurrent [%d] PercentChance [%d]", + aiInterface->getMyFaction()->getIndex(), + (voteResult->allowSwitchTeam ? "Yes" : "No"), allowJoinTeam, + factionSwitchTeamRequestCountCurrent, + settings->getAiAcceptSwitchTeamPercentChance()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] %s\n", __FILE__, + __FUNCTION__, __LINE__, szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [ruleIdx = %d, before rule->execute() [%s]]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),ruleIdx,rule->getName().c_str()); + aiInterface->printLog(3, szBuf); - rule->execute(); + aiInterface->giveCommandSwitchTeamVote(aiInterface->getMyFaction(), + voteResult); + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [ruleIdx = %d, after rule->execute() [%s]]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),ruleIdx,rule->getName().c_str()); - } - } - } + // process ai rules + for (unsigned int ruleIdx = 0; ruleIdx < aiRules.size(); ++ruleIdx) { + AiRule *rule = aiRules[ruleIdx]; + if (rule == NULL) { + throw megaglest_runtime_error("rule == NULL"); + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [END]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld [ruleIdx = %d]\n", __FILE__, + __FUNCTION__, __LINE__, chrono.getMillis(), ruleIdx); + + if ((aiInterface->getTimer() % + (rule->getTestInterval() * GameConstants::updateFps / 1000)) == 0) { + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld " + "[ruleIdx = %d, before rule->test()]\n", + __FILE__, __FUNCTION__, __LINE__, + chrono.getMillis(), ruleIdx); + + // printf("Testing AI Faction # %d RULE + // Name[%s]\n",aiInterface->getFactionIndex(),rule->getName().c_str()); + + if (rule->test()) { + if (outputAIBehaviourToConsole()) + printf("\n\nYYYYY Executing AI Faction # %d RULE Name[%s]\n\n", + aiInterface->getFactionIndex(), rule->getName().c_str()); + + aiInterface->printLog(3, intToStr(1000 * aiInterface->getTimer() / + GameConstants::updateFps) + + ": Executing rule: " + rule->getName() + + '\n'); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld [ruleIdx = %d, before " + "rule->execute() [%s]]\n", + __FILE__, __FUNCTION__, __LINE__, chrono.getMillis(), ruleIdx, + rule->getName().c_str()); + + rule->execute(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld [ruleIdx = %d, after " + "rule->execute() [%s]]\n", + __FILE__, __FUNCTION__, __LINE__, chrono.getMillis(), ruleIdx, + rule->getName().c_str()); + } + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld [END]\n", + __FILE__, __FUNCTION__, __LINE__, + chrono.getMillis()); } - // ==================== state requests ==================== -int Ai::getCountOfType(const UnitType *ut){ - int count= 0; - for(int i=0; igetMyUnitCount(); ++i){ - if(ut == aiInterface->getMyUnit(i)->getType()){ - count++; - } - } - return count; +int Ai::getCountOfType(const UnitType *ut) { + int count = 0; + for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) { + if (ut == aiInterface->getMyUnit(i)->getType()) { + count++; + } + } + return count; } -int Ai::getCountOfClass(UnitClass uc,UnitClass *additionalUnitClassToExcludeFromCount) { - int count= 0; - for(int i = 0; i < aiInterface->getMyUnitCount(); ++i) { - if(aiInterface->getMyUnit(i)->getType()->isOfClass(uc)) { - // Skip unit if it ALSO contains the exclusion unit class type - if(additionalUnitClassToExcludeFromCount != NULL) { - if(aiInterface->getMyUnit(i)->getType()->isOfClass(*additionalUnitClassToExcludeFromCount)) { - continue; - } - } - ++count; - } +int Ai::getCountOfClass(UnitClass uc, + UnitClass *additionalUnitClassToExcludeFromCount) { + int count = 0; + for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) { + if (aiInterface->getMyUnit(i)->getType()->isOfClass(uc)) { + // Skip unit if it ALSO contains the exclusion unit class type + if (additionalUnitClassToExcludeFromCount != NULL) { + if (aiInterface->getMyUnit(i)->getType()->isOfClass( + *additionalUnitClassToExcludeFromCount)) { + continue; + } + } + ++count; } - return count; + } + return count; } -float Ai::getRatioOfClass(UnitClass uc,UnitClass *additionalUnitClassToExcludeFromCount) { - if(aiInterface->getMyUnitCount() == 0) { - return 0; - } - else { - //return static_cast(getCountOfClass(uc,additionalUnitClassToExcludeFromCount)) / aiInterface->getMyUnitCount(); - return truncateDecimal(static_cast(getCountOfClass(uc,additionalUnitClassToExcludeFromCount)) / aiInterface->getMyUnitCount(),6); - } +float Ai::getRatioOfClass(UnitClass uc, + UnitClass *additionalUnitClassToExcludeFromCount) { + if (aiInterface->getMyUnitCount() == 0) { + return 0; + } else { + // return + // static_cast(getCountOfClass(uc,additionalUnitClassToExcludeFromCount)) + // / aiInterface->getMyUnitCount(); + return truncateDecimal( + static_cast( + getCountOfClass(uc, additionalUnitClassToExcludeFromCount)) / + aiInterface->getMyUnitCount(), + 6); + } } const ResourceType *Ai::getNeededResource(int unitIndex) { - int amount = INT_MAX; - const ResourceType *neededResource= NULL; - const TechTree *tt= aiInterface->getTechTree(); - const Unit *unit = aiInterface->getMyUnit(unitIndex); - - for(int i = 0; i < tt->getResourceTypeCount(); ++i) { - const ResourceType *rt= tt->getResourceType(i); - const Resource *r= aiInterface->getResource(rt); - - if( rt->getClass() != rcStatic && rt->getClass() != rcConsumable) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Examining resource [%s] amount [%d] (previous amount [%d]",rt->getName().c_str(),r->getAmount(),amount); - aiInterface->printLog(3, szBuf); - } - - if( rt->getClass() != rcStatic && rt->getClass() != rcConsumable && - r->getAmount() < amount) { - - // Only have up to x units going for this resource so we can focus - // on other needed resources for other units - const int maxUnitsToHarvestResource = 5; - - vector unitsGettingResource = findUnitsHarvestingResourceType(rt); - if((int)unitsGettingResource.size() <= maxUnitsToHarvestResource) { - // Now MAKE SURE the unit has a harvest command for this resource - // AND that the resource is within eye-sight to avoid units - // standing around doing nothing. - const HarvestCommandType *hct= unit->getType()->getFirstHarvestCommand(rt,unit->getFaction()); - Vec2i resPos; - if(hct != NULL && aiInterface->getNearestSightedResource(rt, aiInterface->getHomeLocation(), resPos, false)) { - amount= r->getAmount(); - neededResource= rt; - } - } - } + int amount = INT_MAX; + const ResourceType *neededResource = NULL; + const TechTree *tt = aiInterface->getTechTree(); + const Unit *unit = aiInterface->getMyUnit(unitIndex); + + for (int i = 0; i < tt->getResourceTypeCount(); ++i) { + const ResourceType *rt = tt->getResourceType(i); + const Resource *r = aiInterface->getResource(rt); + + if (rt->getClass() != rcStatic && rt->getClass() != rcConsumable) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "Examining resource [%s] amount [%d] (previous amount [%d]", + rt->getName().c_str(), r->getAmount(), amount); + aiInterface->printLog(3, szBuf); } - char szBuf[8096]=""; - snprintf(szBuf,8096,"Unit [%d - %s] looking for resources (not static or consumable)",unit->getId(),unit->getType()->getName(false).c_str()); - aiInterface->printLog(3, szBuf); - snprintf(szBuf,8096,"[resource type count %d] Needed resource [%s].",tt->getResourceTypeCount(),(neededResource != NULL ? neededResource->getName().c_str() : "")); - aiInterface->printLog(3, szBuf); - - return neededResource; + if (rt->getClass() != rcStatic && rt->getClass() != rcConsumable && + r->getAmount() < amount) { + + // Only have up to x units going for this resource so we can focus + // on other needed resources for other units + const int maxUnitsToHarvestResource = 5; + + vector unitsGettingResource = findUnitsHarvestingResourceType(rt); + if ((int)unitsGettingResource.size() <= maxUnitsToHarvestResource) { + // Now MAKE SURE the unit has a harvest command for this resource + // AND that the resource is within eye-sight to avoid units + // standing around doing nothing. + const HarvestCommandType *hct = + unit->getType()->getFirstHarvestCommand(rt, unit->getFaction()); + Vec2i resPos; + if (hct != NULL && + aiInterface->getNearestSightedResource( + rt, aiInterface->getHomeLocation(), resPos, false)) { + amount = r->getAmount(); + neededResource = rt; + } + } + } + } + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "Unit [%d - %s] looking for resources (not static or consumable)", + unit->getId(), unit->getType()->getName(false).c_str()); + aiInterface->printLog(3, szBuf); + snprintf( + szBuf, 8096, "[resource type count %d] Needed resource [%s].", + tt->getResourceTypeCount(), + (neededResource != NULL ? neededResource->getName().c_str() : "")); + aiInterface->printLog(3, szBuf); + + return neededResource; } -bool Ai::beingAttacked(Vec2i &pos, Field &field, int radius){ - const Unit *enemy = aiInterface->getFirstOnSightEnemyUnit(pos, field, radius); - return (enemy != NULL); +bool Ai::beingAttacked(Vec2i &pos, Field &field, int radius) { + const Unit *enemy = aiInterface->getFirstOnSightEnemyUnit(pos, field, radius); + return (enemy != NULL); } bool Ai::isStableBase() { - UnitClass ucWorkerType = ucWorker; - if(getCountOfClass(ucWarrior,&ucWorkerType) > minWarriors) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Base is stable [minWarriors = %d found = %d]",minWarriors,ucWorkerType); - aiInterface->printLog(4, szBuf); + UnitClass ucWorkerType = ucWorker; + if (getCountOfClass(ucWarrior, &ucWorkerType) > minWarriors) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "Base is stable [minWarriors = %d found = %d]", + minWarriors, ucWorkerType); + aiInterface->printLog(4, szBuf); + + return true; + } else { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "Base is NOT stable [minWarriors = %d found = %d]", + minWarriors, ucWorkerType); + aiInterface->printLog(4, szBuf); - return true; - } - else{ - char szBuf[8096]=""; - snprintf(szBuf,8096,"Base is NOT stable [minWarriors = %d found = %d]",minWarriors,ucWorkerType); - aiInterface->printLog(4, szBuf); + return false; + } +} - return false; +bool Ai::findAbleUnit(int *unitIndex, CommandClass ability, bool idleOnly) { + vector units; + + *unitIndex = -1; + for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) { + const Unit *unit = aiInterface->getMyUnit(i); + if (unit->getType()->isCommandable() && + unit->getType()->hasCommandClass(ability)) { + if (!idleOnly || !unit->anyCommand() || + unit->getCurrCommand()->getCommandType()->getClass() == ccStop) { + units.push_back(i); + } } -} + } -bool Ai::findAbleUnit(int *unitIndex, CommandClass ability, bool idleOnly){ - vector units; - - *unitIndex= -1; - for(int i=0; igetMyUnitCount(); ++i){ - const Unit *unit= aiInterface->getMyUnit(i); - if(unit->getType()->isCommandable() && unit->getType()->hasCommandClass(ability)){ - if(!idleOnly || !unit->anyCommand() || unit->getCurrCommand()->getCommandType()->getClass()==ccStop){ - units.push_back(i); - } - } - } - - if(units.empty()){ - return false; - } - else{ - *unitIndex= units[random.randRange(0, (int)units.size()-1)]; - return true; - } + if (units.empty()) { + return false; + } else { + *unitIndex = units[random.randRange(0, (int)units.size() - 1)]; + return true; + } } vector Ai::findUnitsHarvestingResourceType(const ResourceType *rt) { - vector units; - - Map *map= aiInterface->getMap(); - for(int i = 0; i < aiInterface->getMyUnitCount(); ++i) { - const Unit *unit= aiInterface->getMyUnit(i); - if(unit->getType()->isCommandable()) { - if(unit->getType()->hasCommandClass(ccHarvest)) { - if(unit->anyCommand() && unit->getCurrCommand()->getCommandType()->getClass() == ccHarvest) { - Command *command= unit->getCurrCommand(); - const HarvestCommandType *hct= dynamic_cast(command->getCommandType()); - if(hct != NULL) { - const Vec2i unitTargetPos = unit->getTargetPos(); - SurfaceCell *sc= map->getSurfaceCell(Map::toSurfCoords(unitTargetPos)); - Resource *r= sc->getResource(); - if (r != NULL && r->getType() == rt) { - units.push_back(i); - } - } - } - } - else if(unit->getType()->hasCommandClass(ccProduce)) { - if(unit->anyCommand() && unit->getCurrCommand()->getCommandType()->getClass() == ccProduce) { - Command *command= unit->getCurrCommand(); - const ProduceCommandType *pct= dynamic_cast(command->getCommandType()); - if(pct != NULL) { - const UnitType *ut = pct->getProducedUnit(); - if(ut != NULL) { - const Resource *r = ut->getCost(rt); - if(r != NULL) { - if (r != NULL && r->getAmount() < 0) { - units.push_back(i); - } - } - } - } - } - } - else if(unit->getType()->hasCommandClass(ccBuild)) { - if(unit->anyCommand() && unit->getCurrCommand()->getCommandType()->getClass() == ccBuild) { - Command *command= unit->getCurrCommand(); - const BuildCommandType *bct= dynamic_cast(command->getCommandType()); - if(bct != NULL) { - for(int j = 0; j < bct->getBuildingCount(); ++j) { - const UnitType *ut = bct->getBuilding(j); - if(ut != NULL) { - const Resource *r = ut->getCost(rt); - if(r != NULL) { - if (r != NULL && r->getAmount() < 0) { - units.push_back(i); - break; - } - } - } - } - } - } - } - } - } - - return units; + vector units; + + Map *map = aiInterface->getMap(); + for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) { + const Unit *unit = aiInterface->getMyUnit(i); + if (unit->getType()->isCommandable()) { + if (unit->getType()->hasCommandClass(ccHarvest)) { + if (unit->anyCommand() && + unit->getCurrCommand()->getCommandType()->getClass() == ccHarvest) { + Command *command = unit->getCurrCommand(); + const HarvestCommandType *hct = + dynamic_cast( + command->getCommandType()); + if (hct != NULL) { + const Vec2i unitTargetPos = unit->getTargetPos(); + SurfaceCell *sc = + map->getSurfaceCell(Map::toSurfCoords(unitTargetPos)); + Resource *r = sc->getResource(); + if (r != NULL && r->getType() == rt) { + units.push_back(i); + } + } + } + } else if (unit->getType()->hasCommandClass(ccProduce)) { + if (unit->anyCommand() && + unit->getCurrCommand()->getCommandType()->getClass() == ccProduce) { + Command *command = unit->getCurrCommand(); + const ProduceCommandType *pct = + dynamic_cast( + command->getCommandType()); + if (pct != NULL) { + const UnitType *ut = pct->getProducedUnit(); + if (ut != NULL) { + const Resource *r = ut->getCost(rt); + if (r != NULL) { + if (r != NULL && r->getAmount() < 0) { + units.push_back(i); + } + } + } + } + } + } else if (unit->getType()->hasCommandClass(ccBuild)) { + if (unit->anyCommand() && + unit->getCurrCommand()->getCommandType()->getClass() == ccBuild) { + Command *command = unit->getCurrCommand(); + const BuildCommandType *bct = + dynamic_cast(command->getCommandType()); + if (bct != NULL) { + for (int j = 0; j < bct->getBuildingCount(); ++j) { + const UnitType *ut = bct->getBuilding(j); + if (ut != NULL) { + const Resource *r = ut->getCost(rt); + if (r != NULL) { + if (r != NULL && r->getAmount() < 0) { + units.push_back(i); + break; + } + } + } + } + } + } + } + } + } + + return units; } -//vector Ai::findUnitsDoingCommand(CommandClass currentCommand) { +// vector Ai::findUnitsDoingCommand(CommandClass currentCommand) { // vector units; // // for(int i = 0; i < aiInterface->getMyUnitCount(); ++i) { // const Unit *unit= aiInterface->getMyUnit(i); -// if(unit->getType()->isCommandable() && unit->getType()->hasCommandClass(currentCommand)) { -// if(unit->anyCommand() && unit->getCurrCommand()->getCommandType()->getClass() == currentCommand) { -// units.push_back(i); +// if(unit->getType()->isCommandable() && +// unit->getType()->hasCommandClass(currentCommand)) { +// if(unit->anyCommand() && unit->getCurrCommand()->getCommandType()->getClass() +// == currentCommand) { units.push_back(i); // } // } // } // // return units; -//} - -bool Ai::findAbleUnit(int *unitIndex, CommandClass ability, CommandClass currentCommand){ - vector units; - - *unitIndex= -1; - for(int i=0; igetMyUnitCount(); ++i){ - const Unit *unit= aiInterface->getMyUnit(i); - if(unit->getType()->isCommandable() && unit->getType()->hasCommandClass(ability)){ - if(unit->anyCommand() && unit->getCurrCommand()->getCommandType()->getClass()==currentCommand){ - units.push_back(i); - } - } - } - - if(units.empty()){ - return false; - } - else{ - *unitIndex= units[random.randRange(0, (int)units.size()-1)]; - return true; - } +// } + +bool Ai::findAbleUnit(int *unitIndex, CommandClass ability, + CommandClass currentCommand) { + vector units; + + *unitIndex = -1; + for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) { + const Unit *unit = aiInterface->getMyUnit(i); + if (unit->getType()->isCommandable() && + unit->getType()->hasCommandClass(ability)) { + if (unit->anyCommand() && + unit->getCurrCommand()->getCommandType()->getClass() == + currentCommand) { + units.push_back(i); + } + } + } + + if (units.empty()) { + return false; + } else { + *unitIndex = units[random.randRange(0, (int)units.size() - 1)]; + return true; + } } -bool Ai::findPosForBuilding(const UnitType* building, const Vec2i &searchPos, Vec2i &outPos){ - - for(int currRadius = 0; currRadius < maxBuildRadius; ++currRadius) { - for(int i=searchPos.x - currRadius; i < searchPos.x + currRadius; ++i) { - for(int j=searchPos.y - currRadius; j < searchPos.y + currRadius; ++j) { - outPos= Vec2i(i, j); - if(aiInterface->isFreeCells(outPos - Vec2i(minBuildSpacing), building->getAiBuildSize() + minBuildSpacing * 2, fLand)) { - int aiBuildSizeDiff= building->getAiBuildSize()- building->getSize(); - if( aiBuildSizeDiff>0){ - int halfSize=aiBuildSizeDiff/2; - outPos.x+=halfSize; - outPos.y+=halfSize; - } - return true; - } - } +bool Ai::findPosForBuilding(const UnitType *building, const Vec2i &searchPos, + Vec2i &outPos) { + + for (int currRadius = 0; currRadius < maxBuildRadius; ++currRadius) { + for (int i = searchPos.x - currRadius; i < searchPos.x + currRadius; ++i) { + for (int j = searchPos.y - currRadius; j < searchPos.y + currRadius; + ++j) { + outPos = Vec2i(i, j); + if (aiInterface->isFreeCells( + outPos - Vec2i(minBuildSpacing), + building->getAiBuildSize() + minBuildSpacing * 2, fLand)) { + int aiBuildSizeDiff = + building->getAiBuildSize() - building->getSize(); + if (aiBuildSizeDiff > 0) { + int halfSize = aiBuildSizeDiff / 2; + outPos.x += halfSize; + outPos.y += halfSize; + } + return true; } + } } + } - return false; - + return false; } - // ==================== tasks ==================== -void Ai::addTask(const Task *task){ - tasks.push_back(task); - aiInterface->printLog(2, "Task added: " + task->toString()); +void Ai::addTask(const Task *task) { + tasks.push_back(task); + aiInterface->printLog(2, "Task added: " + task->toString()); } -void Ai::addPriorityTask(const Task *task){ - deleteValues(tasks.begin(), tasks.end()); - tasks.clear(); +void Ai::addPriorityTask(const Task *task) { + deleteValues(tasks.begin(), tasks.end()); + tasks.clear(); - tasks.push_back(task); - aiInterface->printLog(2, "Priority Task added: " + task->toString()); + tasks.push_back(task); + aiInterface->printLog(2, "Priority Task added: " + task->toString()); } -bool Ai::anyTask(){ - return !tasks.empty(); -} +bool Ai::anyTask() { return !tasks.empty(); } -const Task *Ai::getTask() const{ - if(tasks.empty()){ - return NULL; - } - else{ - return tasks.front(); - } +const Task *Ai::getTask() const { + if (tasks.empty()) { + return NULL; + } else { + return tasks.front(); + } } -void Ai::removeTask(const Task *task){ - aiInterface->printLog(2, "Task removed: " + task->toString()); - tasks.remove(task); - delete task; +void Ai::removeTask(const Task *task) { + aiInterface->printLog(2, "Task removed: " + task->toString()); + tasks.remove(task); + delete task; } -void Ai::retryTask(const Task *task){ - tasks.remove(task); - tasks.push_back(task); +void Ai::retryTask(const Task *task) { + tasks.remove(task); + tasks.push_back(task); } // ==================== expansions ==================== void Ai::addExpansion(const Vec2i &pos) { - //check if there is a nearby expansion - for(Positions::iterator it = expansionPositions.begin(); it != expansionPositions.end(); ++it) { - if((*it).dist(pos) < villageRadius) { - return; - } - } + // check if there is a nearby expansion + for (Positions::iterator it = expansionPositions.begin(); + it != expansionPositions.end(); ++it) { + if ((*it).dist(pos) < villageRadius) { + return; + } + } - //add expansion - expansionPositions.push_front(pos); + // add expansion + expansionPositions.push_front(pos); - //remove expansion if queue is list is full - if((int)expansionPositions.size() > maxExpansions){ - expansionPositions.pop_back(); - } + // remove expansion if queue is list is full + if ((int)expansionPositions.size() > maxExpansions) { + expansionPositions.pop_back(); + } } Vec2i Ai::getRandomHomePosition() { - if(expansionPositions.empty() || random.randRange(0, 1) == 0){ - return aiInterface->getHomeLocation(); - } + if (expansionPositions.empty() || random.randRange(0, 1) == 0) { + return aiInterface->getHomeLocation(); + } - return expansionPositions[random.randRange(0, (int)expansionPositions.size()-1)]; + return expansionPositions[random.randRange(0, (int)expansionPositions.size() - + 1)]; } // ==================== actions ==================== -void Ai::sendScoutPatrol(){ - - Vec2i pos; - int unit; - bool possibleTargetFound= false; - - bool ultraResourceAttack= (aiInterface->getControlType() == ctCpuUltra || aiInterface->getControlType() == ctNetworkCpuUltra) - && random.randRange(0, 2) == 1; - bool megaResourceAttack=(aiInterface->getControlType() == ctCpuMega || aiInterface->getControlType() == ctNetworkCpuMega) - && random.randRange(0, 1) == 1; - - if(megaResourceAttack || ultraResourceAttack) { - Map *map= aiInterface->getMap(); - - const TechTree *tt= aiInterface->getTechTree(); - const ResourceType *rt= tt->getResourceType(0); - int tryCount= 0; - int height= map->getH(); - int width= map->getW(); - - for(int i= 0; i < tt->getResourceTypeCount(); ++i){ - const ResourceType *rt_= tt->getResourceType(i); - //const Resource *r= aiInterface->getResource(rt); - - if(rt_->getClass() == rcTech){ - rt=rt_; - break; - } - } - //printf("looking for resource %s\n",rt->getName().c_str()); - while(possibleTargetFound == false){ - tryCount++; - if(tryCount == 4){ - //printf("no target found\n"); - break; - } - pos= Vec2i(random.randRange(2, width - 2), random.randRange(2, height - 2)); - if(map->isInside(pos) && map->isInsideSurface(map->toSurfCoords(pos))){ - //printf("is inside map\n"); - // find first resource in this area - Vec2i resPos; - if(aiInterface->isResourceInRegion(pos, rt, resPos, scoutResourceRange)){ - // found a possible target. - pos= resPos; - //printf("lets try the new target\n"); - possibleTargetFound= true; - break; - } - } - //else printf("is outside map\n"); - } - } - - std::vector warningEnemyList = aiInterface->getEnemyWarningPositionList(); - if( (possibleTargetFound == false) && (warningEnemyList.empty() == false)) { - //for(int i = (int)warningEnemyList.size() - 1; i <= 0; --i) { - //Vec2i &checkPos = warningEnemyList[i]; - Vec2i &checkPos = warningEnemyList[0]; - if (random.randRange(0, 1) == 1 ) { - pos = checkPos; - possibleTargetFound = true; - warningEnemyList.clear(); - } else { - aiInterface->removeEnemyWarningPositionFromList(checkPos); - } - //break; - //} - } - - if(possibleTargetFound == false){ - startLoc= (startLoc + 1) % aiInterface->getMapMaxPlayers(); - pos= aiInterface->getStartLocation(startLoc); - //printf("normal target used\n"); - } - - if(aiInterface->getHomeLocation() != pos){ - if(findAbleUnit(&unit, ccAttack, false)){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - aiInterface->giveCommand(unit, ccAttack, pos); - aiInterface->printLog(2, "Scout patrol sent to: " + intToStr(pos.x) + "," + intToStr(pos.y) + "\n"); - } - } +void Ai::sendScoutPatrol() { + + Vec2i pos; + int unit; + bool possibleTargetFound = false; + + bool ultraResourceAttack = + (aiInterface->getControlType() == ctCpuUltra || + aiInterface->getControlType() == ctNetworkCpuUltra) && + random.randRange(0, 2) == 1; + bool megaResourceAttack = + (aiInterface->getControlType() == ctCpuMega || + aiInterface->getControlType() == ctNetworkCpuMega) && + random.randRange(0, 1) == 1; + + if (megaResourceAttack || ultraResourceAttack) { + Map *map = aiInterface->getMap(); + + const TechTree *tt = aiInterface->getTechTree(); + const ResourceType *rt = tt->getResourceType(0); + int tryCount = 0; + int height = map->getH(); + int width = map->getW(); + + for (int i = 0; i < tt->getResourceTypeCount(); ++i) { + const ResourceType *rt_ = tt->getResourceType(i); + // const Resource *r= aiInterface->getResource(rt); + + if (rt_->getClass() == rcTech) { + rt = rt_; + break; + } + } + // printf("looking for resource %s\n",rt->getName().c_str()); + while (possibleTargetFound == false) { + tryCount++; + if (tryCount == 4) { + // printf("no target found\n"); + break; + } + pos = Vec2i(random.randRange(2, width - 2), + random.randRange(2, height - 2)); + if (map->isInside(pos) && map->isInsideSurface(map->toSurfCoords(pos))) { + // printf("is inside map\n"); + // find first resource in this area + Vec2i resPos; + if (aiInterface->isResourceInRegion(pos, rt, resPos, + scoutResourceRange)) { + // found a possible target. + pos = resPos; + // printf("lets try the new target\n"); + possibleTargetFound = true; + break; + } + } + // else printf("is outside map\n"); + } + } + + std::vector warningEnemyList = + aiInterface->getEnemyWarningPositionList(); + if ((possibleTargetFound == false) && (warningEnemyList.empty() == false)) { + // for(int i = (int)warningEnemyList.size() - 1; i <= 0; --i) { + // Vec2i &checkPos = warningEnemyList[i]; + Vec2i &checkPos = warningEnemyList[0]; + if (random.randRange(0, 1) == 1) { + pos = checkPos; + possibleTargetFound = true; + warningEnemyList.clear(); + } else { + aiInterface->removeEnemyWarningPositionFromList(checkPos); + } + // break; + //} + } + + if (possibleTargetFound == false) { + startLoc = (startLoc + 1) % aiInterface->getMapMaxPlayers(); + pos = aiInterface->getStartLocation(startLoc); + // printf("normal target used\n"); + } + + if (aiInterface->getHomeLocation() != pos) { + if (findAbleUnit(&unit, ccAttack, false)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + + aiInterface->giveCommand(unit, ccAttack, pos); + aiInterface->printLog(2, "Scout patrol sent to: " + intToStr(pos.x) + + "," + intToStr(pos.y) + "\n"); + } + } } -void Ai::massiveAttack(const Vec2i &pos, Field field, bool ultraAttack){ - int producerWarriorCount=0; - int maxProducerWarriors=random.randRange(1,11); - int unitCount = aiInterface->getMyUnitCount(); - int unitGroupCommandId = -1; - - int attackerWorkersHarvestingCount = 0; - for(int i = 0; i < unitCount; ++i) { - bool isWarrior=false; - bool productionInProgress=false; - const Unit *unit= aiInterface->getMyUnit(i); - const AttackCommandType *act= unit->getType()->getFirstAttackCommand(field); - - if( aiInterface->getControlType() == ctCpuMega || - aiInterface->getControlType() == ctNetworkCpuMega) { - if(producerWarriorCount > maxProducerWarriors) { - if( - unit->getCommandSize()>0 && - unit->getCurrCommand()->getCommandType()!=NULL && ( - unit->getCurrCommand()->getCommandType()->getClass()==ccBuild || - unit->getCurrCommand()->getCommandType()->getClass()==ccMorph || - unit->getCurrCommand()->getCommandType()->getClass()==ccProduce - ) - ) { - productionInProgress=true; - isWarrior=false; - producerWarriorCount++; - } - else { - isWarrior =! unit->getType()->hasCommandClass(ccHarvest); - } - - } - else { - isWarrior= !unit->getType()->hasCommandClass(ccHarvest) && !unit->getType()->hasCommandClass(ccProduce); - } - } - else { - isWarrior= !unit->getType()->hasCommandClass(ccHarvest) && !unit->getType()->hasCommandClass(ccProduce); - } - - bool alreadyAttacking= (unit->getCurrSkill()->getClass() == scAttack); - - bool unitSignalledToAttack = false; - if(alreadyAttacking == false && unit->getType()->hasSkillClass(scAttack) && (aiInterface->getControlType() - == ctCpuUltra || aiInterface->getControlType() == ctCpuMega || aiInterface->getControlType() - == ctNetworkCpuUltra || aiInterface->getControlType() == ctNetworkCpuMega)){ - //printf("~~~~~~~~ Unit [%s - %d] checking if unit is being attacked\n",unit->getFullName().c_str(),unit->getId()); - - std::pair beingAttacked= aiInterface->getWorld()->getUnitUpdater()->unitBeingAttacked(unit); - if(beingAttacked.first == true){ - Unit *enemy= beingAttacked.second; - const AttackCommandType *act_forenemy= unit->getType()->getFirstAttackCommand(enemy->getCurrField()); - - //printf("~~~~~~~~ Unit [%s - %d] attacked by enemy [%s - %d] act_forenemy [%p] enemy->getCurrField() = %d\n",unit->getFullName().c_str(),unit->getId(),enemy->getFullName().c_str(),enemy->getId(),act_forenemy,enemy->getCurrField()); - - if(act_forenemy != NULL){ - bool shouldAttack= true; - if(unit->getType()->hasSkillClass(scHarvest)){ - shouldAttack= (attackerWorkersHarvestingCount > minWorkerAttackersHarvesting); - if(shouldAttack == false){ - attackerWorkersHarvestingCount++; - } - } - if(shouldAttack) { - if(unitGroupCommandId == -1) { - unitGroupCommandId = aiInterface->getWorld()->getNextCommandGroupId(); - } - - aiInterface->giveCommand(i, act_forenemy, beingAttacked.second->getPos(), unitGroupCommandId); - unitSignalledToAttack= true; - } - } - else{ - const AttackStoppedCommandType *asct_forenemy= unit->getType()->getFirstAttackStoppedCommand( - enemy->getCurrField()); - //printf("~~~~~~~~ Unit [%s - %d] found enemy [%s - %d] asct_forenemy [%p] enemy->getCurrField() = %d\n",unit->getFullName().c_str(),unit->getId(),enemy->getFullName().c_str(),enemy->getId(),asct_forenemy,enemy->getCurrField()); - if(asct_forenemy != NULL){ - bool shouldAttack= true; - if(unit->getType()->hasSkillClass(scHarvest)){ - shouldAttack= (attackerWorkersHarvestingCount > minWorkerAttackersHarvesting); - if(shouldAttack == false){ - attackerWorkersHarvestingCount++; - } - } - if(shouldAttack){ -// printf("~~~~~~~~ Unit [%s - %d] WILL AttackStoppedCommand [%s - %d]\n", unit->getFullName().c_str(), -// unit->getId(), enemy->getFullName().c_str(), enemy->getId()); - - if(unitGroupCommandId == -1) { - unitGroupCommandId = aiInterface->getWorld()->getNextCommandGroupId(); - } - - aiInterface->giveCommand(i, asct_forenemy, beingAttacked.second->getCenteredPos(), unitGroupCommandId); - unitSignalledToAttack= true; - } - } - } - } - } - if(alreadyAttacking == false && act != NULL && (ultraAttack || isWarrior) && - unitSignalledToAttack == false) { - bool shouldAttack = true; - if(unit->getType()->hasSkillClass(scHarvest)) { - shouldAttack = (attackerWorkersHarvestingCount > minWorkerAttackersHarvesting); - if(shouldAttack == false) { - attackerWorkersHarvestingCount++; - } - } - - // Mega CPU does not send ( far away ) units which are currently producing something - if(aiInterface->getControlType() == ctCpuMega || aiInterface->getControlType() == ctNetworkCpuMega){ - if(!isWarrior ){ - if(!productionInProgress){ - shouldAttack= false; - //printf("no attack \n "); - } - } - } - if(shouldAttack) { - if(unitGroupCommandId == -1) { - unitGroupCommandId = aiInterface->getWorld()->getNextCommandGroupId(); - } - - aiInterface->giveCommand(i, act, pos, unitGroupCommandId); - } - } +void Ai::massiveAttack(const Vec2i &pos, Field field, bool ultraAttack) { + int producerWarriorCount = 0; + int maxProducerWarriors = random.randRange(1, 11); + int unitCount = aiInterface->getMyUnitCount(); + int unitGroupCommandId = -1; + + int attackerWorkersHarvestingCount = 0; + for (int i = 0; i < unitCount; ++i) { + bool isWarrior = false; + bool productionInProgress = false; + const Unit *unit = aiInterface->getMyUnit(i); + const AttackCommandType *act = + unit->getType()->getFirstAttackCommand(field); + + if (aiInterface->getControlType() == ctCpuMega || + aiInterface->getControlType() == ctNetworkCpuMega) { + if (producerWarriorCount > maxProducerWarriors) { + if (unit->getCommandSize() > 0 && + unit->getCurrCommand()->getCommandType() != NULL && + (unit->getCurrCommand()->getCommandType()->getClass() == ccBuild || + unit->getCurrCommand()->getCommandType()->getClass() == ccMorph || + unit->getCurrCommand()->getCommandType()->getClass() == + ccProduce)) { + productionInProgress = true; + isWarrior = false; + producerWarriorCount++; + } else { + isWarrior = !unit->getType()->hasCommandClass(ccHarvest); + } + + } else { + isWarrior = !unit->getType()->hasCommandClass(ccHarvest) && + !unit->getType()->hasCommandClass(ccProduce); + } + } else { + isWarrior = !unit->getType()->hasCommandClass(ccHarvest) && + !unit->getType()->hasCommandClass(ccProduce); } - if( aiInterface->getControlType() == ctCpuEasy || - aiInterface->getControlType() == ctNetworkCpuEasy) { - minWarriors += minMinWarriorsExpandCpuEasy; - } - else if(aiInterface->getControlType() == ctCpuMega || - aiInterface->getControlType() == ctNetworkCpuMega) { - minWarriors += minMinWarriorsExpandCpuMega; - if(minWarriors > maxMinWarriors-1 || randomMinWarriorsReached) { - randomMinWarriorsReached=true; - minWarriors=random.randRange(maxMinWarriors-10, maxMinWarriors*2); - } - } - else if(minWarriors < maxMinWarriors) { - if(aiInterface->getControlType() == ctCpuUltra || - aiInterface->getControlType() == ctNetworkCpuUltra) { - minWarriors += minMinWarriorsExpandCpuUltra; - } - else { - minWarriors+= minMinWarriorsExpandCpuNormal; - } - } - aiInterface->printLog(2, "Massive attack to pos: "+ intToStr(pos.x)+", "+intToStr(pos.y)+"\n"); + bool alreadyAttacking = (unit->getCurrSkill()->getClass() == scAttack); + + bool unitSignalledToAttack = false; + if (alreadyAttacking == false && unit->getType()->hasSkillClass(scAttack) && + (aiInterface->getControlType() == ctCpuUltra || + aiInterface->getControlType() == ctCpuMega || + aiInterface->getControlType() == ctNetworkCpuUltra || + aiInterface->getControlType() == ctNetworkCpuMega)) { + // printf("~~~~~~~~ Unit [%s - %d] checking if unit is being + // attacked\n",unit->getFullName().c_str(),unit->getId()); + + std::pair beingAttacked = + aiInterface->getWorld()->getUnitUpdater()->unitBeingAttacked(unit); + if (beingAttacked.first == true) { + Unit *enemy = beingAttacked.second; + const AttackCommandType *act_forenemy = + unit->getType()->getFirstAttackCommand(enemy->getCurrField()); + + // printf("~~~~~~~~ Unit [%s - %d] attacked by enemy [%s - %d] + // act_forenemy [%p] enemy->getCurrField() = + // %d\n",unit->getFullName().c_str(),unit->getId(),enemy->getFullName().c_str(),enemy->getId(),act_forenemy,enemy->getCurrField()); + + if (act_forenemy != NULL) { + bool shouldAttack = true; + if (unit->getType()->hasSkillClass(scHarvest)) { + shouldAttack = + (attackerWorkersHarvestingCount > minWorkerAttackersHarvesting); + if (shouldAttack == false) { + attackerWorkersHarvestingCount++; + } + } + if (shouldAttack) { + if (unitGroupCommandId == -1) { + unitGroupCommandId = + aiInterface->getWorld()->getNextCommandGroupId(); + } + + aiInterface->giveCommand(i, act_forenemy, + beingAttacked.second->getPos(), + unitGroupCommandId); + unitSignalledToAttack = true; + } + } else { + const AttackStoppedCommandType *asct_forenemy = + unit->getType()->getFirstAttackStoppedCommand( + enemy->getCurrField()); + // printf("~~~~~~~~ Unit [%s - %d] found enemy [%s - %d] asct_forenemy + // [%p] enemy->getCurrField() = + // %d\n",unit->getFullName().c_str(),unit->getId(),enemy->getFullName().c_str(),enemy->getId(),asct_forenemy,enemy->getCurrField()); + if (asct_forenemy != NULL) { + bool shouldAttack = true; + if (unit->getType()->hasSkillClass(scHarvest)) { + shouldAttack = (attackerWorkersHarvestingCount > + minWorkerAttackersHarvesting); + if (shouldAttack == false) { + attackerWorkersHarvestingCount++; + } + } + if (shouldAttack) { + // printf("~~~~~~~~ + // Unit [%s - %d] WILL AttackStoppedCommand [%s - %d]\n", + // unit->getFullName().c_str(), + // unit->getId(), enemy->getFullName().c_str(), enemy->getId()); + + if (unitGroupCommandId == -1) { + unitGroupCommandId = + aiInterface->getWorld()->getNextCommandGroupId(); + } + + aiInterface->giveCommand(i, asct_forenemy, + beingAttacked.second->getCenteredPos(), + unitGroupCommandId); + unitSignalledToAttack = true; + } + } + } + } + } + if (alreadyAttacking == false && act != NULL && + (ultraAttack || isWarrior) && unitSignalledToAttack == false) { + bool shouldAttack = true; + if (unit->getType()->hasSkillClass(scHarvest)) { + shouldAttack = + (attackerWorkersHarvestingCount > minWorkerAttackersHarvesting); + if (shouldAttack == false) { + attackerWorkersHarvestingCount++; + } + } + + // Mega CPU does not send ( far away ) units which are currently producing + // something + if (aiInterface->getControlType() == ctCpuMega || + aiInterface->getControlType() == ctNetworkCpuMega) { + if (!isWarrior) { + if (!productionInProgress) { + shouldAttack = false; + // printf("no attack \n "); + } + } + } + if (shouldAttack) { + if (unitGroupCommandId == -1) { + unitGroupCommandId = aiInterface->getWorld()->getNextCommandGroupId(); + } + + aiInterface->giveCommand(i, act, pos, unitGroupCommandId); + } + } + } + + if (aiInterface->getControlType() == ctCpuEasy || + aiInterface->getControlType() == ctNetworkCpuEasy) { + minWarriors += minMinWarriorsExpandCpuEasy; + } else if (aiInterface->getControlType() == ctCpuMega || + aiInterface->getControlType() == ctNetworkCpuMega) { + minWarriors += minMinWarriorsExpandCpuMega; + if (minWarriors > maxMinWarriors - 1 || randomMinWarriorsReached) { + randomMinWarriorsReached = true; + minWarriors = random.randRange(maxMinWarriors - 10, maxMinWarriors * 2); + } + } else if (minWarriors < maxMinWarriors) { + if (aiInterface->getControlType() == ctCpuUltra || + aiInterface->getControlType() == ctNetworkCpuUltra) { + minWarriors += minMinWarriorsExpandCpuUltra; + } else { + minWarriors += minMinWarriorsExpandCpuNormal; + } + } + aiInterface->printLog(2, "Massive attack to pos: " + intToStr(pos.x) + ", " + + intToStr(pos.y) + "\n"); } void Ai::returnBase(int unitIndex) { - Vec2i pos; - //std::pair r(crFailUndefined,""); - //aiInterface->getFactionIndex(); - pos= Vec2i( - random.randRange(-villageRadius, villageRadius), - random.randRange(-villageRadius, villageRadius)) + - getRandomHomePosition(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - //r= aiInterface->giveCommand(unitIndex, ccMove, pos); - aiInterface->giveCommand(unitIndex, ccMove, pos); - - //aiInterface->printLog(1, "Order return to base pos:" + intToStr(pos.x)+", "+intToStr(pos.y)+": "+rrToStr(r)+"\n"); + Vec2i pos; + // std::pair r(crFailUndefined,""); + // aiInterface->getFactionIndex(); + pos = Vec2i(random.randRange(-villageRadius, villageRadius), + random.randRange(-villageRadius, villageRadius)) + + getRandomHomePosition(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + // r= aiInterface->giveCommand(unitIndex, ccMove, pos); + aiInterface->giveCommand(unitIndex, ccMove, pos); + + // aiInterface->printLog(1, "Order return to base pos:" + intToStr(pos.x)+", + // "+intToStr(pos.y)+": "+rrToStr(r)+"\n"); } void Ai::harvest(int unitIndex) { - const ResourceType *rt= getNeededResource(unitIndex); - if(rt != NULL) { - const HarvestCommandType *hct= aiInterface->getMyUnit(unitIndex)->getType()->getFirstHarvestCommand(rt,aiInterface->getMyUnit(unitIndex)->getFaction()); - - Vec2i resPos; - if(hct != NULL && aiInterface->getNearestSightedResource(rt, aiInterface->getHomeLocation(), resPos, false)) { - resPos= resPos+Vec2i(random.randRange(-2, 2), random.randRange(-2, 2)); - aiInterface->giveCommand(unitIndex, hct, resPos, -1); - //aiInterface->printLog(4, "Order harvest pos:" + intToStr(resPos.x)+", "+intToStr(resPos.y)+": "+rrToStr(r)+"\n"); - } - } + const ResourceType *rt = getNeededResource(unitIndex); + if (rt != NULL) { + const HarvestCommandType *hct = + aiInterface->getMyUnit(unitIndex)->getType()->getFirstHarvestCommand( + rt, aiInterface->getMyUnit(unitIndex)->getFaction()); + + Vec2i resPos; + if (hct != NULL && aiInterface->getNearestSightedResource( + rt, aiInterface->getHomeLocation(), resPos, false)) { + resPos = resPos + Vec2i(random.randRange(-2, 2), random.randRange(-2, 2)); + aiInterface->giveCommand(unitIndex, hct, resPos, -1); + // aiInterface->printLog(4, "Order harvest pos:" + intToStr(resPos.x)+", + // "+intToStr(resPos.y)+": "+rrToStr(r)+"\n"); + } + } } bool Ai::haveBlockedUnits() { - Chrono chrono; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [START]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis()); - - int unitCount = aiInterface->getMyUnitCount(); - Map *map = aiInterface->getMap(); - //If there is no close store - for(int j=0; j < unitCount; ++j) { - const Unit *u= aiInterface->getMyUnit(j); - const UnitType *ut= u->getType(); - - // If this building is a store - if(u->isAlive() && ut->isMobile() && u->getPath() != NULL && (u->getPath()->isBlocked() || u->getPath()->getBlockCount())) { - Vec2i unitPos = u->getPosNotThreadSafe(); - - //printf("#1 AI found blocked unit [%d - %s]\n",u->getId(),u->getFullName().c_str()); - - int failureCount = 0; - int cellCount = 0; - - for(int i = -1; i <= 1; ++i) { - for(int j = -1; j <= 1; ++j) { - Vec2i pos = unitPos + Vec2i(i, j); - if(map->isInside(pos) && map->isInsideSurface(map->toSurfCoords(pos))) { - if(pos != unitPos) { - bool canUnitMoveToCell = map->aproxCanMove(u, unitPos, pos); - if(canUnitMoveToCell == false) { - failureCount++; - } - cellCount++; - } - } - } - } - bool unitImmediatelyBlocked = (failureCount == cellCount); - //printf("#1 unitImmediatelyBlocked = %d, failureCount = %d, cellCount = %d\n",unitImmediatelyBlocked,failureCount,cellCount); - - if(unitImmediatelyBlocked) { - //printf("#1 AI unit IS BLOCKED [%d - %s]\n",u->getId(),u->getFullName().c_str()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [START]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis()); - return true; - } - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [START]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis()); - return false; + Chrono chrono; + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) + chrono.start(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld [START]\n", + __FILE__, __FUNCTION__, __LINE__, + chrono.getMillis()); + + int unitCount = aiInterface->getMyUnitCount(); + Map *map = aiInterface->getMap(); + // If there is no close store + for (int j = 0; j < unitCount; ++j) { + const Unit *u = aiInterface->getMyUnit(j); + const UnitType *ut = u->getType(); + + // If this building is a store + if (u->isAlive() && ut->isMobile() && u->getPath() != NULL && + (u->getPath()->isBlocked() || u->getPath()->getBlockCount())) { + Vec2i unitPos = u->getPosNotThreadSafe(); + + // printf("#1 AI found blocked unit [%d - + // %s]\n",u->getId(),u->getFullName().c_str()); + + int failureCount = 0; + int cellCount = 0; + + for (int i = -1; i <= 1; ++i) { + for (int j = -1; j <= 1; ++j) { + Vec2i pos = unitPos + Vec2i(i, j); + if (map->isInside(pos) && + map->isInsideSurface(map->toSurfCoords(pos))) { + if (pos != unitPos) { + bool canUnitMoveToCell = map->aproxCanMove(u, unitPos, pos); + if (canUnitMoveToCell == false) { + failureCount++; + } + cellCount++; + } + } + } + } + bool unitImmediatelyBlocked = (failureCount == cellCount); + // printf("#1 unitImmediatelyBlocked = %d, failureCount = %d, cellCount = + // %d\n",unitImmediatelyBlocked,failureCount,cellCount); + + if (unitImmediatelyBlocked) { + // printf("#1 AI unit IS BLOCKED [%d - + // %s]\n",u->getId(),u->getFullName().c_str()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld [START]\n", __FILE__, + __FUNCTION__, __LINE__, chrono.getMillis()); + return true; + } + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld [START]\n", + __FILE__, __FUNCTION__, __LINE__, + chrono.getMillis()); + return false; } -bool Ai::getAdjacentUnits(std::map > &signalAdjacentUnits, const Unit *unit) { - //printf("In getAdjacentUnits...\n"); - - bool result = false; - Map *map = aiInterface->getMap(); - Vec2i unitPos = unit->getPosNotThreadSafe(); - for(int i = -1; i <= 1; ++i) { - for(int j = -1; j <= 1; ++j) { - Vec2i pos = unitPos + Vec2i(i, j); - if(map->isInside(pos) && map->isInsideSurface(map->toSurfCoords(pos))) { - if(pos != unitPos) { - Unit *adjacentUnit = map->getCell(pos)->getUnit(unit->getCurrField()); - if(adjacentUnit != NULL && adjacentUnit->getFactionIndex() == unit->getFactionIndex()) { - if(adjacentUnit->getType()->isMobile() && adjacentUnit->getPath() != NULL) { - //signalAdjacentUnits.push_back(adjacentUnit); - float dist = unitPos.dist(adjacentUnit->getPos()); - - std::map >::iterator iterFind1 = signalAdjacentUnits.find(dist); - if(iterFind1 == signalAdjacentUnits.end()) { - signalAdjacentUnits[dist][adjacentUnit->getId()] = adjacentUnit; - - getAdjacentUnits(signalAdjacentUnits, adjacentUnit); - result = true; - } - else { - std::map::iterator iterFind2 = iterFind1->second.find(adjacentUnit->getId()); - if(iterFind2 == iterFind1->second.end()) { - signalAdjacentUnits[dist][adjacentUnit->getId()] = adjacentUnit; - getAdjacentUnits(signalAdjacentUnits, adjacentUnit); - result = true; - } - } - } - } - } - } - } - } - return result; +bool Ai::getAdjacentUnits( + std::map> &signalAdjacentUnits, + const Unit *unit) { + // printf("In getAdjacentUnits...\n"); + + bool result = false; + Map *map = aiInterface->getMap(); + Vec2i unitPos = unit->getPosNotThreadSafe(); + for (int i = -1; i <= 1; ++i) { + for (int j = -1; j <= 1; ++j) { + Vec2i pos = unitPos + Vec2i(i, j); + if (map->isInside(pos) && map->isInsideSurface(map->toSurfCoords(pos))) { + if (pos != unitPos) { + Unit *adjacentUnit = map->getCell(pos)->getUnit(unit->getCurrField()); + if (adjacentUnit != NULL && + adjacentUnit->getFactionIndex() == unit->getFactionIndex()) { + if (adjacentUnit->getType()->isMobile() && + adjacentUnit->getPath() != NULL) { + // signalAdjacentUnits.push_back(adjacentUnit); + float dist = unitPos.dist(adjacentUnit->getPos()); + + std::map>::iterator iterFind1 = + signalAdjacentUnits.find(dist); + if (iterFind1 == signalAdjacentUnits.end()) { + signalAdjacentUnits[dist][adjacentUnit->getId()] = adjacentUnit; + + getAdjacentUnits(signalAdjacentUnits, adjacentUnit); + result = true; + } else { + std::map::iterator iterFind2 = + iterFind1->second.find(adjacentUnit->getId()); + if (iterFind2 == iterFind1->second.end()) { + signalAdjacentUnits[dist][adjacentUnit->getId()] = + adjacentUnit; + getAdjacentUnits(signalAdjacentUnits, adjacentUnit); + result = true; + } + } + } + } + } + } + } + } + return result; } void Ai::unblockUnits() { - Chrono chrono; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [START]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis()); - - int unitCount = aiInterface->getMyUnitCount(); - Map *map = aiInterface->getMap(); - // Find blocked units and move surrounding units out of the way - std::map > signalAdjacentUnits; - for(int idx=0; idx < unitCount; ++idx) { - const Unit *u= aiInterface->getMyUnit(idx); - const UnitType *ut= u->getType(); - - // If this building is a store - if(u->isAlive() && ut->isMobile() && u->getPath() != NULL && (u->getPath()->isBlocked() || u->getPath()->getBlockCount())) { - Vec2i unitPos = u->getPosNotThreadSafe(); - - //printf("#2 AI found blocked unit [%d - %s]\n",u->getId(),u->getFullName().c_str()); - - //int failureCount = 0; - //int cellCount = 0; - - for(int i = -1; i <= 1; ++i) { - for(int j = -1; j <= 1; ++j) { - Vec2i pos = unitPos + Vec2i(i, j); - if(map->isInside(pos) && map->isInsideSurface(map->toSurfCoords(pos))) { - if(pos != unitPos) { - bool canUnitMoveToCell = map->aproxCanMove(u, unitPos, pos); - if(canUnitMoveToCell == false) { - //failureCount++; - getAdjacentUnits(signalAdjacentUnits, u); - } - //cellCount++; - } - } - } - } - //bool unitImmediatelyBlocked = (failureCount == cellCount); - //printf("#2 unitImmediatelyBlocked = %d, failureCount = %d, cellCount = %d, signalAdjacentUnits.size() = %d\n",unitImmediatelyBlocked,failureCount,cellCount,signalAdjacentUnits.size()); - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [START]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis()); - - if(signalAdjacentUnits.empty() == false) { - //printf("#2 AI units ARE BLOCKED about to unblock\n"); - - int unitGroupCommandId = -1; - - for(std::map >::reverse_iterator iterMap = signalAdjacentUnits.rbegin(); - iterMap != signalAdjacentUnits.rend(); ++iterMap) { - - for(std::map::iterator iterMap2 = iterMap->second.begin(); - iterMap2 != iterMap->second.end(); ++iterMap2) { - //int idx = iterMap2->first; - const Unit *adjacentUnit = iterMap2->second; - if(adjacentUnit != NULL && adjacentUnit->getType()->getFirstCtOfClass(ccMove) != NULL) { - const CommandType *ct = adjacentUnit->getType()->getFirstCtOfClass(ccMove); - - for(int moveAttempt = 1; moveAttempt <= villageRadius; ++moveAttempt) { - Vec2i pos= Vec2i( - random.randRange(-villageRadius*2, villageRadius*2), - random.randRange(-villageRadius*2, villageRadius*2)) + - adjacentUnit->getPosNotThreadSafe(); - - bool canUnitMoveToCell = map->aproxCanMove(adjacentUnit, adjacentUnit->getPosNotThreadSafe(), pos); - if(canUnitMoveToCell == true) { - - if(ct != NULL) { - if(unitGroupCommandId == -1) { - unitGroupCommandId = aiInterface->getWorld()->getNextCommandGroupId(); - } - - //std::pair r = aiInterface->giveCommand(adjacentUnit,ct, pos, unitGroupCommandId); - aiInterface->giveCommand(adjacentUnit,ct, pos, unitGroupCommandId); - } - } - } - } - } - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [START]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis()); -} + Chrono chrono; + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) + chrono.start(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld [START]\n", + __FILE__, __FUNCTION__, __LINE__, + chrono.getMillis()); + + int unitCount = aiInterface->getMyUnitCount(); + Map *map = aiInterface->getMap(); + // Find blocked units and move surrounding units out of the way + std::map> signalAdjacentUnits; + for (int idx = 0; idx < unitCount; ++idx) { + const Unit *u = aiInterface->getMyUnit(idx); + const UnitType *ut = u->getType(); + + // If this building is a store + if (u->isAlive() && ut->isMobile() && u->getPath() != NULL && + (u->getPath()->isBlocked() || u->getPath()->getBlockCount())) { + Vec2i unitPos = u->getPosNotThreadSafe(); + + // printf("#2 AI found blocked unit [%d - + // %s]\n",u->getId(),u->getFullName().c_str()); + + // int failureCount = 0; + // int cellCount = 0; + + for (int i = -1; i <= 1; ++i) { + for (int j = -1; j <= 1; ++j) { + Vec2i pos = unitPos + Vec2i(i, j); + if (map->isInside(pos) && + map->isInsideSurface(map->toSurfCoords(pos))) { + if (pos != unitPos) { + bool canUnitMoveToCell = map->aproxCanMove(u, unitPos, pos); + if (canUnitMoveToCell == false) { + // failureCount++; + getAdjacentUnits(signalAdjacentUnits, u); + } + // cellCount++; + } + } + } + } + // bool unitImmediatelyBlocked = (failureCount == cellCount); + // printf("#2 unitImmediatelyBlocked = %d, failureCount = %d, cellCount = + // %d, signalAdjacentUnits.size() = + // %d\n",unitImmediatelyBlocked,failureCount,cellCount,signalAdjacentUnits.size()); + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld [START]\n", + __FILE__, __FUNCTION__, __LINE__, + chrono.getMillis()); + + if (signalAdjacentUnits.empty() == false) { + // printf("#2 AI units ARE BLOCKED about to unblock\n"); + + int unitGroupCommandId = -1; + + for (std::map>::reverse_iterator + iterMap = signalAdjacentUnits.rbegin(); + iterMap != signalAdjacentUnits.rend(); ++iterMap) { + + for (std::map::iterator iterMap2 = + iterMap->second.begin(); + iterMap2 != iterMap->second.end(); ++iterMap2) { + // int idx = iterMap2->first; + const Unit *adjacentUnit = iterMap2->second; + if (adjacentUnit != NULL && + adjacentUnit->getType()->getFirstCtOfClass(ccMove) != NULL) { + const CommandType *ct = + adjacentUnit->getType()->getFirstCtOfClass(ccMove); + + for (int moveAttempt = 1; moveAttempt <= villageRadius; + ++moveAttempt) { + Vec2i pos = + Vec2i(random.randRange(-villageRadius * 2, villageRadius * 2), + random.randRange(-villageRadius * 2, villageRadius * 2)) + + adjacentUnit->getPosNotThreadSafe(); + + bool canUnitMoveToCell = map->aproxCanMove( + adjacentUnit, adjacentUnit->getPosNotThreadSafe(), pos); + if (canUnitMoveToCell == true) { + + if (ct != NULL) { + if (unitGroupCommandId == -1) { + unitGroupCommandId = + aiInterface->getWorld()->getNextCommandGroupId(); + } -bool Ai::outputAIBehaviourToConsole() const { - return false; + // std::pair r = + // aiInterface->giveCommand(adjacentUnit,ct, pos, + // unitGroupCommandId); + aiInterface->giveCommand(adjacentUnit, ct, pos, + unitGroupCommandId); + } + } + } + } + } + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld [START]\n", + __FILE__, __FUNCTION__, __LINE__, + chrono.getMillis()); } +bool Ai::outputAIBehaviourToConsole() const { return false; } + void Ai::saveGame(XmlNode *rootNode) const { - std::map mapTagReplacements; - XmlNode *aiNode = rootNode->addChild("Ai"); - -// AiInterface *aiInterface; -// AiRules aiRules; -// int startLoc; - aiNode->addAttribute("startLoc",intToStr(startLoc), mapTagReplacements); -// bool randomMinWarriorsReached; - aiNode->addAttribute("randomMinWarriorsReached",intToStr(randomMinWarriorsReached), mapTagReplacements); -// Tasks tasks; - for(Tasks::const_iterator it = tasks.begin(); it != tasks.end(); ++it) { - (*it)->saveGame(aiNode); - } -// Positions expansionPositions; - for(Positions::const_iterator it = expansionPositions.begin(); it != expansionPositions.end(); ++it) { - XmlNode *expansionPositionsNode = aiNode->addChild("expansionPositions"); - expansionPositionsNode->addAttribute("pos",(*it).getString(), mapTagReplacements); - } - -// RandomGen random; - aiNode->addAttribute("random",intToStr(random.getLastNumber()), mapTagReplacements); -// std::map factionSwitchTeamRequestCount; - -// int maxBuildRadius; - aiNode->addAttribute("maxBuildRadius",intToStr(maxBuildRadius), mapTagReplacements); -// int minMinWarriors; - aiNode->addAttribute("minMinWarriors",intToStr(minMinWarriors), mapTagReplacements); -// int minMinWarriorsExpandCpuEasy; - aiNode->addAttribute("minMinWarriorsExpandCpuEasy",intToStr(minMinWarriorsExpandCpuEasy), mapTagReplacements); -// int minMinWarriorsExpandCpuMega; - aiNode->addAttribute("minMinWarriorsExpandCpuMega",intToStr(minMinWarriorsExpandCpuMega), mapTagReplacements); -// int minMinWarriorsExpandCpuUltra; - aiNode->addAttribute("minMinWarriorsExpandCpuUltra",intToStr(minMinWarriorsExpandCpuUltra), mapTagReplacements); -// int minMinWarriorsExpandCpuNormal; - aiNode->addAttribute("minMinWarriorsExpandCpuNormal",intToStr(minMinWarriorsExpandCpuNormal), mapTagReplacements); -// int maxMinWarriors; - aiNode->addAttribute("maxMinWarriors",intToStr(maxMinWarriors), mapTagReplacements); -// int maxExpansions; - aiNode->addAttribute("maxExpansions",intToStr(maxExpansions), mapTagReplacements); -// int villageRadius; - aiNode->addAttribute("villageRadius",intToStr(villageRadius), mapTagReplacements); -// int scoutResourceRange; - aiNode->addAttribute("scoutResourceRange",intToStr(scoutResourceRange), mapTagReplacements); -// int minWorkerAttackersHarvesting; - aiNode->addAttribute("minWorkerAttackersHarvesting",intToStr(minWorkerAttackersHarvesting), mapTagReplacements); + std::map mapTagReplacements; + XmlNode *aiNode = rootNode->addChild("Ai"); + + // AiInterface *aiInterface; + // AiRules aiRules; + // int startLoc; + aiNode->addAttribute("startLoc", intToStr(startLoc), mapTagReplacements); + // bool randomMinWarriorsReached; + aiNode->addAttribute("randomMinWarriorsReached", + intToStr(randomMinWarriorsReached), mapTagReplacements); + // Tasks tasks; + for (Tasks::const_iterator it = tasks.begin(); it != tasks.end(); ++it) { + (*it)->saveGame(aiNode); + } + // Positions expansionPositions; + for (Positions::const_iterator it = expansionPositions.begin(); + it != expansionPositions.end(); ++it) { + XmlNode *expansionPositionsNode = aiNode->addChild("expansionPositions"); + expansionPositionsNode->addAttribute("pos", (*it).getString(), + mapTagReplacements); + } + + // RandomGen random; + aiNode->addAttribute("random", intToStr(random.getLastNumber()), + mapTagReplacements); + // std::map factionSwitchTeamRequestCount; + + // int maxBuildRadius; + aiNode->addAttribute("maxBuildRadius", intToStr(maxBuildRadius), + mapTagReplacements); + // int minMinWarriors; + aiNode->addAttribute("minMinWarriors", intToStr(minMinWarriors), + mapTagReplacements); + // int minMinWarriorsExpandCpuEasy; + aiNode->addAttribute("minMinWarriorsExpandCpuEasy", + intToStr(minMinWarriorsExpandCpuEasy), + mapTagReplacements); + // int minMinWarriorsExpandCpuMega; + aiNode->addAttribute("minMinWarriorsExpandCpuMega", + intToStr(minMinWarriorsExpandCpuMega), + mapTagReplacements); + // int minMinWarriorsExpandCpuUltra; + aiNode->addAttribute("minMinWarriorsExpandCpuUltra", + intToStr(minMinWarriorsExpandCpuUltra), + mapTagReplacements); + // int minMinWarriorsExpandCpuNormal; + aiNode->addAttribute("minMinWarriorsExpandCpuNormal", + intToStr(minMinWarriorsExpandCpuNormal), + mapTagReplacements); + // int maxMinWarriors; + aiNode->addAttribute("maxMinWarriors", intToStr(maxMinWarriors), + mapTagReplacements); + // int maxExpansions; + aiNode->addAttribute("maxExpansions", intToStr(maxExpansions), + mapTagReplacements); + // int villageRadius; + aiNode->addAttribute("villageRadius", intToStr(villageRadius), + mapTagReplacements); + // int scoutResourceRange; + aiNode->addAttribute("scoutResourceRange", intToStr(scoutResourceRange), + mapTagReplacements); + // int minWorkerAttackersHarvesting; + aiNode->addAttribute("minWorkerAttackersHarvesting", + intToStr(minWorkerAttackersHarvesting), + mapTagReplacements); } void Ai::loadGame(const XmlNode *rootNode, Faction *faction) { - const XmlNode *aiNode = rootNode->getChild("Ai"); - - startLoc = aiNode->getAttribute("startLoc")->getIntValue(); - randomMinWarriorsReached = aiNode->getAttribute("randomMinWarriorsReached")->getIntValue() != 0; - - vector taskNodeList = aiNode->getChildList("Task"); - for(unsigned int i = 0; i < taskNodeList.size(); ++i) { - XmlNode *taskNode = taskNodeList[i]; - TaskClass taskClass = static_cast(taskNode->getAttribute("taskClass")->getIntValue()); - switch(taskClass) { - case tcProduce: - { - ProduceTask *newTask = ProduceTask::loadGame(taskNode, faction); - tasks.push_back(newTask); - } - break; - case tcBuild: - { - BuildTask *newTask = BuildTask::loadGame(taskNode, faction); - tasks.push_back(newTask); - } - break; - case tcUpgrade: - { - UpgradeTask *newTask = UpgradeTask::loadGame(taskNode, faction); - tasks.push_back(newTask); - } - break; - } - } - - vector expansionPositionsNodeList = aiNode->getChildList("expansionPositions"); - for(unsigned int i = 0; i < expansionPositionsNodeList.size(); ++i) { - XmlNode *expansionPositionsNode = expansionPositionsNodeList[i]; - Vec2i pos = Vec2i::strToVec2(expansionPositionsNode->getAttribute("pos")->getValue()); - expansionPositions.push_back(pos); - } - - // RandomGen random; - random.setLastNumber(aiNode->getAttribute("random")->getIntValue()); - // std::map factionSwitchTeamRequestCount; - - // int maxBuildRadius; - maxBuildRadius = aiNode->getAttribute("maxBuildRadius")->getIntValue(); - // int minMinWarriors; - minMinWarriors = aiNode->getAttribute("minMinWarriors")->getIntValue(); - // int minMinWarriorsExpandCpuEasy; - minMinWarriorsExpandCpuEasy = aiNode->getAttribute("minMinWarriorsExpandCpuEasy")->getIntValue(); - // int minMinWarriorsExpandCpuMega; - minMinWarriorsExpandCpuMega = aiNode->getAttribute("minMinWarriorsExpandCpuMega")->getIntValue(); - // int minMinWarriorsExpandCpuUltra; - minMinWarriorsExpandCpuUltra = aiNode->getAttribute("minMinWarriorsExpandCpuUltra")->getIntValue(); - // int minMinWarriorsExpandCpuNormal; - minMinWarriorsExpandCpuNormal = aiNode->getAttribute("minMinWarriorsExpandCpuNormal")->getIntValue(); - // int maxMinWarriors; - maxMinWarriors = aiNode->getAttribute("maxMinWarriors")->getIntValue(); - // int maxExpansions; - maxExpansions = aiNode->getAttribute("maxExpansions")->getIntValue(); - // int villageRadius; - villageRadius = aiNode->getAttribute("villageRadius")->getIntValue(); - // int scoutResourceRange; - scoutResourceRange = aiNode->getAttribute("scoutResourceRange")->getIntValue(); - // int minWorkerAttackersHarvesting; - minWorkerAttackersHarvesting = aiNode->getAttribute("minWorkerAttackersHarvesting")->getIntValue(); + const XmlNode *aiNode = rootNode->getChild("Ai"); + + startLoc = aiNode->getAttribute("startLoc")->getIntValue(); + randomMinWarriorsReached = + aiNode->getAttribute("randomMinWarriorsReached")->getIntValue() != 0; + + vector taskNodeList = aiNode->getChildList("Task"); + for (unsigned int i = 0; i < taskNodeList.size(); ++i) { + XmlNode *taskNode = taskNodeList[i]; + TaskClass taskClass = static_cast( + taskNode->getAttribute("taskClass")->getIntValue()); + switch (taskClass) { + case tcProduce: { + ProduceTask *newTask = ProduceTask::loadGame(taskNode, faction); + tasks.push_back(newTask); + } break; + case tcBuild: { + BuildTask *newTask = BuildTask::loadGame(taskNode, faction); + tasks.push_back(newTask); + } break; + case tcUpgrade: { + UpgradeTask *newTask = UpgradeTask::loadGame(taskNode, faction); + tasks.push_back(newTask); + } break; + } + } + + vector expansionPositionsNodeList = + aiNode->getChildList("expansionPositions"); + for (unsigned int i = 0; i < expansionPositionsNodeList.size(); ++i) { + XmlNode *expansionPositionsNode = expansionPositionsNodeList[i]; + Vec2i pos = Vec2i::strToVec2( + expansionPositionsNode->getAttribute("pos")->getValue()); + expansionPositions.push_back(pos); + } + + // RandomGen random; + random.setLastNumber(aiNode->getAttribute("random")->getIntValue()); + // std::map factionSwitchTeamRequestCount; + + // int maxBuildRadius; + maxBuildRadius = aiNode->getAttribute("maxBuildRadius")->getIntValue(); + // int minMinWarriors; + minMinWarriors = aiNode->getAttribute("minMinWarriors")->getIntValue(); + // int minMinWarriorsExpandCpuEasy; + minMinWarriorsExpandCpuEasy = + aiNode->getAttribute("minMinWarriorsExpandCpuEasy")->getIntValue(); + // int minMinWarriorsExpandCpuMega; + minMinWarriorsExpandCpuMega = + aiNode->getAttribute("minMinWarriorsExpandCpuMega")->getIntValue(); + // int minMinWarriorsExpandCpuUltra; + minMinWarriorsExpandCpuUltra = + aiNode->getAttribute("minMinWarriorsExpandCpuUltra")->getIntValue(); + // int minMinWarriorsExpandCpuNormal; + minMinWarriorsExpandCpuNormal = + aiNode->getAttribute("minMinWarriorsExpandCpuNormal")->getIntValue(); + // int maxMinWarriors; + maxMinWarriors = aiNode->getAttribute("maxMinWarriors")->getIntValue(); + // int maxExpansions; + maxExpansions = aiNode->getAttribute("maxExpansions")->getIntValue(); + // int villageRadius; + villageRadius = aiNode->getAttribute("villageRadius")->getIntValue(); + // int scoutResourceRange; + scoutResourceRange = + aiNode->getAttribute("scoutResourceRange")->getIntValue(); + // int minWorkerAttackersHarvesting; + minWorkerAttackersHarvesting = + aiNode->getAttribute("minWorkerAttackersHarvesting")->getIntValue(); } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/ai/ai.h b/source/glest_game/ai/ai.h index 518be0b7a..ca4d2efc7 100644 --- a/source/glest_game/ai/ai.h +++ b/source/glest_game/ai/ai.h @@ -3,245 +3,247 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== #ifndef _GLEST_GAME_AI_H_ #define _GLEST_GAME_AI_H_ -#include #include +#include -#include "world.h" -#include "commander.h" #include "command.h" -#include "randomgen.h" +#include "commander.h" #include "leak_dumper.h" +#include "randomgen.h" +#include "world.h" +using Shared::Util::RandomGen; using std::deque; -using std::vector; using std::list; -using Shared::Util::RandomGen; +using std::vector; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { class AiInterface; class AiRule; // ===================================================== -// class Task +// class Task // /// An action that has to be performed by the IA // ===================================================== -enum TaskClass{ - tcProduce, - tcBuild, - tcUpgrade -}; +enum TaskClass { tcProduce, tcBuild, tcUpgrade }; -class Task{ +class Task { protected: - TaskClass taskClass; + TaskClass taskClass; public: - Task(); - virtual ~Task(){} - TaskClass getClass() const {return taskClass;} - virtual string toString() const= 0; + Task(); + virtual ~Task() {} + TaskClass getClass() const { return taskClass; } + virtual string toString() const = 0; - virtual void saveGame(XmlNode *rootNode) const = 0; + virtual void saveGame(XmlNode *rootNode) const = 0; }; // ==================== ProduceTask ==================== -class ProduceTask: public Task{ +class ProduceTask : public Task { private: - UnitClass unitClass; - const UnitType *unitType; - const ResourceType *resourceType; + UnitClass unitClass; + const UnitType *unitType; + const ResourceType *resourceType; + + ProduceTask(); - ProduceTask(); public: - explicit ProduceTask(UnitClass unitClass); - explicit ProduceTask(const UnitType *unitType); - explicit ProduceTask(const ResourceType *resourceType); - - UnitClass getUnitClass() const {return unitClass;} - const UnitType *getUnitType() const {return unitType;} - const ResourceType *getResourceType() const {return resourceType;} - virtual string toString() const; - - virtual void saveGame(XmlNode *rootNode) const; - static ProduceTask * loadGame(const XmlNode *rootNode, Faction *faction); + explicit ProduceTask(UnitClass unitClass); + explicit ProduceTask(const UnitType *unitType); + explicit ProduceTask(const ResourceType *resourceType); + + UnitClass getUnitClass() const { return unitClass; } + const UnitType *getUnitType() const { return unitType; } + const ResourceType *getResourceType() const { return resourceType; } + virtual string toString() const; + + virtual void saveGame(XmlNode *rootNode) const; + static ProduceTask *loadGame(const XmlNode *rootNode, Faction *faction); }; // ==================== BuildTask ==================== -class BuildTask: public Task{ +class BuildTask : public Task { private: - const UnitType *unitType; - const ResourceType *resourceType; - bool forcePos; - Vec2i pos; + const UnitType *unitType; + const ResourceType *resourceType; + bool forcePos; + Vec2i pos; - BuildTask(); + BuildTask(); public: - explicit BuildTask(const UnitType *unitType); - explicit BuildTask(const ResourceType *resourceType); - BuildTask(const UnitType *unitType, const Vec2i &pos); - - const UnitType *getUnitType() const {return unitType;} - const ResourceType *getResourceType() const {return resourceType;} - bool getForcePos() const {return forcePos;} - Vec2i getPos() const {return pos;} - virtual string toString() const; - - virtual void saveGame(XmlNode *rootNode) const; - static BuildTask * loadGame(const XmlNode *rootNode, Faction *faction); + explicit BuildTask(const UnitType *unitType); + explicit BuildTask(const ResourceType *resourceType); + BuildTask(const UnitType *unitType, const Vec2i &pos); + + const UnitType *getUnitType() const { return unitType; } + const ResourceType *getResourceType() const { return resourceType; } + bool getForcePos() const { return forcePos; } + Vec2i getPos() const { return pos; } + virtual string toString() const; + + virtual void saveGame(XmlNode *rootNode) const; + static BuildTask *loadGame(const XmlNode *rootNode, Faction *faction); }; // ==================== UpgradeTask ==================== -class UpgradeTask: public Task{ +class UpgradeTask : public Task { private: - const UpgradeType *upgradeType; + const UpgradeType *upgradeType; + + UpgradeTask(); - UpgradeTask(); public: - explicit UpgradeTask(const UpgradeType *upgradeType); - const UpgradeType *getUpgradeType() const {return upgradeType;} - virtual string toString() const; + explicit UpgradeTask(const UpgradeType *upgradeType); + const UpgradeType *getUpgradeType() const { return upgradeType; } + virtual string toString() const; - virtual void saveGame(XmlNode *rootNode) const; - static UpgradeTask * loadGame(const XmlNode *rootNode, Faction *faction); + virtual void saveGame(XmlNode *rootNode) const; + static UpgradeTask *loadGame(const XmlNode *rootNode, Faction *faction); }; // =============================== -// class AI +// class AI // /// Main AI class // =============================== class Ai { private: - int maxBuildRadius; + int maxBuildRadius; - int minMinWarriors; - int minMinWarriorsExpandCpuEasy; - int minMinWarriorsExpandCpuMega; - int minMinWarriorsExpandCpuUltra; - int minMinWarriorsExpandCpuNormal; - int maxMinWarriors; + int minMinWarriors; + int minMinWarriorsExpandCpuEasy; + int minMinWarriorsExpandCpuMega; + int minMinWarriorsExpandCpuUltra; + int minMinWarriorsExpandCpuNormal; + int maxMinWarriors; - int maxExpansions; - int villageRadius; - int scoutResourceRange; - int minWorkerAttackersHarvesting; - int minBuildSpacing; + int maxExpansions; + int villageRadius; + int scoutResourceRange; + int minWorkerAttackersHarvesting; + int minBuildSpacing; public: - enum ResourceUsage { - ruHarvester, - ruWarrior, - ruBuilding, - ruUpgrade - }; + enum ResourceUsage { ruHarvester, ruWarrior, ruBuilding, ruUpgrade }; private: - typedef vector AiRules; - typedef list Tasks; - typedef deque Positions; + typedef vector AiRules; + typedef list Tasks; + typedef deque Positions; private: - AiInterface *aiInterface; - AiRules aiRules; - int startLoc; - bool randomMinWarriorsReached; - Tasks tasks; - Positions expansionPositions; - RandomGen random; - std::map factionSwitchTeamRequestCount; - int minWarriors; - - bool getAdjacentUnits(std::map > &signalAdjacentUnits, const Unit *unit); - -public: - Ai() { - // Defaults that used to be static which can now be overriden - maxBuildRadius = 40; - minMinWarriors = 7; - minMinWarriorsExpandCpuEasy = 1; - minMinWarriorsExpandCpuMega = 3; - minMinWarriorsExpandCpuUltra = 3; - minMinWarriorsExpandCpuNormal = 3; - maxMinWarriors = 20; - maxExpansions = 2; - villageRadius = 15; - scoutResourceRange = 20; - minWorkerAttackersHarvesting = 3; - minBuildSpacing = 1; - - aiInterface = NULL; - startLoc = -1; - randomMinWarriorsReached = false; - minWarriors = 0; - } - ~Ai(); - - void init(AiInterface *aiInterface,int useStartLocation=-1); - void update(); - - //state requests - AiInterface *getAiInterface() const {return aiInterface;} - RandomGen* getRandom(); - int getCountOfType(const UnitType *ut); - - int getMinWarriors() const { return minWarriors; } - - int getCountOfClass(UnitClass uc,UnitClass *additionalUnitClassToExcludeFromCount=NULL); - float getRatioOfClass(UnitClass uc,UnitClass *additionalUnitClassToExcludeFromCount=NULL); - - const ResourceType *getNeededResource(int unitIndex); - bool isStableBase(); - bool findPosForBuilding(const UnitType* building, const Vec2i &searchPos, Vec2i &pos); - bool findAbleUnit(int *unitIndex, CommandClass ability, bool idleOnly); - bool findAbleUnit(int *unitIndex, CommandClass ability, CommandClass currentCommand); - //vector findUnitsDoingCommand(CommandClass currentCommand); - vector findUnitsHarvestingResourceType(const ResourceType *rt); - - bool beingAttacked(Vec2i &pos, Field &field, int radius); - - //tasks - void addTask(const Task *task); - void addPriorityTask(const Task *task); - bool anyTask(); - const Task *getTask() const; - void removeTask(const Task *task); - void retryTask(const Task *task); - - //expansions - void addExpansion(const Vec2i &pos); - Vec2i getRandomHomePosition(); - - //actions - void sendScoutPatrol(); - void massiveAttack(const Vec2i &pos, Field field, bool ultraAttack= false); - void returnBase(int unitIndex); - void harvest(int unitIndex); - bool haveBlockedUnits(); - void unblockUnits(); - - bool outputAIBehaviourToConsole() const; - - void saveGame(XmlNode *rootNode) const; - void loadGame(const XmlNode *rootNode, Faction *faction); + AiInterface *aiInterface; + AiRules aiRules; + int startLoc; + bool randomMinWarriorsReached; + Tasks tasks; + Positions expansionPositions; + RandomGen random; + std::map factionSwitchTeamRequestCount; + int minWarriors; + + bool getAdjacentUnits( + std::map> &signalAdjacentUnits, + const Unit *unit); + +public: + Ai() { + // Defaults that used to be static which can now be overriden + maxBuildRadius = 40; + minMinWarriors = 7; + minMinWarriorsExpandCpuEasy = 1; + minMinWarriorsExpandCpuMega = 3; + minMinWarriorsExpandCpuUltra = 3; + minMinWarriorsExpandCpuNormal = 3; + maxMinWarriors = 20; + maxExpansions = 2; + villageRadius = 15; + scoutResourceRange = 20; + minWorkerAttackersHarvesting = 3; + minBuildSpacing = 1; + + aiInterface = NULL; + startLoc = -1; + randomMinWarriorsReached = false; + minWarriors = 0; + } + ~Ai(); + + void init(AiInterface *aiInterface, int useStartLocation = -1); + void update(); + + // state requests + AiInterface *getAiInterface() const { return aiInterface; } + RandomGen *getRandom(); + int getCountOfType(const UnitType *ut); + + int getMinWarriors() const { return minWarriors; } + + int getCountOfClass(UnitClass uc, + UnitClass *additionalUnitClassToExcludeFromCount = NULL); + float + getRatioOfClass(UnitClass uc, + UnitClass *additionalUnitClassToExcludeFromCount = NULL); + + const ResourceType *getNeededResource(int unitIndex); + bool isStableBase(); + bool findPosForBuilding(const UnitType *building, const Vec2i &searchPos, + Vec2i &pos); + bool findAbleUnit(int *unitIndex, CommandClass ability, bool idleOnly); + bool findAbleUnit(int *unitIndex, CommandClass ability, + CommandClass currentCommand); + // vector findUnitsDoingCommand(CommandClass currentCommand); + vector findUnitsHarvestingResourceType(const ResourceType *rt); + + bool beingAttacked(Vec2i &pos, Field &field, int radius); + + // tasks + void addTask(const Task *task); + void addPriorityTask(const Task *task); + bool anyTask(); + const Task *getTask() const; + void removeTask(const Task *task); + void retryTask(const Task *task); + + // expansions + void addExpansion(const Vec2i &pos); + Vec2i getRandomHomePosition(); + + // actions + void sendScoutPatrol(); + void massiveAttack(const Vec2i &pos, Field field, bool ultraAttack = false); + void returnBase(int unitIndex); + void harvest(int unitIndex); + bool haveBlockedUnits(); + void unblockUnits(); + + bool outputAIBehaviourToConsole() const; + + void saveGame(XmlNode *rootNode) const; + void loadGame(const XmlNode *rootNode, Faction *faction); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/ai/ai_interface.cpp b/source/glest_game/ai/ai_interface.cpp index 6bb7a7f2f..77e633774 100644 --- a/source/glest_game/ai/ai_interface.cpp +++ b/source/glest_game/ai/ai_interface.cpp @@ -13,15 +13,15 @@ #include "ai.h" #include "command_type.h" +#include "config.h" #include "faction.h" -#include "unit.h" -#include "unit_type.h" -#include "object.h" #include "game.h" -#include "config.h" +#include "leak_dumper.h" #include "network_manager.h" +#include "object.h" #include "platform_util.h" -#include "leak_dumper.h" +#include "unit.h" +#include "unit_type.h" using namespace Shared::Util; using namespace Shared::Graphics; @@ -30,961 +30,1173 @@ using namespace Shared::Graphics; // class AiInterface // ===================================================== -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class FactionThread // ===================================================== AiInterfaceThread::AiInterfaceThread(AiInterface *aiIntf) : BaseThread() { - this->masterController = NULL; - this->triggerIdMutex = new Mutex(CODE_AT_LINE); - this->aiIntf = aiIntf; - uniqueID = "AiInterfaceThread"; + this->masterController = NULL; + this->triggerIdMutex = new Mutex(CODE_AT_LINE); + this->aiIntf = aiIntf; + uniqueID = "AiInterfaceThread"; } AiInterfaceThread::~AiInterfaceThread() { - delete triggerIdMutex; - triggerIdMutex = NULL; + delete triggerIdMutex; + triggerIdMutex = NULL; } void AiInterfaceThread::setQuitStatus(bool value) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d value = %d\n",__FILE__,__FUNCTION__,__LINE__,value); - - BaseThread::setQuitStatus(value); - if(value == true) { - signal(-1); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s] Line: %d value = %d\n", __FILE__, + __FUNCTION__, __LINE__, value); + + BaseThread::setQuitStatus(value); + if (value == true) { + signal(-1); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] Line: %d\n", + __FILE__, __FUNCTION__, __LINE__); } void AiInterfaceThread::signal(int frameIndex) { - if(frameIndex >= 0) { - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(triggerIdMutex,mutexOwnerId); - this->frameIndex.first = frameIndex; - this->frameIndex.second = false; - - safeMutex.ReleaseLock(); - } - semTaskSignalled.signal(); + if (frameIndex >= 0) { + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(triggerIdMutex, mutexOwnerId); + this->frameIndex.first = frameIndex; + this->frameIndex.second = false; + + safeMutex.ReleaseLock(); + } + semTaskSignalled.signal(); } void AiInterfaceThread::setTaskCompleted(int frameIndex) { - if(frameIndex >= 0) { - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(triggerIdMutex,mutexOwnerId); - if(this->frameIndex.first == frameIndex) { - this->frameIndex.second = true; - } - safeMutex.ReleaseLock(); - } + if (frameIndex >= 0) { + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(triggerIdMutex, mutexOwnerId); + if (this->frameIndex.first == frameIndex) { + this->frameIndex.second = true; + } + safeMutex.ReleaseLock(); + } } bool AiInterfaceThread::canShutdown(bool deleteSelfIfShutdownDelayed) { - bool ret = (getExecutingTask() == false); - if(ret == false && deleteSelfIfShutdownDelayed == true) { - setDeleteSelfOnExecutionDone(deleteSelfIfShutdownDelayed); - deleteSelfIfRequired(); - signalQuit(); - } - - return ret; + bool ret = (getExecutingTask() == false); + if (ret == false && deleteSelfIfShutdownDelayed == true) { + setDeleteSelfOnExecutionDone(deleteSelfIfShutdownDelayed); + deleteSelfIfRequired(); + signalQuit(); + } + + return ret; } bool AiInterfaceThread::isSignalCompleted(int frameIndex) { - if(getRunningStatus() == false) { - return true; - } - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(triggerIdMutex,mutexOwnerId); - //bool result = (event != NULL ? event->eventCompleted : true); - bool result = (this->frameIndex.first == frameIndex && this->frameIndex.second == true); - - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] worker thread this = %p, this->frameIndex.first = %d, this->frameIndex.second = %d\n",__FILE__,__FUNCTION__,__LINE__,this,this->frameIndex.first,this->frameIndex.second); - - safeMutex.ReleaseLock(); - return result; + if (getRunningStatus() == false) { + return true; + } + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(triggerIdMutex, mutexOwnerId); + // bool result = (event != NULL ? event->eventCompleted : true); + bool result = + (this->frameIndex.first == frameIndex && this->frameIndex.second == true); + + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] worker + // thread this = %p, this->frameIndex.first = %d, this->frameIndex.second = + // %d\n",__FILE__,__FUNCTION__,__LINE__,this,this->frameIndex.first,this->frameIndex.second); + + safeMutex.ReleaseLock(); + return result; } void AiInterfaceThread::signalQuit() { - if(this->aiIntf != NULL) { - MutexSafeWrapper safeMutex(this->aiIntf->getMutex(),string(__FILE__) + "_" + intToStr(__LINE__)); - this->aiIntf = NULL; - } + if (this->aiIntf != NULL) { + MutexSafeWrapper safeMutex(this->aiIntf->getMutex(), + string(__FILE__) + "_" + intToStr(__LINE__)); + this->aiIntf = NULL; + } - BaseThread::signalQuit(); + BaseThread::signalQuit(); } void AiInterfaceThread::execute() { - RunningStatusSafeWrapper runningStatus(this); - try { - //setRunningStatus(true); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] ****************** STARTING worker thread this = %p\n",__FILE__,__FUNCTION__,__LINE__,this); - - //bool minorDebugPerformance = false; - Chrono chrono; - - //unsigned int idx = 0; - for(;this->aiIntf != NULL;) { - if(getQuitStatus() == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - break; - } - - semTaskSignalled.waitTillSignalled(); - - static string masterSlaveOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MasterSlaveThreadControllerSafeWrapper safeMasterController(masterController,20000,masterSlaveOwnerId); - - if(getQuitStatus() == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - break; - } - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(triggerIdMutex,mutexOwnerId); - bool executeTask = (frameIndex.first >= 0); - - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] frameIndex = %d this = %p executeTask = %d\n",__FILE__,__FUNCTION__,__LINE__,frameIndex.first, this, executeTask); - - safeMutex.ReleaseLock(); - - if(executeTask == true) { - ExecutingTaskSafeWrapper safeExecutingTaskMutex(this); - - MutexSafeWrapper safeMutex(this->aiIntf->getMutex(),string(__FILE__) + "_" + intToStr(__LINE__)); - - this->aiIntf->update(); - - safeMutex.ReleaseLock(); - - setTaskCompleted(frameIndex.first); - } - - if(getQuitStatus() == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - break; - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] ****************** ENDING worker thread this = %p\n",__FILE__,__FUNCTION__,__LINE__,this); - } - catch(const exception &ex) { - //setRunningStatus(false); - - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + RunningStatusSafeWrapper runningStatus(this); + try { + // setRunningStatus(true); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] ****************** STARTING worker thread " + "this = %p\n", + __FILE__, __FUNCTION__, __LINE__, this); + + // bool minorDebugPerformance = false; + Chrono chrono; + + // unsigned int idx = 0; + for (; this->aiIntf != NULL;) { + if (getQuitStatus() == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + break; + } + + semTaskSignalled.waitTillSignalled(); + + static string masterSlaveOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MasterSlaveThreadControllerSafeWrapper safeMasterController( + masterController, 20000, masterSlaveOwnerId); + + if (getQuitStatus() == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + break; + } + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(triggerIdMutex, mutexOwnerId); + bool executeTask = (frameIndex.first >= 0); + + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] + // frameIndex = %d this = %p executeTask = + // %d\n",__FILE__,__FUNCTION__,__LINE__,frameIndex.first, this, + // executeTask); + + safeMutex.ReleaseLock(); + + if (executeTask == true) { + ExecutingTaskSafeWrapper safeExecutingTaskMutex(this); + + MutexSafeWrapper safeMutex(this->aiIntf->getMutex(), + string(__FILE__) + "_" + intToStr(__LINE__)); + + this->aiIntf->update(); + + safeMutex.ReleaseLock(); + + setTaskCompleted(frameIndex.first); + } + + if (getQuitStatus() == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + break; + } + } - throw megaglest_runtime_error(ex.what()); - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] ****************** ENDING worker thread " + "this = %p\n", + __FILE__, __FUNCTION__, __LINE__, this); + } catch (const exception &ex) { + // setRunningStatus(false); + + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", __FILE__, + __FUNCTION__, __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + throw megaglest_runtime_error(ex.what()); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] Line: %d\n", + __FILE__, __FUNCTION__, __LINE__); } AiInterface::AiInterface(Game &game, int factionIndex, int teamIndex, - int useStartLocation) : fp(NULL) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - this->aiMutex = new Mutex(CODE_AT_LINE); - this->workerThread = NULL; - this->world= game.getWorld(); - this->commander= game.getCommander(); - this->console= game.getConsole(); - this->gameSettings = game.getGameSettings(); - - this->factionIndex= factionIndex; - this->teamIndex= teamIndex; - timer= 0; - - //init ai - ai.init(this,useStartLocation); - - //config - logLevel= Config::getInstance().getInt("AiLog"); - redir= Config::getInstance().getBool("AiRedir"); - - aiLogFile = getLogFilename(); - if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - aiLogFile = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + aiLogFile; - } - else { - string userData = Config::getInstance().getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - aiLogFile = userData + aiLogFile; - } + int useStartLocation) + : fp(NULL) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + this->aiMutex = new Mutex(CODE_AT_LINE); + this->workerThread = NULL; + this->world = game.getWorld(); + this->commander = game.getCommander(); + this->console = game.getConsole(); + this->gameSettings = game.getGameSettings(); + + this->factionIndex = factionIndex; + this->teamIndex = teamIndex; + timer = 0; + + // init ai + ai.init(this, useStartLocation); + + // config + logLevel = Config::getInstance().getInt("AiLog"); + redir = Config::getInstance().getBool("AiRedir"); + + aiLogFile = getLogFilename(); + if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { + aiLogFile = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + + aiLogFile; + } else { + string userData = Config::getInstance().getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + aiLogFile = userData + aiLogFile; + } - //clear log file - if(logLevel > 0) { + // clear log file + if (logLevel > 0) { #ifdef WIN32 - fp = _wfopen(::Shared::Platform::utf8_decode(aiLogFile).c_str(), L"wt"); + fp = _wfopen(::Shared::Platform::utf8_decode(aiLogFile).c_str(), L"wt"); #else - fp = fopen(aiLogFile.c_str(), "wt"); + fp = fopen(aiLogFile.c_str(), "wt"); #endif - if(fp == NULL) { - throw megaglest_runtime_error("Can't open file: [" + aiLogFile + "]"); - } - fprintf(fp, "MegaGlest AI log file for Tech [%s] Faction [%s] #%d\n\n",this->gameSettings->getTech().c_str(),this->world->getFaction(this->factionIndex)->getType()->getName().c_str(),this->factionIndex); - } - - - if( Config::getInstance().getBool("EnableAIWorkerThreads","true") == true) { - if(workerThread != NULL) { - workerThread->signalQuit(); - if(workerThread->shutdownAndWait() == true) { - delete workerThread; - } - workerThread = NULL; - } - static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); - this->workerThread = new AiInterfaceThread(this); - this->workerThread->setUniqueID(mutexOwnerId); - this->workerThread->start(); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (fp == NULL) { + throw megaglest_runtime_error("Can't open file: [" + aiLogFile + "]"); + } + fprintf(fp, "MegaGlest AI log file for Tech [%s] Faction [%s] #%d\n\n", + this->gameSettings->getTech().c_str(), + this->world->getFaction(this->factionIndex) + ->getType() + ->getName() + .c_str(), + this->factionIndex); + } + + if (Config::getInstance().getBool("EnableAIWorkerThreads", "true") == true) { + if (workerThread != NULL) { + workerThread->signalQuit(); + if (workerThread->shutdownAndWait() == true) { + delete workerThread; + } + workerThread = NULL; + } + static string mutexOwnerId = + string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + + intToStr(__LINE__); + this->workerThread = new AiInterfaceThread(this); + this->workerThread->setUniqueID(mutexOwnerId); + this->workerThread->start(); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); } void AiInterface::init() { - world=NULL;; - commander=NULL;; - console=NULL;; - gameSettings=NULL;; - timer=0; - factionIndex=0; - teamIndex=0; - redir=false; - logLevel=0; - fp=NULL;; - aiMutex=NULL; - workerThread=NULL; + world = NULL; + ; + commander = NULL; + ; + console = NULL; + ; + gameSettings = NULL; + ; + timer = 0; + factionIndex = 0; + teamIndex = 0; + redir = false; + logLevel = 0; + fp = NULL; + ; + aiMutex = NULL; + workerThread = NULL; } AiInterface::~AiInterface() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] deleting AI factionIndex = %d, teamIndex = %d\n",__FILE__,__FUNCTION__,__LINE__,this->factionIndex,this->teamIndex); - cacheUnitHarvestResourceLookup.clear(); - - if(workerThread != NULL) { - workerThread->signalQuit(); - sleep(0); - if(workerThread->canShutdown(true) == true && - workerThread->shutdownAndWait() == true) { - delete workerThread; - } - workerThread = NULL; - } - - if(fp) { - fclose(fp); - fp = NULL; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] deleting AI factionIndex = %d, teamIndex = %d\n", + __FILE__, __FUNCTION__, __LINE__, this->factionIndex, this->teamIndex); + cacheUnitHarvestResourceLookup.clear(); + + if (workerThread != NULL) { + workerThread->signalQuit(); + sleep(0); + if (workerThread->canShutdown(true) == true && + workerThread->shutdownAndWait() == true) { + delete workerThread; } + workerThread = NULL; + } - delete aiMutex; - aiMutex = NULL; + if (fp) { + fclose(fp); + fp = NULL; + } + + delete aiMutex; + aiMutex = NULL; } void AiInterface::signalWorkerThread(int frameIndex) { - if(workerThread != NULL) { - workerThread->signal(frameIndex); - } - else { - this->update(); - } + if (workerThread != NULL) { + workerThread->signal(frameIndex); + } else { + this->update(); + } } bool AiInterface::isWorkerThreadSignalCompleted(int frameIndex) { - if(workerThread != NULL) { - return workerThread->isSignalCompleted(frameIndex); - } - return true; + if (workerThread != NULL) { + return workerThread->isSignalCompleted(frameIndex); + } + return true; } // ==================== main ==================== void AiInterface::update() { - timer++; - ai.update(); + timer++; + ai.update(); } // ==================== misc ==================== bool AiInterface::isLogLevelEnabled(int level) { - return (this->logLevel >= level); + return (this->logLevel >= level); } -void AiInterface::printLog(int logLevel, const string &s){ - if(isLogLevelEnabled(logLevel) == true) { - string logString= "(" + intToStr(factionIndex) + ") " + s; +void AiInterface::printLog(int logLevel, const string &s) { + if (isLogLevelEnabled(logLevel) == true) { + string logString = "(" + intToStr(factionIndex) + ") " + s; - MutexSafeWrapper safeMutex(aiMutex,string(__FILE__) + "_" + intToStr(__LINE__)); - //print log to file - if(fp != NULL) { - fprintf(fp, "%s\n", logString.c_str()); - } + MutexSafeWrapper safeMutex(aiMutex, + string(__FILE__) + "_" + intToStr(__LINE__)); + // print log to file + if (fp != NULL) { + fprintf(fp, "%s\n", logString.c_str()); + } - //redirect to console - if(redir) { - console->addLine(logString); - } + // redirect to console + if (redir) { + console->addLine(logString); } + } } // ==================== interaction ==================== -Faction *AiInterface::getMyFaction() { - return world->getFaction(factionIndex); -} +Faction *AiInterface::getMyFaction() { return world->getFaction(factionIndex); } bool AiInterface::executeCommandOverNetwork() { - bool enableServerControlledAI = gameSettings->getEnableServerControlledAI(); - bool isNetworkGame = gameSettings->isNetworkGame(); - NetworkRole role = NetworkManager::getInstance().getNetworkRole(); - Faction *faction = world->getFaction(factionIndex); - return faction->getCpuControl(enableServerControlledAI,isNetworkGame,role); -} - -std::pair AiInterface::giveCommandSwitchTeamVote(const Faction* faction, SwitchTeamVote *vote) { - assert(this->gameSettings != NULL); - - commander->trySwitchTeamVote(faction,vote); - return std::pair(crSuccess,""); -} - -std::pair AiInterface::giveCommand(int unitIndex, CommandClass commandClass, const Vec2i &pos){ - assert(this->gameSettings != NULL); - - std::pair result(crFailUndefined,""); - if(executeCommandOverNetwork() == true) { - const Unit *unit = getMyUnit(unitIndex); - result = commander->tryGiveCommand(unit, unit->getType()->getFirstCtOfClass(commandClass), pos, unit->getType(),CardinalDir(CardinalDir::NORTH)); - return result; - } - else { - Command *c= new Command (world->getFaction(factionIndex)->getUnit(unitIndex)->getType()->getFirstCtOfClass(commandClass), pos); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - result = world->getFaction(factionIndex)->getUnit(unitIndex)->giveCommand(c); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - return result; - } -} - -std::pair AiInterface::giveCommand(const Unit *unit, const CommandType *commandType, const Vec2i &pos, int unitGroupCommandId) { - assert(this->gameSettings != NULL); - - std::pair result(crFailUndefined,""); - if(unit == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] Can not find AI unit in AI factionIndex = %d. Game out of synch.",__FILE__,__FUNCTION__,__LINE__,factionIndex); - throw megaglest_runtime_error(szBuf); - } - const UnitType* unitType= unit->getType(); - if(unitType == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] Can not find AI unittype with unit id: %d, AI factionIndex = %d. Game out of synch.",__FILE__,__FUNCTION__,__LINE__,unit->getId(),factionIndex); - throw megaglest_runtime_error(szBuf); - } - if(commandType == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] commandType == NULL, unit id: %d, AI factionIndex = %d. Game out of synch.",__FILE__,__FUNCTION__,__LINE__,unit->getId(),factionIndex); - throw megaglest_runtime_error(szBuf); - } - const CommandType* ct= unit->getType()->findCommandTypeById(commandType->getId()); - if(ct == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d]\nCan not find AI command type for:\nunit = %d\n[%s]\n[%s]\nactual local factionIndex = %d.\nGame out of synch.", - __FILE__,__FUNCTION__,__LINE__, - unit->getId(), unit->getFullName(false).c_str(),unit->getDesc(false).c_str(), - unit->getFaction()->getIndex()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s\n",szBuf); - - std::string worldLog = world->DumpWorldToLog(); - std::string sError = "worldLog = " + worldLog + " " + string(szBuf); - throw megaglest_runtime_error(sError); - } - - if(executeCommandOverNetwork() == true) { - result = commander->tryGiveCommand(unit, commandType, pos, - unit->getType(),CardinalDir(CardinalDir::NORTH), false, NULL,unitGroupCommandId); - return result; - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - Faction *faction = world->getFaction(unit->getFactionIndex()); - Unit *unitToCommand = faction->findUnit(unit->getId()); - Command *cmd = new Command(commandType, pos); - cmd->setUnitCommandGroupId(unitGroupCommandId); - result = unitToCommand->giveCommand(cmd); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - return result; - } -} - -std::pair AiInterface::giveCommand(int unitIndex, const CommandType *commandType, const Vec2i &pos, int unitGroupCommandId) { - assert(this->gameSettings != NULL); - - std::pair result(crFailUndefined,""); - const Unit *unit = getMyUnit(unitIndex); - if(unit == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] Can not find AI unit with index: %d, AI factionIndex = %d. Game out of synch.",__FILE__,__FUNCTION__,__LINE__,unitIndex,factionIndex); - throw megaglest_runtime_error(szBuf); - } - const UnitType* unitType= unit->getType(); - if(unitType == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] Can not find AI unittype with unit index: %d, AI factionIndex = %d. Game out of synch.",__FILE__,__FUNCTION__,__LINE__,unitIndex,factionIndex); - throw megaglest_runtime_error(szBuf); - } - const CommandType* ct= unit->getType()->findCommandTypeById(commandType->getId()); - if(ct == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d]\nCan not find AI command type for:\nunit = %d\n[%s]\n[%s]\nactual local factionIndex = %d.\nGame out of synch.", - __FILE__,__FUNCTION__,__LINE__, - unit->getId(), unit->getFullName(false).c_str(),unit->getDesc(false).c_str(), - unit->getFaction()->getIndex()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s\n",szBuf); - - std::string worldLog = world->DumpWorldToLog(); - std::string sError = "worldLog = " + worldLog + " " + string(szBuf); - throw megaglest_runtime_error(sError); - } - - if(executeCommandOverNetwork() == true) { - const Unit *unit = getMyUnit(unitIndex); - result = commander->tryGiveCommand(unit, commandType, pos, unit->getType(),CardinalDir(CardinalDir::NORTH)); - return result; - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - Command *cmd = new Command(commandType, pos); - cmd->setUnitCommandGroupId(unitGroupCommandId); - result = world->getFaction(factionIndex)->getUnit(unitIndex)->giveCommand(cmd); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - return result; - } -} - -std::pair AiInterface::giveCommand(int unitIndex, const CommandType *commandType, const Vec2i &pos, const UnitType *ut) { - assert(this->gameSettings != NULL); - - std::pair result(crFailUndefined,""); - const Unit *unit = getMyUnit(unitIndex); - if(unit == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] Can not find AI unit with index: %d, AI factionIndex = %d. Game out of synch.",__FILE__,__FUNCTION__,__LINE__,unitIndex,factionIndex); - throw megaglest_runtime_error(szBuf); - } - const UnitType* unitType= unit->getType(); - if(unitType == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] Can not find AI unittype with unit index: %d, AI factionIndex = %d. Game out of synch.",__FILE__,__FUNCTION__,__LINE__,unitIndex,factionIndex); - throw megaglest_runtime_error(szBuf); - } - const CommandType* ct= unit->getType()->findCommandTypeById(commandType->getId()); - if(ct == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d]\nCan not find AI command type for:\nunit = %d\n[%s]\n[%s]\nactual local factionIndex = %d.\nGame out of synch.", - __FILE__,__FUNCTION__,__LINE__, - unit->getId(), unit->getFullName(false).c_str(),unit->getDesc(false).c_str(), - unit->getFaction()->getIndex()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s\n",szBuf); - - std::string worldLog = world->DumpWorldToLog(); - std::string sError = "worldLog = " + worldLog + " " + string(szBuf); - throw megaglest_runtime_error(sError); - } - - if(executeCommandOverNetwork() == true) { - const Unit *unit = getMyUnit(unitIndex); - result = commander->tryGiveCommand(unit, commandType, pos, ut,CardinalDir(CardinalDir::NORTH)); - return result; - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - result = world->getFaction(factionIndex)->getUnit(unitIndex)->giveCommand(new Command(commandType, pos, ut, CardinalDir(CardinalDir::NORTH))); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - return result; - } -} - -std::pair AiInterface::giveCommand(int unitIndex, const CommandType *commandType, Unit *u){ - assert(this->gameSettings != NULL); - assert(this->commander != NULL); - - std::pair result(crFailUndefined,""); - const Unit *unit = getMyUnit(unitIndex); - if(unit == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] Can not find AI unit with index: %d, AI factionIndex = %d. Game out of synch.",__FILE__,__FUNCTION__,__LINE__,unitIndex,factionIndex); - throw megaglest_runtime_error(szBuf); - } - const UnitType* unitType= unit->getType(); - if(unitType == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] Can not find AI unittype with unit index: %d, AI factionIndex = %d. Game out of synch.",__FILE__,__FUNCTION__,__LINE__,unitIndex,factionIndex); - throw megaglest_runtime_error(szBuf); - } - const CommandType* ct= (commandType != NULL ? unit->getType()->findCommandTypeById(commandType->getId()) : NULL); - if(ct == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d]\nCan not find AI command type for:\nunit = %d\n[%s]\n[%s]\nactual local factionIndex = %d.\nGame out of synch.", - __FILE__,__FUNCTION__,__LINE__, - unit->getId(), unit->getFullName(false).c_str(),unit->getDesc(false).c_str(), - unit->getFaction()->getIndex()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s\n",szBuf); - - std::string worldLog = world->DumpWorldToLog(); - std::string sError = "worldLog = " + worldLog + " " + string(szBuf); - throw megaglest_runtime_error(sError); - } - - if(executeCommandOverNetwork() == true) { - Unit *targetUnit = u; - const Unit *unit = getMyUnit(unitIndex); - - result = commander->tryGiveCommand(unit, commandType, Vec2i(0), unit->getType(),CardinalDir(CardinalDir::NORTH),false,targetUnit); - - return result; - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - result = world->getFaction(factionIndex)->getUnit(unitIndex)->giveCommand(new Command(commandType, u)); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - return result; - } + bool enableServerControlledAI = gameSettings->getEnableServerControlledAI(); + bool isNetworkGame = gameSettings->isNetworkGame(); + NetworkRole role = NetworkManager::getInstance().getNetworkRole(); + Faction *faction = world->getFaction(factionIndex); + return faction->getCpuControl(enableServerControlledAI, isNetworkGame, role); } -// ==================== get data ==================== +std::pair +AiInterface::giveCommandSwitchTeamVote(const Faction *faction, + SwitchTeamVote *vote) { + assert(this->gameSettings != NULL); + + commander->trySwitchTeamVote(faction, vote); + return std::pair(crSuccess, ""); +} + +std::pair +AiInterface::giveCommand(int unitIndex, CommandClass commandClass, + const Vec2i &pos) { + assert(this->gameSettings != NULL); + + std::pair result(crFailUndefined, ""); + if (executeCommandOverNetwork() == true) { + const Unit *unit = getMyUnit(unitIndex); + result = commander->tryGiveCommand( + unit, unit->getType()->getFirstCtOfClass(commandClass), pos, + unit->getType(), CardinalDir(CardinalDir::NORTH)); + return result; + } else { + Command *c = new Command(world->getFaction(factionIndex) + ->getUnit(unitIndex) + ->getType() + ->getFirstCtOfClass(commandClass), + pos); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + result = + world->getFaction(factionIndex)->getUnit(unitIndex)->giveCommand(c); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + return result; + } +} + +std::pair +AiInterface::giveCommand(const Unit *unit, const CommandType *commandType, + const Vec2i &pos, int unitGroupCommandId) { + assert(this->gameSettings != NULL); + + std::pair result(crFailUndefined, ""); + if (unit == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] Can not find AI unit in AI factionIndex = " + "%d. Game out of synch.", + __FILE__, __FUNCTION__, __LINE__, factionIndex); + throw megaglest_runtime_error(szBuf); + } + const UnitType *unitType = unit->getType(); + if (unitType == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] Can not find AI unittype with unit id: %d, " + "AI factionIndex = %d. Game out of synch.", + __FILE__, __FUNCTION__, __LINE__, unit->getId(), factionIndex); + throw megaglest_runtime_error(szBuf); + } + if (commandType == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] commandType == NULL, unit id: %d, AI " + "factionIndex = %d. Game out of synch.", + __FILE__, __FUNCTION__, __LINE__, unit->getId(), factionIndex); + throw megaglest_runtime_error(szBuf); + } + const CommandType *ct = + unit->getType()->findCommandTypeById(commandType->getId()); + if (ct == NULL) { + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "In [%s::%s Line: %d]\nCan not find AI command type for:\nunit = " + "%d\n[%s]\n[%s]\nactual local factionIndex = %d.\nGame out of synch.", + __FILE__, __FUNCTION__, __LINE__, unit->getId(), + unit->getFullName(false).c_str(), unit->getDesc(false).c_str(), + unit->getFaction()->getIndex()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s\n", szBuf); + + std::string worldLog = world->DumpWorldToLog(); + std::string sError = "worldLog = " + worldLog + " " + string(szBuf); + throw megaglest_runtime_error(sError); + } + + if (executeCommandOverNetwork() == true) { + result = commander->tryGiveCommand(unit, commandType, pos, unit->getType(), + CardinalDir(CardinalDir::NORTH), false, + NULL, unitGroupCommandId); + return result; + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + Faction *faction = world->getFaction(unit->getFactionIndex()); + Unit *unitToCommand = faction->findUnit(unit->getId()); + Command *cmd = new Command(commandType, pos); + cmd->setUnitCommandGroupId(unitGroupCommandId); + result = unitToCommand->giveCommand(cmd); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + return result; + } +} + +std::pair +AiInterface::giveCommand(int unitIndex, const CommandType *commandType, + const Vec2i &pos, int unitGroupCommandId) { + assert(this->gameSettings != NULL); + + std::pair result(crFailUndefined, ""); + const Unit *unit = getMyUnit(unitIndex); + if (unit == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] Can not find AI unit with index: %d, AI " + "factionIndex = %d. Game out of synch.", + __FILE__, __FUNCTION__, __LINE__, unitIndex, factionIndex); + throw megaglest_runtime_error(szBuf); + } + const UnitType *unitType = unit->getType(); + if (unitType == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] Can not find AI unittype with unit index: " + "%d, AI factionIndex = %d. Game out of synch.", + __FILE__, __FUNCTION__, __LINE__, unitIndex, factionIndex); + throw megaglest_runtime_error(szBuf); + } + const CommandType *ct = + unit->getType()->findCommandTypeById(commandType->getId()); + if (ct == NULL) { + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "In [%s::%s Line: %d]\nCan not find AI command type for:\nunit = " + "%d\n[%s]\n[%s]\nactual local factionIndex = %d.\nGame out of synch.", + __FILE__, __FUNCTION__, __LINE__, unit->getId(), + unit->getFullName(false).c_str(), unit->getDesc(false).c_str(), + unit->getFaction()->getIndex()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s\n", szBuf); + + std::string worldLog = world->DumpWorldToLog(); + std::string sError = "worldLog = " + worldLog + " " + string(szBuf); + throw megaglest_runtime_error(sError); + } + + if (executeCommandOverNetwork() == true) { + const Unit *unit = getMyUnit(unitIndex); + result = commander->tryGiveCommand(unit, commandType, pos, unit->getType(), + CardinalDir(CardinalDir::NORTH)); + return result; + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + Command *cmd = new Command(commandType, pos); + cmd->setUnitCommandGroupId(unitGroupCommandId); + result = + world->getFaction(factionIndex)->getUnit(unitIndex)->giveCommand(cmd); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + return result; + } +} -int AiInterface::getMapMaxPlayers(){ - return world->getMaxPlayers(); +std::pair +AiInterface::giveCommand(int unitIndex, const CommandType *commandType, + const Vec2i &pos, const UnitType *ut) { + assert(this->gameSettings != NULL); + + std::pair result(crFailUndefined, ""); + const Unit *unit = getMyUnit(unitIndex); + if (unit == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] Can not find AI unit with index: %d, AI " + "factionIndex = %d. Game out of synch.", + __FILE__, __FUNCTION__, __LINE__, unitIndex, factionIndex); + throw megaglest_runtime_error(szBuf); + } + const UnitType *unitType = unit->getType(); + if (unitType == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] Can not find AI unittype with unit index: " + "%d, AI factionIndex = %d. Game out of synch.", + __FILE__, __FUNCTION__, __LINE__, unitIndex, factionIndex); + throw megaglest_runtime_error(szBuf); + } + const CommandType *ct = + unit->getType()->findCommandTypeById(commandType->getId()); + if (ct == NULL) { + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "In [%s::%s Line: %d]\nCan not find AI command type for:\nunit = " + "%d\n[%s]\n[%s]\nactual local factionIndex = %d.\nGame out of synch.", + __FILE__, __FUNCTION__, __LINE__, unit->getId(), + unit->getFullName(false).c_str(), unit->getDesc(false).c_str(), + unit->getFaction()->getIndex()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s\n", szBuf); + + std::string worldLog = world->DumpWorldToLog(); + std::string sError = "worldLog = " + worldLog + " " + string(szBuf); + throw megaglest_runtime_error(sError); + } + + if (executeCommandOverNetwork() == true) { + const Unit *unit = getMyUnit(unitIndex); + result = commander->tryGiveCommand(unit, commandType, pos, ut, + CardinalDir(CardinalDir::NORTH)); + return result; + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + result = world->getFaction(factionIndex) + ->getUnit(unitIndex) + ->giveCommand(new Command(commandType, pos, ut, + CardinalDir(CardinalDir::NORTH))); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + return result; + } } -Vec2i AiInterface::getHomeLocation(){ - return world->getMap()->getStartLocation(world->getFaction(factionIndex)->getStartLocationIndex()); +std::pair +AiInterface::giveCommand(int unitIndex, const CommandType *commandType, + Unit *u) { + assert(this->gameSettings != NULL); + assert(this->commander != NULL); + + std::pair result(crFailUndefined, ""); + const Unit *unit = getMyUnit(unitIndex); + if (unit == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] Can not find AI unit with index: %d, AI " + "factionIndex = %d. Game out of synch.", + __FILE__, __FUNCTION__, __LINE__, unitIndex, factionIndex); + throw megaglest_runtime_error(szBuf); + } + const UnitType *unitType = unit->getType(); + if (unitType == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] Can not find AI unittype with unit index: " + "%d, AI factionIndex = %d. Game out of synch.", + __FILE__, __FUNCTION__, __LINE__, unitIndex, factionIndex); + throw megaglest_runtime_error(szBuf); + } + const CommandType *ct = + (commandType != NULL + ? unit->getType()->findCommandTypeById(commandType->getId()) + : NULL); + if (ct == NULL) { + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "In [%s::%s Line: %d]\nCan not find AI command type for:\nunit = " + "%d\n[%s]\n[%s]\nactual local factionIndex = %d.\nGame out of synch.", + __FILE__, __FUNCTION__, __LINE__, unit->getId(), + unit->getFullName(false).c_str(), unit->getDesc(false).c_str(), + unit->getFaction()->getIndex()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s\n", szBuf); + + std::string worldLog = world->DumpWorldToLog(); + std::string sError = "worldLog = " + worldLog + " " + string(szBuf); + throw megaglest_runtime_error(sError); + } + + if (executeCommandOverNetwork() == true) { + Unit *targetUnit = u; + const Unit *unit = getMyUnit(unitIndex); + + result = commander->tryGiveCommand( + unit, commandType, Vec2i(0), unit->getType(), + CardinalDir(CardinalDir::NORTH), false, targetUnit); + + return result; + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + result = world->getFaction(factionIndex) + ->getUnit(unitIndex) + ->giveCommand(new Command(commandType, u)); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + return result; + } } -Vec2i AiInterface::getStartLocation(int loactionIndex){ - return world->getMap()->getStartLocation(loactionIndex); +// ==================== get data ==================== + +int AiInterface::getMapMaxPlayers() { return world->getMaxPlayers(); } + +Vec2i AiInterface::getHomeLocation() { + return world->getMap()->getStartLocation( + world->getFaction(factionIndex)->getStartLocationIndex()); } -int AiInterface::getFactionCount(){ - return world->getFactionCount(); +Vec2i AiInterface::getStartLocation(int loactionIndex) { + return world->getMap()->getStartLocation(loactionIndex); } -int AiInterface::getMyUnitCount() const{ - return world->getFaction(factionIndex)->getUnitCount(); +int AiInterface::getFactionCount() { return world->getFactionCount(); } + +int AiInterface::getMyUnitCount() const { + return world->getFaction(factionIndex)->getUnitCount(); } -int AiInterface::getMyUpgradeCount() const{ - return world->getFaction(factionIndex)->getUpgradeManager()->getUpgradeCount(); +int AiInterface::getMyUpgradeCount() const { + return world->getFaction(factionIndex) + ->getUpgradeManager() + ->getUpgradeCount(); } -//int AiInterface::onSightUnitCount() { -// int count=0; +// int AiInterface::onSightUnitCount() { +// int count=0; // Map *map= world->getMap(); // for(int i=0; igetFactionCount(); ++i) { // for(int j=0; jgetFaction(i)->getUnitCount(); ++j) { // Unit *unit = world->getFaction(i)->getUnit(j); -// SurfaceCell *sc= map->getSurfaceCell(Map::toSurfCoords(unit->getPos())); -// bool cannotSeeUnit = (unit->getType()->hasCellMap() == true && -// unit->getType()->getAllowEmptyCellMap() == true && -// unit->getType()->hasEmptyCellMap() == true); -// if(sc->isVisible(teamIndex) && cannotSeeUnit == false) { -// count++; +// SurfaceCell *sc= +// map->getSurfaceCell(Map::toSurfCoords(unit->getPos())); bool +// cannotSeeUnit = (unit->getType()->hasCellMap() == true && +// unit->getType()->getAllowEmptyCellMap() +//== true && +//unit->getType()->hasEmptyCellMap() == true); if(sc->isVisible(teamIndex) && +//cannotSeeUnit == false) { count++; // } // } // } -// return count; -//} +// return count; +// } -const Resource *AiInterface::getResource(const ResourceType *rt){ - return world->getFaction(factionIndex)->getResource(rt); +const Resource *AiInterface::getResource(const ResourceType *rt) { + return world->getFaction(factionIndex)->getResource(rt); } Unit *AiInterface::getMyUnitPtr(int unitIndex) { - if(unitIndex < 0 || unitIndex >= world->getFaction(factionIndex)->getUnitCount()) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] unitIndex >= world->getFaction(factionIndex)->getUnitCount(), unitIndex = %d, world->getFaction(factionIndex)->getUnitCount() = %d",__FILE__,__FUNCTION__,__LINE__,unitIndex,world->getFaction(factionIndex)->getUnitCount()); - throw megaglest_runtime_error(szBuf); - } - - return world->getFaction(factionIndex)->getUnit(unitIndex); + if (unitIndex < 0 || + unitIndex >= world->getFaction(factionIndex)->getUnitCount()) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] unitIndex >= " + "world->getFaction(factionIndex)->getUnitCount(), unitIndex = %d, " + "world->getFaction(factionIndex)->getUnitCount() = %d", + __FILE__, __FUNCTION__, __LINE__, unitIndex, + world->getFaction(factionIndex)->getUnitCount()); + throw megaglest_runtime_error(szBuf); + } + + return world->getFaction(factionIndex)->getUnit(unitIndex); } const Unit *AiInterface::getMyUnit(int unitIndex) { - return getMyUnitPtr(unitIndex); + return getMyUnitPtr(unitIndex); } -//const Unit *AiInterface::getOnSightUnit(int unitIndex) { +// const Unit *AiInterface::getOnSightUnit(int unitIndex) { // -// int count=0; +// int count=0; // Map *map= world->getMap(); // // for(int i=0; igetFactionCount(); ++i) { -// for(int j=0; jgetFaction(i)->getUnitCount(); ++j) { -// Unit * unit= world->getFaction(i)->getUnit(j); -// SurfaceCell *sc= map->getSurfaceCell(Map::toSurfCoords(unit->getPos())); -// bool cannotSeeUnit = (unit->getType()->hasCellMap() == true && -// unit->getType()->getAllowEmptyCellMap() == true && -// unit->getType()->hasEmptyCellMap() == true); +// for(int j=0; jgetFaction(i)->getUnitCount(); ++j) { +// Unit * unit= world->getFaction(i)->getUnit(j); +// SurfaceCell *sc= +// map->getSurfaceCell(Map::toSurfCoords(unit->getPos())); +// bool cannotSeeUnit = (unit->getType()->hasCellMap() == +//true +//&& +//unit->getType()->getAllowEmptyCellMap() == true && +// unit->getType()->hasEmptyCellMap() +//== true); // -// if(sc->isVisible(teamIndex) && cannotSeeUnit == false) { +// if(sc->isVisible(teamIndex) && cannotSeeUnit == false) { // if(count==unitIndex) { // return unit; // } // else { // count ++; // } -// } -// } +// } +// } // } -// return NULL; -//} - -const FactionType * AiInterface::getMyFactionType(){ - return world->getFaction(factionIndex)->getType(); -} - -const ControlType AiInterface::getControlType(){ - return world->getFaction(factionIndex)->getControlType(); -} - -const TechTree *AiInterface::getTechTree(){ - return world->getTechTree(); -} - - -bool AiInterface::isResourceInRegion(const Vec2i &pos, const ResourceType *rt, Vec2i &resourcePos, int range) const { - const Map *map= world->getMap(); - - int xi=1; - int xj=1; - - if(rand() % 2==1){ - xi=-1; - } - if(rand() % 2==1){ - xj=-1; - } - for(int i = -range; i <= range; ++i) { - for(int j = -range; j <= range; ++j) { - int ii=xi*i; - int jj=xj*j; - if(map->isInside(pos.x + ii, pos.y + jj)) { - Resource *r= map->getSurfaceCell(map->toSurfCoords(Vec2i(pos.x + ii, pos.y + jj)))->getResource(); - if(r != NULL) { - if(r->getType() == rt) { - resourcePos= pos + Vec2i(ii,jj); - return true; - } - } - } - } - } - return false; -} - - - -//returns if there is a resource next to a unit, in "resourcePos" is stored the relative position of the resource -bool AiInterface::isResourceNear(const Vec2i &pos, const ResourceType *rt, Vec2i &resourcePos, Faction *faction, bool fallbackToPeersHarvestingSameResource) const { - const Map *map= world->getMap(); - int size = 1; - for(int i = -1; i <= size; ++i) { - for(int j = -1; j <= size; ++j) { - if(map->isInside(pos.x + i, pos.y + j)) { - Resource *r= map->getSurfaceCell(map->toSurfCoords(Vec2i(pos.x + i, pos.y + j)))->getResource(); - if(r != NULL) { - if(r->getType() == rt) { - resourcePos= pos + Vec2i(i,j); - - return true; - } - } - } - } - } - - if(fallbackToPeersHarvestingSameResource == true && faction != NULL) { - // Look for another unit that is currently harvesting the same resource - // type right now - - // Check the faction cache for a known position where we can harvest - // this resource type - Vec2i result = faction->getClosestResourceTypeTargetFromCache(pos, rt); - if(result.x >= 0) { - resourcePos = result; - - if(pos.dist(resourcePos) <= size) { - return true; - } - } - } - - return false; -} - -bool AiInterface::getNearestSightedResource(const ResourceType *rt, const Vec2i &pos, - Vec2i &resultPos, bool usableResourceTypeOnly) { - Faction *faction = world->getFaction(factionIndex); - //float tmpDist=0; - float nearestDist= infinity; - bool anyResource= false; - resultPos.x = -1; - resultPos.y = -1; - - bool canUseResourceType = (usableResourceTypeOnly == false); - if(usableResourceTypeOnly == true) { - // can any unit harvest this resource yet? - std::map::iterator iterFind = cacheUnitHarvestResourceLookup.find(rt); - - if( iterFind != cacheUnitHarvestResourceLookup.end() && - faction->findUnit(iterFind->second) != NULL) { - canUseResourceType = true; - } - else { - int unitCount = getMyUnitCount(); - for(int i = 0; i < unitCount; ++i) { - const Unit *unit = getMyUnit(i); - const HarvestCommandType *hct= unit->getType()->getFirstHarvestCommand(rt,unit->getFaction()); - if(hct != NULL) { - canUseResourceType = true; - cacheUnitHarvestResourceLookup[rt] = unit->getId(); - break; - } - } - } - } - - if(canUseResourceType == true) { - bool isResourceClose = isResourceNear(pos, rt, resultPos, faction, true); - - // Found a resource - if(isResourceClose == true || resultPos.x >= 0) { - anyResource= true; - } - else { - const Map *map = world->getMap(); - for(int i = 0; i < map->getW(); ++i) { - for(int j = 0; j < map->getH(); ++j) { - Vec2i resPos = Vec2i(i, j); - Vec2i surfPos= Map::toSurfCoords(resPos); - SurfaceCell *sc = map->getSurfaceCell(surfPos); - - //if explored cell - if(sc != NULL && sc->isExplored(teamIndex)) { - Resource *r= sc->getResource(); - - //if resource cell - if(r != NULL) { - if(r->getType() == rt) { - float tmpDist= pos.dist(resPos); - if(tmpDist < nearestDist) { - anyResource= true; - nearestDist= tmpDist; - resultPos= resPos; - } - } - } - } - } - } - } - } - return anyResource; -} - -bool AiInterface::isAlly(const Unit *unit) const{ - return world->getFaction(factionIndex)->isAlly(unit->getFaction()); -} -bool AiInterface::reqsOk(const RequirableType *rt){ - return world->getFaction(factionIndex)->reqsOk(rt); -} - -bool AiInterface::reqsOk(const CommandType *ct){ - return world->getFaction(factionIndex)->reqsOk(ct); +// return NULL; +// } + +const FactionType *AiInterface::getMyFactionType() { + return world->getFaction(factionIndex)->getType(); +} + +const ControlType AiInterface::getControlType() { + return world->getFaction(factionIndex)->getControlType(); +} + +const TechTree *AiInterface::getTechTree() { return world->getTechTree(); } + +bool AiInterface::isResourceInRegion(const Vec2i &pos, const ResourceType *rt, + Vec2i &resourcePos, int range) const { + const Map *map = world->getMap(); + + int xi = 1; + int xj = 1; + + if (rand() % 2 == 1) { + xi = -1; + } + if (rand() % 2 == 1) { + xj = -1; + } + for (int i = -range; i <= range; ++i) { + for (int j = -range; j <= range; ++j) { + int ii = xi * i; + int jj = xj * j; + if (map->isInside(pos.x + ii, pos.y + jj)) { + Resource *r = map->getSurfaceCell( + map->toSurfCoords(Vec2i(pos.x + ii, pos.y + jj))) + ->getResource(); + if (r != NULL) { + if (r->getType() == rt) { + resourcePos = pos + Vec2i(ii, jj); + return true; + } + } + } + } + } + return false; +} + +// returns if there is a resource next to a unit, in "resourcePos" is stored the +// relative position of the resource +bool AiInterface::isResourceNear( + const Vec2i &pos, const ResourceType *rt, Vec2i &resourcePos, + Faction *faction, bool fallbackToPeersHarvestingSameResource) const { + const Map *map = world->getMap(); + int size = 1; + for (int i = -1; i <= size; ++i) { + for (int j = -1; j <= size; ++j) { + if (map->isInside(pos.x + i, pos.y + j)) { + Resource *r = + map->getSurfaceCell(map->toSurfCoords(Vec2i(pos.x + i, pos.y + j))) + ->getResource(); + if (r != NULL) { + if (r->getType() == rt) { + resourcePos = pos + Vec2i(i, j); + + return true; + } + } + } + } + } + + if (fallbackToPeersHarvestingSameResource == true && faction != NULL) { + // Look for another unit that is currently harvesting the same resource + // type right now + + // Check the faction cache for a known position where we can harvest + // this resource type + Vec2i result = faction->getClosestResourceTypeTargetFromCache(pos, rt); + if (result.x >= 0) { + resourcePos = result; + + if (pos.dist(resourcePos) <= size) { + return true; + } + } + } + + return false; +} + +bool AiInterface::getNearestSightedResource(const ResourceType *rt, + const Vec2i &pos, Vec2i &resultPos, + bool usableResourceTypeOnly) { + Faction *faction = world->getFaction(factionIndex); + // float tmpDist=0; + float nearestDist = infinity; + bool anyResource = false; + resultPos.x = -1; + resultPos.y = -1; + + bool canUseResourceType = (usableResourceTypeOnly == false); + if (usableResourceTypeOnly == true) { + // can any unit harvest this resource yet? + std::map::iterator iterFind = + cacheUnitHarvestResourceLookup.find(rt); + + if (iterFind != cacheUnitHarvestResourceLookup.end() && + faction->findUnit(iterFind->second) != NULL) { + canUseResourceType = true; + } else { + int unitCount = getMyUnitCount(); + for (int i = 0; i < unitCount; ++i) { + const Unit *unit = getMyUnit(i); + const HarvestCommandType *hct = + unit->getType()->getFirstHarvestCommand(rt, unit->getFaction()); + if (hct != NULL) { + canUseResourceType = true; + cacheUnitHarvestResourceLookup[rt] = unit->getId(); + break; + } + } + } + } + + if (canUseResourceType == true) { + bool isResourceClose = isResourceNear(pos, rt, resultPos, faction, true); + + // Found a resource + if (isResourceClose == true || resultPos.x >= 0) { + anyResource = true; + } else { + const Map *map = world->getMap(); + for (int i = 0; i < map->getW(); ++i) { + for (int j = 0; j < map->getH(); ++j) { + Vec2i resPos = Vec2i(i, j); + Vec2i surfPos = Map::toSurfCoords(resPos); + SurfaceCell *sc = map->getSurfaceCell(surfPos); + + // if explored cell + if (sc != NULL && sc->isExplored(teamIndex)) { + Resource *r = sc->getResource(); + + // if resource cell + if (r != NULL) { + if (r->getType() == rt) { + float tmpDist = pos.dist(resPos); + if (tmpDist < nearestDist) { + anyResource = true; + nearestDist = tmpDist; + resultPos = resPos; + } + } + } + } + } + } + } + } + return anyResource; +} + +bool AiInterface::isAlly(const Unit *unit) const { + return world->getFaction(factionIndex)->isAlly(unit->getFaction()); +} +bool AiInterface::reqsOk(const RequirableType *rt) { + return world->getFaction(factionIndex)->reqsOk(rt); +} + +bool AiInterface::reqsOk(const CommandType *ct) { + return world->getFaction(factionIndex)->reqsOk(ct); } bool AiInterface::checkCosts(const ProducibleType *pt, const CommandType *ct) { - return world->getFaction(factionIndex)->checkCosts(pt,ct); + return world->getFaction(factionIndex)->checkCosts(pt, ct); } -bool AiInterface::isFreeCells(const Vec2i &pos, int size, Field field){ - return world->getMap()->isFreeCells(pos, size, field); +bool AiInterface::isFreeCells(const Vec2i &pos, int size, Field field) { + return world->getMap()->isFreeCells(pos, size, field); } void AiInterface::removeEnemyWarningPositionFromList(Vec2i &checkPos) { - for(int i = (int)enemyWarningPositionList.size() - 1; i >= 0; --i) { - Vec2i &pos = enemyWarningPositionList[i]; - - if(checkPos == pos) { - enemyWarningPositionList.erase(enemyWarningPositionList.begin()+i); - break; - } - } -} - -const Unit *AiInterface::getFirstOnSightEnemyUnit(Vec2i &pos, Field &field, int radius) { - Map *map= world->getMap(); - - const int CHECK_RADIUS = 12; - const int WARNING_ENEMY_COUNT = 6; - - for(int i = 0; i < world->getFactionCount(); ++i) { - for(int j = 0; j < world->getFaction(i)->getUnitCount(); ++j) { - Unit * unit= world->getFaction(i)->getUnit(j); - SurfaceCell *sc= map->getSurfaceCell(Map::toSurfCoords(unit->getPos())); - bool cannotSeeUnit = (unit->getType()->hasCellMap() == true && - unit->getType()->getAllowEmptyCellMap() == true && - unit->getType()->hasEmptyCellMap() == true); - - if(sc->isVisible(teamIndex) && cannotSeeUnit == false && - isAlly(unit) == false && unit->isAlive() == true) { - pos= unit->getPos(); - field= unit->getCurrField(); - if(pos.dist(getHomeLocation()) < radius) { - printLog(2, "Being attacked at pos "+intToStr(pos.x)+","+intToStr(pos.y)+"\n"); - - // Now check if there are more than x enemies in sight and if - // so make note of the position - int foundEnemies = 0; - std::map foundEnemyList; - for(int aiX = pos.x-CHECK_RADIUS; aiX < pos.x + CHECK_RADIUS; ++aiX) { - for(int aiY = pos.y-CHECK_RADIUS; aiY < pos.y + CHECK_RADIUS; ++aiY) { - Vec2i checkPos(aiX,aiY); - if(map->isInside(checkPos) && map->isInsideSurface(map->toSurfCoords(checkPos))) { - Cell *cAI = map->getCell(checkPos); - SurfaceCell *scAI = map->getSurfaceCell(Map::toSurfCoords(checkPos)); - if(scAI != NULL && cAI != NULL && cAI->getUnit(field) != NULL && sc->isVisible(teamIndex)) { - const Unit *checkUnit = cAI->getUnit(field); - if(foundEnemyList.find(checkUnit->getId()) == foundEnemyList.end()) { - bool cannotSeeUnitAI = (checkUnit->getType()->hasCellMap() == true && - checkUnit->getType()->getAllowEmptyCellMap() == true && - checkUnit->getType()->hasEmptyCellMap() == true); - if(cannotSeeUnitAI == false && isAlly(checkUnit) == false - && checkUnit->isAlive() == true) { - foundEnemies++; - foundEnemyList[checkUnit->getId()] = true; - } - } - } - } - } - } - if(foundEnemies >= WARNING_ENEMY_COUNT) { - if(std::find(enemyWarningPositionList.begin(),enemyWarningPositionList.end(),pos) == enemyWarningPositionList.end()) { - enemyWarningPositionList.push_back(pos); - } - } - return unit; + for (int i = (int)enemyWarningPositionList.size() - 1; i >= 0; --i) { + Vec2i &pos = enemyWarningPositionList[i]; + + if (checkPos == pos) { + enemyWarningPositionList.erase(enemyWarningPositionList.begin() + i); + break; + } + } +} + +const Unit *AiInterface::getFirstOnSightEnemyUnit(Vec2i &pos, Field &field, + int radius) { + Map *map = world->getMap(); + + const int CHECK_RADIUS = 12; + const int WARNING_ENEMY_COUNT = 6; + + for (int i = 0; i < world->getFactionCount(); ++i) { + for (int j = 0; j < world->getFaction(i)->getUnitCount(); ++j) { + Unit *unit = world->getFaction(i)->getUnit(j); + SurfaceCell *sc = map->getSurfaceCell(Map::toSurfCoords(unit->getPos())); + bool cannotSeeUnit = (unit->getType()->hasCellMap() == true && + unit->getType()->getAllowEmptyCellMap() == true && + unit->getType()->hasEmptyCellMap() == true); + + if (sc->isVisible(teamIndex) && cannotSeeUnit == false && + isAlly(unit) == false && unit->isAlive() == true) { + pos = unit->getPos(); + field = unit->getCurrField(); + if (pos.dist(getHomeLocation()) < radius) { + printLog(2, "Being attacked at pos " + intToStr(pos.x) + "," + + intToStr(pos.y) + "\n"); + + // Now check if there are more than x enemies in sight and if + // so make note of the position + int foundEnemies = 0; + std::map foundEnemyList; + for (int aiX = pos.x - CHECK_RADIUS; aiX < pos.x + CHECK_RADIUS; + ++aiX) { + for (int aiY = pos.y - CHECK_RADIUS; aiY < pos.y + CHECK_RADIUS; + ++aiY) { + Vec2i checkPos(aiX, aiY); + if (map->isInside(checkPos) && + map->isInsideSurface(map->toSurfCoords(checkPos))) { + Cell *cAI = map->getCell(checkPos); + SurfaceCell *scAI = + map->getSurfaceCell(Map::toSurfCoords(checkPos)); + if (scAI != NULL && cAI != NULL && + cAI->getUnit(field) != NULL && sc->isVisible(teamIndex)) { + const Unit *checkUnit = cAI->getUnit(field); + if (foundEnemyList.find(checkUnit->getId()) == + foundEnemyList.end()) { + bool cannotSeeUnitAI = + (checkUnit->getType()->hasCellMap() == true && + checkUnit->getType()->getAllowEmptyCellMap() == true && + checkUnit->getType()->hasEmptyCellMap() == true); + if (cannotSeeUnitAI == false && + isAlly(checkUnit) == false && + checkUnit->isAlive() == true) { + foundEnemies++; + foundEnemyList[checkUnit->getId()] = true; + } + } } + } + } + } + if (foundEnemies >= WARNING_ENEMY_COUNT) { + if (std::find(enemyWarningPositionList.begin(), + enemyWarningPositionList.end(), + pos) == enemyWarningPositionList.end()) { + enemyWarningPositionList.push_back(pos); } + } + return unit; } - } - return NULL; + } + } + } + return NULL; } -Map * AiInterface::getMap() { - Map *map= world->getMap(); - return map; +Map *AiInterface::getMap() { + Map *map = world->getMap(); + return map; } -bool AiInterface::factionUsesResourceType(const FactionType *factionType, const ResourceType *rt) { - bool factionUsesResourceType = factionType->factionUsesResourceType(rt); - return factionUsesResourceType; +bool AiInterface::factionUsesResourceType(const FactionType *factionType, + const ResourceType *rt) { + bool factionUsesResourceType = factionType->factionUsesResourceType(rt); + return factionUsesResourceType; } void AiInterface::saveGame(XmlNode *rootNode) const { - std::map mapTagReplacements; - XmlNode *aiInterfaceNode = rootNode->addChild("AiInterface"); + std::map mapTagReplacements; + XmlNode *aiInterfaceNode = rootNode->addChild("AiInterface"); + + // World *world; + // Commander *commander; + // Console *console; + // GameSettings *gameSettings; + // + // Ai ai; + ai.saveGame(aiInterfaceNode); + // int timer; + aiInterfaceNode->addAttribute("timer", intToStr(timer), mapTagReplacements); + // int factionIndex; + aiInterfaceNode->addAttribute("factionIndex", intToStr(factionIndex), + mapTagReplacements); + // int teamIndex; + aiInterfaceNode->addAttribute("teamIndex", intToStr(teamIndex), + mapTagReplacements); + // //config + // bool redir; + aiInterfaceNode->addAttribute("redir", intToStr(redir), mapTagReplacements); + // int logLevel; + aiInterfaceNode->addAttribute("logLevel", intToStr(logLevel), + mapTagReplacements); + // std::map cacheUnitHarvestResourceLookup; + for (std::map::const_iterator iterMap = + cacheUnitHarvestResourceLookup.begin(); + iterMap != cacheUnitHarvestResourceLookup.end(); ++iterMap) { + XmlNode *cacheUnitHarvestResourceLookupNode = + aiInterfaceNode->addChild("cacheUnitHarvestResourceLookup"); + + cacheUnitHarvestResourceLookupNode->addAttribute( + "key", iterMap->first->getName(), mapTagReplacements); + cacheUnitHarvestResourceLookupNode->addAttribute( + "value", intToStr(iterMap->second), mapTagReplacements); + } +} -// World *world; -// Commander *commander; -// Console *console; -// GameSettings *gameSettings; -// -// Ai ai; - ai.saveGame(aiInterfaceNode); -// int timer; - aiInterfaceNode->addAttribute("timer",intToStr(timer), mapTagReplacements); -// int factionIndex; - aiInterfaceNode->addAttribute("factionIndex",intToStr(factionIndex), mapTagReplacements); -// int teamIndex; - aiInterfaceNode->addAttribute("teamIndex",intToStr(teamIndex), mapTagReplacements); -// //config -// bool redir; - aiInterfaceNode->addAttribute("redir",intToStr(redir), mapTagReplacements); -// int logLevel; - aiInterfaceNode->addAttribute("logLevel",intToStr(logLevel), mapTagReplacements); -// std::map cacheUnitHarvestResourceLookup; - for(std::map::const_iterator iterMap = cacheUnitHarvestResourceLookup.begin(); - iterMap != cacheUnitHarvestResourceLookup.end(); ++iterMap) { - XmlNode *cacheUnitHarvestResourceLookupNode = aiInterfaceNode->addChild("cacheUnitHarvestResourceLookup"); - - cacheUnitHarvestResourceLookupNode->addAttribute("key",iterMap->first->getName(), mapTagReplacements); - cacheUnitHarvestResourceLookupNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); - } -} - -// AiInterface::AiInterface(Game &game, int factionIndex, int teamIndex, int useStartLocation) { +// AiInterface::AiInterface(Game &game, int factionIndex, int teamIndex, int +// useStartLocation) { void AiInterface::loadGame(const XmlNode *rootNode, Faction *faction) { - XmlNode *aiInterfaceNode = NULL; - vector aiInterfaceNodeList = rootNode->getChildList("AiInterface"); - for(unsigned int i = 0; i < aiInterfaceNodeList.size(); ++i) { - XmlNode *node = aiInterfaceNodeList[i]; - if(node->getAttribute("factionIndex")->getIntValue() == faction->getIndex()) { - aiInterfaceNode = node; - break; - } - } - - if(aiInterfaceNode != NULL) { - factionIndex = aiInterfaceNode->getAttribute("factionIndex")->getIntValue(); - teamIndex = aiInterfaceNode->getAttribute("teamIndex")->getIntValue(); - - ai.loadGame(aiInterfaceNode, faction); - //firstTime = timeflowNode->getAttribute("firstTime")->getFloatValue(); - - timer = aiInterfaceNode->getAttribute("timer")->getIntValue(); - // int factionIndex; - //factionIndex = aiInterfaceNode->getAttribute("factionIndex")->getIntValue(); - // int teamIndex; - //teamIndex = aiInterfaceNode->getAttribute("teamIndex")->getIntValue(); - // //config - // bool redir; - redir = aiInterfaceNode->getAttribute("redir")->getIntValue() != 0; - // int logLevel; - logLevel = aiInterfaceNode->getAttribute("logLevel")->getIntValue(); - - // std::map cacheUnitHarvestResourceLookup; - // for(std::map::const_iterator iterMap = cacheUnitHarvestResourceLookup.begin(); - // iterMap != cacheUnitHarvestResourceLookup.end(); ++iterMap) { - // XmlNode *cacheUnitHarvestResourceLookupNode = aiInterfaceNode->addChild("cacheUnitHarvestResourceLookup"); - // - // cacheUnitHarvestResourceLookupNode->addAttribute("key",iterMap->first->getName(), mapTagReplacements); - // cacheUnitHarvestResourceLookupNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); - // } - } -} - -}}//end namespace + XmlNode *aiInterfaceNode = NULL; + vector aiInterfaceNodeList = rootNode->getChildList("AiInterface"); + for (unsigned int i = 0; i < aiInterfaceNodeList.size(); ++i) { + XmlNode *node = aiInterfaceNodeList[i]; + if (node->getAttribute("factionIndex")->getIntValue() == + faction->getIndex()) { + aiInterfaceNode = node; + break; + } + } + + if (aiInterfaceNode != NULL) { + factionIndex = aiInterfaceNode->getAttribute("factionIndex")->getIntValue(); + teamIndex = aiInterfaceNode->getAttribute("teamIndex")->getIntValue(); + + ai.loadGame(aiInterfaceNode, faction); + // firstTime = timeflowNode->getAttribute("firstTime")->getFloatValue(); + + timer = aiInterfaceNode->getAttribute("timer")->getIntValue(); + // int factionIndex; + // factionIndex = + // aiInterfaceNode->getAttribute("factionIndex")->getIntValue(); + // int teamIndex; + // teamIndex = aiInterfaceNode->getAttribute("teamIndex")->getIntValue(); + // //config + // bool redir; + redir = aiInterfaceNode->getAttribute("redir")->getIntValue() != 0; + // int logLevel; + logLevel = aiInterfaceNode->getAttribute("logLevel")->getIntValue(); + + // std::map cacheUnitHarvestResourceLookup; + // for(std::map::const_iterator iterMap = + // cacheUnitHarvestResourceLookup.begin(); iterMap != + // cacheUnitHarvestResourceLookup.end(); ++iterMap) { XmlNode + //*cacheUnitHarvestResourceLookupNode = + // aiInterfaceNode->addChild("cacheUnitHarvestResourceLookup"); + // + // cacheUnitHarvestResourceLookupNode->addAttribute("key",iterMap->first->getName(), + // mapTagReplacements); + // cacheUnitHarvestResourceLookupNode->addAttribute("value",intToStr(iterMap->second), + // mapTagReplacements); + // } + } +} + +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/ai/ai_interface.h b/source/glest_game/ai/ai_interface.h index f83247733..9f051132b 100644 --- a/source/glest_game/ai/ai_interface.h +++ b/source/glest_game/ai/ai_interface.h @@ -12,18 +12,19 @@ #ifndef _GLEST_GAME_AIINTERFACE_H_ #define _GLEST_GAME_AIINTERFACE_H_ -#include "world.h" -#include "commander.h" +#include "ai.h" #include "command.h" +#include "commander.h" #include "conversion.h" -#include "ai.h" #include "game_settings.h" -#include #include "leak_dumper.h" +#include "world.h" +#include using Shared::Util::intToStr; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class AiInterface @@ -31,142 +32,168 @@ namespace Glest{ namespace Game{ /// The AI will interact with the game through this interface // ===================================================== -class AiInterfaceThread : public BaseThread, public SlaveThreadControllerInterface { +class AiInterfaceThread : public BaseThread, + public SlaveThreadControllerInterface { protected: + AiInterface *aiIntf; + Semaphore semTaskSignalled; + Mutex *triggerIdMutex; + std::pair frameIndex; + MasterSlaveThreadController *masterController; - AiInterface *aiIntf; - Semaphore semTaskSignalled; - Mutex *triggerIdMutex; - std::pair frameIndex; - MasterSlaveThreadController *masterController; - - virtual void setQuitStatus(bool value); - virtual void setTaskCompleted(int frameIndex); + virtual void setQuitStatus(bool value); + virtual void setTaskCompleted(int frameIndex); public: - explicit AiInterfaceThread(AiInterface *aiIntf); - virtual ~AiInterfaceThread(); - virtual void execute(); - void signal(int frameIndex); - bool isSignalCompleted(int frameIndex); - - virtual void setMasterController(MasterSlaveThreadController *master) { masterController = master; } - virtual void signalSlave(void *userdata) { signal(*((int *)(userdata))); } - - virtual void signalQuit(); - virtual bool canShutdown(bool deleteSelfIfShutdownDelayed=false); + explicit AiInterfaceThread(AiInterface *aiIntf); + virtual ~AiInterfaceThread(); + virtual void execute(); + void signal(int frameIndex); + bool isSignalCompleted(int frameIndex); + + virtual void setMasterController(MasterSlaveThreadController *master) { + masterController = master; + } + virtual void signalSlave(void *userdata) { signal(*((int *)(userdata))); } + + virtual void signalQuit(); + virtual bool canShutdown(bool deleteSelfIfShutdownDelayed = false); }; class AiInterface { private: - World *world; - Commander *commander; - Console *console; - GameSettings *gameSettings; + World *world; + Commander *commander; + Console *console; + GameSettings *gameSettings; - Ai ai; + Ai ai; - int timer; - int factionIndex; - int teamIndex; + int timer; + int factionIndex; + int teamIndex; - //config - bool redir; - int logLevel; - std::string aiLogFile; - FILE *fp; + // config + bool redir; + int logLevel; + std::string aiLogFile; + FILE *fp; - std::map cacheUnitHarvestResourceLookup; + std::map cacheUnitHarvestResourceLookup; - Mutex *aiMutex; + Mutex *aiMutex; - AiInterfaceThread *workerThread; - std::vector enemyWarningPositionList; + AiInterfaceThread *workerThread; + std::vector enemyWarningPositionList; public: - AiInterface(Game &game, int factionIndex, int teamIndex, int useStartLocation=-1); - ~AiInterface(); - - AiInterface(const AiInterface& obj) { - init(); - throw megaglest_runtime_error("class AiInterface is NOT safe to copy!"); - } - AiInterface & operator=(const AiInterface& obj) { - init(); - throw megaglest_runtime_error("class AiInterface is NOT safe to assign!"); - } - - //main - void update(); - - std::vector getEnemyWarningPositionList() const { return enemyWarningPositionList; } - void removeEnemyWarningPositionFromList(Vec2i &checkPos); - - inline Mutex * getMutex() {return aiMutex;} - - void signalWorkerThread(int frameIndex); - bool isWorkerThreadSignalCompleted(int frameIndex); - AiInterfaceThread *getWorkerThread() { return workerThread; } - - bool isLogLevelEnabled(int level); - - //get - int getTimer() const {return timer;} - int getFactionIndex() const {return factionIndex;} - - //misc - void printLog(int logLevel, const string &s); - - //interact - std::pair giveCommand(int unitIndex, CommandClass commandClass, const Vec2i &pos=Vec2i(0)); - std::pair giveCommand(int unitIndex, const CommandType *commandType, const Vec2i &pos, const UnitType* unitType); - std::pair giveCommand(int unitIndex, const CommandType *commandType, const Vec2i &pos, int unitGroupCommandId); - std::pair giveCommand(int unitIndex, const CommandType *commandType, Unit *u= NULL); - std::pair giveCommand(const Unit *unit, const CommandType *commandType, const Vec2i &pos, int unitGroupCommandId); - - std::pair giveCommandSwitchTeamVote(const Faction* faction, SwitchTeamVote *vote); - - //get data - const ControlType getControlType(); - int getMapMaxPlayers(); - Vec2i getHomeLocation(); - Vec2i getStartLocation(int locationIndex); - int getFactionCount(); - int getMyUnitCount() const; - int getMyUpgradeCount() const; - //int onSightUnitCount(); - const Resource *getResource(const ResourceType *rt); - const Unit *getMyUnit(int unitIndex); - Unit *getMyUnitPtr(int unitIndex); - //const Unit *getOnSightUnit(int unitIndex); - const FactionType *getMyFactionType(); - Faction *getMyFaction(); - const TechTree *getTechTree(); - bool isResourceInRegion(const Vec2i &pos, const ResourceType *rt, Vec2i &resourcePos, int range) const; - bool isResourceNear(const Vec2i &pos, const ResourceType *rt, Vec2i &resourcePos, Faction *faction, bool fallbackToPeersHarvestingSameResource) const; - bool getNearestSightedResource(const ResourceType *rt, const Vec2i &pos, Vec2i &resultPos, bool usableResourceTypeOnly); - bool isAlly(const Unit *unit) const; - bool isAlly(int factionIndex) const; - bool reqsOk(const RequirableType *rt); - bool reqsOk(const CommandType *ct); - bool checkCosts(const ProducibleType *pt, const CommandType *ct); - bool isFreeCells(const Vec2i &pos, int size, Field field); - const Unit *getFirstOnSightEnemyUnit(Vec2i &pos, Field &field, int radius); - Map * getMap(); - World * getWorld() { return world; } - - bool factionUsesResourceType(const FactionType *factionType, const ResourceType *rt); - - void saveGame(XmlNode *rootNode) const; - void loadGame(const XmlNode *rootNode, Faction *faction); + AiInterface(Game &game, int factionIndex, int teamIndex, + int useStartLocation = -1); + ~AiInterface(); + + AiInterface(const AiInterface &obj) { + init(); + throw megaglest_runtime_error("class AiInterface is NOT safe to copy!"); + } + AiInterface &operator=(const AiInterface &obj) { + init(); + throw megaglest_runtime_error("class AiInterface is NOT safe to assign!"); + } + + // main + void update(); + + std::vector getEnemyWarningPositionList() const { + return enemyWarningPositionList; + } + void removeEnemyWarningPositionFromList(Vec2i &checkPos); + + inline Mutex *getMutex() { return aiMutex; } + + void signalWorkerThread(int frameIndex); + bool isWorkerThreadSignalCompleted(int frameIndex); + AiInterfaceThread *getWorkerThread() { return workerThread; } + + bool isLogLevelEnabled(int level); + + // get + int getTimer() const { return timer; } + int getFactionIndex() const { return factionIndex; } + + // misc + void printLog(int logLevel, const string &s); + + // interact + std::pair giveCommand(int unitIndex, + CommandClass commandClass, + const Vec2i &pos = Vec2i(0)); + std::pair giveCommand(int unitIndex, + const CommandType *commandType, + const Vec2i &pos, + const UnitType *unitType); + std::pair giveCommand(int unitIndex, + const CommandType *commandType, + const Vec2i &pos, + int unitGroupCommandId); + std::pair + giveCommand(int unitIndex, const CommandType *commandType, Unit *u = NULL); + std::pair giveCommand(const Unit *unit, + const CommandType *commandType, + const Vec2i &pos, + int unitGroupCommandId); + + std::pair + giveCommandSwitchTeamVote(const Faction *faction, SwitchTeamVote *vote); + + // get data + const ControlType getControlType(); + int getMapMaxPlayers(); + Vec2i getHomeLocation(); + Vec2i getStartLocation(int locationIndex); + int getFactionCount(); + int getMyUnitCount() const; + int getMyUpgradeCount() const; + // int onSightUnitCount(); + const Resource *getResource(const ResourceType *rt); + const Unit *getMyUnit(int unitIndex); + Unit *getMyUnitPtr(int unitIndex); + // const Unit *getOnSightUnit(int unitIndex); + const FactionType *getMyFactionType(); + Faction *getMyFaction(); + const TechTree *getTechTree(); + bool isResourceInRegion(const Vec2i &pos, const ResourceType *rt, + Vec2i &resourcePos, int range) const; + bool isResourceNear(const Vec2i &pos, const ResourceType *rt, + Vec2i &resourcePos, Faction *faction, + bool fallbackToPeersHarvestingSameResource) const; + bool getNearestSightedResource(const ResourceType *rt, const Vec2i &pos, + Vec2i &resultPos, bool usableResourceTypeOnly); + bool isAlly(const Unit *unit) const; + bool isAlly(int factionIndex) const; + bool reqsOk(const RequirableType *rt); + bool reqsOk(const CommandType *ct); + bool checkCosts(const ProducibleType *pt, const CommandType *ct); + bool isFreeCells(const Vec2i &pos, int size, Field field); + const Unit *getFirstOnSightEnemyUnit(Vec2i &pos, Field &field, int radius); + Map *getMap(); + World *getWorld() { return world; } + + bool factionUsesResourceType(const FactionType *factionType, + const ResourceType *rt); + + void saveGame(XmlNode *rootNode) const; + void loadGame(const XmlNode *rootNode, Faction *faction); private: - string getLogFilename() const {return "ai"+intToStr(factionIndex)+".log";} - bool executeCommandOverNetwork(); + string getLogFilename() const { + return "ai" + intToStr(factionIndex) + ".log"; + } + bool executeCommandOverNetwork(); - void init(); + void init(); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/ai/ai_rule.cpp b/source/glest_game/ai/ai_rule.cpp index 58365f96f..d1bff6b2f 100644 --- a/source/glest_game/ai/ai_rule.cpp +++ b/source/glest_game/ai/ai_rule.cpp @@ -15,2128 +15,2686 @@ #include "ai.h" #include "ai_interface.h" -#include "unit.h" #include "leak_dumper.h" +#include "unit.h" using Shared::Graphics::Vec2i; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class AiRule // ===================================================== -AiRule::AiRule(Ai *ai){ - this->ai= ai; -} +AiRule::AiRule(Ai *ai) { this->ai = ai; } // ===================================================== // class AiRuleWorkerHarvest // ===================================================== -AiRuleWorkerHarvest::AiRuleWorkerHarvest(Ai *ai): - AiRule(ai) -{ - stoppedWorkerIndex= -1; +AiRuleWorkerHarvest::AiRuleWorkerHarvest(Ai *ai) : AiRule(ai) { + stoppedWorkerIndex = -1; } -bool AiRuleWorkerHarvest::test(){ - return ai->findAbleUnit(&stoppedWorkerIndex, ccHarvest, true); +bool AiRuleWorkerHarvest::test() { + return ai->findAbleUnit(&stoppedWorkerIndex, ccHarvest, true); } -void AiRuleWorkerHarvest::execute(){ - ai->harvest(stoppedWorkerIndex); -} +void AiRuleWorkerHarvest::execute() { ai->harvest(stoppedWorkerIndex); } // ===================================================== // class AiRuleRefreshHarvester // ===================================================== -AiRuleRefreshHarvester::AiRuleRefreshHarvester(Ai *ai): - AiRule(ai) -{ - workerIndex= -1; +AiRuleRefreshHarvester::AiRuleRefreshHarvester(Ai *ai) : AiRule(ai) { + workerIndex = -1; } -bool AiRuleRefreshHarvester::test(){ - return ai->findAbleUnit(&workerIndex, ccHarvest, ccHarvest); +bool AiRuleRefreshHarvester::test() { + return ai->findAbleUnit(&workerIndex, ccHarvest, ccHarvest); } -void AiRuleRefreshHarvester::execute(){ - ai->harvest(workerIndex); -} +void AiRuleRefreshHarvester::execute() { ai->harvest(workerIndex); } // ===================================================== // class AiRuleScoutPatrol // ===================================================== -AiRuleScoutPatrol::AiRuleScoutPatrol(Ai *ai): - AiRule(ai) -{ -} +AiRuleScoutPatrol::AiRuleScoutPatrol(Ai *ai) : AiRule(ai) {} -bool AiRuleScoutPatrol::test(){ - return ai->isStableBase(); -} +bool AiRuleScoutPatrol::test() { return ai->isStableBase(); } -void AiRuleScoutPatrol::execute(){ - ai->sendScoutPatrol(); -} +void AiRuleScoutPatrol::execute() { ai->sendScoutPatrol(); } // ===================================================== // class AiRuleRepair // ===================================================== -AiRuleRepair::AiRuleRepair(Ai *ai): - AiRule(ai) -{ - damagedUnitIndex = 0; - damagedUnitIsCastle = false; +AiRuleRepair::AiRuleRepair(Ai *ai) : AiRule(ai) { + damagedUnitIndex = 0; + damagedUnitIsCastle = false; } -double AiRuleRepair::getMinCastleHpRatio() const { - return 0.6; -} +double AiRuleRepair::getMinCastleHpRatio() const { return 0.6; } int AiRuleRepair::getMinUnitsToRepairCastle() { - int minUnitsRepairingCastle = 7; - if(ai->getCountOfClass(ucWorker) <= 6){ - minUnitsRepairingCastle= 1; - } - else if(ai->getCountOfClass(ucWorker) <= 8){ - minUnitsRepairingCastle= 2; - } - else if(ai->getCountOfClass(ucWorker) <= 10){ - minUnitsRepairingCastle= 3; - } - else if(ai->getCountOfClass(ucWorker) <= 12){ - minUnitsRepairingCastle= 5; - } - return minUnitsRepairingCastle; + int minUnitsRepairingCastle = 7; + if (ai->getCountOfClass(ucWorker) <= 6) { + minUnitsRepairingCastle = 1; + } else if (ai->getCountOfClass(ucWorker) <= 8) { + minUnitsRepairingCastle = 2; + } else if (ai->getCountOfClass(ucWorker) <= 10) { + minUnitsRepairingCastle = 3; + } else if (ai->getCountOfClass(ucWorker) <= 12) { + minUnitsRepairingCastle = 5; + } + return minUnitsRepairingCastle; } -bool AiRuleRepair::test(){ - AiInterface *aiInterface= ai->getAiInterface(); - - int minUnitsRepairingCastle = getMinUnitsToRepairCastle(); - const double minCastleHpRatio = getMinCastleHpRatio(); - - // look for a damaged unit and give priority to the factions bases - // (units that produce workers and store resources) - for(int i = 0; i < aiInterface->getMyUnitCount(); ++i) { - const Unit *u= aiInterface->getMyUnit(i); - //printf("\n\n\n\n!!!!!! Is damaged unit [%d - %s] u->getHpRatio() = %f, hp = %d, mapHp = %d\n",u->getId(),u->getType()->getName().c_str(),u->getHpRatio(),u->getHp(),u->getType()->getTotalMaxHp(u->getTotalUpgrade())); - if(u->getHpRatio() < 1.f) { - //printf("\n\n\n\n!!!!!! Is damaged unit [%d - %s] u->getHpRatio() = %f, hp = %d, mapHp = %d\n",u->getId(),u->getType()->getName().c_str(),u->getHpRatio(),u->getHp(),u->getType()->getTotalMaxHp(u->getTotalUpgrade())); - - bool unitCanProduceWorker = false; - for(int j = 0; unitCanProduceWorker == false && - j < u->getType()->getCommandTypeCount(); ++j) { - const CommandType *ct= u->getType()->getCommandType(j); - - //if the command is produce - if(ct->getClass() == ccProduce || ct->getClass() == ccMorph) { - const ProducibleType *pt = ct->getProduced(); - if(pt != NULL) { - const UnitType *ut = dynamic_cast(pt); - if( ut != NULL && ut->hasCommandClass(ccHarvest) == true && - u->getType()->getStoredResourceCount() > 0) { - //printf("\n\n\n\n!!!!!! found candidate castle unit to repair [%d - %s]\n",u->getId(),u->getType()->getName().c_str()); - unitCanProduceWorker = true; - } - } - } - } - - if(unitCanProduceWorker == true) { - int candidatedamagedUnitIndex=-1; - int unitCountAlreadyRepairingDamagedUnit = 0; - // Now check if any other unit is able to repair this unit - for(int i1 = 0; i1 < aiInterface->getMyUnitCount(); ++i1) { - const Unit *u1= aiInterface->getMyUnit(i1); - const RepairCommandType *rct= static_cast(u1->getType()->getFirstCtOfClass(ccRepair)); - //if(rct) printf("\n\n\n\n^^^^^^^^^^ possible repairer unit [%d - %s] current skill [%d] can reapir damaged unit [%d]\n",u1->getId(),u1->getType()->getName().c_str(),u->getCurrSkill()->getClass(),rct->isRepairableUnitType(u->getType())); - - if(rct != NULL) { - //printf("\n\n\n\n^^^^^^^^^^ possible repairer unit [%d - %s] current skill [%d] can repair damaged unit [%d] Castles hp-ratio = %f\n",u1->getId(),u1->getType()->getName().c_str(),u1->getCurrSkill()->getClass(),rct->isRepairableUnitType(u->getType()),u->getHpRatio()); - - if(u1->getCurrSkill()->getClass() == scStop || u1->getCurrSkill()->getClass() == scMove || - u->getHpRatio() <= minCastleHpRatio) { - if(rct->isRepairableUnitType(u->getType())) { - candidatedamagedUnitIndex= i; - //return true; - } - } - else if(u1->getCurrSkill()->getClass() == scRepair) { - Command *cmd = u1->getCurrCommand(); - if(cmd != NULL && cmd->getCommandType()->getClass() == ccRepair) { - if(cmd->getUnit() != NULL && cmd->getUnit()->getId() == u->getId()) { - //printf("\n\n\n\n^^^^^^^^^^ unit is ALREADY repairer unit [%d - %s]\n",u1->getId(),u1->getType()->getName().c_str()); - unitCountAlreadyRepairingDamagedUnit++; - } - } - } - } - } - - if(candidatedamagedUnitIndex >= 0 && unitCountAlreadyRepairingDamagedUnit < minUnitsRepairingCastle) { - //printf("\n\n\n\n^^^^^^^^^^ AI test will repair damaged unit [%d - %s]\n",u->getId(),u->getType()->getName().c_str()); - damagedUnitIndex = candidatedamagedUnitIndex; - damagedUnitIsCastle=true; - return true; - } - } - } - } - damagedUnitIsCastle=false; - damagedUnitIndex=-1; - // Normal Repair checking - for(int i = 0; i < aiInterface->getMyUnitCount(); ++i) { - const Unit *u= aiInterface->getMyUnit(i); - //printf("\n\n\n\n!!!!!! Is damaged unit [%d - %s] u->getHpRatio() = %f, hp = %d, mapHp = %d\n",u->getId(),u->getType()->getName().c_str(),u->getHpRatio(),u->getHp(),u->getType()->getTotalMaxHp(u->getTotalUpgrade())); - if(u->getHpRatio() < 1.f) { - // Now check if any other unit is able to repair this unit - for(int i1 = 0; i1 < aiInterface->getMyUnitCount(); ++i1) { - const Unit *u1= aiInterface->getMyUnit(i1); - const RepairCommandType *rct= static_cast(u1->getType()->getFirstCtOfClass(ccRepair)); - //if(rct) printf("\n\n\n\n^^^^^^^^^^ possible repairer unit [%d - %s] current skill [%d] can reapir damaged unit [%d]\n",u1->getId(),u1->getType()->getName().c_str(),u->getCurrSkill()->getClass(),rct->isRepairableUnitType(u->getType())); - - if(rct != NULL && (u1->getCurrSkill()->getClass() == scStop || u1->getCurrSkill()->getClass() == scMove)) { - if(rct->isRepairableUnitType(u->getType())) { - damagedUnitIndex= i; - //random if return or not so we get different targets from time to time - if(ai->getRandom()->randRange(0, 1) == 0) - return true; - } - } - } - } - } - if( damagedUnitIndex!=-1) - { - return true; - } - return false; +bool AiRuleRepair::test() { + AiInterface *aiInterface = ai->getAiInterface(); + + int minUnitsRepairingCastle = getMinUnitsToRepairCastle(); + const double minCastleHpRatio = getMinCastleHpRatio(); + + // look for a damaged unit and give priority to the factions bases + // (units that produce workers and store resources) + for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) { + const Unit *u = aiInterface->getMyUnit(i); + // printf("\n\n\n\n!!!!!! Is damaged unit [%d - %s] u->getHpRatio() = %f, hp + // = %d, mapHp = + // %d\n",u->getId(),u->getType()->getName().c_str(),u->getHpRatio(),u->getHp(),u->getType()->getTotalMaxHp(u->getTotalUpgrade())); + if (u->getHpRatio() < 1.f) { + // printf("\n\n\n\n!!!!!! Is damaged unit [%d - %s] u->getHpRatio() = %f, + // hp = %d, mapHp = + // %d\n",u->getId(),u->getType()->getName().c_str(),u->getHpRatio(),u->getHp(),u->getType()->getTotalMaxHp(u->getTotalUpgrade())); + + bool unitCanProduceWorker = false; + for (int j = 0; unitCanProduceWorker == false && + j < u->getType()->getCommandTypeCount(); + ++j) { + const CommandType *ct = u->getType()->getCommandType(j); + + // if the command is produce + if (ct->getClass() == ccProduce || ct->getClass() == ccMorph) { + const ProducibleType *pt = ct->getProduced(); + if (pt != NULL) { + const UnitType *ut = dynamic_cast(pt); + if (ut != NULL && ut->hasCommandClass(ccHarvest) == true && + u->getType()->getStoredResourceCount() > 0) { + // printf("\n\n\n\n!!!!!! found candidate castle unit to repair + // [%d - %s]\n",u->getId(),u->getType()->getName().c_str()); + unitCanProduceWorker = true; + } + } + } + } + + if (unitCanProduceWorker == true) { + int candidatedamagedUnitIndex = -1; + int unitCountAlreadyRepairingDamagedUnit = 0; + // Now check if any other unit is able to repair this unit + for (int i1 = 0; i1 < aiInterface->getMyUnitCount(); ++i1) { + const Unit *u1 = aiInterface->getMyUnit(i1); + const RepairCommandType *rct = static_cast( + u1->getType()->getFirstCtOfClass(ccRepair)); + // if(rct) printf("\n\n\n\n^^^^^^^^^^ possible repairer unit [%d - %s] + // current skill [%d] can reapir damaged unit + // [%d]\n",u1->getId(),u1->getType()->getName().c_str(),u->getCurrSkill()->getClass(),rct->isRepairableUnitType(u->getType())); + + if (rct != NULL) { + // printf("\n\n\n\n^^^^^^^^^^ possible repairer unit [%d - %s] + // current skill [%d] can repair damaged unit [%d] Castles hp-ratio + // = + // %f\n",u1->getId(),u1->getType()->getName().c_str(),u1->getCurrSkill()->getClass(),rct->isRepairableUnitType(u->getType()),u->getHpRatio()); + + if (u1->getCurrSkill()->getClass() == scStop || + u1->getCurrSkill()->getClass() == scMove || + u->getHpRatio() <= minCastleHpRatio) { + if (rct->isRepairableUnitType(u->getType())) { + candidatedamagedUnitIndex = i; + // return true; + } + } else if (u1->getCurrSkill()->getClass() == scRepair) { + Command *cmd = u1->getCurrCommand(); + if (cmd != NULL && + cmd->getCommandType()->getClass() == ccRepair) { + if (cmd->getUnit() != NULL && + cmd->getUnit()->getId() == u->getId()) { + // printf("\n\n\n\n^^^^^^^^^^ unit is ALREADY repairer unit + // [%d - %s]\n",u1->getId(),u1->getType()->getName().c_str()); + unitCountAlreadyRepairingDamagedUnit++; + } + } + } + } + } + + if (candidatedamagedUnitIndex >= 0 && + unitCountAlreadyRepairingDamagedUnit < minUnitsRepairingCastle) { + // printf("\n\n\n\n^^^^^^^^^^ AI test will repair damaged unit [%d - + // %s]\n",u->getId(),u->getType()->getName().c_str()); + damagedUnitIndex = candidatedamagedUnitIndex; + damagedUnitIsCastle = true; + return true; + } + } + } + } + damagedUnitIsCastle = false; + damagedUnitIndex = -1; + // Normal Repair checking + for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) { + const Unit *u = aiInterface->getMyUnit(i); + // printf("\n\n\n\n!!!!!! Is damaged unit [%d - %s] u->getHpRatio() = %f, hp + // = %d, mapHp = + // %d\n",u->getId(),u->getType()->getName().c_str(),u->getHpRatio(),u->getHp(),u->getType()->getTotalMaxHp(u->getTotalUpgrade())); + if (u->getHpRatio() < 1.f) { + // Now check if any other unit is able to repair this unit + for (int i1 = 0; i1 < aiInterface->getMyUnitCount(); ++i1) { + const Unit *u1 = aiInterface->getMyUnit(i1); + const RepairCommandType *rct = static_cast( + u1->getType()->getFirstCtOfClass(ccRepair)); + // if(rct) printf("\n\n\n\n^^^^^^^^^^ possible repairer unit [%d - %s] + // current skill [%d] can reapir damaged unit + // [%d]\n",u1->getId(),u1->getType()->getName().c_str(),u->getCurrSkill()->getClass(),rct->isRepairableUnitType(u->getType())); + + if (rct != NULL && (u1->getCurrSkill()->getClass() == scStop || + u1->getCurrSkill()->getClass() == scMove)) { + if (rct->isRepairableUnitType(u->getType())) { + damagedUnitIndex = i; + // random if return or not so we get different targets from time to + // time + if (ai->getRandom()->randRange(0, 1) == 0) + return true; + } + } + } + } + } + if (damagedUnitIndex != -1) { + return true; + } + return false; } void AiRuleRepair::execute() { - AiInterface *aiInterface= ai->getAiInterface(); - const Unit *damagedUnit= aiInterface->getMyUnit(damagedUnitIndex); - //printf("\n\n\n\n###^^^^^^^^^^ Looking for repairer for damaged unit [%d - %s]\n",damagedUnit->getId(),damagedUnit->getType()->getName().c_str()); - - int minUnitsRepairingCastle = getMinUnitsToRepairCastle(); - const double minCastleHpRatio = getMinCastleHpRatio(); - - if(minUnitsRepairingCastle > 2){ - if(damagedUnit->getCurrSkill()->getClass() == scBeBuilt){// if build is still be build 2 helpers are enough - minUnitsRepairingCastle= 2; - } - - if(!damagedUnitIsCastle){ - minUnitsRepairingCastle= 2; - } - } - if( aiInterface->getControlType() == ctCpuEasy || - aiInterface->getControlType() == ctNetworkCpuEasy) { - if(!damagedUnitIsCastle){ - // cpu easy does not repair! - minUnitsRepairingCastle=0; - } + AiInterface *aiInterface = ai->getAiInterface(); + const Unit *damagedUnit = aiInterface->getMyUnit(damagedUnitIndex); + // printf("\n\n\n\n###^^^^^^^^^^ Looking for repairer for damaged unit [%d - + // %s]\n",damagedUnit->getId(),damagedUnit->getType()->getName().c_str()); + + int minUnitsRepairingCastle = getMinUnitsToRepairCastle(); + const double minCastleHpRatio = getMinCastleHpRatio(); + + if (minUnitsRepairingCastle > 2) { + if (damagedUnit->getCurrSkill()->getClass() == + scBeBuilt) { // if build is still be build 2 helpers are enough + minUnitsRepairingCastle = 2; + } + + if (!damagedUnitIsCastle) { + minUnitsRepairingCastle = 2; + } + } + if (aiInterface->getControlType() == ctCpuEasy || + aiInterface->getControlType() == ctNetworkCpuEasy) { + if (!damagedUnitIsCastle) { + // cpu easy does not repair! + minUnitsRepairingCastle = 0; + } + } + if (aiInterface->getControlType() == ctCpu || + aiInterface->getControlType() == ctNetworkCpu) { + if (!damagedUnitIsCastle) { + // cpu does only repair with one unit! + minUnitsRepairingCastle = 1; + } + } + int unitCountAlreadyRepairingDamagedUnit = 0; + // printf("team %d has damaged unit\n", damagedUnit->getTeam()); + // Now check if any other unit is able to repair this unit + for (int i1 = 0; i1 < aiInterface->getMyUnitCount(); ++i1) { + const Unit *u1 = aiInterface->getMyUnit(i1); + const RepairCommandType *rct = static_cast( + u1->getType()->getFirstCtOfClass(ccRepair)); + // if(rct) printf("\n\n\n\n^^^^^^^^^^ possible repairer unit [%d - %s] + // current skill [%d] can reapir damaged unit + // [%d]\n",u1->getId(),u1->getType()->getName().c_str(),u1->getCurrSkill()->getClass(),rct->isRepairableUnitType(u1->getType())); + Command *cmd = u1->getCurrCommand(); + if (cmd != NULL && cmd->getCommandType()->getClass() == ccRepair) { + // if(cmd->getUnit() != NULL && cmd->getUnit()->getId() == + // damagedUnit->getId()) if(cmd->getUnit() != NULL && cmd->getPos() == + // damagedUnit->getPosWithCellMapSet()) + + if (rct != NULL) { + // printf("\n\n\n\n^^^^^^^^^^ possible repairer unit [%d - %s] current + // skill [%d] can repair damaged unit [%d] Castles hp-ratio = + // %f\n",u1->getId(),u1->getType()->getName().c_str(),u1->getCurrSkill()->getClass(),rct->isRepairableUnitType(u->getType()),u->getHpRatio()); + + if (((RepairCommandType *)(cmd->getCommandType())) + ->isRepairableUnitType(damagedUnit->getType())) { + // printf("^^^^test^^^^^^ unit is ALREADY repairer unit [%d - + // %s]\nminUnitsRepairingCastle=%d\n",u1->getId(), + // u1->getType()->getName().c_str(), minUnitsRepairingCastle); + unitCountAlreadyRepairingDamagedUnit++; + } + } } - if( aiInterface->getControlType() == ctCpu || - aiInterface->getControlType() == ctNetworkCpu) { - if(!damagedUnitIsCastle){ - // cpu does only repair with one unit! - minUnitsRepairingCastle=1; - } + } + + if (unitCountAlreadyRepairingDamagedUnit >= minUnitsRepairingCastle) { + return; + } + + int unitGroupCommandId = -1; + + // find a repairer and issue command + for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) { + const Unit *u = aiInterface->getMyUnit(i); + const RepairCommandType *rct = static_cast( + u->getType()->getFirstCtOfClass(ccRepair)); + // if(rct) printf("\n\n\n\n^^^^^^^^^^ possible repairer unit [%d - %s] + // current skill [%d] can reapir damaged unit + // [%d]\n",u->getId(),u->getType()->getName().c_str(),u->getCurrSkill()->getClass(),rct->isRepairableUnitType(damagedUnit->getType())); + + if (rct != NULL) { + // printf("\n\n\n\n^^^^^^^^^^ possible excute repairer unit [%d - %s] + // current skill [%d] can repair damaged unit [%d] Castles hp-ratio = + // %f\n",u->getId(),u->getType()->getName().c_str(),u->getCurrSkill()->getClass(),rct->isRepairableUnitType(damagedUnit->getType()),damagedUnit->getHpRatio()); + + if ((u->getCurrSkill()->getClass() == scStop || + u->getCurrSkill()->getClass() == scMove || + damagedUnit->getHpRatio() <= minCastleHpRatio)) { + if ((u->getCurrCommand() == NULL || + (u->getCurrCommand()->getCommandType()->getClass() != ccBuild && + u->getCurrCommand()->getCommandType()->getClass() != + ccProduce)) && + rct->isRepairableUnitType(damagedUnit->getType())) { + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",__FILE__,__FUNCTION__,__LINE__); printf("\n\n\n\n^^^^^^^^^^ + // AI execute will repair damaged unit [%d - %s] at pos [%s] + // cellmapPos [%s] using unit [%d + // -%s]\n",damagedUnit->getId(),damagedUnit->getType()->getName().c_str(),damagedUnit->getPos().getString().c_str(),damagedUnit->getPosWithCellMapSet().getString().c_str(),u->getId(),u->getType()->getName().c_str()); + + /* + Map *map= aiInterface->getWorld()->getMap(); + Cell *cell = map->getCell(damagedUnit->getPosWithCellMapSet()); + if(cell != NULL) { + printf("\n\n\n\n^^^^^^^^^^ cell is ok\n"); + + Unit *cellUnit = cell->getUnit(damagedUnit->getCurrField()); + if(cellUnit != NULL) { + printf("\n\n\n\n^^^^^^^^^^ cell unit [%d - %s] at pos + [%s]\n",cellUnit->getId(),cellUnit->getType()->getName().c_str(),cellUnit->getPos().getString().c_str()); + } + } + */ + + // aiInterface->giveCommand(i, rct, damagedUnit->getPos()); + if (unitCountAlreadyRepairingDamagedUnit < minUnitsRepairingCastle) { + + if (unitGroupCommandId == -1) { + unitGroupCommandId = + aiInterface->getWorld()->getNextCommandGroupId(); + } + + aiInterface->giveCommand(i, rct, + damagedUnit->getPosWithCellMapSet(), + unitGroupCommandId); + if (aiInterface->isLogLevelEnabled(3) == true) + aiInterface->printLog(3, "Repairing order issued"); + unitCountAlreadyRepairingDamagedUnit++; + // printf( + // "^^^^^^^^^^adding one unit to repair + //... + // unitCountAlreadyRepairingDamagedUnit/minUnitsRepairingCastle=%d/%d\n", + // unitCountAlreadyRepairingDamagedUnit, + // minUnitsRepairingCastle); + } + + if (!damagedUnitIsCastle || + unitCountAlreadyRepairingDamagedUnit >= minUnitsRepairingCastle) { + return; + } + } + } } - int unitCountAlreadyRepairingDamagedUnit = 0; - //printf("team %d has damaged unit\n", damagedUnit->getTeam()); - // Now check if any other unit is able to repair this unit - for(int i1 = 0; i1 < aiInterface->getMyUnitCount(); ++i1) { - const Unit *u1= aiInterface->getMyUnit(i1); - const RepairCommandType *rct= static_cast(u1->getType()->getFirstCtOfClass(ccRepair)); - //if(rct) printf("\n\n\n\n^^^^^^^^^^ possible repairer unit [%d - %s] current skill [%d] can reapir damaged unit [%d]\n",u1->getId(),u1->getType()->getName().c_str(),u1->getCurrSkill()->getClass(),rct->isRepairableUnitType(u1->getType())); - Command *cmd= u1->getCurrCommand(); - if(cmd != NULL && cmd->getCommandType()->getClass() == ccRepair){ - //if(cmd->getUnit() != NULL && cmd->getUnit()->getId() == damagedUnit->getId()) - //if(cmd->getUnit() != NULL && cmd->getPos() == damagedUnit->getPosWithCellMapSet()) - - if(rct != NULL){ - //printf("\n\n\n\n^^^^^^^^^^ possible repairer unit [%d - %s] current skill [%d] can repair damaged unit [%d] Castles hp-ratio = %f\n",u1->getId(),u1->getType()->getName().c_str(),u1->getCurrSkill()->getClass(),rct->isRepairableUnitType(u->getType()),u->getHpRatio()); - - if(((RepairCommandType*) (cmd->getCommandType()))->isRepairableUnitType(damagedUnit->getType())){ - //printf("^^^^test^^^^^^ unit is ALREADY repairer unit [%d - %s]\nminUnitsRepairingCastle=%d\n",u1->getId(), u1->getType()->getName().c_str(), minUnitsRepairingCastle); - unitCountAlreadyRepairingDamagedUnit++; - } - } - } - } - - if(unitCountAlreadyRepairingDamagedUnit >= minUnitsRepairingCastle){ - return; - } - - int unitGroupCommandId = -1; - - //find a repairer and issue command - for(int i = 0; i < aiInterface->getMyUnitCount(); ++i) { - const Unit *u= aiInterface->getMyUnit(i); - const RepairCommandType *rct= static_cast(u->getType()->getFirstCtOfClass(ccRepair)); - //if(rct) printf("\n\n\n\n^^^^^^^^^^ possible repairer unit [%d - %s] current skill [%d] can reapir damaged unit [%d]\n",u->getId(),u->getType()->getName().c_str(),u->getCurrSkill()->getClass(),rct->isRepairableUnitType(damagedUnit->getType())); - - if(rct != NULL) { - //printf("\n\n\n\n^^^^^^^^^^ possible excute repairer unit [%d - %s] current skill [%d] can repair damaged unit [%d] Castles hp-ratio = %f\n",u->getId(),u->getType()->getName().c_str(),u->getCurrSkill()->getClass(),rct->isRepairableUnitType(damagedUnit->getType()),damagedUnit->getHpRatio()); - - if((u->getCurrSkill()->getClass() == scStop || u->getCurrSkill()->getClass() == scMove || damagedUnit->getHpRatio() <= minCastleHpRatio)) { - if((u->getCurrCommand() == NULL || (u->getCurrCommand()->getCommandType()->getClass() != ccBuild - && u->getCurrCommand()->getCommandType()->getClass() != ccProduce)) - && rct->isRepairableUnitType(damagedUnit->getType())){ - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - //printf("\n\n\n\n^^^^^^^^^^ AI execute will repair damaged unit [%d - %s] at pos [%s] cellmapPos [%s] using unit [%d -%s]\n",damagedUnit->getId(),damagedUnit->getType()->getName().c_str(),damagedUnit->getPos().getString().c_str(),damagedUnit->getPosWithCellMapSet().getString().c_str(),u->getId(),u->getType()->getName().c_str()); - - /* - Map *map= aiInterface->getWorld()->getMap(); - Cell *cell = map->getCell(damagedUnit->getPosWithCellMapSet()); - if(cell != NULL) { - printf("\n\n\n\n^^^^^^^^^^ cell is ok\n"); - - Unit *cellUnit = cell->getUnit(damagedUnit->getCurrField()); - if(cellUnit != NULL) { - printf("\n\n\n\n^^^^^^^^^^ cell unit [%d - %s] at pos [%s]\n",cellUnit->getId(),cellUnit->getType()->getName().c_str(),cellUnit->getPos().getString().c_str()); - } - } - */ - - //aiInterface->giveCommand(i, rct, damagedUnit->getPos()); - if(unitCountAlreadyRepairingDamagedUnit < minUnitsRepairingCastle) { - - if(unitGroupCommandId == -1) { - unitGroupCommandId = aiInterface->getWorld()->getNextCommandGroupId(); - } - - aiInterface->giveCommand(i, rct, damagedUnit->getPosWithCellMapSet(),unitGroupCommandId); - if(aiInterface->isLogLevelEnabled(3) == true) aiInterface->printLog(3, "Repairing order issued"); - unitCountAlreadyRepairingDamagedUnit++; - // printf( - // "^^^^^^^^^^adding one unit to repair ... unitCountAlreadyRepairingDamagedUnit/minUnitsRepairingCastle=%d/%d\n", - // unitCountAlreadyRepairingDamagedUnit, minUnitsRepairingCastle); - } - - if( !damagedUnitIsCastle || unitCountAlreadyRepairingDamagedUnit >= minUnitsRepairingCastle){ - return; - } - } - } - } - } + } } // ===================================================== // class AiRuleReturnBase // ===================================================== -AiRuleReturnBase::AiRuleReturnBase(Ai *ai): - AiRule(ai) -{ - stoppedUnitIndex= -1; +AiRuleReturnBase::AiRuleReturnBase(Ai *ai) : AiRule(ai) { + stoppedUnitIndex = -1; } -bool AiRuleReturnBase::test(){ - return ai->findAbleUnit(&stoppedUnitIndex, ccMove, true); +bool AiRuleReturnBase::test() { + return ai->findAbleUnit(&stoppedUnitIndex, ccMove, true); } -void AiRuleReturnBase::execute(){ - ai->returnBase(stoppedUnitIndex); -} +void AiRuleReturnBase::execute() { ai->returnBase(stoppedUnitIndex); } // ===================================================== // class AiRuleMassiveAttack // ===================================================== -AiRuleMassiveAttack::AiRuleMassiveAttack(Ai *ai): - AiRule(ai) -{ - ultraAttack=false; - field = fLand; +AiRuleMassiveAttack::AiRuleMassiveAttack(Ai *ai) : AiRule(ai) { + ultraAttack = false; + field = fLand; } -bool AiRuleMassiveAttack::test(){ +bool AiRuleMassiveAttack::test() { - if(ai->isStableBase()){ - ultraAttack= false; - return ai->beingAttacked(attackPos, field, INT_MAX); - } - else{ - ultraAttack= true; - return ai->beingAttacked(attackPos, field, baseRadius); - } + if (ai->isStableBase()) { + ultraAttack = false; + return ai->beingAttacked(attackPos, field, INT_MAX); + } else { + ultraAttack = true; + return ai->beingAttacked(attackPos, field, baseRadius); + } } -void AiRuleMassiveAttack::execute(){ - ai->massiveAttack(attackPos, field, ultraAttack); +void AiRuleMassiveAttack::execute() { + ai->massiveAttack(attackPos, field, ultraAttack); } // ===================================================== // class AiRuleAddTasks // ===================================================== -AiRuleAddTasks::AiRuleAddTasks(Ai *ai): - AiRule(ai) -{ -} +AiRuleAddTasks::AiRuleAddTasks(Ai *ai) : AiRule(ai) {} -bool AiRuleAddTasks::test(){ - return !ai->anyTask() || ai->getCountOfClass(ucWorker) < 4; +bool AiRuleAddTasks::test() { + return !ai->anyTask() || ai->getCountOfClass(ucWorker) < 4; } -void AiRuleAddTasks::execute(){ - int buildingCount= ai->getCountOfClass(ucBuilding); - UnitClass ucWorkerType = ucWorker; - int warriorCount= ai->getCountOfClass(ucWarrior,&ucWorkerType); - int workerCount= ai->getCountOfClass(ucWorker); - int upgradeCount= ai->getAiInterface()->getMyUpgradeCount(); - - float buildingRatio= ai->getRatioOfClass(ucBuilding); - float warriorRatio= ai->getRatioOfClass(ucWarrior); - float workerRatio= ai->getRatioOfClass(ucWorker); - - //standard tasks - if(ai->outputAIBehaviourToConsole()) printf("Add a TASK - AiRuleAddTasks adding ProduceTask(ucWorker) workerCount = %d, RULE Name[%s]\n",workerCount,this->getName().c_str()); - - //emergency workers - if(workerCount < 4){ - if(ai->outputAIBehaviourToConsole()) printf("AAA AiRuleAddTasks adding ProduceTask(ucWorker) workerCount = %d, RULE Name[%s]\n",workerCount,this->getName().c_str()); - - ai->addPriorityTask(new ProduceTask(ucWorker)); - } - else{ - if( ai->getAiInterface()->getControlType() == ctCpuMega || - ai->getAiInterface()->getControlType() == ctNetworkCpuMega) - { - if(ai->outputAIBehaviourToConsole()) printf("AAA AiRuleAddTasks adding #1 workerCount = %d[%.2f], buildingCount = %d[%.2f] warriorCount = %d[%.2f] upgradeCount = %d RULE Name[%s]\n", - workerCount,workerRatio,buildingCount,buildingRatio,warriorCount,warriorRatio,upgradeCount,this->getName().c_str()); - - //workers - if(workerCount<5) ai->addTask(new ProduceTask(ucWorker)); - if(workerCount<10) ai->addTask(new ProduceTask(ucWorker)); - if(workerRatio<0.20) ai->addTask(new ProduceTask(ucWorker)); - if(workerRatio<0.30) ai->addTask(new ProduceTask(ucWorker)); - - //warriors - if(warriorCount<10) ai->addTask(new ProduceTask(ucWarrior)); - if(warriorRatio<0.20) ai->addTask(new ProduceTask(ucWarrior)); - if(warriorRatio<0.30) ai->addTask(new ProduceTask(ucWarrior)); - if(workerCount>=10) ai->addTask(new ProduceTask(ucWarrior)); - if(workerCount>=15) ai->addTask(new ProduceTask(ucWarrior)); - if(warriorCount < ai->getMinWarriors() + 2) - { - ai->addTask(new ProduceTask(ucWarrior)); - if( buildingCount>9 ) - { - ai->addTask(new ProduceTask(ucWarrior)); - ai->addTask(new ProduceTask(ucWarrior)); - } - if( buildingCount>12 ) - { - ai->addTask(new ProduceTask(ucWarrior)); - ai->addTask(new ProduceTask(ucWarrior)); - } - } - - //buildings - if(buildingCount<6 || buildingRatio<0.20) ai->addTask(new BuildTask((UnitType *)NULL)); - if(buildingCount<10 && workerCount>12) ai->addTask(new BuildTask((UnitType *)NULL)); - //upgrades - if(upgradeCount==0 && workerCount>5) ai->addTask(new UpgradeTask((const UpgradeType *)NULL)); - if(upgradeCount==1 && workerCount>10) ai->addTask(new UpgradeTask((const UpgradeType *)NULL)); - if(upgradeCount==2 && workerCount>15) ai->addTask(new UpgradeTask((const UpgradeType *)NULL)); - if(ai->isStableBase()) ai->addTask(new UpgradeTask((const UpgradeType *)NULL)); - } - else if(ai->getAiInterface()->getControlType() == ctCpuEasy || - ai->getAiInterface()->getControlType() == ctNetworkCpuEasy) - {// Easy CPU - - if(ai->outputAIBehaviourToConsole()) printf("AAA AiRuleAddTasks adding #2 workerCount = %d[%.2f], buildingCount = %d[%.2f] warriorCount = %d[%.2f] upgradeCount = %d RULE Name[%s]\n", - workerCount,workerRatio,buildingCount,buildingRatio,warriorCount,warriorRatio,upgradeCount,this->getName().c_str()); - - //workers - if(workerCountaddTask(new ProduceTask(ucWorker)); - if(workerCount>5 && workerRatio<0.20) ai->addTask(new ProduceTask(ucWorker)); - - //warriors - if(warriorCount<10) ai->addTask(new ProduceTask(ucWarrior)); - if(warriorRatio<0.20) ai->addTask(new ProduceTask(ucWarrior)); - if(warriorRatio<0.30) ai->addTask(new ProduceTask(ucWarrior)); - if(workerCount>=10) ai->addTask(new ProduceTask(ucWarrior)); - if(workerCount>=15) ai->addTask(new ProduceTask(ucWarrior)); - - //buildings - if(buildingCount<6 || buildingRatio<0.20) ai->addTask(new BuildTask((UnitType *)NULL)); - if(buildingCount<10 && ai->isStableBase()) ai->addTask(new BuildTask((UnitType *)NULL)); - - //upgrades - if(upgradeCount==0 && workerCount>6) ai->addTask(new UpgradeTask((const UpgradeType *)NULL)); - if(upgradeCount==1 && workerCount>7) ai->addTask(new UpgradeTask((const UpgradeType *)NULL)); - if(upgradeCount==2 && workerCount>9) ai->addTask(new UpgradeTask((const UpgradeType *)NULL)); - //if(ai->isStableBase()) ai->addTask(new UpgradeTask()); - } - else - {// normal CPU / UltraCPU ... - if(ai->outputAIBehaviourToConsole()) printf("AAA AiRuleAddTasks adding #3 workerCount = %d[%.2f], buildingCount = %d[%.2f] warriorCount = %d[%.2f] upgradeCount = %d RULE Name[%s]\n", - workerCount,workerRatio,buildingCount,buildingRatio,warriorCount,warriorRatio,upgradeCount,this->getName().c_str()); - - //workers - if(workerCount<5) ai->addTask(new ProduceTask(ucWorker)); - if(workerCount<10) ai->addTask(new ProduceTask(ucWorker)); - if(workerRatio<0.20) ai->addTask(new ProduceTask(ucWorker)); - if(workerRatio<0.30) ai->addTask(new ProduceTask(ucWorker)); - - //warriors - if(warriorCount<10) ai->addTask(new ProduceTask(ucWarrior)); - if(warriorRatio<0.20) ai->addTask(new ProduceTask(ucWarrior)); - if(warriorRatio<0.30) ai->addTask(new ProduceTask(ucWarrior)); - if(workerCount>=10) ai->addTask(new ProduceTask(ucWarrior)); - if(workerCount>=15) ai->addTask(new ProduceTask(ucWarrior)); - - //buildings - if(buildingCount<6 || buildingRatio<0.20) ai->addTask(new BuildTask((UnitType *)NULL)); - if(buildingCount<10 && workerCount>12) ai->addTask(new BuildTask((UnitType *)NULL)); - - //upgrades - if(upgradeCount==0 && workerCount>5) ai->addTask(new UpgradeTask((const UpgradeType *)NULL)); - if(upgradeCount==1 && workerCount>10) ai->addTask(new UpgradeTask((const UpgradeType *)NULL)); - if(upgradeCount==2 && workerCount>15) ai->addTask(new UpgradeTask((const UpgradeType *)NULL)); - if(ai->isStableBase()) ai->addTask(new UpgradeTask((const UpgradeType *)NULL)); - } - } +void AiRuleAddTasks::execute() { + int buildingCount = ai->getCountOfClass(ucBuilding); + UnitClass ucWorkerType = ucWorker; + int warriorCount = ai->getCountOfClass(ucWarrior, &ucWorkerType); + int workerCount = ai->getCountOfClass(ucWorker); + int upgradeCount = ai->getAiInterface()->getMyUpgradeCount(); + + float buildingRatio = ai->getRatioOfClass(ucBuilding); + float warriorRatio = ai->getRatioOfClass(ucWarrior); + float workerRatio = ai->getRatioOfClass(ucWorker); + + // standard tasks + if (ai->outputAIBehaviourToConsole()) + printf("Add a TASK - AiRuleAddTasks adding ProduceTask(ucWorker) " + "workerCount = %d, RULE Name[%s]\n", + workerCount, this->getName().c_str()); + + // emergency workers + if (workerCount < 4) { + if (ai->outputAIBehaviourToConsole()) + printf("AAA AiRuleAddTasks adding ProduceTask(ucWorker) workerCount = " + "%d, RULE Name[%s]\n", + workerCount, this->getName().c_str()); + + ai->addPriorityTask(new ProduceTask(ucWorker)); + } else { + if (ai->getAiInterface()->getControlType() == ctCpuMega || + ai->getAiInterface()->getControlType() == ctNetworkCpuMega) { + if (ai->outputAIBehaviourToConsole()) + printf("AAA AiRuleAddTasks adding #1 workerCount = %d[%.2f], " + "buildingCount = %d[%.2f] warriorCount = %d[%.2f] upgradeCount " + "= %d RULE Name[%s]\n", + workerCount, workerRatio, buildingCount, buildingRatio, + warriorCount, warriorRatio, upgradeCount, + this->getName().c_str()); + + // workers + if (workerCount < 5) + ai->addTask(new ProduceTask(ucWorker)); + if (workerCount < 10) + ai->addTask(new ProduceTask(ucWorker)); + if (workerRatio < 0.20) + ai->addTask(new ProduceTask(ucWorker)); + if (workerRatio < 0.30) + ai->addTask(new ProduceTask(ucWorker)); + + // warriors + if (warriorCount < 10) + ai->addTask(new ProduceTask(ucWarrior)); + if (warriorRatio < 0.20) + ai->addTask(new ProduceTask(ucWarrior)); + if (warriorRatio < 0.30) + ai->addTask(new ProduceTask(ucWarrior)); + if (workerCount >= 10) + ai->addTask(new ProduceTask(ucWarrior)); + if (workerCount >= 15) + ai->addTask(new ProduceTask(ucWarrior)); + if (warriorCount < ai->getMinWarriors() + 2) { + ai->addTask(new ProduceTask(ucWarrior)); + if (buildingCount > 9) { + ai->addTask(new ProduceTask(ucWarrior)); + ai->addTask(new ProduceTask(ucWarrior)); + } + if (buildingCount > 12) { + ai->addTask(new ProduceTask(ucWarrior)); + ai->addTask(new ProduceTask(ucWarrior)); + } + } + + // buildings + if (buildingCount < 6 || buildingRatio < 0.20) + ai->addTask(new BuildTask((UnitType *)NULL)); + if (buildingCount < 10 && workerCount > 12) + ai->addTask(new BuildTask((UnitType *)NULL)); + // upgrades + if (upgradeCount == 0 && workerCount > 5) + ai->addTask(new UpgradeTask((const UpgradeType *)NULL)); + if (upgradeCount == 1 && workerCount > 10) + ai->addTask(new UpgradeTask((const UpgradeType *)NULL)); + if (upgradeCount == 2 && workerCount > 15) + ai->addTask(new UpgradeTask((const UpgradeType *)NULL)); + if (ai->isStableBase()) + ai->addTask(new UpgradeTask((const UpgradeType *)NULL)); + } else if (ai->getAiInterface()->getControlType() == ctCpuEasy || + ai->getAiInterface()->getControlType() == + ctNetworkCpuEasy) { // Easy CPU + + if (ai->outputAIBehaviourToConsole()) + printf("AAA AiRuleAddTasks adding #2 workerCount = %d[%.2f], " + "buildingCount = %d[%.2f] warriorCount = %d[%.2f] upgradeCount " + "= %d RULE Name[%s]\n", + workerCount, workerRatio, buildingCount, buildingRatio, + warriorCount, warriorRatio, upgradeCount, + this->getName().c_str()); + + // workers + if (workerCount < buildingCount + 2) + ai->addTask(new ProduceTask(ucWorker)); + if (workerCount > 5 && workerRatio < 0.20) + ai->addTask(new ProduceTask(ucWorker)); + + // warriors + if (warriorCount < 10) + ai->addTask(new ProduceTask(ucWarrior)); + if (warriorRatio < 0.20) + ai->addTask(new ProduceTask(ucWarrior)); + if (warriorRatio < 0.30) + ai->addTask(new ProduceTask(ucWarrior)); + if (workerCount >= 10) + ai->addTask(new ProduceTask(ucWarrior)); + if (workerCount >= 15) + ai->addTask(new ProduceTask(ucWarrior)); + + // buildings + if (buildingCount < 6 || buildingRatio < 0.20) + ai->addTask(new BuildTask((UnitType *)NULL)); + if (buildingCount < 10 && ai->isStableBase()) + ai->addTask(new BuildTask((UnitType *)NULL)); + + // upgrades + if (upgradeCount == 0 && workerCount > 6) + ai->addTask(new UpgradeTask((const UpgradeType *)NULL)); + if (upgradeCount == 1 && workerCount > 7) + ai->addTask(new UpgradeTask((const UpgradeType *)NULL)); + if (upgradeCount == 2 && workerCount > 9) + ai->addTask(new UpgradeTask((const UpgradeType *)NULL)); + // if(ai->isStableBase()) ai->addTask(new UpgradeTask()); + } else { // normal CPU / UltraCPU ... + if (ai->outputAIBehaviourToConsole()) + printf("AAA AiRuleAddTasks adding #3 workerCount = %d[%.2f], " + "buildingCount = %d[%.2f] warriorCount = %d[%.2f] upgradeCount " + "= %d RULE Name[%s]\n", + workerCount, workerRatio, buildingCount, buildingRatio, + warriorCount, warriorRatio, upgradeCount, + this->getName().c_str()); + + // workers + if (workerCount < 5) + ai->addTask(new ProduceTask(ucWorker)); + if (workerCount < 10) + ai->addTask(new ProduceTask(ucWorker)); + if (workerRatio < 0.20) + ai->addTask(new ProduceTask(ucWorker)); + if (workerRatio < 0.30) + ai->addTask(new ProduceTask(ucWorker)); + + // warriors + if (warriorCount < 10) + ai->addTask(new ProduceTask(ucWarrior)); + if (warriorRatio < 0.20) + ai->addTask(new ProduceTask(ucWarrior)); + if (warriorRatio < 0.30) + ai->addTask(new ProduceTask(ucWarrior)); + if (workerCount >= 10) + ai->addTask(new ProduceTask(ucWarrior)); + if (workerCount >= 15) + ai->addTask(new ProduceTask(ucWarrior)); + + // buildings + if (buildingCount < 6 || buildingRatio < 0.20) + ai->addTask(new BuildTask((UnitType *)NULL)); + if (buildingCount < 10 && workerCount > 12) + ai->addTask(new BuildTask((UnitType *)NULL)); + + // upgrades + if (upgradeCount == 0 && workerCount > 5) + ai->addTask(new UpgradeTask((const UpgradeType *)NULL)); + if (upgradeCount == 1 && workerCount > 10) + ai->addTask(new UpgradeTask((const UpgradeType *)NULL)); + if (upgradeCount == 2 && workerCount > 15) + ai->addTask(new UpgradeTask((const UpgradeType *)NULL)); + if (ai->isStableBase()) + ai->addTask(new UpgradeTask((const UpgradeType *)NULL)); + } + } } // ===================================================== // class AiRuleBuildOneFarm // ===================================================== -AiRuleBuildOneFarm::AiRuleBuildOneFarm(Ai *ai): - AiRule(ai) -{ - farm=NULL; -} - -bool AiRuleBuildOneFarm::test(){ - AiInterface *aiInterface= ai->getAiInterface(); - - //for all units - for(int i=0; igetMyFactionType()->getUnitTypeCount(); ++i){ - const UnitType *ut= aiInterface->getMyFactionType()->getUnitType(i); - - //for all production commands - for(int j=0; jgetCommandTypeCount(); ++j){ - const CommandType *ct= ut->getCommandType(j); - if(ct->getClass()==ccProduce){ - const UnitType *producedType= static_cast(ct)->getProducedUnit(); - - //for all resources - for(int k=0; kgetCostCount(); ++k){ - const Resource *r= producedType->getCost(k); - - //find a food producer in the farm produced units - if(r->getAmount() < 0 && r->getType()->getClass() == rcConsumable && ai->getCountOfType(ut) == 0) { - if(aiInterface->reqsOk(ct) && aiInterface->getMyFaction()->canCreateUnit(ut, true, true, true) == true) { - farm= ut; - //printf("AiRuleBuildOneFarm returning true, RULE Name[%s] ut [%s] producedType [%s]\n",this->getName().c_str(),ut->getName().c_str(),producedType->getName().c_str()); - - if(ai->outputAIBehaviourToConsole()) printf("AiRuleBuildOneFarm returning true, RULE Name[%s]\n",this->getName().c_str()); - - return true; - } - } - } - } - } - } - return false; +AiRuleBuildOneFarm::AiRuleBuildOneFarm(Ai *ai) : AiRule(ai) { farm = NULL; } + +bool AiRuleBuildOneFarm::test() { + AiInterface *aiInterface = ai->getAiInterface(); + + // for all units + for (int i = 0; i < aiInterface->getMyFactionType()->getUnitTypeCount(); + ++i) { + const UnitType *ut = aiInterface->getMyFactionType()->getUnitType(i); + + // for all production commands + for (int j = 0; j < ut->getCommandTypeCount(); ++j) { + const CommandType *ct = ut->getCommandType(j); + if (ct->getClass() == ccProduce) { + const UnitType *producedType = + static_cast(ct)->getProducedUnit(); + + // for all resources + for (int k = 0; k < producedType->getCostCount(); ++k) { + const Resource *r = producedType->getCost(k); + + // find a food producer in the farm produced units + if (r->getAmount() < 0 && r->getType()->getClass() == rcConsumable && + ai->getCountOfType(ut) == 0) { + if (aiInterface->reqsOk(ct) && + aiInterface->getMyFaction()->canCreateUnit(ut, true, true, + true) == true) { + farm = ut; + // printf("AiRuleBuildOneFarm returning true, RULE Name[%s] ut + // [%s] producedType + // [%s]\n",this->getName().c_str(),ut->getName().c_str(),producedType->getName().c_str()); + + if (ai->outputAIBehaviourToConsole()) + printf("AiRuleBuildOneFarm returning true, RULE Name[%s]\n", + this->getName().c_str()); + + return true; + } + } + } + } + } + } + return false; } -void AiRuleBuildOneFarm::execute(){ - ai->addPriorityTask(new BuildTask(farm)); -} +void AiRuleBuildOneFarm::execute() { ai->addPriorityTask(new BuildTask(farm)); } // ===================================================== // class AiRuleProduceResourceProducer // ===================================================== -AiRuleProduceResourceProducer::AiRuleProduceResourceProducer(Ai *ai): - AiRule(ai) -{ - interval= shortInterval; - rt=NULL; - newResourceBehaviour=Config::getInstance().getBool("NewResourceBehaviour","false");; +AiRuleProduceResourceProducer::AiRuleProduceResourceProducer(Ai *ai) + : AiRule(ai) { + interval = shortInterval; + rt = NULL; + newResourceBehaviour = + Config::getInstance().getBool("NewResourceBehaviour", "false"); + ; } -bool AiRuleProduceResourceProducer::test(){ - //emergency tasks: resource buildings - AiInterface *aiInterface= ai->getAiInterface(); - - //consumables first - for(int i=0; igetTechTree()->getResourceTypeCount(); ++i){ - rt= aiInterface->getTechTree()->getResourceType(i); - const Resource *r= aiInterface->getResource(rt); - - if(ai->outputAIBehaviourToConsole()) printf("CONSUMABLE [%s][%d] Testing AI RULE Name[%s]\n",rt->getName().c_str(), r->getBalance(), this->getName().c_str()); - - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"CONSUMABLE [%s][%d] Testing AI RULE Name[%s]",rt->getName().c_str(), r->getBalance(), this->getName().c_str()); - aiInterface->printLog(4, szBuf); - } - - bool factionUsesResourceType = aiInterface->factionUsesResourceType(aiInterface->getMyFactionType(), rt); - if(factionUsesResourceType == true && rt->getClass() == rcConsumable) { - // The consumable balance is negative - if(r->getBalance() < 0) { - if(newResourceBehaviour == true) { - interval = shortInterval; - } - else { - interval = longInterval; - } - - return true; - } - // If the consumable balance is down to 1/3 of what we need - else { - if(r->getBalance() * 3 + r->getAmount() < 0) { - if(newResourceBehaviour == true) { - interval = shortInterval; - } - else { - interval = longInterval; - } - - return true; - } - } - } - } - - int targetStaticResourceCount = minStaticResources; - if(aiInterface->getMyFactionType()->getAIBehaviorStaticOverideValue(aibsvcMinStaticResourceCount) != INT_MAX) { - targetStaticResourceCount = aiInterface->getMyFactionType()->getAIBehaviorStaticOverideValue(aibsvcMinStaticResourceCount); - } - - //statics second - for(int i=0; i < aiInterface->getTechTree()->getResourceTypeCount(); ++i) { - rt= aiInterface->getTechTree()->getResourceType(i); - const Resource *r= aiInterface->getResource(rt); - - if(ai->outputAIBehaviourToConsole()) printf("STATIC [%s][%d] [min %d] Testing AI RULE Name[%s]\n",rt->getName().c_str(), r->getAmount(), targetStaticResourceCount, this->getName().c_str()); - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"STATIC resource check [%s][%d] [min %d] Testing AI RULE Name[%s]",rt->getName().c_str(), r->getAmount(), targetStaticResourceCount, this->getName().c_str()); - aiInterface->printLog(4, szBuf); - } - - if(rt->getClass() == rcStatic && r->getAmount() < targetStaticResourceCount) { - bool factionUsesResourceType = aiInterface->factionUsesResourceType(aiInterface->getMyFactionType(), rt); - if(factionUsesResourceType == true) { - if(newResourceBehaviour==true) - interval = shortInterval; - else - interval = longInterval; - return true; - } - } +bool AiRuleProduceResourceProducer::test() { + // emergency tasks: resource buildings + AiInterface *aiInterface = ai->getAiInterface(); + + // consumables first + for (int i = 0; i < aiInterface->getTechTree()->getResourceTypeCount(); ++i) { + rt = aiInterface->getTechTree()->getResourceType(i); + const Resource *r = aiInterface->getResource(rt); + + if (ai->outputAIBehaviourToConsole()) + printf("CONSUMABLE [%s][%d] Testing AI RULE Name[%s]\n", + rt->getName().c_str(), r->getBalance(), this->getName().c_str()); + + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "CONSUMABLE [%s][%d] Testing AI RULE Name[%s]", + rt->getName().c_str(), r->getBalance(), this->getName().c_str()); + aiInterface->printLog(4, szBuf); } - if(ai->outputAIBehaviourToConsole()) printf("STATIC returning FALSE\n"); - if(aiInterface->isLogLevelEnabled(4) == true) aiInterface->printLog(4, "Static Resource check returning FALSE"); + bool factionUsesResourceType = aiInterface->factionUsesResourceType( + aiInterface->getMyFactionType(), rt); + if (factionUsesResourceType == true && rt->getClass() == rcConsumable) { + // The consumable balance is negative + if (r->getBalance() < 0) { + if (newResourceBehaviour == true) { + interval = shortInterval; + } else { + interval = longInterval; + } - if(newResourceBehaviour==true) - interval = longInterval; - else - interval = shortInterval; - return false; + return true; + } + // If the consumable balance is down to 1/3 of what we need + else { + if (r->getBalance() * 3 + r->getAmount() < 0) { + if (newResourceBehaviour == true) { + interval = shortInterval; + } else { + interval = longInterval; + } + + return true; + } + } + } + } + + int targetStaticResourceCount = minStaticResources; + if (aiInterface->getMyFactionType()->getAIBehaviorStaticOverideValue( + aibsvcMinStaticResourceCount) != INT_MAX) { + targetStaticResourceCount = + aiInterface->getMyFactionType()->getAIBehaviorStaticOverideValue( + aibsvcMinStaticResourceCount); + } + + // statics second + for (int i = 0; i < aiInterface->getTechTree()->getResourceTypeCount(); ++i) { + rt = aiInterface->getTechTree()->getResourceType(i); + const Resource *r = aiInterface->getResource(rt); + + if (ai->outputAIBehaviourToConsole()) + printf("STATIC [%s][%d] [min %d] Testing AI RULE Name[%s]\n", + rt->getName().c_str(), r->getAmount(), targetStaticResourceCount, + this->getName().c_str()); + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "STATIC resource check [%s][%d] [min %d] Testing AI RULE Name[%s]", + rt->getName().c_str(), r->getAmount(), targetStaticResourceCount, + this->getName().c_str()); + aiInterface->printLog(4, szBuf); + } + + if (rt->getClass() == rcStatic && + r->getAmount() < targetStaticResourceCount) { + bool factionUsesResourceType = aiInterface->factionUsesResourceType( + aiInterface->getMyFactionType(), rt); + if (factionUsesResourceType == true) { + if (newResourceBehaviour == true) + interval = shortInterval; + else + interval = longInterval; + return true; + } + } + } + + if (ai->outputAIBehaviourToConsole()) + printf("STATIC returning FALSE\n"); + if (aiInterface->isLogLevelEnabled(4) == true) + aiInterface->printLog(4, "Static Resource check returning FALSE"); + + if (newResourceBehaviour == true) + interval = longInterval; + else + interval = shortInterval; + return false; } -void AiRuleProduceResourceProducer::execute(){ - ai->addPriorityTask(new ProduceTask(rt)); - ai->addTask(new BuildTask(rt)); +void AiRuleProduceResourceProducer::execute() { + ai->addPriorityTask(new ProduceTask(rt)); + ai->addTask(new BuildTask(rt)); } // ===================================================== // class AiRuleProduce // ===================================================== -AiRuleProduce::AiRuleProduce(Ai *ai): - AiRule(ai) -{ - produceTask= NULL; - newResourceBehaviour=Config::getInstance().getBool("NewResourceBehaviour","false"); +AiRuleProduce::AiRuleProduce(Ai *ai) : AiRule(ai) { + produceTask = NULL; + newResourceBehaviour = + Config::getInstance().getBool("NewResourceBehaviour", "false"); } -bool AiRuleProduce::test(){ - const Task *task= ai->getTask(); +bool AiRuleProduce::test() { + const Task *task = ai->getTask(); - if(task==NULL || task->getClass()!=tcProduce){ - return false; - } + if (task == NULL || task->getClass() != tcProduce) { + return false; + } - produceTask= static_cast(task); - return true; + produceTask = static_cast(task); + return true; } void AiRuleProduce::execute() { - AiInterface *aiInterface= ai->getAiInterface(); - if(produceTask!=NULL) { - - if(ai->outputAIBehaviourToConsole()) printf("AiRuleProduce producing [%s]\n",(produceTask->getUnitType() != NULL ? produceTask->getUnitType()->getName(false).c_str() : "null")); - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"AiRuleProduce producing [%s]",(produceTask->getUnitType() != NULL ? produceTask->getUnitType()->getName(false).c_str() : "null")); - aiInterface->printLog(4, szBuf); - } - - //generic produce task, produce random unit that has the skill or produces the resource - if(produceTask->getUnitType() == NULL) { - if(newResourceBehaviour){ - produceGenericNew(produceTask); - } - else - produceGeneric(produceTask); - } - - //specific produce task, produce if possible, retry if not enough resources - else { - produceSpecific(produceTask); - } - - //remove the task - ai->removeTask(produceTask); - } + AiInterface *aiInterface = ai->getAiInterface(); + if (produceTask != NULL) { + + if (ai->outputAIBehaviourToConsole()) + printf("AiRuleProduce producing [%s]\n", + (produceTask->getUnitType() != NULL + ? produceTask->getUnitType()->getName(false).c_str() + : "null")); + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "AiRuleProduce producing [%s]", + (produceTask->getUnitType() != NULL + ? produceTask->getUnitType()->getName(false).c_str() + : "null")); + aiInterface->printLog(4, szBuf); + } + + // generic produce task, produce random unit that has the skill or produces + // the resource + if (produceTask->getUnitType() == NULL) { + if (newResourceBehaviour) { + produceGenericNew(produceTask); + } else + produceGeneric(produceTask); + } + + // specific produce task, produce if possible, retry if not enough resources + else { + produceSpecific(produceTask); + } + + // remove the task + ai->removeTask(produceTask); + } } -bool AiRuleProduce::canUnitTypeOfferResourceType(const UnitType *ut, const ResourceType *rt) { - bool unitTypeOffersResourceType = false; - - AiInterface *aiInterface= ai->getAiInterface(); - - if(ut != NULL && rt != NULL && aiInterface != NULL && aiInterface->reqsOk(ut)) { - // Check of the unit 'gives' the resource - // if the unit produces the resource - const Resource *r= ut->getCost(rt); - if(r != NULL) { - if(ai->outputAIBehaviourToConsole()) printf("#2 produceGeneric r = [%s][%d] Testing AI RULE Name[%s]\n",r->getDescription(false).c_str(),r->getAmount(), this->getName().c_str()); - } - - if(r != NULL && r->getAmount() < 0) { - unitTypeOffersResourceType = true; - } - else { - // for each command check if we produce a unit that handles the resource - for(int commandIndex = 0; commandIndex < ut->getCommandTypeCount(); ++commandIndex) { - const CommandType *ct= ut->getCommandType(commandIndex); - - //if the command is produce - if(ct->getClass() == ccProduce || ct->getClass()==ccMorph) { - const UnitType *producedUnit= static_cast(ct->getProduced()); - - if(ai->outputAIBehaviourToConsole()) printf("produceGeneric [%p] Testing AI RULE Name[%s]\n",rt, this->getName().c_str()); - - //if the unit produces the resource - const Resource *r = producedUnit->getCost(rt); - if(r != NULL) { - if(ai->outputAIBehaviourToConsole()) printf("produceGeneric r = [%s][%d] Testing AI RULE Name[%s]\n",r->getDescription(false).c_str(),r->getAmount(), this->getName().c_str()); - } - - if(r != NULL && r->getAmount() < 0) { - unitTypeOffersResourceType = true; - break; - } - } - } - } - } - - if(aiInterface != NULL && aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"canUnitTypeOfferResourceType for unit type [%s] for resource type [%s] returned: %d",(ut != NULL ? ut->getName(false).c_str() : "n/a"),(rt != NULL ? rt->getName(false).c_str() : "n/a"),unitTypeOffersResourceType); - aiInterface->printLog(4, szBuf); - } - - return unitTypeOffersResourceType; +bool AiRuleProduce::canUnitTypeOfferResourceType(const UnitType *ut, + const ResourceType *rt) { + bool unitTypeOffersResourceType = false; + + AiInterface *aiInterface = ai->getAiInterface(); + + if (ut != NULL && rt != NULL && aiInterface != NULL && + aiInterface->reqsOk(ut)) { + // Check of the unit 'gives' the resource + // if the unit produces the resource + const Resource *r = ut->getCost(rt); + if (r != NULL) { + if (ai->outputAIBehaviourToConsole()) + printf("#2 produceGeneric r = [%s][%d] Testing AI RULE Name[%s]\n", + r->getDescription(false).c_str(), r->getAmount(), + this->getName().c_str()); + } + + if (r != NULL && r->getAmount() < 0) { + unitTypeOffersResourceType = true; + } else { + // for each command check if we produce a unit that handles the resource + for (int commandIndex = 0; commandIndex < ut->getCommandTypeCount(); + ++commandIndex) { + const CommandType *ct = ut->getCommandType(commandIndex); + + // if the command is produce + if (ct->getClass() == ccProduce || ct->getClass() == ccMorph) { + const UnitType *producedUnit = + static_cast(ct->getProduced()); + + if (ai->outputAIBehaviourToConsole()) + printf("produceGeneric [%p] Testing AI RULE Name[%s]\n", rt, + this->getName().c_str()); + + // if the unit produces the resource + const Resource *r = producedUnit->getCost(rt); + if (r != NULL) { + if (ai->outputAIBehaviourToConsole()) + printf("produceGeneric r = [%s][%d] Testing AI RULE Name[%s]\n", + r->getDescription(false).c_str(), r->getAmount(), + this->getName().c_str()); + } + + if (r != NULL && r->getAmount() < 0) { + unitTypeOffersResourceType = true; + break; + } + } + } + } + } + + if (aiInterface != NULL && aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "canUnitTypeOfferResourceType for unit type [%s] for resource " + "type [%s] returned: %d", + (ut != NULL ? ut->getName(false).c_str() : "n/a"), + (rt != NULL ? rt->getName(false).c_str() : "n/a"), + unitTypeOffersResourceType); + aiInterface->printLog(4, szBuf); + } + + return unitTypeOffersResourceType; } -bool AiRuleProduce::setAIProduceTaskForResourceType(const ProduceTask* pt, - AiInterface* aiInterface) { - bool taskAdded = false; - if (aiInterface->getMyFactionType()->getAIBehaviorUnits( - aibcResourceProducerUnits).size() > 0) { - const std::vector& unitList = - aiInterface->getMyFactionType()->getAIBehaviorUnits( - aibcResourceProducerUnits); - for (unsigned int i = 0; i < unitList.size(); ++i) { - const FactionType::PairPUnitTypeInt& priorityUnit = unitList[i]; - const UnitType* ut = priorityUnit.first; - if (ai->getCountOfType(ut) < priorityUnit.second && - canUnitTypeOfferResourceType(ut, pt->getResourceType()) == true && - aiInterface->getMyFaction()->canCreateUnit(priorityUnit.first, false, true, true) == true) { - ai->addTask(new ProduceTask(priorityUnit.first)); - taskAdded = true; - break; - } - } - } - - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"setAIProduceTaskForResourceType for resource type [%s] returned: %d",pt->getResourceType()->getName(false).c_str(),taskAdded); - aiInterface->printLog(4, szBuf); - } - - return taskAdded; +bool AiRuleProduce::setAIProduceTaskForResourceType(const ProduceTask *pt, + AiInterface *aiInterface) { + bool taskAdded = false; + if (aiInterface->getMyFactionType() + ->getAIBehaviorUnits(aibcResourceProducerUnits) + .size() > 0) { + const std::vector &unitList = + aiInterface->getMyFactionType()->getAIBehaviorUnits( + aibcResourceProducerUnits); + for (unsigned int i = 0; i < unitList.size(); ++i) { + const FactionType::PairPUnitTypeInt &priorityUnit = unitList[i]; + const UnitType *ut = priorityUnit.first; + if (ai->getCountOfType(ut) < priorityUnit.second && + canUnitTypeOfferResourceType(ut, pt->getResourceType()) == true && + aiInterface->getMyFaction()->canCreateUnit(priorityUnit.first, false, + true, true) == true) { + ai->addTask(new ProduceTask(priorityUnit.first)); + taskAdded = true; + break; + } + } + } + + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "setAIProduceTaskForResourceType for resource type [%s] returned: %d", + pt->getResourceType()->getName(false).c_str(), taskAdded); + aiInterface->printLog(4, szBuf); + } + + return taskAdded; } -void AiRuleProduce::addUnitTypeToCandidates(const UnitType* producedUnit, - UnitTypes& ableUnits, UnitTypesGiveBack& ableUnitsGiveBack, - bool unitCanGiveBackResource) { - // if the unit is not already on the list - if (find(ableUnits.begin(), ableUnits.end(), producedUnit) == ableUnits.end()) { - ableUnits.push_back(producedUnit); - ableUnitsGiveBack.push_back(unitCanGiveBackResource); - - AiInterface *aiInterface= ai->getAiInterface(); - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"addUnitTypeToCandidates for unit type [%s] unitCanGiveBackResource = %d",producedUnit->getName(false).c_str(),unitCanGiveBackResource); - aiInterface->printLog(4, szBuf); - } - - } +void AiRuleProduce::addUnitTypeToCandidates( + const UnitType *producedUnit, UnitTypes &ableUnits, + UnitTypesGiveBack &ableUnitsGiveBack, bool unitCanGiveBackResource) { + // if the unit is not already on the list + if (find(ableUnits.begin(), ableUnits.end(), producedUnit) == + ableUnits.end()) { + ableUnits.push_back(producedUnit); + ableUnitsGiveBack.push_back(unitCanGiveBackResource); + + AiInterface *aiInterface = ai->getAiInterface(); + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "addUnitTypeToCandidates for unit type [%s] " + "unitCanGiveBackResource = %d", + producedUnit->getName(false).c_str(), unitCanGiveBackResource); + aiInterface->printLog(4, szBuf); + } + } } void AiRuleProduce::produceGenericNew(const ProduceTask *pt) { - UnitTypes ableUnits; - UnitTypesGiveBack ableUnitsGiveBack; - - AiInterface *aiInterface= ai->getAiInterface(); - if(pt->getResourceType() != NULL) { - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"****START: produceGeneric for resource type [%s]",pt->getResourceType()->getName(false).c_str()); - aiInterface->printLog(4, szBuf); - } - - if(setAIProduceTaskForResourceType(pt, aiInterface) == true) { - return; - } - } - else if(pt->getUnitClass() == ucWorker) { - if(aiInterface->getMyFactionType()->getAIBehaviorUnits(aibcWorkerUnits).size() > 0) { - const std::vector &unitList = aiInterface->getMyFactionType()->getAIBehaviorUnits(aibcWorkerUnits); - for(unsigned int i = 0; i < unitList.size(); ++i) { - const FactionType::PairPUnitTypeInt &priorityUnit = unitList[i]; - if(ai->getCountOfType(priorityUnit.first) < priorityUnit.second && - aiInterface->getMyFaction()->canCreateUnit(priorityUnit.first, false, true, true) == true) { - ai->addTask(new ProduceTask(priorityUnit.first)); - return; - } - } - } - } - else if(pt->getUnitClass() == ucWarrior) { - if(aiInterface->getMyFactionType()->getAIBehaviorUnits(aibcWarriorUnits).size() > 0) { - const std::vector &unitList = aiInterface->getMyFactionType()->getAIBehaviorUnits(aibcWarriorUnits); - for(unsigned int i = 0; i < unitList.size(); ++i) { - const FactionType::PairPUnitTypeInt &priorityUnit = unitList[i]; - if(ai->getCountOfType(priorityUnit.first) < priorityUnit.second && - aiInterface->getMyFaction()->canCreateUnit(priorityUnit.first, false, true, true) == true) { - ai->addTask(new ProduceTask(priorityUnit.first)); - return; - } - } - } - } - - //for each unit, produce it if possible - for(int i = 0; i < aiInterface->getMyUnitCount(); ++i) { - if(aiInterface->getMyUnit(i)->getCurrCommand()!=NULL && aiInterface->getMyUnit(i)->getCurrCommand()->getCommandType()->getClass()==ccBuild){ - //skip this units as it is currently building something - continue; - } - //for each command - const UnitType *ut= aiInterface->getMyUnit(i)->getType(); - - //bool produceIt= false; - for(int j = 0; j < ut->getCommandTypeCount(); ++j) { - const CommandType *ct= ut->getCommandType(j); - - //if the command is produce - //bool produceIt= false; - if(ct->getClass() == ccProduce || ct->getClass()==ccMorph) { - const UnitType *producedUnit= static_cast(ct->getProduced()); - - if(ai->outputAIBehaviourToConsole()) printf("produceGeneric [%p] Testing AI RULE Name[%s]\n",pt->getResourceType(), this->getName().c_str()); - - //if the unit produces the resource - if(pt->getResourceType() != NULL) { - const Resource *r= producedUnit->getCost(pt->getResourceType()); - if(r != NULL) { - if(ai->outputAIBehaviourToConsole()) printf("produceGeneric r = [%s][%d] Testing AI RULE Name[%s]\n",r->getDescription(false).c_str(),r->getAmount(), this->getName().c_str()); - } - - if(r != NULL && r->getAmount() < 0) { - if(aiInterface->reqsOk(ct) && aiInterface->reqsOk(producedUnit)){ - //produceIt= true; - addUnitTypeToCandidates(producedUnit, ableUnits,ableUnitsGiveBack, false); - } - } - } - else { - //if the unit is from the right class - if(ai->outputAIBehaviourToConsole()) printf("produceGeneric right class = [%d] Testing AI RULE Name[%s]\n",producedUnit->isOfClass(pt->getUnitClass()), this->getName().c_str()); - - if(producedUnit->isOfClass(pt->getUnitClass())){ - if(aiInterface->reqsOk(ct) && aiInterface->reqsOk(producedUnit)){ - //produceIt= true; - addUnitTypeToCandidates(producedUnit, ableUnits,ableUnitsGiveBack, false); - } - } - } - } - } - // Now check of the unit 'gives' the resource -// This is likely a unit that it BUILT by another and that is handled by a different AI task type: Build -// if(produceIt == false && pt->getResourceType() != NULL) { -// const Resource *r= ut->getCost(pt->getResourceType()); -// if(r != NULL) { -// if(ai->outputAIBehaviourToConsole()) printf("#2 produceGeneric r = [%s][%d] Testing AI RULE Name[%s]\n",r->getDescription(false).c_str(),r->getAmount(), this->getName().c_str()); -// } -// -// if(r != NULL && r->getAmount() < 0) { -// if(aiInterface->reqsOk(ut)){ -// produceIt= true; -// addUnitTypeToCandidates(ut, ableUnits,ableUnitsGiveBack, true); -// } -// } -// } - - } - - //add specific produce task - if(ableUnits.empty() == false) { - - if(ai->outputAIBehaviourToConsole()) printf("produceGeneric !ableUnits.empty(), ableUnits.size() = [%d] Testing AI RULE Name[%s]\n",(int)ableUnits.size(), this->getName().c_str()); - - // Now check if we already have at least 2 produce or morph - // resource based units, if so prefer units that give back the resource - if(pt->getResourceType() != NULL && ableUnits.size() > 1) { - //priority for non produced units - UnitTypes newAbleUnits; - bool haveEnoughProducers = true; - bool haveNonProducers = false; - for(unsigned int i=0; i < ableUnits.size(); ++i) { - const UnitType *ut = ableUnits[i]; - bool givesBack = ableUnitsGiveBack[i]; - if(givesBack == false && ai->getCountOfType(ut) < 2) { - haveEnoughProducers = false; - } - else if(givesBack == true) { - haveNonProducers = true; - newAbleUnits.push_back(ut); - } - - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In produceGeneric for unit type [%s] givesBack: %d count of unit type: %d",ut->getName(false).c_str(),givesBack,ai->getCountOfType(ut)); - aiInterface->printLog(4, szBuf); - } - - } - - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"haveEnoughProducers [%d] haveNonProducers [%d]",haveEnoughProducers,haveNonProducers); - aiInterface->printLog(4, szBuf); - - for(unsigned int i = 0; i < ableUnits.size(); ++i) { - const UnitType *ut = ableUnits[i]; - snprintf(szBuf,8096,"i: %u unit type [%s]",i,ut->getName(false).c_str()); - aiInterface->printLog(4, szBuf); - } - for(unsigned int i = 0; i < newAbleUnits.size(); ++i) { - const UnitType *ut = newAbleUnits[i]; - snprintf(szBuf,8096,"i: %u new unit type [%s]",i,ut->getName(false).c_str()); - aiInterface->printLog(4, szBuf); - } - } - - if(haveEnoughProducers == true && haveNonProducers == true) { - ableUnits = newAbleUnits; - } - } - - //priority for non produced units - for(unsigned int i=0; i < ableUnits.size(); ++i) { - if(ai->getCountOfType(ableUnits[i]) == 0) { - if(ai->getRandom()->randRange(0, 1)==0) { - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In produceGeneric priority adding produce task: %d of " MG_SIZE_T_SPECIFIER " for unit type [%s]",i,ableUnits.size(),ableUnits[i]->getName(false).c_str()); - aiInterface->printLog(4, szBuf); - } - - ai->addTask(new ProduceTask(ableUnits[i])); - return; - } - } - } - - //normal case - int randomUnitTypeIndex = ai->getRandom()->randRange(0, (int)ableUnits.size()-1); - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In produceGeneric randomUnitTypeIndex = %d of " MG_SIZE_T_SPECIFIER " equals unit type [%s]",randomUnitTypeIndex,ableUnits.size()-1,ableUnits[randomUnitTypeIndex]->getName(false).c_str()); - aiInterface->printLog(4, szBuf); - } - - const UnitType *ut = ableUnits[randomUnitTypeIndex]; - - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"== END In produceGeneric normal adding produce task for unit type [%s]",ut->getName(false).c_str()); - aiInterface->printLog(4, szBuf); - } - - ai->addTask(new ProduceTask(ut)); - } + UnitTypes ableUnits; + UnitTypesGiveBack ableUnitsGiveBack; + + AiInterface *aiInterface = ai->getAiInterface(); + if (pt->getResourceType() != NULL) { + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "****START: produceGeneric for resource type [%s]", + pt->getResourceType()->getName(false).c_str()); + aiInterface->printLog(4, szBuf); + } + + if (setAIProduceTaskForResourceType(pt, aiInterface) == true) { + return; + } + } else if (pt->getUnitClass() == ucWorker) { + if (aiInterface->getMyFactionType() + ->getAIBehaviorUnits(aibcWorkerUnits) + .size() > 0) { + const std::vector &unitList = + aiInterface->getMyFactionType()->getAIBehaviorUnits(aibcWorkerUnits); + for (unsigned int i = 0; i < unitList.size(); ++i) { + const FactionType::PairPUnitTypeInt &priorityUnit = unitList[i]; + if (ai->getCountOfType(priorityUnit.first) < priorityUnit.second && + aiInterface->getMyFaction()->canCreateUnit( + priorityUnit.first, false, true, true) == true) { + ai->addTask(new ProduceTask(priorityUnit.first)); + return; + } + } + } + } else if (pt->getUnitClass() == ucWarrior) { + if (aiInterface->getMyFactionType() + ->getAIBehaviorUnits(aibcWarriorUnits) + .size() > 0) { + const std::vector &unitList = + aiInterface->getMyFactionType()->getAIBehaviorUnits(aibcWarriorUnits); + for (unsigned int i = 0; i < unitList.size(); ++i) { + const FactionType::PairPUnitTypeInt &priorityUnit = unitList[i]; + if (ai->getCountOfType(priorityUnit.first) < priorityUnit.second && + aiInterface->getMyFaction()->canCreateUnit( + priorityUnit.first, false, true, true) == true) { + ai->addTask(new ProduceTask(priorityUnit.first)); + return; + } + } + } + } + + // for each unit, produce it if possible + for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) { + if (aiInterface->getMyUnit(i)->getCurrCommand() != NULL && + aiInterface->getMyUnit(i) + ->getCurrCommand() + ->getCommandType() + ->getClass() == ccBuild) { + // skip this units as it is currently building something + continue; + } + // for each command + const UnitType *ut = aiInterface->getMyUnit(i)->getType(); + + // bool produceIt= false; + for (int j = 0; j < ut->getCommandTypeCount(); ++j) { + const CommandType *ct = ut->getCommandType(j); + + // if the command is produce + // bool produceIt= false; + if (ct->getClass() == ccProduce || ct->getClass() == ccMorph) { + const UnitType *producedUnit = + static_cast(ct->getProduced()); + + if (ai->outputAIBehaviourToConsole()) + printf("produceGeneric [%p] Testing AI RULE Name[%s]\n", + pt->getResourceType(), this->getName().c_str()); + + // if the unit produces the resource + if (pt->getResourceType() != NULL) { + const Resource *r = producedUnit->getCost(pt->getResourceType()); + if (r != NULL) { + if (ai->outputAIBehaviourToConsole()) + printf("produceGeneric r = [%s][%d] Testing AI RULE Name[%s]\n", + r->getDescription(false).c_str(), r->getAmount(), + this->getName().c_str()); + } + + if (r != NULL && r->getAmount() < 0) { + if (aiInterface->reqsOk(ct) && aiInterface->reqsOk(producedUnit)) { + // produceIt= true; + addUnitTypeToCandidates(producedUnit, ableUnits, + ableUnitsGiveBack, false); + } + } + } else { + // if the unit is from the right class + if (ai->outputAIBehaviourToConsole()) + printf( + "produceGeneric right class = [%d] Testing AI RULE Name[%s]\n", + producedUnit->isOfClass(pt->getUnitClass()), + this->getName().c_str()); + + if (producedUnit->isOfClass(pt->getUnitClass())) { + if (aiInterface->reqsOk(ct) && aiInterface->reqsOk(producedUnit)) { + // produceIt= true; + addUnitTypeToCandidates(producedUnit, ableUnits, + ableUnitsGiveBack, false); + } + } + } + } + } + // Now check of the unit 'gives' the resource + // This is likely a unit that it BUILT by another and that is handled by a + // different AI task type: Build + // if(produceIt == false && pt->getResourceType() != NULL) { + // const Resource *r= ut->getCost(pt->getResourceType()); + // if(r != NULL) { + // if(ai->outputAIBehaviourToConsole()) printf("#2 produceGeneric r + //= + //[%s][%d] Testing AI RULE + // Name[%s]\n",r->getDescription(false).c_str(),r->getAmount(), + // this->getName().c_str()); + // } + // + // if(r != NULL && r->getAmount() < 0) { + // if(aiInterface->reqsOk(ut)){ + // produceIt= true; + // addUnitTypeToCandidates(ut, + //ableUnits,ableUnitsGiveBack, true); + // } + // } + // } + } + + // add specific produce task + if (ableUnits.empty() == false) { + + if (ai->outputAIBehaviourToConsole()) + printf("produceGeneric !ableUnits.empty(), ableUnits.size() = [%d] " + "Testing AI RULE Name[%s]\n", + (int)ableUnits.size(), this->getName().c_str()); + + // Now check if we already have at least 2 produce or morph + // resource based units, if so prefer units that give back the resource + if (pt->getResourceType() != NULL && ableUnits.size() > 1) { + // priority for non produced units + UnitTypes newAbleUnits; + bool haveEnoughProducers = true; + bool haveNonProducers = false; + for (unsigned int i = 0; i < ableUnits.size(); ++i) { + const UnitType *ut = ableUnits[i]; + bool givesBack = ableUnitsGiveBack[i]; + if (givesBack == false && ai->getCountOfType(ut) < 2) { + haveEnoughProducers = false; + } else if (givesBack == true) { + haveNonProducers = true; + newAbleUnits.push_back(ut); + } + + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In produceGeneric for unit type [%s] givesBack: %d count " + "of unit type: %d", + ut->getName(false).c_str(), givesBack, + ai->getCountOfType(ut)); + aiInterface->printLog(4, szBuf); + } + } + + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "haveEnoughProducers [%d] haveNonProducers [%d]", + haveEnoughProducers, haveNonProducers); + aiInterface->printLog(4, szBuf); + + for (unsigned int i = 0; i < ableUnits.size(); ++i) { + const UnitType *ut = ableUnits[i]; + snprintf(szBuf, 8096, "i: %u unit type [%s]", i, + ut->getName(false).c_str()); + aiInterface->printLog(4, szBuf); + } + for (unsigned int i = 0; i < newAbleUnits.size(); ++i) { + const UnitType *ut = newAbleUnits[i]; + snprintf(szBuf, 8096, "i: %u new unit type [%s]", i, + ut->getName(false).c_str()); + aiInterface->printLog(4, szBuf); + } + } + + if (haveEnoughProducers == true && haveNonProducers == true) { + ableUnits = newAbleUnits; + } + } + + // priority for non produced units + for (unsigned int i = 0; i < ableUnits.size(); ++i) { + if (ai->getCountOfType(ableUnits[i]) == 0) { + if (ai->getRandom()->randRange(0, 1) == 0) { + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In produceGeneric priority adding produce task: %d " + "of " MG_SIZE_T_SPECIFIER " for unit type [%s]", + i, ableUnits.size(), ableUnits[i]->getName(false).c_str()); + aiInterface->printLog(4, szBuf); + } + + ai->addTask(new ProduceTask(ableUnits[i])); + return; + } + } + } + + // normal case + int randomUnitTypeIndex = + ai->getRandom()->randRange(0, (int)ableUnits.size() - 1); + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "In produceGeneric randomUnitTypeIndex = %d of " MG_SIZE_T_SPECIFIER + " equals unit type [%s]", + randomUnitTypeIndex, ableUnits.size() - 1, + ableUnits[randomUnitTypeIndex]->getName(false).c_str()); + aiInterface->printLog(4, szBuf); + } + + const UnitType *ut = ableUnits[randomUnitTypeIndex]; + + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "== END In produceGeneric normal adding produce task for unit " + "type [%s]", + ut->getName(false).c_str()); + aiInterface->printLog(4, szBuf); + } + + ai->addTask(new ProduceTask(ut)); + } } void AiRuleProduce::produceGeneric(const ProduceTask *pt) { - typedef vector UnitTypes; - UnitTypes ableUnits; - AiInterface *aiInterface= ai->getAiInterface(); - - if(pt->getResourceType() != NULL) { - if(aiInterface->getMyFactionType()->getAIBehaviorUnits(aibcResourceProducerUnits).size() > 0) { - const std::vector &unitList = aiInterface->getMyFactionType()->getAIBehaviorUnits(aibcResourceProducerUnits); - for(unsigned int i = 0; i < unitList.size(); ++i) { - const FactionType::PairPUnitTypeInt &priorityUnit = unitList[i]; - if(ai->getCountOfType(priorityUnit.first) < priorityUnit.second && - aiInterface->getMyFaction()->canCreateUnit(priorityUnit.first, false, true, true) == true) { - //if(ai->getRandom()->randRange(0, 1)==0) { - ai->addTask(new ProduceTask(priorityUnit.first)); - return; - //} - } - } - } - } - else if(pt->getUnitClass() == ucWorker) { - if(aiInterface->getMyFactionType()->getAIBehaviorUnits(aibcWorkerUnits).size() > 0) { - const std::vector &unitList = aiInterface->getMyFactionType()->getAIBehaviorUnits(aibcWorkerUnits); - for(unsigned int i = 0; i < unitList.size(); ++i) { - const FactionType::PairPUnitTypeInt &priorityUnit = unitList[i]; - if(ai->getCountOfType(priorityUnit.first) < priorityUnit.second && - aiInterface->getMyFaction()->canCreateUnit(priorityUnit.first, false, true, true) == true) { - //if(ai->getRandom()->randRange(0, 1)==0) { - ai->addTask(new ProduceTask(priorityUnit.first)); - return; - //} - } - } - } - } - else if(pt->getUnitClass() == ucWarrior) { - if(aiInterface->getMyFactionType()->getAIBehaviorUnits(aibcWarriorUnits).size() > 0) { - const std::vector &unitList = aiInterface->getMyFactionType()->getAIBehaviorUnits(aibcWarriorUnits); - for(unsigned int i = 0; i < unitList.size(); ++i) { - const FactionType::PairPUnitTypeInt &priorityUnit = unitList[i]; - if(ai->getCountOfType(priorityUnit.first) < priorityUnit.second && - aiInterface->getMyFaction()->canCreateUnit(priorityUnit.first, false, true, true) == true) { - //if(ai->getRandom()->randRange(0, 1)==0) { - ai->addTask(new ProduceTask(priorityUnit.first)); - return; - //} - } - } - } - } - - //for each unit, produce it if possible - for(int i = 0; i < aiInterface->getMyUnitCount(); ++i) { - if(aiInterface->getMyUnit(i)->getCurrCommand()!=NULL && aiInterface->getMyUnit(i)->getCurrCommand()->getCommandType()->getClass()==ccBuild){ - //skip this units as it is currently building something - continue; - } - //for each command - const UnitType *ut= aiInterface->getMyUnit(i)->getType(); - for(int j = 0; j < ut->getCommandTypeCount(); ++j) { - const CommandType *ct= ut->getCommandType(j); - - //if the command is produce - if(ct->getClass() == ccProduce || ct->getClass()==ccMorph) { - - const UnitType *producedUnit= static_cast(ct->getProduced()); - bool produceIt= false; - - if(ai->outputAIBehaviourToConsole()) printf("produceGeneric [%p] Testing AI RULE Name[%s]\n",pt->getResourceType(), this->getName().c_str()); - - //if the unit produces the resource - if(pt->getResourceType() != NULL) { - const Resource *r= producedUnit->getCost(pt->getResourceType()); - - if(r != NULL) { - if(ai->outputAIBehaviourToConsole()) printf("produceGeneric r = [%s][%d] Testing AI RULE Name[%s]\n",r->getDescription(false).c_str(),r->getAmount(), this->getName().c_str()); - } - - if(r != NULL && r->getAmount() < 0) { - produceIt= true; - } - } - - else { - //if the unit is from the right class - if(ai->outputAIBehaviourToConsole()) printf("produceGeneric right class = [%d] Testing AI RULE Name[%s]\n",producedUnit->isOfClass(pt->getUnitClass()), this->getName().c_str()); - - if(producedUnit->isOfClass(pt->getUnitClass())){ - if(aiInterface->reqsOk(ct) && aiInterface->reqsOk(producedUnit)){ - produceIt= true; - } - } - } - - if(produceIt) { - //if the unit is not already on the list - if(find(ableUnits.begin(), ableUnits.end(), producedUnit)==ableUnits.end()){ - ableUnits.push_back(producedUnit); - } - } - } - } - } - - //add specific produce task - if(ableUnits.empty() == false) { - - if(ai->outputAIBehaviourToConsole()) printf("produceGeneric !ableUnits.empty(), ableUnits.size() = [%d] Testing AI RULE Name[%s]\n",(int)ableUnits.size(), this->getName().c_str()); - - //priority for non produced units - for(unsigned int i=0; i < ableUnits.size(); ++i) { - if(ai->getCountOfType(ableUnits[i]) == 0) { - if(ai->getRandom()->randRange(0, 1)==0){ - ai->addTask(new ProduceTask(ableUnits[i])); - return; - } - } - } - - //normal case - ai->addTask(new ProduceTask(ableUnits[ai->getRandom()->randRange(0, (int)ableUnits.size()-1)])); - } + typedef vector UnitTypes; + UnitTypes ableUnits; + AiInterface *aiInterface = ai->getAiInterface(); + + if (pt->getResourceType() != NULL) { + if (aiInterface->getMyFactionType() + ->getAIBehaviorUnits(aibcResourceProducerUnits) + .size() > 0) { + const std::vector &unitList = + aiInterface->getMyFactionType()->getAIBehaviorUnits( + aibcResourceProducerUnits); + for (unsigned int i = 0; i < unitList.size(); ++i) { + const FactionType::PairPUnitTypeInt &priorityUnit = unitList[i]; + if (ai->getCountOfType(priorityUnit.first) < priorityUnit.second && + aiInterface->getMyFaction()->canCreateUnit( + priorityUnit.first, false, true, true) == true) { + // if(ai->getRandom()->randRange(0, 1)==0) { + ai->addTask(new ProduceTask(priorityUnit.first)); + return; + //} + } + } + } + } else if (pt->getUnitClass() == ucWorker) { + if (aiInterface->getMyFactionType() + ->getAIBehaviorUnits(aibcWorkerUnits) + .size() > 0) { + const std::vector &unitList = + aiInterface->getMyFactionType()->getAIBehaviorUnits(aibcWorkerUnits); + for (unsigned int i = 0; i < unitList.size(); ++i) { + const FactionType::PairPUnitTypeInt &priorityUnit = unitList[i]; + if (ai->getCountOfType(priorityUnit.first) < priorityUnit.second && + aiInterface->getMyFaction()->canCreateUnit( + priorityUnit.first, false, true, true) == true) { + // if(ai->getRandom()->randRange(0, 1)==0) { + ai->addTask(new ProduceTask(priorityUnit.first)); + return; + //} + } + } + } + } else if (pt->getUnitClass() == ucWarrior) { + if (aiInterface->getMyFactionType() + ->getAIBehaviorUnits(aibcWarriorUnits) + .size() > 0) { + const std::vector &unitList = + aiInterface->getMyFactionType()->getAIBehaviorUnits(aibcWarriorUnits); + for (unsigned int i = 0; i < unitList.size(); ++i) { + const FactionType::PairPUnitTypeInt &priorityUnit = unitList[i]; + if (ai->getCountOfType(priorityUnit.first) < priorityUnit.second && + aiInterface->getMyFaction()->canCreateUnit( + priorityUnit.first, false, true, true) == true) { + // if(ai->getRandom()->randRange(0, 1)==0) { + ai->addTask(new ProduceTask(priorityUnit.first)); + return; + //} + } + } + } + } + + // for each unit, produce it if possible + for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) { + if (aiInterface->getMyUnit(i)->getCurrCommand() != NULL && + aiInterface->getMyUnit(i) + ->getCurrCommand() + ->getCommandType() + ->getClass() == ccBuild) { + // skip this units as it is currently building something + continue; + } + // for each command + const UnitType *ut = aiInterface->getMyUnit(i)->getType(); + for (int j = 0; j < ut->getCommandTypeCount(); ++j) { + const CommandType *ct = ut->getCommandType(j); + + // if the command is produce + if (ct->getClass() == ccProduce || ct->getClass() == ccMorph) { + + const UnitType *producedUnit = + static_cast(ct->getProduced()); + bool produceIt = false; + + if (ai->outputAIBehaviourToConsole()) + printf("produceGeneric [%p] Testing AI RULE Name[%s]\n", + pt->getResourceType(), this->getName().c_str()); + + // if the unit produces the resource + if (pt->getResourceType() != NULL) { + const Resource *r = producedUnit->getCost(pt->getResourceType()); + + if (r != NULL) { + if (ai->outputAIBehaviourToConsole()) + printf("produceGeneric r = [%s][%d] Testing AI RULE Name[%s]\n", + r->getDescription(false).c_str(), r->getAmount(), + this->getName().c_str()); + } + + if (r != NULL && r->getAmount() < 0) { + produceIt = true; + } + } + + else { + // if the unit is from the right class + if (ai->outputAIBehaviourToConsole()) + printf( + "produceGeneric right class = [%d] Testing AI RULE Name[%s]\n", + producedUnit->isOfClass(pt->getUnitClass()), + this->getName().c_str()); + + if (producedUnit->isOfClass(pt->getUnitClass())) { + if (aiInterface->reqsOk(ct) && aiInterface->reqsOk(producedUnit)) { + produceIt = true; + } + } + } + + if (produceIt) { + // if the unit is not already on the list + if (find(ableUnits.begin(), ableUnits.end(), producedUnit) == + ableUnits.end()) { + ableUnits.push_back(producedUnit); + } + } + } + } + } + + // add specific produce task + if (ableUnits.empty() == false) { + + if (ai->outputAIBehaviourToConsole()) + printf("produceGeneric !ableUnits.empty(), ableUnits.size() = [%d] " + "Testing AI RULE Name[%s]\n", + (int)ableUnits.size(), this->getName().c_str()); + + // priority for non produced units + for (unsigned int i = 0; i < ableUnits.size(); ++i) { + if (ai->getCountOfType(ableUnits[i]) == 0) { + if (ai->getRandom()->randRange(0, 1) == 0) { + ai->addTask(new ProduceTask(ableUnits[i])); + return; + } + } + } + + // normal case + ai->addTask(new ProduceTask( + ableUnits[ai->getRandom()->randRange(0, (int)ableUnits.size() - 1)])); + } } -void AiRuleProduce::produceSpecific(const ProduceTask *pt){ - - AiInterface *aiInterface= ai->getAiInterface(); - - if(ai->outputAIBehaviourToConsole()) printf("produceSpecific aiInterface->reqsOk(pt->getUnitType()) = [%s][%d] Testing AI RULE Name[%s]\n",pt->getUnitType()->getName().c_str(),aiInterface->reqsOk(pt->getUnitType()), this->getName().c_str()); - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"== START produceSpecific aiInterface->reqsOk(pt->getUnitType()) = [%s][%d] Testing AI RULE Name[%s]",pt->getUnitType()->getName().c_str(),aiInterface->reqsOk(pt->getUnitType()), this->getName().c_str()); - aiInterface->printLog(4, szBuf); - } - - //if unit meets requirements - if(aiInterface->reqsOk(pt->getUnitType())) { - - const CommandType *ctypeForCostCheck = NULL; - //for each unit - for(int i=0; igetMyUnitCount(); ++i){ - //don't use units which are currently building - if(aiInterface->getMyUnit(i)->getCurrCommand()!=NULL && aiInterface->getMyUnit(i)->getCurrCommand()->getCommandType()->getClass()==ccBuild){ - //skip this units as it is currently building something - continue; - } - //for each command - const UnitType *ut= aiInterface->getMyUnit(i)->getType(); - for(int j=0; jgetCommandTypeCount(); ++j){ - const CommandType *ct= ut->getCommandType(j); - - //if the command is produce - if(ct->getClass()==ccProduce || ct->getClass()==ccMorph){ - const UnitType *producedUnit= static_cast(ct->getProduced()); - - //if units match - if(producedUnit == pt->getUnitType()){ - - if(ai->outputAIBehaviourToConsole()) printf("produceSpecific aiInterface->reqsOk(ct) = [%d] Testing AI RULE Name[%s]\n",aiInterface->reqsOk(ct), this->getName().c_str()); - - if(aiInterface->reqsOk(ct)){ - if(ctypeForCostCheck == NULL || ct->getClass() == ccMorph) { - if(ctypeForCostCheck != NULL && ct->getClass() == ccMorph) { - const MorphCommandType *mct = dynamic_cast(ct); - if(mct == NULL) { - throw megaglest_runtime_error("mct == NULL"); - } - if(mct->getIgnoreResourceRequirements() == true) { - ctypeForCostCheck= ct; - } - } - else { - ctypeForCostCheck= ct; - } - } - } - } - } - } - } - - if(ai->outputAIBehaviourToConsole()) printf("produceSpecific aiInterface->checkCosts(pt->getUnitType()) = [%d] Testing AI RULE Name[%s]\n",aiInterface->checkCosts(pt->getUnitType(),ctypeForCostCheck), this->getName().c_str()); - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"produceSpecific aiInterface->checkCosts(pt->getUnitType()) = [%d] Testing AI RULE Name[%s]",aiInterface->checkCosts(pt->getUnitType(),ctypeForCostCheck), this->getName().c_str()); - aiInterface->printLog(4, szBuf); - } - - //if unit doesnt meet resources retry - if(aiInterface->checkCosts(pt->getUnitType(),ctypeForCostCheck) == false) { - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Check costs FAILED."); - aiInterface->printLog(4, szBuf); - } - - ai->retryTask(pt); - return; - } - - //produce specific unit - vector producers; - // Hold a list of units which can produce or morph - // then a list of commandtypes for each unit - map > producersDefaultCommandType; - const CommandType *defCt= NULL; - - //for each unit - for(int i=0; igetMyUnitCount(); ++i){ - if(aiInterface->getMyUnit(i)->getCurrCommand()!=NULL && aiInterface->getMyUnit(i)->getCurrCommand()->getCommandType()->getClass()==ccBuild){ - //skip this units as it is currently building something - continue; - } - //for each command - const UnitType *ut= aiInterface->getMyUnit(i)->getType(); - for(int j=0; jgetCommandTypeCount(); ++j){ - const CommandType *ct= ut->getCommandType(j); - - //if the command is produce - if(ct->getClass()==ccProduce || ct->getClass()==ccMorph){ - const UnitType *producedUnit= static_cast(ct->getProduced()); - - //if units match - if(producedUnit == pt->getUnitType()){ - - if(ai->outputAIBehaviourToConsole()) printf("produceSpecific aiInterface->reqsOk(ct) = [%d] Testing AI RULE Name[%s]\n",aiInterface->reqsOk(ct), this->getName().c_str()); - - if(aiInterface->reqsOk(ct)){ - //defCt= ct; - producers.push_back(i); - producersDefaultCommandType[i].push_back(ct); - } - } - } - } - } - - //produce from random producer - if(producers.empty() == false) { - - if(ai->outputAIBehaviourToConsole()) printf("produceSpecific producers.empty() = [%d] Testing AI RULE Name[%s]\n",producers.empty(), this->getName().c_str()); - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"produceSpecific producers.empty() = [%d] Testing AI RULE Name[%s]",producers.empty(), this->getName().c_str()); - aiInterface->printLog(4, szBuf); - } - - // Narrow down producers list to those who are not busy if possible - vector idle_producers; - for(unsigned int i = 0; i < producers.size(); ++i) { - int currentProducerIndex = producers[i]; - if(currentProducerIndex >= aiInterface->getMyUnitCount()) { - char szBuf[8096]=""; - printf("In [%s::%s Line: %d] currentProducerIndex >= aiInterface->getMyUnitCount(), currentProducerIndex = %d, aiInterface->getMyUnitCount() = %d, i = %u,producers.size() = " MG_SIZE_T_SPECIFIER "\n",__FILE__,__FUNCTION__,__LINE__,currentProducerIndex,aiInterface->getMyUnitCount(),i,producers.size()); - snprintf(szBuf,8096,"In [%s::%s Line: %d] currentProducerIndex >= aiInterface->getMyUnitCount(), currentProducerIndex = %d, aiInterface->getMyUnitCount() = %u, i = %u,producers.size() = " MG_SIZE_T_SPECIFIER "",__FILE__,__FUNCTION__,__LINE__,currentProducerIndex,aiInterface->getMyUnitCount(),i,producers.size()); - throw megaglest_runtime_error(szBuf); - } - - const Unit *unit = aiInterface->getMyUnit(currentProducerIndex); - if(unit->anyCommand() == false) { - idle_producers.push_back(currentProducerIndex); - } - } - if(idle_producers.empty() == false) { - producers = idle_producers; - } - - if( aiInterface->getControlType() == ctCpuMega || - aiInterface->getControlType() == ctNetworkCpuMega) - {// mega cpu trys to balance the commands to the producers - int randomstart=ai->getRandom()->randRange(0, (int)producers.size()-1); - int lowestCommandCount=1000000; - int currentProducerIndex=producers[randomstart]; - int bestIndex=-1; - //int besti=0; - int currentCommandCount=0; - for(unsigned int i=randomstart; i= producers.size()) { - prIndex = (i - (int)producers.size()); - } - currentProducerIndex=producers[prIndex]; - - if(currentProducerIndex >= aiInterface->getMyUnitCount()) { - char szBuf[8096]=""; - printf("In [%s::%s Line: %d] currentProducerIndex >= aiInterface->getMyUnitCount(), currentProducerIndex = %d, aiInterface->getMyUnitCount() = %d, i = %u,producers.size() = " MG_SIZE_T_SPECIFIER "\n",__FILE__,__FUNCTION__,__LINE__,currentProducerIndex,aiInterface->getMyUnitCount(),i,producers.size()); - snprintf(szBuf,8096,"In [%s::%s Line: %d] currentProducerIndex >= aiInterface->getMyUnitCount(), currentProducerIndex = %d, aiInterface->getMyUnitCount() = %u, i = %u,producers.size() = " MG_SIZE_T_SPECIFIER "",__FILE__,__FUNCTION__,__LINE__,currentProducerIndex,aiInterface->getMyUnitCount(),i,producers.size()); - throw megaglest_runtime_error(szBuf); - } - if(prIndex >= (int)producers.size()) { - char szBuf[8096]=""; - printf("In [%s::%s Line: %d] prIndex >= producers.size(), currentProducerIndex = %d, i = %u,producers.size() = " MG_SIZE_T_SPECIFIER " \n",__FILE__,__FUNCTION__,__LINE__,prIndex,i,producers.size()); - snprintf(szBuf,8096,"In [%s::%s Line: %d] currentProducerIndex >= producers.size(), currentProducerIndex = %d, i = %u,producers.size() = " MG_SIZE_T_SPECIFIER "",__FILE__,__FUNCTION__,__LINE__,currentProducerIndex,i,producers.size()); - throw megaglest_runtime_error(szBuf); - } - - currentCommandCount=aiInterface->getMyUnit(currentProducerIndex)->getCommandSize(); - if( currentCommandCount==1 && - aiInterface->getMyUnit(currentProducerIndex)->getCurrCommand()->getCommandType()->getClass()==ccStop) - {// special for non buildings - currentCommandCount=0; - } - if(lowestCommandCount>currentCommandCount) - { - lowestCommandCount=aiInterface->getMyUnit(currentProducerIndex)->getCommandSize(); - bestIndex=currentProducerIndex; - //besti=i%(producers.size()); - } - } - if(bestIndex >= 0) { - if( aiInterface->getMyUnit(bestIndex)->getCommandSize() > 2) { - // maybe we need another producer of this kind if possible! - if(aiInterface->reqsOk(aiInterface->getMyUnit(bestIndex)->getType())) { - if(ai->getCountOfClass(ucBuilding) > 5) { - ai->addTask(new BuildTask(aiInterface->getMyUnit(bestIndex)->getType())); - } - } - // need to calculate another producer, maybe its better to produce another warrior with another producer - vector backupProducers; - // find another producer unit which is free and produce any kind of warrior. - //for each unit - for(int i=0; igetMyUnitCount(); ++i){ - const UnitType *ut= aiInterface->getMyUnit(i)->getType(); - //for each command - for(int j=0; jgetCommandTypeCount(); ++j){ - const CommandType *ct= ut->getCommandType(j); - //if the command is produce - if(ct->getClass() == ccProduce) { - const UnitType *unitType= static_cast(ct->getProduced()); - if(unitType->hasSkillClass(scAttack) && !unitType->hasCommandClass(ccHarvest) && aiInterface->reqsOk(ct)) - {//this can produce a warrior - backupProducers.push_back(i); - } - } - } - } - if(!backupProducers.empty()) { - int randomstart=ai->getRandom()->randRange(0, (int)backupProducers.size()-1); - int lowestCommandCount=1000000; - int currentProducerIndex=backupProducers[randomstart]; - int bestIndex=-1; - for(unsigned int i=randomstart; i= backupProducers.size()) { - prIndex = (i - (int)backupProducers.size()); - } - - currentProducerIndex=backupProducers[prIndex]; - - if(currentProducerIndex >= aiInterface->getMyUnitCount()) { - char szBuf[8096]=""; - printf("In [%s::%s Line: %d] currentProducerIndex >= aiInterface->getMyUnitCount(), currentProducerIndex = %d, aiInterface->getMyUnitCount() = %d, i = %u,backupProducers.size() = " MG_SIZE_T_SPECIFIER "\n",__FILE__,__FUNCTION__,__LINE__,currentProducerIndex,aiInterface->getMyUnitCount(),i,backupProducers.size()); - snprintf(szBuf,8096,"In [%s::%s Line: %d] currentProducerIndex >= aiInterface->getMyUnitCount(), currentProducerIndex = %d, aiInterface->getMyUnitCount() = %d, i = %u,backupProducers.size() = " MG_SIZE_T_SPECIFIER "",__FILE__,__FUNCTION__,__LINE__,currentProducerIndex,aiInterface->getMyUnitCount(),i,backupProducers.size()); - throw megaglest_runtime_error(szBuf); - } - if(prIndex >= (int)backupProducers.size()) { - char szBuf[8096]=""; - printf("In [%s::%s Line: %d] prIndex >= backupProducers.size(), currentProducerIndex = %d, i = %u,backupProducers.size() = " MG_SIZE_T_SPECIFIER " \n",__FILE__,__FUNCTION__,__LINE__,prIndex,i,backupProducers.size()); - snprintf(szBuf,8096,"In [%s::%s Line: %d] currentProducerIndex >= backupProducers.size(), currentProducerIndex = %d, i = %u,backupProducers.size() = " MG_SIZE_T_SPECIFIER "",__FILE__,__FUNCTION__,__LINE__,currentProducerIndex,i,backupProducers.size()); - throw megaglest_runtime_error(szBuf); - } - - int currentCommandCount=aiInterface->getMyUnit(currentProducerIndex)->getCommandSize(); - if( currentCommandCount==1 && - aiInterface->getMyUnit(currentProducerIndex)->getCurrCommand()->getCommandType()->getClass()==ccStop) - {// special for non buildings - currentCommandCount=0; - } - if(lowestCommandCount>currentCommandCount) { - lowestCommandCount=currentCommandCount; - bestIndex=currentProducerIndex; - if(lowestCommandCount==0) break; - } - } - // a good producer is found, lets choose a warrior production - vector productionCommandIndexes; - if(bestIndex >= 0) { - const UnitType *ut=aiInterface->getMyUnit(bestIndex)->getType(); - for(int j=0; jgetCommandTypeCount(); ++j){ - const CommandType *ct= ut->getCommandType(j); - - //if the command is produce - if(ct->getClass()==ccProduce) { - const UnitType *unitType= static_cast(ct->getProduced()); - if(unitType->hasSkillClass(scAttack) && !unitType->hasCommandClass(ccHarvest) && aiInterface->reqsOk(ct)) - {//this can produce a warrior - productionCommandIndexes.push_back(j); - } - } - } - - int commandIndex=productionCommandIndexes[ai->getRandom()->randRange(0, (int)productionCommandIndexes.size()-1)]; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(ai->outputAIBehaviourToConsole()) printf("mega #1 produceSpecific giveCommand to unit [%s] commandType [%s]\n",aiInterface->getMyUnit(bestIndex)->getType()->getName().c_str(),ut->getCommandType(commandIndex)->getName().c_str()); - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"mega #1 produceSpecific giveCommand to unit [%s] commandType [%s]",aiInterface->getMyUnit(bestIndex)->getType()->getName().c_str(),ut->getCommandType(commandIndex)->getName().c_str()); - aiInterface->printLog(4, szBuf); - } - - aiInterface->giveCommand(bestIndex, ut->getCommandType(commandIndex)); - } - } - else - {// do it like normal CPU - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - defCt = NULL; - if(producersDefaultCommandType.find(bestIndex) != producersDefaultCommandType.end()) { - int bestCommandTypeCount = (int)producersDefaultCommandType[bestIndex].size(); - int bestCommandTypeIndex = ai->getRandom()->randRange(0, bestCommandTypeCount-1); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] bestCommandTypeIndex = %d, bestCommandTypeCount = %d\n",__FILE__,__FUNCTION__,__LINE__,bestCommandTypeIndex,bestCommandTypeCount); - - defCt = producersDefaultCommandType[bestIndex][bestCommandTypeIndex]; - } - - if(ai->outputAIBehaviourToConsole()) printf("mega #2 produceSpecific giveCommand to unit [%s] commandType [%s]\n",aiInterface->getMyUnit(bestIndex)->getType()->getName().c_str(),(defCt != NULL ? defCt->getName().c_str() : "n/a")); - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"mega #2 produceSpecific giveCommand to unit [%s] commandType [%s]",aiInterface->getMyUnit(bestIndex)->getType()->getName().c_str(),(defCt != NULL ? defCt->getName().c_str() : "n/a")); - aiInterface->printLog(4, szBuf); - } - aiInterface->giveCommand(bestIndex, defCt); - } - } - else { - if(currentCommandCount == 0) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - defCt = NULL; - if(producersDefaultCommandType.find(bestIndex) != producersDefaultCommandType.end()) { - //defCt = producersDefaultCommandType[bestIndex]; - int bestCommandTypeCount = (int)producersDefaultCommandType[bestIndex].size(); - int bestCommandTypeIndex = ai->getRandom()->randRange(0, bestCommandTypeCount-1); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] bestCommandTypeIndex = %d, bestCommandTypeCount = %d\n",__FILE__,__FUNCTION__,__LINE__,bestCommandTypeIndex,bestCommandTypeCount); - - defCt = producersDefaultCommandType[bestIndex][bestCommandTypeIndex]; - } - - if(ai->outputAIBehaviourToConsole()) printf("mega #3 produceSpecific giveCommand to unit [%s] commandType [%s]\n",aiInterface->getMyUnit(bestIndex)->getType()->getName().c_str(),(defCt != NULL ? defCt->getName().c_str() : "n/a")); - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"mega #3 produceSpecific giveCommand to unit [%s] commandType [%s]",aiInterface->getMyUnit(bestIndex)->getType()->getName().c_str(),(defCt != NULL ? defCt->getName().c_str() : "n/a")); - aiInterface->printLog(4, szBuf); - } - - aiInterface->giveCommand(bestIndex, defCt); - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - defCt = NULL; - if(producersDefaultCommandType.find(bestIndex) != producersDefaultCommandType.end()) { - //defCt = producersDefaultCommandType[bestIndex]; - int bestCommandTypeCount = (int)producersDefaultCommandType[bestIndex].size(); - int bestCommandTypeIndex = ai->getRandom()->randRange(0, bestCommandTypeCount-1); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] bestCommandTypeIndex = %d, bestCommandTypeCount = %d\n",__FILE__,__FUNCTION__,__LINE__,bestCommandTypeIndex,bestCommandTypeCount); - - defCt = producersDefaultCommandType[bestIndex][bestCommandTypeIndex]; - } - if(ai->outputAIBehaviourToConsole()) printf("mega #4 produceSpecific giveCommand to unit [%s] commandType [%s]\n",aiInterface->getMyUnit(bestIndex)->getType()->getName().c_str(),(defCt != NULL ? defCt->getName().c_str() : "n/a")); - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"mega #4 produceSpecific giveCommand to unit [%s] commandType [%s]",aiInterface->getMyUnit(bestIndex)->getType()->getName().c_str(),(defCt != NULL ? defCt->getName().c_str() : "n/a")); - aiInterface->printLog(4, szBuf); - } - - aiInterface->giveCommand(bestIndex, defCt); - } - } - } - else { - int pIndex = ai->getRandom()->randRange(0, (int)producers.size()-1); - int producerIndex= producers[pIndex]; - defCt = NULL; - if(producersDefaultCommandType.find(producerIndex) != producersDefaultCommandType.end()) { - //defCt = producersDefaultCommandType[producerIndex]; - int bestCommandTypeCount = (int)producersDefaultCommandType[producerIndex].size(); - int bestCommandTypeIndex = ai->getRandom()->randRange(0, bestCommandTypeCount-1); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] bestCommandTypeIndex = %d, bestCommandTypeCount = %d\n",__FILE__,__FUNCTION__,__LINE__,bestCommandTypeIndex,bestCommandTypeCount); - - defCt = producersDefaultCommandType[producerIndex][bestCommandTypeIndex]; - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] producers.size() = %d, producerIndex = %d, pIndex = %d, producersDefaultCommandType.size() = %d\n",__FILE__,__FUNCTION__,__LINE__,producers.size(),producerIndex,pIndex,producersDefaultCommandType.size()); - - if(ai->outputAIBehaviourToConsole()) printf("produceSpecific giveCommand to unit [%s] commandType [%s]\n",aiInterface->getMyUnit(producerIndex)->getType()->getName().c_str(),(defCt != NULL ? defCt->getName().c_str() : "n/a")); - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"produceSpecific giveCommand to unit [%s] commandType [%s]",aiInterface->getMyUnit(producerIndex)->getType()->getName().c_str(),(defCt != NULL ? defCt->getName().c_str() : "(null)")); - aiInterface->printLog(4, szBuf); - } - aiInterface->giveCommand(producerIndex, defCt); - } - } - } +void AiRuleProduce::produceSpecific(const ProduceTask *pt) { + + AiInterface *aiInterface = ai->getAiInterface(); + + if (ai->outputAIBehaviourToConsole()) + printf("produceSpecific aiInterface->reqsOk(pt->getUnitType()) = [%s][%d] " + "Testing AI RULE Name[%s]\n", + pt->getUnitType()->getName().c_str(), + aiInterface->reqsOk(pt->getUnitType()), this->getName().c_str()); + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "== START produceSpecific aiInterface->reqsOk(pt->getUnitType()) " + "= [%s][%d] Testing AI RULE Name[%s]", + pt->getUnitType()->getName().c_str(), + aiInterface->reqsOk(pt->getUnitType()), this->getName().c_str()); + aiInterface->printLog(4, szBuf); + } + + // if unit meets requirements + if (aiInterface->reqsOk(pt->getUnitType())) { + + const CommandType *ctypeForCostCheck = NULL; + // for each unit + for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) { + // don't use units which are currently building + if (aiInterface->getMyUnit(i)->getCurrCommand() != NULL && + aiInterface->getMyUnit(i) + ->getCurrCommand() + ->getCommandType() + ->getClass() == ccBuild) { + // skip this units as it is currently building something + continue; + } + // for each command + const UnitType *ut = aiInterface->getMyUnit(i)->getType(); + for (int j = 0; j < ut->getCommandTypeCount(); ++j) { + const CommandType *ct = ut->getCommandType(j); + + // if the command is produce + if (ct->getClass() == ccProduce || ct->getClass() == ccMorph) { + const UnitType *producedUnit = + static_cast(ct->getProduced()); + + // if units match + if (producedUnit == pt->getUnitType()) { + + if (ai->outputAIBehaviourToConsole()) + printf("produceSpecific aiInterface->reqsOk(ct) = [%d] Testing " + "AI RULE Name[%s]\n", + aiInterface->reqsOk(ct), this->getName().c_str()); + + if (aiInterface->reqsOk(ct)) { + if (ctypeForCostCheck == NULL || ct->getClass() == ccMorph) { + if (ctypeForCostCheck != NULL && ct->getClass() == ccMorph) { + const MorphCommandType *mct = + dynamic_cast(ct); + if (mct == NULL) { + throw megaglest_runtime_error("mct == NULL"); + } + if (mct->getIgnoreResourceRequirements() == true) { + ctypeForCostCheck = ct; + } + } else { + ctypeForCostCheck = ct; + } + } + } + } + } + } + } + + if (ai->outputAIBehaviourToConsole()) + printf("produceSpecific aiInterface->checkCosts(pt->getUnitType()) = " + "[%d] Testing AI RULE Name[%s]\n", + aiInterface->checkCosts(pt->getUnitType(), ctypeForCostCheck), + this->getName().c_str()); + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "produceSpecific aiInterface->checkCosts(pt->getUnitType()) = " + "[%d] Testing AI RULE Name[%s]", + aiInterface->checkCosts(pt->getUnitType(), ctypeForCostCheck), + this->getName().c_str()); + aiInterface->printLog(4, szBuf); + } + + // if unit doesnt meet resources retry + if (aiInterface->checkCosts(pt->getUnitType(), ctypeForCostCheck) == + false) { + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "Check costs FAILED."); + aiInterface->printLog(4, szBuf); + } + + ai->retryTask(pt); + return; + } + + // produce specific unit + vector producers; + // Hold a list of units which can produce or morph + // then a list of commandtypes for each unit + map> producersDefaultCommandType; + const CommandType *defCt = NULL; + + // for each unit + for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) { + if (aiInterface->getMyUnit(i)->getCurrCommand() != NULL && + aiInterface->getMyUnit(i) + ->getCurrCommand() + ->getCommandType() + ->getClass() == ccBuild) { + // skip this units as it is currently building something + continue; + } + // for each command + const UnitType *ut = aiInterface->getMyUnit(i)->getType(); + for (int j = 0; j < ut->getCommandTypeCount(); ++j) { + const CommandType *ct = ut->getCommandType(j); + + // if the command is produce + if (ct->getClass() == ccProduce || ct->getClass() == ccMorph) { + const UnitType *producedUnit = + static_cast(ct->getProduced()); + + // if units match + if (producedUnit == pt->getUnitType()) { + + if (ai->outputAIBehaviourToConsole()) + printf("produceSpecific aiInterface->reqsOk(ct) = [%d] Testing " + "AI RULE Name[%s]\n", + aiInterface->reqsOk(ct), this->getName().c_str()); + + if (aiInterface->reqsOk(ct)) { + // defCt= ct; + producers.push_back(i); + producersDefaultCommandType[i].push_back(ct); + } + } + } + } + } + + // produce from random producer + if (producers.empty() == false) { + + if (ai->outputAIBehaviourToConsole()) + printf("produceSpecific producers.empty() = [%d] Testing AI RULE " + "Name[%s]\n", + producers.empty(), this->getName().c_str()); + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "produceSpecific producers.empty() = [%d] Testing AI RULE Name[%s]", + producers.empty(), this->getName().c_str()); + aiInterface->printLog(4, szBuf); + } + + // Narrow down producers list to those who are not busy if possible + vector idle_producers; + for (unsigned int i = 0; i < producers.size(); ++i) { + int currentProducerIndex = producers[i]; + if (currentProducerIndex >= aiInterface->getMyUnitCount()) { + char szBuf[8096] = ""; + printf("In [%s::%s Line: %d] currentProducerIndex >= " + "aiInterface->getMyUnitCount(), currentProducerIndex = %d, " + "aiInterface->getMyUnitCount() = %d, i = %u,producers.size() " + "= " MG_SIZE_T_SPECIFIER "\n", + __FILE__, __FUNCTION__, __LINE__, currentProducerIndex, + aiInterface->getMyUnitCount(), i, producers.size()); + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] currentProducerIndex >= " + "aiInterface->getMyUnitCount(), currentProducerIndex = %d, " + "aiInterface->getMyUnitCount() = %u, i = " + "%u,producers.size() = " MG_SIZE_T_SPECIFIER "", + __FILE__, __FUNCTION__, __LINE__, currentProducerIndex, + aiInterface->getMyUnitCount(), i, producers.size()); + throw megaglest_runtime_error(szBuf); + } + + const Unit *unit = aiInterface->getMyUnit(currentProducerIndex); + if (unit->anyCommand() == false) { + idle_producers.push_back(currentProducerIndex); + } + } + if (idle_producers.empty() == false) { + producers = idle_producers; + } + + if (aiInterface->getControlType() == ctCpuMega || + aiInterface->getControlType() == + ctNetworkCpuMega) { // mega cpu trys to balance the commands to + // the producers + int randomstart = + ai->getRandom()->randRange(0, (int)producers.size() - 1); + int lowestCommandCount = 1000000; + int currentProducerIndex = producers[randomstart]; + int bestIndex = -1; + // int besti=0; + int currentCommandCount = 0; + for (unsigned int i = randomstart; i < producers.size() + randomstart; + i++) { + int prIndex = i; + if (i >= producers.size()) { + prIndex = (i - (int)producers.size()); + } + currentProducerIndex = producers[prIndex]; + + if (currentProducerIndex >= aiInterface->getMyUnitCount()) { + char szBuf[8096] = ""; + printf("In [%s::%s Line: %d] currentProducerIndex >= " + "aiInterface->getMyUnitCount(), currentProducerIndex = %d, " + "aiInterface->getMyUnitCount() = %d, i = " + "%u,producers.size() = " MG_SIZE_T_SPECIFIER "\n", + __FILE__, __FUNCTION__, __LINE__, currentProducerIndex, + aiInterface->getMyUnitCount(), i, producers.size()); + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] currentProducerIndex >= " + "aiInterface->getMyUnitCount(), currentProducerIndex = " + "%d, aiInterface->getMyUnitCount() = %u, i = " + "%u,producers.size() = " MG_SIZE_T_SPECIFIER "", + __FILE__, __FUNCTION__, __LINE__, currentProducerIndex, + aiInterface->getMyUnitCount(), i, producers.size()); + throw megaglest_runtime_error(szBuf); + } + if (prIndex >= (int)producers.size()) { + char szBuf[8096] = ""; + printf("In [%s::%s Line: %d] prIndex >= producers.size(), " + "currentProducerIndex = %d, i = %u,producers.size() " + "= " MG_SIZE_T_SPECIFIER " \n", + __FILE__, __FUNCTION__, __LINE__, prIndex, i, + producers.size()); + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] currentProducerIndex >= " + "producers.size(), currentProducerIndex = %d, i = " + "%u,producers.size() = " MG_SIZE_T_SPECIFIER "", + __FILE__, __FUNCTION__, __LINE__, currentProducerIndex, i, + producers.size()); + throw megaglest_runtime_error(szBuf); + } + + currentCommandCount = + aiInterface->getMyUnit(currentProducerIndex)->getCommandSize(); + if (currentCommandCount == 1 && + aiInterface->getMyUnit(currentProducerIndex) + ->getCurrCommand() + ->getCommandType() + ->getClass() == ccStop) { // special for non buildings + currentCommandCount = 0; + } + if (lowestCommandCount > currentCommandCount) { + lowestCommandCount = + aiInterface->getMyUnit(currentProducerIndex)->getCommandSize(); + bestIndex = currentProducerIndex; + // besti=i%(producers.size()); + } + } + if (bestIndex >= 0) { + if (aiInterface->getMyUnit(bestIndex)->getCommandSize() > 2) { + // maybe we need another producer of this kind if possible! + if (aiInterface->reqsOk( + aiInterface->getMyUnit(bestIndex)->getType())) { + if (ai->getCountOfClass(ucBuilding) > 5) { + ai->addTask(new BuildTask( + aiInterface->getMyUnit(bestIndex)->getType())); + } + } + // need to calculate another producer, maybe its better to produce + // another warrior with another producer + vector backupProducers; + // find another producer unit which is free and produce any kind of + // warrior. + // for each unit + for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) { + const UnitType *ut = aiInterface->getMyUnit(i)->getType(); + // for each command + for (int j = 0; j < ut->getCommandTypeCount(); ++j) { + const CommandType *ct = ut->getCommandType(j); + // if the command is produce + if (ct->getClass() == ccProduce) { + const UnitType *unitType = + static_cast(ct->getProduced()); + if (unitType->hasSkillClass(scAttack) && + !unitType->hasCommandClass(ccHarvest) && + aiInterface->reqsOk(ct)) { // this can produce a warrior + backupProducers.push_back(i); + } + } + } + } + if (!backupProducers.empty()) { + int randomstart = ai->getRandom()->randRange( + 0, (int)backupProducers.size() - 1); + int lowestCommandCount = 1000000; + int currentProducerIndex = backupProducers[randomstart]; + int bestIndex = -1; + for (unsigned int i = randomstart; + i < backupProducers.size() + randomstart; i++) { + int prIndex = i; + if (i >= backupProducers.size()) { + prIndex = (i - (int)backupProducers.size()); + } + + currentProducerIndex = backupProducers[prIndex]; + + if (currentProducerIndex >= aiInterface->getMyUnitCount()) { + char szBuf[8096] = ""; + printf( + "In [%s::%s Line: %d] currentProducerIndex >= " + "aiInterface->getMyUnitCount(), currentProducerIndex = " + "%d, aiInterface->getMyUnitCount() = %d, i = " + "%u,backupProducers.size() = " MG_SIZE_T_SPECIFIER "\n", + __FILE__, __FUNCTION__, __LINE__, currentProducerIndex, + aiInterface->getMyUnitCount(), i, backupProducers.size()); + snprintf( + szBuf, 8096, + "In [%s::%s Line: %d] currentProducerIndex >= " + "aiInterface->getMyUnitCount(), currentProducerIndex = " + "%d, aiInterface->getMyUnitCount() = %d, i = " + "%u,backupProducers.size() = " MG_SIZE_T_SPECIFIER "", + __FILE__, __FUNCTION__, __LINE__, currentProducerIndex, + aiInterface->getMyUnitCount(), i, backupProducers.size()); + throw megaglest_runtime_error(szBuf); + } + if (prIndex >= (int)backupProducers.size()) { + char szBuf[8096] = ""; + printf("In [%s::%s Line: %d] prIndex >= " + "backupProducers.size(), currentProducerIndex = %d, i " + "= %u,backupProducers.size() = " MG_SIZE_T_SPECIFIER + " \n", + __FILE__, __FUNCTION__, __LINE__, prIndex, i, + backupProducers.size()); + snprintf( + szBuf, 8096, + "In [%s::%s Line: %d] currentProducerIndex >= " + "backupProducers.size(), currentProducerIndex = %d, i = " + "%u,backupProducers.size() = " MG_SIZE_T_SPECIFIER "", + __FILE__, __FUNCTION__, __LINE__, currentProducerIndex, i, + backupProducers.size()); + throw megaglest_runtime_error(szBuf); + } + + int currentCommandCount = + aiInterface->getMyUnit(currentProducerIndex) + ->getCommandSize(); + if (currentCommandCount == 1 && + aiInterface->getMyUnit(currentProducerIndex) + ->getCurrCommand() + ->getCommandType() + ->getClass() == + ccStop) { // special for non buildings + currentCommandCount = 0; + } + if (lowestCommandCount > currentCommandCount) { + lowestCommandCount = currentCommandCount; + bestIndex = currentProducerIndex; + if (lowestCommandCount == 0) + break; + } + } + // a good producer is found, lets choose a warrior production + vector productionCommandIndexes; + if (bestIndex >= 0) { + const UnitType *ut = + aiInterface->getMyUnit(bestIndex)->getType(); + for (int j = 0; j < ut->getCommandTypeCount(); ++j) { + const CommandType *ct = ut->getCommandType(j); + + // if the command is produce + if (ct->getClass() == ccProduce) { + const UnitType *unitType = + static_cast(ct->getProduced()); + if (unitType->hasSkillClass(scAttack) && + !unitType->hasCommandClass(ccHarvest) && + aiInterface->reqsOk(ct)) { // this can produce a warrior + productionCommandIndexes.push_back(j); + } + } + } + + int commandIndex = + productionCommandIndexes[ai->getRandom()->randRange( + 0, (int)productionCommandIndexes.size() - 1)]; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + + if (ai->outputAIBehaviourToConsole()) + printf("mega #1 produceSpecific giveCommand to unit [%s] " + "commandType [%s]\n", + aiInterface->getMyUnit(bestIndex) + ->getType() + ->getName() + .c_str(), + ut->getCommandType(commandIndex)->getName().c_str()); + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "mega #1 produceSpecific giveCommand to unit [%s] " + "commandType [%s]", + aiInterface->getMyUnit(bestIndex) + ->getType() + ->getName() + .c_str(), + ut->getCommandType(commandIndex)->getName().c_str()); + aiInterface->printLog(4, szBuf); + } + + aiInterface->giveCommand(bestIndex, + ut->getCommandType(commandIndex)); + } + } else { // do it like normal CPU + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + defCt = NULL; + if (producersDefaultCommandType.find(bestIndex) != + producersDefaultCommandType.end()) { + int bestCommandTypeCount = + (int)producersDefaultCommandType[bestIndex].size(); + int bestCommandTypeIndex = + ai->getRandom()->randRange(0, bestCommandTypeCount - 1); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] bestCommandTypeIndex = %d, " + "bestCommandTypeCount = %d\n", + __FILE__, __FUNCTION__, __LINE__, bestCommandTypeIndex, + bestCommandTypeCount); + + defCt = producersDefaultCommandType[bestIndex] + [bestCommandTypeIndex]; + } + + if (ai->outputAIBehaviourToConsole()) + printf("mega #2 produceSpecific giveCommand to unit [%s] " + "commandType [%s]\n", + aiInterface->getMyUnit(bestIndex) + ->getType() + ->getName() + .c_str(), + (defCt != NULL ? defCt->getName().c_str() : "n/a")); + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "mega #2 produceSpecific giveCommand to unit [%s] " + "commandType [%s]", + aiInterface->getMyUnit(bestIndex) + ->getType() + ->getName() + .c_str(), + (defCt != NULL ? defCt->getName().c_str() : "n/a")); + aiInterface->printLog(4, szBuf); + } + aiInterface->giveCommand(bestIndex, defCt); + } + } else { + if (currentCommandCount == 0) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + defCt = NULL; + if (producersDefaultCommandType.find(bestIndex) != + producersDefaultCommandType.end()) { + // defCt = producersDefaultCommandType[bestIndex]; + int bestCommandTypeCount = + (int)producersDefaultCommandType[bestIndex].size(); + int bestCommandTypeIndex = + ai->getRandom()->randRange(0, bestCommandTypeCount - 1); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] bestCommandTypeIndex = %d, " + "bestCommandTypeCount = %d\n", + __FILE__, __FUNCTION__, __LINE__, bestCommandTypeIndex, + bestCommandTypeCount); + + defCt = producersDefaultCommandType[bestIndex] + [bestCommandTypeIndex]; + } + + if (ai->outputAIBehaviourToConsole()) + printf("mega #3 produceSpecific giveCommand to unit [%s] " + "commandType [%s]\n", + aiInterface->getMyUnit(bestIndex) + ->getType() + ->getName() + .c_str(), + (defCt != NULL ? defCt->getName().c_str() : "n/a")); + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "mega #3 produceSpecific giveCommand to unit [%s] " + "commandType [%s]", + aiInterface->getMyUnit(bestIndex) + ->getType() + ->getName() + .c_str(), + (defCt != NULL ? defCt->getName().c_str() : "n/a")); + aiInterface->printLog(4, szBuf); + } + + aiInterface->giveCommand(bestIndex, defCt); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + defCt = NULL; + if (producersDefaultCommandType.find(bestIndex) != + producersDefaultCommandType.end()) { + // defCt = producersDefaultCommandType[bestIndex]; + int bestCommandTypeCount = + (int)producersDefaultCommandType[bestIndex].size(); + int bestCommandTypeIndex = + ai->getRandom()->randRange(0, bestCommandTypeCount - 1); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] bestCommandTypeIndex = %d, " + "bestCommandTypeCount = %d\n", + __FILE__, __FUNCTION__, __LINE__, bestCommandTypeIndex, + bestCommandTypeCount); + + defCt = + producersDefaultCommandType[bestIndex][bestCommandTypeIndex]; + } + if (ai->outputAIBehaviourToConsole()) + printf("mega #4 produceSpecific giveCommand to unit [%s] " + "commandType [%s]\n", + aiInterface->getMyUnit(bestIndex) + ->getType() + ->getName() + .c_str(), + (defCt != NULL ? defCt->getName().c_str() : "n/a")); + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "mega #4 produceSpecific giveCommand to unit [%s] " + "commandType [%s]", + aiInterface->getMyUnit(bestIndex) + ->getType() + ->getName() + .c_str(), + (defCt != NULL ? defCt->getName().c_str() : "n/a")); + aiInterface->printLog(4, szBuf); + } + + aiInterface->giveCommand(bestIndex, defCt); + } + } + } else { + int pIndex = ai->getRandom()->randRange(0, (int)producers.size() - 1); + int producerIndex = producers[pIndex]; + defCt = NULL; + if (producersDefaultCommandType.find(producerIndex) != + producersDefaultCommandType.end()) { + // defCt = producersDefaultCommandType[producerIndex]; + int bestCommandTypeCount = + (int)producersDefaultCommandType[producerIndex].size(); + int bestCommandTypeIndex = + ai->getRandom()->randRange(0, bestCommandTypeCount - 1); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] bestCommandTypeIndex = %d, " + "bestCommandTypeCount = %d\n", + __FILE__, __FUNCTION__, __LINE__, bestCommandTypeIndex, + bestCommandTypeCount); + + defCt = + producersDefaultCommandType[producerIndex][bestCommandTypeIndex]; + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] producers.size() = %d, producerIndex = %d, " + "pIndex = %d, producersDefaultCommandType.size() = %d\n", + __FILE__, __FUNCTION__, __LINE__, producers.size(), producerIndex, + pIndex, producersDefaultCommandType.size()); + + if (ai->outputAIBehaviourToConsole()) + printf("produceSpecific giveCommand to unit [%s] commandType [%s]\n", + aiInterface->getMyUnit(producerIndex) + ->getType() + ->getName() + .c_str(), + (defCt != NULL ? defCt->getName().c_str() : "n/a")); + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "produceSpecific giveCommand to unit [%s] commandType [%s]", + aiInterface->getMyUnit(producerIndex) + ->getType() + ->getName() + .c_str(), + (defCt != NULL ? defCt->getName().c_str() : "(null)")); + aiInterface->printLog(4, szBuf); + } + aiInterface->giveCommand(producerIndex, defCt); + } + } + } } // ======================================== // class AiRuleBuild // ======================================== -AiRuleBuild::AiRuleBuild(Ai *ai): - AiRule(ai) -{ - buildTask= NULL; -} +AiRuleBuild::AiRuleBuild(Ai *ai) : AiRule(ai) { buildTask = NULL; } -bool AiRuleBuild::test(){ - const Task *task= ai->getTask(); +bool AiRuleBuild::test() { + const Task *task = ai->getTask(); - if(task==NULL || task->getClass()!=tcBuild){ - return false; - } + if (task == NULL || task->getClass() != tcBuild) { + return false; + } - buildTask= static_cast(task); - return true; + buildTask = static_cast(task); + return true; } - void AiRuleBuild::execute() { - if(buildTask!=NULL) { - if(ai->outputAIBehaviourToConsole()) printf("BUILD AiRuleBuild Unit Name[%s]\n",(buildTask->getUnitType() != NULL ? buildTask->getUnitType()->getName(false).c_str() : "null")); - - //generic build task, build random building that can be built - if(buildTask->getUnitType() == NULL) { - buildGeneric(buildTask); - } - //specific building task, build if possible, retry if not enough resources or not position - else { - buildSpecific(buildTask); - } - - //remove the task - ai->removeTask(buildTask); - } + if (buildTask != NULL) { + if (ai->outputAIBehaviourToConsole()) + printf("BUILD AiRuleBuild Unit Name[%s]\n", + (buildTask->getUnitType() != NULL + ? buildTask->getUnitType()->getName(false).c_str() + : "null")); + + // generic build task, build random building that can be built + if (buildTask->getUnitType() == NULL) { + buildGeneric(buildTask); + } + // specific building task, build if possible, retry if not enough resources + // or not position + else { + buildSpecific(buildTask); + } + + // remove the task + ai->removeTask(buildTask); + } } void AiRuleBuild::buildGeneric(const BuildTask *bt) { - //find buildings that can be built - AiInterface *aiInterface= ai->getAiInterface(); - - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"== START: buildGeneric for resource type [%s]",(bt->getResourceType() != NULL ? bt->getResourceType()->getName().c_str() : "null")); - aiInterface->printLog(4, szBuf); - } - - typedef vector UnitTypes; - UnitTypes buildings; - - if(bt->getResourceType() != NULL) { - if(aiInterface->getMyFactionType()->getAIBehaviorUnits(aibcResourceProducerUnits).size() > 0) { - const std::vector &unitList = aiInterface->getMyFactionType()->getAIBehaviorUnits(aibcResourceProducerUnits); - for(unsigned int i = 0; i < unitList.size(); ++i) { - const FactionType::PairPUnitTypeInt &priorityUnit = unitList[i]; - if(ai->getCountOfType(priorityUnit.first) < priorityUnit.second && - aiInterface->getMyFaction()->canCreateUnit(priorityUnit.first, true, false, false) == true) { - //if(ai->getRandom()->randRange(0, 1)==0) { - - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In buildGeneric for resource type [%s] aibcResourceProducerUnits = " MG_SIZE_T_SPECIFIER " priorityUnit.first: [%s]\n",bt->getResourceType()->getName().c_str(),unitList.size(),priorityUnit.first->getName().c_str()); - aiInterface->printLog(4, szBuf); - } - - ai->addTask(new BuildTask(priorityUnit.first)); - return; - //} - } - } - } - } - else { - if(aiInterface->getMyFactionType()->getAIBehaviorUnits(aibcBuildingUnits).size() > 0) { - const std::vector &unitList = aiInterface->getMyFactionType()->getAIBehaviorUnits(aibcBuildingUnits); - for(unsigned int i = 0; i < unitList.size(); ++i) { - const FactionType::PairPUnitTypeInt &priorityUnit = unitList[i]; - if(ai->getCountOfType(priorityUnit.first) < priorityUnit.second && - aiInterface->getMyFaction()->canCreateUnit(priorityUnit.first, true, false, false) == true) { - //if(ai->getRandom()->randRange(0, 1)==0) { - - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In buildGeneric for resource type [%s] aibcBuildingUnits = " MG_SIZE_T_SPECIFIER " priorityUnit.first: [%s]\n",bt->getResourceType()->getName().c_str(),unitList.size(),priorityUnit.first->getName().c_str()); - aiInterface->printLog(4, szBuf); - } - - ai->addTask(new BuildTask(priorityUnit.first)); - return; - //} - } - } - } - } - - //for each unit - for(int i=0; igetMyUnitCount(); ++i){ - - //for each command - const UnitType *ut= aiInterface->getMyUnit(i)->getType(); - for(int j=0; jgetCommandTypeCount(); ++j){ - const CommandType *ct= ut->getCommandType(j); - - //if the command is build - if(ct->getClass()==ccBuild){ - const BuildCommandType *bct= static_cast(ct); - - //for each building - for(int k=0; kgetBuildingCount(); ++k){ - const UnitType *building= bct->getBuilding(k); - if(aiInterface->reqsOk(bct) && aiInterface->reqsOk(building)){ - - //if any building, or produces resource - const ResourceType *rt= bt->getResourceType(); - const Resource *cost= building->getCost(rt); - if(rt==NULL || (cost!=NULL && cost->getAmount()<0)){ - if (find(buildings.begin(), buildings.end(), building) == buildings.end()) { - buildings.push_back(building); - } - } - } - } - } - } - } - - if(aiInterface->isLogLevelEnabled(4) == true) { - for(int i = 0; i < (int)buildings.size(); ++i) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In buildGeneric i = %d unit type: [%s]\n",i,buildings[i]->getName().c_str()); - aiInterface->printLog(4, szBuf); - } - } - - //add specific build task - buildBestBuilding(buildings); + // find buildings that can be built + AiInterface *aiInterface = ai->getAiInterface(); + + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "== START: buildGeneric for resource type [%s]", + (bt->getResourceType() != NULL + ? bt->getResourceType()->getName().c_str() + : "null")); + aiInterface->printLog(4, szBuf); + } + + typedef vector UnitTypes; + UnitTypes buildings; + + if (bt->getResourceType() != NULL) { + if (aiInterface->getMyFactionType() + ->getAIBehaviorUnits(aibcResourceProducerUnits) + .size() > 0) { + const std::vector &unitList = + aiInterface->getMyFactionType()->getAIBehaviorUnits( + aibcResourceProducerUnits); + for (unsigned int i = 0; i < unitList.size(); ++i) { + const FactionType::PairPUnitTypeInt &priorityUnit = unitList[i]; + if (ai->getCountOfType(priorityUnit.first) < priorityUnit.second && + aiInterface->getMyFaction()->canCreateUnit(priorityUnit.first, true, + false, false) == true) { + // if(ai->getRandom()->randRange(0, 1)==0) { + + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In buildGeneric for resource type [%s] " + "aibcResourceProducerUnits = " MG_SIZE_T_SPECIFIER + " priorityUnit.first: [%s]\n", + bt->getResourceType()->getName().c_str(), unitList.size(), + priorityUnit.first->getName().c_str()); + aiInterface->printLog(4, szBuf); + } + + ai->addTask(new BuildTask(priorityUnit.first)); + return; + //} + } + } + } + } else { + if (aiInterface->getMyFactionType() + ->getAIBehaviorUnits(aibcBuildingUnits) + .size() > 0) { + const std::vector &unitList = + aiInterface->getMyFactionType()->getAIBehaviorUnits( + aibcBuildingUnits); + for (unsigned int i = 0; i < unitList.size(); ++i) { + const FactionType::PairPUnitTypeInt &priorityUnit = unitList[i]; + if (ai->getCountOfType(priorityUnit.first) < priorityUnit.second && + aiInterface->getMyFaction()->canCreateUnit(priorityUnit.first, true, + false, false) == true) { + // if(ai->getRandom()->randRange(0, 1)==0) { + + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In buildGeneric for resource type [%s] aibcBuildingUnits " + "= " MG_SIZE_T_SPECIFIER " priorityUnit.first: [%s]\n", + bt->getResourceType()->getName().c_str(), unitList.size(), + priorityUnit.first->getName().c_str()); + aiInterface->printLog(4, szBuf); + } + + ai->addTask(new BuildTask(priorityUnit.first)); + return; + //} + } + } + } + } + + // for each unit + for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) { + + // for each command + const UnitType *ut = aiInterface->getMyUnit(i)->getType(); + for (int j = 0; j < ut->getCommandTypeCount(); ++j) { + const CommandType *ct = ut->getCommandType(j); + + // if the command is build + if (ct->getClass() == ccBuild) { + const BuildCommandType *bct = static_cast(ct); + + // for each building + for (int k = 0; k < bct->getBuildingCount(); ++k) { + const UnitType *building = bct->getBuilding(k); + if (aiInterface->reqsOk(bct) && aiInterface->reqsOk(building)) { + + // if any building, or produces resource + const ResourceType *rt = bt->getResourceType(); + const Resource *cost = building->getCost(rt); + if (rt == NULL || (cost != NULL && cost->getAmount() < 0)) { + if (find(buildings.begin(), buildings.end(), building) == + buildings.end()) { + buildings.push_back(building); + } + } + } + } + } + } + } + + if (aiInterface->isLogLevelEnabled(4) == true) { + for (int i = 0; i < (int)buildings.size(); ++i) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In buildGeneric i = %d unit type: [%s]\n", i, + buildings[i]->getName().c_str()); + aiInterface->printLog(4, szBuf); + } + } + + // add specific build task + buildBestBuilding(buildings); } -void AiRuleBuild::buildBestBuilding(const vector &buildings){ - - AiInterface *aiInterface= ai->getAiInterface(); - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"==> START buildBestBuilding buildings.size = " MG_SIZE_T_SPECIFIER "\n",buildings.size()); - aiInterface->printLog(4, szBuf); - } - - if(!buildings.empty()){ - - //build the least built building - bool buildingFound= false; - for(int i=0; i<10 && !buildingFound; ++i){ - - if(i>0){ - - //Defensive buildings have priority - for(int j=0; j < (int)buildings.size() && buildingFound == false; ++j){ - const UnitType *building= buildings[j]; - if(ai->getCountOfType(building)<=i+1 && isDefensive(building)) { - - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In buildBestBuilding defensive building unit type: [%s] i = %d j = %d\n",building->getName().c_str(),i,j); - aiInterface->printLog(4, szBuf); - } - - ai->addTask(new BuildTask(building)); - buildingFound= true; - } - } - - //Warrior producers next - for(unsigned int j=0; jgetCountOfType(building)<=i+1 && isWarriorProducer(building)) { - - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In buildBestBuilding warriorproducer building unit type: [%s] i = %d j = %u\n",building->getName().c_str(),i,j); - aiInterface->printLog(4, szBuf); - } - - ai->addTask(new BuildTask(building)); - buildingFound= true; - } - } - - //Resource producers next - for(unsigned int j=0; jgetCountOfType(building)<=i+1 && isResourceProducer(building)) { - - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In buildBestBuilding resourceproducer building unit type: [%s] i = %d j = %u\n",building->getName().c_str(),i,j); - aiInterface->printLog(4, szBuf); - } - - ai->addTask(new BuildTask(building)); - buildingFound= true; - } - } - } - - //Any building - for(unsigned int j=0; jgetCountOfType(building)<=i) { - - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In buildBestBuilding ANY building unit type: [%s] i = %d j = %u\n",building->getName().c_str(),i,j); - aiInterface->printLog(4, szBuf); - } - - ai->addTask(new BuildTask(building)); - buildingFound= true; - } - } - } - } - - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"==> END buildBestBuilding buildings.size = " MG_SIZE_T_SPECIFIER "\n",buildings.size()); - aiInterface->printLog(4, szBuf); - } +void AiRuleBuild::buildBestBuilding(const vector &buildings) { + + AiInterface *aiInterface = ai->getAiInterface(); + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "==> START buildBestBuilding buildings.size = " MG_SIZE_T_SPECIFIER + "\n", + buildings.size()); + aiInterface->printLog(4, szBuf); + } + + if (!buildings.empty()) { + + // build the least built building + bool buildingFound = false; + for (int i = 0; i < 10 && !buildingFound; ++i) { + + if (i > 0) { + + // Defensive buildings have priority + for (int j = 0; j < (int)buildings.size() && buildingFound == false; + ++j) { + const UnitType *building = buildings[j]; + if (ai->getCountOfType(building) <= i + 1 && isDefensive(building)) { + + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In buildBestBuilding defensive building unit type: " + "[%s] i = %d j = %d\n", + building->getName().c_str(), i, j); + aiInterface->printLog(4, szBuf); + } + + ai->addTask(new BuildTask(building)); + buildingFound = true; + } + } + + // Warrior producers next + for (unsigned int j = 0; j < buildings.size() && !buildingFound; ++j) { + const UnitType *building = buildings[j]; + if (ai->getCountOfType(building) <= i + 1 && + isWarriorProducer(building)) { + + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In buildBestBuilding warriorproducer building unit " + "type: [%s] i = %d j = %u\n", + building->getName().c_str(), i, j); + aiInterface->printLog(4, szBuf); + } + + ai->addTask(new BuildTask(building)); + buildingFound = true; + } + } + + // Resource producers next + for (unsigned int j = 0; j < buildings.size() && !buildingFound; ++j) { + const UnitType *building = buildings[j]; + if (ai->getCountOfType(building) <= i + 1 && + isResourceProducer(building)) { + + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In buildBestBuilding resourceproducer building unit " + "type: [%s] i = %d j = %u\n", + building->getName().c_str(), i, j); + aiInterface->printLog(4, szBuf); + } + + ai->addTask(new BuildTask(building)); + buildingFound = true; + } + } + } + + // Any building + for (unsigned int j = 0; j < buildings.size() && !buildingFound; ++j) { + const UnitType *building = buildings[j]; + if (ai->getCountOfType(building) <= i) { + + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In buildBestBuilding ANY building unit type: [%s] i = %d " + "j = %u\n", + building->getName().c_str(), i, j); + aiInterface->printLog(4, szBuf); + } + + ai->addTask(new BuildTask(building)); + buildingFound = true; + } + } + } + } + + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "==> END buildBestBuilding buildings.size = " MG_SIZE_T_SPECIFIER + "\n", + buildings.size()); + aiInterface->printLog(4, szBuf); + } } void AiRuleBuild::buildSpecific(const BuildTask *bt) { - AiInterface *aiInterface= ai->getAiInterface(); - - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"== START: buildSpecific for resource type [%s] bt->getUnitType() [%s]",(bt->getResourceType() != NULL ? bt->getResourceType()->getName().c_str() : "null"),(bt->getUnitType() != NULL ? bt->getUnitType()->getName(false).c_str() : "null")); - aiInterface->printLog(4, szBuf); - } - - //if reqs ok - if(aiInterface->reqsOk(bt->getUnitType())) { - - //retry if not enough resources - if(aiInterface->checkCosts(bt->getUnitType(),NULL) == false) { - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In buildSpecific for resource type [%s] checkcosts == false RETRYING",(bt->getResourceType() != NULL ? bt->getResourceType()->getName().c_str() : "null")); - aiInterface->printLog(4, szBuf); - } - - ai->retryTask(bt); - return; - } - - vector builders; - // Hold a list of units which can build - // then a list of build commandtypes for each unit - map > buildersDefaultCommandType; - const BuildCommandType *defBct= NULL; - - //for each unit - for(int i = 0; i < aiInterface->getMyUnitCount(); ++i) { - - //if the unit is not going to build - const Unit *u = aiInterface->getMyUnit(i); - if(u->anyCommand() == false || u->getCurrCommand()->getCommandType()->getClass() != ccBuild) { - - //for each command - const UnitType *ut= aiInterface->getMyUnit(i)->getType(); - for(int j = 0; j < ut->getCommandTypeCount(); ++j) { - const CommandType *ct= ut->getCommandType(j); - - //if the command is build - if(ct->getClass() == ccBuild) { - const BuildCommandType *bct= static_cast(ct); - - //for each building - for(int k = 0; k < bct->getBuildingCount(); ++k) { - const UnitType *building= bct->getBuilding(k); - - //if building match - if(bt->getUnitType() == building) { - if(aiInterface->reqsOk(bct)) { - builders.push_back(i); - buildersDefaultCommandType[i].push_back(bct); - //defBct= bct; - } - } - } - } - } - } - } - - //use random builder to build - if(builders.empty() == false) { - int bIndex = ai->getRandom()->randRange(0, (int)builders.size()-1); - int builderIndex= builders[bIndex]; - Vec2i pos; - Vec2i searchPos = bt->getForcePos()? bt->getPos(): ai->getRandomHomePosition(); - if(bt->getForcePos() == false) { - const int enemySightDistanceToAvoid = 18; - vector enemies; - ai->getAiInterface()->getWorld()->getUnitUpdater()->findEnemiesForCell(searchPos,bt->getUnitType()->getSize(),enemySightDistanceToAvoid,ai->getAiInterface()->getMyFaction(),enemies,true); - if(enemies.empty() == false) { - for(int i1 = 0; i1 < 25 && enemies.empty() == false; ++i1) { - for(int j1 = 0; j1 < 25 && enemies.empty() == false; ++j1) { - Vec2i tryPos = searchPos + Vec2i(i1,j1); - - const int spacing = 1; - if(ai->getAiInterface()->isFreeCells(tryPos - Vec2i(spacing), bt->getUnitType()->getSize() + spacing * 2, fLand)) { - enemies.clear(); - ai->getAiInterface()->getWorld()->getUnitUpdater()->findEnemiesForCell(tryPos,bt->getUnitType()->getSize(),enemySightDistanceToAvoid,ai->getAiInterface()->getMyFaction(),enemies,true); - if(enemies.empty() == true) { - searchPos = tryPos; - } - } - } - } - } - if(enemies.empty() == false) { - for(int i1 = -1; i1 >= -25 && enemies.empty() == false; --i1) { - for(int j1 = -1; j1 >= -25 && enemies.empty() == false; --j1) { - Vec2i tryPos = searchPos + Vec2i(i1,j1); - - const int spacing = 1; - if(ai->getAiInterface()->isFreeCells(tryPos - Vec2i(spacing), bt->getUnitType()->getSize() + spacing * 2, fLand)) { - enemies.clear(); - ai->getAiInterface()->getWorld()->getUnitUpdater()->findEnemiesForCell(tryPos,bt->getUnitType()->getSize(),enemySightDistanceToAvoid,ai->getAiInterface()->getMyFaction(),enemies,true); - if(enemies.empty() == true) { - searchPos = tryPos; - } - } - } - } - } - } - - //if free pos give command, else retry - if(ai->findPosForBuilding(bt->getUnitType(), searchPos, pos)) { - defBct = NULL; - if(buildersDefaultCommandType.find(builderIndex) != buildersDefaultCommandType.end()) { - //defBct = buildersDefaultCommandType[builderIndex]; - int bestCommandTypeCount = (int)buildersDefaultCommandType[builderIndex].size(); - int bestCommandTypeIndex = ai->getRandom()->randRange(0, bestCommandTypeCount-1); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] bestCommandTypeIndex = %d, bestCommandTypeCount = %d\n",__FILE__,__FUNCTION__,__LINE__,bestCommandTypeIndex,bestCommandTypeCount); - - defBct = buildersDefaultCommandType[builderIndex][bestCommandTypeIndex]; - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] builderIndex = %d, bIndex = %d, defBct = %p\n",__FILE__,__FUNCTION__,__LINE__,builderIndex,bIndex,defBct); - - aiInterface->giveCommand(builderIndex, defBct, pos, bt->getUnitType()); - } - else { - ai->retryTask(bt); - return; - } - } - } - else { - if(aiInterface->isLogLevelEnabled(4) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In buildSpecific for resource type [%s] reqsok == false",(bt->getResourceType() != NULL ? bt->getResourceType()->getName().c_str() : "null")); - aiInterface->printLog(4, szBuf); - } - - } -} + AiInterface *aiInterface = ai->getAiInterface(); + + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "== START: buildSpecific for resource type [%s] bt->getUnitType() [%s]", + (bt->getResourceType() != NULL + ? bt->getResourceType()->getName().c_str() + : "null"), + (bt->getUnitType() != NULL ? bt->getUnitType()->getName(false).c_str() + : "null")); + aiInterface->printLog(4, szBuf); + } + + // if reqs ok + if (aiInterface->reqsOk(bt->getUnitType())) { + + // retry if not enough resources + if (aiInterface->checkCosts(bt->getUnitType(), NULL) == false) { + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In buildSpecific for resource type [%s] checkcosts == false " + "RETRYING", + (bt->getResourceType() != NULL + ? bt->getResourceType()->getName().c_str() + : "null")); + aiInterface->printLog(4, szBuf); + } + + ai->retryTask(bt); + return; + } -bool AiRuleBuild::isDefensive(const UnitType *building){ - if(ai->outputAIBehaviourToConsole()) printf("BUILD isDefensive check for Unit Name[%s] result = %d\n",building->getName(false).c_str(),building->hasSkillClass(scAttack)); + vector builders; + // Hold a list of units which can build + // then a list of build commandtypes for each unit + map> buildersDefaultCommandType; + const BuildCommandType *defBct = NULL; + + // for each unit + for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) { + + // if the unit is not going to build + const Unit *u = aiInterface->getMyUnit(i); + if (u->anyCommand() == false || + u->getCurrCommand()->getCommandType()->getClass() != ccBuild) { + + // for each command + const UnitType *ut = aiInterface->getMyUnit(i)->getType(); + for (int j = 0; j < ut->getCommandTypeCount(); ++j) { + const CommandType *ct = ut->getCommandType(j); + + // if the command is build + if (ct->getClass() == ccBuild) { + const BuildCommandType *bct = + static_cast(ct); + + // for each building + for (int k = 0; k < bct->getBuildingCount(); ++k) { + const UnitType *building = bct->getBuilding(k); + + // if building match + if (bt->getUnitType() == building) { + if (aiInterface->reqsOk(bct)) { + builders.push_back(i); + buildersDefaultCommandType[i].push_back(bct); + // defBct= bct; + } + } + } + } + } + } + } - return building->hasSkillClass(scAttack); + // use random builder to build + if (builders.empty() == false) { + int bIndex = ai->getRandom()->randRange(0, (int)builders.size() - 1); + int builderIndex = builders[bIndex]; + Vec2i pos; + Vec2i searchPos = + bt->getForcePos() ? bt->getPos() : ai->getRandomHomePosition(); + if (bt->getForcePos() == false) { + const int enemySightDistanceToAvoid = 18; + vector enemies; + ai->getAiInterface()->getWorld()->getUnitUpdater()->findEnemiesForCell( + searchPos, bt->getUnitType()->getSize(), enemySightDistanceToAvoid, + ai->getAiInterface()->getMyFaction(), enemies, true); + if (enemies.empty() == false) { + for (int i1 = 0; i1 < 25 && enemies.empty() == false; ++i1) { + for (int j1 = 0; j1 < 25 && enemies.empty() == false; ++j1) { + Vec2i tryPos = searchPos + Vec2i(i1, j1); + + const int spacing = 1; + if (ai->getAiInterface()->isFreeCells( + tryPos - Vec2i(spacing), + bt->getUnitType()->getSize() + spacing * 2, fLand)) { + enemies.clear(); + ai->getAiInterface() + ->getWorld() + ->getUnitUpdater() + ->findEnemiesForCell(tryPos, bt->getUnitType()->getSize(), + enemySightDistanceToAvoid, + ai->getAiInterface()->getMyFaction(), + enemies, true); + if (enemies.empty() == true) { + searchPos = tryPos; + } + } + } + } + } + if (enemies.empty() == false) { + for (int i1 = -1; i1 >= -25 && enemies.empty() == false; --i1) { + for (int j1 = -1; j1 >= -25 && enemies.empty() == false; --j1) { + Vec2i tryPos = searchPos + Vec2i(i1, j1); + + const int spacing = 1; + if (ai->getAiInterface()->isFreeCells( + tryPos - Vec2i(spacing), + bt->getUnitType()->getSize() + spacing * 2, fLand)) { + enemies.clear(); + ai->getAiInterface() + ->getWorld() + ->getUnitUpdater() + ->findEnemiesForCell(tryPos, bt->getUnitType()->getSize(), + enemySightDistanceToAvoid, + ai->getAiInterface()->getMyFaction(), + enemies, true); + if (enemies.empty() == true) { + searchPos = tryPos; + } + } + } + } + } + } + + // if free pos give command, else retry + if (ai->findPosForBuilding(bt->getUnitType(), searchPos, pos)) { + defBct = NULL; + if (buildersDefaultCommandType.find(builderIndex) != + buildersDefaultCommandType.end()) { + // defBct = buildersDefaultCommandType[builderIndex]; + int bestCommandTypeCount = + (int)buildersDefaultCommandType[builderIndex].size(); + int bestCommandTypeIndex = + ai->getRandom()->randRange(0, bestCommandTypeCount - 1); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] bestCommandTypeIndex = %d, " + "bestCommandTypeCount = %d\n", + __FILE__, __FUNCTION__, __LINE__, bestCommandTypeIndex, + bestCommandTypeCount); + + defBct = + buildersDefaultCommandType[builderIndex][bestCommandTypeIndex]; + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] builderIndex = %d, " + "bIndex = %d, defBct = %p\n", + __FILE__, __FUNCTION__, __LINE__, + builderIndex, bIndex, defBct); + + aiInterface->giveCommand(builderIndex, defBct, pos, bt->getUnitType()); + } else { + ai->retryTask(bt); + return; + } + } + } else { + if (aiInterface->isLogLevelEnabled(4) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In buildSpecific for resource type [%s] reqsok == false", + (bt->getResourceType() != NULL + ? bt->getResourceType()->getName().c_str() + : "null")); + aiInterface->printLog(4, szBuf); + } + } } -bool AiRuleBuild::isResourceProducer(const UnitType *building){ - for(int i= 0; igetCostCount(); i++){ - if(building->getCost(i)->getAmount()<0){ - if(ai->outputAIBehaviourToConsole()) printf("BUILD isResourceProducer check for Unit Name[%s] result = true\n",building->getName(false).c_str()); - - return true; - } - } - if(ai->outputAIBehaviourToConsole()) printf("BUILD isResourceProducer check for Unit Name[%s] result = false\n",building->getName(false).c_str()); +bool AiRuleBuild::isDefensive(const UnitType *building) { + if (ai->outputAIBehaviourToConsole()) + printf("BUILD isDefensive check for Unit Name[%s] result = %d\n", + building->getName(false).c_str(), building->hasSkillClass(scAttack)); - return false; + return building->hasSkillClass(scAttack); } -bool AiRuleBuild::isWarriorProducer(const UnitType *building){ - for(int i= 0; i < building->getCommandTypeCount(); i++){ - const CommandType *ct= building->getCommandType(i); - if(ct->getClass() == ccProduce){ - const UnitType *ut= static_cast(ct)->getProducedUnit(); +bool AiRuleBuild::isResourceProducer(const UnitType *building) { + for (int i = 0; i < building->getCostCount(); i++) { + if (building->getCost(i)->getAmount() < 0) { + if (ai->outputAIBehaviourToConsole()) + printf( + "BUILD isResourceProducer check for Unit Name[%s] result = true\n", + building->getName(false).c_str()); - if(ut->isOfClass(ucWarrior)){ - if(ai->outputAIBehaviourToConsole()) printf("BUILD isWarriorProducer check for Unit Name[%s] result = true\n",building->getName(false).c_str()); + return true; + } + } + if (ai->outputAIBehaviourToConsole()) + printf("BUILD isResourceProducer check for Unit Name[%s] result = false\n", + building->getName(false).c_str()); - return true; - } - } - } - if(ai->outputAIBehaviourToConsole()) printf("BUILD isWarriorProducer check for Unit Name[%s] result = false\n",building->getName(false).c_str()); + return false; +} - return false; +bool AiRuleBuild::isWarriorProducer(const UnitType *building) { + for (int i = 0; i < building->getCommandTypeCount(); i++) { + const CommandType *ct = building->getCommandType(i); + if (ct->getClass() == ccProduce) { + const UnitType *ut = + static_cast(ct)->getProducedUnit(); + + if (ut->isOfClass(ucWarrior)) { + if (ai->outputAIBehaviourToConsole()) + printf( + "BUILD isWarriorProducer check for Unit Name[%s] result = true\n", + building->getName(false).c_str()); + + return true; + } + } + } + if (ai->outputAIBehaviourToConsole()) + printf("BUILD isWarriorProducer check for Unit Name[%s] result = false\n", + building->getName(false).c_str()); + + return false; } // ======================================== // class AiRuleUpgrade // ======================================== -AiRuleUpgrade::AiRuleUpgrade(Ai *ai): - AiRule(ai) -{ - upgradeTask= NULL; -} +AiRuleUpgrade::AiRuleUpgrade(Ai *ai) : AiRule(ai) { upgradeTask = NULL; } -bool AiRuleUpgrade::test(){ - const Task *task= ai->getTask(); +bool AiRuleUpgrade::test() { + const Task *task = ai->getTask(); - if(task==NULL || task->getClass()!=tcUpgrade){ - return false; - } + if (task == NULL || task->getClass() != tcUpgrade) { + return false; + } - upgradeTask= static_cast(task); - return true; + upgradeTask = static_cast(task); + return true; } -void AiRuleUpgrade::execute(){ +void AiRuleUpgrade::execute() { - //upgrade any upgrade - if(upgradeTask->getUpgradeType()==NULL){ - upgradeGeneric(upgradeTask); - } - //upgrade specific upgrade - else{ - upgradeSpecific(upgradeTask); - } + // upgrade any upgrade + if (upgradeTask->getUpgradeType() == NULL) { + upgradeGeneric(upgradeTask); + } + // upgrade specific upgrade + else { + upgradeSpecific(upgradeTask); + } - //remove the task - ai->removeTask(upgradeTask); + // remove the task + ai->removeTask(upgradeTask); } -void AiRuleUpgrade::upgradeGeneric(const UpgradeTask *upgt){ - - typedef vector UpgradeTypes; - AiInterface *aiInterface= ai->getAiInterface(); - - //find upgrades that can be upgraded - UpgradeTypes upgrades; - - if(aiInterface->getMyFactionType()->getAIBehaviorUpgrades().size() > 0) { - const std::vector &upgradeList = aiInterface->getMyFactionType()->getAIBehaviorUpgrades(); - for(unsigned int i = 0; i < upgradeList.size(); ++i) { - const UpgradeType* priorityUpgrade = upgradeList[i]; - - //for each upgrade, upgrade it if possible - for(int k = 0; k < aiInterface->getMyUnitCount(); ++k) { - - //for each command - const UnitType *ut= aiInterface->getMyUnit(k)->getType(); - for(int j = 0; j < ut->getCommandTypeCount(); ++j) { - const CommandType *ct= ut->getCommandType(j); - - //if the command is upgrade - if(ct->getClass() == ccUpgrade) { - const UpgradeCommandType *upgct= dynamic_cast(ct); - if(upgct != NULL) { - const UpgradeType *upgrade= upgct->getProducedUpgrade(); - if(upgrade == priorityUpgrade) { - if(aiInterface->reqsOk(upgct) == true && - aiInterface->getMyFaction()->getUpgradeManager()->isUpgradingOrUpgraded(priorityUpgrade) == false) { - //if(ai->getRandom()->randRange(0, 1)==0) { - ai->addTask(new UpgradeTask(priorityUpgrade)); - return; - //} - } - } - } - } - } - } - } - } - - //for each upgrade, upgrade it if possible - for(int i=0; igetMyUnitCount(); ++i){ - - //for each command - const UnitType *ut= aiInterface->getMyUnit(i)->getType(); - for(int j=0; jgetCommandTypeCount(); ++j){ - const CommandType *ct= ut->getCommandType(j); - - //if the command is upgrade - if(ct->getClass()==ccUpgrade){ - const UpgradeCommandType *upgct= static_cast(ct); - const UpgradeType *upgrade= upgct->getProducedUpgrade(); - if(aiInterface->reqsOk(upgct)){ - upgrades.push_back(upgrade); - } - } - } - } - - //add specific upgrade task - if(!upgrades.empty()){ - ai->addTask(new UpgradeTask(upgrades[ai->getRandom()->randRange(0, (int)upgrades.size()-1)])); - } -} - -void AiRuleUpgrade::upgradeSpecific(const UpgradeTask *upgt){ - - AiInterface *aiInterface= ai->getAiInterface(); - - //if reqs ok - if(aiInterface->reqsOk(upgt->getUpgradeType())){ +void AiRuleUpgrade::upgradeGeneric(const UpgradeTask *upgt) { + + typedef vector UpgradeTypes; + AiInterface *aiInterface = ai->getAiInterface(); + + // find upgrades that can be upgraded + UpgradeTypes upgrades; + + if (aiInterface->getMyFactionType()->getAIBehaviorUpgrades().size() > 0) { + const std::vector &upgradeList = + aiInterface->getMyFactionType()->getAIBehaviorUpgrades(); + for (unsigned int i = 0; i < upgradeList.size(); ++i) { + const UpgradeType *priorityUpgrade = upgradeList[i]; + + // for each upgrade, upgrade it if possible + for (int k = 0; k < aiInterface->getMyUnitCount(); ++k) { + + // for each command + const UnitType *ut = aiInterface->getMyUnit(k)->getType(); + for (int j = 0; j < ut->getCommandTypeCount(); ++j) { + const CommandType *ct = ut->getCommandType(j); + + // if the command is upgrade + if (ct->getClass() == ccUpgrade) { + const UpgradeCommandType *upgct = + dynamic_cast(ct); + if (upgct != NULL) { + const UpgradeType *upgrade = upgct->getProducedUpgrade(); + if (upgrade == priorityUpgrade) { + if (aiInterface->reqsOk(upgct) == true && + aiInterface->getMyFaction() + ->getUpgradeManager() + ->isUpgradingOrUpgraded(priorityUpgrade) == false) { + // if(ai->getRandom()->randRange(0, 1)==0) { + ai->addTask(new UpgradeTask(priorityUpgrade)); + return; + //} + } + } + } + } + } + } + } + } + + // for each upgrade, upgrade it if possible + for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) { + + // for each command + const UnitType *ut = aiInterface->getMyUnit(i)->getType(); + for (int j = 0; j < ut->getCommandTypeCount(); ++j) { + const CommandType *ct = ut->getCommandType(j); + + // if the command is upgrade + if (ct->getClass() == ccUpgrade) { + const UpgradeCommandType *upgct = + static_cast(ct); + const UpgradeType *upgrade = upgct->getProducedUpgrade(); + if (aiInterface->reqsOk(upgct)) { + upgrades.push_back(upgrade); + } + } + } + } - //if resources dont meet retry - if(!aiInterface->checkCosts(upgt->getUpgradeType(), NULL)) { - ai->retryTask(upgt); - return; - } + // add specific upgrade task + if (!upgrades.empty()) { + ai->addTask(new UpgradeTask( + upgrades[ai->getRandom()->randRange(0, (int)upgrades.size() - 1)])); + } +} - //for each unit - for(int i=0; igetMyUnitCount(); ++i){ +void AiRuleUpgrade::upgradeSpecific(const UpgradeTask *upgt) { - //for each command - const UnitType *ut= aiInterface->getMyUnit(i)->getType(); - for(int j=0; jgetCommandTypeCount(); ++j){ - const CommandType *ct= ut->getCommandType(j); + AiInterface *aiInterface = ai->getAiInterface(); - //if the command is upgrade - if(ct->getClass()==ccUpgrade){ - const UpgradeCommandType *uct= static_cast(ct); - const UpgradeType *producedUpgrade= uct->getProducedUpgrade(); + // if reqs ok + if (aiInterface->reqsOk(upgt->getUpgradeType())) { - //if upgrades match - if(producedUpgrade == upgt->getUpgradeType()){ - if(aiInterface->reqsOk(uct)){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - aiInterface->giveCommand(i, uct); - } - } - } - } - } + // if resources dont meet retry + if (!aiInterface->checkCosts(upgt->getUpgradeType(), NULL)) { + ai->retryTask(upgt); + return; + } - } + // for each unit + for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) { + + // for each command + const UnitType *ut = aiInterface->getMyUnit(i)->getType(); + for (int j = 0; j < ut->getCommandTypeCount(); ++j) { + const CommandType *ct = ut->getCommandType(j); + + // if the command is upgrade + if (ct->getClass() == ccUpgrade) { + const UpgradeCommandType *uct = + static_cast(ct); + const UpgradeType *producedUpgrade = uct->getProducedUpgrade(); + + // if upgrades match + if (producedUpgrade == upgt->getUpgradeType()) { + if (aiInterface->reqsOk(uct)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + aiInterface->giveCommand(i, uct); + } + } + } + } + } + } } // ======================================== // class AiRuleExpand // ======================================== -AiRuleExpand::AiRuleExpand(Ai *ai): - AiRule(ai) -{ - storeType= NULL; -} +AiRuleExpand::AiRuleExpand(Ai *ai) : AiRule(ai) { storeType = NULL; } bool AiRuleExpand::test() { - AiInterface *aiInterface = ai->getAiInterface(); - - int unitCount = aiInterface->getMyUnitCount(); - for(int i = 0; i < aiInterface->getTechTree()->getResourceTypeCount(); ++i) { - const ResourceType *rt = aiInterface->getTechTree()->getResourceType(i); - if(rt->getClass() == rcTech) { - bool factionUsesResourceType = aiInterface->factionUsesResourceType(aiInterface->getMyFactionType(), rt); - if(factionUsesResourceType == true) { - // If any resource sighted - if(aiInterface->getNearestSightedResource(rt, aiInterface->getHomeLocation(), expandPos, true)) { - int minDistance= INT_MAX; - storeType= NULL; - - //If there is no close store - for(int j=0; j < unitCount; ++j) { - const Unit *u= aiInterface->getMyUnit(j); - const UnitType *ut= u->getType(); - - // If this building is a store - if(ut->getStore(rt) > 0) { - storeType = ut; - int distance= static_cast (u->getPosNotThreadSafe().dist(expandPos)); - if(distance < minDistance) { - minDistance = distance; - } - } - } - - if(minDistance > expandDistance) { - return true; - } - } - else { - // send patrol to look for resource - ai->sendScoutPatrol(); - } - } - } - } - - return false; -} + AiInterface *aiInterface = ai->getAiInterface(); + + int unitCount = aiInterface->getMyUnitCount(); + for (int i = 0; i < aiInterface->getTechTree()->getResourceTypeCount(); ++i) { + const ResourceType *rt = aiInterface->getTechTree()->getResourceType(i); + if (rt->getClass() == rcTech) { + bool factionUsesResourceType = aiInterface->factionUsesResourceType( + aiInterface->getMyFactionType(), rt); + if (factionUsesResourceType == true) { + // If any resource sighted + if (aiInterface->getNearestSightedResource( + rt, aiInterface->getHomeLocation(), expandPos, true)) { + int minDistance = INT_MAX; + storeType = NULL; + + // If there is no close store + for (int j = 0; j < unitCount; ++j) { + const Unit *u = aiInterface->getMyUnit(j); + const UnitType *ut = u->getType(); + + // If this building is a store + if (ut->getStore(rt) > 0) { + storeType = ut; + int distance = + static_cast(u->getPosNotThreadSafe().dist(expandPos)); + if (distance < minDistance) { + minDistance = distance; + } + } + } + + if (minDistance > expandDistance) { + return true; + } + } else { + // send patrol to look for resource + ai->sendScoutPatrol(); + } + } + } + } -void AiRuleExpand::execute(){ - ai->addExpansion(expandPos); - ai->addPriorityTask(new BuildTask(storeType, expandPos)); + return false; } +void AiRuleExpand::execute() { + ai->addExpansion(expandPos); + ai->addPriorityTask(new BuildTask(storeType, expandPos)); +} // ======================================== // class AiRuleUnBlock // ======================================== -AiRuleUnBlock::AiRuleUnBlock(Ai *ai): - AiRule(ai) -{ +AiRuleUnBlock::AiRuleUnBlock(Ai *ai) : AiRule(ai) {} -} +bool AiRuleUnBlock::test() { return ai->haveBlockedUnits(); } -bool AiRuleUnBlock::test() { - return ai->haveBlockedUnits(); -} - -void AiRuleUnBlock::execute(){ - ai->unblockUnits(); -} +void AiRuleUnBlock::execute() { ai->unblockUnits(); } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/ai/ai_rule.h b/source/glest_game/ai/ai_rule.h index d212a51f5..62b28eae3 100644 --- a/source/glest_game/ai/ai_rule.h +++ b/source/glest_game/ai/ai_rule.h @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,20 +13,21 @@ #define _GLEST_GAME_AIRULE_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include -#include "vec.h" -#include "skill_type.h" #include "leak_dumper.h" +#include "skill_type.h" +#include "vec.h" +#include using std::string; using Shared::Graphics::Vec2i; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { class Ai; class AiInterface; @@ -38,314 +39,329 @@ class UpgradeTask; class ResourceType; // ===================================================== -// class AiRule +// class AiRule // -/// An action that the AI will perform periodically +/// An action that the AI will perform periodically /// if the test succeeds // ===================================================== -class AiRule{ +class AiRule { protected: - Ai *ai; + Ai *ai; public: - explicit AiRule(Ai *ai); - virtual ~AiRule() {} + explicit AiRule(Ai *ai); + virtual ~AiRule() {} - virtual int getTestInterval() const= 0; //in milliseconds - virtual string getName() const= 0; + virtual int getTestInterval() const = 0; // in milliseconds + virtual string getName() const = 0; - virtual bool test()= 0; - virtual void execute()= 0; + virtual bool test() = 0; + virtual void execute() = 0; }; // ===================================================== // class AiRuleWorkerHarvest // ===================================================== -class AiRuleWorkerHarvest: public AiRule{ +class AiRuleWorkerHarvest : public AiRule { private: - int stoppedWorkerIndex; + int stoppedWorkerIndex; public: - explicit AiRuleWorkerHarvest(Ai *ai); - - virtual int getTestInterval() const {return 2000;} - virtual string getName() const {return "Worker stopped => Order worker to harvest";} + explicit AiRuleWorkerHarvest(Ai *ai); - virtual bool test(); - virtual void execute(); + virtual int getTestInterval() const { return 2000; } + virtual string getName() const { + return "Worker stopped => Order worker to harvest"; + } + + virtual bool test(); + virtual void execute(); }; // ===================================================== // class AiRuleRefreshHarvester // ===================================================== -class AiRuleRefreshHarvester: public AiRule{ +class AiRuleRefreshHarvester : public AiRule { private: - int workerIndex; + int workerIndex; public: - explicit AiRuleRefreshHarvester(Ai *ai); - - virtual int getTestInterval() const {return 20000;} - virtual string getName() const {return "Worker reassigned to needed resource";} + explicit AiRuleRefreshHarvester(Ai *ai); + + virtual int getTestInterval() const { return 20000; } + virtual string getName() const { + return "Worker reassigned to needed resource"; + } - virtual bool test(); - virtual void execute(); + virtual bool test(); + virtual void execute(); }; // ===================================================== // class AiRuleScoutPatrol // ===================================================== -class AiRuleScoutPatrol: public AiRule{ +class AiRuleScoutPatrol : public AiRule { public: - explicit AiRuleScoutPatrol(Ai *ai); - - virtual int getTestInterval() const {return 10000;} - virtual string getName() const {return "Base is stable => Send scout patrol";} + explicit AiRuleScoutPatrol(Ai *ai); - virtual bool test(); - virtual void execute(); + virtual int getTestInterval() const { return 10000; } + virtual string getName() const { + return "Base is stable => Send scout patrol"; + } + + virtual bool test(); + virtual void execute(); }; // ===================================================== // class AiRuleRepair // ===================================================== -class AiRuleRepair: public AiRule{ +class AiRuleRepair : public AiRule { private: - int damagedUnitIndex; - bool damagedUnitIsCastle; + int damagedUnitIndex; + bool damagedUnitIsCastle; - int getMinUnitsToRepairCastle(); - double getMinCastleHpRatio() const; + int getMinUnitsToRepairCastle(); + double getMinCastleHpRatio() const; public: - explicit AiRuleRepair(Ai *ai); - - virtual int getTestInterval() const {return 10000;} - virtual string getName() const {return "Building Damaged => Repair";} + explicit AiRuleRepair(Ai *ai); + + virtual int getTestInterval() const { return 10000; } + virtual string getName() const { return "Building Damaged => Repair"; } - virtual bool test(); - virtual void execute(); + virtual bool test(); + virtual void execute(); }; // ===================================================== // class AiRuleReturnBase // ===================================================== -class AiRuleReturnBase: public AiRule{ +class AiRuleReturnBase : public AiRule { private: - int stoppedUnitIndex; + int stoppedUnitIndex; + public: - explicit AiRuleReturnBase(Ai *ai); - - virtual int getTestInterval() const {return 5000;} - virtual string getName() const {return "Stopped unit => Order return base";} + explicit AiRuleReturnBase(Ai *ai); + + virtual int getTestInterval() const { return 5000; } + virtual string getName() const { return "Stopped unit => Order return base"; } - virtual bool test(); - virtual void execute(); + virtual bool test(); + virtual void execute(); }; // ===================================================== // class AiRuleMassiveAttack // ===================================================== -class AiRuleMassiveAttack: public AiRule{ +class AiRuleMassiveAttack : public AiRule { private: - static const int baseRadius= 25; + static const int baseRadius = 25; private: - Vec2i attackPos; - Field field; - bool ultraAttack; + Vec2i attackPos; + Field field; + bool ultraAttack; public: - explicit AiRuleMassiveAttack(Ai *ai); - - virtual int getTestInterval() const {return 1000;} - virtual string getName() const {return "Unit under attack => Order massive attack";} + explicit AiRuleMassiveAttack(Ai *ai); - virtual bool test(); - virtual void execute(); + virtual int getTestInterval() const { return 1000; } + virtual string getName() const { + return "Unit under attack => Order massive attack"; + } + + virtual bool test(); + virtual void execute(); }; // ===================================================== // class AiRuleAddTasks // ===================================================== -class AiRuleAddTasks: public AiRule{ +class AiRuleAddTasks : public AiRule { public: - explicit AiRuleAddTasks(Ai *ai); - - virtual int getTestInterval() const {return 5000;} - virtual string getName() const {return "Tasks empty => Add tasks";} + explicit AiRuleAddTasks(Ai *ai); + + virtual int getTestInterval() const { return 5000; } + virtual string getName() const { return "Tasks empty => Add tasks"; } - virtual bool test(); - virtual void execute(); + virtual bool test(); + virtual void execute(); }; // ===================================================== // class AiRuleBuildOneFarm // ===================================================== -class AiRuleBuildOneFarm: public AiRule{ +class AiRuleBuildOneFarm : public AiRule { private: - const UnitType *farm; + const UnitType *farm; public: - explicit AiRuleBuildOneFarm(Ai *ai); + explicit AiRuleBuildOneFarm(Ai *ai); - virtual int getTestInterval() const {return 10000;} - virtual string getName() const {return "No farms => Build one";} + virtual int getTestInterval() const { return 10000; } + virtual string getName() const { return "No farms => Build one"; } - virtual bool test(); - virtual void execute(); + virtual bool test(); + virtual void execute(); }; // ===================================================== // class AiRuleProduceResourceProducer // ===================================================== -class AiRuleProduceResourceProducer: public AiRule{ +class AiRuleProduceResourceProducer : public AiRule { private: - static const int minStaticResources= 20; - static const int longInterval= 60000; - static const int shortInterval= 5000; - const ResourceType *rt; - int interval; - bool newResourceBehaviour; + static const int minStaticResources = 20; + static const int longInterval = 60000; + static const int shortInterval = 5000; + const ResourceType *rt; + int interval; + bool newResourceBehaviour; public: - explicit AiRuleProduceResourceProducer(Ai *ai); - - virtual int getTestInterval() const {return interval;} - virtual string getName() const {return "No resources => Build Resource Producer";} + explicit AiRuleProduceResourceProducer(Ai *ai); + + virtual int getTestInterval() const { return interval; } + virtual string getName() const { + return "No resources => Build Resource Producer"; + } - virtual bool test(); - virtual void execute(); + virtual bool test(); + virtual void execute(); }; // ===================================================== // class AiRuleProduce // ===================================================== -class AiRuleProduce: public AiRule{ +class AiRuleProduce : public AiRule { private: - const ProduceTask *produceTask; + const ProduceTask *produceTask; - typedef vector UnitTypes; - typedef vector UnitTypesGiveBack; - bool newResourceBehaviour; + typedef vector UnitTypes; + typedef vector UnitTypesGiveBack; + bool newResourceBehaviour; public: - explicit AiRuleProduce(Ai *ai); + explicit AiRuleProduce(Ai *ai); - virtual int getTestInterval() const {return 2000;} - virtual string getName() const {return "Performing produce task";} + virtual int getTestInterval() const { return 2000; } + virtual string getName() const { return "Performing produce task"; } - virtual bool test(); - virtual void execute(); + virtual bool test(); + virtual void execute(); private: - void produceGeneric(const ProduceTask *pt); - void produceGenericNew(const ProduceTask *pt); - void produceSpecific(const ProduceTask *pt); - bool canUnitTypeOfferResourceType(const UnitType *ut, const ResourceType *rt); - bool setAIProduceTaskForResourceType(const ProduceTask* pt, - AiInterface* aiInterface); - void addUnitTypeToCandidates(const UnitType* producedUnit, - UnitTypes& ableUnits, UnitTypesGiveBack& ableUnitsGiveBack, - bool unitCanGiveBackResource); + void produceGeneric(const ProduceTask *pt); + void produceGenericNew(const ProduceTask *pt); + void produceSpecific(const ProduceTask *pt); + bool canUnitTypeOfferResourceType(const UnitType *ut, const ResourceType *rt); + bool setAIProduceTaskForResourceType(const ProduceTask *pt, + AiInterface *aiInterface); + void addUnitTypeToCandidates(const UnitType *producedUnit, + UnitTypes &ableUnits, + UnitTypesGiveBack &ableUnitsGiveBack, + bool unitCanGiveBackResource); }; // ===================================================== // class AiRuleBuild // ===================================================== -class AiRuleBuild: public AiRule{ +class AiRuleBuild : public AiRule { private: - const BuildTask *buildTask; + const BuildTask *buildTask; public: - explicit AiRuleBuild(Ai *ai); + explicit AiRuleBuild(Ai *ai); - virtual int getTestInterval() const {return 2000;} - virtual string getName() const {return "Performing build task";} + virtual int getTestInterval() const { return 2000; } + virtual string getName() const { return "Performing build task"; } - virtual bool test(); - virtual void execute(); + virtual bool test(); + virtual void execute(); private: - void buildGeneric(const BuildTask *bt); - void buildSpecific(const BuildTask *bt); - void buildBestBuilding(const vector &buildings); + void buildGeneric(const BuildTask *bt); + void buildSpecific(const BuildTask *bt); + void buildBestBuilding(const vector &buildings); - bool isDefensive(const UnitType *building); - bool isResourceProducer(const UnitType *building); - bool isWarriorProducer(const UnitType *building); + bool isDefensive(const UnitType *building); + bool isResourceProducer(const UnitType *building); + bool isWarriorProducer(const UnitType *building); }; // ===================================================== // class AiRuleUpgrade // ===================================================== -class AiRuleUpgrade: public AiRule{ +class AiRuleUpgrade : public AiRule { private: - const UpgradeTask *upgradeTask; + const UpgradeTask *upgradeTask; public: - explicit AiRuleUpgrade(Ai *ai); + explicit AiRuleUpgrade(Ai *ai); - virtual int getTestInterval() const {return 2000;} - virtual string getName() const {return "Performing upgrade task";} + virtual int getTestInterval() const { return 2000; } + virtual string getName() const { return "Performing upgrade task"; } - virtual bool test(); - virtual void execute(); + virtual bool test(); + virtual void execute(); private: - void upgradeSpecific(const UpgradeTask *upgt); - void upgradeGeneric(const UpgradeTask *upgt); + void upgradeSpecific(const UpgradeTask *upgt); + void upgradeGeneric(const UpgradeTask *upgt); }; // ===================================================== // class AiRuleExpand // ===================================================== -class AiRuleExpand: public AiRule{ +class AiRuleExpand : public AiRule { private: - static const int expandDistance= 30; + static const int expandDistance = 30; private: - Vec2i expandPos; - const UnitType *storeType; + Vec2i expandPos; + const UnitType *storeType; public: - explicit AiRuleExpand(Ai *ai); + explicit AiRuleExpand(Ai *ai); - virtual int getTestInterval() const {return 30000;} - virtual string getName() const {return "Expanding";} + virtual int getTestInterval() const { return 30000; } + virtual string getName() const { return "Expanding"; } - virtual bool test(); - virtual void execute(); + virtual bool test(); + virtual void execute(); }; // ===================================================== // class AiRuleUnBlock // ===================================================== -class AiRuleUnBlock: public AiRule{ +class AiRuleUnBlock : public AiRule { public: - explicit AiRuleUnBlock(Ai *ai); + explicit AiRuleUnBlock(Ai *ai); - virtual int getTestInterval() const {return 3000;} - virtual string getName() const {return "Blocked Units => Move surrounding units";} + virtual int getTestInterval() const { return 3000; } + virtual string getName() const { + return "Blocked Units => Move surrounding units"; + } - virtual bool test(); - virtual void execute(); + virtual bool test(); + virtual void execute(); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/ai/path_finder.cpp b/source/glest_game/ai/path_finder.cpp index 936eb3f2a..b8cb7e678 100644 --- a/source/glest_game/ai/path_finder.cpp +++ b/source/glest_game/ai/path_finder.cpp @@ -2,9 +2,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -12,15 +12,15 @@ #include +#include "command.h" #include "config.h" +#include "faction.h" +#include "leak_dumper.h" #include "map.h" -#include "unit.h" -#include "unit_type.h" #include "platform_common.h" -#include "command.h" -#include "faction.h" #include "randomgen.h" -#include "leak_dumper.h" +#include "unit.h" +#include "unit_type.h" using namespace std; using namespace Shared::Graphics; @@ -28,1126 +28,1434 @@ using namespace Shared::Util; using namespace Shared::PlatformCommon; using Shared::Util::RandomGen; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class PathFinder // ===================================================== -// ===================== PUBLIC ======================== +// ===================== PUBLIC ======================== -const int PathFinder::maxFreeSearchRadius = 10; +const int PathFinder::maxFreeSearchRadius = 10; -int PathFinder::pathFindNodesAbsoluteMax = 900; -int PathFinder::pathFindNodesMax = 2000; -const int PathFinder::pathFindBailoutRadius = 20; -const int PathFinder::pathFindExtendRefreshForNodeCount = 25; -const int PathFinder::pathFindExtendRefreshNodeCountMin = 40; -const int PathFinder::pathFindExtendRefreshNodeCountMax = 40; +int PathFinder::pathFindNodesAbsoluteMax = 900; +int PathFinder::pathFindNodesMax = 2000; +const int PathFinder::pathFindBailoutRadius = 20; +const int PathFinder::pathFindExtendRefreshForNodeCount = 25; +const int PathFinder::pathFindExtendRefreshNodeCountMin = 40; +const int PathFinder::pathFindExtendRefreshNodeCountMax = 40; PathFinder::PathFinder() { - minorDebugPathfinder = false; - map=NULL; + minorDebugPathfinder = false; + map = NULL; } int PathFinder::getPathFindExtendRefreshNodeCount(FactionState &faction) { - //int refreshNodeCount = faction.random.randRange(PathFinder::pathFindExtendRefreshNodeCountMin,PathFinder::pathFindExtendRefreshNodeCountMax); - //return refreshNodeCount; - return PathFinder::pathFindExtendRefreshNodeCountMin; + // int refreshNodeCount = + // faction.random.randRange(PathFinder::pathFindExtendRefreshNodeCountMin,PathFinder::pathFindExtendRefreshNodeCountMax); + // return refreshNodeCount; + return PathFinder::pathFindExtendRefreshNodeCountMin; } PathFinder::PathFinder(const Map *map) { - minorDebugPathfinder = false; + minorDebugPathfinder = false; - map=NULL; - init(map); + map = NULL; + init(map); } void PathFinder::init(const Map *map) { - for(int factionIndex = 0; factionIndex < GameConstants::maxPlayers; ++factionIndex) { - FactionState &faction = factions.getFactionState(factionIndex); - - faction.nodePool.resize(pathFindNodesAbsoluteMax); - faction.useMaxNodeCount = PathFinder::pathFindNodesMax; - } - this->map= map; + for (int factionIndex = 0; factionIndex < GameConstants::maxPlayers; + ++factionIndex) { + FactionState &faction = factions.getFactionState(factionIndex); + + faction.nodePool.resize(pathFindNodesAbsoluteMax); + faction.useMaxNodeCount = PathFinder::pathFindNodesMax; + } + this->map = map; } void PathFinder::init() { - minorDebugPathfinder = false; - map=NULL; + minorDebugPathfinder = false; + map = NULL; } PathFinder::~PathFinder() { - for(int factionIndex = 0; factionIndex < GameConstants::maxPlayers; ++factionIndex) { - FactionState &faction = factions.getFactionState(factionIndex); - - faction.nodePool.clear(); - } - factions.clear(); - map=NULL; + for (int factionIndex = 0; factionIndex < GameConstants::maxPlayers; + ++factionIndex) { + FactionState &faction = factions.getFactionState(factionIndex); + + faction.nodePool.clear(); + } + factions.clear(); + map = NULL; } void PathFinder::clearCaches() { - for(int factionIndex = 0; factionIndex < GameConstants::maxPlayers; ++factionIndex) { - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - FactionState &faction = factions.getFactionState(factionIndex); - MutexSafeWrapper safeMutex(faction.getMutexPreCache(),mutexOwnerId); - - faction.precachedTravelState.clear(); - faction.precachedPath.clear(); - } + for (int factionIndex = 0; factionIndex < GameConstants::maxPlayers; + ++factionIndex) { + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + FactionState &faction = factions.getFactionState(factionIndex); + MutexSafeWrapper safeMutex(faction.getMutexPreCache(), mutexOwnerId); + + faction.precachedTravelState.clear(); + faction.precachedPath.clear(); + } } void PathFinder::clearUnitPrecache(Unit *unit) { - if(unit != NULL && factions.size() > unit->getFactionIndex()) { - int factionIndex = unit->getFactionIndex(); - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - FactionState &faction = factions.getFactionState(factionIndex); - MutexSafeWrapper safeMutex(faction.getMutexPreCache(),mutexOwnerId); - - faction.precachedTravelState[unit->getId()] = tsImpossible; - faction.precachedPath[unit->getId()].clear(); - } + if (unit != NULL && factions.size() > unit->getFactionIndex()) { + int factionIndex = unit->getFactionIndex(); + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + FactionState &faction = factions.getFactionState(factionIndex); + MutexSafeWrapper safeMutex(faction.getMutexPreCache(), mutexOwnerId); + + faction.precachedTravelState[unit->getId()] = tsImpossible; + faction.precachedPath[unit->getId()].clear(); + } } void PathFinder::removeUnitPrecache(Unit *unit) { - if(unit != NULL && factions.size() > unit->getFactionIndex()) { - int factionIndex = unit->getFactionIndex(); - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - FactionState &faction = factions.getFactionState(factionIndex); - MutexSafeWrapper safeMutex(faction.getMutexPreCache(),mutexOwnerId); - - if(faction.precachedTravelState.find(unit->getId()) != faction.precachedTravelState.end()) { - faction.precachedTravelState.erase(unit->getId()); - } - if(faction.precachedPath.find(unit->getId()) != faction.precachedPath.end()) { - faction.precachedPath.erase(unit->getId()); - } - } + if (unit != NULL && factions.size() > unit->getFactionIndex()) { + int factionIndex = unit->getFactionIndex(); + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + FactionState &faction = factions.getFactionState(factionIndex); + MutexSafeWrapper safeMutex(faction.getMutexPreCache(), mutexOwnerId); + + if (faction.precachedTravelState.find(unit->getId()) != + faction.precachedTravelState.end()) { + faction.precachedTravelState.erase(unit->getId()); + } + if (faction.precachedPath.find(unit->getId()) != + faction.precachedPath.end()) { + faction.precachedPath.erase(unit->getId()); + } + } } -TravelState PathFinder::findPath(Unit *unit, const Vec2i &finalPos, bool *wasStuck, int frameIndex) { - TravelState ts = tsImpossible; - - try { - - int factionIndex = unit->getFactionIndex(); - FactionState &faction = factions.getFactionState(factionIndex); - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexPrecache(faction.getMutexPreCache(),mutexOwnerId); - - if(map == NULL) { - throw megaglest_runtime_error("map == NULL"); - } - - unit->setCurrentPathFinderDesiredFinalPos(finalPos); - - - if(frameIndex >= 0) { - clearUnitPrecache(unit); - } - if(unit->getFaction()->canUnitsPathfind() == true) { - unit->getFaction()->addUnitToPathfindingList(unit->getId()); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"canUnitsPathfind() == false"); - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - - return tsBlocked; - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"[findPath] unit->getPos() [%s] finalPos [%s]", - unit->getPos().getString().c_str(),finalPos.getString().c_str()); - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - - //route cache - if(finalPos == unit->getPos()) { - if(frameIndex < 0) { - //if arrived - unit->setCurrSkill(scStop); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Unit finalPos [%s] == unit->getPos() [%s]",finalPos.getString().c_str(),unit->getPos().getString().c_str()); - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugPathFinder).enabled == true) { - string commandDesc = "none"; - Command *command= unit->getCurrCommand(); - if(command != NULL && command->getCommandType() != NULL) { - commandDesc = command->getCommandType()->toString(false); - } - char szBuf[8096]=""; - snprintf(szBuf,8096,"State: arrived#1 at pos: %s, command [%s]",finalPos.getString().c_str(),commandDesc.c_str()); - unit->setCurrentUnitTitle(szBuf); - } - - return tsArrived; - } - - UnitPathInterface *path= unit->getPath(); - if(path->isEmpty() == false) { - UnitPathBasic *basic_path = dynamic_cast(path); - if(basic_path != NULL) { - //route cache - Vec2i pos= basic_path->pop(frameIndex < 0); - - if(map->canMove(unit, unit->getPos(), pos)) { - if(frameIndex < 0) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && - SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax).enabled == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"#1 map->canMove to pos [%s] from [%s]",pos.getString().c_str(),unit->getPos().getString().c_str()); - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - - unit->setTargetPos(pos,frameIndex < 0); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && - SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax).enabled == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"#2 map->canMove to pos [%s] from [%s]",pos.getString().c_str(),unit->getPos().getString().c_str()); - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - - } - - return tsMoving; - } - } - else if(dynamic_cast(path) != NULL) { - UnitPath *advPath = dynamic_cast(path); - //route cache - Vec2i pos= advPath->peek(); - if(map->canMove(unit, unit->getPos(), pos)) { - if(frameIndex < 0) { - advPath->pop(); - unit->setTargetPos(pos,frameIndex < 0); - } - - return tsMoving; - } - } - else { - throw megaglest_runtime_error("unsupported or missing path finder detected!"); - } - } - - if(path->isStuck() == true && - (unit->getLastStuckPos() == finalPos || path->getBlockCount() > 500) && - unit->isLastStuckFrameWithinCurrentFrameTolerance(frameIndex >= 0) == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"path->isStuck() == true unit->getLastStuckPos() [%s] finalPos [%s] path->getBlockCount() [%d]",unit->getLastStuckPos().getString().c_str(),finalPos.getString().c_str(),path->getBlockCount()); - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - - return tsBlocked; - } - - //route cache miss - int maxNodeCount=-1; - if(unit->getUsePathfinderExtendedMaxNodes() == true) { - - maxNodeCount= PathFinder::pathFindNodesAbsoluteMax; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"maxNodeCount: %d",maxNodeCount); - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - } - - bool minorDebugPathfinderPerformance = false; - Chrono chrono; - if(minorDebugPathfinderPerformance) chrono.start(); - - uint32 searched_node_count = 0; - minorDebugPathfinder = false; - if(minorDebugPathfinder) printf("Legacy Pathfind Unit [%d - %s] from = %s to = %s frameIndex = %d\n",unit->getId(),unit->getType()->getName(false).c_str(),unit->getPos().getString().c_str(),finalPos.getString().c_str(),frameIndex); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"calling aStar()"); - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - - ts = aStar(unit, finalPos, false, frameIndex, maxNodeCount,&searched_node_count); - //post actions - switch(ts) { - case tsBlocked: - case tsArrived: - // The unit is stuck (not only blocked but unable to go anywhere for a while) - // We will try to bail out of the immediate area - if( ts == tsBlocked && unit->getInBailOutAttempt() == false && - path->isStuck() == true) { - - if(minorDebugPathfinder) printf("Pathfind Unit [%d - %s] START BAILOUT ATTEMPT frameIndex = %d\n",unit->getId(),unit->getType()->getName(false).c_str(),frameIndex); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"[attempting to BAIL OUT] finalPos [%s] ts [%d]", - finalPos.getString().c_str(),ts); - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - - if(wasStuck != NULL) { - *wasStuck = true; - } - unit->setInBailOutAttempt(true); - - bool unitImmediatelyBlocked = false; - - // First check if unit currently blocked all around them, if so don't try to pathfind - const Vec2i unitPos = unit->getPos(); - int failureCount = 0; - int cellCount = 0; - - for(int i = -1; i <= 1; ++i) { - for(int j = -1; j <= 1; ++j) { - Vec2i pos = unitPos + Vec2i(i, j); - if(pos != unitPos) { - bool canUnitMoveToCell = map->aproxCanMove(unit, unitPos, pos); - if(canUnitMoveToCell == false) { - failureCount++; - } - cellCount++; - } - } - } - unitImmediatelyBlocked = (failureCount == cellCount); - if(unitImmediatelyBlocked == false) { - - int factionIndex = unit->getFactionIndex(); - FactionState &faction = factions.getFactionState(factionIndex); - - //if(Thread::isCurrentThreadMainThread() == false) { - // throw megaglest_runtime_error("#2 Invalid access to FactionState random from outside main thread current id = " + - // intToStr(Thread::getCurrentThreadId()) + " main = " + intToStr(Thread::getMainThreadId())); - //} - - int tryRadius = faction.random.randRange(1,2); - //int tryRadius = faction.random.IRandomX(1,2); - //int tryRadius = 1; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In astar bailout() tryRadius %d",tryRadius); - - if(frameIndex >= 0) { - unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); - } - else { - unit->logSynchData(__FILE__,__LINE__,szBuf); - } - } - - // Try to bail out up to PathFinder::pathFindBailoutRadius cells away - if(tryRadius == 2) { - for(int bailoutX = -PathFinder::pathFindBailoutRadius; bailoutX <= PathFinder::pathFindBailoutRadius && ts == tsBlocked; ++bailoutX) { - for(int bailoutY = -PathFinder::pathFindBailoutRadius; bailoutY <= PathFinder::pathFindBailoutRadius && ts == tsBlocked; ++bailoutY) { - const Vec2i newFinalPos = finalPos + Vec2i(bailoutX,bailoutY); - bool canUnitMove = map->canMove(unit, unit->getPos(), newFinalPos); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"[attempting to BAIL OUT] finalPos [%s] newFinalPos [%s] ts [%d] canUnitMove [%d]", - finalPos.getString().c_str(),newFinalPos.getString().c_str(),ts,canUnitMove); - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - - if(canUnitMove) { - - int maxBailoutNodeCount = (PathFinder::pathFindBailoutRadius * 2); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"calling aStar()"); - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - - ts= aStar(unit, newFinalPos, true, frameIndex, maxBailoutNodeCount,&searched_node_count); - } - } - } - } - else { - for(int bailoutX = PathFinder::pathFindBailoutRadius; bailoutX >= -PathFinder::pathFindBailoutRadius && ts == tsBlocked; --bailoutX) { - for(int bailoutY = PathFinder::pathFindBailoutRadius; bailoutY >= -PathFinder::pathFindBailoutRadius && ts == tsBlocked; --bailoutY) { - const Vec2i newFinalPos = finalPos + Vec2i(bailoutX,bailoutY); - bool canUnitMove = map->canMove(unit, unit->getPos(), newFinalPos); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"[attempting to BAIL OUT] finalPos [%s] newFinalPos [%s] ts [%d] canUnitMove [%d]", - finalPos.getString().c_str(),newFinalPos.getString().c_str(),ts,canUnitMove); - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - - if(canUnitMove) { - int maxBailoutNodeCount = (PathFinder::pathFindBailoutRadius * 2); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"calling aStar()"); - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - - ts= aStar(unit, newFinalPos, true, frameIndex, maxBailoutNodeCount,&searched_node_count); - } - } - } - } - } - unit->setInBailOutAttempt(false); - - if(ts == tsBlocked) { - unit->setLastStuckFrameToCurrentFrame(); - unit->setLastStuckPos(finalPos); - } - } - if(ts == tsArrived || ts == tsBlocked) { - if(frameIndex < 0) { - unit->setCurrSkill(scStop); - } - } - break; - case tsMoving: - { - if(dynamic_cast(path) != NULL) { - UnitPathBasic *basicPath = dynamic_cast(path); - Vec2i pos; - if(frameIndex < 0 && basicPath != NULL) { - pos = basicPath->pop(frameIndex < 0); - } - else { - - if(faction.precachedPath[unit->getId()].size() <= 0) { - throw megaglest_runtime_error("factions[unit->getFactionIndex()].precachedPath[unit->getId()].size() <= 0!"); - } - - pos = faction.precachedPath[unit->getId()][0]; - - } - - if(map->canMove(unit, unit->getPos(), pos)) { - if(frameIndex < 0) { - unit->setTargetPos(pos,frameIndex < 0); - } - } - else { - if(frameIndex < 0) { - unit->setCurrSkill(scStop); - } - - if(minorDebugPathfinderPerformance && chrono.getMillis() >= 1) printf("Unit [%d - %s] astar #2 took [%lld] msecs, ts = %d searched_node_count = %d.\n",unit->getId(),unit->getType()->getName(false).c_str(),(long long int)chrono.getMillis(),ts,searched_node_count); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"tsBlocked"); - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - - return tsBlocked; - } - } - else if(dynamic_cast(path) != NULL) { - UnitPath *advPath = dynamic_cast(path); - Vec2i pos= advPath->peek(); - if(map->canMove(unit, unit->getPos(), pos)) { - if(frameIndex < 0) { - advPath->pop(); - unit->setTargetPos(pos,frameIndex < 0); - } - } - else { - if(frameIndex < 0) { - unit->setCurrSkill(scStop); - } - - if(minorDebugPathfinder) printf("Pathfind Unit [%d - %s] INT BAILOUT ATTEMPT BLOCKED frameIndex = %d\n",unit->getId(),unit->getType()->getName(false).c_str(),frameIndex); - - if(minorDebugPathfinderPerformance && chrono.getMillis() >= 1) printf("Unit [%d - %s] astar #3 took [%lld] msecs, ts = %d searched_node_count = %d.\n",unit->getId(),unit->getType()->getName(false).c_str(),(long long int)chrono.getMillis(),ts,searched_node_count); - return tsBlocked; - } - } - else { - throw megaglest_runtime_error("unsupported or missing path finder detected!"); - } - } - break; - - default: - break; - } - if(minorDebugPathfinderPerformance && chrono.getMillis() >= 1) printf("Unit [%d - %s] astar took [%lld] msecs, ts = %d searched_node_count = %d.\n",unit->getId(),unit->getType()->getName(false).c_str(),(long long int)chrono.getMillis(),ts,searched_node_count); - - } - catch(const exception &ex) { - //setRunningStatus(false); - - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - throw megaglest_runtime_error(ex.what()); - } - catch(...) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] UNKNOWN error\n",__FILE__,__FUNCTION__,__LINE__); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - throw megaglest_runtime_error(szBuf); - } - - return ts; +TravelState PathFinder::findPath(Unit *unit, const Vec2i &finalPos, + bool *wasStuck, int frameIndex) { + TravelState ts = tsImpossible; + + try { + + int factionIndex = unit->getFactionIndex(); + FactionState &faction = factions.getFactionState(factionIndex); + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexPrecache(faction.getMutexPreCache(), + mutexOwnerId); + + if (map == NULL) { + throw megaglest_runtime_error("map == NULL"); + } + + unit->setCurrentPathFinderDesiredFinalPos(finalPos); + + if (frameIndex >= 0) { + clearUnitPrecache(unit); + } + if (unit->getFaction()->canUnitsPathfind() == true) { + unit->getFaction()->addUnitToPathfindingList(unit->getId()); + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + frameIndex < 0) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "canUnitsPathfind() == false"); + unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__, szBuf); + } + + return tsBlocked; + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + frameIndex < 0) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "[findPath] unit->getPos() [%s] finalPos [%s]", + unit->getPos().getString().c_str(), + finalPos.getString().c_str()); + unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__, szBuf); + } + + // route cache + if (finalPos == unit->getPos()) { + if (frameIndex < 0) { + // if arrived + unit->setCurrSkill(scStop); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "Unit finalPos [%s] == unit->getPos() [%s]", + finalPos.getString().c_str(), + unit->getPos().getString().c_str()); + unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__, szBuf); + } + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugPathFinder) + .enabled == true) { + string commandDesc = "none"; + Command *command = unit->getCurrCommand(); + if (command != NULL && command->getCommandType() != NULL) { + commandDesc = command->getCommandType()->toString(false); + } + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "State: arrived#1 at pos: %s, command [%s]", + finalPos.getString().c_str(), commandDesc.c_str()); + unit->setCurrentUnitTitle(szBuf); + } + + return tsArrived; + } + + UnitPathInterface *path = unit->getPath(); + if (path->isEmpty() == false) { + UnitPathBasic *basic_path = dynamic_cast(path); + if (basic_path != NULL) { + // route cache + Vec2i pos = basic_path->pop(frameIndex < 0); + + if (map->canMove(unit, unit->getPos(), pos)) { + if (frameIndex < 0) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + SystemFlags::getSystemSettingType( + SystemFlags::debugWorldSynchMax) + .enabled == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "#1 map->canMove to pos [%s] from [%s]", + pos.getString().c_str(), + unit->getPos().getString().c_str()); + unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__, szBuf); + } + + unit->setTargetPos(pos, frameIndex < 0); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + SystemFlags::getSystemSettingType( + SystemFlags::debugWorldSynchMax) + .enabled == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "#2 map->canMove to pos [%s] from [%s]", + pos.getString().c_str(), + unit->getPos().getString().c_str()); + unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__, szBuf); + } + } + + return tsMoving; + } + } else if (dynamic_cast(path) != NULL) { + UnitPath *advPath = dynamic_cast(path); + // route cache + Vec2i pos = advPath->peek(); + if (map->canMove(unit, unit->getPos(), pos)) { + if (frameIndex < 0) { + advPath->pop(); + unit->setTargetPos(pos, frameIndex < 0); + } + + return tsMoving; + } + } else { + throw megaglest_runtime_error( + "unsupported or missing path finder detected!"); + } + } + + if (path->isStuck() == true && + (unit->getLastStuckPos() == finalPos || path->getBlockCount() > 500) && + unit->isLastStuckFrameWithinCurrentFrameTolerance(frameIndex >= 0) == + true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + frameIndex < 0) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "path->isStuck() == true unit->getLastStuckPos() [%s] " + "finalPos [%s] path->getBlockCount() [%d]", + unit->getLastStuckPos().getString().c_str(), + finalPos.getString().c_str(), path->getBlockCount()); + unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__, szBuf); + } + + return tsBlocked; + } + + // route cache miss + int maxNodeCount = -1; + if (unit->getUsePathfinderExtendedMaxNodes() == true) { + + maxNodeCount = PathFinder::pathFindNodesAbsoluteMax; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + frameIndex < 0) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "maxNodeCount: %d", maxNodeCount); + unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__, szBuf); + } + } + + bool minorDebugPathfinderPerformance = false; + Chrono chrono; + if (minorDebugPathfinderPerformance) + chrono.start(); + + uint32 searched_node_count = 0; + minorDebugPathfinder = false; + if (minorDebugPathfinder) + printf( + "Legacy Pathfind Unit [%d - %s] from = %s to = %s frameIndex = %d\n", + unit->getId(), unit->getType()->getName(false).c_str(), + unit->getPos().getString().c_str(), finalPos.getString().c_str(), + frameIndex); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + frameIndex < 0) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "calling aStar()"); + unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__, szBuf); + } + + ts = aStar(unit, finalPos, false, frameIndex, maxNodeCount, + &searched_node_count); + // post actions + switch (ts) { + case tsBlocked: + case tsArrived: + // The unit is stuck (not only blocked but unable to go anywhere for a + // while) We will try to bail out of the immediate area + if (ts == tsBlocked && unit->getInBailOutAttempt() == false && + path->isStuck() == true) { + + if (minorDebugPathfinder) + printf( + "Pathfind Unit [%d - %s] START BAILOUT ATTEMPT frameIndex = %d\n", + unit->getId(), unit->getType()->getName(false).c_str(), + frameIndex); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + frameIndex < 0) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "[attempting to BAIL OUT] finalPos [%s] ts [%d]", + finalPos.getString().c_str(), ts); + unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__, szBuf); + } + + if (wasStuck != NULL) { + *wasStuck = true; + } + unit->setInBailOutAttempt(true); + + bool unitImmediatelyBlocked = false; + + // First check if unit currently blocked all around them, if so don't + // try to pathfind + const Vec2i unitPos = unit->getPos(); + int failureCount = 0; + int cellCount = 0; + + for (int i = -1; i <= 1; ++i) { + for (int j = -1; j <= 1; ++j) { + Vec2i pos = unitPos + Vec2i(i, j); + if (pos != unitPos) { + bool canUnitMoveToCell = map->aproxCanMove(unit, unitPos, pos); + if (canUnitMoveToCell == false) { + failureCount++; + } + cellCount++; + } + } + } + unitImmediatelyBlocked = (failureCount == cellCount); + if (unitImmediatelyBlocked == false) { + + int factionIndex = unit->getFactionIndex(); + FactionState &faction = factions.getFactionState(factionIndex); + + // if(Thread::isCurrentThreadMainThread() == false) { + // throw megaglest_runtime_error("#2 Invalid access to FactionState + // random from outside main thread current id = " + + // intToStr(Thread::getCurrentThreadId()) + " main = " + //+ intToStr(Thread::getMainThreadId())); + // } + + int tryRadius = faction.random.randRange(1, 2); + // int tryRadius = faction.random.IRandomX(1,2); + // int tryRadius = 1; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In astar bailout() tryRadius %d", tryRadius); + + if (frameIndex >= 0) { + unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf); + } else { + unit->logSynchData(__FILE__, __LINE__, szBuf); + } + } + + // Try to bail out up to PathFinder::pathFindBailoutRadius cells away + if (tryRadius == 2) { + for (int bailoutX = -PathFinder::pathFindBailoutRadius; + bailoutX <= PathFinder::pathFindBailoutRadius && + ts == tsBlocked; + ++bailoutX) { + for (int bailoutY = -PathFinder::pathFindBailoutRadius; + bailoutY <= PathFinder::pathFindBailoutRadius && + ts == tsBlocked; + ++bailoutY) { + const Vec2i newFinalPos = finalPos + Vec2i(bailoutX, bailoutY); + bool canUnitMove = + map->canMove(unit, unit->getPos(), newFinalPos); + + if (SystemFlags::getSystemSettingType( + SystemFlags::debugWorldSynch) + .enabled == true && + frameIndex < 0) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "[attempting to BAIL OUT] finalPos [%s] newFinalPos " + "[%s] ts [%d] canUnitMove [%d]", + finalPos.getString().c_str(), + newFinalPos.getString().c_str(), ts, canUnitMove); + unit->logSynchData( + extractFileFromDirectoryPath(__FILE__).c_str(), __LINE__, + szBuf); + } + + if (canUnitMove) { + + int maxBailoutNodeCount = + (PathFinder::pathFindBailoutRadius * 2); + + if (SystemFlags::getSystemSettingType( + SystemFlags::debugWorldSynch) + .enabled == true && + frameIndex < 0) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "calling aStar()"); + unit->logSynchData( + extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__, szBuf); + } + + ts = aStar(unit, newFinalPos, true, frameIndex, + maxBailoutNodeCount, &searched_node_count); + } + } + } + } else { + for (int bailoutX = PathFinder::pathFindBailoutRadius; + bailoutX >= -PathFinder::pathFindBailoutRadius && + ts == tsBlocked; + --bailoutX) { + for (int bailoutY = PathFinder::pathFindBailoutRadius; + bailoutY >= -PathFinder::pathFindBailoutRadius && + ts == tsBlocked; + --bailoutY) { + const Vec2i newFinalPos = finalPos + Vec2i(bailoutX, bailoutY); + bool canUnitMove = + map->canMove(unit, unit->getPos(), newFinalPos); + + if (SystemFlags::getSystemSettingType( + SystemFlags::debugWorldSynch) + .enabled == true && + frameIndex < 0) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "[attempting to BAIL OUT] finalPos [%s] newFinalPos " + "[%s] ts [%d] canUnitMove [%d]", + finalPos.getString().c_str(), + newFinalPos.getString().c_str(), ts, canUnitMove); + unit->logSynchData( + extractFileFromDirectoryPath(__FILE__).c_str(), __LINE__, + szBuf); + } + + if (canUnitMove) { + int maxBailoutNodeCount = + (PathFinder::pathFindBailoutRadius * 2); + + if (SystemFlags::getSystemSettingType( + SystemFlags::debugWorldSynch) + .enabled == true && + frameIndex < 0) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "calling aStar()"); + unit->logSynchData( + extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__, szBuf); + } + + ts = aStar(unit, newFinalPos, true, frameIndex, + maxBailoutNodeCount, &searched_node_count); + } + } + } + } + } + unit->setInBailOutAttempt(false); + + if (ts == tsBlocked) { + unit->setLastStuckFrameToCurrentFrame(); + unit->setLastStuckPos(finalPos); + } + } + if (ts == tsArrived || ts == tsBlocked) { + if (frameIndex < 0) { + unit->setCurrSkill(scStop); + } + } + break; + case tsMoving: { + if (dynamic_cast(path) != NULL) { + UnitPathBasic *basicPath = dynamic_cast(path); + Vec2i pos; + if (frameIndex < 0 && basicPath != NULL) { + pos = basicPath->pop(frameIndex < 0); + } else { + + if (faction.precachedPath[unit->getId()].size() <= 0) { + throw megaglest_runtime_error( + "factions[unit->getFactionIndex()].precachedPath[unit->getId()]" + ".size() <= 0!"); + } + + pos = faction.precachedPath[unit->getId()][0]; + } + + if (map->canMove(unit, unit->getPos(), pos)) { + if (frameIndex < 0) { + unit->setTargetPos(pos, frameIndex < 0); + } + } else { + if (frameIndex < 0) { + unit->setCurrSkill(scStop); + } + + if (minorDebugPathfinderPerformance && chrono.getMillis() >= 1) + printf("Unit [%d - %s] astar #2 took [%lld] msecs, ts = %d " + "searched_node_count = %d.\n", + unit->getId(), unit->getType()->getName(false).c_str(), + (long long int)chrono.getMillis(), ts, searched_node_count); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + frameIndex < 0) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "tsBlocked"); + unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__, szBuf); + } + + return tsBlocked; + } + } else if (dynamic_cast(path) != NULL) { + UnitPath *advPath = dynamic_cast(path); + Vec2i pos = advPath->peek(); + if (map->canMove(unit, unit->getPos(), pos)) { + if (frameIndex < 0) { + advPath->pop(); + unit->setTargetPos(pos, frameIndex < 0); + } + } else { + if (frameIndex < 0) { + unit->setCurrSkill(scStop); + } + + if (minorDebugPathfinder) + printf("Pathfind Unit [%d - %s] INT BAILOUT ATTEMPT BLOCKED " + "frameIndex = %d\n", + unit->getId(), unit->getType()->getName(false).c_str(), + frameIndex); + + if (minorDebugPathfinderPerformance && chrono.getMillis() >= 1) + printf("Unit [%d - %s] astar #3 took [%lld] msecs, ts = %d " + "searched_node_count = %d.\n", + unit->getId(), unit->getType()->getName(false).c_str(), + (long long int)chrono.getMillis(), ts, searched_node_count); + return tsBlocked; + } + } else { + throw megaglest_runtime_error( + "unsupported or missing path finder detected!"); + } + } break; + + default: + break; + } + if (minorDebugPathfinderPerformance && chrono.getMillis() >= 1) + printf("Unit [%d - %s] astar took [%lld] msecs, ts = %d " + "searched_node_count = %d.\n", + unit->getId(), unit->getType()->getName(false).c_str(), + (long long int)chrono.getMillis(), ts, searched_node_count); + + } catch (const exception &ex) { + // setRunningStatus(false); + + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", __FILE__, + __FUNCTION__, __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + throw megaglest_runtime_error(ex.what()); + } catch (...) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] UNKNOWN error\n", __FILE__, + __FUNCTION__, __LINE__); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + throw megaglest_runtime_error(szBuf); + } + + return ts; } -// ==================== PRIVATE ==================== - -//route a unit using A* algorithm -TravelState PathFinder::aStar(Unit *unit, const Vec2i &targetPos, bool inBailout, - int frameIndex, int maxNodeCount, uint32 *searched_node_count) { - TravelState ts = tsImpossible; - - try { - - int unitFactionIndex = unit->getFactionIndex(); - int factionIndex = unit->getFactionIndex(); - FactionState &faction = factions.getFactionState(factionIndex); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex >= 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In aStar()"); - unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); - } +// ==================== PRIVATE ==================== - Chrono chrono; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); +// route a unit using A* algorithm +TravelState PathFinder::aStar(Unit *unit, const Vec2i &targetPos, + bool inBailout, int frameIndex, int maxNodeCount, + uint32 *searched_node_count) { + TravelState ts = tsImpossible; + + try { - if(map == NULL) { - throw megaglest_runtime_error("map == NULL"); - } + int unitFactionIndex = unit->getFactionIndex(); + int factionIndex = unit->getFactionIndex(); + FactionState &faction = factions.getFactionState(factionIndex); + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + frameIndex >= 0) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In aStar()"); + unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf); + } - if(maxNodeCount < 0) { - - int factionIndex = unit->getFactionIndex(); - FactionState &faction = factions.getFactionState(factionIndex); - - maxNodeCount = faction.useMaxNodeCount; - } - - if(maxNodeCount >= 1 && unit->getPathfindFailedConsecutiveFrameCount() >= 3) { - maxNodeCount = 200; - } - - UnitPathInterface *path= unit->getPath(); - - faction.nodePoolCount= 0; - faction.openNodesList.clear(); - faction.openPosList.clear(); - faction.closedNodesList.clear(); - - // check the pre-cache to see if we can re-use a cached path - if(frameIndex < 0) { - - bool foundPrecacheTravelState = (faction.precachedTravelState.find(unit->getId()) != faction.precachedTravelState.end()); - if(foundPrecacheTravelState == true) { - -// if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) { -// char szBuf[8096]=""; -// snprintf(szBuf,8096,"factions[unitFactionIndex].precachedTravelState[unit->getId()]: %d",faction.precachedTravelState[unit->getId()]); -// unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); -// } - - bool foundPrecacheTravelStateIsMoving = (faction.precachedTravelState[unit->getId()] == tsMoving); - if(foundPrecacheTravelStateIsMoving == true) { - bool canMoveToCells = true; - - Vec2i lastPos = unit->getPos(); - - int unitPrecachePathSize = (int)faction.precachedPath[unit->getId()].size(); - - for(int i=0; i < unitPrecachePathSize; i++) { - - Vec2i nodePos = faction.precachedPath[unit->getId()][i]; - - if(map->isInside(nodePos) == false || map->isInsideSurface(map->toSurfCoords(nodePos)) == false) { - throw megaglest_runtime_error("Pathfinder invalid node path position = " + nodePos.getString() + " i = " + intToStr(i)); - } - - if(i < unit->getPathFindRefreshCellCount() || - (unitPrecachePathSize >= pathFindExtendRefreshForNodeCount && - i < getPathFindExtendRefreshNodeCount(faction))) { - - if(canUnitMoveSoon(unit, lastPos, nodePos) == false) { - canMoveToCells = false; - break; - } - lastPos = nodePos; - } - else { - break; - } - } - - if(canMoveToCells == true) { - path->clear(); - //UnitPathBasic *basicPathFinder = dynamic_cast(path); - - int unitPrecachePathSize = (int)faction.precachedPath[unit->getId()].size(); - - for(int i=0; i < unitPrecachePathSize; i++) { - - Vec2i nodePos = faction.precachedPath[unit->getId()][i]; - - if(map->isInside(nodePos) == false || map->isInsideSurface(map->toSurfCoords(nodePos)) == false) { - throw megaglest_runtime_error("Pathfinder invalid node path position = " + nodePos.getString() + " i = " + intToStr(i)); - } - - //if(i < pathFindRefresh || - if(i < unit->getPathFindRefreshCellCount() || - (unitPrecachePathSize >= pathFindExtendRefreshForNodeCount && - i < getPathFindExtendRefreshNodeCount(faction))) { - path->add(nodePos); - } - } - unit->setUsePathfinderExtendedMaxNodes(false); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"return factions[unitFactionIndex].precachedTravelState[unit->getId()];"); - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - - return faction.precachedTravelState[unit->getId()]; - } - else { - clearUnitPrecache(unit); - } - } - else { - - bool foundPrecacheTravelStateIsBlocked = (faction.precachedTravelState[unit->getId()] == tsBlocked); - - if(foundPrecacheTravelStateIsBlocked == true) { - path->incBlockCount(); - unit->setUsePathfinderExtendedMaxNodes(false); - -// if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) { -// char szBuf[8096]=""; -// snprintf(szBuf,8096,"return factions[unitFactionIndex].precachedTravelState[unit->getId()];"); -// unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); -// } - - return faction.precachedTravelState[unit->getId()]; - } - } - } - } - else { - clearUnitPrecache(unit); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"[clearUnitPrecache]"); - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - } - - const Vec2i unitPos = unit->getPos(); - const Vec2i finalPos= computeNearestFreePos(unit, targetPos); - - float dist = unitPos.dist(finalPos); - - faction.useMaxNodeCount = PathFinder::pathFindNodesMax; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled == true && chrono.getMillis() > 4) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - - //path find algorithm - - //a) push starting pos into openNodes - Node *firstNode= newNode(faction,maxNodeCount); - if(firstNode == NULL) { - throw megaglest_runtime_error("firstNode == NULL"); - } - - firstNode->next= NULL; - firstNode->prev= NULL; - firstNode->pos= unitPos; - firstNode->heuristic= heuristic(unitPos, finalPos); - firstNode->exploredCell= true; - if(faction.openNodesList.find(firstNode->heuristic) == faction.openNodesList.end()) { - faction.openNodesList[firstNode->heuristic].clear(); - } - faction.openNodesList[firstNode->heuristic].push_back(firstNode); - faction.openPosList[firstNode->pos] = true; - - //b) loop - bool pathFound = true; - bool nodeLimitReached = false; - Node *node = NULL; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled == true && chrono.getMillis() > 4) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - - // First check if unit currently blocked all around them, if so don't try to pathfind - if(inBailout == false && unitPos != finalPos) { - int failureCount = 0; - int cellCount = 0; - - for(int i = -1; i <= 1; ++i) { - for(int j = -1; j <= 1; ++j) { - Vec2i pos = unitPos + Vec2i(i, j); - if(pos != unitPos) { - bool canUnitMoveToCell = canUnitMoveSoon(unit, unitPos, pos); - if(canUnitMoveToCell == false) { - failureCount++; - } - cellCount++; - } - } - } - nodeLimitReached = (failureCount == cellCount); - pathFound = !nodeLimitReached; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"nodeLimitReached: %d failureCount: %d cellCount: %d",nodeLimitReached,failureCount,cellCount); - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled == true && chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] **Check if dest blocked, distance for unit [%d - %s] from [%s] to [%s] is %.2f took msecs: %lld nodeLimitReached = %d, failureCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,unit->getId(),unit->getFullName(false).c_str(), unitPos.getString().c_str(), finalPos.getString().c_str(), dist,(long long int)chrono.getMillis(),nodeLimitReached,failureCount); - - if(nodeLimitReached == false) { - // First check if final destination blocked - failureCount = 0; - cellCount = 0; - - for(int i = -1; i <= 1; ++i) { - for(int j = -1; j <= 1; ++j) { - Vec2i pos = finalPos + Vec2i(i, j); - if(pos != finalPos) { - bool canUnitMoveToCell = canUnitMoveSoon(unit, pos, finalPos); - if(canUnitMoveToCell == false) { - failureCount++; - } - cellCount++; - } - } - } - nodeLimitReached = (failureCount == cellCount); - pathFound = !nodeLimitReached; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"nodeLimitReached: %d failureCount: %d cellCount: %d",nodeLimitReached,failureCount,cellCount); - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled == true && chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] **Check if dest blocked, distance for unit [%d - %s] from [%s] to [%s] is %.2f took msecs: %lld nodeLimitReached = %d, failureCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,unit->getId(),unit->getFullName(false).c_str(), unitPos.getString().c_str(), finalPos.getString().c_str(), dist,(long long int)chrono.getMillis(),nodeLimitReached,failureCount); - } - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"inBailout: %d unitPos: [%s] finalPos [%s]",inBailout,unitPos.getString().c_str(), finalPos.getString().c_str()); - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - } - // - - // START - std::map ,bool> canAddNode; - std::map closedNodes; - std::map cameFrom; - cameFrom[unitPos] = Vec2i(-1,-1); - - // Do the a-star base pathfind work if required - int whileLoopCount = 0; - if(nodeLimitReached == false) { - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Calling doAStarPathSearch nodeLimitReached: %d whileLoopCount: %d unitFactionIndex: %d pathFound: %d finalPos [%s] maxNodeCount: %d frameIndex: %d",nodeLimitReached, whileLoopCount, unitFactionIndex, - pathFound, finalPos.getString().c_str(), maxNodeCount,frameIndex); - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - - doAStarPathSearch(nodeLimitReached, whileLoopCount, unitFactionIndex, - pathFound, node, finalPos, - closedNodes, cameFrom, canAddNode, unit, maxNodeCount,frameIndex); - - if(searched_node_count != NULL) { - *searched_node_count = whileLoopCount; - } - - // Now see if the unit is eligible for pathfind max nodes boost? - if(nodeLimitReached == true) { - unit->incrementPathfindFailedConsecutiveFrameCount(); - } - else { - unit->resetPathfindFailedConsecutiveFrameCount(); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Calling doAStarPathSearch nodeLimitReached: %d whileLoopCount: %d unitFactionIndex: %d pathFound: %d finalPos [%s] maxNodeCount: %d pathFindNodesAbsoluteMax: %d frameIndex: %d",nodeLimitReached, whileLoopCount, unitFactionIndex, - pathFound, finalPos.getString().c_str(), maxNodeCount,pathFindNodesAbsoluteMax,frameIndex); - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - - if(nodeLimitReached == true && maxNodeCount != pathFindNodesAbsoluteMax) { - if(unit->isLastPathfindFailedFrameWithinCurrentFrameTolerance() == true) { - if(frameIndex < 0) { - unit->setLastPathfindFailedFrameToCurrentFrame(); - unit->setLastPathfindFailedPos(finalPos); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"calling aStar()"); - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - - return aStar(unit, targetPos, false, frameIndex, pathFindNodesAbsoluteMax); - } - } - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"nodeLimitReached: %d",nodeLimitReached); - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - } - - - Node *lastNode= node; - - //if consumed all nodes find best node (to avoid strange behaviour) - if(nodeLimitReached == true) { - - if(faction.closedNodesList.empty() == false) { - float bestHeuristic = truncateDecimal(faction.closedNodesList.begin()->first,6); - if(lastNode != NULL && bestHeuristic < lastNode->heuristic) { - lastNode= faction.closedNodesList.begin()->second.front(); - } - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled == true && chrono.getMillis() > 4) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - - //check results of path finding - ts = tsImpossible; - if(pathFound == false || lastNode == firstNode) { - if(minorDebugPathfinder) printf("Legacy Pathfind Unit [%d - %s] NOT FOUND PATH count = %d frameIndex = %d\n",unit->getId(),unit->getType()->getName().c_str(),whileLoopCount,frameIndex); - - //blocked - if(SystemFlags::getSystemSettingType(SystemFlags::debugPathFinder).enabled == true) { - string commandDesc = "none"; - Command *command= unit->getCurrCommand(); - if(command != NULL && command->getCommandType() != NULL) { - commandDesc = command->getCommandType()->toString(false); - } - - std::pair lastHarvest = unit->getLastHarvestResourceTarget(); - - char szBuf[8096]=""; - snprintf(szBuf,8096,"State: blocked, cmd [%s] pos: [%s], dest pos: [%s], lastHarvest = [%s - %d], reason A= %d, B= %d, C= %d, D= %d, E= %d, F = %d",commandDesc.c_str(),unit->getPos().getString().c_str(), targetPos.getString().c_str(),lastHarvest.first.getString().c_str(),lastHarvest.second, pathFound,(lastNode == firstNode),path->getBlockCount(), path->isBlocked(), nodeLimitReached,path->isStuck()); - unit->setCurrentUnitTitle(szBuf); - } - - if(frameIndex < 0) { - unit->setUsePathfinderExtendedMaxNodes(false); - } - - ts= tsBlocked; - if(frameIndex < 0) { - path->incBlockCount(); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled == true && chrono.getMillis() > 4) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - } - else { - if(minorDebugPathfinder) printf("Legacy Pathfind Unit [%d - %s] FOUND PATH count = %d frameIndex = %d\n",unit->getId(),unit->getType()->getName().c_str(),whileLoopCount,frameIndex); - //on the way - ts= tsMoving; - - //build next pointers - Node *currNode= lastNode; - while(currNode->prev != NULL) { - currNode->prev->next= currNode; - currNode= currNode->prev; - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled == true && chrono.getMillis() > 4) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - - if(frameIndex < 0) { - if(maxNodeCount == pathFindNodesAbsoluteMax) { - unit->setUsePathfinderExtendedMaxNodes(true); - } - else { - unit->setUsePathfinderExtendedMaxNodes(false); - } - } - - //store path - if(frameIndex < 0) { - path->clear(); - } - - //UnitPathBasic *basicPathFinder = dynamic_cast(path); - - currNode= firstNode; - - for(int i=0; currNode->next != NULL; currNode= currNode->next, i++) { - Vec2i nodePos = currNode->next->pos; - if(map->isInside(nodePos) == false || map->isInsideSurface(map->toSurfCoords(nodePos)) == false) { - throw megaglest_runtime_error("Pathfinder invalid node path position = " + nodePos.getString() + " i = " + intToStr(i)); - } - - if(minorDebugPathfinder) printf("nodePos [%s]\n",nodePos.getString().c_str()); - - if(frameIndex >= 0) { - faction.precachedPath[unit->getId()].push_back(nodePos); - } - else { - if(i < unit->getPathFindRefreshCellCount() || - (whileLoopCount >= pathFindExtendRefreshForNodeCount && - i < getPathFindExtendRefreshNodeCount(faction))) { - path->add(nodePos); - } - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled == true && chrono.getMillis() > 4) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && - SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax).enabled == true) { - char szBuf[8096]=""; - - string pathToTake = ""; - if(frameIndex < 0) { - vector pathQueue = path->getQueue(); - for(unsigned int index = 0; index < pathQueue.size(); ++index) { - Vec2i &pos = pathQueue[index]; - if(pathToTake != "") { - pathToTake += ", "; - } - pathToTake += pos.getString(); - } - } - else { - for(unsigned int index = 0; index < faction.precachedPath[unit->getId()].size(); ++index) { - Vec2i &pos = faction.precachedPath[unit->getId()][index]; - if(pathToTake != "") { - pathToTake += ", "; - } - pathToTake += pos.getString(); - } - } - snprintf(szBuf,8096,"Path for unit to take = %s",pathToTake.c_str()); - if(frameIndex < 0) { - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - else { - unit->logSynchDataThreaded(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPathFinder).enabled == true) { - string commandDesc = "none"; - Command *command= unit->getCurrCommand(); - if(command != NULL && command->getCommandType() != NULL) { - commandDesc = command->getCommandType()->toString(false); - } - - char szBuf[8096]=""; - snprintf(szBuf,8096,"State: moving, cmd [%s] pos: %s dest pos: %s, Queue= %d",commandDesc.c_str(),unit->getPos().getString().c_str(), targetPos.getString().c_str(),path->getQueueCount()); - unit->setCurrentUnitTitle(szBuf); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled == true && chrono.getMillis() > 4) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - } - - - faction.openNodesList.clear(); - faction.openPosList.clear(); - faction.closedNodesList.clear(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled == true && chrono.getMillis() > 4) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d took msecs: %lld --------------------------- [END OF METHOD] ---------------------------\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - - if(frameIndex >= 0) { - - FactionState &faction = factions.getFactionState(factionIndex); - faction.precachedTravelState[unit->getId()] = ts; - } - else { - if(SystemFlags::VERBOSE_MODE_ENABLED && chrono.getMillis() >= 5) printf("In [%s::%s Line: %d] astar took [%lld] msecs, ts = %d.\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,(long long int)chrono.getMillis(),ts); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"return ts: %d",ts); - unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); - } - - } - catch(const exception &ex) { - - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - throw megaglest_runtime_error(ex.what()); - } - catch(...) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] UNKNOWN error\n",__FILE__,__FUNCTION__,__LINE__); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - throw megaglest_runtime_error(szBuf); - } - - return ts; + Chrono chrono; + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled) + chrono.start(); + + if (map == NULL) { + throw megaglest_runtime_error("map == NULL"); + } + + if (maxNodeCount < 0) { + + int factionIndex = unit->getFactionIndex(); + FactionState &faction = factions.getFactionState(factionIndex); + + maxNodeCount = faction.useMaxNodeCount; + } + + if (maxNodeCount >= 1 && + unit->getPathfindFailedConsecutiveFrameCount() >= 3) { + maxNodeCount = 200; + } + + UnitPathInterface *path = unit->getPath(); + + faction.nodePoolCount = 0; + faction.openNodesList.clear(); + faction.openPosList.clear(); + faction.closedNodesList.clear(); + + // check the pre-cache to see if we can re-use a cached path + if (frameIndex < 0) { + + bool foundPrecacheTravelState = + (faction.precachedTravelState.find(unit->getId()) != + faction.precachedTravelState.end()); + if (foundPrecacheTravelState == true) { + + // if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled + //== true && frameIndex < 0) { char + //szBuf[8096]=""; + // snprintf(szBuf,8096,"factions[unitFactionIndex].precachedTravelState[unit->getId()]: + //%d",faction.precachedTravelState[unit->getId()]); + // unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); + // } + + bool foundPrecacheTravelStateIsMoving = + (faction.precachedTravelState[unit->getId()] == tsMoving); + if (foundPrecacheTravelStateIsMoving == true) { + bool canMoveToCells = true; + + Vec2i lastPos = unit->getPos(); + + int unitPrecachePathSize = + (int)faction.precachedPath[unit->getId()].size(); + + for (int i = 0; i < unitPrecachePathSize; i++) { + + Vec2i nodePos = faction.precachedPath[unit->getId()][i]; + + if (map->isInside(nodePos) == false || + map->isInsideSurface(map->toSurfCoords(nodePos)) == false) { + throw megaglest_runtime_error( + "Pathfinder invalid node path position = " + + nodePos.getString() + " i = " + intToStr(i)); + } + + if (i < unit->getPathFindRefreshCellCount() || + (unitPrecachePathSize >= pathFindExtendRefreshForNodeCount && + i < getPathFindExtendRefreshNodeCount(faction))) { + + if (canUnitMoveSoon(unit, lastPos, nodePos) == false) { + canMoveToCells = false; + break; + } + lastPos = nodePos; + } else { + break; + } + } + + if (canMoveToCells == true) { + path->clear(); + // UnitPathBasic *basicPathFinder = dynamic_cast(path); + + int unitPrecachePathSize = + (int)faction.precachedPath[unit->getId()].size(); + + for (int i = 0; i < unitPrecachePathSize; i++) { + + Vec2i nodePos = faction.precachedPath[unit->getId()][i]; + + if (map->isInside(nodePos) == false || + map->isInsideSurface(map->toSurfCoords(nodePos)) == false) { + throw megaglest_runtime_error( + "Pathfinder invalid node path position = " + + nodePos.getString() + " i = " + intToStr(i)); + } + + // if(i < pathFindRefresh || + if (i < unit->getPathFindRefreshCellCount() || + (unitPrecachePathSize >= pathFindExtendRefreshForNodeCount && + i < getPathFindExtendRefreshNodeCount(faction))) { + path->add(nodePos); + } + } + unit->setUsePathfinderExtendedMaxNodes(false); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "return " + "factions[unitFactionIndex].precachedTravelState[unit->" + "getId()];"); + unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__, szBuf); + } + + return faction.precachedTravelState[unit->getId()]; + } else { + clearUnitPrecache(unit); + } + } else { + + bool foundPrecacheTravelStateIsBlocked = + (faction.precachedTravelState[unit->getId()] == tsBlocked); + + if (foundPrecacheTravelStateIsBlocked == true) { + path->incBlockCount(); + unit->setUsePathfinderExtendedMaxNodes(false); + + // if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled + //== true && frameIndex < 0) { char + //szBuf[8096]=""; snprintf(szBuf,8096,"return + // factions[unitFactionIndex].precachedTravelState[unit->getId()];"); + // unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); + // } + + return faction.precachedTravelState[unit->getId()]; + } + } + } + } else { + clearUnitPrecache(unit); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + frameIndex < 0) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "[clearUnitPrecache]"); + unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__, szBuf); + } + } + + const Vec2i unitPos = unit->getPos(); + const Vec2i finalPos = computeNearestFreePos(unit, targetPos); + + float dist = unitPos.dist(finalPos); + + faction.useMaxNodeCount = PathFinder::pathFindNodesMax; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled == true && + chrono.getMillis() > 4) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, chrono.getMillis()); + + // path find algorithm + + // a) push starting pos into openNodes + Node *firstNode = newNode(faction, maxNodeCount); + if (firstNode == NULL) { + throw megaglest_runtime_error("firstNode == NULL"); + } + + firstNode->next = NULL; + firstNode->prev = NULL; + firstNode->pos = unitPos; + firstNode->heuristic = heuristic(unitPos, finalPos); + firstNode->exploredCell = true; + if (faction.openNodesList.find(firstNode->heuristic) == + faction.openNodesList.end()) { + faction.openNodesList[firstNode->heuristic].clear(); + } + faction.openNodesList[firstNode->heuristic].push_back(firstNode); + faction.openPosList[firstNode->pos] = true; + + // b) loop + bool pathFound = true; + bool nodeLimitReached = false; + Node *node = NULL; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled == true && + chrono.getMillis() > 4) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, chrono.getMillis()); + + // First check if unit currently blocked all around them, if so don't try to + // pathfind + if (inBailout == false && unitPos != finalPos) { + int failureCount = 0; + int cellCount = 0; + + for (int i = -1; i <= 1; ++i) { + for (int j = -1; j <= 1; ++j) { + Vec2i pos = unitPos + Vec2i(i, j); + if (pos != unitPos) { + bool canUnitMoveToCell = canUnitMoveSoon(unit, unitPos, pos); + if (canUnitMoveToCell == false) { + failureCount++; + } + cellCount++; + } + } + } + nodeLimitReached = (failureCount == cellCount); + pathFound = !nodeLimitReached; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + frameIndex < 0) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "nodeLimitReached: %d failureCount: %d cellCount: %d", + nodeLimitReached, failureCount, cellCount); + unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__, szBuf); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled == true && + chrono.getMillis() > 1) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] **Check if dest blocked, distance for unit " + "[%d - %s] from [%s] to [%s] is %.2f took msecs: %lld " + "nodeLimitReached = %d, failureCount = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, unit->getId(), unit->getFullName(false).c_str(), + unitPos.getString().c_str(), finalPos.getString().c_str(), dist, + (long long int)chrono.getMillis(), nodeLimitReached, failureCount); + + if (nodeLimitReached == false) { + // First check if final destination blocked + failureCount = 0; + cellCount = 0; + + for (int i = -1; i <= 1; ++i) { + for (int j = -1; j <= 1; ++j) { + Vec2i pos = finalPos + Vec2i(i, j); + if (pos != finalPos) { + bool canUnitMoveToCell = canUnitMoveSoon(unit, pos, finalPos); + if (canUnitMoveToCell == false) { + failureCount++; + } + cellCount++; + } + } + } + nodeLimitReached = (failureCount == cellCount); + pathFound = !nodeLimitReached; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + frameIndex < 0) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "nodeLimitReached: %d failureCount: %d cellCount: %d", + nodeLimitReached, failureCount, cellCount); + unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__, szBuf); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled == true && + chrono.getMillis() > 1) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] **Check if dest blocked, distance for unit " + "[%d - %s] from [%s] to [%s] is %.2f took msecs: %lld " + "nodeLimitReached = %d, failureCount = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, unit->getId(), unit->getFullName(false).c_str(), + unitPos.getString().c_str(), finalPos.getString().c_str(), dist, + (long long int)chrono.getMillis(), nodeLimitReached, + failureCount); + } + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + frameIndex < 0) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "inBailout: %d unitPos: [%s] finalPos [%s]", + inBailout, unitPos.getString().c_str(), + finalPos.getString().c_str()); + unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__, szBuf); + } + } + // + + // START + std::map, bool> canAddNode; + std::map closedNodes; + std::map cameFrom; + cameFrom[unitPos] = Vec2i(-1, -1); + + // Do the a-star base pathfind work if required + int whileLoopCount = 0; + if (nodeLimitReached == false) { + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + frameIndex < 0) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "Calling doAStarPathSearch nodeLimitReached: %d " + "whileLoopCount: %d unitFactionIndex: %d pathFound: %d " + "finalPos [%s] maxNodeCount: %d frameIndex: %d", + nodeLimitReached, whileLoopCount, unitFactionIndex, pathFound, + finalPos.getString().c_str(), maxNodeCount, frameIndex); + unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__, szBuf); + } + + doAStarPathSearch(nodeLimitReached, whileLoopCount, unitFactionIndex, + pathFound, node, finalPos, closedNodes, cameFrom, + canAddNode, unit, maxNodeCount, frameIndex); + + if (searched_node_count != NULL) { + *searched_node_count = whileLoopCount; + } + + // Now see if the unit is eligible for pathfind max nodes boost? + if (nodeLimitReached == true) { + unit->incrementPathfindFailedConsecutiveFrameCount(); + } else { + unit->resetPathfindFailedConsecutiveFrameCount(); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + frameIndex < 0) { + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "Calling doAStarPathSearch nodeLimitReached: %d whileLoopCount: %d " + "unitFactionIndex: %d pathFound: %d finalPos [%s] maxNodeCount: %d " + "pathFindNodesAbsoluteMax: %d frameIndex: %d", + nodeLimitReached, whileLoopCount, unitFactionIndex, pathFound, + finalPos.getString().c_str(), maxNodeCount, + pathFindNodesAbsoluteMax, frameIndex); + unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__, szBuf); + } + + if (nodeLimitReached == true && + maxNodeCount != pathFindNodesAbsoluteMax) { + if (unit->isLastPathfindFailedFrameWithinCurrentFrameTolerance() == + true) { + if (frameIndex < 0) { + unit->setLastPathfindFailedFrameToCurrentFrame(); + unit->setLastPathfindFailedPos(finalPos); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + frameIndex < 0) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "calling aStar()"); + unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__, szBuf); + } + + return aStar(unit, targetPos, false, frameIndex, + pathFindNodesAbsoluteMax); + } + } + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + frameIndex < 0) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "nodeLimitReached: %d", nodeLimitReached); + unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__, szBuf); + } + } + + Node *lastNode = node; + + // if consumed all nodes find best node (to avoid strange behaviour) + if (nodeLimitReached == true) { + + if (faction.closedNodesList.empty() == false) { + float bestHeuristic = + truncateDecimal(faction.closedNodesList.begin()->first, 6); + if (lastNode != NULL && bestHeuristic < lastNode->heuristic) { + lastNode = faction.closedNodesList.begin()->second.front(); + } + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled == true && + chrono.getMillis() > 4) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, chrono.getMillis()); + + // check results of path finding + ts = tsImpossible; + if (pathFound == false || lastNode == firstNode) { + if (minorDebugPathfinder) + printf("Legacy Pathfind Unit [%d - %s] NOT FOUND PATH count = %d " + "frameIndex = %d\n", + unit->getId(), unit->getType()->getName().c_str(), + whileLoopCount, frameIndex); + + // blocked + if (SystemFlags::getSystemSettingType(SystemFlags::debugPathFinder) + .enabled == true) { + string commandDesc = "none"; + Command *command = unit->getCurrCommand(); + if (command != NULL && command->getCommandType() != NULL) { + commandDesc = command->getCommandType()->toString(false); + } + + std::pair lastHarvest = + unit->getLastHarvestResourceTarget(); + + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "State: blocked, cmd [%s] pos: [%s], dest pos: [%s], lastHarvest = " + "[%s - %d], reason A= %d, B= %d, C= %d, D= %d, E= %d, F = %d", + commandDesc.c_str(), unit->getPos().getString().c_str(), + targetPos.getString().c_str(), + lastHarvest.first.getString().c_str(), lastHarvest.second, + pathFound, (lastNode == firstNode), path->getBlockCount(), + path->isBlocked(), nodeLimitReached, path->isStuck()); + unit->setCurrentUnitTitle(szBuf); + } + + if (frameIndex < 0) { + unit->setUsePathfinderExtendedMaxNodes(false); + } + + ts = tsBlocked; + if (frameIndex < 0) { + path->incBlockCount(); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled == true && + chrono.getMillis() > 4) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, chrono.getMillis()); + } else { + if (minorDebugPathfinder) + printf("Legacy Pathfind Unit [%d - %s] FOUND PATH count = %d " + "frameIndex = %d\n", + unit->getId(), unit->getType()->getName().c_str(), + whileLoopCount, frameIndex); + // on the way + ts = tsMoving; + + // build next pointers + Node *currNode = lastNode; + while (currNode->prev != NULL) { + currNode->prev->next = currNode; + currNode = currNode->prev; + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled == true && + chrono.getMillis() > 4) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, chrono.getMillis()); + + if (frameIndex < 0) { + if (maxNodeCount == pathFindNodesAbsoluteMax) { + unit->setUsePathfinderExtendedMaxNodes(true); + } else { + unit->setUsePathfinderExtendedMaxNodes(false); + } + } + + // store path + if (frameIndex < 0) { + path->clear(); + } + + // UnitPathBasic *basicPathFinder = dynamic_cast(path); + + currNode = firstNode; + + for (int i = 0; currNode->next != NULL; currNode = currNode->next, i++) { + Vec2i nodePos = currNode->next->pos; + if (map->isInside(nodePos) == false || + map->isInsideSurface(map->toSurfCoords(nodePos)) == false) { + throw megaglest_runtime_error( + "Pathfinder invalid node path position = " + nodePos.getString() + + " i = " + intToStr(i)); + } + + if (minorDebugPathfinder) + printf("nodePos [%s]\n", nodePos.getString().c_str()); + + if (frameIndex >= 0) { + faction.precachedPath[unit->getId()].push_back(nodePos); + } else { + if (i < unit->getPathFindRefreshCellCount() || + (whileLoopCount >= pathFindExtendRefreshForNodeCount && + i < getPathFindExtendRefreshNodeCount(faction))) { + path->add(nodePos); + } + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled == true && + chrono.getMillis() > 4) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, chrono.getMillis()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax) + .enabled == true) { + char szBuf[8096] = ""; + + string pathToTake = ""; + if (frameIndex < 0) { + vector pathQueue = path->getQueue(); + for (unsigned int index = 0; index < pathQueue.size(); ++index) { + Vec2i &pos = pathQueue[index]; + if (pathToTake != "") { + pathToTake += ", "; + } + pathToTake += pos.getString(); + } + } else { + for (unsigned int index = 0; + index < faction.precachedPath[unit->getId()].size(); ++index) { + Vec2i &pos = faction.precachedPath[unit->getId()][index]; + if (pathToTake != "") { + pathToTake += ", "; + } + pathToTake += pos.getString(); + } + } + snprintf(szBuf, 8096, "Path for unit to take = %s", pathToTake.c_str()); + if (frameIndex < 0) { + unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__, szBuf); + } else { + unit->logSynchDataThreaded( + extractFileFromDirectoryPath(__FILE__).c_str(), __LINE__, szBuf); + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPathFinder) + .enabled == true) { + string commandDesc = "none"; + Command *command = unit->getCurrCommand(); + if (command != NULL && command->getCommandType() != NULL) { + commandDesc = command->getCommandType()->toString(false); + } + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "State: moving, cmd [%s] pos: %s dest pos: %s, Queue= %d", + commandDesc.c_str(), unit->getPos().getString().c_str(), + targetPos.getString().c_str(), path->getQueueCount()); + unit->setCurrentUnitTitle(szBuf); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled == true && + chrono.getMillis() > 4) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, chrono.getMillis()); + } + + faction.openNodesList.clear(); + faction.openPosList.clear(); + faction.closedNodesList.clear(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled == true && + chrono.getMillis() > 4) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s] Line: %d took msecs: %lld --------------------------- " + "[END OF METHOD] ---------------------------\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chrono.getMillis()); + + if (frameIndex >= 0) { + + FactionState &faction = factions.getFactionState(factionIndex); + faction.precachedTravelState[unit->getId()] = ts; + } else { + if (SystemFlags::VERBOSE_MODE_ENABLED && chrono.getMillis() >= 5) + printf("In [%s::%s Line: %d] astar took [%lld] msecs, ts = %d.\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, (long long int)chrono.getMillis(), ts); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + frameIndex < 0) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "return ts: %d", ts); + unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__, szBuf); + } + + } catch (const exception &ex) { + + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", __FILE__, + __FUNCTION__, __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + throw megaglest_runtime_error(ex.what()); + } catch (...) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] UNKNOWN error\n", __FILE__, + __FUNCTION__, __LINE__); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + throw megaglest_runtime_error(szBuf); + } + + return ts; } -void PathFinder::processNearestFreePos(const Vec2i &finalPos, int i, int j, int size, Field field, int teamIndex,Vec2i unitPos, Vec2i &nearestPos, float &nearestDist) { - - try { - Vec2i currPos= finalPos + Vec2i(i, j); - - if(map->isAproxFreeCells(currPos, size, field, teamIndex)) { - float dist = currPos.dist(finalPos); - - //if nearer from finalPos - if(dist < nearestDist){ - nearestPos = currPos; - nearestDist = dist; - } - //if the distance is the same compare distance to unit - else if(dist == nearestDist){ - if(currPos.dist(unitPos) < nearestPos.dist(unitPos)) { - nearestPos = currPos; - } - } - } - } - catch(const exception &ex) { - - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - throw megaglest_runtime_error(ex.what()); - } - catch(...) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] UNKNOWN error\n",__FILE__,__FUNCTION__,__LINE__); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - throw megaglest_runtime_error(szBuf); - } - +void PathFinder::processNearestFreePos(const Vec2i &finalPos, int i, int j, + int size, Field field, int teamIndex, + Vec2i unitPos, Vec2i &nearestPos, + float &nearestDist) { + + try { + Vec2i currPos = finalPos + Vec2i(i, j); + + if (map->isAproxFreeCells(currPos, size, field, teamIndex)) { + float dist = currPos.dist(finalPos); + + // if nearer from finalPos + if (dist < nearestDist) { + nearestPos = currPos; + nearestDist = dist; + } + // if the distance is the same compare distance to unit + else if (dist == nearestDist) { + if (currPos.dist(unitPos) < nearestPos.dist(unitPos)) { + nearestPos = currPos; + } + } + } + } catch (const exception &ex) { + + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", __FILE__, + __FUNCTION__, __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + throw megaglest_runtime_error(ex.what()); + } catch (...) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] UNKNOWN error\n", __FILE__, + __FUNCTION__, __LINE__); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + throw megaglest_runtime_error(szBuf); + } } -Vec2i PathFinder::computeNearestFreePos(const Unit *unit, const Vec2i &finalPos) { - - Vec2i nearestPos(0,0); - try { - - if(map == NULL) { - throw megaglest_runtime_error("map == NULL"); - } - - //unit data - int size= unit->getType()->getSize(); - Field field= unit->getCurrField(); - int teamIndex= unit->getTeam(); - - //if finalPos is free return it - if(map->isAproxFreeCells(finalPos, size, field, teamIndex)) { - return finalPos; - } - - //find nearest pos - Vec2i unitPos= unit->getPosNotThreadSafe(); - nearestPos= unitPos; - - float nearestDist = unitPos.dist(finalPos); - - for(int i= -maxFreeSearchRadius; i <= maxFreeSearchRadius; ++i) { - for(int j= -maxFreeSearchRadius; j <= maxFreeSearchRadius; ++j) { - processNearestFreePos(finalPos, i, j, size, field, teamIndex, unitPos, nearestPos, nearestDist); - } - } - - } - catch(const exception &ex) { - - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - throw megaglest_runtime_error(ex.what()); - } - catch(...) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] UNKNOWN error\n",__FILE__,__FUNCTION__,__LINE__); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - throw megaglest_runtime_error(szBuf); - } - - return nearestPos; +Vec2i PathFinder::computeNearestFreePos(const Unit *unit, + const Vec2i &finalPos) { + + Vec2i nearestPos(0, 0); + try { + + if (map == NULL) { + throw megaglest_runtime_error("map == NULL"); + } + + // unit data + int size = unit->getType()->getSize(); + Field field = unit->getCurrField(); + int teamIndex = unit->getTeam(); + + // if finalPos is free return it + if (map->isAproxFreeCells(finalPos, size, field, teamIndex)) { + return finalPos; + } + + // find nearest pos + Vec2i unitPos = unit->getPosNotThreadSafe(); + nearestPos = unitPos; + + float nearestDist = unitPos.dist(finalPos); + + for (int i = -maxFreeSearchRadius; i <= maxFreeSearchRadius; ++i) { + for (int j = -maxFreeSearchRadius; j <= maxFreeSearchRadius; ++j) { + processNearestFreePos(finalPos, i, j, size, field, teamIndex, unitPos, + nearestPos, nearestDist); + } + } + + } catch (const exception &ex) { + + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", __FILE__, + __FUNCTION__, __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + throw megaglest_runtime_error(ex.what()); + } catch (...) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] UNKNOWN error\n", __FILE__, + __FUNCTION__, __LINE__); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + throw megaglest_runtime_error(szBuf); + } + + return nearestPos; } int PathFinder::findNodeIndex(Node *node, Nodes &nodeList) { - int index = -1; - if(node != NULL) { - for(unsigned int i = 0; i < nodeList.size(); ++i) { - Node *curnode = nodeList[i]; - if(node == curnode) { - index = i; - break; - } - } - } - return index; + int index = -1; + if (node != NULL) { + for (unsigned int i = 0; i < nodeList.size(); ++i) { + Node *curnode = nodeList[i]; + if (node == curnode) { + index = i; + break; + } + } + } + return index; } int PathFinder::findNodeIndex(Node *node, std::vector &nodeList) { - int index = -1; - if(node != NULL) { - for(unsigned int i = 0; i < nodeList.size(); ++i) { - Node &curnode = nodeList[i]; - if(node == &curnode) { - index = i; - break; - } - } - } - return index; + int index = -1; + if (node != NULL) { + for (unsigned int i = 0; i < nodeList.size(); ++i) { + Node &curnode = nodeList[i]; + if (node == &curnode) { + index = i; + break; + } + } + } + return index; } -//bool PathFinder::unitCannotMove(Unit *unit) { +// bool PathFinder::unitCannotMove(Unit *unit) { // bool unitImmediatelyBlocked = false; // // try { -// // First check if unit currently blocked all around them, if so don't try to pathfind -// const Vec2i unitPos = unit->getPos(); -// int failureCount = 0; -// int cellCount = 0; +// // First check if unit currently blocked all around them, if so don't +// try to pathfind const Vec2i unitPos = unit->getPos(); int failureCount +// = 0; int cellCount = 0; // // for(int i = -1; i <= 1; ++i) { // for(int j = -1; j <= 1; ++j) { // Vec2i pos = unitPos + Vec2i(i, j); // if(pos != unitPos) { -// bool canUnitMoveToCell = map->aproxCanMove(unit, unitPos, pos); -// if(canUnitMoveToCell == false) { -// failureCount++; +// bool canUnitMoveToCell = map->aproxCanMove(unit, +// unitPos, pos); if(canUnitMoveToCell == false) { +// failureCount++; // } // cellCount++; // } @@ -1159,87 +1467,110 @@ int PathFinder::findNodeIndex(Node *node, std::vector &nodeList) { // catch(const exception &ex) { // //setRunningStatus(false); // -// SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); -// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); +// SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s +//Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); +// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) +// SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: +//%d]\n",__FILE__,__FUNCTION__,__LINE__); // // throw megaglest_runtime_error(ex.what()); // } // catch(...) { // char szBuf[8096]=""; -// snprintf(szBuf,8096,"In [%s::%s %d] UNKNOWN error\n",__FILE__,__FUNCTION__,__LINE__); +// snprintf(szBuf,8096,"In [%s::%s %d] UNKNOWN +// error\n",__FILE__,__FUNCTION__,__LINE__); // SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); // throw megaglest_runtime_error(szBuf); // } // // return unitImmediatelyBlocked; -//} +// } void PathFinder::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *pathfinderNode = rootNode->addChild("PathFinder"); - - pathfinderNode->addAttribute("pathFindNodesMax",intToStr(pathFindNodesMax), mapTagReplacements); - pathfinderNode->addAttribute("pathFindNodesAbsoluteMax",intToStr(pathFindNodesAbsoluteMax), mapTagReplacements); - for(unsigned int i = 0; i < (unsigned int)factions.size(); ++i) { - FactionState &factionState = factions.getFactionState(i); - XmlNode *factionsNode = pathfinderNode->addChild("factions"); - - for(unsigned int j = 0; j < (unsigned int)factionState.nodePool.size(); ++j) { - Node *curNode = &factionState.nodePool[j]; - XmlNode *nodePoolNode = factionsNode->addChild("nodePool"); - - nodePoolNode->addAttribute("pos",curNode->pos.getString(), mapTagReplacements); - int nextIdx = findNodeIndex(curNode->next, factionState.nodePool); - nodePoolNode->addAttribute("next",intToStr(nextIdx), mapTagReplacements); - int prevIdx = findNodeIndex(curNode->prev, factionState.nodePool); - nodePoolNode->addAttribute("prev",intToStr(prevIdx), mapTagReplacements); - nodePoolNode->addAttribute("heuristic",floatToStr(curNode->heuristic,6), mapTagReplacements); - nodePoolNode->addAttribute("exploredCell",intToStr(curNode->exploredCell), mapTagReplacements); - } - - factionsNode->addAttribute("nodePoolCount",intToStr(factionState.nodePoolCount), mapTagReplacements); - factionsNode->addAttribute("random",intToStr(factionState.random.getLastNumber()), mapTagReplacements); - factionsNode->addAttribute("useMaxNodeCount",intToStr(factionState.useMaxNodeCount), mapTagReplacements); - } + std::map mapTagReplacements; + XmlNode *pathfinderNode = rootNode->addChild("PathFinder"); + + pathfinderNode->addAttribute("pathFindNodesMax", intToStr(pathFindNodesMax), + mapTagReplacements); + pathfinderNode->addAttribute("pathFindNodesAbsoluteMax", + intToStr(pathFindNodesAbsoluteMax), + mapTagReplacements); + for (unsigned int i = 0; i < (unsigned int)factions.size(); ++i) { + FactionState &factionState = factions.getFactionState(i); + XmlNode *factionsNode = pathfinderNode->addChild("factions"); + + for (unsigned int j = 0; j < (unsigned int)factionState.nodePool.size(); + ++j) { + Node *curNode = &factionState.nodePool[j]; + XmlNode *nodePoolNode = factionsNode->addChild("nodePool"); + + nodePoolNode->addAttribute("pos", curNode->pos.getString(), + mapTagReplacements); + int nextIdx = findNodeIndex(curNode->next, factionState.nodePool); + nodePoolNode->addAttribute("next", intToStr(nextIdx), mapTagReplacements); + int prevIdx = findNodeIndex(curNode->prev, factionState.nodePool); + nodePoolNode->addAttribute("prev", intToStr(prevIdx), mapTagReplacements); + nodePoolNode->addAttribute("heuristic", floatToStr(curNode->heuristic, 6), + mapTagReplacements); + nodePoolNode->addAttribute( + "exploredCell", intToStr(curNode->exploredCell), mapTagReplacements); + } + + factionsNode->addAttribute("nodePoolCount", + intToStr(factionState.nodePoolCount), + mapTagReplacements); + factionsNode->addAttribute("random", + intToStr(factionState.random.getLastNumber()), + mapTagReplacements); + factionsNode->addAttribute("useMaxNodeCount", + intToStr(factionState.useMaxNodeCount), + mapTagReplacements); + } } void PathFinder::loadGame(const XmlNode *rootNode) { - const XmlNode *pathfinderNode = rootNode->getChild("PathFinder"); - - vector factionsNodeList = pathfinderNode->getChildList("factions"); - for(unsigned int i = 0; i < (unsigned int)factionsNodeList.size(); ++i) { - XmlNode *factionsNode = factionsNodeList[i]; - - FactionState &factionState = factions.getFactionState(i); - vector nodePoolListNode = factionsNode->getChildList("nodePool"); - for(unsigned int j = 0; j < (unsigned int)nodePoolListNode.size() && j < (unsigned int)pathFindNodesAbsoluteMax; ++j) { - XmlNode *nodePoolNode = nodePoolListNode[j]; - - Node *curNode = &factionState.nodePool[j]; - curNode->pos = Vec2i::strToVec2(nodePoolNode->getAttribute("pos")->getValue()); - int nextNode = nodePoolNode->getAttribute("next")->getIntValue(); - if(nextNode >= 0) { - curNode->next = &factionState.nodePool[nextNode]; - } - else { - curNode->next = NULL; - } - - int prevNode = nodePoolNode->getAttribute("prev")->getIntValue(); - if(prevNode >= 0) { - curNode->prev = &factionState.nodePool[prevNode]; - } - else { - curNode->prev = NULL; - } - curNode->heuristic = nodePoolNode->getAttribute("heuristic")->getFloatValue(); - curNode->exploredCell = nodePoolNode->getAttribute("exploredCell")->getIntValue() != 0; - } - - factionState.nodePoolCount = factionsNode->getAttribute("nodePoolCount")->getIntValue(); - factionState.random.setLastNumber(factionsNode->getAttribute("random")->getIntValue()); - factionState.useMaxNodeCount = PathFinder::pathFindNodesMax; - } + const XmlNode *pathfinderNode = rootNode->getChild("PathFinder"); + + vector factionsNodeList = pathfinderNode->getChildList("factions"); + for (unsigned int i = 0; i < (unsigned int)factionsNodeList.size(); ++i) { + XmlNode *factionsNode = factionsNodeList[i]; + + FactionState &factionState = factions.getFactionState(i); + vector nodePoolListNode = factionsNode->getChildList("nodePool"); + for (unsigned int j = 0; j < (unsigned int)nodePoolListNode.size() && + j < (unsigned int)pathFindNodesAbsoluteMax; + ++j) { + XmlNode *nodePoolNode = nodePoolListNode[j]; + + Node *curNode = &factionState.nodePool[j]; + curNode->pos = + Vec2i::strToVec2(nodePoolNode->getAttribute("pos")->getValue()); + int nextNode = nodePoolNode->getAttribute("next")->getIntValue(); + if (nextNode >= 0) { + curNode->next = &factionState.nodePool[nextNode]; + } else { + curNode->next = NULL; + } + + int prevNode = nodePoolNode->getAttribute("prev")->getIntValue(); + if (prevNode >= 0) { + curNode->prev = &factionState.nodePool[prevNode]; + } else { + curNode->prev = NULL; + } + curNode->heuristic = + nodePoolNode->getAttribute("heuristic")->getFloatValue(); + curNode->exploredCell = + nodePoolNode->getAttribute("exploredCell")->getIntValue() != 0; + } + + factionState.nodePoolCount = + factionsNode->getAttribute("nodePoolCount")->getIntValue(); + factionState.random.setLastNumber( + factionsNode->getAttribute("random")->getIntValue()); + factionState.useMaxNodeCount = PathFinder::pathFindNodesMax; + } } -}} //end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/ai/path_finder.h b/source/glest_game/ai/path_finder.h index c914a154f..6c45d77e4 100644 --- a/source/glest_game/ai/path_finder.h +++ b/source/glest_game/ai/path_finder.h @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,24 +13,25 @@ #define _GLEST_GAME_PATHFINDER_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include "vec.h" -#include -#include #include "game_constants.h" -#include "skill_type.h" #include "map.h" +#include "skill_type.h" #include "unit.h" -//#include "randomc.h" +#include "vec.h" +#include +#include +// #include "randomc.h" #include "leak_dumper.h" -using std::vector; using Shared::Graphics::Vec2i; +using std::vector; -namespace Glest { namespace Game { +namespace Glest { +namespace Game { // ===================================================== // class PathFinder @@ -40,446 +41,478 @@ namespace Glest { namespace Game { class PathFinder { public: - class BadUnitNodeList { - public: - BadUnitNodeList() { - unitSize = -1; - field = fLand; - } - int unitSize; - Field field; - std::map > badPosList; - - inline bool isPosBad(const Vec2i &pos1,const Vec2i &pos2) { - bool result = false; - - std::map >::iterator iterFind = badPosList.find(pos1); - if(iterFind != badPosList.end()) { - std::map::iterator iterFind2 = iterFind->second.find(pos2); - if(iterFind2 != iterFind->second.end()) { - result = true; - } - } - - return result; - } - }; - - class Node { - public: - Node() { - clear(); - } - void clear() { - pos.x = 0; - pos.y = 0; - next=NULL; - prev=NULL; - heuristic=0.0; - exploredCell=false; - } - Vec2i pos; - Node *next; - Node *prev; - float heuristic; - bool exploredCell; - }; - typedef vector Nodes; - - class FactionState { - protected: - Mutex *factionMutexPrecache; - public: - explicit FactionState(int factionIndex) : - //factionMutexPrecache(new Mutex) { - factionMutexPrecache(NULL) { //, random(factionIndex) { - - openPosList.clear(); - openNodesList.clear(); - closedNodesList.clear(); - nodePool.clear(); - nodePoolCount = 0; - this->factionIndex = factionIndex; - useMaxNodeCount = 0; - - precachedTravelState.clear(); - precachedPath.clear(); - } - ~FactionState() { - - delete factionMutexPrecache; - factionMutexPrecache = NULL; - } - Mutex * getMutexPreCache() { - return factionMutexPrecache; - } - - std::map openPosList; - std::map openNodesList; - std::map closedNodesList; - std::vector nodePool; - - int nodePoolCount; - int factionIndex; - RandomGen random; - //CRandomMersenne random; - int useMaxNodeCount; - - std::map precachedTravelState; - std::map > precachedPath; - }; - - class FactionStateManager { - protected: - typedef vector FactionStateList; - FactionStateList factions; - - void init() { - for(int index = 0; index < GameConstants::maxPlayers; ++index) { - factions.push_back(new FactionState(index)); - } - } - - public: - FactionStateManager() { - init(); - } - ~FactionStateManager() { - clear(); - } - - FactionState & getFactionState(int index) { - FactionState *faction = factions[index]; - return *faction; - } - void clear() { - for(unsigned int index = 0; index < (unsigned int)factions.size(); ++index) { - delete factions[index]; - } - - factions.clear(); - } - int size() { - return (int)factions.size(); - } - }; + class BadUnitNodeList { + public: + BadUnitNodeList() { + unitSize = -1; + field = fLand; + } + int unitSize; + Field field; + std::map> badPosList; + + inline bool isPosBad(const Vec2i &pos1, const Vec2i &pos2) { + bool result = false; + + std::map>::iterator iterFind = + badPosList.find(pos1); + if (iterFind != badPosList.end()) { + std::map::iterator iterFind2 = iterFind->second.find(pos2); + if (iterFind2 != iterFind->second.end()) { + result = true; + } + } + + return result; + } + }; + + class Node { + public: + Node() { clear(); } + void clear() { + pos.x = 0; + pos.y = 0; + next = NULL; + prev = NULL; + heuristic = 0.0; + exploredCell = false; + } + Vec2i pos; + Node *next; + Node *prev; + float heuristic; + bool exploredCell; + }; + typedef vector Nodes; + + class FactionState { + protected: + Mutex *factionMutexPrecache; + + public: + explicit FactionState(int factionIndex) + : // factionMutexPrecache(new Mutex) { + factionMutexPrecache(NULL) { //, random(factionIndex) { + + openPosList.clear(); + openNodesList.clear(); + closedNodesList.clear(); + nodePool.clear(); + nodePoolCount = 0; + this->factionIndex = factionIndex; + useMaxNodeCount = 0; + + precachedTravelState.clear(); + precachedPath.clear(); + } + ~FactionState() { + + delete factionMutexPrecache; + factionMutexPrecache = NULL; + } + Mutex *getMutexPreCache() { return factionMutexPrecache; } + + std::map openPosList; + std::map openNodesList; + std::map closedNodesList; + std::vector nodePool; + + int nodePoolCount; + int factionIndex; + RandomGen random; + // CRandomMersenne random; + int useMaxNodeCount; + + std::map precachedTravelState; + std::map> precachedPath; + }; + + class FactionStateManager { + protected: + typedef vector FactionStateList; + FactionStateList factions; + + void init() { + for (int index = 0; index < GameConstants::maxPlayers; ++index) { + factions.push_back(new FactionState(index)); + } + } + + public: + FactionStateManager() { init(); } + ~FactionStateManager() { clear(); } + + FactionState &getFactionState(int index) { + FactionState *faction = factions[index]; + return *faction; + } + void clear() { + for (unsigned int index = 0; index < (unsigned int)factions.size(); + ++index) { + delete factions[index]; + } + + factions.clear(); + } + int size() { return (int)factions.size(); } + }; public: - static const int maxFreeSearchRadius; + static const int maxFreeSearchRadius; - static const int pathFindBailoutRadius; - static const int pathFindExtendRefreshForNodeCount; - static const int pathFindExtendRefreshNodeCountMin; - static const int pathFindExtendRefreshNodeCountMax; + static const int pathFindBailoutRadius; + static const int pathFindExtendRefreshForNodeCount; + static const int pathFindExtendRefreshNodeCountMin; + static const int pathFindExtendRefreshNodeCountMax; private: + static int pathFindNodesMax; + static int pathFindNodesAbsoluteMax; - static int pathFindNodesMax; - static int pathFindNodesAbsoluteMax; - - - FactionStateManager factions; - const Map *map; - bool minorDebugPathfinder; + FactionStateManager factions; + const Map *map; + bool minorDebugPathfinder; public: - PathFinder(); - explicit PathFinder(const Map *map); - ~PathFinder(); - - PathFinder(const PathFinder& obj) { - init(); - throw megaglest_runtime_error("class PathFinder is NOT safe to copy!"); - } - PathFinder & operator=(const PathFinder& obj) { - init(); - throw megaglest_runtime_error("class PathFinder is NOT safe to assign!"); - } - - void init(const Map *map); - TravelState findPath(Unit *unit, const Vec2i &finalPos, bool *wasStuck=NULL,int frameIndex=-1); - void clearUnitPrecache(Unit *unit); - void removeUnitPrecache(Unit *unit); - void clearCaches(); - - //bool unitCannotMove(Unit *unit); - - int findNodeIndex(Node *node, Nodes &nodeList); - int findNodeIndex(Node *node, std::vector &nodeList); - - void saveGame(XmlNode *rootNode); - void loadGame(const XmlNode *rootNode); + PathFinder(); + explicit PathFinder(const Map *map); + ~PathFinder(); + + PathFinder(const PathFinder &obj) { + init(); + throw megaglest_runtime_error("class PathFinder is NOT safe to copy!"); + } + PathFinder &operator=(const PathFinder &obj) { + init(); + throw megaglest_runtime_error("class PathFinder is NOT safe to assign!"); + } + + void init(const Map *map); + TravelState findPath(Unit *unit, const Vec2i &finalPos, bool *wasStuck = NULL, + int frameIndex = -1); + void clearUnitPrecache(Unit *unit); + void removeUnitPrecache(Unit *unit); + void clearCaches(); + + // bool unitCannotMove(Unit *unit); + + int findNodeIndex(Node *node, Nodes &nodeList); + int findNodeIndex(Node *node, std::vector &nodeList); + + void saveGame(XmlNode *rootNode); + void loadGame(const XmlNode *rootNode); private: - void init(); - - TravelState aStar(Unit *unit, const Vec2i &finalPos, bool inBailout, - int frameIndex, int maxNodeCount=-1,uint32 *searched_node_count=NULL); - inline static Node *newNode(FactionState &faction, int maxNodeCount) { - if( faction.nodePoolCount < (int)faction.nodePool.size() && - faction.nodePoolCount < maxNodeCount) { - Node *node= &(faction.nodePool[faction.nodePoolCount]); - node->clear(); - faction.nodePoolCount++; - return node; - } - return NULL; - } - - Vec2i computeNearestFreePos(const Unit *unit, const Vec2i &targetPos); - - inline static float heuristic(const Vec2i &pos, const Vec2i &finalPos) { - return pos.dist(finalPos); - } - - inline static bool openPos(const Vec2i &sucPos, FactionState &faction) { - if(faction.openPosList.find(sucPos) == faction.openPosList.end()) { - return false; - } - return true; - } - - inline static Node * minHeuristicFastLookup(FactionState &faction) { - if(faction.openNodesList.empty() == true) { - throw megaglest_runtime_error("openNodesList.empty() == true"); - } - - Node *result = faction.openNodesList.begin()->second.front(); - faction.openNodesList.begin()->second.erase(faction.openNodesList.begin()->second.begin()); - if(faction.openNodesList.begin()->second.empty()) { - faction.openNodesList.erase(faction.openNodesList.begin()); - } - return result; - } - - inline bool processNode(Unit *unit, Node *node,const Vec2i finalPos, - int x, int y, bool &nodeLimitReached,int maxNodeCount) { - bool result = false; - Vec2i sucPos= node->pos + Vec2i(x, y); - - int unitFactionIndex = unit->getFactionIndex(); - FactionState &faction = factions.getFactionState(unitFactionIndex); - - bool foundOpenPosForPos = openPos(sucPos, faction); - bool allowUnitMoveSoon = canUnitMoveSoon(unit, node->pos, sucPos); - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && - SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax).enabled == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In processNode() nodeLimitReached %d unitFactionIndex %d foundOpenPosForPos %d allowUnitMoveSoon %d maxNodeCount %d node->pos = %s finalPos = %s sucPos = %s faction.openPosList.size() %lu closedNodesList.size() %lu", - nodeLimitReached,unitFactionIndex,foundOpenPosForPos, allowUnitMoveSoon, maxNodeCount,node->pos.getString().c_str(),finalPos.getString().c_str(),sucPos.getString().c_str(),faction.openPosList.size(),faction.closedNodesList.size()); - - if(Thread::isCurrentThreadMainThread() == false) { - unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); - } - else { - unit->logSynchData(__FILE__,__LINE__,szBuf); - } - } - - if(foundOpenPosForPos == false && allowUnitMoveSoon) { - //if node is not open and canMove then generate another node - Node *sucNode= newNode(faction,maxNodeCount); - if(sucNode != NULL) { - sucNode->pos= sucPos; - sucNode->heuristic = heuristic(sucNode->pos, finalPos); - sucNode->prev= node; - sucNode->next= NULL; - sucNode->exploredCell = map->getSurfaceCell( - Map::toSurfCoords(sucPos))->isExplored(unit->getTeam()); - if(faction.openNodesList.find(sucNode->heuristic) == faction.openNodesList.end()) { - faction.openNodesList[sucNode->heuristic].clear(); - } - faction.openNodesList[sucNode->heuristic].push_back(sucNode); - faction.openPosList[sucNode->pos] = true; - - result = true; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && - SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax).enabled == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In processNode() sucPos = %s",sucPos.getString().c_str()); - - if(Thread::isCurrentThreadMainThread() == false) { - unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); - } - else { - unit->logSynchData(__FILE__,__LINE__,szBuf); - } - } - - } - else { - nodeLimitReached= true; - } - } - - return result; - } - - void processNearestFreePos(const Vec2i &finalPos, int i, int j, int size, - Field field, int teamIndex,Vec2i unitPos, Vec2i &nearestPos, float &nearestDist); - int getPathFindExtendRefreshNodeCount(FactionState &faction); - - inline bool canUnitMoveSoon(Unit *unit, const Vec2i &pos1, const Vec2i &pos2) { - bool result = map->aproxCanMoveSoon(unit, pos1, pos2); - return result; - } - - inline void doAStarPathSearch(bool & nodeLimitReached, int & whileLoopCount, - int & unitFactionIndex, bool & pathFound, Node *& node, const Vec2i & finalPos, - const std::map &closedNodes, - const std::map &cameFrom, const std::map ,bool> &canAddNode, - Unit *& unit, int & maxNodeCount, int curFrameIndex) { - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && - SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax).enabled == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In doAStarPathSearch() nodeLimitReached %d whileLoopCount %d unitFactionIndex %d pathFound %d maxNodeCount %d", - nodeLimitReached,whileLoopCount,unitFactionIndex,pathFound, maxNodeCount); - - if(curFrameIndex >= 0) { - unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); - } - else { - unit->logSynchData(__FILE__,__LINE__,szBuf); - } - } - - FactionState &faction = factions.getFactionState(unitFactionIndex); - - while(nodeLimitReached == false) { - whileLoopCount++; - if(faction.openNodesList.empty() == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && - SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax).enabled == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In doAStarPathSearch() nodeLimitReached %d whileLoopCount %d unitFactionIndex %d pathFound %d maxNodeCount %d", - nodeLimitReached,whileLoopCount,unitFactionIndex,pathFound, maxNodeCount); - - if(curFrameIndex >= 0) { - unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); - } - else { - unit->logSynchData(__FILE__,__LINE__,szBuf); - } - } - - pathFound = false; - break; - } - node = minHeuristicFastLookup(faction); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && - SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax).enabled == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In doAStarPathSearch() nodeLimitReached %d whileLoopCount %d unitFactionIndex %d pathFound %d maxNodeCount %d node->pos = %s finalPos = %s node->exploredCell = %d", - nodeLimitReached,whileLoopCount,unitFactionIndex,pathFound, maxNodeCount,node->pos.getString().c_str(),finalPos.getString().c_str(),node->exploredCell); - - if(curFrameIndex >= 0) { - unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); - } - else { - unit->logSynchData(__FILE__,__LINE__,szBuf); - } - } - - if(node->pos == finalPos || node->exploredCell == false) { - pathFound = true; - break; - } - - if(faction.closedNodesList.find(node->heuristic) == faction.closedNodesList.end()) { - faction.closedNodesList[node->heuristic].clear(); - } - faction.closedNodesList[node->heuristic].push_back(node); - faction.openPosList[node->pos] = true; - - int failureCount = 0; - int cellCount = 0; - -// if(Thread::isCurrentThreadMainThread() == false) { -// throw megaglest_runtime_error("#1 Invalid access to FactionState random from outside main thread current id = " + -// intToStr(Thread::getCurrentThreadId()) + " main = " + intToStr(Thread::getMainThreadId())); -// } - - //int tryDirection = 1; - //int tryDirection = faction.random.IRandomX(1, 4); - int tryDirection = faction.random.randRange(1, 4); - //int tryDirection = unit->getRandom(true)->randRange(1, 4); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && - SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax).enabled == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In doAStarPathSearch() tryDirection %d",tryDirection); - - if(curFrameIndex >= 0) { - unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); - } - else { - unit->logSynchData(__FILE__,__LINE__,szBuf); - } - } - - if(tryDirection == 4) { - for(int i = 1;i >= -1 && nodeLimitReached == false;--i) { - for(int j = -1;j <= 1 && nodeLimitReached == false;++j) { - if(processNode(unit, node, finalPos, i, j, nodeLimitReached, maxNodeCount) == false) { - failureCount++; - } - cellCount++; - } - } - } - else if(tryDirection == 3) { - for(int i = -1;i <= 1 && nodeLimitReached == false;++i) { - for(int j = 1;j >= -1 && nodeLimitReached == false;--j) { - if(processNode(unit, node, finalPos, i, j, nodeLimitReached, maxNodeCount) == false) { - failureCount++; - } - cellCount++; - } - } - } - else if(tryDirection == 2) { - for(int i = -1;i <= 1 && nodeLimitReached == false;++i) { - for(int j = -1;j <= 1 && nodeLimitReached == false;++j) { - if(processNode(unit, node, finalPos, i, j, nodeLimitReached, maxNodeCount) == false) { - failureCount++; - } - cellCount++; - } - } - } - else { - for(int i = 1;i >= -1 && nodeLimitReached == false;--i) { - for(int j = 1;j >= -1 && nodeLimitReached == false;--j) { - if(processNode(unit, node, finalPos, i, j, nodeLimitReached, maxNodeCount) == false) { - failureCount++; - } - cellCount++; - } - } - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && - SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax).enabled == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In doAStarPathSearch() nodeLimitReached %d whileLoopCount %d unitFactionIndex %d pathFound %d maxNodeCount %d", - nodeLimitReached,whileLoopCount,unitFactionIndex,pathFound, maxNodeCount); - - if(curFrameIndex >= 0) { - unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); - } - else { - unit->logSynchData(__FILE__,__LINE__,szBuf); - } - } - - } - + void init(); + + TravelState aStar(Unit *unit, const Vec2i &finalPos, bool inBailout, + int frameIndex, int maxNodeCount = -1, + uint32 *searched_node_count = NULL); + inline static Node *newNode(FactionState &faction, int maxNodeCount) { + if (faction.nodePoolCount < (int)faction.nodePool.size() && + faction.nodePoolCount < maxNodeCount) { + Node *node = &(faction.nodePool[faction.nodePoolCount]); + node->clear(); + faction.nodePoolCount++; + return node; + } + return NULL; + } + + Vec2i computeNearestFreePos(const Unit *unit, const Vec2i &targetPos); + + inline static float heuristic(const Vec2i &pos, const Vec2i &finalPos) { + return pos.dist(finalPos); + } + + inline static bool openPos(const Vec2i &sucPos, FactionState &faction) { + if (faction.openPosList.find(sucPos) == faction.openPosList.end()) { + return false; + } + return true; + } + + inline static Node *minHeuristicFastLookup(FactionState &faction) { + if (faction.openNodesList.empty() == true) { + throw megaglest_runtime_error("openNodesList.empty() == true"); + } + + Node *result = faction.openNodesList.begin()->second.front(); + faction.openNodesList.begin()->second.erase( + faction.openNodesList.begin()->second.begin()); + if (faction.openNodesList.begin()->second.empty()) { + faction.openNodesList.erase(faction.openNodesList.begin()); + } + return result; + } + + inline bool processNode(Unit *unit, Node *node, const Vec2i finalPos, int x, + int y, bool &nodeLimitReached, int maxNodeCount) { + bool result = false; + Vec2i sucPos = node->pos + Vec2i(x, y); + + int unitFactionIndex = unit->getFactionIndex(); + FactionState &faction = factions.getFactionState(unitFactionIndex); + + bool foundOpenPosForPos = openPos(sucPos, faction); + bool allowUnitMoveSoon = canUnitMoveSoon(unit, node->pos, sucPos); + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax) + .enabled == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In processNode() nodeLimitReached %d unitFactionIndex %d " + "foundOpenPosForPos %d allowUnitMoveSoon %d maxNodeCount %d " + "node->pos = %s finalPos = %s sucPos = %s " + "faction.openPosList.size() %lu closedNodesList.size() %lu", + nodeLimitReached, unitFactionIndex, foundOpenPosForPos, + allowUnitMoveSoon, maxNodeCount, node->pos.getString().c_str(), + finalPos.getString().c_str(), sucPos.getString().c_str(), + faction.openPosList.size(), faction.closedNodesList.size()); + + if (Thread::isCurrentThreadMainThread() == false) { + unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf); + } else { + unit->logSynchData(__FILE__, __LINE__, szBuf); + } + } + + if (foundOpenPosForPos == false && allowUnitMoveSoon) { + // if node is not open and canMove then generate another node + Node *sucNode = newNode(faction, maxNodeCount); + if (sucNode != NULL) { + sucNode->pos = sucPos; + sucNode->heuristic = heuristic(sucNode->pos, finalPos); + sucNode->prev = node; + sucNode->next = NULL; + sucNode->exploredCell = map->getSurfaceCell(Map::toSurfCoords(sucPos)) + ->isExplored(unit->getTeam()); + if (faction.openNodesList.find(sucNode->heuristic) == + faction.openNodesList.end()) { + faction.openNodesList[sucNode->heuristic].clear(); + } + faction.openNodesList[sucNode->heuristic].push_back(sucNode); + faction.openPosList[sucNode->pos] = true; + + result = true; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax) + .enabled == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In processNode() sucPos = %s", + sucPos.getString().c_str()); + + if (Thread::isCurrentThreadMainThread() == false) { + unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf); + } else { + unit->logSynchData(__FILE__, __LINE__, szBuf); + } + } + + } else { + nodeLimitReached = true; + } + } + + return result; + } + + void processNearestFreePos(const Vec2i &finalPos, int i, int j, int size, + Field field, int teamIndex, Vec2i unitPos, + Vec2i &nearestPos, float &nearestDist); + int getPathFindExtendRefreshNodeCount(FactionState &faction); + + inline bool canUnitMoveSoon(Unit *unit, const Vec2i &pos1, + const Vec2i &pos2) { + bool result = map->aproxCanMoveSoon(unit, pos1, pos2); + return result; + } + + inline void + doAStarPathSearch(bool &nodeLimitReached, int &whileLoopCount, + int &unitFactionIndex, bool &pathFound, Node *&node, + const Vec2i &finalPos, + const std::map &closedNodes, + const std::map &cameFrom, + const std::map, bool> &canAddNode, + Unit *&unit, int &maxNodeCount, int curFrameIndex) { + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax) + .enabled == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In doAStarPathSearch() nodeLimitReached %d whileLoopCount %d " + "unitFactionIndex %d pathFound %d maxNodeCount %d", + nodeLimitReached, whileLoopCount, unitFactionIndex, pathFound, + maxNodeCount); + + if (curFrameIndex >= 0) { + unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf); + } else { + unit->logSynchData(__FILE__, __LINE__, szBuf); + } + } + + FactionState &faction = factions.getFactionState(unitFactionIndex); + + while (nodeLimitReached == false) { + whileLoopCount++; + if (faction.openNodesList.empty() == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax) + .enabled == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In doAStarPathSearch() nodeLimitReached %d whileLoopCount " + "%d unitFactionIndex %d pathFound %d maxNodeCount %d", + nodeLimitReached, whileLoopCount, unitFactionIndex, + pathFound, maxNodeCount); + + if (curFrameIndex >= 0) { + unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf); + } else { + unit->logSynchData(__FILE__, __LINE__, szBuf); + } + } + + pathFound = false; + break; + } + node = minHeuristicFastLookup(faction); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax) + .enabled == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In doAStarPathSearch() nodeLimitReached %d whileLoopCount %d " + "unitFactionIndex %d pathFound %d maxNodeCount %d node->pos = " + "%s finalPos = %s node->exploredCell = %d", + nodeLimitReached, whileLoopCount, unitFactionIndex, pathFound, + maxNodeCount, node->pos.getString().c_str(), + finalPos.getString().c_str(), node->exploredCell); + + if (curFrameIndex >= 0) { + unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf); + } else { + unit->logSynchData(__FILE__, __LINE__, szBuf); + } + } + + if (node->pos == finalPos || node->exploredCell == false) { + pathFound = true; + break; + } + + if (faction.closedNodesList.find(node->heuristic) == + faction.closedNodesList.end()) { + faction.closedNodesList[node->heuristic].clear(); + } + faction.closedNodesList[node->heuristic].push_back(node); + faction.openPosList[node->pos] = true; + + int failureCount = 0; + int cellCount = 0; + + // if(Thread::isCurrentThreadMainThread() == false) + //{ throw megaglest_runtime_error("#1 + //Invalid access to FactionState random from outside main thread current + // id = " + intToStr(Thread::getCurrentThreadId()) + //+ " main = " + intToStr(Thread::getMainThreadId())); + // } + + // int tryDirection = 1; + // int tryDirection = faction.random.IRandomX(1, 4); + int tryDirection = faction.random.randRange(1, 4); + // int tryDirection = unit->getRandom(true)->randRange(1, 4); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax) + .enabled == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In doAStarPathSearch() tryDirection %d", + tryDirection); + + if (curFrameIndex >= 0) { + unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf); + } else { + unit->logSynchData(__FILE__, __LINE__, szBuf); + } + } + + if (tryDirection == 4) { + for (int i = 1; i >= -1 && nodeLimitReached == false; --i) { + for (int j = -1; j <= 1 && nodeLimitReached == false; ++j) { + if (processNode(unit, node, finalPos, i, j, nodeLimitReached, + maxNodeCount) == false) { + failureCount++; + } + cellCount++; + } + } + } else if (tryDirection == 3) { + for (int i = -1; i <= 1 && nodeLimitReached == false; ++i) { + for (int j = 1; j >= -1 && nodeLimitReached == false; --j) { + if (processNode(unit, node, finalPos, i, j, nodeLimitReached, + maxNodeCount) == false) { + failureCount++; + } + cellCount++; + } + } + } else if (tryDirection == 2) { + for (int i = -1; i <= 1 && nodeLimitReached == false; ++i) { + for (int j = -1; j <= 1 && nodeLimitReached == false; ++j) { + if (processNode(unit, node, finalPos, i, j, nodeLimitReached, + maxNodeCount) == false) { + failureCount++; + } + cellCount++; + } + } + } else { + for (int i = 1; i >= -1 && nodeLimitReached == false; --i) { + for (int j = 1; j >= -1 && nodeLimitReached == false; --j) { + if (processNode(unit, node, finalPos, i, j, nodeLimitReached, + maxNodeCount) == false) { + failureCount++; + } + cellCount++; + } + } + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax) + .enabled == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In doAStarPathSearch() nodeLimitReached %d whileLoopCount %d " + "unitFactionIndex %d pathFound %d maxNodeCount %d", + nodeLimitReached, whileLoopCount, unitFactionIndex, pathFound, + maxNodeCount); + + if (curFrameIndex >= 0) { + unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf); + } else { + unit->logSynchData(__FILE__, __LINE__, szBuf); + } + } + } }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/facilities/auto_test.cpp b/source/glest_game/facilities/auto_test.cpp index ff2167f02..8de082617 100644 --- a/source/glest_game/facilities/auto_test.cpp +++ b/source/glest_game/facilities/auto_test.cpp @@ -11,19 +11,19 @@ #include "auto_test.h" -#include "program.h" +#include "config.h" +#include "core_data.h" +#include "game.h" #include "main_menu.h" +#include "menu_state_custom_game.h" #include "menu_state_new_game.h" #include "menu_state_scenario.h" -#include "menu_state_custom_game.h" -#include "game.h" -#include "core_data.h" -#include "config.h" +#include "program.h" #include "leak_dumper.h" - -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class AutoTest @@ -39,73 +39,77 @@ string AutoTest::loadGameSettingsFile = ""; // ===================== PUBLIC ======================== AutoTest::AutoTest() { - exitGame = false; - gameStartTime = invalidTime; - random.init(time(NULL)); + exitGame = false; + gameStartTime = invalidTime; + random.init(time(NULL)); } -AutoTest & AutoTest::getInstance() { - static AutoTest autoTest; - return autoTest; +AutoTest &AutoTest::getInstance() { + static AutoTest autoTest; + return autoTest; } void AutoTest::updateIntro(Program *program) { - program->setState(new MainMenu(program)); + program->setState(new MainMenu(program)); } void AutoTest::updateRoot(Program *program, MainMenu *mainMenu) { - mainMenu->setState(new MenuStateNewGame(program, mainMenu)); + mainMenu->setState(new MenuStateNewGame(program, mainMenu)); } void AutoTest::updateNewGame(Program *program, MainMenu *mainMenu) { - if(loadGameSettingsFile != "") { - gameStartTime = invalidTime; - bool fileFound = CoreData::getInstance().loadGameSettingsFromFile( - loadGameSettingsFile, &gameSettings); - - if(fileFound == false) { - throw megaglest_runtime_error("Specified game settings file [" + loadGameSettingsFile + "] was NOT found!"); - } - //printf("Got settings:\n%s",gameSettings.toString().c_str()); - mainMenu->setState(new MenuStateCustomGame(program, mainMenu, false, pNewGame, true, &gameSettings)); - } - else { - mainMenu->setState(new MenuStateScenario(program, mainMenu, false, - Config::getInstance().getPathListForType(ptScenarios))); - } + if (loadGameSettingsFile != "") { + gameStartTime = invalidTime; + bool fileFound = CoreData::getInstance().loadGameSettingsFromFile( + loadGameSettingsFile, &gameSettings); + + if (fileFound == false) { + throw megaglest_runtime_error("Specified game settings file [" + + loadGameSettingsFile + "] was NOT found!"); + } + // printf("Got settings:\n%s",gameSettings.toString().c_str()); + mainMenu->setState(new MenuStateCustomGame(program, mainMenu, false, + pNewGame, true, &gameSettings)); + } else { + mainMenu->setState(new MenuStateScenario( + program, mainMenu, false, + Config::getInstance().getPathListForType(ptScenarios))); + } } void AutoTest::updateScenario(MenuStateScenario *menuStateScenario) { - gameStartTime = invalidTime; + gameStartTime = invalidTime; - int scenarioIndex = random.randRange(0, menuStateScenario->getScenarioCount()-1); - menuStateScenario->setScenario(scenarioIndex); + int scenarioIndex = + random.randRange(0, menuStateScenario->getScenarioCount() - 1); + menuStateScenario->setScenario(scenarioIndex); - menuStateScenario->launchGame(); + menuStateScenario->launchGame(); } bool AutoTest::updateGame(Game *game) { - // record start time - if(gameStartTime == invalidTime) { - gameStartTime = time(NULL); - } - - // quit if we've espend enough time in the game - if(difftime(time(NULL),gameStartTime) > gameTime) { - Program *program = game->getProgram(); - Stats endStats = game->quitGame(); - if(AutoTest::wantExitGame == true) { - exitGame = true; - } - Game::exitGameState(program, endStats); - return true; - } - - return false; + // record start time + if (gameStartTime == invalidTime) { + gameStartTime = time(NULL); + } + + // quit if we've espend enough time in the game + if (difftime(time(NULL), gameStartTime) > gameTime) { + Program *program = game->getProgram(); + Stats endStats = game->quitGame(); + if (AutoTest::wantExitGame == true) { + exitGame = true; + } + Game::exitGameState(program, endStats); + return true; + } + + return false; } void AutoTest::updateBattleEnd(Program *program) { - program->setState(new MainMenu(program)); + program->setState(new MainMenu(program)); } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/facilities/auto_test.h b/source/glest_game/facilities/auto_test.h index 73b878fc4..59f87252f 100644 --- a/source/glest_game/facilities/auto_test.h +++ b/source/glest_game/facilities/auto_test.h @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2009 Martio Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,20 +13,21 @@ #define _SHARED_UTIL_AUTO_TEST_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include -#include "randomgen.h" -#include #include "game_settings.h" #include "leak_dumper.h" +#include "randomgen.h" +#include +#include using namespace std; using Shared::Util::RandomGen; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { class Program; class MainMenu; @@ -34,43 +35,46 @@ class MenuStateScenario; class Game; // ===================================================== -// class AutoTest +// class AutoTest // /// Interface to write log files // ===================================================== -class AutoTest{ +class AutoTest { private: - int gameStartTime; - RandomGen random; - bool exitGame; - static bool wantExitGame; + int gameStartTime; + RandomGen random; + bool exitGame; + static bool wantExitGame; - static GameSettings gameSettings; - static string loadGameSettingsFile; + static GameSettings gameSettings; + static string loadGameSettingsFile; - static const time_t invalidTime; - static time_t gameTime; + static const time_t invalidTime; + static time_t gameTime; public: - static AutoTest & getInstance(); - AutoTest(); - - static void setMaxGameTime(time_t value) { gameTime = value; } - static void setWantExitGameWhenDone(bool value) { wantExitGame = value; } - static string getLoadGameSettingsFile() { return loadGameSettingsFile; } - static void setLoadGameSettingsFile(const string &filename) { loadGameSettingsFile = filename; } - - bool mustExitGame() const { return exitGame; } - - void updateIntro(Program *program); - void updateRoot(Program *program, MainMenu *mainMenu); - void updateNewGame(Program *program, MainMenu *mainMenu); - void updateScenario(MenuStateScenario *menuStateScenario); - bool updateGame(Game *game); - void updateBattleEnd(Program *program); + static AutoTest &getInstance(); + AutoTest(); + + static void setMaxGameTime(time_t value) { gameTime = value; } + static void setWantExitGameWhenDone(bool value) { wantExitGame = value; } + static string getLoadGameSettingsFile() { return loadGameSettingsFile; } + static void setLoadGameSettingsFile(const string &filename) { + loadGameSettingsFile = filename; + } + + bool mustExitGame() const { return exitGame; } + + void updateIntro(Program *program); + void updateRoot(Program *program, MainMenu *mainMenu); + void updateNewGame(Program *program, MainMenu *mainMenu); + void updateScenario(MenuStateScenario *menuStateScenario); + bool updateGame(Game *game); + void updateBattleEnd(Program *program); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/facilities/components.cpp b/source/glest_game/facilities/components.cpp index f5ab6015b..40865a85f 100644 --- a/source/glest_game/facilities/components.cpp +++ b/source/glest_game/facilities/components.cpp @@ -13,1508 +13,1596 @@ #include -#include "metrics.h" +#include "conversion.h" #include "core_data.h" +#include "gen_uuid.h" +#include "lang.h" +#include "metrics.h" #include "platform_util.h" #include "util.h" -#include "conversion.h" -#include "lang.h" -#include "gen_uuid.h" -//#include +// #include #include "leak_dumper.h" using namespace std; using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class GraphicComponent // ===================================================== -float GraphicComponent::anim= 0.f; -float GraphicComponent::fade= 0.f; -const float GraphicComponent::animSpeed= 0.02f; -const float GraphicComponent::fadeSpeed= 0.01f; +float GraphicComponent::anim = 0.f; +float GraphicComponent::fade = 0.f; +const float GraphicComponent::animSpeed = 0.02f; +const float GraphicComponent::fadeSpeed = 0.01f; // WHITE -Vec3f GraphicComponent::customTextColor = Vec3f(1.0,1.0,1.0); - -std::map > GraphicComponent::registeredGraphicComponentList; - -GraphicComponent::GraphicComponent(const std::string &containerName, const std::string &objName, bool registerControl) { - this->containerName = containerName; - this->instanceName = ""; - if(containerName == "" || objName == "") { - //char szBuf[8096]=""; - //snprintf(szBuf,8096,"Control not properly registered Container [%s] Control [%s]\n",containerName.c_str(),objName.c_str()); - //throw megaglest_runtime_error(szBuf); - } - if(objName != "" && registerControl) { - registerGraphicComponent(containerName,objName); - } - else { - this->instanceName = objName; - } - this->fontCallbackName = objName + "_" + getNewUUD(); - CoreData::getInstance().registerFontChangedCallback(this->getFontCallbackName(), this); - - enabled = true; - editable = true; - visible = true; - x = 0; - y = 0; - w = 0; - h = 0; - text = ""; - font = NULL; - font3D = NULL; - textNativeTranslation = ""; +Vec3f GraphicComponent::customTextColor = Vec3f(1.0, 1.0, 1.0); + +std::map> + GraphicComponent::registeredGraphicComponentList; + +GraphicComponent::GraphicComponent(const std::string &containerName, + const std::string &objName, + bool registerControl) { + this->containerName = containerName; + this->instanceName = ""; + if (containerName == "" || objName == "") { + // char szBuf[8096]=""; + // snprintf(szBuf,8096,"Control not properly registered Container [%s] + // Control [%s]\n",containerName.c_str(),objName.c_str()); throw + // megaglest_runtime_error(szBuf); + } + if (objName != "" && registerControl) { + registerGraphicComponent(containerName, objName); + } else { + this->instanceName = objName; + } + this->fontCallbackName = objName + "_" + getNewUUD(); + CoreData::getInstance().registerFontChangedCallback( + this->getFontCallbackName(), this); + + enabled = true; + editable = true; + visible = true; + x = 0; + y = 0; + w = 0; + h = 0; + text = ""; + font = NULL; + font3D = NULL; + textNativeTranslation = ""; } string GraphicComponent::getNewUUD() { - char uuid_str[38]; - get_uuid_string(uuid_str,sizeof(uuid_str)); - return string(uuid_str); + char uuid_str[38]; + get_uuid_string(uuid_str, sizeof(uuid_str)); + return string(uuid_str); } GraphicComponent::~GraphicComponent() { - CoreData::getInstance().unRegisterFontChangedCallback(this->getFontCallbackName()); + CoreData::getInstance().unRegisterFontChangedCallback( + this->getFontCallbackName()); } void GraphicComponent::clearRegisteredComponents(std::string containerName) { - if(containerName == "") { - GraphicComponent::registeredGraphicComponentList.clear(); - } - else { - GraphicComponent::registeredGraphicComponentList[containerName].clear(); - } -} - -void GraphicComponent::clearRegisterGraphicComponent(std::string containerName, std::string objName) { - GraphicComponent *obj = findRegisteredComponent(containerName, objName); - if(obj) { - GraphicComponent::registeredGraphicComponentList[containerName].erase(objName); - } -} - -void GraphicComponent::clearRegisterGraphicComponent(std::string containerName, std::vector objNameList) { - for(int idx = 0; idx < (int)objNameList.size(); ++idx) { - GraphicComponent::clearRegisterGraphicComponent(containerName, objNameList[idx]); - } -} - -void GraphicComponent::registerGraphicComponent(std::string containerName, std::string objName) { - // unregistered old name if we have been renamed - if(this->getInstanceName() != "") { - //printf("RENAME Register Callback detected calling: Control old [%s] new [%s]\n",this->getInstanceName().c_str(),objName.c_str()); - clearRegisterGraphicComponent(this->containerName, this->getInstanceName()); - } - else { - //printf("NEW Register Callback detected calling: Control container [%s] name [%s]\n",containerName.c_str(),objName.c_str()); - } - - if(containerName == "" || objName == "") { - //char szBuf[8096]=""; - //snprintf(szBuf,8096,"Control not properly registered Container [%s] Control [%s]\n",this->containerName.c_str(),objName.c_str()); - //throw megaglest_runtime_error(szBuf); - } - - this->containerName = containerName; - this->instanceName = objName; - registeredGraphicComponentList[containerName][objName] = this; - //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] registered [%s] [%s] count = %d\n",__FILE__,__FUNCTION__,__LINE__,containerName.c_str(),instanceName.c_str(),registeredGraphicComponentList[containerName].size()); -} - -void GraphicComponent::registerGraphicComponentOnlyFontCallbacks(std::string containerName, std::string objName) { - if(this->getInstanceName() != "") { - //printf("(FONT ONLY) RENAME Register Callback detected calling: Control old [%s] new [%s]\n",this->getInstanceName().c_str(),objName.c_str()); - clearRegisterGraphicComponent(this->containerName, this->getInstanceName()); - } - else { - //printf("(FONT ONLY) NEW Register Callback detected calling: Control container [%s] name [%s]\n",containerName.c_str(),objName.c_str()); - } - - if(containerName == "" || objName == "") { - //char szBuf[8096]=""; - //snprintf(szBuf,8096,"Control not properly registered Container [%s] Control [%s]\n",this->containerName.c_str(),objName.c_str()); - //throw megaglest_runtime_error(szBuf); - } - - this->containerName = containerName; - this->instanceName = objName; -} - -GraphicComponent * GraphicComponent::findRegisteredComponent(std::string containerName, std::string objName) { - GraphicComponent *result = NULL; - - std::map >::iterator iterFind1 = GraphicComponent::registeredGraphicComponentList.find(containerName); - if(iterFind1 != GraphicComponent::registeredGraphicComponentList.end()) { - std::map::iterator iterFind2 = iterFind1->second.find(objName); - if(iterFind2 != iterFind1->second.end()) { - result = iterFind2->second; - } - } - return result; + if (containerName == "") { + GraphicComponent::registeredGraphicComponentList.clear(); + } else { + GraphicComponent::registeredGraphicComponentList[containerName].clear(); + } +} + +void GraphicComponent::clearRegisterGraphicComponent(std::string containerName, + std::string objName) { + GraphicComponent *obj = findRegisteredComponent(containerName, objName); + if (obj) { + GraphicComponent::registeredGraphicComponentList[containerName].erase( + objName); + } +} + +void GraphicComponent::clearRegisterGraphicComponent( + std::string containerName, std::vector objNameList) { + for (int idx = 0; idx < (int)objNameList.size(); ++idx) { + GraphicComponent::clearRegisterGraphicComponent(containerName, + objNameList[idx]); + } +} + +void GraphicComponent::registerGraphicComponent(std::string containerName, + std::string objName) { + // unregistered old name if we have been renamed + if (this->getInstanceName() != "") { + // printf("RENAME Register Callback detected calling: Control old [%s] new + // [%s]\n",this->getInstanceName().c_str(),objName.c_str()); + clearRegisterGraphicComponent(this->containerName, this->getInstanceName()); + } else { + // printf("NEW Register Callback detected calling: Control container [%s] + // name [%s]\n",containerName.c_str(),objName.c_str()); + } + + if (containerName == "" || objName == "") { + // char szBuf[8096]=""; + // snprintf(szBuf,8096,"Control not properly registered Container [%s] + // Control [%s]\n",this->containerName.c_str(),objName.c_str()); throw + // megaglest_runtime_error(szBuf); + } + + this->containerName = containerName; + this->instanceName = objName; + registeredGraphicComponentList[containerName][objName] = this; + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] + // registered [%s] [%s] count = + // %d\n",__FILE__,__FUNCTION__,__LINE__,containerName.c_str(),instanceName.c_str(),registeredGraphicComponentList[containerName].size()); +} + +void GraphicComponent::registerGraphicComponentOnlyFontCallbacks( + std::string containerName, std::string objName) { + if (this->getInstanceName() != "") { + // printf("(FONT ONLY) RENAME Register Callback detected calling: Control + // old [%s] new [%s]\n",this->getInstanceName().c_str(),objName.c_str()); + clearRegisterGraphicComponent(this->containerName, this->getInstanceName()); + } else { + // printf("(FONT ONLY) NEW Register Callback detected calling: Control + // container [%s] name [%s]\n",containerName.c_str(),objName.c_str()); + } + + if (containerName == "" || objName == "") { + // char szBuf[8096]=""; + // snprintf(szBuf,8096,"Control not properly registered Container [%s] + // Control [%s]\n",this->containerName.c_str(),objName.c_str()); throw + // megaglest_runtime_error(szBuf); + } + + this->containerName = containerName; + this->instanceName = objName; +} + +GraphicComponent * +GraphicComponent::findRegisteredComponent(std::string containerName, + std::string objName) { + GraphicComponent *result = NULL; + + std::map>::iterator + iterFind1 = + GraphicComponent::registeredGraphicComponentList.find(containerName); + if (iterFind1 != GraphicComponent::registeredGraphicComponentList.end()) { + std::map::iterator iterFind2 = + iterFind1->second.find(objName); + if (iterFind2 != iterFind1->second.end()) { + result = iterFind2->second; + } + } + return result; } void GraphicComponent::applyAllCustomProperties(std::string containerName) { - Config &config = Config::getInstance(); - if( config.getBool("CustomPropertiesUsageAllowed","false")==false){ - return; - } - std::map >::iterator iterFind1 = GraphicComponent::registeredGraphicComponentList.find(containerName); - if(iterFind1 != GraphicComponent::registeredGraphicComponentList.end()) { - for(std::map::iterator iterFind2 = iterFind1->second.begin(); - iterFind2 != iterFind1->second.end(); ++iterFind2) { - iterFind2->second->applyCustomProperties(containerName); - } - } + Config &config = Config::getInstance(); + if (config.getBool("CustomPropertiesUsageAllowed", "false") == false) { + return; + } + std::map>::iterator + iterFind1 = + GraphicComponent::registeredGraphicComponentList.find(containerName); + if (iterFind1 != GraphicComponent::registeredGraphicComponentList.end()) { + for (std::map::iterator iterFind2 = + iterFind1->second.begin(); + iterFind2 != iterFind1->second.end(); ++iterFind2) { + iterFind2->second->applyCustomProperties(containerName); + } + } } void GraphicComponent::applyCustomProperties(std::string containerName) { - if(instanceName != "") { - Config &config = Config::getInstance(); - if( config.getBool("CustomPropertiesUsageAllowed","false")==false){ - return; - } - std::map >::iterator iterFind1 = GraphicComponent::registeredGraphicComponentList.find(containerName); - if(iterFind1 != GraphicComponent::registeredGraphicComponentList.end()) { - std::map::iterator iterFind2 = iterFind1->second.find(instanceName); - if(iterFind2 != iterFind1->second.end()) { - - //string languageToken = config.getString("Lang"); - string languageToken = Lang::getInstance().getLanguage(); - - //if(dynamic_cast(iterFind2->second) != NULL) { - GraphicComponent *ctl = dynamic_cast(iterFind2->second); - - // First check default overrides - ctl->x = config.getInt(containerName + "_" + iterFind2->first + "_x",intToStr(ctl->x).c_str()); - ctl->y = config.getInt(containerName + "_" + iterFind2->first + "_y",intToStr(ctl->y).c_str()); - ctl->w = config.getInt(containerName + "_" + iterFind2->first + "_w",intToStr(ctl->w).c_str()); - ctl->h = config.getInt(containerName + "_" + iterFind2->first + "_h",intToStr(ctl->h).c_str()); - ctl->visible = config.getBool(containerName + "_" + iterFind2->first + "_visible",boolToStr(ctl->visible).c_str()); - - // Now check language specific overrides - ctl->x = config.getInt(containerName + "_" + iterFind2->first + "_x_" + languageToken, intToStr(ctl->x).c_str()); - ctl->y = config.getInt(containerName + "_" + iterFind2->first + "_y_" + languageToken, intToStr(ctl->y).c_str()); - ctl->w = config.getInt(containerName + "_" + iterFind2->first + "_w_" + languageToken, intToStr(ctl->w).c_str()); - ctl->h = config.getInt(containerName + "_" + iterFind2->first + "_h_" + languageToken, intToStr(ctl->h).c_str()); - ctl->visible = config.getBool(containerName + "_" + iterFind2->first + "_visible_" + languageToken,boolToStr(ctl->visible).c_str()); - } - } - } + if (instanceName != "") { + Config &config = Config::getInstance(); + if (config.getBool("CustomPropertiesUsageAllowed", "false") == false) { + return; + } + std::map>::iterator + iterFind1 = GraphicComponent::registeredGraphicComponentList.find( + containerName); + if (iterFind1 != GraphicComponent::registeredGraphicComponentList.end()) { + std::map::iterator iterFind2 = + iterFind1->second.find(instanceName); + if (iterFind2 != iterFind1->second.end()) { + + // string languageToken = config.getString("Lang"); + string languageToken = Lang::getInstance().getLanguage(); + + // if(dynamic_cast(iterFind2->second) != NULL) { + GraphicComponent *ctl = + dynamic_cast(iterFind2->second); + + // First check default overrides + ctl->x = config.getInt(containerName + "_" + iterFind2->first + "_x", + intToStr(ctl->x).c_str()); + ctl->y = config.getInt(containerName + "_" + iterFind2->first + "_y", + intToStr(ctl->y).c_str()); + ctl->w = config.getInt(containerName + "_" + iterFind2->first + "_w", + intToStr(ctl->w).c_str()); + ctl->h = config.getInt(containerName + "_" + iterFind2->first + "_h", + intToStr(ctl->h).c_str()); + ctl->visible = + config.getBool(containerName + "_" + iterFind2->first + "_visible", + boolToStr(ctl->visible).c_str()); + + // Now check language specific overrides + ctl->x = config.getInt(containerName + "_" + iterFind2->first + "_x_" + + languageToken, + intToStr(ctl->x).c_str()); + ctl->y = config.getInt(containerName + "_" + iterFind2->first + "_y_" + + languageToken, + intToStr(ctl->y).c_str()); + ctl->w = config.getInt(containerName + "_" + iterFind2->first + "_w_" + + languageToken, + intToStr(ctl->w).c_str()); + ctl->h = config.getInt(containerName + "_" + iterFind2->first + "_h_" + + languageToken, + intToStr(ctl->h).c_str()); + ctl->visible = config.getBool(containerName + "_" + iterFind2->first + + "_visible_" + languageToken, + boolToStr(ctl->visible).c_str()); + } + } + } } bool GraphicComponent::saveAllCustomProperties(std::string containerName) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] registered [%s] count = %d\n",__FILE__,__FUNCTION__,__LINE__,containerName.c_str(),registeredGraphicComponentList[containerName].size()); - Config &config = Config::getInstance(); - if( config.getBool("CustomPropertiesSaveAllowed","false")==false){ - return false; - } - bool foundPropertiesToSave = false; - std::map >::iterator iterFind1 = GraphicComponent::registeredGraphicComponentList.find(containerName); - if(iterFind1 != GraphicComponent::registeredGraphicComponentList.end()) { - for(std::map::iterator iterFind2 = iterFind1->second.begin(); - iterFind2 != iterFind1->second.end(); ++iterFind2) { - bool saved = iterFind2->second->saveCustomProperties(containerName); - foundPropertiesToSave = (saved || foundPropertiesToSave); - } - } - - if(foundPropertiesToSave == true) { - Config &config = Config::getInstance(); - config.save(); - } - - return foundPropertiesToSave; + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] registered [%s] count = %d\n", __FILE__, + __FUNCTION__, __LINE__, containerName.c_str(), + registeredGraphicComponentList[containerName].size()); + Config &config = Config::getInstance(); + if (config.getBool("CustomPropertiesSaveAllowed", "false") == false) { + return false; + } + bool foundPropertiesToSave = false; + std::map>::iterator + iterFind1 = + GraphicComponent::registeredGraphicComponentList.find(containerName); + if (iterFind1 != GraphicComponent::registeredGraphicComponentList.end()) { + for (std::map::iterator iterFind2 = + iterFind1->second.begin(); + iterFind2 != iterFind1->second.end(); ++iterFind2) { + bool saved = iterFind2->second->saveCustomProperties(containerName); + foundPropertiesToSave = (saved || foundPropertiesToSave); + } + } + + if (foundPropertiesToSave == true) { + Config &config = Config::getInstance(); + config.save(); + } + + return foundPropertiesToSave; } bool GraphicComponent::saveCustomProperties(std::string containerName) { - bool savedChange = false; - if(instanceName != "") { - Config &config = Config::getInstance(); - if( config.getBool("CustomPropertiesSaveAllowed","false")==false){ - return false; - } - - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] looking for [%s] [%s]\n",__FILE__,__FUNCTION__,__LINE__,containerName.c_str(),instanceName.c_str()); - - std::map >::iterator iterFind1 = GraphicComponent::registeredGraphicComponentList.find(containerName); - if(iterFind1 != GraphicComponent::registeredGraphicComponentList.end()) { - - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] looking for [%s]\n",__FILE__,__FUNCTION__,__LINE__,instanceName.c_str()); - - std::map::iterator iterFind2 = iterFind1->second.find(instanceName); - if(iterFind2 != iterFind1->second.end()) { - - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] FOUND [%s]\n",__FILE__,__FUNCTION__,__LINE__,instanceName.c_str()); - - //string languageToken = config.getString("Lang"); - - //if(dynamic_cast(iterFind2->second) != NULL) { - GraphicComponent *ctl = dynamic_cast(iterFind2->second); - - // First check default overrides - config.setInt(containerName + "_" + iterFind2->first + "_x",ctl->x); - config.setInt(containerName + "_" + iterFind2->first + "_y",ctl->y); - config.setInt(containerName + "_" + iterFind2->first + "_w",ctl->w); - config.setInt(containerName + "_" + iterFind2->first + "_h",ctl->h); - - savedChange = true; - // Now check language specific overrides - //ctl->x = config.getInt(containerName + "_" + iterFind2->first + "_x_" + languageToken, intToStr(ctl->x).c_str()); - //ctl->y = config.getInt(containerName + "_" + iterFind2->first + "_y_" + languageToken, intToStr(ctl->y).c_str()); - //ctl->w = config.getInt(containerName + "_" + iterFind2->first + "_w_" + languageToken, intToStr(ctl->w).c_str()); - //ctl->h = config.getInt(containerName + "_" + iterFind2->first + "_h_" + languageToken, intToStr(ctl->h).c_str()); - - //} - } - } - } - - return savedChange; -} - -void GraphicComponent::setFont(Font2D *font) { - this->font = font; - if (this->font != NULL) { - this->font2DUniqueId = font->getFontUniqueId(); - } - else { - this->font2DUniqueId = ""; - } -} - -void GraphicComponent::setFont3D(Font3D *font) { - this->font3D = font; - if (this->font3D != NULL) { - this->font3DUniqueId = font->getFontUniqueId(); - } - else { - this->font3DUniqueId = ""; - } -} - -void GraphicComponent::FontChangedCallback(std::string fontUniqueId, Font *font) { - //printf("In FontChanged for [%s] font [%p] Control 2D [%s] 3D [%s]\n", fontUniqueId.c_str(),font,this->font2DUniqueId.c_str(),this->font3DUniqueId.c_str()); - if (fontUniqueId != "") { - if (fontUniqueId == this->font2DUniqueId) { - if (font != NULL) { - this->font = (Font2D *)font; - } - else { - this->font = NULL; - } - } - else if (fontUniqueId == this->font3DUniqueId) { - if (font != NULL) { - this->font3D = (Font3D *)font; - } - else { - this->font3D = NULL; - } - } - } -} + bool savedChange = false; + if (instanceName != "") { + Config &config = Config::getInstance(); + if (config.getBool("CustomPropertiesSaveAllowed", "false") == false) { + return false; + } -void GraphicComponent::reloadFonts() { - setFont(CoreData::getInstance().getMenuFontNormal()); - setFont3D(CoreData::getInstance().getMenuFontNormal3D()); + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] looking for [%s] [%s]\n", + __FILE__, __FUNCTION__, __LINE__, + containerName.c_str(), instanceName.c_str()); + + std::map>::iterator + iterFind1 = GraphicComponent::registeredGraphicComponentList.find( + containerName); + if (iterFind1 != GraphicComponent::registeredGraphicComponentList.end()) { + + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d] looking for [%s]\n", + __FILE__, __FUNCTION__, __LINE__, instanceName.c_str()); + + std::map::iterator iterFind2 = + iterFind1->second.find(instanceName); + if (iterFind2 != iterFind1->second.end()) { + + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] FOUND [%s]\n", __FILE__, + __FUNCTION__, __LINE__, instanceName.c_str()); + + // string languageToken = config.getString("Lang"); + + // if(dynamic_cast(iterFind2->second) != NULL) { + GraphicComponent *ctl = + dynamic_cast(iterFind2->second); + + // First check default overrides + config.setInt(containerName + "_" + iterFind2->first + "_x", ctl->x); + config.setInt(containerName + "_" + iterFind2->first + "_y", ctl->y); + config.setInt(containerName + "_" + iterFind2->first + "_w", ctl->w); + config.setInt(containerName + "_" + iterFind2->first + "_h", ctl->h); + + savedChange = true; + // Now check language specific overrides + // ctl->x = config.getInt(containerName + "_" + iterFind2->first + "_x_" + // + languageToken, intToStr(ctl->x).c_str()); ctl->y = + // config.getInt(containerName + "_" + iterFind2->first + "_y_" + + // languageToken, intToStr(ctl->y).c_str()); ctl->w = + // config.getInt(containerName + "_" + iterFind2->first + "_w_" + + // languageToken, intToStr(ctl->w).c_str()); ctl->h = + // config.getInt(containerName + "_" + iterFind2->first + "_h_" + + // languageToken, intToStr(ctl->h).c_str()); + + //} + } + } + } + + return savedChange; +} + +void GraphicComponent::setFont(Font2D *font) { + this->font = font; + if (this->font != NULL) { + this->font2DUniqueId = font->getFontUniqueId(); + } else { + this->font2DUniqueId = ""; + } +} + +void GraphicComponent::setFont3D(Font3D *font) { + this->font3D = font; + if (this->font3D != NULL) { + this->font3DUniqueId = font->getFontUniqueId(); + } else { + this->font3DUniqueId = ""; + } +} + +void GraphicComponent::FontChangedCallback(std::string fontUniqueId, + Font *font) { + // printf("In FontChanged for [%s] font [%p] Control 2D [%s] 3D [%s]\n", + // fontUniqueId.c_str(),font,this->font2DUniqueId.c_str(),this->font3DUniqueId.c_str()); + if (fontUniqueId != "") { + if (fontUniqueId == this->font2DUniqueId) { + if (font != NULL) { + this->font = (Font2D *)font; + } else { + this->font = NULL; + } + } else if (fontUniqueId == this->font3DUniqueId) { + if (font != NULL) { + this->font3D = (Font3D *)font; + } else { + this->font3D = NULL; + } + } + } } -void GraphicComponent::reloadFontsForRegisterGraphicComponents(std::string containerName) { - std::map >::iterator iterFind1 = GraphicComponent::registeredGraphicComponentList.find(containerName); - if(iterFind1 != GraphicComponent::registeredGraphicComponentList.end()) { - for(std::map::iterator iterFind2 = iterFind1->second.begin(); - iterFind2 != iterFind1->second.end(); ++iterFind2) { - GraphicComponent *ctl = dynamic_cast(iterFind2->second); - if(ctl) { - ctl->reloadFonts(); - } - } - } +void GraphicComponent::reloadFonts() { + setFont(CoreData::getInstance().getMenuFontNormal()); + setFont3D(CoreData::getInstance().getMenuFontNormal3D()); +} + +void GraphicComponent::reloadFontsForRegisterGraphicComponents( + std::string containerName) { + std::map>::iterator + iterFind1 = + GraphicComponent::registeredGraphicComponentList.find(containerName); + if (iterFind1 != GraphicComponent::registeredGraphicComponentList.end()) { + for (std::map::iterator iterFind2 = + iterFind1->second.begin(); + iterFind2 != iterFind1->second.end(); ++iterFind2) { + GraphicComponent *ctl = + dynamic_cast(iterFind2->second); + if (ctl) { + ctl->reloadFonts(); + } + } + } } void GraphicComponent::init(int x, int y, int w, int h) { - this->x= x; - this->y= y; - this->w= w; - this->h= h; - reloadFonts(); - enabled= true; + this->x = x; + this->y = y; + this->w = w; + this->h = h; + reloadFonts(); + enabled = true; } -bool GraphicComponent::eventMouseWheel(int x, int y,int zDelta){ - return mouseMove(x,y); +bool GraphicComponent::eventMouseWheel(int x, int y, int zDelta) { + return mouseMove(x, y); } bool GraphicComponent::mouseMove(int x, int y) { - if(this->getVisible() == false) { - return false; - } + if (this->getVisible() == false) { + return false; + } - return - x > this->x && - y > this->y && - x < this->x + w && - y < this->y + h; + return x > this->x && y > this->y && x < this->x + w && y < this->y + h; } -bool GraphicComponent::mouseClick(int x, int y){ - if(getVisible() && getEnabled() && getEditable()) - return mouseMove(x, y); - else - return false; +bool GraphicComponent::mouseClick(int x, int y) { + if (getVisible() && getEnabled() && getEditable()) + return mouseMove(x, y); + else + return false; } -void GraphicComponent::update(){ - fade+= fadeSpeed; - anim+= animSpeed; - if(fade>1.f) fade= 1.f; - if(anim>1.f) anim= 0.f; +void GraphicComponent::update() { + fade += fadeSpeed; + anim += animSpeed; + if (fade > 1.f) + fade = 1.f; + if (anim > 1.f) + anim = 0.f; } -void GraphicComponent::resetFade(){ - fade= 0.f; -} +void GraphicComponent::resetFade() { fade = 0.f; } // ===================================================== // class GraphicLabel // ===================================================== -const int GraphicLabel::defH= 20; -const int GraphicLabel::defW= 70; - -GraphicLabel::GraphicLabel(const std::string &containerName, const std::string &objName, bool registerControl) : - GraphicComponent(containerName, objName, registerControl) { - centered = false; - wordWrap = false; - centeredW = -1; - centeredH = 1; - editable = false; - editModeEnabled = false; - maxEditWidth = -1; - maxEditRenderWidth = -1; - renderBackground = false; - backgroundColor=Vec4f(0.2f,0.2f,0.2f,0.6f); - isPassword = false; - texture = NULL; -} - -void GraphicLabel::init(int x, int y, int w, int h, bool centered, Vec3f textColor, bool wordWrap) { - GraphicComponent::init(x, y, w, h); - this->centered= centered; - this->textColor=textColor; - this->wordWrap = wordWrap; +const int GraphicLabel::defH = 20; +const int GraphicLabel::defW = 70; + +GraphicLabel::GraphicLabel(const std::string &containerName, + const std::string &objName, bool registerControl) + : GraphicComponent(containerName, objName, registerControl) { + centered = false; + wordWrap = false; + centeredW = -1; + centeredH = 1; + editable = false; + editModeEnabled = false; + maxEditWidth = -1; + maxEditRenderWidth = -1; + renderBackground = false; + backgroundColor = Vec4f(0.2f, 0.2f, 0.2f, 0.6f); + isPassword = false; + texture = NULL; +} + +void GraphicLabel::init(int x, int y, int w, int h, bool centered, + Vec3f textColor, bool wordWrap) { + GraphicComponent::init(x, y, w, h); + this->centered = centered; + this->textColor = textColor; + this->wordWrap = wordWrap; } bool GraphicLabel::mouseMove(int x, int y) { - if(this->getVisible() == false) { - return false; - } + if (this->getVisible() == false) { + return false; + } - int useWidth = w; - if(text.length() > 0 && font3D != NULL) { - float lineWidth = (font3D->getTextHandler()->Advance(text.c_str()) * Shared::Graphics::Font::scaleFontValue); - useWidth = (int)lineWidth; - } + int useWidth = w; + if (text.length() > 0 && font3D != NULL) { + float lineWidth = (font3D->getTextHandler()->Advance(text.c_str()) * + Shared::Graphics::Font::scaleFontValue); + useWidth = (int)lineWidth; + } - if(editable && useWidth this->x && - y > this->y && - x < this->x + useWidth && - y < this->y + h; + return x > this->x && y > this->y && x < this->x + useWidth && + y < this->y + h; } bool GraphicLabel::getCenteredW() const { - bool result = (centered || centeredW == 1); - return result; + bool result = (centered || centeredW == 1); + return result; } -//void GraphicLabel::setCenteredW(bool centered) { +// void GraphicLabel::setCenteredW(bool centered) { // centeredW = (centered ? 1 : 0); -//} +// } bool GraphicLabel::getCenteredH() const { - bool result = (centered || centeredH == 1); - return result; + bool result = (centered || centeredH == 1); + return result; } -//void GraphicLabel::setCenteredH(bool centered) { +// void GraphicLabel::setCenteredH(bool centered) { // centeredH = (centered ? 1 : 0); -//} +// } // ===================================================== // class GraphicButton // ===================================================== -const int GraphicButton::defH= 22; -const int GraphicButton::defW= 90; +const int GraphicButton::defH = 22; +const int GraphicButton::defW = 90; -GraphicButton::GraphicButton(const std::string &containerName, const std::string &objName, bool registerControl) : - GraphicComponent(containerName,objName,registerControl) { +GraphicButton::GraphicButton(const std::string &containerName, + const std::string &objName, bool registerControl) + : GraphicComponent(containerName, objName, registerControl) { - lighted = false; - alwaysLighted = false; - useCustomTexture = false; - customTexture = NULL; + lighted = false; + alwaysLighted = false; + useCustomTexture = false; + customTexture = NULL; } -void GraphicButton::init(int x, int y, int w, int h){ - GraphicComponent::init(x, y, w, h); - lighted= false; +void GraphicButton::init(int x, int y, int w, int h) { + GraphicComponent::init(x, y, w, h); + lighted = false; } -bool GraphicButton::mouseMove(int x, int y){ - if(this->getVisible() == false) { - return false; - } +bool GraphicButton::mouseMove(int x, int y) { + if (this->getVisible() == false) { + return false; + } - bool b= GraphicComponent::mouseMove(x, y); - lighted= b; - return b; + bool b = GraphicComponent::mouseMove(x, y); + lighted = b; + return b; } // ===================================================== // class GraphicListBox // ===================================================== -const int GraphicListBox::defH= 22; -const int GraphicListBox::defW= 140; - -GraphicListBox::GraphicListBox(const std::string &containerName, const std::string &objName) -: GraphicComponent(containerName, objName), graphButton1(containerName, objName + "_button1"), - graphButton2(containerName, objName + "_button2") { - selectedItemIndex = 0; - lighted = false; - leftControlled = false; -} - -void GraphicListBox::init(int x, int y, int w, int h, Vec3f textColor){ - GraphicComponent::init(x, y, w, h); - - this->textColor=textColor; - graphButton1.init(x, y, h, h); - graphButton2.init(x+w-h, y, h, h); - graphButton1.setText("<"); - graphButton2.setText(">"); - selectedItemIndex=-1; - lighted=false; -} - -const string & GraphicListBox::getTextNativeTranslation() { - if(this->translated_items.empty() == true || - this->selectedItemIndex < 0 || - this->selectedItemIndex >= (int)this->translated_items.size() || - this->items.size() != this->translated_items.size()) { - return this->text; - } - else { - return this->translated_items[this->selectedItemIndex]; - } -} - -//queryes -void GraphicListBox::pushBackItem(string item, string translated_item){ - items.push_back(item); - translated_items.push_back(translated_item); - setSelectedItemIndex(0); +const int GraphicListBox::defH = 22; +const int GraphicListBox::defW = 140; + +GraphicListBox::GraphicListBox(const std::string &containerName, + const std::string &objName) + : GraphicComponent(containerName, objName), + graphButton1(containerName, objName + "_button1"), + graphButton2(containerName, objName + "_button2") { + selectedItemIndex = 0; + lighted = false; + leftControlled = false; } -void GraphicListBox::clearItems(){ - items.clear(); - translated_items.clear(); - selectedItemIndex=-1; - setText(""); +void GraphicListBox::init(int x, int y, int w, int h, Vec3f textColor) { + GraphicComponent::init(x, y, w, h); + + this->textColor = textColor; + graphButton1.init(x, y, h, h); + graphButton2.init(x + w - h, y, h, h); + graphButton1.setText("<"); + graphButton2.setText(">"); + selectedItemIndex = -1; + lighted = false; } +const string &GraphicListBox::getTextNativeTranslation() { + if (this->translated_items.empty() == true || this->selectedItemIndex < 0 || + this->selectedItemIndex >= (int)this->translated_items.size() || + this->items.size() != this->translated_items.size()) { + return this->text; + } else { + return this->translated_items[this->selectedItemIndex]; + } +} -void GraphicListBox::setItems(const vector &items, const vector translated_items){ - this->items= items; - this->translated_items = translated_items; - if(items.empty() == false) { - setSelectedItemIndex(0); - } - else { - selectedItemIndex=-1; - setText(""); - } +// queryes +void GraphicListBox::pushBackItem(string item, string translated_item) { + items.push_back(item); + translated_items.push_back(translated_item); + setSelectedItemIndex(0); } -void GraphicListBox::setSelectedItemIndex(int index, bool errorOnMissing){ - if(errorOnMissing == true && (index < 0 || index >= (int)items.size())) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Index not found in listbox name: [%s] value index: %d size: %lu",this->instanceName.c_str(),index,(unsigned long)items.size()); - throw megaglest_runtime_error(szBuf); - } - selectedItemIndex= index; - setText(getSelectedItem()); +void GraphicListBox::clearItems() { + items.clear(); + translated_items.clear(); + selectedItemIndex = -1; + setText(""); +} + +void GraphicListBox::setItems(const vector &items, + const vector translated_items) { + this->items = items; + this->translated_items = translated_items; + if (items.empty() == false) { + setSelectedItemIndex(0); + } else { + selectedItemIndex = -1; + setText(""); + } +} + +void GraphicListBox::setSelectedItemIndex(int index, bool errorOnMissing) { + if (errorOnMissing == true && (index < 0 || index >= (int)items.size())) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "Index not found in listbox name: [%s] value index: %d size: %lu", + this->instanceName.c_str(), index, (unsigned long)items.size()); + throw megaglest_runtime_error(szBuf); + } + selectedItemIndex = index; + setText(getSelectedItem()); } void GraphicListBox::setLeftControlled(bool leftControlled) { - if(this->leftControlled!=leftControlled){ - this->leftControlled= leftControlled; - if(leftControlled==true) { - graphButton2.setX(x+graphButton1.getW()-4); - graphButton2.setH(graphButton2.getH()-4); - graphButton2.setW(graphButton2.getW()-4); - graphButton1.setH(graphButton1.getH()-4); - graphButton1.setW(graphButton1.getW()-4); - graphButton2.setY(graphButton2.getY()+2); - graphButton1.setY(graphButton1.getY()+2); - } - else { - graphButton2.setX(x+w-graphButton2.getW()+4); - graphButton2.setH(graphButton2.getH()+4); - graphButton2.setW(graphButton2.getW()+4); - graphButton1.setH(graphButton1.getH()+4); - graphButton1.setW(graphButton1.getW()+4); - graphButton2.setY(graphButton2.getY()-2); - graphButton1.setY(graphButton1.getY()-2); - } - } + if (this->leftControlled != leftControlled) { + this->leftControlled = leftControlled; + if (leftControlled == true) { + graphButton2.setX(x + graphButton1.getW() - 4); + graphButton2.setH(graphButton2.getH() - 4); + graphButton2.setW(graphButton2.getW() - 4); + graphButton1.setH(graphButton1.getH() - 4); + graphButton1.setW(graphButton1.getW() - 4); + graphButton2.setY(graphButton2.getY() + 2); + graphButton1.setY(graphButton1.getY() + 2); + } else { + graphButton2.setX(x + w - graphButton2.getW() + 4); + graphButton2.setH(graphButton2.getH() + 4); + graphButton2.setW(graphButton2.getW() + 4); + graphButton1.setH(graphButton1.getH() + 4); + graphButton1.setW(graphButton1.getW() + 4); + graphButton2.setY(graphButton2.getY() - 2); + graphButton1.setY(graphButton1.getY() - 2); + } + } } void GraphicListBox::setX(int x) { - this->x= x; - graphButton1.setX(x); - if(leftControlled==true) { - graphButton2.setX(x+graphButton1.getW()); - } - else { - graphButton2.setX(x+w-graphButton2.getW()); - } + this->x = x; + graphButton1.setX(x); + if (leftControlled == true) { + graphButton2.setX(x + graphButton1.getW()); + } else { + graphButton2.setX(x + w - graphButton2.getW()); + } } void GraphicListBox::setY(int y) { - this->y= y; - graphButton1.setY(y); - graphButton2.setY(y); + this->y = y; + graphButton1.setY(y); + graphButton2.setY(y); } -void GraphicListBox::setEditable(bool editable){ - graphButton1.setEditable(editable); - graphButton2.setEditable(editable); - GraphicComponent::setEditable(editable); +void GraphicListBox::setEditable(bool editable) { + graphButton1.setEditable(editable); + graphButton2.setEditable(editable); + GraphicComponent::setEditable(editable); } bool GraphicListBox::hasItem(string item) const { - bool result = false; - vector::const_iterator iter= find(items.begin(), items.end(), item); - if(iter != items.end()) { - result = true; - } - - return result; -} - -void GraphicListBox::setSelectedItem(string item, bool errorOnMissing){ - vector::iterator iter; - - iter= find(items.begin(), items.end(), item); - - if(iter==items.end()) { - if(errorOnMissing == true) { - for(int idx = 0; idx < (int)items.size(); idx++) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\ninstanceName [%s] idx = %d items[idx] = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,instanceName.c_str(),idx,items[idx].c_str()); - } - - char szBuf[8096]=""; - snprintf(szBuf,8096,"Value not found in listbox name: [%s] value: %s",this->instanceName.c_str(),item.c_str()); - throw megaglest_runtime_error(szBuf); - } - } - else { - setSelectedItemIndex(iter-items.begin()); - } - -} - -bool GraphicListBox::mouseMove(int x, int y){ - if(this->getVisible() == false) { - return false; - } - - return - graphButton1.mouseMove(x, y) || - graphButton2.mouseMove(x, y); -} - -bool GraphicListBox::mouseClick(int x, int y,string advanceToItemStartingWith) { - if(this->getVisible() == false) { - return false; - } - - if(!items.empty()) { - bool b1= graphButton1.mouseClick(x, y); - bool b2= graphButton2.mouseClick(x, y); - - if(b1) { - bool bFound = false; - if(advanceToItemStartingWith != "") { - for(int i = selectedItemIndex - 1; i >= 0; --i) { - string item = items[i]; - if((int)translated_items.size() > i) item = translated_items[i]; - if(StartsWith(toLower(item),toLower(advanceToItemStartingWith)) == true) { - bFound = true; - selectedItemIndex = i; - break; - } - } - if(bFound == false) { - for(int i = (int)items.size() - 1; i >= selectedItemIndex; --i) { - string item = items[i]; - if((int)translated_items.size() > i) item = translated_items[i]; - //printf("Trying to match [%s] with item [%s]\n",advanceToItemStartingWith.c_str(),item.c_str()); - if(StartsWith(toLower(item),toLower(advanceToItemStartingWith)) == true) { - bFound = true; - selectedItemIndex = i; - break; - } - } - } - } - if(bFound == false) { - selectedItemIndex--; - } - if(selectedItemIndex<0){ - selectedItemIndex = (int)items.size()-1; - } - } - else if(b2) { - bool bFound = false; - if(advanceToItemStartingWith != "") { - for(int i = selectedItemIndex + 1; i < (int)items.size(); ++i) { - string item = items[i]; - if((int)translated_items.size() > i) item = translated_items[i]; - //printf("Trying to match [%s] with item [%s]\n",advanceToItemStartingWith.c_str(),item.c_str()); - if(StartsWith(toLower(item),toLower(advanceToItemStartingWith)) == true) { - bFound = true; - selectedItemIndex = i; - break; - } - } - if(bFound == false) { - for(int i = 0; i <= selectedItemIndex; ++i) { - string item = items[i]; - if((int)translated_items.size() > i) item = translated_items[i]; - //printf("Trying to match [%s] with item [%s]\n",advanceToItemStartingWith.c_str(),item.c_str()); - if(StartsWith(toLower(item),toLower(advanceToItemStartingWith)) == true) { - bFound = true; - selectedItemIndex = i; - break; - } - } - } - } - if(bFound == false) { - selectedItemIndex++; - } - if(selectedItemIndex >= (int)items.size()) { - selectedItemIndex=0; - } - } - setText(getSelectedItem()); - - return b1 || b2; - } - return false; + bool result = false; + vector::const_iterator iter = find(items.begin(), items.end(), item); + if (iter != items.end()) { + result = true; + } + + return result; +} + +void GraphicListBox::setSelectedItem(string item, bool errorOnMissing) { + vector::iterator iter; + + iter = find(items.begin(), items.end(), item); + + if (iter == items.end()) { + if (errorOnMissing == true) { + for (int idx = 0; idx < (int)items.size(); idx++) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d]\ninstanceName [%s] idx " + "= %d items[idx] = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, instanceName.c_str(), + idx, items[idx].c_str()); + } + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "Value not found in listbox name: [%s] value: %s", + this->instanceName.c_str(), item.c_str()); + throw megaglest_runtime_error(szBuf); + } + } else { + setSelectedItemIndex(iter - items.begin()); + } +} + +bool GraphicListBox::mouseMove(int x, int y) { + if (this->getVisible() == false) { + return false; + } + + return graphButton1.mouseMove(x, y) || graphButton2.mouseMove(x, y); +} + +bool GraphicListBox::mouseClick(int x, int y, + string advanceToItemStartingWith) { + if (this->getVisible() == false) { + return false; + } + + if (!items.empty()) { + bool b1 = graphButton1.mouseClick(x, y); + bool b2 = graphButton2.mouseClick(x, y); + + if (b1) { + bool bFound = false; + if (advanceToItemStartingWith != "") { + for (int i = selectedItemIndex - 1; i >= 0; --i) { + string item = items[i]; + if ((int)translated_items.size() > i) + item = translated_items[i]; + if (StartsWith(toLower(item), toLower(advanceToItemStartingWith)) == + true) { + bFound = true; + selectedItemIndex = i; + break; + } + } + if (bFound == false) { + for (int i = (int)items.size() - 1; i >= selectedItemIndex; --i) { + string item = items[i]; + if ((int)translated_items.size() > i) + item = translated_items[i]; + // printf("Trying to match [%s] with item + // [%s]\n",advanceToItemStartingWith.c_str(),item.c_str()); + if (StartsWith(toLower(item), toLower(advanceToItemStartingWith)) == + true) { + bFound = true; + selectedItemIndex = i; + break; + } + } + } + } + if (bFound == false) { + selectedItemIndex--; + } + if (selectedItemIndex < 0) { + selectedItemIndex = (int)items.size() - 1; + } + } else if (b2) { + bool bFound = false; + if (advanceToItemStartingWith != "") { + for (int i = selectedItemIndex + 1; i < (int)items.size(); ++i) { + string item = items[i]; + if ((int)translated_items.size() > i) + item = translated_items[i]; + // printf("Trying to match [%s] with item + // [%s]\n",advanceToItemStartingWith.c_str(),item.c_str()); + if (StartsWith(toLower(item), toLower(advanceToItemStartingWith)) == + true) { + bFound = true; + selectedItemIndex = i; + break; + } + } + if (bFound == false) { + for (int i = 0; i <= selectedItemIndex; ++i) { + string item = items[i]; + if ((int)translated_items.size() > i) + item = translated_items[i]; + // printf("Trying to match [%s] with item + // [%s]\n",advanceToItemStartingWith.c_str(),item.c_str()); + if (StartsWith(toLower(item), toLower(advanceToItemStartingWith)) == + true) { + bFound = true; + selectedItemIndex = i; + break; + } + } + } + } + if (bFound == false) { + selectedItemIndex++; + } + if (selectedItemIndex >= (int)items.size()) { + selectedItemIndex = 0; + } + } + setText(getSelectedItem()); + + return b1 || b2; + } + return false; } // ===================================================== // class GraphicComboBox // ===================================================== -const int GraphicComboBox::defH= 22; -const int GraphicComboBox::defW= 140; - -GraphicComboBox::GraphicComboBox(const std::string &containerName, const std::string &objName) -: GraphicComponent(containerName, objName), dropDownButton(containerName, objName + "_button") { - selectedItemIndex = 0; - lighted = false; -} - -void GraphicComboBox::init(int x, int y, int w, int h, Vec3f textColor){ - GraphicComponent::init(x, y, w, h); - - this->textColor=textColor; - dropDownButton.init(x+w-h, y, h, h); - dropDownButton.setText("v"); - - popupLineCount=15; - popupButtonHeight=20; - - int scrollBarLength=popupLineCount*popupButtonHeight; - int popupYpos=y+h; - if( y>200) popupYpos=y-scrollBarLength; - scrollBar.init(x+w-h,popupYpos,false,scrollBarLength,20); - scrollBar.setVisibleSize(popupLineCount); - scrollBar.setVisibleStart(0); - scrollBar.setLighted(false); - scrollBar.setVisible(true); - setPopupLineCount(popupLineCount); - - selectedItemIndex=-1; - popupShowing=false; - lighted=false; - preselectedItemIndex=-1; -} - -void GraphicComboBox::setPopupLineCount(int popupLineCount) { - this->popupLineCount = popupLineCount; - int scrollBarLength=popupLineCount*popupButtonHeight; - int popupYpos=getY()+getH(); - if( y>200) popupYpos=y-scrollBarLength; - scrollBar.setY(popupYpos); - scrollBar.setLength(scrollBarLength); - scrollBar.setVisibleSize(popupLineCount); - } - -const string & GraphicComboBox::getTextNativeTranslation(int index) { - if(this->translated_items.empty() == true || - index < 0 || - index >= (int)this->translated_items.size() || - this->items.size() != this->translated_items.size()) { - return this->text; - } - else { - return this->translated_items[index]; - } -} - -const string & GraphicComboBox::getTextNativeTranslation() { - return getTextNativeTranslation(this->selectedItemIndex); -} - -//queryes -void GraphicComboBox::pushBackItem(string item, string translated_item){ - items.push_back(item); - translated_items.push_back(translated_item); - setSelectedItemIndex(0); - createButton(item); -} - -void GraphicComboBox::clearItems(){ - clearButtons(); - items.clear(); - translated_items.clear(); - selectedItemIndex=-1; - setText(""); -} - -GraphicButton* GraphicComboBox::createButton(string item) { - GraphicButton *button = new GraphicButton(); - button->init(getX(), scrollBar.getY(), getW()-scrollBar.getW(), getPopupButtonHeight()); - button->setText(item); - button->setUseCustomTexture(true); - button->setCustomTexture(CoreData::getInstance().getCustomTexture()); - popupButtons.push_back(button); - scrollBar.setElementCount((int)popupButtons.size()); - layoutButtons(); - return button; +const int GraphicComboBox::defH = 22; +const int GraphicComboBox::defW = 140; + +GraphicComboBox::GraphicComboBox(const std::string &containerName, + const std::string &objName) + : GraphicComponent(containerName, objName), + dropDownButton(containerName, objName + "_button") { + selectedItemIndex = 0; + lighted = false; +} + +void GraphicComboBox::init(int x, int y, int w, int h, Vec3f textColor) { + GraphicComponent::init(x, y, w, h); + + this->textColor = textColor; + dropDownButton.init(x + w - h, y, h, h); + dropDownButton.setText("v"); + + popupLineCount = 15; + popupButtonHeight = 20; + + int scrollBarLength = popupLineCount * popupButtonHeight; + int popupYpos = y + h; + if (y > 200) + popupYpos = y - scrollBarLength; + scrollBar.init(x + w - h, popupYpos, false, scrollBarLength, 20); + scrollBar.setVisibleSize(popupLineCount); + scrollBar.setVisibleStart(0); + scrollBar.setLighted(false); + scrollBar.setVisible(true); + setPopupLineCount(popupLineCount); + + selectedItemIndex = -1; + popupShowing = false; + lighted = false; + preselectedItemIndex = -1; +} + +void GraphicComboBox::setPopupLineCount(int popupLineCount) { + this->popupLineCount = popupLineCount; + int scrollBarLength = popupLineCount * popupButtonHeight; + int popupYpos = getY() + getH(); + if (y > 200) + popupYpos = y - scrollBarLength; + scrollBar.setY(popupYpos); + scrollBar.setLength(scrollBarLength); + scrollBar.setVisibleSize(popupLineCount); +} + +const string &GraphicComboBox::getTextNativeTranslation(int index) { + if (this->translated_items.empty() == true || index < 0 || + index >= (int)this->translated_items.size() || + this->items.size() != this->translated_items.size()) { + return this->text; + } else { + return this->translated_items[index]; + } +} + +const string &GraphicComboBox::getTextNativeTranslation() { + return getTextNativeTranslation(this->selectedItemIndex); +} + +// queryes +void GraphicComboBox::pushBackItem(string item, string translated_item) { + items.push_back(item); + translated_items.push_back(translated_item); + setSelectedItemIndex(0); + createButton(item); +} + +void GraphicComboBox::clearItems() { + clearButtons(); + items.clear(); + translated_items.clear(); + selectedItemIndex = -1; + setText(""); +} + +GraphicButton *GraphicComboBox::createButton(string item) { + GraphicButton *button = new GraphicButton(); + button->init(getX(), scrollBar.getY(), getW() - scrollBar.getW(), + getPopupButtonHeight()); + button->setText(item); + button->setUseCustomTexture(true); + button->setCustomTexture(CoreData::getInstance().getCustomTexture()); + popupButtons.push_back(button); + scrollBar.setElementCount((int)popupButtons.size()); + layoutButtons(); + return button; } void GraphicComboBox::layoutButtons() { - if (scrollBar.getElementCount() != 0) { - int keyButtonsYBase=scrollBar.getY()+scrollBar.getLength();; - for (int i = scrollBar.getVisibleStart(); - i <= scrollBar.getVisibleEnd(); ++i) { - if(i >= (int)popupButtons.size()) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"i >= popupButtons.size(), i = %d, popupButtons.size() = %d",i,(int)popupButtons.size()); - throw megaglest_runtime_error(szBuf); - } - popupButtons[i]->setY(keyButtonsYBase - getPopupButtonHeight() * (i+1 - - scrollBar.getVisibleStart())); - } - } - + if (scrollBar.getElementCount() != 0) { + int keyButtonsYBase = scrollBar.getY() + scrollBar.getLength(); + ; + for (int i = scrollBar.getVisibleStart(); i <= scrollBar.getVisibleEnd(); + ++i) { + if (i >= (int)popupButtons.size()) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "i >= popupButtons.size(), i = %d, popupButtons.size() = %d", + i, (int)popupButtons.size()); + throw megaglest_runtime_error(szBuf); + } + popupButtons[i]->setY(keyButtonsYBase - + getPopupButtonHeight() * + (i + 1 - scrollBar.getVisibleStart())); + } + } } void GraphicComboBox::clearButtons() { - while(!popupButtons.empty()) { - delete popupButtons.back(); - popupButtons.pop_back(); - } - scrollBar.setElementCount(0); -} - -void GraphicComboBox::setItems(const vector &items, const vector translated_items){ - clearItems(); - this->items= items; - this->translated_items = translated_items; - if(items.empty() == false) { - setSelectedItemIndex(0); - } - else { - selectedItemIndex=-1; - setText(""); - } - for(int idx = 0; idx < (int)items.size(); idx++) { - createButton(this->items[idx]); - } -} - -void GraphicComboBox::setSelectedItemIndex(int index, bool errorOnMissing){ - if(errorOnMissing == true && (index < 0 || index >= (int)items.size())) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Index not found in listbox name: [%s] value index: %d size: %lu",this->instanceName.c_str(),index,(unsigned long)items.size()); - throw megaglest_runtime_error(szBuf); - } - selectedItemIndex= index; - preselectedItemIndex= index; - setText(getSelectedItem()); + while (!popupButtons.empty()) { + delete popupButtons.back(); + popupButtons.pop_back(); + } + scrollBar.setElementCount(0); +} + +void GraphicComboBox::setItems(const vector &items, + const vector translated_items) { + clearItems(); + this->items = items; + this->translated_items = translated_items; + if (items.empty() == false) { + setSelectedItemIndex(0); + } else { + selectedItemIndex = -1; + setText(""); + } + for (int idx = 0; idx < (int)items.size(); idx++) { + createButton(this->items[idx]); + } +} + +void GraphicComboBox::setSelectedItemIndex(int index, bool errorOnMissing) { + if (errorOnMissing == true && (index < 0 || index >= (int)items.size())) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "Index not found in listbox name: [%s] value index: %d size: %lu", + this->instanceName.c_str(), index, (unsigned long)items.size()); + throw megaglest_runtime_error(szBuf); + } + selectedItemIndex = index; + preselectedItemIndex = index; + setText(getSelectedItem()); } - void GraphicComboBox::setX(int x) { - this->x= x; - dropDownButton.setX(x+w); + this->x = x; + dropDownButton.setX(x + w); } void GraphicComboBox::setY(int y) { - this->y= y; - dropDownButton.setY(y); + this->y = y; + dropDownButton.setY(y); } -void GraphicComboBox::setEditable(bool editable){ - dropDownButton.setEditable(editable); - GraphicComponent::setEditable(editable); +void GraphicComboBox::setEditable(bool editable) { + dropDownButton.setEditable(editable); + GraphicComponent::setEditable(editable); } bool GraphicComboBox::hasItem(string item) const { - bool result = false; - vector::const_iterator iter= find(items.begin(), items.end(), item); - if(iter != items.end()) { - result = true; - } - - return result; + bool result = false; + vector::const_iterator iter = find(items.begin(), items.end(), item); + if (iter != items.end()) { + result = true; + } + + return result; +} + +void GraphicComboBox::setSelectedItem(string item, bool errorOnMissing) { + vector::iterator iter; + + iter = find(items.begin(), items.end(), item); + + if (iter == items.end()) { + if (errorOnMissing == true) { + for (int idx = 0; idx < (int)items.size(); idx++) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d]\ninstanceName [%s] idx " + "= %d items[idx] = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, instanceName.c_str(), + idx, items[idx].c_str()); + } + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "Value not found in listbox name: [%s] value: %s", + this->instanceName.c_str(), item.c_str()); + throw megaglest_runtime_error(szBuf); + } + } else { + setSelectedItemIndex(iter - items.begin()); + } } -void GraphicComboBox::setSelectedItem(string item, bool errorOnMissing){ - vector::iterator iter; - - iter= find(items.begin(), items.end(), item); - - if(iter==items.end()) { - if(errorOnMissing == true) { - for(int idx = 0; idx < (int)items.size(); idx++) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\ninstanceName [%s] idx = %d items[idx] = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,instanceName.c_str(),idx,items[idx].c_str()); - } - - char szBuf[8096]=""; - snprintf(szBuf,8096,"Value not found in listbox name: [%s] value: %s",this->instanceName.c_str(),item.c_str()); - throw megaglest_runtime_error(szBuf); - } - } - else { - setSelectedItemIndex(iter-items.begin()); - } - +void GraphicComboBox::togglePopupVisibility() { + if (popupShowing == true) { + popupShowing = false; + scrollBar.setVisible(false); + } else { + popupShowing = true; + scrollBar.setVisible(true); + layoutButtons(); + } } -void GraphicComboBox::togglePopupVisibility(){ - if( popupShowing == true ){ - popupShowing=false; - scrollBar.setVisible(false); - } - else { - popupShowing=true; - scrollBar.setVisible(true); - layoutButtons(); - } +bool GraphicComboBox::eventMouseWheel(int x, int y, int zDelta) { + if (popupShowing == true) { + scrollBar.eventMouseWheel(x, y, zDelta, true); + layoutButtons(); + mouseMoveOverButtons(x, y); + return true; + } else + return false; +} + +bool GraphicComboBox::mouseMoveOverButtons(int x, int y) { + bool result = false; + if (popupShowing) { + bool foundMouseOver = false; + for (int i = scrollBar.getVisibleStart(); i <= scrollBar.getVisibleEnd(); + ++i) { + if (popupButtons[i]->mouseMove(x, y)) { + foundMouseOver = true; + result = true; + setPreselectedItemIndex(i); + layoutButtons(); + } + if (!foundMouseOver) { + setPreselectedItemIndex(getSelectedItemIndex()); + } + } + } + return result; } -bool GraphicComboBox::eventMouseWheel(int x, int y, int zDelta) { - if (popupShowing == true) { - scrollBar.eventMouseWheel(x,y,zDelta,true); - layoutButtons(); - mouseMoveOverButtons(x,y); - return true; - } else - return false; -} - -bool GraphicComboBox::mouseMoveOverButtons(int x, int y){ - bool result=false; - if (popupShowing) { - bool foundMouseOver=false; - for (int i = scrollBar.getVisibleStart(); i <= scrollBar.getVisibleEnd(); ++i) { - if (popupButtons[i]->mouseMove(x, y)) { - foundMouseOver=true; - result = true; - setPreselectedItemIndex(i); - layoutButtons(); - } - if(!foundMouseOver){ - setPreselectedItemIndex(getSelectedItemIndex()); - } - } - } - return result; -} - -bool GraphicComboBox::mouseMove(int x, int y){ - if(this->getVisible() == false) { - return false; - } - bool scrollbarResult=scrollBar.mouseMove(x,y); - bool buttonResult=dropDownButton.mouseMove(x, y); - return scrollbarResult||buttonResult||mouseMoveOverButtons(x,y);; +bool GraphicComboBox::mouseMove(int x, int y) { + if (this->getVisible() == false) { + return false; + } + bool scrollbarResult = scrollBar.mouseMove(x, y); + bool buttonResult = dropDownButton.mouseMove(x, y); + return scrollbarResult || buttonResult || mouseMoveOverButtons(x, y); + ; } bool GraphicComboBox::mouseClick(int x, int y) { - if(this->getVisible() == false) { - return false; - } - - if(!items.empty()) { - bool returnValue=true; - if( dropDownButton.mouseClick(x, y)&& selectedItemIndex>=0) { - scrollBar.setVisibleStart(selectedItemIndex); - popupButtons[selectedItemIndex]->setLighted(true); - togglePopupVisibility(); - } - else if(scrollBar.mouseClick(x,y)){ - layoutButtons(); - returnValue=false; - } - else if (popupShowing){ - returnValue=false; - for (int i = scrollBar.getVisibleStart(); - i <= scrollBar.getVisibleEnd(); ++i) { - if( popupButtons[i]->mouseClick(x,y)){ - setSelectedItemIndex(i); - layoutButtons(); - togglePopupVisibility(); - returnValue=true; - } - } - if(returnValue==false){ - returnValue=true; - togglePopupVisibility(); - setPreselectedItemIndex(selectedItemIndex); - } - } - else{ - returnValue=false; - } - - return returnValue; - } - return false; + if (this->getVisible() == false) { + return false; + } + + if (!items.empty()) { + bool returnValue = true; + if (dropDownButton.mouseClick(x, y) && selectedItemIndex >= 0) { + scrollBar.setVisibleStart(selectedItemIndex); + popupButtons[selectedItemIndex]->setLighted(true); + togglePopupVisibility(); + } else if (scrollBar.mouseClick(x, y)) { + layoutButtons(); + returnValue = false; + } else if (popupShowing) { + returnValue = false; + for (int i = scrollBar.getVisibleStart(); i <= scrollBar.getVisibleEnd(); + ++i) { + if (popupButtons[i]->mouseClick(x, y)) { + setSelectedItemIndex(i); + layoutButtons(); + togglePopupVisibility(); + returnValue = true; + } + } + if (returnValue == false) { + returnValue = true; + togglePopupVisibility(); + setPreselectedItemIndex(selectedItemIndex); + } + } else { + returnValue = false; + } + + return returnValue; + } + return false; } bool GraphicComboBox::mouseDown(int x, int y) { - if( scrollBar.mouseDown(x,y)){ - layoutButtons(); - return true; - } - return false; -} -void GraphicComboBox::mouseUp(int x, int y) { - scrollBar.mouseUp(x,y); + if (scrollBar.mouseDown(x, y)) { + layoutButtons(); + return true; + } + return false; } - - - +void GraphicComboBox::mouseUp(int x, int y) { scrollBar.mouseUp(x, y); } // ===================================================== // class GraphicMessageBox // ===================================================== -const int GraphicMessageBox::defH= 280; -const int GraphicMessageBox::defW= 350; +const int GraphicMessageBox::defH = 280; +const int GraphicMessageBox::defW = 350; -GraphicMessageBox::GraphicMessageBox(const std::string &containerName, const std::string &objName) : - GraphicComponent(containerName, objName) { - header= ""; - autoWordWrap=true; +GraphicMessageBox::GraphicMessageBox(const std::string &containerName, + const std::string &objName) + : GraphicComponent(containerName, objName) { + header = ""; + autoWordWrap = true; } -GraphicMessageBox::~GraphicMessageBox(){ - removeButtons(); -} +GraphicMessageBox::~GraphicMessageBox() { removeButtons(); } -void GraphicMessageBox::removeButtons(){ - while(!buttons.empty()){ - delete buttons.back(); - buttons.pop_back(); - } +void GraphicMessageBox::removeButtons() { + while (!buttons.empty()) { + delete buttons.back(); + buttons.pop_back(); + } } -void GraphicMessageBox::init(const string &button1Str, const string &button2Str, int newWidth, int newHeight){ - init(button1Str, newWidth, newHeight); - addButton(button2Str); +void GraphicMessageBox::init(const string &button1Str, const string &button2Str, + int newWidth, int newHeight) { + init(button1Str, newWidth, newHeight); + addButton(button2Str); } -void GraphicMessageBox::init(const string &button1Str, int newWidth, int newHeight){ - init(newWidth,newHeight); - removeButtons(); - addButton(button1Str); +void GraphicMessageBox::init(const string &button1Str, int newWidth, + int newHeight) { + init(newWidth, newHeight); + removeButtons(); + addButton(button1Str); } void GraphicMessageBox::init(int newWidth, int newHeight) { - setFont(CoreData::getInstance().getMenuFontNormal()); - setFont3D(CoreData::getInstance().getMenuFontNormal3D()); - - h= (newHeight >= 0 ? newHeight : defH); - w= (newWidth >= 0 ? newWidth : defW); - - const Metrics &metrics= Metrics::getInstance(); - - x= (metrics.getVirtualW() - w) / 2; - y= (metrics.getVirtualH() - h) / 2; -} - -void GraphicMessageBox::addButton(const string &buttonStr, int width, int height){ - GraphicButton *newButton= new GraphicButton(containerName, instanceName + "_Button_" + buttonStr); - newButton->init(0, 0); - newButton->setText(buttonStr); - if(width != -1){ - newButton->setW(width); - } - if(height != -1){ - newButton->setH(height); - } - buttons.push_back(newButton); - alignButtons(); -} - -void GraphicMessageBox::alignButtons(){ - int currXPos= 0; - int totalbuttonListLength=0; - int buttonOffset=5; - for(int i= 0; i < getButtonCount(); i++){ - GraphicButton *button= getButton(i); - totalbuttonListLength+=button->getW(); - } - totalbuttonListLength+=(getButtonCount()-1)*buttonOffset; - currXPos=x+w/2-totalbuttonListLength/2; - for(int i= 0; i < getButtonCount(); i++){ - GraphicButton *button= getButton(i); - button->setY(y + 25); - button->setX(currXPos); - currXPos+=button->getW()+buttonOffset; - } -} - -void GraphicMessageBox::setX(int x){ - this->x= x; - alignButtons(); -} - -void GraphicMessageBox::setY(int y){ - this->y= y; - alignButtons(); -} - -bool GraphicMessageBox::mouseMove(int x, int y){ - if(this->getVisible() == false){ - return false; - } - for(int i= 0; i < getButtonCount(); i++){ - if(getButton(i)->mouseMove(x, y)){ - return true; - } - } - return false; -} - -bool GraphicMessageBox::mouseClick(int x, int y){ - if(this->getVisible() == false){ - return false; - } - - for(int i= 0; i < getButtonCount(); i++){ - if(getButton(i)->mouseClick(x, y)){ - return true; - } - } - return false; -} - -bool GraphicMessageBox::mouseClick(int x, int y, int &clickedButton){ - if(this->getVisible() == false){ - return false; - } - - for(int i= 0; i < getButtonCount(); i++){ - if(getButton(i)->mouseClick(x, y)){ - clickedButton=i; - return true; - } - } - return false; + setFont(CoreData::getInstance().getMenuFontNormal()); + setFont3D(CoreData::getInstance().getMenuFontNormal3D()); + + h = (newHeight >= 0 ? newHeight : defH); + w = (newWidth >= 0 ? newWidth : defW); + + const Metrics &metrics = Metrics::getInstance(); + + x = (metrics.getVirtualW() - w) / 2; + y = (metrics.getVirtualH() - h) / 2; +} + +void GraphicMessageBox::addButton(const string &buttonStr, int width, + int height) { + GraphicButton *newButton = + new GraphicButton(containerName, instanceName + "_Button_" + buttonStr); + newButton->init(0, 0); + newButton->setText(buttonStr); + if (width != -1) { + newButton->setW(width); + } + if (height != -1) { + newButton->setH(height); + } + buttons.push_back(newButton); + alignButtons(); +} + +void GraphicMessageBox::alignButtons() { + int currXPos = 0; + int totalbuttonListLength = 0; + int buttonOffset = 5; + for (int i = 0; i < getButtonCount(); i++) { + GraphicButton *button = getButton(i); + totalbuttonListLength += button->getW(); + } + totalbuttonListLength += (getButtonCount() - 1) * buttonOffset; + currXPos = x + w / 2 - totalbuttonListLength / 2; + for (int i = 0; i < getButtonCount(); i++) { + GraphicButton *button = getButton(i); + button->setY(y + 25); + button->setX(currXPos); + currXPos += button->getW() + buttonOffset; + } +} + +void GraphicMessageBox::setX(int x) { + this->x = x; + alignButtons(); +} + +void GraphicMessageBox::setY(int y) { + this->y = y; + alignButtons(); +} + +bool GraphicMessageBox::mouseMove(int x, int y) { + if (this->getVisible() == false) { + return false; + } + for (int i = 0; i < getButtonCount(); i++) { + if (getButton(i)->mouseMove(x, y)) { + return true; + } + } + return false; +} + +bool GraphicMessageBox::mouseClick(int x, int y) { + if (this->getVisible() == false) { + return false; + } + + for (int i = 0; i < getButtonCount(); i++) { + if (getButton(i)->mouseClick(x, y)) { + return true; + } + } + return false; +} + +bool GraphicMessageBox::mouseClick(int x, int y, int &clickedButton) { + if (this->getVisible() == false) { + return false; + } + + for (int i = 0; i < getButtonCount(); i++) { + if (getButton(i)->mouseClick(x, y)) { + clickedButton = i; + return true; + } + } + return false; } // ===================================================== // class GraphicLine // ===================================================== -const int GraphicLine::defH= 5; -const int GraphicLine::defW= 1000; +const int GraphicLine::defH = 5; +const int GraphicLine::defW = 1000; -GraphicLine::GraphicLine(const std::string &containerName, const std::string &objName) -: GraphicComponent(containerName, objName) { - horizontal = false; +GraphicLine::GraphicLine(const std::string &containerName, + const std::string &objName) + : GraphicComponent(containerName, objName) { + horizontal = false; } -void GraphicLine::init(int x, int y, int w, int h){ - GraphicComponent::init(x, y, w, h); - horizontal=true; +void GraphicLine::init(int x, int y, int w, int h) { + GraphicComponent::init(x, y, w, h); + horizontal = true; } // ===================================================== // class GraphicCheckBox // ===================================================== -const int GraphicCheckBox::defH= 22; -const int GraphicCheckBox::defW= 22; +const int GraphicCheckBox::defH = 22; +const int GraphicCheckBox::defW = 22; -GraphicCheckBox::GraphicCheckBox(const std::string &containerName, const std::string &objName) -: GraphicComponent(containerName, objName) { - value = false; - lighted = false; +GraphicCheckBox::GraphicCheckBox(const std::string &containerName, + const std::string &objName) + : GraphicComponent(containerName, objName) { + value = false; + lighted = false; } -void GraphicCheckBox::init(int x, int y, int w, int h){ - GraphicComponent::init(x, y, w, h); - value=true; - lighted= false; +void GraphicCheckBox::init(int x, int y, int w, int h) { + GraphicComponent::init(x, y, w, h); + value = true; + lighted = false; } -bool GraphicCheckBox::mouseMove(int x, int y){ - if(this->getVisible() == false) { - return false; - } +bool GraphicCheckBox::mouseMove(int x, int y) { + if (this->getVisible() == false) { + return false; + } - bool b= GraphicComponent::mouseMove(x, y); - lighted= b; - return b; + bool b = GraphicComponent::mouseMove(x, y); + lighted = b; + return b; } -bool GraphicCheckBox::mouseClick(int x, int y){ - bool result=GraphicComponent::mouseClick( x, y); - if(result == true) { - if(value) { - value=false; - } - else { - value=true; - } - } - return result; +bool GraphicCheckBox::mouseClick(int x, int y) { + bool result = GraphicComponent::mouseClick(x, y); + if (result == true) { + if (value) { + value = false; + } else { + value = true; + } + } + return result; } // ===================================================== // class GraphicScrollBar // ===================================================== -const int GraphicScrollBar::defThickness=20; -const int GraphicScrollBar::defLength= 200; - -GraphicScrollBar::GraphicScrollBar(const std::string &containerName, const std::string &objName) -: GraphicComponent(containerName, objName) { - lighted = false; - activated = false; - horizontal = false; - elementCount = 0; - visibleSize = 0; - visibleStart = 0; - - // position on component for renderer - visibleCompPosStart = 0; - visibleCompPosEnd = 0; -} - -void GraphicScrollBar::init(int x, int y, bool horizontal,int length, int thickness){ - GraphicComponent::init(x, y, horizontal?length:thickness,horizontal?thickness:length ); - this->horizontal=horizontal; - this->elementCount=1; - this->visibleSize=1; - this->visibleStart=0; - this->visibleCompPosStart=0; - this->visibleCompPosEnd=length; - activated = false; - lighted = false; +const int GraphicScrollBar::defThickness = 20; +const int GraphicScrollBar::defLength = 200; + +GraphicScrollBar::GraphicScrollBar(const std::string &containerName, + const std::string &objName) + : GraphicComponent(containerName, objName) { + lighted = false; + activated = false; + horizontal = false; + elementCount = 0; + visibleSize = 0; + visibleStart = 0; + + // position on component for renderer + visibleCompPosStart = 0; + visibleCompPosEnd = 0; +} + +void GraphicScrollBar::init(int x, int y, bool horizontal, int length, + int thickness) { + GraphicComponent::init(x, y, horizontal ? length : thickness, + horizontal ? thickness : length); + this->horizontal = horizontal; + this->elementCount = 1; + this->visibleSize = 1; + this->visibleStart = 0; + this->visibleCompPosStart = 0; + this->visibleCompPosEnd = length; + activated = false; + lighted = false; } bool GraphicScrollBar::mouseDown(int x, int y) { - bool result=false; - if(getVisible() && getEnabled() && getEditable()) - { - if(activated && elementCount>0) - { - if( elementCount>visibleSize) { - int pos; - if(horizontal){ - pos=x-this->x; - } - else { - // invert the clicked point ( y is from bottom to top normally ) - pos=getLength()-(y-this->y); - } - float partSize=(float)getLength()/(float)elementCount; - float visiblePartSize=partSize*(float)visibleSize; - float startPos=((float)pos)-visiblePartSize/2; - - visibleStart=startPos/partSize; - setVisibleStart(visibleStart); - result=true; - } - } - } - return result; + bool result = false; + if (getVisible() && getEnabled() && getEditable()) { + if (activated && elementCount > 0) { + if (elementCount > visibleSize) { + int pos; + if (horizontal) { + pos = x - this->x; + } else { + // invert the clicked point ( y is from bottom to top normally ) + pos = getLength() - (y - this->y); + } + float partSize = (float)getLength() / (float)elementCount; + float visiblePartSize = partSize * (float)visibleSize; + float startPos = ((float)pos) - visiblePartSize / 2; + + visibleStart = startPos / partSize; + setVisibleStart(visibleStart); + result = true; + } + } + } + return result; } void GraphicScrollBar::mouseUp(int x, int y) { - activated = false; - lighted = false; -} - -void GraphicScrollBar::setVisibleStart(int vs){ - visibleStart=vs; - - if(visibleStart>elementCount-visibleSize) { - visibleStart=elementCount-visibleSize; - } - if(visibleStart<0) { - visibleStart=0; - } - float partSize = 0.f; - if(elementCount > 0) { - partSize = (float)getLength()/(float)elementCount; - } - visibleCompPosStart=visibleStart*partSize; - visibleCompPosEnd=visibleStart*partSize+visibleSize*partSize; - if(visibleCompPosEnd>getLength()) { - visibleCompPosEnd=getLength(); - } - if(!horizontal) { - // invert the display ( y is from bottom to top normally ) - visibleCompPosStart=getLength()-visibleCompPosStart; - visibleCompPosEnd=getLength()-visibleCompPosEnd; - } -} - -void GraphicScrollBar::setElementCount(int elementCount){ - this->elementCount=elementCount; - setVisibleStart(getVisibleStart()); -} - -void GraphicScrollBar::setVisibleSize(int visibleSize){ - this->visibleSize=visibleSize; - setVisibleStart(getVisibleStart()); -} - - -bool GraphicScrollBar::mouseClick(int x, int y){ - bool result=GraphicComponent::mouseClick( x, y); - if(result) { - activated = true; - lighted = true; - mouseDown( x, y); - } - return result; + activated = false; + lighted = false; +} + +void GraphicScrollBar::setVisibleStart(int vs) { + visibleStart = vs; + + if (visibleStart > elementCount - visibleSize) { + visibleStart = elementCount - visibleSize; + } + if (visibleStart < 0) { + visibleStart = 0; + } + float partSize = 0.f; + if (elementCount > 0) { + partSize = (float)getLength() / (float)elementCount; + } + visibleCompPosStart = visibleStart * partSize; + visibleCompPosEnd = visibleStart * partSize + visibleSize * partSize; + if (visibleCompPosEnd > getLength()) { + visibleCompPosEnd = getLength(); + } + if (!horizontal) { + // invert the display ( y is from bottom to top normally ) + visibleCompPosStart = getLength() - visibleCompPosStart; + visibleCompPosEnd = getLength() - visibleCompPosEnd; + } +} + +void GraphicScrollBar::setElementCount(int elementCount) { + this->elementCount = elementCount; + setVisibleStart(getVisibleStart()); +} + +void GraphicScrollBar::setVisibleSize(int visibleSize) { + this->visibleSize = visibleSize; + setVisibleStart(getVisibleStart()); +} + +bool GraphicScrollBar::mouseClick(int x, int y) { + bool result = GraphicComponent::mouseClick(x, y); + if (result) { + activated = true; + lighted = true; + mouseDown(x, y); + } + return result; } bool GraphicScrollBar::eventMouseWheel(int x, int y, int zDelta) { - return eventMouseWheel(x,y,zDelta,false); + return eventMouseWheel(x, y, zDelta, false); } -bool GraphicScrollBar::eventMouseWheel(int x, int y, int zDelta,bool ignorePos) { - if(ignorePos|| GraphicComponent::mouseMove(x, y)){ - int newVisibleStart = this->getVisibleStart() - zDelta/60; - if (newVisibleStart < 0) - newVisibleStart = 0; - if (newVisibleStart > this->getLength() - this->getVisibleSize()) - newVisibleStart = this->getLength() - this->getVisibleSize(); +bool GraphicScrollBar::eventMouseWheel(int x, int y, int zDelta, + bool ignorePos) { + if (ignorePos || GraphicComponent::mouseMove(x, y)) { + int newVisibleStart = this->getVisibleStart() - zDelta / 60; + if (newVisibleStart < 0) + newVisibleStart = 0; + if (newVisibleStart > this->getLength() - this->getVisibleSize()) + newVisibleStart = this->getLength() - this->getVisibleSize(); - this->setVisibleStart(newVisibleStart); - return true; - } - return false; + this->setVisibleStart(newVisibleStart); + return true; + } + return false; } -bool GraphicScrollBar::mouseMove(int x, int y){ - if(this->getVisible() == false) { - return false; - } +bool GraphicScrollBar::mouseMove(int x, int y) { + if (this->getVisible() == false) { + return false; + } - bool inScrollBar = GraphicComponent::mouseMove(x, y); - if (activated) { - lighted = true; - } else { - lighted = inScrollBar; - } - return inScrollBar; + bool inScrollBar = GraphicComponent::mouseMove(x, y); + if (activated) { + lighted = true; + } else { + lighted = inScrollBar; + } + return inScrollBar; } -int GraphicScrollBar::getLength() const { - return horizontal?getW():getH(); -} +int GraphicScrollBar::getLength() const { return horizontal ? getW() : getH(); } -//int GraphicScrollBar::getThickness() const { +// int GraphicScrollBar::getThickness() const { // return horizontal?getH():getW(); -//} +// } void GraphicScrollBar::arrangeComponents(vector &gcs) { - if(getElementCount()!=0 ) { - for(int i = getVisibleStart(); i <= getVisibleEnd(); ++i) { - if(horizontal){ - gcs[i]->setX(getX()+getLength()-gcs[i]->getW()-gcs[i]->getW()*(i-getVisibleStart())); - } - else { - gcs[i]->setY(getY()+getLength()-gcs[i]->getH()-gcs[i]->getH()*(i-getVisibleStart())); - } - } + if (getElementCount() != 0) { + for (int i = getVisibleStart(); i <= getVisibleEnd(); ++i) { + if (horizontal) { + gcs[i]->setX(getX() + getLength() - gcs[i]->getW() - + gcs[i]->getW() * (i - getVisibleStart())); + } else { + gcs[i]->setY(getY() + getLength() - gcs[i]->getH() - + gcs[i]->getH() * (i - getVisibleStart())); + } } + } } // =========================================================== // class PopupMenu // =========================================================== -const int PopupMenu::defH= 240; -const int PopupMenu::defW= 350; - -PopupMenu::PopupMenu(const std::string &containerName, const std::string &objName) : - GraphicComponent(containerName, objName, false) { - registerGraphicComponentOnlyFontCallbacks(containerName,objName); +const int PopupMenu::defH = 240; +const int PopupMenu::defW = 350; - h= defH; - w= defW; -} - -PopupMenu::~PopupMenu() { +PopupMenu::PopupMenu(const std::string &containerName, + const std::string &objName) + : GraphicComponent(containerName, objName, false) { + registerGraphicComponentOnlyFontCallbacks(containerName, objName); + h = defH; + w = defW; } -void PopupMenu::init(string menuHeader,std::vector menuItems) { - header = menuHeader; - - setFont(CoreData::getInstance().getMenuFontNormal()); - setFont3D(CoreData::getInstance().getMenuFontNormal3D()); - - buttons.clear(); +PopupMenu::~PopupMenu() {} - const Metrics &metrics= Metrics::getInstance(); +void PopupMenu::init(string menuHeader, std::vector menuItems) { + header = menuHeader; - x= (metrics.getVirtualW()-w)/2; - y= (metrics.getVirtualH()-h)/2; + setFont(CoreData::getInstance().getMenuFontNormal()); + setFont3D(CoreData::getInstance().getMenuFontNormal3D()); - int textHeight = GraphicButton::defH; - int textHeightSpacing = 6; + buttons.clear(); - int maxButtonWidth = -1; - for(unsigned int i = 0; i < menuItems.size(); ++i) { - int currentButtonWidth = -1; - if(font3D != NULL && Shared::Graphics::Font::forceLegacyFonts == false) { - FontMetrics *fontMetrics= font3D->getMetrics(); - if(fontMetrics) { - currentButtonWidth = fontMetrics->getTextWidth(menuItems[i]); - } - } - else if(font) { - FontMetrics *fontMetrics= font->getMetrics(); - if(fontMetrics) { - currentButtonWidth = fontMetrics->getTextWidth(menuItems[i]); - } - } + const Metrics &metrics = Metrics::getInstance(); - if(maxButtonWidth < 0 || currentButtonWidth > maxButtonWidth) { - maxButtonWidth = currentButtonWidth + textHeightSpacing; - } - } + x = (metrics.getVirtualW() - w) / 2; + y = (metrics.getVirtualH() - h) / 2; - int yStartOffset = y + h - (textHeight * 2); + int textHeight = GraphicButton::defH; + int textHeightSpacing = 6; - if(maxButtonWidth >= w) { - w = maxButtonWidth + textHeightSpacing; - x= (metrics.getVirtualW()-w)/2; - } - - int offsetH = (yStartOffset - y); - int maxH = (offsetH + (((int)menuItems.size() -1 ) * (textHeight + textHeightSpacing))); - if(maxH >= h) { - h = maxH; - y= (metrics.getVirtualH()-h)/2; - yStartOffset = y + h - (textHeight * 2); - } - - for(unsigned int i = 0; i < menuItems.size(); ++i) { - GraphicButton button(containerName, instanceName + "_Popup_Button_" + menuItems[i],false); - button.registerGraphicComponentOnlyFontCallbacks(containerName, instanceName + "_Popup_Button_" + menuItems[i]); - button.init(x+(w-maxButtonWidth)/2, yStartOffset - (i*(textHeight + textHeightSpacing))); - button.setText(menuItems[i]); - button.setW(maxButtonWidth); + int maxButtonWidth = -1; + for (unsigned int i = 0; i < menuItems.size(); ++i) { + int currentButtonWidth = -1; + if (font3D != NULL && Shared::Graphics::Font::forceLegacyFonts == false) { + FontMetrics *fontMetrics = font3D->getMetrics(); + if (fontMetrics) { + currentButtonWidth = fontMetrics->getTextWidth(menuItems[i]); + } + } else if (font) { + FontMetrics *fontMetrics = font->getMetrics(); + if (fontMetrics) { + currentButtonWidth = fontMetrics->getTextWidth(menuItems[i]); + } + } - buttons.push_back(button); - } + if (maxButtonWidth < 0 || currentButtonWidth > maxButtonWidth) { + maxButtonWidth = currentButtonWidth + textHeightSpacing; + } + } + + int yStartOffset = y + h - (textHeight * 2); + + if (maxButtonWidth >= w) { + w = maxButtonWidth + textHeightSpacing; + x = (metrics.getVirtualW() - w) / 2; + } + + int offsetH = (yStartOffset - y); + int maxH = (offsetH + + (((int)menuItems.size() - 1) * (textHeight + textHeightSpacing))); + if (maxH >= h) { + h = maxH; + y = (metrics.getVirtualH() - h) / 2; + yStartOffset = y + h - (textHeight * 2); + } + + for (unsigned int i = 0; i < menuItems.size(); ++i) { + GraphicButton button(containerName, + instanceName + "_Popup_Button_" + menuItems[i], false); + button.registerGraphicComponentOnlyFontCallbacks( + containerName, instanceName + "_Popup_Button_" + menuItems[i]); + button.init(x + (w - maxButtonWidth) / 2, + yStartOffset - (i * (textHeight + textHeightSpacing))); + button.setText(menuItems[i]); + button.setW(maxButtonWidth); + + buttons.push_back(button); + } } void PopupMenu::setX(int x) { - this->x= x; + this->x = x; - for(unsigned int i = 0; i < buttons.size(); ++i) { - GraphicButton &button = buttons[i]; - button.init(x+(w-GraphicButton::defW)/4, y+25 + (i*25)); - } + for (unsigned int i = 0; i < buttons.size(); ++i) { + GraphicButton &button = buttons[i]; + button.init(x + (w - GraphicButton::defW) / 4, y + 25 + (i * 25)); + } } void PopupMenu::setY(int y) { - this->y= y; + this->y = y; - for(unsigned int i = 0; i < buttons.size(); ++i) { - GraphicButton &button = buttons[i]; - button.init(x+(w-GraphicButton::defW)/4, y+25 + (i*25)); - } + for (unsigned int i = 0; i < buttons.size(); ++i) { + GraphicButton &button = buttons[i]; + button.init(x + (w - GraphicButton::defW) / 4, y + 25 + (i * 25)); + } } -bool PopupMenu::mouseMove(int x, int y){ - if(this->getVisible() == false) { - return false; - } +bool PopupMenu::mouseMove(int x, int y) { + if (this->getVisible() == false) { + return false; + } - for(unsigned int i = 0; i < buttons.size(); ++i) { - GraphicButton &button = buttons[i]; - if(button.mouseMove(x, y)) { - return true; - } - } + for (unsigned int i = 0; i < buttons.size(); ++i) { + GraphicButton &button = buttons[i]; + if (button.mouseMove(x, y)) { + return true; + } + } - return false; + return false; } bool PopupMenu::mouseClick(int x, int y) { - if(this->getVisible() == false) { - return false; - } - - for(unsigned int i = 0; i < buttons.size(); ++i) { - GraphicButton &button = buttons[i]; - if(button.mouseClick(x, y)) { - return true; - } - } - return false; -} - -std::pair PopupMenu::mouseClickedMenuItem(int x, int y) { - std::pair result; - for(unsigned int i = 0; i < buttons.size(); ++i) { - GraphicButton &button = buttons[i]; - if(button.mouseClick(x, y)) { - result.first = i; - result.second = buttons[i].getText(); - break; - } - } - - return result; -} - -}}//end namespace + if (this->getVisible() == false) { + return false; + } + + for (unsigned int i = 0; i < buttons.size(); ++i) { + GraphicButton &button = buttons[i]; + if (button.mouseClick(x, y)) { + return true; + } + } + return false; +} + +std::pair PopupMenu::mouseClickedMenuItem(int x, int y) { + std::pair result; + for (unsigned int i = 0; i < buttons.size(); ++i) { + GraphicButton &button = buttons[i]; + if (button.mouseClick(x, y)) { + result.first = i; + result.second = buttons[i].getText(); + break; + } + } + + return result; +} + +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/facilities/components.h b/source/glest_game/facilities/components.h index d26f06cfa..5f3cd0246 100644 --- a/source/glest_game/facilities/components.h +++ b/source/glest_game/facilities/components.h @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,18 +13,18 @@ #define _GLEST_GAME_GRAPHCOMPONENT_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include -#include -#include -#include #include "font.h" -#include "texture.h" #include "leak_dumper.h" +#include "texture.h" #include "vec.h" +#include +#include +#include +#include using std::string; using std::vector; @@ -34,7 +34,8 @@ using Shared::Graphics::Font3D; using namespace Shared::Graphics; using Shared::Graphics::Vec3f; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { class GraphicComponent; @@ -46,525 +47,555 @@ class GraphicComponent; class GraphicComponent : public FontChangedCallbackInterface { public: - static const float animSpeed; - static const float fadeSpeed; + static const float animSpeed; + static const float fadeSpeed; - static std::map > registeredGraphicComponentList; + static std::map> + registeredGraphicComponentList; protected: - int x, y, w, h; - string text; - string textNativeTranslation; - Font2D *font; - Font3D *font3D; - string font2DUniqueId; - string font3DUniqueId; - bool enabled; - bool editable; - bool visible; - - static float anim; - static float fade; - static Vec3f customTextColor; - - string containerName; - string instanceName; - string fontCallbackName; - - string getNewUUD(); - virtual void FontChangedCallback(std::string fontUniqueId, Font *font); + int x, y, w, h; + string text; + string textNativeTranslation; + Font2D *font; + Font3D *font3D; + string font2DUniqueId; + string font3DUniqueId; + bool enabled; + bool editable; + bool visible; + + static float anim; + static float fade; + static Vec3f customTextColor; + + string containerName; + string instanceName; + string fontCallbackName; + + string getNewUUD(); + virtual void FontChangedCallback(std::string fontUniqueId, Font *font); public: - GraphicComponent(const std::string &containerName="", const std::string &objName="", bool registerControl=true); - virtual ~GraphicComponent(); - - static void setCustomTextColor(Vec3f value) { customTextColor = value; } - static Vec3f getCustomTextColor() { return customTextColor; } - - static void clearRegisteredComponents(std::string containerName=""); - static void clearRegisterGraphicComponent(std::string containerName, std::string objName); - static void clearRegisterGraphicComponent(std::string containerName, std::vector objNameList); - virtual void registerGraphicComponent(std::string containerName, std::string objName); - virtual void registerGraphicComponentOnlyFontCallbacks(std::string containerName, std::string objName); - static GraphicComponent * findRegisteredComponent(std::string containerName, std::string objName); - static void applyAllCustomProperties(std::string containerName); - virtual void applyCustomProperties(std::string containerName); - - static bool saveAllCustomProperties(std::string containerName); - virtual bool saveCustomProperties(std::string containerName); - - virtual void init(int x, int y, int w, int h); - - string getContainerName() const { return containerName; } - string getInstanceName() const { return instanceName; } - string getFontCallbackName() const { return fontCallbackName; } - void setInstanceName(string value) { instanceName = value; } - - virtual int getX() const {return x;} - virtual int getY() const {return y;} - virtual int getW() const {return w;} - virtual int getH() const {return h;} - virtual const string &getText() const {return text;} - virtual const string &getTextNativeTranslation() { return this->textNativeTranslation;} - virtual Font2D *getFont() {return font;} - virtual Font3D *getFont3D() {return font3D;} - virtual bool getEnabled() const {return enabled;} - virtual bool getEditable() const {return editable;} - virtual bool getVisible() const {return visible;} - - virtual void setX(int x) {this->x= x;} - virtual void setY(int y) {this->y= y;} - virtual void setW(int w) {this->w= w;} - virtual void setH(int h) {this->h= h;} - virtual void setText(const string &text) {this->text= text;} - virtual void setTextNativeTranslation(const string &text) {this->textNativeTranslation= text;} - virtual void setFont(Font2D *font); - virtual void setFont3D(Font3D *font); - virtual void setEnabled(bool enabled) {this->enabled= enabled;} - virtual void setEditable(bool editable) {this->editable= editable;} - virtual void setVisible(bool value) {this->visible = value;} - - virtual void reloadFonts(); - static void reloadFontsForRegisterGraphicComponents(std::string containerName); - - virtual bool eventMouseWheel(int x, int y,int zDelta); - virtual bool mouseMove(int x, int y); - virtual bool mouseClick(int x, int y); - - static void update(); - static void resetFade(); - static float getAnim() {return anim;} - static float getFade() {return fade;} + GraphicComponent(const std::string &containerName = "", + const std::string &objName = "", + bool registerControl = true); + virtual ~GraphicComponent(); + + static void setCustomTextColor(Vec3f value) { customTextColor = value; } + static Vec3f getCustomTextColor() { return customTextColor; } + + static void clearRegisteredComponents(std::string containerName = ""); + static void clearRegisterGraphicComponent(std::string containerName, + std::string objName); + static void + clearRegisterGraphicComponent(std::string containerName, + std::vector objNameList); + virtual void registerGraphicComponent(std::string containerName, + std::string objName); + virtual void + registerGraphicComponentOnlyFontCallbacks(std::string containerName, + std::string objName); + static GraphicComponent *findRegisteredComponent(std::string containerName, + std::string objName); + static void applyAllCustomProperties(std::string containerName); + virtual void applyCustomProperties(std::string containerName); + + static bool saveAllCustomProperties(std::string containerName); + virtual bool saveCustomProperties(std::string containerName); + + virtual void init(int x, int y, int w, int h); + + string getContainerName() const { return containerName; } + string getInstanceName() const { return instanceName; } + string getFontCallbackName() const { return fontCallbackName; } + void setInstanceName(string value) { instanceName = value; } + + virtual int getX() const { return x; } + virtual int getY() const { return y; } + virtual int getW() const { return w; } + virtual int getH() const { return h; } + virtual const string &getText() const { return text; } + virtual const string &getTextNativeTranslation() { + return this->textNativeTranslation; + } + virtual Font2D *getFont() { return font; } + virtual Font3D *getFont3D() { return font3D; } + virtual bool getEnabled() const { return enabled; } + virtual bool getEditable() const { return editable; } + virtual bool getVisible() const { return visible; } + + virtual void setX(int x) { this->x = x; } + virtual void setY(int y) { this->y = y; } + virtual void setW(int w) { this->w = w; } + virtual void setH(int h) { this->h = h; } + virtual void setText(const string &text) { this->text = text; } + virtual void setTextNativeTranslation(const string &text) { + this->textNativeTranslation = text; + } + virtual void setFont(Font2D *font); + virtual void setFont3D(Font3D *font); + virtual void setEnabled(bool enabled) { this->enabled = enabled; } + virtual void setEditable(bool editable) { this->editable = editable; } + virtual void setVisible(bool value) { this->visible = value; } + + virtual void reloadFonts(); + static void + reloadFontsForRegisterGraphicComponents(std::string containerName); + + virtual bool eventMouseWheel(int x, int y, int zDelta); + virtual bool mouseMove(int x, int y); + virtual bool mouseClick(int x, int y); + + static void update(); + static void resetFade(); + static float getAnim() { return anim; } + static float getFade() { return fade; } }; // =========================================================== -// class GraphicLabel +// class GraphicLabel // =========================================================== -class GraphicLabel: public GraphicComponent { +class GraphicLabel : public GraphicComponent { public: - static const int defH; - static const int defW; + static const int defH; + static const int defW; private: - bool centered; - Vec3f textColor; - bool wordWrap; + bool centered; + Vec3f textColor; + bool wordWrap; - int centeredW; - int centeredH; + int centeredW; + int centeredH; - bool editModeEnabled; - int maxEditWidth; - int maxEditRenderWidth; - bool renderBackground; - Vec4f backgroundColor; + bool editModeEnabled; + int maxEditWidth; + int maxEditRenderWidth; + bool renderBackground; + Vec4f backgroundColor; - vector textCharLength; - bool isPassword; - Texture2D *texture; + vector textCharLength; + bool isPassword; + Texture2D *texture; public: - GraphicLabel(const std::string &containerName="", const std::string &objName="", bool registerControl=true); - void init(int x, int y, int w=defW, int h=defH, bool centered= false, Vec3f textColor=GraphicComponent::customTextColor, bool wordWrap=false); + GraphicLabel(const std::string &containerName = "", + const std::string &objName = "", bool registerControl = true); + void init(int x, int y, int w = defW, int h = defH, bool centered = false, + Vec3f textColor = GraphicComponent::customTextColor, + bool wordWrap = false); - virtual bool mouseMove(int x, int y); + virtual bool mouseMove(int x, int y); - vector getTextCharLengthList() const { return textCharLength; } - void setTextCharLengthList(vector value) { textCharLength = value; } - void clearTextCharLengthList() { textCharLength.clear(); } - void addTextCharLengthToList(int length) { textCharLength.push_back(length); } - void deleteTextCharLengthFromList() { textCharLength.pop_back(); } + vector getTextCharLengthList() const { return textCharLength; } + void setTextCharLengthList(vector value) { textCharLength = value; } + void clearTextCharLengthList() { textCharLength.clear(); } + void addTextCharLengthToList(int length) { textCharLength.push_back(length); } + void deleteTextCharLengthFromList() { textCharLength.pop_back(); } - bool getIsPassword() const { return isPassword; } - void setIsPassword(bool value) { isPassword = value; } + bool getIsPassword() const { return isPassword; } + void setIsPassword(bool value) { isPassword = value; } - bool getCentered() const {return centered;} - void setCentered(bool centered) {this->centered= centered;} + bool getCentered() const { return centered; } + void setCentered(bool centered) { this->centered = centered; } - bool getCenteredW() const; - //void setCenteredW(bool centered); + bool getCenteredW() const; + // void setCenteredW(bool centered); - bool getCenteredH() const; - //void setCenteredH(bool centered); + bool getCenteredH() const; + // void setCenteredH(bool centered); - Vec3f getTextColor() const {return textColor;} - void setTextColor(Vec3f color) {this->textColor= color;} + Vec3f getTextColor() const { return textColor; } + void setTextColor(Vec3f color) { this->textColor = color; } - bool getWordWrap() const { return wordWrap; } - void setWordWrap(bool value) { wordWrap = value; } + bool getWordWrap() const { return wordWrap; } + void setWordWrap(bool value) { wordWrap = value; } - void setEditModeEnabled(bool value) { editModeEnabled = value; } - bool getEditModeEnabled() const { return editModeEnabled; } + void setEditModeEnabled(bool value) { editModeEnabled = value; } + bool getEditModeEnabled() const { return editModeEnabled; } - void setMaxEditWidth(int value) { maxEditWidth = value; } - int getMaxEditWidth() const { return maxEditWidth; } + void setMaxEditWidth(int value) { maxEditWidth = value; } + int getMaxEditWidth() const { return maxEditWidth; } - void setRenderBackground(bool value) { renderBackground = value; } - bool getRenderBackground() const { return renderBackground; } - Vec4f getBackgroundColor() const {return backgroundColor;} - void setBackgroundColor(Vec4f color) {this->backgroundColor= color;} + void setRenderBackground(bool value) { renderBackground = value; } + bool getRenderBackground() const { return renderBackground; } + Vec4f getBackgroundColor() const { return backgroundColor; } + void setBackgroundColor(Vec4f color) { this->backgroundColor = color; } - void setMaxEditRenderWidth(int value) { maxEditRenderWidth = value; } - int getMaxEditRenderWidth() const { return maxEditRenderWidth; } + void setMaxEditRenderWidth(int value) { maxEditRenderWidth = value; } + int getMaxEditRenderWidth() const { return maxEditRenderWidth; } - void setTexture(Texture2D *value) { texture = value; } - Texture2D *getTexture() const { return texture; } + void setTexture(Texture2D *value) { texture = value; } + Texture2D *getTexture() const { return texture; } }; // =========================================================== -// class GraphicButton +// class GraphicButton // =========================================================== -class GraphicButton: public GraphicComponent { +class GraphicButton : public GraphicComponent { public: - static const int defH; - static const int defW; - + static const int defH; + static const int defW; + private: - bool lighted; - bool alwaysLighted; + bool lighted; + bool alwaysLighted; + + bool useCustomTexture; + Texture *customTexture; - bool useCustomTexture; - Texture *customTexture; - public: - GraphicButton(const std::string &containerName="", const std::string &objName="", bool registerControl=true); - void init(int x, int y, int w=defW, int h=defH); + GraphicButton(const std::string &containerName = "", + const std::string &objName = "", bool registerControl = true); + void init(int x, int y, int w = defW, int h = defH); - bool getUseCustomTexture() const { return useCustomTexture; } - Texture *getCustomTexture() const { return customTexture; } + bool getUseCustomTexture() const { return useCustomTexture; } + Texture *getCustomTexture() const { return customTexture; } - void setUseCustomTexture(bool value) { useCustomTexture=value; } - void setCustomTexture(Texture *value) { customTexture=value; } + void setUseCustomTexture(bool value) { useCustomTexture = value; } + void setCustomTexture(Texture *value) { customTexture = value; } - bool getLighted() const {return lighted||alwaysLighted;} - void setLighted(bool lighted) {this->lighted= lighted;} - bool getAlwaysLighted() const {return alwaysLighted;} - void setAlwaysLighted(bool value) {this->alwaysLighted= value;} - virtual bool mouseMove(int x, int y); + bool getLighted() const { return lighted || alwaysLighted; } + void setLighted(bool lighted) { this->lighted = lighted; } + bool getAlwaysLighted() const { return alwaysLighted; } + void setAlwaysLighted(bool value) { this->alwaysLighted = value; } + virtual bool mouseMove(int x, int y); }; // =========================================================== // class GraphicScrollBar // =========================================================== -class GraphicScrollBar: public GraphicComponent { +class GraphicScrollBar : public GraphicComponent { public: - static const int defLength; - static const int defThickness; + static const int defLength; + static const int defThickness; private: - bool activated; - bool lighted; - bool horizontal; - int elementCount; - int visibleSize; - int visibleStart; + bool activated; + bool lighted; + bool horizontal; + int elementCount; + int visibleSize; + int visibleStart; - // position on component for renderer - int visibleCompPosStart; - int visibleCompPosEnd; + // position on component for renderer + int visibleCompPosStart; + int visibleCompPosEnd; public: - GraphicScrollBar(const std::string &containerName="", const std::string &objName=""); - void init(int x, int y, bool horizontal,int length=defLength, int thickness=defThickness); - virtual bool mouseDown(int x, int y); - virtual bool eventMouseWheel(int x, int y,int zDelta); - virtual bool eventMouseWheel(int x, int y,int zDelta,bool ignorePos); - virtual bool mouseMove(int x, int y); - virtual void mouseUp(int x, int y); - virtual bool mouseClick(int x, int y); - - - bool getHorizontal() const {return horizontal;} - int getLength() const; - void setLength(int length) {horizontal?setW(length):setH(length);} - //int getThickness() const; - - - bool getLighted() const {return lighted;} - void setLighted(bool lighted) {this->lighted= lighted;} - - int getElementCount() const {return elementCount;} - void setElementCount(int elementCount); - int getVisibleSize() const {return visibleSize;} - void setVisibleSize(int visibleSize); - int getVisibleStart() const {return visibleStart;} - int getVisibleEnd() const {return visibleStart+visibleSize>elementCount-1?elementCount-1: visibleStart+visibleSize-1;} - void setVisibleStart(int visibleStart); - - int getVisibleCompPosStart() const {return visibleCompPosStart;} - int getVisibleCompPosEnd() const {return visibleCompPosEnd;} - void arrangeComponents(vector &gcs); + GraphicScrollBar(const std::string &containerName = "", + const std::string &objName = ""); + void init(int x, int y, bool horizontal, int length = defLength, + int thickness = defThickness); + virtual bool mouseDown(int x, int y); + virtual bool eventMouseWheel(int x, int y, int zDelta); + virtual bool eventMouseWheel(int x, int y, int zDelta, bool ignorePos); + virtual bool mouseMove(int x, int y); + virtual void mouseUp(int x, int y); + virtual bool mouseClick(int x, int y); + + bool getHorizontal() const { return horizontal; } + int getLength() const; + void setLength(int length) { horizontal ? setW(length) : setH(length); } + // int getThickness() const; + + bool getLighted() const { return lighted; } + void setLighted(bool lighted) { this->lighted = lighted; } + + int getElementCount() const { return elementCount; } + void setElementCount(int elementCount); + int getVisibleSize() const { return visibleSize; } + void setVisibleSize(int visibleSize); + int getVisibleStart() const { return visibleStart; } + int getVisibleEnd() const { + return visibleStart + visibleSize > elementCount - 1 + ? elementCount - 1 + : visibleStart + visibleSize - 1; + } + void setVisibleStart(int visibleStart); + + int getVisibleCompPosStart() const { return visibleCompPosStart; } + int getVisibleCompPosEnd() const { return visibleCompPosEnd; } + void arrangeComponents(vector &gcs); }; - // =========================================================== -// class GraphicListBox +// class GraphicListBox // =========================================================== -class GraphicListBox: public GraphicComponent { +class GraphicListBox : public GraphicComponent { public: - static const int defH; - static const int defW; + static const int defH; + static const int defW; private: - GraphicButton graphButton1, graphButton2; - vector items; - vector translated_items; - int selectedItemIndex; - bool lighted; - Vec3f textColor; - bool leftControlled; - + GraphicButton graphButton1, graphButton2; + vector items; + vector translated_items; + int selectedItemIndex; + bool lighted; + Vec3f textColor; + bool leftControlled; + public: - GraphicListBox(const std::string &containerName="", const std::string &objName=""); - void init(int x, int y, int w=defW, int h=defH, Vec3f textColor=GraphicComponent::customTextColor); - - int getItemCount() const {return (int)items.size();} - string getItem(int index) const {return items[index];} - int getSelectedItemIndex() const {return selectedItemIndex;} - string getSelectedItem() const {return items[selectedItemIndex];} - GraphicButton *getButton1() {return &graphButton1;} - GraphicButton *getButton2() {return &graphButton2;} - bool getLighted() const {return lighted;} - void setLighted(bool lighted) {this->lighted= lighted;} - bool getLeftControlled() const {return leftControlled;} - void setLeftControlled(bool leftControlled); - Vec3f getTextColor() const {return textColor;} - void setTextColor(Vec3f color) {this->textColor= color;} - - void pushBackItem(string item, string translated_item=""); - void clearItems(); - vector & getItems() {return items;} - void setItems(const vector &items, const vector translated_items=vector()); - void setSelectedItemIndex(int index, bool errorOnMissing=true); - void setSelectedItem(string item, bool errorOnMissing=true); - void setEditable(bool editable); - - bool hasItem(string item) const; - - virtual void setX(int x); - virtual void setY(int y); - - virtual bool mouseMove(int x, int y); - virtual bool mouseClick(int x, int y, string advanceToItemStartingWith=""); - - virtual const string &getTextNativeTranslation(); + GraphicListBox(const std::string &containerName = "", + const std::string &objName = ""); + void init(int x, int y, int w = defW, int h = defH, + Vec3f textColor = GraphicComponent::customTextColor); + + int getItemCount() const { return (int)items.size(); } + string getItem(int index) const { return items[index]; } + int getSelectedItemIndex() const { return selectedItemIndex; } + string getSelectedItem() const { return items[selectedItemIndex]; } + GraphicButton *getButton1() { return &graphButton1; } + GraphicButton *getButton2() { return &graphButton2; } + bool getLighted() const { return lighted; } + void setLighted(bool lighted) { this->lighted = lighted; } + bool getLeftControlled() const { return leftControlled; } + void setLeftControlled(bool leftControlled); + Vec3f getTextColor() const { return textColor; } + void setTextColor(Vec3f color) { this->textColor = color; } + + void pushBackItem(string item, string translated_item = ""); + void clearItems(); + vector &getItems() { return items; } + void setItems(const vector &items, + const vector translated_items = vector()); + void setSelectedItemIndex(int index, bool errorOnMissing = true); + void setSelectedItem(string item, bool errorOnMissing = true); + void setEditable(bool editable); + + bool hasItem(string item) const; + + virtual void setX(int x); + virtual void setY(int y); + + virtual bool mouseMove(int x, int y); + virtual bool mouseClick(int x, int y, string advanceToItemStartingWith = ""); + + virtual const string &getTextNativeTranslation(); }; // =========================================================== // class GraphicComboBox // =========================================================== -typedef vector GraphicButtons; -class GraphicComboBox: public GraphicComponent { +typedef vector GraphicButtons; +class GraphicComboBox : public GraphicComponent { public: - static const int defH; - static const int defW; + static const int defH; + static const int defW; private: - GraphicScrollBar scrollBar; - GraphicButtons popupButtons; - GraphicButton dropDownButton; - bool popupShowing; - int preselectedItemIndex; - int popupLineCount; - int popupButtonHeight; - vector items; - vector translated_items; - int selectedItemIndex; - bool lighted; - Vec3f textColor; + GraphicScrollBar scrollBar; + GraphicButtons popupButtons; + GraphicButton dropDownButton; + bool popupShowing; + int preselectedItemIndex; + int popupLineCount; + int popupButtonHeight; + vector items; + vector translated_items; + int selectedItemIndex; + bool lighted; + Vec3f textColor; public: - GraphicComboBox(const std::string &containerName="", const std::string &objName=""); - void init(int x, int y, int w=defW, int h=defH, Vec3f textColor=GraphicComponent::customTextColor); - - int getItemCount() const {return (int)items.size();} - string getItem(int index) const {return items[index];} - int getSelectedItemIndex() const {return selectedItemIndex;} - string getSelectedItem() const { - if (selectedItemIndex < 0) - return ""; - else - return items[selectedItemIndex]; - } - GraphicButton *getButton() {return &dropDownButton;} - GraphicScrollBar *getScrollbar() {return &scrollBar;} - GraphicButtons *getPopupButtons() {return &popupButtons;} - bool getLighted() const {return lighted;} - void setLighted(bool lighted) {this->lighted= lighted;} - Vec3f getTextColor() const {return textColor;} - void setTextColor(Vec3f color) {this->textColor= color;} - bool isDropDownShowing() {return this->popupShowing; } - - void pushBackItem(string item, string translated_item=""); - void clearItems(); - - GraphicButton* createButton(string item); - vector & getItems() {return items;} - void setItems(const vector &items, const vector translated_items=vector()); - void setSelectedItemIndex(int index, bool errorOnMissing=true); - void setSelectedItem(string item, bool errorOnMissing=true); - void setEditable(bool editable); - - bool hasItem(string item) const; - - virtual void setX(int x); - virtual void setY(int y); - - virtual bool eventMouseWheel(int x, int y,int zDelta); - virtual bool mouseMove(int x, int y); - virtual bool mouseClick(int x, int y); - virtual bool mouseDown(int x, int y); - virtual void mouseUp(int x, int y); - - virtual const string &getTextNativeTranslation(); - - int getPopupLineCount() const {return popupLineCount;} - void setPopupLineCount(int popupLineCount); - - int getPopupButtonHeight() const {return popupButtonHeight; } - void setPopupButtonHeight(int popupButtonHeight) { - this->popupButtonHeight = popupButtonHeight; - scrollBar.setLength(popupLineCount * popupButtonHeight); - } - - string getPreselectedItem() const { - return items[preselectedItemIndex]; - } - - int getPreselectedItemIndex() const { - return preselectedItemIndex; - } + GraphicComboBox(const std::string &containerName = "", + const std::string &objName = ""); + void init(int x, int y, int w = defW, int h = defH, + Vec3f textColor = GraphicComponent::customTextColor); + + int getItemCount() const { return (int)items.size(); } + string getItem(int index) const { return items[index]; } + int getSelectedItemIndex() const { return selectedItemIndex; } + string getSelectedItem() const { + if (selectedItemIndex < 0) + return ""; + else + return items[selectedItemIndex]; + } + GraphicButton *getButton() { return &dropDownButton; } + GraphicScrollBar *getScrollbar() { return &scrollBar; } + GraphicButtons *getPopupButtons() { return &popupButtons; } + bool getLighted() const { return lighted; } + void setLighted(bool lighted) { this->lighted = lighted; } + Vec3f getTextColor() const { return textColor; } + void setTextColor(Vec3f color) { this->textColor = color; } + bool isDropDownShowing() { return this->popupShowing; } + + void pushBackItem(string item, string translated_item = ""); + void clearItems(); + + GraphicButton *createButton(string item); + vector &getItems() { return items; } + void setItems(const vector &items, + const vector translated_items = vector()); + void setSelectedItemIndex(int index, bool errorOnMissing = true); + void setSelectedItem(string item, bool errorOnMissing = true); + void setEditable(bool editable); + + bool hasItem(string item) const; + + virtual void setX(int x); + virtual void setY(int y); + + virtual bool eventMouseWheel(int x, int y, int zDelta); + virtual bool mouseMove(int x, int y); + virtual bool mouseClick(int x, int y); + virtual bool mouseDown(int x, int y); + virtual void mouseUp(int x, int y); + + virtual const string &getTextNativeTranslation(); + + int getPopupLineCount() const { return popupLineCount; } + void setPopupLineCount(int popupLineCount); + + int getPopupButtonHeight() const { return popupButtonHeight; } + void setPopupButtonHeight(int popupButtonHeight) { + this->popupButtonHeight = popupButtonHeight; + scrollBar.setLength(popupLineCount * popupButtonHeight); + } + + string getPreselectedItem() const { return items[preselectedItemIndex]; } + + int getPreselectedItemIndex() const { return preselectedItemIndex; } private: - bool mouseMoveOverButtons(int x, int y); - void setPreselectedItemIndex(int index) { - this->preselectedItemIndex = index; - } - virtual const string &getTextNativeTranslation(int index); - virtual void togglePopupVisibility(); - void clearButtons(); - void layoutButtons(); + bool mouseMoveOverButtons(int x, int y); + void setPreselectedItemIndex(int index) { + this->preselectedItemIndex = index; + } + virtual const string &getTextNativeTranslation(int index); + virtual void togglePopupVisibility(); + void clearButtons(); + void layoutButtons(); }; // =========================================================== -// class GraphicMessageBox +// class GraphicMessageBox // =========================================================== -class GraphicMessageBox: public GraphicComponent { +class GraphicMessageBox : public GraphicComponent { public: - static const int defH; - static const int defW; + static const int defH; + static const int defW; private: - GraphicButtons buttons; - string header; - bool autoWordWrap; + GraphicButtons buttons; + string header; + bool autoWordWrap; private: - void alignButtons(); + void alignButtons(); + public: - GraphicMessageBox(const std::string &containerName="", const std::string &objName=""); - virtual ~GraphicMessageBox(); - void init(const string &button1Str, const string &button2Str, int newWidth=-1,int newHeight=-1); - void init(const string &button1Str, int newWidth=-1,int newHeight=-1); - void init(int newWidth=-1,int newHeight=-1); - void removeButtons(); - void addButton(const string &buttonStr, int width=-1,int height=-1); - - bool getAutoWordWrap() const { return autoWordWrap; } - void setAutoWordWrap(bool value) { autoWordWrap = value; } - - int getButtonCount() const {return (int)buttons.size();} - GraphicButton *getButton(int index) {return buttons[index];} - string getHeader() const {return header;} - - virtual void setX(int x); - virtual void setY(int y); - - void setHeader(string header) {this->header= header;} - - virtual bool mouseMove(int x, int y); - virtual bool mouseClick(int x, int y); - bool mouseClick(int x, int y, int &clickedButton); + GraphicMessageBox(const std::string &containerName = "", + const std::string &objName = ""); + virtual ~GraphicMessageBox(); + void init(const string &button1Str, const string &button2Str, + int newWidth = -1, int newHeight = -1); + void init(const string &button1Str, int newWidth = -1, int newHeight = -1); + void init(int newWidth = -1, int newHeight = -1); + void removeButtons(); + void addButton(const string &buttonStr, int width = -1, int height = -1); + + bool getAutoWordWrap() const { return autoWordWrap; } + void setAutoWordWrap(bool value) { autoWordWrap = value; } + + int getButtonCount() const { return (int)buttons.size(); } + GraphicButton *getButton(int index) { return buttons[index]; } + string getHeader() const { return header; } + + virtual void setX(int x); + virtual void setY(int y); + + void setHeader(string header) { this->header = header; } + + virtual bool mouseMove(int x, int y); + virtual bool mouseClick(int x, int y); + bool mouseClick(int x, int y, int &clickedButton); }; // =========================================================== -// class GraphicLine +// class GraphicLine // =========================================================== -class GraphicLine: public GraphicComponent { +class GraphicLine : public GraphicComponent { public: - static const int defH; - static const int defW; - + static const int defH; + static const int defW; + private: - bool horizontal; - + bool horizontal; + public: - GraphicLine(const std::string &containerName="", const std::string &objName=""); - void init(int x, int y, int w=defW, int h=defH); - bool getHorizontal() const {return horizontal;} - void setHorizontal(bool horizontal) {this->horizontal= horizontal;} + GraphicLine(const std::string &containerName = "", + const std::string &objName = ""); + void init(int x, int y, int w = defW, int h = defH); + bool getHorizontal() const { return horizontal; } + void setHorizontal(bool horizontal) { this->horizontal = horizontal; } }; // =========================================================== -// class GraphicCheckBox +// class GraphicCheckBox // =========================================================== -class GraphicCheckBox: public GraphicComponent { +class GraphicCheckBox : public GraphicComponent { public: - static const int defH; - static const int defW; - + static const int defH; + static const int defW; + private: - bool value; - bool lighted; + bool value; + bool lighted; public: - GraphicCheckBox(const std::string &containerName="", const std::string &objName=""); - void init(int x, int y, int w=defW, int h=defH); - bool getValue() const {return value;} - void setValue(bool value) {this->value= value;} - bool getLighted() const {return lighted;} - void setLighted(bool lighted) {this->lighted= lighted;} - virtual bool mouseMove(int x, int y); - virtual bool mouseClick(int x, int y); + GraphicCheckBox(const std::string &containerName = "", + const std::string &objName = ""); + void init(int x, int y, int w = defW, int h = defH); + bool getValue() const { return value; } + void setValue(bool value) { this->value = value; } + bool getLighted() const { return lighted; } + void setLighted(bool lighted) { this->lighted = lighted; } + virtual bool mouseMove(int x, int y); + virtual bool mouseClick(int x, int y); }; - // =========================================================== // class PopupMenu // =========================================================== -class PopupMenu: public GraphicComponent { +class PopupMenu : public GraphicComponent { public: - static const int defH; - static const int defW; + static const int defH; + static const int defW; private: - std::vector buttons; - string header; + std::vector buttons; + string header; public: - PopupMenu(const std::string &containerName="", const std::string &objName=""); - virtual ~PopupMenu(); - void init(string menuHeader, std::vector menuItems); + PopupMenu(const std::string &containerName = "", + const std::string &objName = ""); + virtual ~PopupMenu(); + void init(string menuHeader, std::vector menuItems); - std::vector & getMenuItems() {return buttons;} - string getHeader() const {return header;} + std::vector &getMenuItems() { return buttons; } + string getHeader() const { return header; } - virtual void setX(int x); - virtual void setY(int y); + virtual void setX(int x); + virtual void setY(int y); - void setHeader(string header) {this->header= header;} + void setHeader(string header) { this->header = header; } - virtual bool mouseMove(int x, int y); - virtual bool mouseClick(int x, int y); - std::pair mouseClickedMenuItem(int x, int y); + virtual bool mouseMove(int x, int y); + virtual bool mouseClick(int x, int y); + std::pair mouseClickedMenuItem(int x, int y); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/facilities/game_util.cpp b/source/glest_game/facilities/game_util.cpp index 0751271d7..7dad7558b 100644 --- a/source/glest_game/facilities/game_util.cpp +++ b/source/glest_game/facilities/game_util.cpp @@ -11,399 +11,445 @@ #include "game_util.h" -#include "util.h" -#include "lang.h" -#include "game_constants.h" +#include "cache_manager.h" #include "config.h" -#include -#include "platform_util.h" #include "conversion.h" -#include "cache_manager.h" #include "errno.h" +#include "game_constants.h" +#include "lang.h" #include "leak_dumper.h" +#include "platform_util.h" +#include "util.h" +#include using namespace Shared::Util; using namespace Shared::Platform; -namespace Glest { namespace Game { +namespace Glest { +namespace Game { -const char *mailString = " http://bugs.megaglest.org"; +const char *mailString = " http://bugs.megaglest.org"; // !! Use minor versions !! Only major and minor version control compatibility! // typical version numbers look like this: v3.13-beta1.0 v3.12-dev v3.12.1 // don't forget to update file: source/version.txt -const string glestVersionString = "v3.13-dev"; -const string lastCompatibleSaveGameVersionString = "v3.11.1"; +const string glestVersionString = "v3.13-dev"; +const string lastCompatibleSaveGameVersionString = "v3.11.1"; #if defined(GITVERSIONHEADER) - #include "gitversion.h" +#include "gitversion.h" #endif #if defined(GITVERSION) || defined(GITVERSIONHEADER) - const string GIT_RawRev = string(GITVERSION); +const string GIT_RawRev = string(GITVERSION); #else - const string GIT_RawRev = "$5608.a3c8464$"; +const string GIT_RawRev = "$5608.a3c8464$"; #endif -const string GIT_Rev = string("Rev: ") + string(GIT_RawRev); +const string GIT_Rev = string("Rev: ") + string(GIT_RawRev); -string getRAWGITRevisionString() { - return GIT_RawRev; -} -string getCrashDumpFileName(){ - return "megaglest" + glestVersionString + ".dmp"; +string getRAWGITRevisionString() { return GIT_RawRev; } +string getCrashDumpFileName() { + return "megaglest" + glestVersionString + ".dmp"; } string getPlatformTypeNameString() { - static string platform; - if(platform == "") { + static string platform; + if (platform == "") { #if defined(WIN32) - #if defined(__MINGW32__) - platform = "W-Ming32"; - #else - platform = "Windows"; - #endif +#if defined(__MINGW32__) + platform = "W-Ming32"; +#else + platform = "Windows"; +#endif #elif defined(__FreeBSD__) - platform = "FreeBSD"; + platform = "FreeBSD"; #elif defined(__NetBSD__) - platform = "NetBSD"; + platform = "NetBSD"; #elif defined(__OpenBSD__) - platform = "OpenBSD"; + platform = "OpenBSD"; #elif defined(__APPLE__) - platform = "MacOS"; + platform = "MacOS"; #elif defined(_AIX) - platform = "AIX"; + platform = "AIX"; #elif defined(__ANDROID__) - platform = "Android"; + platform = "Android"; #elif defined(__BEOS__) - platform = "BEOS"; + platform = "BEOS"; #elif defined(__gnu_linux__) - platform = "Linux"; + platform = "Linux"; #elif defined(__sun) - platform = "Solaris"; + platform = "Solaris"; #elif defined(__GNUC__) - #if defined(__MINGW32__) - platform = "L-Ming32"; - #else - platform = "GNU"; - #endif +#if defined(__MINGW32__) + platform = "L-Ming32"; +#else + platform = "GNU"; +#endif #else - platform = "???"; + platform = "???"; #endif - } - return platform; + } + return platform; } string getPlatformArchTypeNameString() { - static string platform; - if(platform == "") { + static string platform; + if (platform == "") { -#if defined(_M_X64) || defined(_M_AMD64) || defined(__x86_64__) || defined(_WIN64) - platform = "-X64"; +#if defined(_M_X64) || defined(_M_AMD64) || defined(__x86_64__) || \ + defined(_WIN64) + platform = "-X64"; #elif defined(_M_ALPHA) || defined(__alpha__) - platform = "-ALPHA"; + platform = "-ALPHA"; #elif defined(_M_IA64) || defined(__ia64__) - platform = "-IA64"; + platform = "-IA64"; #elif defined(_M_MRX000) || defined(__mips__) - platform = "-MIPS"; + platform = "-MIPS"; #elif defined(_M_PPC) || defined(__powerpc__) - platform = "-POWERPC"; + platform = "-POWERPC"; #elif defined(__sparc__) - platform = "-SPARC"; + platform = "-SPARC"; #elif defined(_M_ARM_FP) || defined(__arm__) || defined(_M_ARM) - platform = "-ARM"; + platform = "-ARM"; #endif - } - return platform; + } + return platform; } string getPlatformNameString() { - static string platform; - if(platform == "") { - platform = getPlatformTypeNameString() + getPlatformArchTypeNameString(); - } - return platform; + static string platform; + if (platform == "") { + platform = getPlatformTypeNameString() + getPlatformArchTypeNameString(); + } + return platform; } -string getGITRevisionString() { - return GIT_Rev; -} +string getGITRevisionString() { return GIT_Rev; } string getCompilerNameString() { - static string version = ""; - if(version == "") { + static string version = ""; + if (version == "") { #if defined(WIN32) && defined(_MSC_VER) - version = "VC++: " + intToStr(_MSC_VER); - + version = "VC++: " + intToStr(_MSC_VER); #elif defined(__clang__) - version = "Clang: " + intToStr(__clang_major__) + "." + intToStr(__clang_minor__) + "." + intToStr(__clang_patchlevel__); + version = "Clang: " + intToStr(__clang_major__) + "." + + intToStr(__clang_minor__) + "." + intToStr(__clang_patchlevel__); #elif defined(__GNUC__) - #if defined(__GNUC__) - # if defined(__GNUC_PATCHLEVEL__) - # define __GNUC_VERSION__ (__GNUC__ * 10000 \ - + __GNUC_MINOR__ * 100 \ - + __GNUC_PATCHLEVEL__) - # else - # define __GNUC_VERSION__ (__GNUC__ * 10000 \ - + __GNUC_MINOR__ * 100) - # endif - #endif - version = "GNUC"; - - #if defined(__MINGW32__) - version += "-MINGW"; - #endif - - version += ": " + intToStr(__GNUC_VERSION__); +#if defined(__GNUC__) +#if defined(__GNUC_PATCHLEVEL__) +#define __GNUC_VERSION__ \ + (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) +#else +#define __GNUC_VERSION__ (__GNUC__ * 10000 + __GNUC_MINOR__ * 100) +#endif +#endif + version = "GNUC"; + +#if defined(__MINGW32__) + version += "-MINGW"; +#endif + + version += ": " + intToStr(__GNUC_VERSION__); #else - version = "???"; + version = "???"; #endif #if defined(DEBUG) || defined(_DEBUG) -version += " [DEBUG]"; + version += " [DEBUG]"; #endif -#if defined(_M_X64) || defined(_M_IA64) || defined(_M_AMD64) || defined(__x86_64__) || defined(_WIN64) - version += " [64bit]"; +#if defined(_M_X64) || defined(_M_IA64) || defined(_M_AMD64) || \ + defined(__x86_64__) || defined(_WIN64) + version += " [64bit]"; #endif - } - return version; + } + return version; } string getNetworkVersionString() { - static string version = ""; - if(version == "") { - version = glestVersionString+"-"+getCompilerNameString()+"-"+getCompileDateTime(); - } - return version; + static string version = ""; + if (version == "") { + version = glestVersionString + "-" + getCompilerNameString() + "-" + + getCompileDateTime(); + } + return version; } string getNetworkVersionGITString() { - static string version = ""; - if(version == "") { - version = glestVersionString + "-" + getGITRevisionString() + "-" + getCompilerNameString(); - } - return version; + static string version = ""; + if (version == "") { + version = glestVersionString + "-" + getGITRevisionString() + "-" + + getCompilerNameString(); + } + return version; } string getCompileDateTime() { - static string result = ""; -// if(result == "") { -// result = string(__DATE__) + " " + string(__TIME__); -// } - return result; + static string result = ""; + // if(result == "") { + // result = string(__DATE__) + " " + string(__TIME__); + // } + return result; } -string getNetworkPlatformFreeVersionString() { - return glestVersionString; -} +string getNetworkPlatformFreeVersionString() { return glestVersionString; } string getAboutString1(int i) { - //case 1: return "Built: " + string(__DATE__) + " " + GIT_Rev; - switch(i) { - case 0: return "MegaGlest " + glestVersionString + " (" + "Shared Library " + sharedLibVersionString + ")"; - case 1: return GIT_Rev; - case 2: return "Copyright 2001-2010 The Glest Team"; - case 3: return "Copyright 2010-2021 The MegaGlest Team"; - } - return ""; + // case 1: return "Built: " + string(__DATE__) + " " + GIT_Rev; + switch (i) { + case 0: + return "MegaGlest " + glestVersionString + " (" + "Shared Library " + + sharedLibVersionString + ")"; + case 1: + return GIT_Rev; + case 2: + return "Copyright 2001-2010 The Glest Team"; + case 3: + return "Copyright 2010-2021 The MegaGlest Team"; + } + return ""; } string getAboutString2(int i) { - switch(i) { - case 0: return "Web: https://megaglest.org"; - case 1: return "Bug reports: " + string(mailString); - case 2: return "IRC: irc://irc.libera.chat/megaglest"; - } - return ""; + switch (i) { + case 0: + return "Web: https://megaglest.org"; + case 1: + return "Bug reports: " + string(mailString); + case 2: + return "IRC: irc://irc.libera.chat/megaglest"; + } + return ""; } string getTeammateName(int i) { - switch(i) { - case 0: return "Martiño Figueroa"; - //case 0: return "Martino Figueroa"; - case 1: return "José Luis González"; - //case 1: return "Jose Luis Gonzalez"; - case 2: return "Tucho Fernández"; - //case 2: return "Tucho Fernandez"; - case 3: return "José Zanni"; - //case 3: return "Jose Zanni"; - case 4: return "Félix Menéndez"; - //case 4: return "Felix Menendez"; - case 5: return "Marcos Caruncho"; - case 6: return "Matthias Braun"; - case 7: return "Titus Tscharntke"; - case 8: return "Mark Vejvoda"; - } - return ""; + switch (i) { + case 0: + return "Martiño Figueroa"; + // case 0: return "Martino Figueroa"; + case 1: + return "José Luis González"; + // case 1: return "Jose Luis Gonzalez"; + case 2: + return "Tucho Fernández"; + // case 2: return "Tucho Fernandez"; + case 3: + return "José Zanni"; + // case 3: return "Jose Zanni"; + case 4: + return "Félix Menéndez"; + // case 4: return "Felix Menendez"; + case 5: + return "Marcos Caruncho"; + case 6: + return "Matthias Braun"; + case 7: + return "Titus Tscharntke"; + case 8: + return "Mark Vejvoda"; + } + return ""; } string getTeammateRole(int i) { - Lang &lang = Lang::getInstance(); - - switch(i) { - case 0: return lang.getString("Programming"); - case 1: return lang.getString("SoundAndMusic"); - case 2: return lang.getString("3dAnd2dArt"); - case 3: return lang.getString("2dArtAndWeb"); - case 4: return lang.getString("Animation"); - case 5: return lang.getString("3dArt"); - case 6: return lang.getString("LinuxPort"); - case 7: return lang.getString("Megaglest3d2dProgramming"); - case 8: return lang.getString("MegaglestProgramming"); - } - return ""; + Lang &lang = Lang::getInstance(); + + switch (i) { + case 0: + return lang.getString("Programming"); + case 1: + return lang.getString("SoundAndMusic"); + case 2: + return lang.getString("3dAnd2dArt"); + case 3: + return lang.getString("2dArtAndWeb"); + case 4: + return lang.getString("Animation"); + case 5: + return lang.getString("3dArt"); + case 6: + return lang.getString("LinuxPort"); + case 7: + return lang.getString("Megaglest3d2dProgramming"); + case 8: + return lang.getString("MegaglestProgramming"); + } + return ""; } string formatString(string str) { - string outStr = str; - - if(!outStr.empty()){ - outStr[0]= toupper(outStr[0]); - } - - bool afterSeparator= false; - for(int i= 0; i < (int)str.size(); ++i){ - if(outStr[i]=='_'){ - outStr[i]= ' '; - } - else if(afterSeparator){ - outStr[i]= toupper(outStr[i]); - afterSeparator= false; - } - if(outStr[i]=='\n' || outStr[i]=='(' || outStr[i]==' '){ - afterSeparator= true; - } - } - return outStr; -} - -string getGameCustomCoreDataPath(string originalBasePath, string uniqueFilePath) { - // original file path setup - if(originalBasePath != "") { - endPathWithSlash(originalBasePath); - } - // - - // mydata user data override - Config &config = Config::getInstance(); - string data_path = config.getString("UserData_Root",""); - if(data_path != "") { - endPathWithSlash(data_path); + string outStr = str; + + if (!outStr.empty()) { + outStr[0] = toupper(outStr[0]); + } + + bool afterSeparator = false; + for (int i = 0; i < (int)str.size(); ++i) { + if (outStr[i] == '_') { + outStr[i] = ' '; + } else if (afterSeparator) { + outStr[i] = toupper(outStr[i]); + afterSeparator = false; } - // - - // if set this is the current active mod - string custom_mod_path = config.getCustomRuntimeProperty(Config::ACTIVE_MOD_PROPERTY_NAME); - if(custom_mod_path != "") { - endPathWithSlash(custom_mod_path); + if (outStr[i] == '\n' || outStr[i] == '(' || outStr[i] == ' ') { + afterSeparator = true; } - // - - // decide which file to use - string result = ""; - - if (SystemFlags::VERBOSE_MODE_ENABLED) printf("Looking for [%s] in\n#1: [%s]\n#2: [%s]\n#3: [%s]\n",uniqueFilePath.c_str(),custom_mod_path.c_str(),data_path.c_str(),originalBasePath.c_str()); - - if(custom_mod_path != "" && - (uniqueFilePath == "" || fileExists(custom_mod_path + uniqueFilePath) == true)) { - result = custom_mod_path + uniqueFilePath; - } - else if(data_path != "" && - (uniqueFilePath == "" || fileExists(data_path + uniqueFilePath) == true)) { - result = data_path + uniqueFilePath; - } - else { - result = originalBasePath + uniqueFilePath; - } - - if (SystemFlags::VERBOSE_MODE_ENABLED) printf("result [%s]\n",result.c_str()); + } + return outStr; +} - return result; +string getGameCustomCoreDataPath(string originalBasePath, + string uniqueFilePath) { + // original file path setup + if (originalBasePath != "") { + endPathWithSlash(originalBasePath); + } + // + + // mydata user data override + Config &config = Config::getInstance(); + string data_path = config.getString("UserData_Root", ""); + if (data_path != "") { + endPathWithSlash(data_path); + } + // + + // if set this is the current active mod + string custom_mod_path = + config.getCustomRuntimeProperty(Config::ACTIVE_MOD_PROPERTY_NAME); + if (custom_mod_path != "") { + endPathWithSlash(custom_mod_path); + } + // + + // decide which file to use + string result = ""; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Looking for [%s] in\n#1: [%s]\n#2: [%s]\n#3: [%s]\n", + uniqueFilePath.c_str(), custom_mod_path.c_str(), data_path.c_str(), + originalBasePath.c_str()); + + if (custom_mod_path != "" && + (uniqueFilePath == "" || + fileExists(custom_mod_path + uniqueFilePath) == true)) { + result = custom_mod_path + uniqueFilePath; + } else if (data_path != "" && + (uniqueFilePath == "" || + fileExists(data_path + uniqueFilePath) == true)) { + result = data_path + uniqueFilePath; + } else { + result = originalBasePath + uniqueFilePath; + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("result [%s]\n", result.c_str()); + + return result; } string getGameReadWritePath(const string &lookupKey) { - string path = ""; - - if(lookupKey != "") { - std::map &pathCache = CacheManager::getCachedItem< std::map >(GameConstants::pathCacheLookupKey); - std::map::const_iterator iterFind = pathCache.find(lookupKey); - if(iterFind != pathCache.end()) { - path = iterFind->second; - - if(path != "" && EndsWith(path, "/") == false && EndsWith(path, "\\") == false) { - path += "/"; - } - - //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] path to be used for [%s] files [%s]\n",__FILE__,__FUNCTION__,__LINE__,lookupKey.c_str(),path.c_str()); - } - } - - if(path == "") { - path = safeCharPtrCopy(getenv("GLESTHOME"),8095); - if(path != "" && EndsWith(path, "/") == false && EndsWith(path, "\\") == false) { - path += "/"; - } + string path = ""; + + if (lookupKey != "") { + std::map &pathCache = + CacheManager::getCachedItem>( + GameConstants::pathCacheLookupKey); + std::map::const_iterator iterFind = + pathCache.find(lookupKey); + if (iterFind != pathCache.end()) { + path = iterFind->second; + + if (path != "" && EndsWith(path, "/") == false && + EndsWith(path, "\\") == false) { + path += "/"; + } + + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] + // path to be used for [%s] files + // [%s]\n",__FILE__,__FUNCTION__,__LINE__,lookupKey.c_str(),path.c_str()); + } + } - //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] path to be used for read/write files [%s]\n",__FILE__,__FUNCTION__,__LINE__,path.c_str()); + if (path == "") { + path = safeCharPtrCopy(getenv("GLESTHOME"), 8095); + if (path != "" && EndsWith(path, "/") == false && + EndsWith(path, "\\") == false) { + path += "/"; } - return path; + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] + // path to be used for read/write files + // [%s]\n",__FILE__,__FUNCTION__,__LINE__,path.c_str()); + } + + return path; } void initSpecialStrings() { - getCrashDumpFileName(); - getPlatformNameString(); - getGITRevisionString(); - getCompilerNameString(); - getNetworkVersionString(); - getNetworkVersionGITString(); - getNetworkPlatformFreeVersionString(); - getCompileDateTime(); + getCrashDumpFileName(); + getPlatformNameString(); + getGITRevisionString(); + getCompilerNameString(); + getNetworkVersionString(); + getNetworkVersionGITString(); + getNetworkPlatformFreeVersionString(); + getCompileDateTime(); } bool upgradeFilesInTemp() { - // Get path to temp files - string tempFilePath = "temp/"; - if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - tempFilePath = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + tempFilePath; - } - else { - Config &config = Config::getInstance(); - string userData = config.getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - tempFilePath = userData + tempFilePath; - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Temp files path [%s]\n",tempFilePath.c_str()); - - // Move all files into binary folder - bool anyFailures = false; - vector fileList = getFolderTreeContentsListRecursively(tempFilePath, "", false, NULL); - for(unsigned int index = 0; index < fileList.size(); ++index) { - string fileName = fileList[index]; - string newFileName = Properties::getApplicationPath() + extractFileFromDirectoryPath(fileName); - bool result = renameFile(fileName,newFileName); - if(result == false) { - printf("FAILED Rename: [%s] to [%s] result = %d errno = %d\n",fileName.c_str(),newFileName.c_str(),result,errno); - - anyFailures = true; - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Rename: [%s] to [%s] result = %d\n",fileName.c_str(),newFileName.c_str(),result); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Successfully updated!\n"); - - return (fileList.size() > 0 && anyFailures == false); + // Get path to temp files + string tempFilePath = "temp/"; + if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { + tempFilePath = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + + tempFilePath; + } else { + Config &config = Config::getInstance(); + string userData = config.getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + tempFilePath = userData + tempFilePath; + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Temp files path [%s]\n", tempFilePath.c_str()); + + // Move all files into binary folder + bool anyFailures = false; + vector fileList = + getFolderTreeContentsListRecursively(tempFilePath, "", false, NULL); + for (unsigned int index = 0; index < fileList.size(); ++index) { + string fileName = fileList[index]; + string newFileName = Properties::getApplicationPath() + + extractFileFromDirectoryPath(fileName); + bool result = renameFile(fileName, newFileName); + if (result == false) { + printf("FAILED Rename: [%s] to [%s] result = %d errno = %d\n", + fileName.c_str(), newFileName.c_str(), result, errno); + + anyFailures = true; + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Rename: [%s] to [%s] result = %d\n", fileName.c_str(), + newFileName.c_str(), result); + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Successfully updated!\n"); + + return (fileList.size() > 0 && anyFailures == false); } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/facilities/game_util.h b/source/glest_game/facilities/game_util.h index 80a6391c5..925fadbf9 100644 --- a/source/glest_game/facilities/game_util.h +++ b/source/glest_game/facilities/game_util.h @@ -13,19 +13,20 @@ #define _GLEST_GAME_GAMEUTIL_H_ #ifdef WIN32 - #include - #include +#include +#include #endif +#include "leak_dumper.h" +#include "util.h" #include #include -#include "util.h" -#include "leak_dumper.h" -using std::string; using Shared::Util::sharedLibVersionString; +using std::string; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { extern const char *mailString; extern const string glestVersionString; @@ -51,11 +52,13 @@ string getCompileDateTime(); string formatString(string str); -string getGameReadWritePath(const string &lookupKey=""); -string getGameCustomCoreDataPath(string originalBasePath, string uniqueFilePath); +string getGameReadWritePath(const string &lookupKey = ""); +string getGameCustomCoreDataPath(string originalBasePath, + string uniqueFilePath); bool upgradeFilesInTemp(); -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/facilities/logger.cpp b/source/glest_game/facilities/logger.cpp index b93e15493..80b2f1187 100644 --- a/source/glest_game/facilities/logger.cpp +++ b/source/glest_game/facilities/logger.cpp @@ -11,344 +11,360 @@ #include "logger.h" -#include "util.h" -#include "renderer.h" -#include "properties.h" -#include "sound_renderer.h" #include "core_data.h" -#include "metrics.h" -#include "lang.h" -#include "graphics_interface.h" #include "game_constants.h" #include "game_util.h" -#include "platform_util.h" +#include "graphics_interface.h" +#include "lang.h" #include "leak_dumper.h" +#include "metrics.h" +#include "platform_util.h" +#include "properties.h" +#include "renderer.h" +#include "sound_renderer.h" +#include "util.h" using namespace std; using namespace Shared::Graphics; using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class Logger // ===================================================== -const int Logger::logLineCount= 15; +const int Logger::logLineCount = 15; // ===================== PUBLIC ======================== -Logger::Logger() : buttonCancel("Logger","buttonCancel"), buttonNextHint("Logger","buttonCancel") { - progress = 0; - string logs_path = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey); - if(logs_path != "") { - fileName= logs_path + "log.txt"; - } - else { - string userData = Config::getInstance().getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - fileName= userData + "log.txt"; - } - loadingTexture=NULL; - gameHintToShow=""; - showProgressBar = false; - - displayColor=Vec4f(1.f,1.f,1.f,0.1f); - - cancelSelected = false; - buttonCancel.setEnabled(false); - - buttonNextHint.setEnabled(false); -} +Logger::Logger() + : buttonCancel("Logger", "buttonCancel"), + buttonNextHint("Logger", "buttonCancel") { + progress = 0; + string logs_path = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey); + if (logs_path != "") { + fileName = logs_path + "log.txt"; + } else { + string userData = Config::getInstance().getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + fileName = userData + "log.txt"; + } + loadingTexture = NULL; + gameHintToShow = ""; + showProgressBar = false; + + displayColor = Vec4f(1.f, 1.f, 1.f, 0.1f); + + cancelSelected = false; + buttonCancel.setEnabled(false); -Logger::~Logger() { + buttonNextHint.setEnabled(false); } -Logger & Logger::getInstance() { - static Logger logger; - return logger; +Logger::~Logger() {} + +Logger &Logger::getInstance() { + static Logger logger; + return logger; } -void Logger::add(const string str, bool renderScreen, const string statusText) { +void Logger::add(const string str, bool renderScreen, const string statusText) { #ifdef WIN32 - FILE *f= _wfopen(utf8_decode(fileName).c_str(), L"at+"); + FILE *f = _wfopen(utf8_decode(fileName).c_str(), L"at+"); #else - FILE *f = fopen(fileName.c_str(), "at+"); + FILE *f = fopen(fileName.c_str(), "at+"); #endif - if(f != NULL){ - fprintf(f, "%s\n", str.c_str()); - fclose(f); - } - this->current= str; - this->statusText = statusText; - - if(renderScreen == true && GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - renderLoadingScreen(); - } + if (f != NULL) { + fprintf(f, "%s\n", str.c_str()); + fclose(f); + } + this->current = str; + this->statusText = statusText; + + if (renderScreen == true && + GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + renderLoadingScreen(); + } } void Logger::clear() { - string s = "Log file\n"; + string s = "Log file\n"; #ifdef WIN32 - FILE *f= _wfopen(utf8_decode(fileName).c_str(), L"wt+"); + FILE *f = _wfopen(utf8_decode(fileName).c_str(), L"wt+"); #else - FILE *f= fopen(fileName.c_str(), "wt+"); + FILE *f = fopen(fileName.c_str(), "wt+"); #endif - if(f == NULL){ - throw megaglest_runtime_error("Error opening log file" + fileName); - } + if (f == NULL) { + throw megaglest_runtime_error("Error opening log file" + fileName); + } - fprintf(f, "%s", s.c_str()); - fprintf(f, "\n"); + fprintf(f, "%s", s.c_str()); + fprintf(f, "\n"); - fclose(f); + fclose(f); } void Logger::loadLoadingScreen(string filepath) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(filepath == "") { - loadingTexture = NULL; - } - else { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] filepath = [%s]\n",__FILE__,__FUNCTION__,__LINE__,filepath.c_str()); - loadingTexture = Renderer::findTexture(filepath); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - } - - Lang &lang = Lang::getInstance(); - buttonCancel.setText(lang.getString("Cancel")); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + if (filepath == "") { + loadingTexture = NULL; + } else { + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] filepath = [%s]\n", __FILE__, + __FUNCTION__, __LINE__, filepath.c_str()); + loadingTexture = Renderer::findTexture(filepath); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + } + + Lang &lang = Lang::getInstance(); + buttonCancel.setText(lang.getString("Cancel")); } -void Logger::loadGameHints(string filePathEnglish,string filePathTranslation,bool clearList) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if((filePathEnglish == "") || (filePathTranslation == "")) { - return; - } - else { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] filePathEnglish = [%s]\n filePathTranslation = [%s]\n",__FILE__,__FUNCTION__,__LINE__,filePathEnglish.c_str(),filePathTranslation.c_str()); - gameHints.load(filePathEnglish,clearList); - gameHintsTranslation.load(filePathTranslation,clearList); - showNextHint(); - - Lang &lang = Lang::getInstance(); - buttonNextHint.setText(lang.getString("ShowNextHint","",true)); - buttonCancel.setText(lang.getString("Cancel")); - - GraphicComponent::applyAllCustomProperties("Loading"); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - } +void Logger::loadGameHints(string filePathEnglish, string filePathTranslation, + bool clearList) { + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + if ((filePathEnglish == "") || (filePathTranslation == "")) { + return; + } else { + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] filePathEnglish = [%s]\n " + "filePathTranslation = [%s]\n", + __FILE__, __FUNCTION__, __LINE__, + filePathEnglish.c_str(), + filePathTranslation.c_str()); + gameHints.load(filePathEnglish, clearList); + gameHintsTranslation.load(filePathTranslation, clearList); + showNextHint(); + + Lang &lang = Lang::getInstance(); + buttonNextHint.setText(lang.getString("ShowNextHint", "", true)); + buttonCancel.setText(lang.getString("Cancel")); + + GraphicComponent::applyAllCustomProperties("Loading"); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + } } void Logger::showNextHint() { - string key=gameHints.getRandomKey(true); - string tmpString=gameHintsTranslation.getString(key,""); - if(tmpString!=""){ - gameHintToShow=tmpString; - } - else { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] key [%s] not found for [%s] hint translation\n",__FILE__,__FUNCTION__,__LINE__,key.c_str(),Lang::getInstance().getLanguage().c_str()); - tmpString=gameHints.getString(key,""); - if(tmpString!=""){ - gameHintToShow=tmpString; - } - else { - gameHintToShow="Problems to resolve hint key '"+key+"'"; - } - } - replaceAll(gameHintToShow, "\\n", "\n"); - - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - - vector > mergedKeySettings = configKeys.getMergedProperties(); - for(unsigned int j = 0; j < mergedKeySettings.size(); ++j) { - pair &property = mergedKeySettings[j]; - replaceAll(gameHintToShow, "#"+property.first+"#", property.second); - } - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + string key = gameHints.getRandomKey(true); + string tmpString = gameHintsTranslation.getString(key, ""); + if (tmpString != "") { + gameHintToShow = tmpString; + } else { + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d] key [%s] not found for [%s] hint translation\n", + __FILE__, __FUNCTION__, __LINE__, key.c_str(), + Lang::getInstance().getLanguage().c_str()); + tmpString = gameHints.getString(key, ""); + if (tmpString != "") { + gameHintToShow = tmpString; + } else { + gameHintToShow = "Problems to resolve hint key '" + key + "'"; + } + } + replaceAll(gameHintToShow, "\\n", "\n"); + + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + + vector> mergedKeySettings = + configKeys.getMergedProperties(); + for (unsigned int j = 0; j < mergedKeySettings.size(); ++j) { + pair &property = mergedKeySettings[j]; + replaceAll(gameHintToShow, "#" + property.first + "#", property.second); + } + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); } void Logger::clearHints() { - gameHintToShow=""; - gameHints.clear(); - gameHintsTranslation.clear(); + gameHintToShow = ""; + gameHints.clear(); + gameHintsTranslation.clear(); } void Logger::handleMouseClick(int x, int y) { - if(buttonCancel.getEnabled() == true) { - if(buttonCancel.mouseClick(x, y)) { - cancelSelected = true; - } - } - if(buttonNextHint.getEnabled() == true && buttonNextHint.mouseClick(x,y) == true) { - showNextHint(); - //buttonNextHint.setLighted(false); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - CoreData &coreData= CoreData::getInstance(); - soundRenderer.playFx(coreData.getClickSoundC()); - } + if (buttonCancel.getEnabled() == true) { + if (buttonCancel.mouseClick(x, y)) { + cancelSelected = true; + } + } + if (buttonNextHint.getEnabled() == true && + buttonNextHint.mouseClick(x, y) == true) { + showNextHint(); + // buttonNextHint.setLighted(false); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + CoreData &coreData = CoreData::getInstance(); + soundRenderer.playFx(coreData.getClickSoundC()); + } } // ==================== PRIVATE ==================== void Logger::renderLoadingScreen() { - Renderer &renderer= Renderer::getInstance(); - CoreData &coreData= CoreData::getInstance(); - const Metrics &metrics= Metrics::getInstance(); - - //3d - //renderer.reset3d(); - //renderer.clearZBuffer(); - - renderer.reset2d(); - renderer.clearBuffers(); - if(loadingTexture == NULL) { - renderer.renderBackground(CoreData::getInstance().getBackgroundTexture()); - } - else { - renderer.renderBackground(loadingTexture); - } - - if(showProgressBar == true) { - if(Renderer::renderText3DEnabled) { - renderer.renderProgressBar3D( - progress, - metrics.getVirtualW() / 4, - 59 * metrics.getVirtualH() / 100, - coreData.getDisplayFontSmall3D(), - 500,""); // no string here, because it has to be language specific and does not give much information - } - else { - renderer.renderProgressBar( - progress, - metrics.getVirtualW() / 4, - 59 * metrics.getVirtualH() / 100, - coreData.getDisplayFontSmall(), - 500,""); // no string here, because it has to be language specific and does not give much information - } + Renderer &renderer = Renderer::getInstance(); + CoreData &coreData = CoreData::getInstance(); + const Metrics &metrics = Metrics::getInstance(); + + // 3d + // renderer.reset3d(); + // renderer.clearZBuffer(); + + renderer.reset2d(); + renderer.clearBuffers(); + if (loadingTexture == NULL) { + renderer.renderBackground(CoreData::getInstance().getBackgroundTexture()); + } else { + renderer.renderBackground(loadingTexture); + } + + if (showProgressBar == true) { + if (Renderer::renderText3DEnabled) { + renderer.renderProgressBar3D( + progress, metrics.getVirtualW() / 4, 59 * metrics.getVirtualH() / 100, + coreData.getDisplayFontSmall3D(), 500, + ""); // no string here, because it has to be language specific and + // does not give much information + } else { + renderer.renderProgressBar( + progress, metrics.getVirtualW() / 4, 59 * metrics.getVirtualH() / 100, + coreData.getDisplayFontSmall(), 500, + ""); // no string here, because it has to be language specific and + // does not give much information } + } + + int xLocation = metrics.getVirtualW() / 4; + if (Renderer::renderText3DEnabled) { + + renderer.renderTextShadow3D(state, coreData.getMenuFontBig3D(), + displayColor, xLocation, + 65 * metrics.getVirtualH() / 100, false); + + renderer.renderTextShadow3D(current, coreData.getMenuFontNormal3D(), + displayColor, xLocation, + 62 * metrics.getVirtualH() / 100, false); - int xLocation = metrics.getVirtualW() / 4; - if(Renderer::renderText3DEnabled) { - - renderer.renderTextShadow3D( - state, coreData.getMenuFontBig3D(), displayColor, - xLocation, - 65 * metrics.getVirtualH() / 100, false); - - renderer.renderTextShadow3D( - current, coreData.getMenuFontNormal3D(), displayColor, - xLocation, - 62 * metrics.getVirtualH() / 100, false); - - if(this->statusText != "") { - renderer.renderTextShadow3D( - this->statusText, coreData.getMenuFontNormal3D(), displayColor, - xLocation, - 56 * metrics.getVirtualH() / 100, false); - } - } - else { - renderer.renderTextShadow( - state, coreData.getMenuFontBig(), displayColor, - xLocation, - 65 * metrics.getVirtualH() / 100, false); - - renderer.renderTextShadow( - current, coreData.getMenuFontNormal(), displayColor, - xLocation, - 62 * metrics.getVirtualH() / 100, false); - - if(this->statusText != "") { - renderer.renderTextShadow( - this->statusText, coreData.getMenuFontNormal(), displayColor, - xLocation, - 56 * metrics.getVirtualH() / 100, false); - } - } - - if(gameHintToShow != "") { - Lang &lang = Lang::getInstance(); - string hintText = lang.getString("Hint","",true); - char szBuf[8096]=""; - snprintf(szBuf,8096,hintText.c_str(),gameHintToShow.c_str()); - hintText = szBuf; - - if(Renderer::renderText3DEnabled) { - int xLocationHint = (metrics.getVirtualW() / 2) - (coreData.getMenuFontBig3D()->getMetrics()->getTextWidth(hintText) / 2); - - renderer.renderTextShadow3D( - hintText, coreData.getMenuFontBig3D(), displayColor, - //xLocation*1.5f, - xLocationHint, - 90 * metrics.getVirtualH() / 100, false); - } - else { - int xLocationHint = (metrics.getVirtualW() / 2) - (coreData.getMenuFontBig()->getMetrics()->getTextWidth(hintText) / 2); - - renderer.renderTextShadow( - hintText, coreData.getMenuFontBig(), displayColor, - //xLocation*1.5f, - xLocationHint, - 90 * metrics.getVirtualH() / 100, false); - - } - //Show next Hint - if(buttonNextHint.getEnabled() == false) { - buttonNextHint.init((metrics.getVirtualW() / 2) - (175 / 2), 90 * metrics.getVirtualH() / 100 + 20, 175); - buttonNextHint.setText(lang.getString("ShowNextHint","",true)); - buttonNextHint.setEnabled(true); - buttonNextHint.setVisible(true); - buttonNextHint.setEditable(true); - } - - renderer.renderButton(&buttonNextHint); - -/* - if(Renderer::renderText3DEnabled) { - int xLocationHint = (metrics.getVirtualW() / 2) - (coreData.getMenuFontBig3D()->getMetrics()->getTextWidth(hintText) / 2); - - renderer.renderText3D( - lang.getString("ShowNextHint","",true), coreData.getMenuFontNormal3D(), nextHintTitleColor, - //xLocation*1.5f, - xLocationHint, - 93 * metrics.getVirtualH() / 100, false); - } - else { - int xLocationHint = (metrics.getVirtualW() / 2) - (coreData.getMenuFontBig()->getMetrics()->getTextWidth(hintText) / 2); - - renderer.renderText( - lang.getString("ShowNextHint","",true), coreData.getMenuFontNormal(), nextHintTitleColor, - //xLocation*1.5f, - xLocationHint, - 93 * metrics.getVirtualH() / 100, false); - - } -*/ - - } - - if(buttonCancel.getEnabled() == true) { - renderer.renderButton(&buttonCancel); + if (this->statusText != "") { + renderer.renderTextShadow3D( + this->statusText, coreData.getMenuFontNormal3D(), displayColor, + xLocation, 56 * metrics.getVirtualH() / 100, false); + } + } else { + renderer.renderTextShadow(state, coreData.getMenuFontBig(), displayColor, + xLocation, 65 * metrics.getVirtualH() / 100, + false); + + renderer.renderTextShadow(current, coreData.getMenuFontNormal(), + displayColor, xLocation, + 62 * metrics.getVirtualH() / 100, false); + + if (this->statusText != "") { + renderer.renderTextShadow(this->statusText, coreData.getMenuFontNormal(), + displayColor, xLocation, + 56 * metrics.getVirtualH() / 100, false); + } + } + + if (gameHintToShow != "") { + Lang &lang = Lang::getInstance(); + string hintText = lang.getString("Hint", "", true); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, hintText.c_str(), gameHintToShow.c_str()); + hintText = szBuf; + + if (Renderer::renderText3DEnabled) { + int xLocationHint = + (metrics.getVirtualW() / 2) - + (coreData.getMenuFontBig3D()->getMetrics()->getTextWidth(hintText) / + 2); + + renderer.renderTextShadow3D( + hintText, coreData.getMenuFontBig3D(), displayColor, + // xLocation*1.5f, + xLocationHint, 90 * metrics.getVirtualH() / 100, false); + } else { + int xLocationHint = + (metrics.getVirtualW() / 2) - + (coreData.getMenuFontBig()->getMetrics()->getTextWidth(hintText) / 2); + + renderer.renderTextShadow( + hintText, coreData.getMenuFontBig(), displayColor, + // xLocation*1.5f, + xLocationHint, 90 * metrics.getVirtualH() / 100, false); + } + // Show next Hint + if (buttonNextHint.getEnabled() == false) { + buttonNextHint.init((metrics.getVirtualW() / 2) - (175 / 2), + 90 * metrics.getVirtualH() / 100 + 20, 175); + buttonNextHint.setText(lang.getString("ShowNextHint", "", true)); + buttonNextHint.setEnabled(true); + buttonNextHint.setVisible(true); + buttonNextHint.setEditable(true); } - renderer.swapBuffers(); + renderer.renderButton(&buttonNextHint); + + /* + if(Renderer::renderText3DEnabled) { + int xLocationHint = (metrics.getVirtualW() / 2) - + (coreData.getMenuFontBig3D()->getMetrics()->getTextWidth(hintText) / 2); + + renderer.renderText3D( + lang.getString("ShowNextHint","",true), + coreData.getMenuFontNormal3D(), nextHintTitleColor, + //xLocation*1.5f, + xLocationHint, + 93 * metrics.getVirtualH() / 100, + false); + } + else { + int xLocationHint = (metrics.getVirtualW() / 2) - + (coreData.getMenuFontBig()->getMetrics()->getTextWidth(hintText) / 2); + + renderer.renderText( + lang.getString("ShowNextHint","",true), + coreData.getMenuFontNormal(), nextHintTitleColor, + //xLocation*1.5f, + xLocationHint, + 93 * metrics.getVirtualH() / 100, false); + + } + */ + } + + if (buttonCancel.getEnabled() == true) { + renderer.renderButton(&buttonCancel); + } + + renderer.swapBuffers(); } void Logger::setCancelLoadingEnabled(bool value) { - Lang &lang= Lang::getInstance(); - const Metrics &metrics= Metrics::getInstance(); - //string containerName = "logger"; - //buttonCancel.registerGraphicComponent(containerName,"buttonCancel"); - buttonCancel.init((metrics.getVirtualW() / 2) - (125 / 2), 50 * metrics.getVirtualH() / 100, 125); - buttonCancel.setText(lang.getString("Cancel")); - buttonCancel.setEnabled(value); - //GraphicComponent::applyAllCustomProperties(containerName); + Lang &lang = Lang::getInstance(); + const Metrics &metrics = Metrics::getInstance(); + // string containerName = "logger"; + // buttonCancel.registerGraphicComponent(containerName,"buttonCancel"); + buttonCancel.init((metrics.getVirtualW() / 2) - (125 / 2), + 50 * metrics.getVirtualH() / 100, 125); + buttonCancel.setText(lang.getString("Cancel")); + buttonCancel.setEnabled(value); + // GraphicComponent::applyAllCustomProperties(containerName); } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/facilities/logger.h b/source/glest_game/facilities/logger.h index 7728934f0..0e881192b 100644 --- a/source/glest_game/facilities/logger.h +++ b/source/glest_game/facilities/logger.h @@ -13,24 +13,25 @@ #define _SHARED_UTIL_LOGGER_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include #include +#include -#include "texture.h" -#include "properties.h" #include "components.h" #include "leak_dumper.h" +#include "properties.h" +#include "texture.h" -using std::string; -using std::deque; using Shared::Graphics::Texture2D; using Shared::Util::Properties; +using std::deque; +using std::string; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class Logger @@ -40,64 +41,66 @@ namespace Glest{ namespace Game{ class Logger { private: - static const int logLineCount; + static const int logLineCount; private: - typedef deque Strings; + typedef deque Strings; private: - string fileName; - string state; - string subtitle; - string current; - Texture2D *loadingTexture; - Properties gameHints; - Properties gameHintsTranslation; - string gameHintToShow; - int progress; - bool showProgressBar; - - string statusText; - bool cancelSelected; - GraphicButton buttonCancel; - Vec4f displayColor; - GraphicButton buttonNextHint; + string fileName; + string state; + string subtitle; + string current; + Texture2D *loadingTexture; + Properties gameHints; + Properties gameHintsTranslation; + string gameHintToShow; + int progress; + bool showProgressBar; + + string statusText; + bool cancelSelected; + GraphicButton buttonCancel; + Vec4f displayColor; + GraphicButton buttonNextHint; private: - Logger(); - ~Logger(); + Logger(); + ~Logger(); public: - static Logger & getInstance(); + static Logger &getInstance(); - //void setMasterserverMode(bool value) { masterserverMode = value; } + // void setMasterserverMode(bool value) { masterserverMode = value; } - void setFile(const string &fileName) {this->fileName= fileName;} - void setState(const string &state) {this->state= state;} - void setSubtitle(const string &subtitle) {this->subtitle= subtitle;} - void setProgress(int value) { this->progress = value; } - int getProgress() const {return progress;} - void showProgress() { showProgressBar = true;} - void hideProgress() { showProgressBar = false;} + void setFile(const string &fileName) { this->fileName = fileName; } + void setState(const string &state) { this->state = state; } + void setSubtitle(const string &subtitle) { this->subtitle = subtitle; } + void setProgress(int value) { this->progress = value; } + int getProgress() const { return progress; } + void showProgress() { showProgressBar = true; } + void hideProgress() { showProgressBar = false; } - void add(const string str, bool renderScreen= false, const string statusText=""); - void loadLoadingScreen(string filepath); - void loadGameHints(string filePathEnglish,string filePathTranslation,bool clearList); - void renderLoadingScreen(); + void add(const string str, bool renderScreen = false, + const string statusText = ""); + void loadLoadingScreen(string filepath); + void loadGameHints(string filePathEnglish, string filePathTranslation, + bool clearList); + void renderLoadingScreen(); - void setCancelLoadingEnabled(bool value); - bool getCancelLoading() const { return cancelSelected; } - void setCancelLoading(bool value) { cancelSelected = value; } - void handleMouseClick(int x, int y); - void clearHints(); + void setCancelLoadingEnabled(bool value); + bool getCancelLoading() const { return cancelSelected; } + void setCancelLoading(bool value) { cancelSelected = value; } + void handleMouseClick(int x, int y); + void clearHints(); - void clear(); + void clear(); private: - void showNextHint(); - + void showNextHint(); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/game/achievement.cpp b/source/glest_game/game/achievement.cpp index 2d82d7865..e939d0a50 100644 --- a/source/glest_game/game/achievement.cpp +++ b/source/glest_game/game/achievement.cpp @@ -10,82 +10,83 @@ // ============================================================== #include "achievement.h" -#include "game.h" -#include "world.h" -#include "steam.h" -#include "leak_dumper.h" #include "config.h" #include "core_data.h" +#include "game.h" +#include "leak_dumper.h" +#include "steam.h" +#include "world.h" - -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { AchievementBase::AchievementBase() { - name = ""; - description = ""; - pictureName = ""; + name = ""; + description = ""; + pictureName = ""; } -AchievementBase::~AchievementBase(){ -} +AchievementBase::~AchievementBase() {} void AchievementBase::load(const XmlNode *node) { - name= node->getAttribute("name")->getRestrictedValue(); - description = node->getAttribute("description")->getRestrictedValue(); - pictureName = node->getAttribute("pictureName")->getRestrictedValue(); + name = node->getAttribute("name")->getRestrictedValue(); + description = node->getAttribute("description")->getRestrictedValue(); + pictureName = node->getAttribute("pictureName")->getRestrictedValue(); } // ===================================================== // class CounterBasedAchievement // ===================================================== -CounterBasedAchievement::CounterBasedAchievement():AchievementBase(){ - counterName=""; - minCount=0; -} -CounterBasedAchievement::~CounterBasedAchievement(){ +CounterBasedAchievement::CounterBasedAchievement() : AchievementBase() { + counterName = ""; + minCount = 0; } +CounterBasedAchievement::~CounterBasedAchievement() {} -void CounterBasedAchievement::load(const XmlNode *node){ - AchievementBase::load(node); - counterName= node->getAttribute("counterName")->getRestrictedValue(); - minCount= node->getAttribute("minCount")->getIntValue(); - printf("achievementName=%s\n",getName().c_str()); +void CounterBasedAchievement::load(const XmlNode *node) { + AchievementBase::load(node); + counterName = node->getAttribute("counterName")->getRestrictedValue(); + minCount = node->getAttribute("minCount")->getIntValue(); + printf("achievementName=%s\n", getName().c_str()); } -bool CounterBasedAchievement::checkAchieved(Game *game, PlayerAchievementsInterface *playerStats) { - if (playerStats->getStatAsInt(counterName.c_str()) >= minCount) - return true; - else - return false; +bool CounterBasedAchievement::checkAchieved( + Game *game, PlayerAchievementsInterface *playerStats) { + if (playerStats->getStatAsInt(counterName.c_str()) >= minCount) + return true; + else + return false; } // ===================================================== // class Achievements // ===================================================== -Achievements::Achievements(){ - string dataPath= getGameReadWritePath(GameConstants::path_data_CacheLookupKey); - string filepath=getGameCustomCoreDataPath(dataPath, "data/achievements/achievements.xml"); - load(filepath); +Achievements::Achievements() { + string dataPath = + getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + string filepath = + getGameCustomCoreDataPath(dataPath, "data/achievements/achievements.xml"); + load(filepath); } -const AchievementVector* Achievements::getAchievements(){ - static Achievements instance; - return &(instance.achievements); +const AchievementVector *Achievements::getAchievements() { + static Achievements instance; + return &(instance.achievements); } -void Achievements::load( string xmlFilePath){ - XmlTree xmlTree; - xmlTree.load(xmlFilePath,Properties::getTagReplacementValues()); - const XmlNode *node= xmlTree.getRootNode(); - for (unsigned int i=0; igetChildCount();++i){ - XmlNode *currentNode=node->getChild(i); - if("counterBasedAchievement"==currentNode->getName()){ - CounterBasedAchievement a; - a.load(currentNode); - achievements.push_back(&a); - } - } - +void Achievements::load(string xmlFilePath) { + XmlTree xmlTree; + xmlTree.load(xmlFilePath, Properties::getTagReplacementValues()); + const XmlNode *node = xmlTree.getRootNode(); + for (unsigned int i = 0; i < node->getChildCount(); ++i) { + XmlNode *currentNode = node->getChild(i); + if ("counterBasedAchievement" == currentNode->getName()) { + CounterBasedAchievement a; + a.load(currentNode); + achievements.push_back(&a); + } + } } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/game/achievement.h b/source/glest_game/game/achievement.h index 035f73f98..481d06ba6 100644 --- a/source/glest_game/game/achievement.h +++ b/source/glest_game/game/achievement.h @@ -12,15 +12,15 @@ #define _GLEST_GAME_ACHIEVEMENT_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include +#include "leak_dumper.h" #include "util.h" #include "vec.h" #include "xml_parser.h" -#include "leak_dumper.h" +#include using Shared::Xml::XmlNode; using std::vector; @@ -37,31 +37,25 @@ class PlayerAchievementsInterface; class AchievementBase { private: - string name; - string description; - string pictureName; + string name; + string description; + string pictureName; public: - AchievementBase(); - virtual ~AchievementBase(); - virtual void load(const XmlNode *node); + AchievementBase(); + virtual ~AchievementBase(); + virtual void load(const XmlNode *node); - string getDescription() const { - return description; - } + string getDescription() const { return description; } - string getName() const { - return name; - } + string getName() const { return name; } - string getPictureName() const { - return pictureName; - } - - virtual bool checkAchieved(Game *game, PlayerAchievementsInterface *playerStats) { - return false; - } + string getPictureName() const { return pictureName; } + virtual bool checkAchieved(Game *game, + PlayerAchievementsInterface *playerStats) { + return false; + } }; // ===================================================== @@ -69,26 +63,23 @@ class AchievementBase { // achievements based on counters // ===================================================== -class CounterBasedAchievement: public AchievementBase{ +class CounterBasedAchievement : public AchievementBase { private: - string counterName; - int minCount; + string counterName; + int minCount; public: - CounterBasedAchievement(); - ~CounterBasedAchievement(); + CounterBasedAchievement(); + ~CounterBasedAchievement(); - void load(const XmlNode *node); + void load(const XmlNode *node); - string getCounterName() const { - return counterName; - } + string getCounterName() const { return counterName; } - int getMinCount() const { - return minCount; - } + int getMinCount() const { return minCount; } - virtual bool checkAchieved(Game *game, PlayerAchievementsInterface *playerStats); + virtual bool checkAchieved(Game *game, + PlayerAchievementsInterface *playerStats); }; // ===================================================== @@ -96,19 +87,21 @@ class CounterBasedAchievement: public AchievementBase{ // a class holding all achievements // ===================================================== -typedef vector AchievementVector; +typedef vector AchievementVector; class Achievements { private: - AchievementVector achievements; - Achievements(); + AchievementVector achievements; + Achievements(); + public: - static const AchievementVector* getAchievements(); + static const AchievementVector *getAchievements(); + private: - void load( string xmlFilePath); + void load(string xmlFilePath); }; -} -} //end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/game/chat_manager.cpp b/source/glest_game/game/chat_manager.cpp index 3228d7036..8f0705ae7 100644 --- a/source/glest_game/game/chat_manager.cpp +++ b/source/glest_game/game/chat_manager.cpp @@ -11,506 +11,586 @@ #include "chat_manager.h" -#include "window.h" -#include "console.h" #include "config.h" -#include "network_manager.h" -#include "lang.h" +#include "console.h" #include "core_data.h" +#include "lang.h" +#include "leak_dumper.h" +#include "network_manager.h" +#include "sound_renderer.h" +#include "string_utils.h" #include "util.h" +#include "window.h" #include -#include "string_utils.h" -#include "sound_renderer.h" -#include "leak_dumper.h" using namespace std; using namespace Shared::Platform; using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class ChatManager // ===================================================== ChatManager::ChatManager() { - console= NULL; - editEnabled= false; - teamMode= false; - thisTeamIndex= -1; - disableTeamMode = false; - xPos=75; - yPos=155; - maxTextLenght=90; - textCharLength.clear(); - text=""; - font=CoreData::getInstance().getConsoleFont(); - font3D=CoreData::getInstance().getConsoleFont3D(); - inMenu=false; - customCB = NULL; - this->maxCustomTextLength = maxTextLenght; + console = NULL; + editEnabled = false; + teamMode = false; + thisTeamIndex = -1; + disableTeamMode = false; + xPos = 75; + yPos = 155; + maxTextLenght = 90; + textCharLength.clear(); + text = ""; + font = CoreData::getInstance().getConsoleFont(); + font3D = CoreData::getInstance().getConsoleFont3D(); + inMenu = false; + customCB = NULL; + this->maxCustomTextLength = maxTextLenght; } -void ChatManager::init(Console* console, int thisTeamIndex, const bool inMenu, string manualPlayerNameOverride) { - this->console= console; - this->thisTeamIndex= thisTeamIndex; - this->disableTeamMode= false; - this->inMenu=inMenu; - this->manualPlayerNameOverride = manualPlayerNameOverride; +void ChatManager::init(Console *console, int thisTeamIndex, const bool inMenu, + string manualPlayerNameOverride) { + this->console = console; + this->thisTeamIndex = thisTeamIndex; + this->disableTeamMode = false; + this->inMenu = inMenu; + this->manualPlayerNameOverride = manualPlayerNameOverride; } void ChatManager::setDisableTeamMode(bool value) { - disableTeamMode = value; + disableTeamMode = value; - if(disableTeamMode == true) { - teamMode = false; - } + if (disableTeamMode == true) { + teamMode = false; + } } void ChatManager::keyUp(SDL_KeyboardEvent key) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - try { - if(editEnabled == true) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] key = [%c] [%d]\n",__FILE__,__FUNCTION__,__LINE__,key.keysym.sym,key.keysym.sym); - - if(isKeyPressed(SDLK_ESCAPE,key,false) == true) { - text.clear(); - textCharLength.clear(); - editEnabled= false; - - if(customCB != NULL) { - customCB->processInputText(text,true); - customCB = NULL; - } - } - } - } - catch(const exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - throw megaglest_runtime_error(szBuf); - } - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + try { + if (editEnabled == true) { + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d] key = [%c] [%d]\n", + __FILE__, __FUNCTION__, __LINE__, key.keysym.sym, key.keysym.sym); + + if (isKeyPressed(SDLK_ESCAPE, key, false) == true) { + text.clear(); + textCharLength.clear(); + editEnabled = false; + + if (customCB != NULL) { + customCB->processInputText(text, true); + customCB = NULL; + } + } + } + } catch (const exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d] error [%s]\n", __FILE__, + __FUNCTION__, __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + throw megaglest_runtime_error(szBuf); + } + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); } bool ChatManager::textInput(std::string inputText) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] inputText [%s]\n",__FILE__,__FUNCTION__,__LINE__,inputText.c_str()); - - int maxTextLenAllowed = (customCB != NULL ? this->maxCustomTextLength : maxTextLenght); - string textToAdd = getTextWithLengthCheck(inputText,textCharLength.size(),maxTextLenAllowed); - - if(editEnabled && (int)textCharLength.size() < maxTextLenAllowed && textToAdd.size() > 0) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - appendText(textToAdd, true, true); - updateAutoCompleteBuffer(); - return true; - } - return false; + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] inputText [%s]\n", __FILE__, + __FUNCTION__, __LINE__, inputText.c_str()); + + int maxTextLenAllowed = + (customCB != NULL ? this->maxCustomTextLength : maxTextLenght); + string textToAdd = getTextWithLengthCheck(inputText, textCharLength.size(), + maxTextLenAllowed); + + if (editEnabled && (int)textCharLength.size() < maxTextLenAllowed && + textToAdd.size() > 0) { + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + appendText(textToAdd, true, true); + updateAutoCompleteBuffer(); + return true; + } + return false; } -string ChatManager::getTextWithLengthCheck(string addText, int currentLength, int maxLength) { - string resultText = ""; - if(addText.empty() == false) { - int utf8CharsAdded = 0; - for(unsigned int index = 0; index < addText.size(); ) { - int len = getUTF8_Width(&addText[index]); - utf8CharsAdded++; - if(currentLength + utf8CharsAdded > maxLength) { - break; - } - resultText += addText.substr(index,len); - index += len; - } - } - return resultText; +string ChatManager::getTextWithLengthCheck(string addText, int currentLength, + int maxLength) { + string resultText = ""; + if (addText.empty() == false) { + int utf8CharsAdded = 0; + for (unsigned int index = 0; index < addText.size();) { + int len = getUTF8_Width(&addText[index]); + utf8CharsAdded++; + if (currentLength + utf8CharsAdded > maxLength) { + break; + } + resultText += addText.substr(index, len); + index += len; + } + } + return resultText; } void ChatManager::keyDown(SDL_KeyboardEvent key) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] key = [%c] [%d]\n",__FILE__,__FUNCTION__,__LINE__,key.keysym.sym,key.keysym.sym); - - try { - Lang &lang= Lang::getInstance(); - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - - //toggle team mode - if(editEnabled == false && - isKeyPressed(configKeys.getSDLKey("ChatTeamMode"),key) == true) { - if(disableTeamMode == true) { - if (!inMenu) { - console->addLine(lang.getString("ChatModeDisabledToAvoidCheating") ); - } - } - else { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] key = [%c] [%d]\n",__FILE__,__FUNCTION__,__LINE__,key.keysym.sym,key.keysym.sym); - - if (!inMenu) { - if (teamMode == true) { - teamMode = false; - console->addLine(lang.getString("ChatMode") + ": " + lang.getString("All")); - } else { - teamMode = true; - console->addLine(lang.getString("ChatMode") + ": " + lang.getString("Team")); - } - } - } - } - - - if(isKeyPressed(SDLK_RETURN,key, false) == true) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] key = [%c] [%d]\n",__FILE__,__FUNCTION__,__LINE__,key.keysym.sym,key.keysym.sym); - - SDL_keysym keystate = key.keysym; - if(keystate.mod & (KMOD_LALT | KMOD_RALT)){ - // alt+enter is ignored - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] key = [%c] [%d]\n",__FILE__,__FUNCTION__,__LINE__,key.keysym.sym,key.keysym.sym); - } - else { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] key = [%c] [%d]\n",__FILE__,__FUNCTION__,__LINE__,key.keysym.sym,key.keysym.sym); - - if(editEnabled == true) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] key = [%c] [%d]\n",__FILE__,__FUNCTION__,__LINE__,key.keysym.sym,key.keysym.sym); - - GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); - if(text.empty() == false) { - - if(customCB == NULL) { - //string playerName = gameNetworkInterface->getHumanPlayerName(); - int playerIndex = gameNetworkInterface->getHumanPlayerIndex(); - - if(this->manualPlayerNameOverride != "") { - console->addLine(text,false,this->manualPlayerNameOverride,Vec3f(1.f, 1.f, 1.f),teamMode); - } - else { - console->addLine(text,false,playerIndex,Vec3f(1.f, 1.f, 1.f),teamMode); - } - - gameNetworkInterface->sendTextMessage("*"+text, teamMode? thisTeamIndex: -1, false, ""); - if(inMenu == false && Config::getInstance().getBool("ChatStaysActive","false")==false ) { - editEnabled= false; - } - } - } - else { - editEnabled= false; - } - - if(customCB != NULL) { - customCB->processInputText(text,false); - editEnabled= false; - customCB = NULL; - } - - text.clear(); - textCharLength.clear(); - } - else { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] key = [%c] [%d]\n",__FILE__,__FUNCTION__,__LINE__,key.keysym.sym,key.keysym.sym); - - switchOnEdit(); - } - } - } - else if(isKeyPressed(SDLK_TAB,key, false) == true) { - if(text.empty() == false) { - // First find the prefix characters to auto-complete - string currentAutoCompleteName = ""; - - int startPos = -1; - for(int i = (int)text.size()-1; i >= 0; --i) { - if(text[i] != ' ') { - startPos = i; - } - else { - break; - } - } - - if(startPos >= 0) { - currentAutoCompleteName = text.substr(startPos); - } - - //printf("TAB currentAutoCompleteName [%s] lastAutoCompleteSearchText [%s]\n",currentAutoCompleteName.c_str(),lastAutoCompleteSearchText.c_str()); - string autoCompleteName = lastAutoCompleteSearchText; - - // Now lookup the prefix for a match in playernames - string autoCompleteResult = ""; - - int replaceCurrentAutoCompleteName = -1; - vector matchedIndexes; - - GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); - const GameSettings *settings = gameNetworkInterface->getGameSettings(); - for(unsigned int factionIndex = 0; factionIndex < (unsigned int)settings->getFactionCount(); ++factionIndex) { - string playerName = settings->getNetworkPlayerName(factionIndex); - if(playerName.length() > autoCompleteName.length() && - StartsWith(toLower(playerName), toLower(autoCompleteName)) == true) { - if(toLower(playerName) == toLower(currentAutoCompleteName)) { - replaceCurrentAutoCompleteName = factionIndex; - } - else { - autoCompleteResult = playerName.substr(autoCompleteName.length()); - matchedIndexes.push_back(factionIndex); - } - } - } - if(matchedIndexes.empty() == false) { - int newMatchedIndex = -1; - for(unsigned int index = 0; index < (unsigned int)matchedIndexes.size(); ++index) { - int possibleMatchIndex = matchedIndexes[index]; - if(replaceCurrentAutoCompleteName < 0 || possibleMatchIndex>replaceCurrentAutoCompleteName) { - newMatchedIndex = possibleMatchIndex; - break; - } - } - if(newMatchedIndex < 0) { - for(unsigned int index = 0; index < (unsigned int)matchedIndexes.size(); ++index) { - int possibleMatchIndex = matchedIndexes[index]; - if(replaceCurrentAutoCompleteName < 0 || possibleMatchIndex>replaceCurrentAutoCompleteName) { - newMatchedIndex = possibleMatchIndex; - break; - } - } - } - - if(newMatchedIndex >= 0) { - autoCompleteResult = settings->getNetworkPlayerName(newMatchedIndex).substr(autoCompleteName.length()); - } - } - - if(autoCompleteResult == "") { - replaceCurrentAutoCompleteName = -1; - matchedIndexes.clear(); - for(unsigned int index = 0; index < (unsigned int)autoCompleteTextList.size(); ++index) { - string autoText = autoCompleteTextList[index]; - - //printf("CHECKING #2 autoText.length() = %d [%s] autoCompleteName.length() = %d [%s]\n",autoText.length(),autoText.c_str(),autoCompleteName.length(),currentAutoCompleteName.c_str()); - - if(autoText.length() > autoCompleteName.length() && - StartsWith(toLower(autoText), toLower(autoCompleteName)) == true) { - - if(toLower(autoText) == toLower(currentAutoCompleteName)) { - replaceCurrentAutoCompleteName = index; - //printf("CHECKING #2 REPLACE\n"); - } - else { - autoCompleteResult = autoText.substr(autoCompleteName.length()); - //printf("CHECKING #2 autoCompleteResult [%s] autoCompleteName [%s]\n",autoCompleteResult.c_str(),autoCompleteName.c_str()); - matchedIndexes.push_back(index); - } - } - } - if(matchedIndexes.empty() == false) { - int newMatchedIndex = -1; - for(unsigned int index = 0; index < (unsigned int)matchedIndexes.size(); ++index) { - int possibleMatchIndex = matchedIndexes[index]; - if(replaceCurrentAutoCompleteName < 0 || possibleMatchIndex>replaceCurrentAutoCompleteName) { - newMatchedIndex = possibleMatchIndex; - break; - } - } - if(newMatchedIndex < 0) { - for(unsigned int index = 0; index < (unsigned int)matchedIndexes.size(); ++index) { - int possibleMatchIndex = matchedIndexes[index]; - if(replaceCurrentAutoCompleteName < 0 || possibleMatchIndex>replaceCurrentAutoCompleteName) { - newMatchedIndex = possibleMatchIndex; - break; - } - } - } - - if(newMatchedIndex >= 0) { - autoCompleteResult = autoCompleteTextList[newMatchedIndex].substr(autoCompleteName.length()); - } - } - } - - if(autoCompleteResult != "") { - if(replaceCurrentAutoCompleteName >= 0) { - deleteText((int)currentAutoCompleteName.length(), false); - - autoCompleteResult = autoCompleteName + autoCompleteResult; - - //printf("REPLACE: currentAutoCompleteName [%s] autoCompleteResult [%s] text [%s]\n",currentAutoCompleteName.c_str(),autoCompleteResult.c_str(),text.c_str()); - } - else { - //printf("ADD: currentAutoCompleteName [%s] autoCompleteResult [%s] text [%s]\n",currentAutoCompleteName.c_str(),autoCompleteResult.c_str(),text.c_str()); - } - appendText(autoCompleteResult, false, false); - } - } - } - else if(isKeyPressed(SDLK_BACKSPACE,key,false) == true) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] key = [%c] [%d]\n",__FILE__,__FUNCTION__,__LINE__,key.keysym.sym,key.keysym.sym); - - deleteText(1); - } - - } - catch(const exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - throw megaglest_runtime_error(szBuf); - } - - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d] key = [%c] [%d]\n", + __FILE__, __FUNCTION__, __LINE__, key.keysym.sym, key.keysym.sym); + + try { + Lang &lang = Lang::getInstance(); + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + + // toggle team mode + if (editEnabled == false && + isKeyPressed(configKeys.getSDLKey("ChatTeamMode"), key) == true) { + if (disableTeamMode == true) { + if (!inMenu) { + console->addLine(lang.getString("ChatModeDisabledToAvoidCheating")); + } + } else { + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d] key = [%c] [%d]\n", + __FILE__, __FUNCTION__, __LINE__, key.keysym.sym, key.keysym.sym); + + if (!inMenu) { + if (teamMode == true) { + teamMode = false; + console->addLine(lang.getString("ChatMode") + ": " + + lang.getString("All")); + } else { + teamMode = true; + console->addLine(lang.getString("ChatMode") + ": " + + lang.getString("Team")); + } + } + } + } + + if (isKeyPressed(SDLK_RETURN, key, false) == true) { + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d] key = [%c] [%d]\n", + __FILE__, __FUNCTION__, __LINE__, key.keysym.sym, key.keysym.sym); + + SDL_keysym keystate = key.keysym; + if (keystate.mod & (KMOD_LALT | KMOD_RALT)) { + // alt+enter is ignored + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d] key = [%c] [%d]\n", + __FILE__, __FUNCTION__, __LINE__, key.keysym.sym, key.keysym.sym); + } else { + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d] key = [%c] [%d]\n", + __FILE__, __FUNCTION__, __LINE__, key.keysym.sym, key.keysym.sym); + + if (editEnabled == true) { + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] key = [%c] [%d]\n", + __FILE__, __FUNCTION__, __LINE__, + key.keysym.sym, key.keysym.sym); + + GameNetworkInterface *gameNetworkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + if (text.empty() == false) { + + if (customCB == NULL) { + // string playerName = + // gameNetworkInterface->getHumanPlayerName(); + int playerIndex = gameNetworkInterface->getHumanPlayerIndex(); + + if (this->manualPlayerNameOverride != "") { + console->addLine(text, false, this->manualPlayerNameOverride, + Vec3f(1.f, 1.f, 1.f), teamMode); + } else { + console->addLine(text, false, playerIndex, Vec3f(1.f, 1.f, 1.f), + teamMode); + } + + gameNetworkInterface->sendTextMessage( + "*" + text, teamMode ? thisTeamIndex : -1, false, ""); + if (inMenu == false && Config::getInstance().getBool( + "ChatStaysActive", "false") == false) { + editEnabled = false; + } + } + } else { + editEnabled = false; + } + + if (customCB != NULL) { + customCB->processInputText(text, false); + editEnabled = false; + customCB = NULL; + } + + text.clear(); + textCharLength.clear(); + } else { + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] key = [%c] [%d]\n", + __FILE__, __FUNCTION__, __LINE__, + key.keysym.sym, key.keysym.sym); + + switchOnEdit(); + } + } + } else if (isKeyPressed(SDLK_TAB, key, false) == true) { + if (text.empty() == false) { + // First find the prefix characters to auto-complete + string currentAutoCompleteName = ""; + + int startPos = -1; + for (int i = (int)text.size() - 1; i >= 0; --i) { + if (text[i] != ' ') { + startPos = i; + } else { + break; + } + } + + if (startPos >= 0) { + currentAutoCompleteName = text.substr(startPos); + } + + // printf("TAB currentAutoCompleteName [%s] lastAutoCompleteSearchText + // [%s]\n",currentAutoCompleteName.c_str(),lastAutoCompleteSearchText.c_str()); + string autoCompleteName = lastAutoCompleteSearchText; + + // Now lookup the prefix for a match in playernames + string autoCompleteResult = ""; + + int replaceCurrentAutoCompleteName = -1; + vector matchedIndexes; + + GameNetworkInterface *gameNetworkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + const GameSettings *settings = gameNetworkInterface->getGameSettings(); + for (unsigned int factionIndex = 0; + factionIndex < (unsigned int)settings->getFactionCount(); + ++factionIndex) { + string playerName = settings->getNetworkPlayerName(factionIndex); + if (playerName.length() > autoCompleteName.length() && + StartsWith(toLower(playerName), toLower(autoCompleteName)) == + true) { + if (toLower(playerName) == toLower(currentAutoCompleteName)) { + replaceCurrentAutoCompleteName = factionIndex; + } else { + autoCompleteResult = playerName.substr(autoCompleteName.length()); + matchedIndexes.push_back(factionIndex); + } + } + } + if (matchedIndexes.empty() == false) { + int newMatchedIndex = -1; + for (unsigned int index = 0; + index < (unsigned int)matchedIndexes.size(); ++index) { + int possibleMatchIndex = matchedIndexes[index]; + if (replaceCurrentAutoCompleteName < 0 || + possibleMatchIndex > replaceCurrentAutoCompleteName) { + newMatchedIndex = possibleMatchIndex; + break; + } + } + if (newMatchedIndex < 0) { + for (unsigned int index = 0; + index < (unsigned int)matchedIndexes.size(); ++index) { + int possibleMatchIndex = matchedIndexes[index]; + if (replaceCurrentAutoCompleteName < 0 || + possibleMatchIndex > replaceCurrentAutoCompleteName) { + newMatchedIndex = possibleMatchIndex; + break; + } + } + } + + if (newMatchedIndex >= 0) { + autoCompleteResult = settings->getNetworkPlayerName(newMatchedIndex) + .substr(autoCompleteName.length()); + } + } + + if (autoCompleteResult == "") { + replaceCurrentAutoCompleteName = -1; + matchedIndexes.clear(); + for (unsigned int index = 0; + index < (unsigned int)autoCompleteTextList.size(); ++index) { + string autoText = autoCompleteTextList[index]; + + // printf("CHECKING #2 autoText.length() = %d [%s] + // autoCompleteName.length() = %d + // [%s]\n",autoText.length(),autoText.c_str(),autoCompleteName.length(),currentAutoCompleteName.c_str()); + + if (autoText.length() > autoCompleteName.length() && + StartsWith(toLower(autoText), toLower(autoCompleteName)) == + true) { + + if (toLower(autoText) == toLower(currentAutoCompleteName)) { + replaceCurrentAutoCompleteName = index; + // printf("CHECKING #2 REPLACE\n"); + } else { + autoCompleteResult = autoText.substr(autoCompleteName.length()); + // printf("CHECKING #2 autoCompleteResult [%s] autoCompleteName + // [%s]\n",autoCompleteResult.c_str(),autoCompleteName.c_str()); + matchedIndexes.push_back(index); + } + } + } + if (matchedIndexes.empty() == false) { + int newMatchedIndex = -1; + for (unsigned int index = 0; + index < (unsigned int)matchedIndexes.size(); ++index) { + int possibleMatchIndex = matchedIndexes[index]; + if (replaceCurrentAutoCompleteName < 0 || + possibleMatchIndex > replaceCurrentAutoCompleteName) { + newMatchedIndex = possibleMatchIndex; + break; + } + } + if (newMatchedIndex < 0) { + for (unsigned int index = 0; + index < (unsigned int)matchedIndexes.size(); ++index) { + int possibleMatchIndex = matchedIndexes[index]; + if (replaceCurrentAutoCompleteName < 0 || + possibleMatchIndex > replaceCurrentAutoCompleteName) { + newMatchedIndex = possibleMatchIndex; + break; + } + } + } + + if (newMatchedIndex >= 0) { + autoCompleteResult = autoCompleteTextList[newMatchedIndex].substr( + autoCompleteName.length()); + } + } + } + + if (autoCompleteResult != "") { + if (replaceCurrentAutoCompleteName >= 0) { + deleteText((int)currentAutoCompleteName.length(), false); + + autoCompleteResult = autoCompleteName + autoCompleteResult; + + // printf("REPLACE: currentAutoCompleteName [%s] autoCompleteResult + // [%s] text + // [%s]\n",currentAutoCompleteName.c_str(),autoCompleteResult.c_str(),text.c_str()); + } else { + // printf("ADD: currentAutoCompleteName [%s] autoCompleteResult [%s] + // text + // [%s]\n",currentAutoCompleteName.c_str(),autoCompleteResult.c_str(),text.c_str()); + } + appendText(autoCompleteResult, false, false); + } + } + } else if (isKeyPressed(SDLK_BACKSPACE, key, false) == true) { + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d] key = [%c] [%d]\n", + __FILE__, __FUNCTION__, __LINE__, key.keysym.sym, key.keysym.sym); + + deleteText(1); + } + + } catch (const exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] error [%s]\n", __FILE__, __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + throw megaglest_runtime_error(szBuf); + } + + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); } void ChatManager::keyPress(SDL_KeyboardEvent c) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] key = [%c] [%d]\n",__FILE__,__FUNCTION__,__LINE__,c.keysym.sym,c.keysym.sym); - -// no more textinput with keyPress in SDL2! -// int maxTextLenAllowed = (customCB != NULL ? this->maxCustomTextLength : maxTextLenght); -// if(editEnabled && (int)text.size() < maxTextLenAllowed) { -// SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] key = [%c] [%d]\n",__FILE__,__FUNCTION__,__LINE__,c.keysym.sym,c.keysym.sym); -// //space is the first meaningful code -// wchar_t key = extractKeyPressedUnicode(c); -// wchar_t textAppend[] = { key, 0 }; -// appendText(textAppend); -// } + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] key = [%c] [%d]\n", __FILE__, + __FUNCTION__, __LINE__, c.keysym.sym, c.keysym.sym); + + // no more textinput with keyPress in SDL2! + // int maxTextLenAllowed = (customCB != NULL ? this->maxCustomTextLength : + // maxTextLenght); if(editEnabled && (int)text.size() < maxTextLenAllowed) + // { SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] + //key = [%c] + //[%d]\n",__FILE__,__FUNCTION__,__LINE__,c.keysym.sym,c.keysym.sym); + // //space is the first meaningful code + // wchar_t key = extractKeyPressedUnicode(c); + // wchar_t textAppend[] = { key, 0 }; + // appendText(textAppend); + // } } -void ChatManager::switchOnEdit(CustomInputCallbackInterface *customCB,int maxCustomTextLength) { - editEnabled= true; - text.clear(); - textCharLength.clear(); - this->customCB = customCB; - if(maxCustomTextLength > 0) { - this->maxCustomTextLength = maxCustomTextLength; - } - else { - this->maxCustomTextLength = maxTextLenght; - } +void ChatManager::switchOnEdit(CustomInputCallbackInterface *customCB, + int maxCustomTextLength) { + editEnabled = true; + text.clear(); + textCharLength.clear(); + this->customCB = customCB; + if (maxCustomTextLength > 0) { + this->maxCustomTextLength = maxCustomTextLength; + } else { + this->maxCustomTextLength = maxTextLenght; + } } -void ChatManager::deleteText(int deleteCount,bool addToAutoCompleteBuffer) { - if(text.empty() == false && deleteCount >= 0) { - for(unsigned int i = 0; i < (unsigned int)deleteCount; ++i) { - if(textCharLength.empty() == false) { - //printf("BEFORE DEL textCharLength.size() = %d textCharLength[textCharLength.size()-1] = %d text.length() = %d\n",textCharLength.size(),textCharLength[textCharLength.size()-1],text.length()); - - if(textCharLength[textCharLength.size()-1] > (int)text.length()) { - textCharLength[(int)textCharLength.size()-1] = (int)text.length(); - } - for(unsigned int i = 0; i < (unsigned int)textCharLength[textCharLength.size()-1]; ++i) { - text.erase(text.end() -1); - } - //printf("AFTER DEL textCharLength.size() = %d textCharLength[textCharLength.size()-1] = %d text.length() = %d\n",textCharLength.size(),textCharLength[textCharLength.size()-1],text.length()); - textCharLength.pop_back(); - - if(addToAutoCompleteBuffer == true) { - updateAutoCompleteBuffer(); - } - } - } - } - +void ChatManager::deleteText(int deleteCount, bool addToAutoCompleteBuffer) { + if (text.empty() == false && deleteCount >= 0) { + for (unsigned int i = 0; i < (unsigned int)deleteCount; ++i) { + if (textCharLength.empty() == false) { + // printf("BEFORE DEL textCharLength.size() = %d + // textCharLength[textCharLength.size()-1] = %d text.length() = + // %d\n",textCharLength.size(),textCharLength[textCharLength.size()-1],text.length()); + + if (textCharLength[textCharLength.size() - 1] > (int)text.length()) { + textCharLength[(int)textCharLength.size() - 1] = (int)text.length(); + } + for (unsigned int i = 0; + i < (unsigned int)textCharLength[textCharLength.size() - 1]; ++i) { + text.erase(text.end() - 1); + } + // printf("AFTER DEL textCharLength.size() = %d + // textCharLength[textCharLength.size()-1] = %d text.length() = + // %d\n",textCharLength.size(),textCharLength[textCharLength.size()-1],text.length()); + textCharLength.pop_back(); + + if (addToAutoCompleteBuffer == true) { + updateAutoCompleteBuffer(); + } + } + } + } } -void ChatManager::appendText(string addText, bool validateChars, bool addToAutoCompleteBuffer) { +void ChatManager::appendText(string addText, bool validateChars, + bool addToAutoCompleteBuffer) { - for(unsigned int index = 0; index < addText.size(); ) { - int len = getUTF8_Width(&addText[index]); - textCharLength.push_back(len); - text += addText.substr(index,len); - index += len; + for (unsigned int index = 0; index < addText.size();) { + int len = getUTF8_Width(&addText[index]); + textCharLength.push_back(len); + text += addText.substr(index, len); + index += len; - if(addToAutoCompleteBuffer == true) { - updateAutoCompleteBuffer(); - } - } + if (addToAutoCompleteBuffer == true) { + updateAutoCompleteBuffer(); + } + } } void ChatManager::updateAutoCompleteBuffer() { - if(text.empty() == false) { - int startPos = -1; - for(int i = (int)text.size()-1; i >= 0; --i) { - if(text[i] != ' ') { - startPos = i; - } - else { - break; - } - } - - if(startPos >= 0) { - lastAutoCompleteSearchText = text.substr(startPos); - } - } + if (text.empty() == false) { + int startPos = -1; + for (int i = (int)text.size() - 1; i >= 0; --i) { + if (text[i] != ' ') { + startPos = i; + } else { + break; + } + } + + if (startPos >= 0) { + lastAutoCompleteSearchText = text.substr(startPos); + } + } } void ChatManager::addText(string text) { - int maxTextLenAllowed = (customCB != NULL ? this->maxCustomTextLength : maxTextLenght); - if(editEnabled && (int)text.size() + (int)this->text.size() <= maxTextLenAllowed) { - this->text += text; - for(int i= 0; i<(int)text.size() ; i++){ - textCharLength.push_back(1); - } - } + int maxTextLenAllowed = + (customCB != NULL ? this->maxCustomTextLength : maxTextLenght); + if (editEnabled && + (int)text.size() + (int)this->text.size() <= maxTextLenAllowed) { + this->text += text; + for (int i = 0; i < (int)text.size(); i++) { + textCharLength.push_back(1); + } + } } void ChatManager::updateNetwork() { - try { - GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); - //string text; - //string sender; - //Config &config= Config::getInstance(); - - //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] gameNetworkInterface->getChatText() [%s]\n",__FILE__,__FUNCTION__,__LINE__,gameNetworkInterface->getChatText().c_str()); - - if(gameNetworkInterface != NULL && - gameNetworkInterface->getChatTextList(false).empty() == false) { - Lang &lang= Lang::getInstance(); - - std::vector chatList = gameNetworkInterface->getChatTextList(true); - for(int idx = 0; idx < (int)chatList.size(); idx++) { - const ChatMsgInfo msg = chatList[idx]; - int teamIndex= msg.chatTeamIndex; - - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] got nmtText [%s] for team = %d\n",__FILE__,__FUNCTION__,msg.chatText.c_str(),teamIndex); - - if(teamIndex == -1 || teamIndex == thisTeamIndex) { - if(msg.targetLanguage == "" || lang.isLanguageLocal(msg.targetLanguage) == true) { - bool teamMode = (teamIndex != -1 && teamIndex == thisTeamIndex); - string playerName = gameNetworkInterface->getHumanPlayerName(); - if(this->manualPlayerNameOverride != "") { - playerName = this->manualPlayerNameOverride; - } - - //printf("Network chat msg from: [%d - %s] [%s]\n",msg.chatPlayerIndex,gameNetworkInterface->getHumanPlayerName().c_str(),this->manualPlayerNameOverride.c_str()); - - if(StartsWith(msg.chatText,"*")){ - if(msg.chatText.find(playerName) != string::npos){ - CoreData &coreData= CoreData::getInstance(); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - soundRenderer.playFx(coreData.getHighlightSound(),true); - } - console->addLine(msg.chatText.substr(1,msg.chatText.size()), true, msg.chatPlayerIndex,Vec3f(1.f, 1.f, 1.f),teamMode); - } - else { - console->addLine(msg.chatText, true, msg.chatPlayerIndex,Vec3f(1.f, 1.f, 1.f),teamMode); - } - - } - - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Added text to console\n",__FILE__,__FUNCTION__); - } - - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - } - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - //gameNetworkInterface->clearChatInfo(); - } - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - throw megaglest_runtime_error(szBuf); - } + try { + GameNetworkInterface *gameNetworkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + // string text; + // string sender; + // Config &config= Config::getInstance(); + + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] + // gameNetworkInterface->getChatText() + // [%s]\n",__FILE__,__FUNCTION__,__LINE__,gameNetworkInterface->getChatText().c_str()); + + if (gameNetworkInterface != NULL && + gameNetworkInterface->getChatTextList(false).empty() == false) { + Lang &lang = Lang::getInstance(); + + std::vector chatList = + gameNetworkInterface->getChatTextList(true); + for (int idx = 0; idx < (int)chatList.size(); idx++) { + const ChatMsgInfo msg = chatList[idx]; + int teamIndex = msg.chatTeamIndex; + + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s] got nmtText [%s] for team = %d\n", + __FILE__, __FUNCTION__, msg.chatText.c_str(), + teamIndex); + + if (teamIndex == -1 || teamIndex == thisTeamIndex) { + if (msg.targetLanguage == "" || + lang.isLanguageLocal(msg.targetLanguage) == true) { + bool teamMode = (teamIndex != -1 && teamIndex == thisTeamIndex); + string playerName = gameNetworkInterface->getHumanPlayerName(); + if (this->manualPlayerNameOverride != "") { + playerName = this->manualPlayerNameOverride; + } + + // printf("Network chat msg from: [%d - %s] + // [%s]\n",msg.chatPlayerIndex,gameNetworkInterface->getHumanPlayerName().c_str(),this->manualPlayerNameOverride.c_str()); + + if (StartsWith(msg.chatText, "*")) { + if (msg.chatText.find(playerName) != string::npos) { + CoreData &coreData = CoreData::getInstance(); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + soundRenderer.playFx(coreData.getHighlightSound(), true); + } + console->addLine(msg.chatText.substr(1, msg.chatText.size()), + true, msg.chatPlayerIndex, Vec3f(1.f, 1.f, 1.f), + teamMode); + } else { + console->addLine(msg.chatText, true, msg.chatPlayerIndex, + Vec3f(1.f, 1.f, 1.f), teamMode); + } + } + + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s] Added text to console\n", + __FILE__, __FUNCTION__); + } + + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + } + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + // gameNetworkInterface->clearChatInfo(); + } + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] error [%s]\n", __FILE__, __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + throw megaglest_runtime_error(szBuf); + } } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/game/chat_manager.h b/source/glest_game/game/chat_manager.h index f63f78a6e..9c6a908e2 100644 --- a/source/glest_game/game/chat_manager.h +++ b/source/glest_game/game/chat_manager.h @@ -13,22 +13,23 @@ #define _GLEST_GAME_CHATMANAGER_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include #include "font.h" +#include "leak_dumper.h" #include +#include #include -#include "leak_dumper.h" -using std::string; -using std::vector; using Shared::Graphics::Font2D; using Shared::Graphics::Font3D; +using std::string; +using std::vector; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { class Console; @@ -37,8 +38,8 @@ class Console; // class CustomInputCallbackInterface { public: - virtual void processInputText(string text, bool cancelled) = 0; - virtual ~CustomInputCallbackInterface() {} + virtual void processInputText(string text, bool cancelled) = 0; + virtual ~CustomInputCallbackInterface() {} }; // ===================================================== @@ -48,67 +49,75 @@ class CustomInputCallbackInterface { class ChatManager { private: - bool editEnabled; - bool teamMode; - bool disableTeamMode; - Console* console; - string text; - vector textCharLength; - int thisTeamIndex; - bool inMenu; - string manualPlayerNameOverride; - int xPos; - int yPos; - int maxTextLenght; - Font2D *font; - Font3D *font3D; - - string lastAutoCompleteSearchText; - vector autoCompleteTextList; - - CustomInputCallbackInterface *customCB; - int maxCustomTextLength; - - string getTextWithLengthCheck(string text, int currentLength, int maxLength); - void appendText(string addText, bool validateChars=true,bool addToAutoCompleteBuffer=true); - void deleteText(int deleteCount,bool addToAutoCompleteBuffer=true); - void updateAutoCompleteBuffer(); + bool editEnabled; + bool teamMode; + bool disableTeamMode; + Console *console; + string text; + vector textCharLength; + int thisTeamIndex; + bool inMenu; + string manualPlayerNameOverride; + int xPos; + int yPos; + int maxTextLenght; + Font2D *font; + Font3D *font3D; + + string lastAutoCompleteSearchText; + vector autoCompleteTextList; + + CustomInputCallbackInterface *customCB; + int maxCustomTextLength; + + string getTextWithLengthCheck(string text, int currentLength, int maxLength); + void appendText(string addText, bool validateChars = true, + bool addToAutoCompleteBuffer = true); + void deleteText(int deleteCount, bool addToAutoCompleteBuffer = true); + void updateAutoCompleteBuffer(); public: - ChatManager(); - void init(Console* console, int thisTeamIndex, const bool inMenu=false, string manualPlayerNameOverride=""); - - bool textInput(std::string text); - void keyDown(SDL_KeyboardEvent key); - void keyUp(SDL_KeyboardEvent key); - void keyPress(SDL_KeyboardEvent c); - void updateNetwork(); - - bool getEditEnabled() const {return editEnabled;} - bool getTeamMode() const {return teamMode;} - bool getInMenu() const {return inMenu;} - string getText() const {return text;} - int getXPos() const {return xPos;} - void setXPos(int xPos) {this->xPos= xPos;} - int getYPos() const {return yPos;} - void setYPos(int yPos) {this->yPos= yPos;} - int getMaxTextLenght() const {return maxTextLenght;} - void setMaxTextLenght(int maxTextLenght) {this->maxTextLenght= maxTextLenght;} - Font2D *getFont() const {return font;} - Font3D *getFont3D() const {return font3D;} - void setFont(Font2D *font) {this->font= font;} - void setFont3D(Font3D *font) {this->font3D= font;} - void addText(string text); - void switchOnEdit(CustomInputCallbackInterface *customCB=NULL,int maxCustomTextLength=-1); - - bool getDisableTeamMode() const { return disableTeamMode; } - void setDisableTeamMode(bool value); - - void setAutoCompleteTextList(const vector &list) { autoCompleteTextList = list; } - - bool isInCustomInputMode() const { return customCB != NULL; }; + ChatManager(); + void init(Console *console, int thisTeamIndex, const bool inMenu = false, + string manualPlayerNameOverride = ""); + + bool textInput(std::string text); + void keyDown(SDL_KeyboardEvent key); + void keyUp(SDL_KeyboardEvent key); + void keyPress(SDL_KeyboardEvent c); + void updateNetwork(); + + bool getEditEnabled() const { return editEnabled; } + bool getTeamMode() const { return teamMode; } + bool getInMenu() const { return inMenu; } + string getText() const { return text; } + int getXPos() const { return xPos; } + void setXPos(int xPos) { this->xPos = xPos; } + int getYPos() const { return yPos; } + void setYPos(int yPos) { this->yPos = yPos; } + int getMaxTextLenght() const { return maxTextLenght; } + void setMaxTextLenght(int maxTextLenght) { + this->maxTextLenght = maxTextLenght; + } + Font2D *getFont() const { return font; } + Font3D *getFont3D() const { return font3D; } + void setFont(Font2D *font) { this->font = font; } + void setFont3D(Font3D *font) { this->font3D = font; } + void addText(string text); + void switchOnEdit(CustomInputCallbackInterface *customCB = NULL, + int maxCustomTextLength = -1); + + bool getDisableTeamMode() const { return disableTeamMode; } + void setDisableTeamMode(bool value); + + void setAutoCompleteTextList(const vector &list) { + autoCompleteTextList = list; + } + + bool isInCustomInputMode() const { return customCB != NULL; }; }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/game/commander.cpp b/source/glest_game/game/commander.cpp index a9f10b75d..24b523e37 100644 --- a/source/glest_game/game/commander.cpp +++ b/source/glest_game/game/commander.cpp @@ -11,1067 +11,1443 @@ #include "commander.h" -#include "world.h" -#include "unit.h" -#include "conversion.h" -#include "upgrade.h" #include "command.h" #include "command_type.h" -#include "network_manager.h" -#include "console.h" #include "config.h" -#include "platform_util.h" +#include "console.h" +#include "conversion.h" #include "game.h" #include "game_settings.h" -#include "game.h" +#include "network_manager.h" +#include "platform_util.h" +#include "unit.h" +#include "upgrade.h" +#include "world.h" using namespace Shared::Graphics; using namespace Shared::Util; using namespace Shared::Platform; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class Commander // ===================================================== Commander::Commander() { - this->world = NULL; - this->pauseNetworkCommands = false; + this->world = NULL; + this->pauseNetworkCommands = false; } -Commander::~Commander() { +Commander::~Commander() {} + +void Commander::init(World *world) { this->world = world; } + +bool Commander::canSubmitCommandType(const Unit *unit, + const CommandType *commandType) const { + bool canSubmitCommand = true; + const MorphCommandType *mct = + dynamic_cast(commandType); + if (mct && unit->getCommandSize() > 0) { + Command *cur_command = unit->getCurrCommand(); + if (cur_command != NULL) { + const MorphCommandType *cur_mct = + dynamic_cast(cur_command->getCommandType()); + if (cur_mct && unit->getCurrSkill() && + unit->getCurrSkill()->getClass() == scMorph) { + const UnitType *morphUnitType = mct->getMorphUnit(); + const UnitType *cur_morphUnitType = cur_mct->getMorphUnit(); + + if (morphUnitType != NULL && cur_morphUnitType != NULL && + morphUnitType->getId() == cur_morphUnitType->getId()) { + canSubmitCommand = false; + } + } + } + } + return canSubmitCommand; } -void Commander::init(World *world){ - this->world= world; -} +std::pair +Commander::tryGiveCommand(const Selection *selection, + const CommandType *commandType, const Vec2i &pos, + const UnitType *unitType, CardinalDir facing, + bool tryQueue, Unit *targetUnit) const { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (this->pauseNetworkCommands == true) { + return std::pair(crFailUndefined, ""); + } + + std::pair result(crFailUndefined, ""); + if (selection->isEmpty() == false && commandType != NULL) { + Vec2i refPos; + CommandResultContainer results; + + refPos = world->getMap()->computeRefPos(selection); + + const Unit *builderUnit = + world->getMap()->findClosestUnitToPos(selection, pos, unitType); + + int builderUnitId = builderUnit->getId(); + CommandStateType commandStateType = cst_None; + int commandStateValue = -1; + + int unitCommandGroupId = -1; + if (selection->getCount() > 1) { + unitCommandGroupId = world->getNextCommandGroupId(); + } + + // give orders to all selected units + for (int i = 0; i < selection->getCount(); ++i) { + const Unit *unit = selection->getUnit(i); + + std::pair resultCur(crFailUndefined, ""); + bool canSubmitCommand = canSubmitCommandType(unit, commandType); + if (canSubmitCommand == true) { + int unitId = unit->getId(); + Vec2i currPos = world->getMap()->computeDestPos( + refPos, unit->getPosNotThreadSafe(), pos); + + Vec2i usePos = currPos; + const CommandType *useCommandtype = commandType; + if (dynamic_cast(commandType) != NULL) { + usePos = pos; + if (builderUnit->getId() != unitId) { + useCommandtype = unit->getType()->getFirstRepairCommand(unitType); + commandStateType = cst_linkedUnit; + commandStateValue = builderUnitId; + } else { + commandStateType = cst_None; + commandStateValue = -1; + } + } -bool Commander::canSubmitCommandType(const Unit *unit, const CommandType *commandType) const { - bool canSubmitCommand=true; - const MorphCommandType *mct = dynamic_cast(commandType); - if(mct && unit->getCommandSize() > 0) { - Command *cur_command= unit->getCurrCommand(); - if(cur_command != NULL) { - const MorphCommandType *cur_mct= dynamic_cast(cur_command->getCommandType()); - if(cur_mct && unit->getCurrSkill() && unit->getCurrSkill()->getClass() == scMorph) { - const UnitType *morphUnitType = mct->getMorphUnit(); - const UnitType *cur_morphUnitType = cur_mct->getMorphUnit(); - - if(morphUnitType != NULL && cur_morphUnitType != NULL && morphUnitType->getId() == cur_morphUnitType->getId()) { - canSubmitCommand = false; - } - } - } - } - return canSubmitCommand; + if (useCommandtype != NULL) { + NetworkCommand networkCommand( + this->world, nctGiveCommand, unitId, useCommandtype->getId(), + usePos, unitType->getId(), + (targetUnit != NULL ? targetUnit->getId() : -1), facing, tryQueue, + commandStateType, commandStateValue, unitCommandGroupId); + + // every unit is ordered to a the position + resultCur = pushNetworkCommand(&networkCommand); + } + } + + results.push_back(resultCur); + } + + return computeResult(results); + } + return std::pair(crFailUndefined, ""); } -std::pair Commander::tryGiveCommand(const Selection *selection, const CommandType *commandType, - const Vec2i &pos, const UnitType* unitType, - CardinalDir facing, bool tryQueue,Unit *targetUnit) const { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(this->pauseNetworkCommands == true) { - return std::pair(crFailUndefined,""); - } - - std::pair result(crFailUndefined,""); - if(selection->isEmpty() == false && commandType != NULL) { - Vec2i refPos; - CommandResultContainer results; - - refPos = world->getMap()->computeRefPos(selection); - - const Unit *builderUnit = world->getMap()->findClosestUnitToPos(selection, pos, unitType); - - int builderUnitId = builderUnit->getId(); - CommandStateType commandStateType = cst_None; - int commandStateValue = -1; - - int unitCommandGroupId = -1; - if(selection->getCount() > 1) { - unitCommandGroupId = world->getNextCommandGroupId(); - } - - //give orders to all selected units - for(int i = 0; i < selection->getCount(); ++i) { - const Unit *unit = selection->getUnit(i); - - - std::pair resultCur(crFailUndefined,""); - bool canSubmitCommand = canSubmitCommandType(unit, commandType); - if(canSubmitCommand == true) { - int unitId= unit->getId(); - Vec2i currPos= world->getMap()->computeDestPos(refPos, unit->getPosNotThreadSafe(), pos); - - Vec2i usePos = currPos; - const CommandType *useCommandtype = commandType; - if(dynamic_cast(commandType) != NULL) { - usePos = pos; - if(builderUnit->getId() != unitId) { - useCommandtype = unit->getType()->getFirstRepairCommand(unitType); - commandStateType = cst_linkedUnit; - commandStateValue = builderUnitId; - } - else { - commandStateType = cst_None; - commandStateValue = -1; - } - } - - if(useCommandtype != NULL) { - NetworkCommand networkCommand(this->world,nctGiveCommand, unitId, - useCommandtype->getId(), usePos, unitType->getId(), - (targetUnit != NULL ? targetUnit->getId() : -1), - facing, tryQueue, commandStateType,commandStateValue, - unitCommandGroupId); - - //every unit is ordered to a the position - resultCur= pushNetworkCommand(&networkCommand); - } - } - - results.push_back(resultCur); - } - - return computeResult(results); - } - return std::pair(crFailUndefined,""); +std::pair +Commander::tryGiveCommand(const Unit *unit, const CommandType *commandType, + const Vec2i &pos, const UnitType *unitType, + CardinalDir facing, bool tryQueue, Unit *targetUnit, + int unitGroupCommandId) const { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (this->pauseNetworkCommands == true) { + return std::pair(crFailUndefined, ""); + } + + Chrono chrono; + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) + chrono.start(); + + assert(this->world != NULL); + assert(unit != NULL); + assert(commandType != NULL); + assert(unitType != NULL); + + 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()); + + std::pair result(crFailUndefined, ""); + bool canSubmitCommand = canSubmitCommandType(unit, commandType); + if (canSubmitCommand == true) { + NetworkCommand networkCommand( + this->world, nctGiveCommand, unit->getId(), commandType->getId(), pos, + unitType->getId(), (targetUnit != NULL ? targetUnit->getId() : -1), + facing, tryQueue, cst_None, -1, unitGroupCommandId); + + 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()); + + result = pushNetworkCommand(&networkCommand); + } + + 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()); + + return result; } -std::pair Commander::tryGiveCommand(const Unit* unit, const CommandType *commandType, - const Vec2i &pos, const UnitType* unitType, - CardinalDir facing, bool tryQueue,Unit *targetUnit, - int unitGroupCommandId) const { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +std::pair +Commander::tryGiveCommand(const Selection *selection, CommandClass commandClass, + const Vec2i &pos, const Unit *targetUnit, + bool tryQueue) const { + + if (this->pauseNetworkCommands == true) { + return std::pair(crFailUndefined, ""); + } + + std::pair result(crFailUndefined, ""); + if (selection->isEmpty() == false) { + Vec2i refPos, currPos; + CommandResultContainer results; - if(this->pauseNetworkCommands == true) { - return std::pair(crFailUndefined,""); - } + refPos = world->getMap()->computeRefPos(selection); - Chrono chrono; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); + int unitCommandGroupId = -1; + if (selection->getCount() > 1) { + unitCommandGroupId = world->getNextCommandGroupId(); + } - assert(this->world != NULL); - assert(unit != NULL); - assert(commandType != NULL); - assert(unitType != NULL); + // give orders to all selected units + for (int i = 0; i < selection->getCount(); ++i) { + const Unit *unit = selection->getUnit(i); + const CommandType *ct = unit->getType()->getFirstCtOfClass(commandClass); + if (ct != NULL) { + std::pair resultCur(crFailUndefined, ""); + + bool canSubmitCommand = canSubmitCommandType(unit, ct); + if (canSubmitCommand == true) { + + int targetId = + targetUnit == NULL ? Unit::invalidId : targetUnit->getId(); + int unitId = selection->getUnit(i)->getId(); + Vec2i currPos = world->getMap()->computeDestPos( + refPos, selection->getUnit(i)->getPosNotThreadSafe(), pos); + NetworkCommand networkCommand( + this->world, nctGiveCommand, unitId, ct->getId(), currPos, -1, + targetId, -1, tryQueue, cst_None, -1, unitCommandGroupId); + + // every unit is ordered to a different pos + resultCur = pushNetworkCommand(&networkCommand); + } + results.push_back(resultCur); + } else { + results.push_back( + std::pair(crFailUndefined, "")); + } + } + return computeResult(results); + } else { + return std::pair(crFailUndefined, ""); + } +} - 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()); +std::pair +Commander::tryGiveCommand(const Selection *selection, + const CommandType *commandType, const Vec2i &pos, + const Unit *targetUnit, bool tryQueue) const { - std::pair result(crFailUndefined,""); - bool canSubmitCommand=canSubmitCommandType(unit, commandType); - if(canSubmitCommand == true) { - NetworkCommand networkCommand(this->world,nctGiveCommand, unit->getId(), - commandType->getId(), pos, unitType->getId(), - (targetUnit != NULL ? targetUnit->getId() : -1), - facing, tryQueue,cst_None,-1,unitGroupCommandId); + if (this->pauseNetworkCommands == true) { + return std::pair(crFailUndefined, ""); + } - 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()); + std::pair result(crFailUndefined, ""); - result = pushNetworkCommand(&networkCommand); - } + if (!selection->isEmpty() && commandType != NULL) { + Vec2i refPos; + CommandResultContainer results; - 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()); + refPos = world->getMap()->computeRefPos(selection); - return result; -} + int unitCommandGroupId = -1; + if (selection->getCount() > 1) { + unitCommandGroupId = world->getNextCommandGroupId(); + } -std::pair Commander::tryGiveCommand(const Selection *selection, CommandClass commandClass, - const Vec2i &pos, const Unit *targetUnit, bool tryQueue) const{ - - if(this->pauseNetworkCommands == true) { - return std::pair(crFailUndefined,""); - } - - std::pair result(crFailUndefined,""); - if(selection->isEmpty() == false) { - Vec2i refPos, currPos; - CommandResultContainer results; - - refPos= world->getMap()->computeRefPos(selection); - - int unitCommandGroupId = -1; - if(selection->getCount() > 1) { - unitCommandGroupId = world->getNextCommandGroupId(); - } - - //give orders to all selected units - for(int i = 0; i < selection->getCount(); ++i) { - const Unit *unit= selection->getUnit(i); - const CommandType *ct= unit->getType()->getFirstCtOfClass(commandClass); - if(ct != NULL) { - std::pair resultCur(crFailUndefined,""); - - bool canSubmitCommand=canSubmitCommandType(unit, ct); - if(canSubmitCommand == true) { - - int targetId= targetUnit==NULL? Unit::invalidId: targetUnit->getId(); - int unitId= selection->getUnit(i)->getId(); - Vec2i currPos= world->getMap()->computeDestPos(refPos, - selection->getUnit(i)->getPosNotThreadSafe(), pos); - NetworkCommand networkCommand(this->world,nctGiveCommand, - unitId, ct->getId(), currPos, -1, targetId, -1, - tryQueue,cst_None,-1,unitCommandGroupId); - - //every unit is ordered to a different pos - resultCur= pushNetworkCommand(&networkCommand); - } - results.push_back(resultCur); - } - else{ - results.push_back(std::pair(crFailUndefined,"")); - } - } - return computeResult(results); - } - else { - return std::pair(crFailUndefined,""); - } -} + // give orders to all selected units + for (int i = 0; i < selection->getCount(); ++i) { + const Unit *unit = selection->getUnit(i); + assert(unit != NULL); + + std::pair resultCur(crFailUndefined, ""); + + bool canSubmitCommand = canSubmitCommandType(unit, commandType); + if (canSubmitCommand == true) { + int targetId = + targetUnit == NULL ? Unit::invalidId : targetUnit->getId(); + int unitId = unit->getId(); + Vec2i currPos = world->getMap()->computeDestPos( + refPos, unit->getPosNotThreadSafe(), pos); + NetworkCommand networkCommand( + this->world, nctGiveCommand, unitId, commandType->getId(), currPos, + -1, targetId, -1, tryQueue, cst_None, -1, unitCommandGroupId); + + // every unit is ordered to a different position + resultCur = pushNetworkCommand(&networkCommand); + } + results.push_back(resultCur); + } -std::pair Commander::tryGiveCommand(const Selection *selection, - const CommandType *commandType, const Vec2i &pos, - const Unit *targetUnit, bool tryQueue) const { - - if(this->pauseNetworkCommands == true) { - return std::pair(crFailUndefined,""); - } - - std::pair result(crFailUndefined,""); - - if(!selection->isEmpty() && commandType!=NULL){ - Vec2i refPos; - CommandResultContainer results; - - refPos= world->getMap()->computeRefPos(selection); - - int unitCommandGroupId = -1; - if(selection->getCount() > 1) { - unitCommandGroupId = world->getNextCommandGroupId(); - } - - //give orders to all selected units - for(int i = 0; i < selection->getCount(); ++i) { - const Unit *unit = selection->getUnit(i); - assert(unit != NULL); - - std::pair resultCur(crFailUndefined,""); - - bool canSubmitCommand=canSubmitCommandType(unit, commandType); - if(canSubmitCommand == true) { - int targetId= targetUnit==NULL? Unit::invalidId: targetUnit->getId(); - int unitId= unit->getId(); - Vec2i currPos= world->getMap()->computeDestPos(refPos, unit->getPosNotThreadSafe(), pos); - NetworkCommand networkCommand(this->world,nctGiveCommand, unitId, - commandType->getId(), currPos, -1, targetId, -1, tryQueue, - cst_None, -1, unitCommandGroupId); - - //every unit is ordered to a different position - resultCur= pushNetworkCommand(&networkCommand); - } - results.push_back(resultCur); - } - - return computeResult(results); - } - else{ - return std::pair(crFailUndefined,""); - } + return computeResult(results); + } else { + return std::pair(crFailUndefined, ""); + } } -//auto command -std::pair Commander::tryGiveCommand(const Selection *selection, const Vec2i &pos, - const Unit *targetUnit, bool tryQueue, int unitCommandGroupId) const { - - if(this->pauseNetworkCommands == true) { - return std::pair(crFailUndefined,""); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - std::pair result(crFailUndefined,""); - - if(selection->isEmpty() == false){ - Vec2i refPos, currPos; - CommandResultContainer results; - - if(unitCommandGroupId == -1 && selection->getCount() > 1) { - unitCommandGroupId = world->getNextCommandGroupId(); - } - - //give orders to all selected units - refPos= world->getMap()->computeRefPos(selection); - for(int i=0; i < selection->getCount(); ++i) { - //every unit is ordered to a different pos - const Unit *unit = selection->getUnit(i); - assert(unit != NULL); - - currPos= world->getMap()->computeDestPos(refPos, unit->getPosNotThreadSafe(), pos); - - //get command type - const CommandType *commandType= unit->computeCommandType(pos, targetUnit); - - //give commands - if(commandType != NULL) { - int targetId= targetUnit==NULL? Unit::invalidId: targetUnit->getId(); - int unitId= unit->getId(); - - std::pair resultCur(crFailUndefined,""); - - bool canSubmitCommand=canSubmitCommandType(unit, commandType); - if(canSubmitCommand == true) { - NetworkCommand networkCommand(this->world,nctGiveCommand, - unitId, commandType->getId(), currPos, -1, targetId, - -1, tryQueue, cst_None, -1, unitCommandGroupId); - resultCur= pushNetworkCommand(&networkCommand); - } - results.push_back(resultCur); - } - else if(unit->isMeetingPointSettable() == true) { - NetworkCommand command(this->world,nctSetMeetingPoint, - unit->getId(), -1, currPos,-1,-1,-1,false, - cst_None,-1,unitCommandGroupId); - - std::pair resultCur= pushNetworkCommand(&command); - results.push_back(resultCur); - } - else { - results.push_back(std::pair(crFailUndefined,"")); - } - } - result = computeResult(results); - } - - return result; +// auto command +std::pair +Commander::tryGiveCommand(const Selection *selection, const Vec2i &pos, + const Unit *targetUnit, bool tryQueue, + int unitCommandGroupId) const { + + if (this->pauseNetworkCommands == true) { + return std::pair(crFailUndefined, ""); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + std::pair result(crFailUndefined, ""); + + if (selection->isEmpty() == false) { + Vec2i refPos, currPos; + CommandResultContainer results; + + if (unitCommandGroupId == -1 && selection->getCount() > 1) { + unitCommandGroupId = world->getNextCommandGroupId(); + } + + // give orders to all selected units + refPos = world->getMap()->computeRefPos(selection); + for (int i = 0; i < selection->getCount(); ++i) { + // every unit is ordered to a different pos + const Unit *unit = selection->getUnit(i); + assert(unit != NULL); + + currPos = world->getMap()->computeDestPos( + refPos, unit->getPosNotThreadSafe(), pos); + + // get command type + const CommandType *commandType = + unit->computeCommandType(pos, targetUnit); + + // give commands + if (commandType != NULL) { + int targetId = + targetUnit == NULL ? Unit::invalidId : targetUnit->getId(); + int unitId = unit->getId(); + + std::pair resultCur(crFailUndefined, ""); + + bool canSubmitCommand = canSubmitCommandType(unit, commandType); + if (canSubmitCommand == true) { + NetworkCommand networkCommand(this->world, nctGiveCommand, unitId, + commandType->getId(), currPos, -1, + targetId, -1, tryQueue, cst_None, -1, + unitCommandGroupId); + resultCur = pushNetworkCommand(&networkCommand); + } + results.push_back(resultCur); + } else if (unit->isMeetingPointSettable() == true) { + NetworkCommand command(this->world, nctSetMeetingPoint, unit->getId(), + -1, currPos, -1, -1, -1, false, cst_None, -1, + unitCommandGroupId); + + std::pair resultCur = + pushNetworkCommand(&command); + results.push_back(resultCur); + } else { + results.push_back( + std::pair(crFailUndefined, "")); + } + } + result = computeResult(results); + } + + return result; } CommandResult Commander::tryCancelCommand(const Selection *selection) const { - if(this->pauseNetworkCommands == true) { - return crFailUndefined; - } - - int unitCommandGroupId = -1; - if(selection->getCount() > 1) { - unitCommandGroupId = world->getNextCommandGroupId(); - } - - for(int i = 0; i < selection->getCount(); ++i) { - NetworkCommand command(this->world,nctCancelCommand, - selection->getUnit(i)->getId(),-1,Vec2i(0),-1,-1,-1,false, - cst_None,-1,unitCommandGroupId); - pushNetworkCommand(&command); - } - - return crSuccess; + if (this->pauseNetworkCommands == true) { + return crFailUndefined; + } + + int unitCommandGroupId = -1; + if (selection->getCount() > 1) { + unitCommandGroupId = world->getNextCommandGroupId(); + } + + for (int i = 0; i < selection->getCount(); ++i) { + NetworkCommand command(this->world, nctCancelCommand, + selection->getUnit(i)->getId(), -1, Vec2i(0), -1, -1, + -1, false, cst_None, -1, unitCommandGroupId); + pushNetworkCommand(&command); + } + + return crSuccess; } -void Commander::trySetMeetingPoint(const Unit* unit, const Vec2i &pos) const { - if(this->pauseNetworkCommands == true) { - return; - } +void Commander::trySetMeetingPoint(const Unit *unit, const Vec2i &pos) const { + if (this->pauseNetworkCommands == true) { + return; + } - NetworkCommand command(this->world,nctSetMeetingPoint, unit->getId(), -1, pos); - pushNetworkCommand(&command); + NetworkCommand command(this->world, nctSetMeetingPoint, unit->getId(), -1, + pos); + pushNetworkCommand(&command); } -void Commander::trySwitchTeam(const Faction* faction, int teamIndex) const { - if(this->pauseNetworkCommands == true) { - return; - } +void Commander::trySwitchTeam(const Faction *faction, int teamIndex) const { + if (this->pauseNetworkCommands == true) { + return; + } - NetworkCommand command(this->world,nctSwitchTeam, faction->getIndex(), teamIndex); - pushNetworkCommand(&command); + NetworkCommand command(this->world, nctSwitchTeam, faction->getIndex(), + teamIndex); + pushNetworkCommand(&command); } -void Commander::trySwitchTeamVote(const Faction* faction, SwitchTeamVote *vote) const { - if(this->pauseNetworkCommands == true) { - return; - } +void Commander::trySwitchTeamVote(const Faction *faction, + SwitchTeamVote *vote) const { + if (this->pauseNetworkCommands == true) { + return; + } - NetworkCommand command(this->world,nctSwitchTeamVote, faction->getIndex(), vote->factionIndex,Vec2i(0),vote->allowSwitchTeam); - pushNetworkCommand(&command); + NetworkCommand command(this->world, nctSwitchTeamVote, faction->getIndex(), + vote->factionIndex, Vec2i(0), vote->allowSwitchTeam); + pushNetworkCommand(&command); } -void Commander::tryDisconnectNetworkPlayer(const Faction* faction, int playerIndex) const { - NetworkCommand command(this->world,nctDisconnectNetworkPlayer, faction->getIndex(), playerIndex); - pushNetworkCommand(&command); +void Commander::tryDisconnectNetworkPlayer(const Faction *faction, + int playerIndex) const { + NetworkCommand command(this->world, nctDisconnectNetworkPlayer, + faction->getIndex(), playerIndex); + pushNetworkCommand(&command); } void Commander::tryPauseGame(bool joinNetworkGame, bool clearCaches) const { - NetworkCommand command(this->world,nctPauseResume,1); - command.commandTypeId = (clearCaches == true ? 1 : 0); - command.unitTypeId = (joinNetworkGame == true ? 1 : 0); - pushNetworkCommand(&command); + NetworkCommand command(this->world, nctPauseResume, 1); + command.commandTypeId = (clearCaches == true ? 1 : 0); + command.unitTypeId = (joinNetworkGame == true ? 1 : 0); + pushNetworkCommand(&command); } void Commander::tryResumeGame(bool joinNetworkGame, bool clearCaches) const { - NetworkCommand command(this->world,nctPauseResume,0); - command.commandTypeId = (clearCaches == true ? 1 : 0); - command.unitTypeId = (joinNetworkGame == true ? 1 : 0); - pushNetworkCommand(&command); + NetworkCommand command(this->world, nctPauseResume, 0); + command.commandTypeId = (clearCaches == true ? 1 : 0); + command.unitTypeId = (joinNetworkGame == true ? 1 : 0); + pushNetworkCommand(&command); } void Commander::tryNetworkPlayerDisconnected(int factionIndex) const { - //printf("tryNetworkPlayerDisconnected factionIndex: %d\n",factionIndex); + // printf("tryNetworkPlayerDisconnected factionIndex: %d\n",factionIndex); - //if(this->pauseNetworkCommands == true) { - // return; - //} + // if(this->pauseNetworkCommands == true) { + // return; + // } - NetworkCommand command(this->world,nctPlayerStatusChange, factionIndex, npst_Disconnected); - pushNetworkCommand(&command); + NetworkCommand command(this->world, nctPlayerStatusChange, factionIndex, + npst_Disconnected); + pushNetworkCommand(&command); } // ==================== PRIVATE ==================== -std::pair Commander::computeResult(const CommandResultContainer &results) const { - std::pair result(crFailUndefined,""); - switch(results.size()) { - case 0: - return std::pair(crFailUndefined,""); - case 1: - return results.front(); - default: - for(int i = 0; i < (int)results.size(); ++i) { - if(results[i].first != crSuccess) { - return std::pair(crSomeFailed,results[i].second); - } - } - break; - } - return std::pair(crSuccess,""); +std::pair +Commander::computeResult(const CommandResultContainer &results) const { + std::pair result(crFailUndefined, ""); + switch (results.size()) { + case 0: + return std::pair(crFailUndefined, ""); + case 1: + return results.front(); + default: + for (int i = 0; i < (int)results.size(); ++i) { + if (results[i].first != crSuccess) { + return std::pair(crSomeFailed, + results[i].second); + } + } + break; + } + return std::pair(crSuccess, ""); } -std::pair Commander::pushNetworkCommand(const NetworkCommand* networkCommand) const { - GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); - std::pair result(crSuccess,""); - - //validate unit - const Unit* unit = NULL; - if( networkCommand->getNetworkCommandType() != nctSwitchTeam && - networkCommand->getNetworkCommandType() != nctSwitchTeamVote && - networkCommand->getNetworkCommandType() != nctPauseResume && - networkCommand->getNetworkCommandType() != nctPlayerStatusChange && - networkCommand->getNetworkCommandType() != nctDisconnectNetworkPlayer) { - unit= world->findUnitById(networkCommand->getUnitId()); - if(unit == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s - %d] Command refers to non existent unit id = %d. Game out of synch.",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkCommand->getUnitId()); - GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); - if(gameNetworkInterface != NULL) { - char szMsg[8096]=""; - snprintf(szMsg,8096,"Player detected an error: Command refers to non existent unit id = %d. Game out of synch.",networkCommand->getUnitId()); - gameNetworkInterface->sendTextMessage(szMsg,-1, true, ""); - } - throw megaglest_runtime_error(szBuf); - } - } - - //add the command to the interface - gameNetworkInterface->requestCommand(networkCommand); - - //calculate the result of the command - if(unit != NULL && networkCommand->getNetworkCommandType() == nctGiveCommand) { - //printf("In [%s::%s Line: %d] result.first = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,result.first); - Command* command= buildCommand(networkCommand); - result= unit->checkCommand(command); - delete command; - } - return result; +std::pair +Commander::pushNetworkCommand(const NetworkCommand *networkCommand) const { + GameNetworkInterface *gameNetworkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + std::pair result(crSuccess, ""); + + // validate unit + const Unit *unit = NULL; + if (networkCommand->getNetworkCommandType() != nctSwitchTeam && + networkCommand->getNetworkCommandType() != nctSwitchTeamVote && + networkCommand->getNetworkCommandType() != nctPauseResume && + networkCommand->getNetworkCommandType() != nctPlayerStatusChange && + networkCommand->getNetworkCommandType() != nctDisconnectNetworkPlayer) { + unit = world->findUnitById(networkCommand->getUnitId()); + if (unit == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s - %d] Command refers to non existent unit id = %d. " + "Game out of synch.", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, networkCommand->getUnitId()); + GameNetworkInterface *gameNetworkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + if (gameNetworkInterface != NULL) { + char szMsg[8096] = ""; + snprintf(szMsg, 8096, + "Player detected an error: Command refers to non existent " + "unit id = %d. Game out of synch.", + networkCommand->getUnitId()); + gameNetworkInterface->sendTextMessage(szMsg, -1, true, ""); + } + throw megaglest_runtime_error(szBuf); + } + } + + // add the command to the interface + gameNetworkInterface->requestCommand(networkCommand); + + // calculate the result of the command + if (unit != NULL && + networkCommand->getNetworkCommandType() == nctGiveCommand) { + // printf("In [%s::%s Line: %d] result.first = + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,result.first); + Command *command = buildCommand(networkCommand); + result = unit->checkCommand(command); + delete command; + } + return result; } -void Commander::signalNetworkUpdate(Game *game) { - updateNetwork(game); -} +void Commander::signalNetworkUpdate(Game *game) { updateNetwork(game); } bool Commander::getReplayCommandListForFrame(int worldFrameCount) { - bool haveReplyCommands = false; - if(replayCommandList.empty() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("worldFrameCount = %d replayCommandList.size() = " MG_SIZE_T_SPECIFIER "\n",worldFrameCount,replayCommandList.size()); - - std::vector replayList; - for(unsigned int i = 0; i < replayCommandList.size(); ++i) { - std::pair &cmd = replayCommandList[i]; - if(cmd.first <= worldFrameCount) { - replayList.push_back(cmd.second); - haveReplyCommands = true; - } - } - if(haveReplyCommands == true) { - replayCommandList.erase(replayCommandList.begin(),replayCommandList.begin() + replayList.size()); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("worldFrameCount = %d GIVING COMMANDS replayList.size() = " MG_SIZE_T_SPECIFIER "\n",worldFrameCount,replayList.size()); - for(int i= 0; i < (int)replayList.size(); ++i){ - giveNetworkCommand(&replayList[i]); - } - GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); - gameNetworkInterface->setKeyframe(worldFrameCount); - } - } - return haveReplyCommands; + bool haveReplyCommands = false; + if (replayCommandList.empty() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf( + "worldFrameCount = %d replayCommandList.size() = " MG_SIZE_T_SPECIFIER + "\n", + worldFrameCount, replayCommandList.size()); + + std::vector replayList; + for (unsigned int i = 0; i < replayCommandList.size(); ++i) { + std::pair &cmd = replayCommandList[i]; + if (cmd.first <= worldFrameCount) { + replayList.push_back(cmd.second); + haveReplyCommands = true; + } + } + if (haveReplyCommands == true) { + replayCommandList.erase(replayCommandList.begin(), + replayCommandList.begin() + replayList.size()); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("worldFrameCount = %d GIVING COMMANDS replayList.size() " + "= " MG_SIZE_T_SPECIFIER "\n", + worldFrameCount, replayList.size()); + for (int i = 0; i < (int)replayList.size(); ++i) { + giveNetworkCommand(&replayList[i]); + } + GameNetworkInterface *gameNetworkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + gameNetworkInterface->setKeyframe(worldFrameCount); + } + } + return haveReplyCommands; } bool Commander::hasReplayCommandListForFrame() const { - return (replayCommandList.empty() == false); + return (replayCommandList.empty() == false); } int Commander::getReplayCommandListForFrameCount() const { - return (int)replayCommandList.size(); + return (int)replayCommandList.size(); } void Commander::updateNetwork(Game *game) { - if(world == NULL) { - return; - } - NetworkManager &networkManager= NetworkManager::getInstance(); - - //check that this is a keyframe - if(game != NULL) { - GameSettings *gameSettings = game->getGameSettings(); - if( networkManager.isNetworkGame() == false || - (world->getFrameCount() % gameSettings->getNetworkFramePeriod()) == 0) { - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] networkManager.isNetworkGame() = %d,world->getFrameCount() = %d, gameSettings->getNetworkFramePeriod() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkManager.isNetworkGame(),world->getFrameCount(),gameSettings->getNetworkFramePeriod()); - - if(getReplayCommandListForFrame(world->getFrameCount()) == false) { - GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) perfTimer.start(); - //update the keyframe - gameNetworkInterface->updateKeyframe(world->getFrameCount()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && perfTimer.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] gameNetworkInterface->updateKeyframe for %d took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,world->getFrameCount(),perfTimer.getMillis()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) perfTimer.start(); - //give pending commands - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("START process: %d network commands in frame: %d\n",gameNetworkInterface->getPendingCommandCount(),this->world->getFrameCount()); - for(int i= 0; i < gameNetworkInterface->getPendingCommandCount(); ++i){ - giveNetworkCommand(gameNetworkInterface->getPendingCommand(i)); - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("END process: %d network commands in frame: %d\n",gameNetworkInterface->getPendingCommandCount(),this->world->getFrameCount()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && perfTimer.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] giveNetworkCommand took %lld msecs, PendingCommandCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,perfTimer.getMillis(),gameNetworkInterface->getPendingCommandCount()); - gameNetworkInterface->clearPendingCommands(); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Cleared network commands in frame: %d\n",this->world->getFrameCount()); - } + if (world == NULL) { + return; + } + NetworkManager &networkManager = NetworkManager::getInstance(); + + // check that this is a keyframe + if (game != NULL) { + GameSettings *gameSettings = game->getGameSettings(); + if (networkManager.isNetworkGame() == false || + (world->getFrameCount() % gameSettings->getNetworkFramePeriod()) == 0) { + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] networkManager.isNetworkGame() = " + "%d,world->getFrameCount() = %d, " + "gameSettings->getNetworkFramePeriod() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, networkManager.isNetworkGame(), world->getFrameCount(), + gameSettings->getNetworkFramePeriod()); + + if (getReplayCommandListForFrame(world->getFrameCount()) == false) { + GameNetworkInterface *gameNetworkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled) + perfTimer.start(); + // update the keyframe + gameNetworkInterface->updateKeyframe(world->getFrameCount()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + perfTimer.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] gameNetworkInterface->updateKeyframe for " + "%d took %lld msecs\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, world->getFrameCount(), perfTimer.getMillis()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled) + perfTimer.start(); + // give pending commands + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("START process: %d network commands in frame: %d\n", + gameNetworkInterface->getPendingCommandCount(), + this->world->getFrameCount()); + for (int i = 0; i < gameNetworkInterface->getPendingCommandCount(); + ++i) { + giveNetworkCommand(gameNetworkInterface->getPendingCommand(i)); } - } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("END process: %d network commands in frame: %d\n", + gameNetworkInterface->getPendingCommandCount(), + this->world->getFrameCount()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + perfTimer.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] giveNetworkCommand took %lld msecs, " + "PendingCommandCount = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, perfTimer.getMillis(), + gameNetworkInterface->getPendingCommandCount()); + gameNetworkInterface->clearPendingCommands(); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Cleared network commands in frame: %d\n", + this->world->getFrameCount()); + } + } + } } -void Commander::addToReplayCommandList(NetworkCommand &command,int worldFrameCount) { - replayCommandList.push_back(make_pair(worldFrameCount,command)); +void Commander::addToReplayCommandList(NetworkCommand &command, + int worldFrameCount) { + replayCommandList.push_back(make_pair(worldFrameCount, command)); } -void Commander::giveNetworkCommand(NetworkCommand* networkCommand) const { - Chrono chrono; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [START]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - - - world->getGame()->addNetworkCommandToReplayList(networkCommand,world->getFrameCount()); - - networkCommand->preprocessNetworkCommand(this->world); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [after networkCommand->preprocessNetworkCommand]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - - bool commandWasHandled = false; - // Handle special commands first (that just use network command members as placeholders) - switch(networkCommand->getNetworkCommandType()) { - case nctSwitchTeam: { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctSwitchTeam\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - commandWasHandled = true; - int factionIndex = networkCommand->getUnitId(); - int newTeam = networkCommand->getCommandTypeId(); - - // Auto join empty team or ask players to join - bool autoJoinTeam = true; - for(int i = 0; i < world->getFactionCount(); ++i) { - if(newTeam == world->getFaction(i)->getTeam()) { - autoJoinTeam = false; - break; - } - } - - if(autoJoinTeam == true) { - Faction *faction = world->getFaction(factionIndex); - int oldTeam = faction->getTeam(); - faction->setTeam(newTeam); - GameSettings *settings = world->getGameSettingsPtr(); - settings->setTeam(factionIndex,newTeam); - world->getStats()->setTeam(factionIndex, newTeam); - - if(factionIndex == world->getThisFactionIndex()) { - world->setThisTeamIndex(newTeam); - GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); - if(gameNetworkInterface != NULL) { - - Lang &lang= Lang::getInstance(); - const vector languageList = settings->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - char szMsg[8096]=""; - if(lang.hasString("PlayerSwitchedTeam",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("PlayerSwitchedTeam",languageList[i]).c_str(),settings->getNetworkPlayerName(factionIndex).c_str(),oldTeam,newTeam); - } - else { - snprintf(szMsg,8096,"Player %s switched from team# %d to team# %d.",settings->getNetworkPlayerName(factionIndex).c_str(),oldTeam,newTeam); - } - bool localEcho = lang.isLanguageLocal(languageList[i]); - gameNetworkInterface->sendTextMessage(szMsg,-1, localEcho,languageList[i]); - } - } - world->getGame()->reInitGUI(); - } - } - else { - for(int i = 0; i < world->getFactionCount(); ++i) { - if(newTeam == world->getFaction(i)->getTeam()) { - Faction *faction = world->getFaction(factionIndex); - - SwitchTeamVote vote; - vote.factionIndex = factionIndex; - vote.allowSwitchTeam = false; - vote.oldTeam = faction->getTeam(); - vote.newTeam = newTeam; - vote.voted = false; - - world->getFaction(i)->setSwitchTeamVote(vote); - } - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [after unit->setMeetingPos]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctSetMeetingPoint\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - break; - - case nctSwitchTeamVote: { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctSwitchTeamVote\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - commandWasHandled = true; - - int votingFactionIndex = networkCommand->getUnitId(); - int factionIndex = networkCommand->getCommandTypeId(); - bool allowSwitchTeam = networkCommand->getUnitTypeId() != 0; - - Faction *faction = world->getFaction(votingFactionIndex); - - SwitchTeamVote *vote = faction->getSwitchTeamVote(factionIndex); - if(vote == NULL) { - throw megaglest_runtime_error("vote == NULL"); - } - vote->voted = true; - vote->allowSwitchTeam = allowSwitchTeam; - - // Join the new team if > 50 % said yes - int newTeamTotalMemberCount=0; - int newTeamVotedYes=0; - int newTeamVotedNo=0; - - for(int i = 0; i < world->getFactionCount(); ++i) { - if(vote->newTeam == world->getFaction(i)->getTeam()) { - newTeamTotalMemberCount++; - - SwitchTeamVote *teamVote = world->getFaction(i)->getSwitchTeamVote(factionIndex); - if(teamVote != NULL && teamVote->voted == true) { - if(teamVote->allowSwitchTeam == true) { - newTeamVotedYes++; - } - else { - newTeamVotedNo++; - } - } - } - } - - // If > 50% of team vote yes, switch th eplayers team - if(newTeamTotalMemberCount > 0 && newTeamVotedYes > 0 && - static_cast(newTeamVotedYes) / static_cast(newTeamTotalMemberCount) > 0.5) { - Faction *faction = world->getFaction(factionIndex); - int oldTeam = faction->getTeam(); - faction->setTeam(vote->newTeam); - GameSettings *settings = world->getGameSettingsPtr(); - settings->setTeam(factionIndex,vote->newTeam); - world->getStats()->setTeam(factionIndex, vote->newTeam); - - if(factionIndex == world->getThisFactionIndex()) { - world->setThisTeamIndex(vote->newTeam); - GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); - if(gameNetworkInterface != NULL) { - - Lang &lang= Lang::getInstance(); - const vector languageList = settings->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - char szMsg[8096]=""; - if(lang.hasString("PlayerSwitchedTeam",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("PlayerSwitchedTeam",languageList[i]).c_str(),settings->getNetworkPlayerName(factionIndex).c_str(),oldTeam,vote->newTeam); - } - else { - snprintf(szMsg,8096,"Player %s switched from team# %d to team# %d.",settings->getNetworkPlayerName(factionIndex).c_str(),oldTeam,vote->newTeam); - } - bool localEcho = lang.isLanguageLocal(languageList[i]); - gameNetworkInterface->sendTextMessage(szMsg,-1, localEcho,languageList[i]); - } - } - world->getGame()->reInitGUI(); - } - } - else if(newTeamTotalMemberCount == (newTeamVotedYes + newTeamVotedNo)) { - if(factionIndex == world->getThisFactionIndex()) { - GameSettings *settings = world->getGameSettingsPtr(); - Faction *faction = world->getFaction(factionIndex); - int oldTeam = faction->getTeam(); - - GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); - if(gameNetworkInterface != NULL) { - - Lang &lang= Lang::getInstance(); - const vector languageList = settings->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - char szMsg[8096]=""; - if(lang.hasString("PlayerSwitchedTeamDenied",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("PlayerSwitchedTeamDenied",languageList[i]).c_str(),settings->getNetworkPlayerName(factionIndex).c_str(),oldTeam,vote->newTeam); - } - else { - snprintf(szMsg,8096,"Player %s was denied the request to switch from team# %d to team# %d.",settings->getNetworkPlayerName(factionIndex).c_str(),oldTeam,vote->newTeam); - } - bool localEcho = lang.isLanguageLocal(languageList[i]); - gameNetworkInterface->sendTextMessage(szMsg,-1, localEcho,languageList[i]); - } - } - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [after unit->setMeetingPos]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctSetMeetingPoint\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void Commander::giveNetworkCommand(NetworkCommand *networkCommand) const { + Chrono chrono; + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) + chrono.start(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld [START]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, chrono.getMillis()); + + world->getGame()->addNetworkCommandToReplayList(networkCommand, + world->getFrameCount()); + + networkCommand->preprocessNetworkCommand(this->world); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld [after " + "networkCommand->preprocessNetworkCommand]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, chrono.getMillis()); + + bool commandWasHandled = false; + // Handle special commands first (that just use network command members as + // placeholders) + switch (networkCommand->getNetworkCommandType()) { + case nctSwitchTeam: { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] found nctSwitchTeam\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + commandWasHandled = true; + int factionIndex = networkCommand->getUnitId(); + int newTeam = networkCommand->getCommandTypeId(); + + // Auto join empty team or ask players to join + bool autoJoinTeam = true; + for (int i = 0; i < world->getFactionCount(); ++i) { + if (newTeam == world->getFaction(i)->getTeam()) { + autoJoinTeam = false; + break; + } + } + + if (autoJoinTeam == true) { + Faction *faction = world->getFaction(factionIndex); + int oldTeam = faction->getTeam(); + faction->setTeam(newTeam); + GameSettings *settings = world->getGameSettingsPtr(); + settings->setTeam(factionIndex, newTeam); + world->getStats()->setTeam(factionIndex, newTeam); + + if (factionIndex == world->getThisFactionIndex()) { + world->setThisTeamIndex(newTeam); + GameNetworkInterface *gameNetworkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + if (gameNetworkInterface != NULL) { + + Lang &lang = Lang::getInstance(); + const vector languageList = + settings->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + char szMsg[8096] = ""; + if (lang.hasString("PlayerSwitchedTeam", languageList[i]) == true) { + snprintf( + szMsg, 8096, + lang.getString("PlayerSwitchedTeam", languageList[i]).c_str(), + settings->getNetworkPlayerName(factionIndex).c_str(), oldTeam, + newTeam); + } else { + snprintf(szMsg, 8096, + "Player %s switched from team# %d to team# %d.", + settings->getNetworkPlayerName(factionIndex).c_str(), + oldTeam, newTeam); + } + bool localEcho = lang.isLanguageLocal(languageList[i]); + gameNetworkInterface->sendTextMessage(szMsg, -1, localEcho, + languageList[i]); + } } - break; - - case nctDisconnectNetworkPlayer: { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctDisconnectNetworkPlayer\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - commandWasHandled = true; - - NetworkManager &networkManager= NetworkManager::getInstance(); - NetworkRole role = networkManager.getNetworkRole(); - //GameSettings *settings = world->getGameSettingsPtr(); - - if(role == nrServer) { - //int factionIndex = networkCommand->getUnitId(); - int playerIndex = networkCommand->getCommandTypeId(); - - GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); - if(gameNetworkInterface != NULL) { - ServerInterface *server = networkManager.getServerInterface(); - if(server != NULL && server->isClientConnected(playerIndex) == true) { - - MutexSafeWrapper safeMutex(server->getSlotMutex(playerIndex),CODE_AT_LINE); - ConnectionSlot *slot = server->getSlot(playerIndex,false); - if(slot != NULL) { - safeMutex.ReleaseLock(); - NetworkMessageQuit networkMessageQuit; - slot->sendMessage(&networkMessageQuit); - sleep(5); - - //printf("Sending nctDisconnectNetworkPlayer\n"); - server = networkManager.getServerInterface(false); - if(server != NULL) { - MutexSafeWrapper safeMutex2(server->getSlotMutex(playerIndex),CODE_AT_LINE); - slot = server->getSlot(playerIndex,false); - if(slot != NULL) { - safeMutex2.ReleaseLock(); - slot->close(); - } - } - } - } - } - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctDisconnectNetworkPlayer\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + world->getGame()->reInitGUI(); + } + } else { + for (int i = 0; i < world->getFactionCount(); ++i) { + if (newTeam == world->getFaction(i)->getTeam()) { + Faction *faction = world->getFaction(factionIndex); + + SwitchTeamVote vote; + vote.factionIndex = factionIndex; + vote.allowSwitchTeam = false; + vote.oldTeam = faction->getTeam(); + vote.newTeam = newTeam; + vote.voted = false; + + world->getFaction(i)->setSwitchTeamVote(vote); } - break; - - case nctPauseResume: - { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctPauseResume\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - commandWasHandled = true; - - bool pauseGame = networkCommand->getUnitId() != 0; - bool clearCaches = (networkCommand->getCommandTypeId() == 1); - bool joinNetworkGame = (networkCommand->getUnitTypeId() == 1); - Game *game = this->world->getGame(); - - //printf("nctPauseResume pauseGame = %d\n",pauseGame); - game->setPaused(pauseGame,true,clearCaches,joinNetworkGame); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctPauseResume\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - break; - - case nctPlayerStatusChange: - { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctPlayerStatusChange\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - commandWasHandled = true; - - int factionIndex = networkCommand->getUnitId(); - int playerStatus = networkCommand->getCommandTypeId(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"nctPlayerStatusChange factionIndex = %d playerStatus = %d\n",factionIndex,playerStatus); - - //printf("#1 nctPlayerStatusChange factionIndex = %d playerStatus = %d\n",factionIndex,playerStatus); - - GameSettings *settings = world->getGameSettingsPtr(); - if(playerStatus == npst_Disconnected) { - //printf("Commander nctPlayerStatusChange factionIndex: %d\n",factionIndex); - - settings->setNetworkPlayerStatuses(factionIndex,npst_Disconnected); - - //printf("nctPlayerStatusChange -> faction->getPersonalityType() = %d index [%d] control [%d] networkstatus [%d]\n", - // world->getFaction(factionIndex)->getPersonalityType(),world->getFaction(factionIndex)->getIndex(),world->getFaction(factionIndex)->getControlType(),settings->getNetworkPlayerStatuses(factionIndex)); - - //printf("#2 nctPlayerStatusChange factionIndex = %d playerStatus = %d\n",factionIndex,playerStatus); - settings->setFactionControl(factionIndex,ctCpuUltra); - settings->setResourceMultiplierIndex(factionIndex,settings->getFallbackCpuMultiplier()); - //Game *game = this->world->getGame(); - //game->get - Faction *faction = this->world->getFaction(factionIndex); - faction->setControlType(ctCpuUltra); - - if(!world->getGame()->getGameOver()&& !this->world->getGame()->factionLostGame(factionIndex)){ - // use the fallback multiplier here - - // mark player as "leaver" - this->world->getStats()->setPlayerLeftBeforeEnd(factionIndex,true); - // set disconnect time for endgame stats - this->world->getStats()->setTimePlayerLeft(factionIndex,this->world->getStats()->getFramesToCalculatePlaytime()); - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctPlayerStatusChange\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - break; - + } } - if(commandWasHandled == false) { - Unit* unit= world->findUnitById(networkCommand->getUnitId()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [after world->findUnitById]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Running command NetworkCommandType = %d, unitid = %d [%p] factionindex = %d\n",networkCommand->getNetworkCommandType(),networkCommand->getUnitId(),unit,(unit != NULL ? unit->getFactionIndex() : -1)); - //execute command, if unit is still alive - if(unit != NULL) { - switch(networkCommand->getNetworkCommandType()) { - case nctGiveCommand:{ - assert(networkCommand->getCommandTypeId() != CommandType::invalidId); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctGiveCommand networkCommand->getUnitId() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkCommand->getUnitId()); - - Command* command= buildCommand(networkCommand); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [after buildCommand]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] command = %p\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,command); - - unit->giveCommand(command, (networkCommand->getWantQueue() != 0)); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [after unit->giveCommand]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctGiveCommand networkCommand->getUnitId() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkCommand->getUnitId()); - } - break; - case nctCancelCommand: { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctCancelCommand\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - unit->cancelCommand(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [after unit->cancelCommand]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctCancelCommand\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - break; - case nctSetMeetingPoint: { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctSetMeetingPoint\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - unit->setMeetingPos(networkCommand->getPosition()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [after unit->setMeetingPos]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctSetMeetingPoint\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - break; + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld [after unit->setMeetingPos]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chrono.getMillis()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] found nctSetMeetingPoint\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } break; + + case nctSwitchTeamVote: { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] found nctSwitchTeamVote\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + commandWasHandled = true; + + int votingFactionIndex = networkCommand->getUnitId(); + int factionIndex = networkCommand->getCommandTypeId(); + bool allowSwitchTeam = networkCommand->getUnitTypeId() != 0; + + Faction *faction = world->getFaction(votingFactionIndex); + + SwitchTeamVote *vote = faction->getSwitchTeamVote(factionIndex); + if (vote == NULL) { + throw megaglest_runtime_error("vote == NULL"); + } + vote->voted = true; + vote->allowSwitchTeam = allowSwitchTeam; + + // Join the new team if > 50 % said yes + int newTeamTotalMemberCount = 0; + int newTeamVotedYes = 0; + int newTeamVotedNo = 0; + + for (int i = 0; i < world->getFactionCount(); ++i) { + if (vote->newTeam == world->getFaction(i)->getTeam()) { + newTeamTotalMemberCount++; + + SwitchTeamVote *teamVote = + world->getFaction(i)->getSwitchTeamVote(factionIndex); + if (teamVote != NULL && teamVote->voted == true) { + if (teamVote->allowSwitchTeam == true) { + newTeamVotedYes++; + } else { + newTeamVotedNo++; + } + } + } + } - default: - assert(false); - break; + // If > 50% of team vote yes, switch th eplayers team + if (newTeamTotalMemberCount > 0 && newTeamVotedYes > 0 && + static_cast(newTeamVotedYes) / + static_cast(newTeamTotalMemberCount) > + 0.5) { + Faction *faction = world->getFaction(factionIndex); + int oldTeam = faction->getTeam(); + faction->setTeam(vote->newTeam); + GameSettings *settings = world->getGameSettingsPtr(); + settings->setTeam(factionIndex, vote->newTeam); + world->getStats()->setTeam(factionIndex, vote->newTeam); + + if (factionIndex == world->getThisFactionIndex()) { + world->setThisTeamIndex(vote->newTeam); + GameNetworkInterface *gameNetworkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + if (gameNetworkInterface != NULL) { + + Lang &lang = Lang::getInstance(); + const vector languageList = + settings->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + char szMsg[8096] = ""; + if (lang.hasString("PlayerSwitchedTeam", languageList[i]) == true) { + snprintf( + szMsg, 8096, + lang.getString("PlayerSwitchedTeam", languageList[i]).c_str(), + settings->getNetworkPlayerName(factionIndex).c_str(), oldTeam, + vote->newTeam); + } else { + snprintf(szMsg, 8096, + "Player %s switched from team# %d to team# %d.", + settings->getNetworkPlayerName(factionIndex).c_str(), + oldTeam, vote->newTeam); } + bool localEcho = lang.isLanguageLocal(languageList[i]); + gameNetworkInterface->sendTextMessage(szMsg, -1, localEcho, + languageList[i]); + } } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] NULL Unit for id = %d, networkCommand->getNetworkCommandType() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkCommand->getUnitId(),networkCommand->getNetworkCommandType()); + world->getGame()->reInitGUI(); + } + } else if (newTeamTotalMemberCount == (newTeamVotedYes + newTeamVotedNo)) { + if (factionIndex == world->getThisFactionIndex()) { + GameSettings *settings = world->getGameSettingsPtr(); + Faction *faction = world->getFaction(factionIndex); + int oldTeam = faction->getTeam(); + + GameNetworkInterface *gameNetworkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + if (gameNetworkInterface != NULL) { + + Lang &lang = Lang::getInstance(); + const vector languageList = + settings->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + char szMsg[8096] = ""; + if (lang.hasString("PlayerSwitchedTeamDenied", languageList[i]) == + true) { + snprintf( + szMsg, 8096, + lang.getString("PlayerSwitchedTeamDenied", languageList[i]) + .c_str(), + settings->getNetworkPlayerName(factionIndex).c_str(), oldTeam, + vote->newTeam); + } else { + snprintf(szMsg, 8096, + "Player %s was denied the request to switch from team# " + "%d to team# %d.", + settings->getNetworkPlayerName(factionIndex).c_str(), + oldTeam, vote->newTeam); + } + bool localEcho = lang.isLanguageLocal(languageList[i]); + gameNetworkInterface->sendTextMessage(szMsg, -1, localEcho, + languageList[i]); + } } + } } - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [END]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); -} - -Command* Commander::buildCommand(const NetworkCommand* networkCommand) const { - assert(networkCommand->getNetworkCommandType()==nctGiveCommand); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] networkCommand [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkCommand->toString().c_str()); - - if(world == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] world == NULL for unit with id: %d",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkCommand->getUnitId()); - throw megaglest_runtime_error(szBuf); - } - - Unit* target= NULL; - const CommandType* ct= NULL; - const Unit* unit= world->findUnitById(networkCommand->getUnitId()); - - //validate unit - if(unit == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] Can not find unit with id: %d. Game out of synch.",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkCommand->getUnitId()); - SystemFlags::OutputDebug(SystemFlags::debugError,"%s\n",szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s\n",szBuf); - - GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); - if(gameNetworkInterface != NULL) { - char szMsg[8096]=""; - snprintf(szMsg,8096,"Player detected an error: Can not find unit with id: %d. Game out of synch.",networkCommand->getUnitId()); - gameNetworkInterface->sendTextMessage(szMsg,-1, true, ""); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld [after unit->setMeetingPos]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chrono.getMillis()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] found nctSetMeetingPoint\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } break; + + case nctDisconnectNetworkPlayer: { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] found nctDisconnectNetworkPlayer\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + commandWasHandled = true; + + NetworkManager &networkManager = NetworkManager::getInstance(); + NetworkRole role = networkManager.getNetworkRole(); + // GameSettings *settings = world->getGameSettingsPtr(); + + if (role == nrServer) { + // int factionIndex = networkCommand->getUnitId(); + int playerIndex = networkCommand->getCommandTypeId(); + + GameNetworkInterface *gameNetworkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + if (gameNetworkInterface != NULL) { + ServerInterface *server = networkManager.getServerInterface(); + if (server != NULL && server->isClientConnected(playerIndex) == true) { + + MutexSafeWrapper safeMutex(server->getSlotMutex(playerIndex), + CODE_AT_LINE); + ConnectionSlot *slot = server->getSlot(playerIndex, false); + if (slot != NULL) { + safeMutex.ReleaseLock(); + NetworkMessageQuit networkMessageQuit; + slot->sendMessage(&networkMessageQuit); + sleep(5); + + // printf("Sending nctDisconnectNetworkPlayer\n"); + server = networkManager.getServerInterface(false); + if (server != NULL) { + MutexSafeWrapper safeMutex2(server->getSlotMutex(playerIndex), + CODE_AT_LINE); + slot = server->getSlot(playerIndex, false); + if (slot != NULL) { + safeMutex2.ReleaseLock(); + slot->close(); + } + } + } } + } + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] found nctDisconnectNetworkPlayer\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } break; + + case nctPauseResume: { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] found nctPauseResume\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + commandWasHandled = true; + + bool pauseGame = networkCommand->getUnitId() != 0; + bool clearCaches = (networkCommand->getCommandTypeId() == 1); + bool joinNetworkGame = (networkCommand->getUnitTypeId() == 1); + Game *game = this->world->getGame(); + + // printf("nctPauseResume pauseGame = %d\n",pauseGame); + game->setPaused(pauseGame, true, clearCaches, joinNetworkGame); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] found nctPauseResume\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + } break; + + case nctPlayerStatusChange: { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] found nctPlayerStatusChange\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + commandWasHandled = true; + + int factionIndex = networkCommand->getUnitId(); + int playerStatus = networkCommand->getCommandTypeId(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "nctPlayerStatusChange factionIndex = %d playerStatus = %d\n", + factionIndex, playerStatus); + + // printf("#1 nctPlayerStatusChange factionIndex = %d playerStatus = + // %d\n",factionIndex,playerStatus); + + GameSettings *settings = world->getGameSettingsPtr(); + if (playerStatus == npst_Disconnected) { + // printf("Commander nctPlayerStatusChange factionIndex: + // %d\n",factionIndex); + + settings->setNetworkPlayerStatuses(factionIndex, npst_Disconnected); + + // printf("nctPlayerStatusChange -> faction->getPersonalityType() = %d + // index [%d] control [%d] networkstatus [%d]\n", + // world->getFaction(factionIndex)->getPersonalityType(),world->getFaction(factionIndex)->getIndex(),world->getFaction(factionIndex)->getControlType(),settings->getNetworkPlayerStatuses(factionIndex)); + + // printf("#2 nctPlayerStatusChange factionIndex = %d playerStatus = + // %d\n",factionIndex,playerStatus); + settings->setFactionControl(factionIndex, ctCpuUltra); + settings->setResourceMultiplierIndex( + factionIndex, settings->getFallbackCpuMultiplier()); + // Game *game = this->world->getGame(); + // game->get + Faction *faction = this->world->getFaction(factionIndex); + faction->setControlType(ctCpuUltra); + + if (!world->getGame()->getGameOver() && + !this->world->getGame()->factionLostGame(factionIndex)) { + // use the fallback multiplier here + + // mark player as "leaver" + this->world->getStats()->setPlayerLeftBeforeEnd(factionIndex, true); + // set disconnect time for endgame stats + this->world->getStats()->setTimePlayerLeft( + factionIndex, + this->world->getStats()->getFramesToCalculatePlaytime()); + } + } - throw megaglest_runtime_error(szBuf); - } - - ct = unit->getType()->findCommandTypeById(networkCommand->getCommandTypeId()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] found nctPlayerStatusChange\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } break; + } + + if (commandWasHandled == false) { + Unit *unit = world->findUnitById(networkCommand->getUnitId()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld [after world->findUnitById]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chrono.getMillis()); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Running command NetworkCommandType = %d, unitid = %d [%p] " + "factionindex = %d\n", + networkCommand->getNetworkCommandType(), + networkCommand->getUnitId(), unit, + (unit != NULL ? unit->getFactionIndex() : -1)); + // execute command, if unit is still alive + if (unit != NULL) { + switch (networkCommand->getNetworkCommandType()) { + case nctGiveCommand: { + assert(networkCommand->getCommandTypeId() != CommandType::invalidId); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] found nctGiveCommand " + "networkCommand->getUnitId() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, networkCommand->getUnitId()); + + Command *command = buildCommand(networkCommand); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld [after buildCommand]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chrono.getMillis()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d] command = %p\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, command); + + unit->giveCommand(command, (networkCommand->getWantQueue() != 0)); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld [after " + "unit->giveCommand]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chrono.getMillis()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] found nctGiveCommand " + "networkCommand->getUnitId() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, networkCommand->getUnitId()); + } break; + case nctCancelCommand: { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] found nctCancelCommand\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + unit->cancelCommand(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld [after " + "unit->cancelCommand]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chrono.getMillis()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] found nctCancelCommand\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } break; + case nctSetMeetingPoint: { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] found nctSetMeetingPoint\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + unit->setMeetingPos(networkCommand->getPosition()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld [after " + "unit->setMeetingPos]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chrono.getMillis()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] found nctSetMeetingPoint\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } break; + + default: + assert(false); + break; + } + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] NULL Unit for id = %d, " + "networkCommand->getNetworkCommandType() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, networkCommand->getUnitId(), + networkCommand->getNetworkCommandType()); + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld [END]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, chrono.getMillis()); +} - if(unit->getFaction()->getIndex() != networkCommand->getUnitFactionIndex()) { +Command *Commander::buildCommand(const NetworkCommand *networkCommand) const { + assert(networkCommand->getNetworkCommandType() == nctGiveCommand); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d] networkCommand [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + networkCommand->toString().c_str()); + + if (world == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] world == NULL for unit with id: %d", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, networkCommand->getUnitId()); + throw megaglest_runtime_error(szBuf); + } + + Unit *target = NULL; + const CommandType *ct = NULL; + const Unit *unit = world->findUnitById(networkCommand->getUnitId()); + + // validate unit + if (unit == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] Can not find unit with id: %d. Game out of " + "synch.", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, networkCommand->getUnitId()); + SystemFlags::OutputDebug(SystemFlags::debugError, "%s\n", szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s\n", szBuf); + + GameNetworkInterface *gameNetworkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + if (gameNetworkInterface != NULL) { + char szMsg[8096] = ""; + snprintf(szMsg, 8096, + "Player detected an error: Can not find unit with id: %d. Game " + "out of synch.", + networkCommand->getUnitId()); + gameNetworkInterface->sendTextMessage(szMsg, -1, true, ""); + } - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d]\nUnit / Faction mismatch for network command = [%s]\n%s\nfor unit = %d\n[%s]\n[%s]\nactual local factionIndex = %d.\nGame out of synch.", - __FILE__,__FUNCTION__,__LINE__,networkCommand->toString().c_str(),unit->getType()->getCommandTypeListDesc().c_str(),unit->getId(), unit->getFullName(false).c_str(),unit->getDesc(false).c_str(),unit->getFaction()->getIndex()); + throw megaglest_runtime_error(szBuf); + } + + ct = unit->getType()->findCommandTypeById(networkCommand->getCommandTypeId()); + + if (unit->getFaction()->getIndex() != networkCommand->getUnitFactionIndex()) { + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d]\nUnit / Faction mismatch for network " + "command = [%s]\n%s\nfor unit = %d\n[%s]\n[%s]\nactual local " + "factionIndex = %d.\nGame out of synch.", + __FILE__, __FUNCTION__, __LINE__, + networkCommand->toString().c_str(), + unit->getType()->getCommandTypeListDesc().c_str(), unit->getId(), + unit->getFullName(false).c_str(), unit->getDesc(false).c_str(), + unit->getFaction()->getIndex()); + + SystemFlags::OutputDebug(SystemFlags::debugError, "%s\n", szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s\n", szBuf); + // std::string worldLog = world->DumpWorldToLog(); + world->DumpWorldToLog(); + + GameNetworkInterface *gameNetworkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + if (gameNetworkInterface != NULL && + gameNetworkInterface->isConnected() == true) { + char szMsg[8096] = ""; + snprintf( + szMsg, 8096, + "Player detected an error: Unit / Faction mismatch for unitId: %d", + networkCommand->getUnitId()); + gameNetworkInterface->sendTextMessage(szMsg, -1, true, ""); + snprintf( + szMsg, 8096, + "Local faction index = %d, remote index = %d. Game out of synch.", + unit->getFaction()->getIndex(), + networkCommand->getUnitFactionIndex()); + gameNetworkInterface->sendTextMessage(szMsg, -1, true, ""); + + } else if (gameNetworkInterface != NULL) { + char szMsg[8096] = ""; + snprintf(szMsg, 8096, + "Player detected an error: Connection lost, possible Unit / " + "Faction mismatch for unitId: %d", + networkCommand->getUnitId()); + gameNetworkInterface->sendTextMessage(szMsg, -1, true, ""); + snprintf( + szMsg, 8096, + "Local faction index = %d, remote index = %d. Game out of synch.", + unit->getFaction()->getIndex(), + networkCommand->getUnitFactionIndex()); + gameNetworkInterface->sendTextMessage(szMsg, -1, true, ""); + } - SystemFlags::OutputDebug(SystemFlags::debugError,"%s\n",szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s\n",szBuf); - //std::string worldLog = world->DumpWorldToLog(); - world->DumpWorldToLog(); + std::string sError = "Error [#1]: Game is out of sync (Unit / Faction " + "mismatch)\nplease check log files for details."; + throw megaglest_runtime_error(sError); + } - GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); - if(gameNetworkInterface != NULL && gameNetworkInterface->isConnected() == true) { - char szMsg[8096]=""; - snprintf(szMsg,8096,"Player detected an error: Unit / Faction mismatch for unitId: %d",networkCommand->getUnitId()); - gameNetworkInterface->sendTextMessage(szMsg,-1, true, ""); - snprintf(szMsg,8096,"Local faction index = %d, remote index = %d. Game out of synch.",unit->getFaction()->getIndex(),networkCommand->getUnitFactionIndex()); - gameNetworkInterface->sendTextMessage(szMsg,-1, true, ""); + const UnitType *unitType = world->findUnitTypeById( + unit->getFaction()->getType(), networkCommand->getUnitTypeId()); - } - else if(gameNetworkInterface != NULL) { - char szMsg[8096]=""; - snprintf(szMsg,8096,"Player detected an error: Connection lost, possible Unit / Faction mismatch for unitId: %d",networkCommand->getUnitId()); - gameNetworkInterface->sendTextMessage(szMsg,-1, true,""); - snprintf(szMsg,8096,"Local faction index = %d, remote index = %d. Game out of synch.",unit->getFaction()->getIndex(),networkCommand->getUnitFactionIndex()); - gameNetworkInterface->sendTextMessage(szMsg,-1, true,""); - } + // debug test! + // throw megaglest_runtime_error("Test missing command type!"); - std::string sError = "Error [#1]: Game is out of sync (Unit / Faction mismatch)\nplease check log files for details."; - throw megaglest_runtime_error(sError); - } + // validate command type - const UnitType* unitType= world->findUnitTypeById(unit->getFaction()->getType(), networkCommand->getUnitTypeId()); + // !!!Test out of synch behaviour + // ct = NULL; - // debug test! - //throw megaglest_runtime_error("Test missing command type!"); + // Check if the command was for the unit before it morphed, if so cancel it + bool isCancelPreMorphCommand = false; + if (ct == NULL && unit->getPreMorphType() != NULL) { + const CommandType *ctPreMorph = + unit->getPreMorphType()->findCommandTypeById( + networkCommand->getCommandTypeId()); + if (ctPreMorph != NULL) { + ct = unit->getType()->getFirstCtOfClass(ccStop); + isCancelPreMorphCommand = true; + } + } + + if (ct == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d]\nCan not find command type for network " + "command = [%s]\n%s\nfor unit = %d\n[%s]\n[%s]\nactual local " + "factionIndex = %d.\nUnit Type Info:\n[%s]\nNetwork unit " + "type:\n[%s]\nisCancelPreMorphCommand: %d\nGame out of synch.", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, networkCommand->toString().c_str(), + unit->getType()->getCommandTypeListDesc().c_str(), unit->getId(), + unit->getFullName(false).c_str(), unit->getDesc(false).c_str(), + unit->getFaction()->getIndex(), + unit->getType()->toString().c_str(), + (unitType != NULL ? unitType->getName(false).c_str() : "null"), + isCancelPreMorphCommand); + + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s\n", szBuf); + SystemFlags::OutputDebug(SystemFlags::debugError, "%s\n", szBuf); + world->DumpWorldToLog(); + + GameNetworkInterface *gameNetworkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + if (gameNetworkInterface != NULL) { + char szMsg[8096] = ""; + snprintf( + szMsg, 8096, + "Player detected an error: Can not find command type: %d for unitId: " + "%d [%s]. isCancelPreMorphCommand: %d Game out of synch.", + networkCommand->getCommandTypeId(), networkCommand->getUnitId(), + (unitType != NULL ? unitType->getName(false).c_str() : "null"), + isCancelPreMorphCommand); + gameNetworkInterface->sendTextMessage(szMsg, -1, true, ""); + } - //validate command type + std::string sError = + "Error [#3]: Game is out of sync, please check log files for details."; + // abort(); + throw megaglest_runtime_error(sError); + } + + CardinalDir facing; + // get facing/target ... the target might be dead due to lag, cope with it + if (isCancelPreMorphCommand == false) { + if (ct->getClass() == ccBuild) { + if (networkCommand->getTargetId() < 0 || + networkCommand->getTargetId() >= 4) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "networkCommand->getTargetId() >= 0 && " + "networkCommand->getTargetId() < 4, [%s]", + networkCommand->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + facing = CardinalDir(networkCommand->getTargetId()); + } else if (networkCommand->getTargetId() != Unit::invalidId) { + target = world->findUnitById(networkCommand->getTargetId()); + } + } + + // create command + Command *command = NULL; + if (isCancelPreMorphCommand == false) { + if (unitType != NULL) { + command = + new Command(ct, networkCommand->getPosition(), unitType, facing); + } else if (target == NULL) { + command = new Command(ct, networkCommand->getPosition()); + } else { + command = new Command(ct, target); + } + } else { + command = new Command(ct, NULL); + } - // !!!Test out of synch behaviour - //ct = NULL; + // Add in any special state + CommandStateType commandStateType = networkCommand->getCommandStateType(); + int commandStateValue = networkCommand->getCommandStateValue(); - // Check if the command was for the unit before it morphed, if so cancel it - bool isCancelPreMorphCommand = false; - if(ct == NULL && unit->getPreMorphType() != NULL) { - const CommandType *ctPreMorph = unit->getPreMorphType()->findCommandTypeById(networkCommand->getCommandTypeId()); - if(ctPreMorph != NULL) { - ct = unit->getType()->getFirstCtOfClass(ccStop); - isCancelPreMorphCommand = true; - } - } + command->setStateType(commandStateType); + command->setStateValue(commandStateValue); + command->setUnitCommandGroupId(networkCommand->getUnitCommandGroupId()); - if(ct == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d]\nCan not find command type for network command = [%s]\n%s\nfor unit = %d\n[%s]\n[%s]\nactual local factionIndex = %d.\nUnit Type Info:\n[%s]\nNetwork unit type:\n[%s]\nisCancelPreMorphCommand: %d\nGame out of synch.", - extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkCommand->toString().c_str(),unit->getType()->getCommandTypeListDesc().c_str(), - unit->getId(), unit->getFullName(false).c_str(),unit->getDesc(false).c_str(),unit->getFaction()->getIndex(),unit->getType()->toString().c_str(), - (unitType != NULL ? unitType->getName(false).c_str() : "null"),isCancelPreMorphCommand); - - SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s\n",szBuf); - SystemFlags::OutputDebug(SystemFlags::debugError,"%s\n",szBuf); - world->DumpWorldToLog(); - - GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); - if(gameNetworkInterface != NULL) { - char szMsg[8096]=""; - snprintf(szMsg,8096,"Player detected an error: Can not find command type: %d for unitId: %d [%s]. isCancelPreMorphCommand: %d Game out of synch.",networkCommand->getCommandTypeId(),networkCommand->getUnitId(),(unitType != NULL ? unitType->getName(false).c_str() : "null"),isCancelPreMorphCommand); - gameNetworkInterface->sendTextMessage(szMsg,-1, true, ""); - } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - std::string sError = "Error [#3]: Game is out of sync, please check log files for details."; - //abort(); - throw megaglest_runtime_error(sError); - } - - CardinalDir facing; - // get facing/target ... the target might be dead due to lag, cope with it - if(isCancelPreMorphCommand == false) { - if(ct->getClass() == ccBuild) { - if(networkCommand->getTargetId() < 0 || networkCommand->getTargetId() >= 4) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"networkCommand->getTargetId() >= 0 && networkCommand->getTargetId() < 4, [%s]",networkCommand->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - facing = CardinalDir(networkCommand->getTargetId()); - } - else if (networkCommand->getTargetId() != Unit::invalidId ) { - target= world->findUnitById(networkCommand->getTargetId()); - } - } - - //create command - Command *command= NULL; - if(isCancelPreMorphCommand == false) { - if(unitType != NULL) { - command= new Command(ct, networkCommand->getPosition(), unitType, facing); - } - else if(target == NULL) { - command= new Command(ct, networkCommand->getPosition()); - } - else { - command= new Command(ct, target); - } - } - else { - command= new Command(ct, NULL); - } - - // Add in any special state - CommandStateType commandStateType = networkCommand->getCommandStateType(); - int commandStateValue = networkCommand->getCommandStateValue(); - - command->setStateType(commandStateType); - command->setStateValue(commandStateValue); - command->setUnitCommandGroupId(networkCommand->getUnitCommandGroupId()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //issue command - return command; + // issue command + return command; } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/game/commander.h b/source/glest_game/game/commander.h index c74ac32e0..31343bfca 100644 --- a/source/glest_game/game/commander.h +++ b/source/glest_game/game/commander.h @@ -13,21 +13,22 @@ #define _GLEST_GAME_COMMANDER_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include -#include "vec.h" -#include "selection.h" -#include "command_type.h" -#include "platform_util.h" #include "base_thread.h" +#include "command_type.h" #include "leak_dumper.h" +#include "platform_util.h" +#include "selection.h" +#include "vec.h" +#include using std::vector; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { using Shared::Graphics::Vec2i; using Shared::PlatformCommon::Chrono; @@ -47,60 +48,82 @@ class SwitchTeamVote; // ===================================================== class Commander { private: - typedef vector > CommandResultContainer; + typedef vector> CommandResultContainer; private: - World *world; - Chrono perfTimer; + World *world; + Chrono perfTimer; - std::vector > replayCommandList; + std::vector> replayCommandList; - bool pauseNetworkCommands; + bool pauseNetworkCommands; public: - Commander(); - virtual ~Commander(); - - bool getPauseNetworkCommands() const { return this->pauseNetworkCommands; } - void setPauseNetworkCommands(bool pause) { this->pauseNetworkCommands = pause; } - - void signalNetworkUpdate(Game *game); - void init(World *world); - void updateNetwork(Game *game); - - void addToReplayCommandList(NetworkCommand &command,int worldFrameCount); - bool getReplayCommandListForFrame(int worldFrameCount); - bool hasReplayCommandListForFrame() const; - int getReplayCommandListForFrameCount() const; - - std::pair tryGiveCommand(const Selection *selection, const CommandType *commandType, - const Vec2i &pos, const UnitType* unitType, - CardinalDir facing, bool tryQueue,Unit *targetUnit=NULL) const; - - std::pair tryGiveCommand(const Unit* unit, const CommandType *commandType, const Vec2i &pos, const UnitType* unitType, CardinalDir facing, bool tryQueue = false,Unit *targetUnit=NULL,int unitGroupCommandId=-1) const; - std::pair tryGiveCommand(const Selection *selection, CommandClass commandClass, const Vec2i &pos= Vec2i(0), const Unit *targetUnit= NULL, bool tryQueue = false) const; - std::pair tryGiveCommand(const Selection *selection, const CommandType *commandType, const Vec2i &pos= Vec2i(0), const Unit *targetUnit= NULL, bool tryQueue = false) const; - std::pair tryGiveCommand(const Selection *selection, const Vec2i &pos, const Unit *targetUnit= NULL, bool tryQueue = false, int unitCommandGroupId = -1) const; - CommandResult tryCancelCommand(const Selection *selection) const; - void trySetMeetingPoint(const Unit* unit, const Vec2i &pos) const; - void trySwitchTeam(const Faction* faction, int teamIndex) const; - void trySwitchTeamVote(const Faction* faction, SwitchTeamVote *vote) const; - void tryDisconnectNetworkPlayer(const Faction* faction, int playerIndex) const; - - void tryPauseGame(bool joinNetworkGame, bool clearCaches) const; - void tryResumeGame(bool joinNetworkGame, bool clearCaches) const; - - void tryNetworkPlayerDisconnected(int factionIndex) const; - - Command* buildCommand(const NetworkCommand* networkCommand) const; + Commander(); + virtual ~Commander(); + + bool getPauseNetworkCommands() const { return this->pauseNetworkCommands; } + void setPauseNetworkCommands(bool pause) { + this->pauseNetworkCommands = pause; + } + + void signalNetworkUpdate(Game *game); + void init(World *world); + void updateNetwork(Game *game); + + void addToReplayCommandList(NetworkCommand &command, int worldFrameCount); + bool getReplayCommandListForFrame(int worldFrameCount); + bool hasReplayCommandListForFrame() const; + int getReplayCommandListForFrameCount() const; + + std::pair + tryGiveCommand(const Selection *selection, const CommandType *commandType, + const Vec2i &pos, const UnitType *unitType, CardinalDir facing, + bool tryQueue, Unit *targetUnit = NULL) const; + + std::pair + tryGiveCommand(const Unit *unit, const CommandType *commandType, + const Vec2i &pos, const UnitType *unitType, CardinalDir facing, + bool tryQueue = false, Unit *targetUnit = NULL, + int unitGroupCommandId = -1) const; + std::pair tryGiveCommand(const Selection *selection, + CommandClass commandClass, + const Vec2i &pos = Vec2i(0), + const Unit *targetUnit = NULL, + bool tryQueue = false) const; + std::pair + tryGiveCommand(const Selection *selection, const CommandType *commandType, + const Vec2i &pos = Vec2i(0), const Unit *targetUnit = NULL, + bool tryQueue = false) const; + std::pair + tryGiveCommand(const Selection *selection, const Vec2i &pos, + const Unit *targetUnit = NULL, bool tryQueue = false, + int unitCommandGroupId = -1) const; + CommandResult tryCancelCommand(const Selection *selection) const; + void trySetMeetingPoint(const Unit *unit, const Vec2i &pos) const; + void trySwitchTeam(const Faction *faction, int teamIndex) const; + void trySwitchTeamVote(const Faction *faction, SwitchTeamVote *vote) const; + void tryDisconnectNetworkPlayer(const Faction *faction, + int playerIndex) const; + + void tryPauseGame(bool joinNetworkGame, bool clearCaches) const; + void tryResumeGame(bool joinNetworkGame, bool clearCaches) const; + + void tryNetworkPlayerDisconnected(int factionIndex) const; + + Command *buildCommand(const NetworkCommand *networkCommand) const; private: - std::pair pushNetworkCommand(const NetworkCommand* networkCommand) const; - std::pair computeResult(const CommandResultContainer &results) const; - void giveNetworkCommand(NetworkCommand* networkCommand) const; - bool canSubmitCommandType(const Unit *unit, const CommandType *commandType) const; + std::pair + pushNetworkCommand(const NetworkCommand *networkCommand) const; + std::pair + computeResult(const CommandResultContainer &results) const; + void giveNetworkCommand(NetworkCommand *networkCommand) const; + bool canSubmitCommandType(const Unit *unit, + const CommandType *commandType) const; }; -}} //end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/game/console.cpp b/source/glest_game/game/console.cpp index ac26f74d2..0ce53d353 100644 --- a/source/glest_game/game/console.cpp +++ b/source/glest_game/game/console.cpp @@ -11,258 +11,264 @@ #include "console.h" -#include "lang.h" #include "config.h" -#include "program.h" -#include "game_constants.h" -#include "sound_renderer.h" #include "core_data.h" -#include -#include "network_manager.h" +#include "game_constants.h" #include "gen_uuid.h" +#include "lang.h" #include "leak_dumper.h" +#include "network_manager.h" +#include "program.h" +#include "sound_renderer.h" +#include using namespace std; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class Console // ===================================================== Console::Console() { - registerGraphicComponent("Console", "Generic-Console"); - this->fontCallbackName = getInstanceName() + "_" + getNewUUD(); - CoreData::getInstance().registerFontChangedCallback(this->getFontCallbackName(), this); - - maxLines = Config::getInstance().getInt("ConsoleMaxLines"); - maxStoredLines = Config::getInstance().getInt("ConsoleMaxLinesStored"); - timeout = Config::getInstance().getInt("ConsoleTimeout"); - timeElapsed = 0.0f; - xPos=20; - yPos=20; - lineHeight=Config::getInstance().getInt("FontConsoleBaseSize","18")+2; - setFont(CoreData::getInstance().getConsoleFont()); - setFont3D(CoreData::getInstance().getConsoleFont3D()); - - stringToHighlight=""; - onlyChatMessagesInStoredLines=true; + registerGraphicComponent("Console", "Generic-Console"); + this->fontCallbackName = getInstanceName() + "_" + getNewUUD(); + CoreData::getInstance().registerFontChangedCallback( + this->getFontCallbackName(), this); + + maxLines = Config::getInstance().getInt("ConsoleMaxLines"); + maxStoredLines = Config::getInstance().getInt("ConsoleMaxLinesStored"); + timeout = Config::getInstance().getInt("ConsoleTimeout"); + timeElapsed = 0.0f; + xPos = 20; + yPos = 20; + lineHeight = Config::getInstance().getInt("FontConsoleBaseSize", "18") + 2; + setFont(CoreData::getInstance().getConsoleFont()); + setFont3D(CoreData::getInstance().getConsoleFont3D()); + + stringToHighlight = ""; + onlyChatMessagesInStoredLines = true; } string Console::getNewUUD() { - char uuid_str[38]; - get_uuid_string(uuid_str,sizeof(uuid_str)); - return string(uuid_str); + char uuid_str[38]; + get_uuid_string(uuid_str, sizeof(uuid_str)); + return string(uuid_str); } Console::~Console() { - CoreData::getInstance().unRegisterFontChangedCallback(this->getFontCallbackName()); + CoreData::getInstance().unRegisterFontChangedCallback( + this->getFontCallbackName()); } void Console::setFont(Font2D *font) { - this->font = font; - if (this->font != NULL) { - this->font2DUniqueId = font->getFontUniqueId(); - } - else { - this->font2DUniqueId = ""; - } + this->font = font; + if (this->font != NULL) { + this->font2DUniqueId = font->getFontUniqueId(); + } else { + this->font2DUniqueId = ""; + } } void Console::setFont3D(Font3D *font) { - this->font3D = font; - if (this->font3D != NULL) { - this->font3DUniqueId = font->getFontUniqueId(); - } - else { - this->font3DUniqueId = ""; - } + this->font3D = font; + if (this->font3D != NULL) { + this->font3DUniqueId = font->getFontUniqueId(); + } else { + this->font3DUniqueId = ""; + } } -void Console::registerGraphicComponent(const std::string &containerName, const std::string &objName) { - this->instanceName = objName; +void Console::registerGraphicComponent(const std::string &containerName, + const std::string &objName) { + this->instanceName = objName; } void Console::FontChangedCallback(std::string fontUniqueId, Font *font) { - if (fontUniqueId != "") { - if (fontUniqueId == this->font2DUniqueId) { - if (font != NULL) { - this->font = (Font2D *)font; - } - else { - this->font = NULL; - } - } - else if (fontUniqueId == this->font3DUniqueId) { - if (font != NULL) { - this->font3D = (Font3D *)font; - } - else { - this->font3D = NULL; - } - } - } + if (fontUniqueId != "") { + if (fontUniqueId == this->font2DUniqueId) { + if (font != NULL) { + this->font = (Font2D *)font; + } else { + this->font = NULL; + } + } else if (fontUniqueId == this->font3DUniqueId) { + if (font != NULL) { + this->font3D = (Font3D *)font; + } else { + this->font3D = NULL; + } + } + } } void Console::resetFonts() { - setFont(CoreData::getInstance().getConsoleFont()); - setFont3D(CoreData::getInstance().getConsoleFont3D()); + setFont(CoreData::getInstance().getConsoleFont()); + setFont3D(CoreData::getInstance().getConsoleFont3D()); } -void Console::addStdMessage(const string &s,bool clearOtherLines) { - if(clearOtherLines == true) { - addLineOnly(Lang::getInstance().getString(s)); - } - else { - addLine(Lang::getInstance().getString(s)); - } +void Console::addStdMessage(const string &s, bool clearOtherLines) { + if (clearOtherLines == true) { + addLineOnly(Lang::getInstance().getString(s)); + } else { + addLine(Lang::getInstance().getString(s)); + } } -void Console::addStdMessage(const string &s,const string &failText, bool clearOtherLines) { - if(clearOtherLines == true) { - addLineOnly(Lang::getInstance().getString(s) + failText); - } - else { - addLine(Lang::getInstance().getString(s) + failText); - } +void Console::addStdMessage(const string &s, const string &failText, + bool clearOtherLines) { + if (clearOtherLines == true) { + addLineOnly(Lang::getInstance().getString(s) + failText); + } else { + addLine(Lang::getInstance().getString(s) + failText); + } } -void Console::addStdScenarioMessage(const string &s,bool clearOtherLines) { - if(clearOtherLines == true) { - addLineOnly(Lang::getInstance().getScenarioString(s)); - } - else { - addLine(Lang::getInstance().getScenarioString(s)); - } +void Console::addStdScenarioMessage(const string &s, bool clearOtherLines) { + if (clearOtherLines == true) { + addLineOnly(Lang::getInstance().getScenarioString(s)); + } else { + addLine(Lang::getInstance().getScenarioString(s)); + } } void Console::addLineOnly(const string &line) { - addLine(line,false,-1,Vec3f(1.f, 1.f, 1.f),false,true); + addLine(line, false, -1, Vec3f(1.f, 1.f, 1.f), false, true); } -void Console::addLine(const string &line, bool playSound, int playerIndex, Vec3f textColor, bool teamMode,bool clearOtherLines) { - try { - if(playSound == true) { - SoundRenderer::getInstance().playFx(CoreData::getInstance().getClickSoundA()); - } - ConsoleLineInfo info; - info.text = line; - info.timeStamp = timeElapsed; - info.PlayerIndex = playerIndex; - info.originalPlayerName = ""; - info.color = textColor; - info.teamMode = teamMode; - if(playerIndex >= 0) { - GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); - if(gameNetworkInterface != NULL) { - info.originalPlayerName = gameNetworkInterface->getGameSettings()->getNetworkPlayerNameByPlayerIndex(playerIndex); - //for(int i = 0; i < GameConstants::maxPlayers; ++i) { - // printf("i = %d, playerName = [%s]\n",i,gameNetworkInterface->getGameSettings()->getNetworkPlayerName(i).c_str()); - //} - } - } - //printf("info.PlayerIndex = %d, line [%s]\n",info.PlayerIndex,info.originalPlayerName.c_str()); - - if(clearOtherLines == true) { - lines.clear(); - storedLines.clear(); - } - lines.insert(lines.begin(), info); - if((int)lines.size() > maxLines) { - lines.pop_back(); - } - if(onlyChatMessagesInStoredLines==false || info.PlayerIndex!=-1) { - storedLines.insert(storedLines.begin(), info); - if((int)storedLines.size() > maxStoredLines) { - storedLines.pop_back(); - } - } - } - catch(const exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - throw megaglest_runtime_error(szBuf); - } +void Console::addLine(const string &line, bool playSound, int playerIndex, + Vec3f textColor, bool teamMode, bool clearOtherLines) { + try { + if (playSound == true) { + SoundRenderer::getInstance().playFx( + CoreData::getInstance().getClickSoundA()); + } + ConsoleLineInfo info; + info.text = line; + info.timeStamp = timeElapsed; + info.PlayerIndex = playerIndex; + info.originalPlayerName = ""; + info.color = textColor; + info.teamMode = teamMode; + if (playerIndex >= 0) { + GameNetworkInterface *gameNetworkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + if (gameNetworkInterface != NULL) { + info.originalPlayerName = + gameNetworkInterface->getGameSettings() + ->getNetworkPlayerNameByPlayerIndex(playerIndex); + // for(int i = 0; i < GameConstants::maxPlayers; ++i) { + // printf("i = %d, playerName = + //[%s]\n",i,gameNetworkInterface->getGameSettings()->getNetworkPlayerName(i).c_str()); + // } + } + } + // printf("info.PlayerIndex = %d, line + // [%s]\n",info.PlayerIndex,info.originalPlayerName.c_str()); + + if (clearOtherLines == true) { + lines.clear(); + storedLines.clear(); + } + lines.insert(lines.begin(), info); + if ((int)lines.size() > maxLines) { + lines.pop_back(); + } + if (onlyChatMessagesInStoredLines == false || info.PlayerIndex != -1) { + storedLines.insert(storedLines.begin(), info); + if ((int)storedLines.size() > maxStoredLines) { + storedLines.pop_back(); + } + } + } catch (const exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] error [%s]\n", __FILE__, __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + throw megaglest_runtime_error(szBuf); + } } -void Console::addLine(const string &line, bool playSound, const string &playerName, Vec3f textColor, bool teamMode) { - try { - if(playSound == true) { - SoundRenderer::getInstance().playFx(CoreData::getInstance().getClickSoundA()); - } - ConsoleLineInfo info; - info.text = line; - info.timeStamp = timeElapsed; - info.PlayerIndex = -1; - info.originalPlayerName = ""; - info.color = textColor; - info.teamMode = teamMode; - if(playerName != "") { - info.originalPlayerName = playerName; - } - //printf("info.PlayerIndex = %d, line [%s]\n",info.PlayerIndex,info.originalPlayerName.c_str()); - - lines.insert(lines.begin(), info); - if((int)lines.size() > maxLines) { - lines.pop_back(); - } - storedLines.insert(storedLines.begin(), info); - if((int)storedLines.size() > maxStoredLines) { - storedLines.pop_back(); - } - } - catch(const exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - throw megaglest_runtime_error(szBuf); - } +void Console::addLine(const string &line, bool playSound, + const string &playerName, Vec3f textColor, + bool teamMode) { + try { + if (playSound == true) { + SoundRenderer::getInstance().playFx( + CoreData::getInstance().getClickSoundA()); + } + ConsoleLineInfo info; + info.text = line; + info.timeStamp = timeElapsed; + info.PlayerIndex = -1; + info.originalPlayerName = ""; + info.color = textColor; + info.teamMode = teamMode; + if (playerName != "") { + info.originalPlayerName = playerName; + } + // printf("info.PlayerIndex = %d, line + // [%s]\n",info.PlayerIndex,info.originalPlayerName.c_str()); + + lines.insert(lines.begin(), info); + if ((int)lines.size() > maxLines) { + lines.pop_back(); + } + storedLines.insert(storedLines.begin(), info); + if ((int)storedLines.size() > maxStoredLines) { + storedLines.pop_back(); + } + } catch (const exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] error [%s]\n", __FILE__, __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + throw megaglest_runtime_error(szBuf); + } } void Console::clearStoredLines() { - while(storedLines.empty() == false) { - storedLines.pop_back(); - } + while (storedLines.empty() == false) { + storedLines.pop_back(); + } } void Console::update() { - timeElapsed += 1.f / GameConstants::updateFps; + timeElapsed += 1.f / GameConstants::updateFps; - if(lines.empty() == false) { - if(lines.back().timeStamp < (timeElapsed - timeout)) { - lines.pop_back(); - } + if (lines.empty() == false) { + if (lines.back().timeStamp < (timeElapsed - timeout)) { + lines.pop_back(); } + } } -bool Console::isEmpty() { - return lines.empty(); -} +bool Console::isEmpty() { return lines.empty(); } -//string Console::getLine(int i) const { +// string Console::getLine(int i) const { // if(i < 0 || i >= (int)lines.size()) // throw megaglest_runtime_error("i >= Lines.size()"); // return lines[i].text; -//} +// } -//string Console::getStoredLine(int i) const { +// string Console::getStoredLine(int i) const { // if(i < 0 || i >= (int)storedLines.size()) // throw megaglest_runtime_error("i >= storedLines.size()"); // return storedLines[i].text; -//} +// } ConsoleLineInfo Console::getLineItem(int i) const { - if(i < 0 || i >= (int)lines.size()) - throw megaglest_runtime_error("i >= Lines.size()"); - return lines[i]; + if (i < 0 || i >= (int)lines.size()) + throw megaglest_runtime_error("i >= Lines.size()"); + return lines[i]; } ConsoleLineInfo Console::getStoredLineItem(int i) const { - if(i < 0 || i >= (int)storedLines.size()) - throw megaglest_runtime_error("i >= storedLines.size()"); - return storedLines[i]; + if (i < 0 || i >= (int)storedLines.size()) + throw megaglest_runtime_error("i >= storedLines.size()"); + return storedLines[i]; } - -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/game/console.h b/source/glest_game/game/console.h index cb9f7919d..c84c88833 100644 --- a/source/glest_game/game/console.h +++ b/source/glest_game/game/console.h @@ -13,26 +13,27 @@ #define _GLEST_GAME_CONSOLE_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include -#include -#include -#include #include "font.h" #include "leak_dumper.h" #include "vec.h" +#include +#include +#include +#include +using std::pair; using std::string; using std::vector; -using std::pair; using namespace std; -namespace Glest { namespace Game { +namespace Glest { +namespace Game { - using Shared::Graphics::Font; +using Shared::Graphics::Font; using Shared::Graphics::Font2D; using Shared::Graphics::Font3D; using Shared::Graphics::FontChangedCallbackInterface; @@ -45,98 +46,109 @@ using Shared::Graphics::Vec3f; class ConsoleLineInfo { public: - string text; - float timeStamp; - int PlayerIndex; - string originalPlayerName; - Vec3f color; - bool teamMode; + string text; + float timeStamp; + int PlayerIndex; + string originalPlayerName; + Vec3f color; + bool teamMode; }; -class Console: public FontChangedCallbackInterface { +class Console : public FontChangedCallbackInterface { private: - static const int consoleLines= 5; + static const int consoleLines = 5; public: - - typedef vector Lines; - typedef Lines::const_iterator LineIterator; + typedef vector Lines; + typedef Lines::const_iterator LineIterator; private: - float timeElapsed; - Lines lines; - Lines storedLines; - string stringToHighlight; - - //config - int maxLines; - int maxStoredLines; - float timeout; - int xPos; - int yPos; - int lineHeight; - Font2D *font; - Font3D *font3D; - string font2DUniqueId; - string font3DUniqueId; - - bool onlyChatMessagesInStoredLines; - - string instanceName; - string fontCallbackName; - - string getNewUUD(); + float timeElapsed; + Lines lines; + Lines storedLines; + string stringToHighlight; + + // config + int maxLines; + int maxStoredLines; + float timeout; + int xPos; + int yPos; + int lineHeight; + Font2D *font; + Font3D *font3D; + string font2DUniqueId; + string font3DUniqueId; + + bool onlyChatMessagesInStoredLines; + + string instanceName; + string fontCallbackName; + + string getNewUUD(); public: - - Console(); - virtual ~Console(); - - void registerGraphicComponent(const std::string &containerName, const std::string &objName); - string getInstanceName() const { return instanceName; } - void setInstanceName(const string &value) { instanceName = value; } - string getFontCallbackName() const { return fontCallbackName; } - - int getStoredLineCount() const {return (int)storedLines.size();} - int getLineCount() const {return (int)lines.size();} - bool getOnlyChatMessagesInStoredLines() const { return onlyChatMessagesInStoredLines ;} - void setOnlyChatMessagesInStoredLines(bool value) {this->onlyChatMessagesInStoredLines= value;} - - int getXPos() const {return xPos;} - void setXPos(int xPos) {this->xPos= xPos;} - int getYPos() const {return yPos;} - void setYPos(int yPos) {this->yPos= yPos;} - int getLineHeight() const {return lineHeight;} - void setLineHeight(int lineHeight) {this->lineHeight= lineHeight;} - Font2D *getFont() const {return font;} - Font3D *getFont3D() const {return font3D;} - void setFont(Font2D *font); - void setFont3D(Font3D *font); - string getStringToHighlight() const { return stringToHighlight;} - void setStringToHighlight(const string &stringToHighlight) { this->stringToHighlight = stringToHighlight;} - void resetFonts(); - - - //string getLine(int i) const; - //string getStoredLine(int i) const; - ConsoleLineInfo getLineItem(int i) const; - ConsoleLineInfo getStoredLineItem(int i) const; - - void clearStoredLines(); - void addStdMessage(const string &s, bool clearOtherLines=false); - void addStdMessage(const string &s, const string &failText, bool clearOtherLines=false); - - void addStdScenarioMessage(const string &s,bool clearOtherLines=false); - void addLineOnly(const string &line); - void addLine(const string &line, bool playSound= false,int playerIndex=-1,Vec3f textColor=Vec3f(1.f, 1.f, 1.f),bool teamMode=false,bool clearOtherLines=false); - void addLine(const string &line, bool playSound, const string &playerName, Vec3f textColor=Vec3f(1.f, 1.f, 1.f),bool teamMode=false); - void addLine(const string &line, bool playSound, Vec3f textColor) { addLine(line,playSound,"",textColor,false); } - void update(); - bool isEmpty(); - - virtual void FontChangedCallback(std::string fontUniqueId, Font *font); + Console(); + virtual ~Console(); + + void registerGraphicComponent(const std::string &containerName, + const std::string &objName); + string getInstanceName() const { return instanceName; } + void setInstanceName(const string &value) { instanceName = value; } + string getFontCallbackName() const { return fontCallbackName; } + + int getStoredLineCount() const { return (int)storedLines.size(); } + int getLineCount() const { return (int)lines.size(); } + bool getOnlyChatMessagesInStoredLines() const { + return onlyChatMessagesInStoredLines; + } + void setOnlyChatMessagesInStoredLines(bool value) { + this->onlyChatMessagesInStoredLines = value; + } + + int getXPos() const { return xPos; } + void setXPos(int xPos) { this->xPos = xPos; } + int getYPos() const { return yPos; } + void setYPos(int yPos) { this->yPos = yPos; } + int getLineHeight() const { return lineHeight; } + void setLineHeight(int lineHeight) { this->lineHeight = lineHeight; } + Font2D *getFont() const { return font; } + Font3D *getFont3D() const { return font3D; } + void setFont(Font2D *font); + void setFont3D(Font3D *font); + string getStringToHighlight() const { return stringToHighlight; } + void setStringToHighlight(const string &stringToHighlight) { + this->stringToHighlight = stringToHighlight; + } + void resetFonts(); + + // string getLine(int i) const; + // string getStoredLine(int i) const; + ConsoleLineInfo getLineItem(int i) const; + ConsoleLineInfo getStoredLineItem(int i) const; + + void clearStoredLines(); + void addStdMessage(const string &s, bool clearOtherLines = false); + void addStdMessage(const string &s, const string &failText, + bool clearOtherLines = false); + + void addStdScenarioMessage(const string &s, bool clearOtherLines = false); + void addLineOnly(const string &line); + void addLine(const string &line, bool playSound = false, int playerIndex = -1, + Vec3f textColor = Vec3f(1.f, 1.f, 1.f), bool teamMode = false, + bool clearOtherLines = false); + void addLine(const string &line, bool playSound, const string &playerName, + Vec3f textColor = Vec3f(1.f, 1.f, 1.f), bool teamMode = false); + void addLine(const string &line, bool playSound, Vec3f textColor) { + addLine(line, playSound, "", textColor, false); + } + void update(); + bool isEmpty(); + + virtual void FontChangedCallback(std::string fontUniqueId, Font *font); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/game/game.cpp b/source/glest_game/game/game.cpp index 178f68b4e..e3ca65496 100644 --- a/source/glest_game/game/game.cpp +++ b/source/glest_game/game/game.cpp @@ -10,26 +10,26 @@ #include "game.h" -#include "config.h" -#include "renderer.h" -#include "particle_renderer.h" -#include "commander.h" +#include "auto_test.h" #include "battle_end.h" -#include "sound_renderer.h" -#include "profiler.h" -#include "core_data.h" -#include "metrics.h" -#include "faction.h" -#include "network_manager.h" +#include "cache_manager.h" #include "checksum.h" -#include "auto_test.h" -#include "menu_state_keysetup.h" -#include "video_player.h" +#include "commander.h" #include "compression_utils.h" -#include "cache_manager.h" +#include "config.h" #include "conversion.h" -#include "steam.h" +#include "core_data.h" +#include "faction.h" #include "memory.h" +#include "menu_state_keysetup.h" +#include "metrics.h" +#include "network_manager.h" +#include "particle_renderer.h" +#include "profiler.h" +#include "renderer.h" +#include "sound_renderer.h" +#include "steam.h" +#include "video_player.h" #include "leak_dumper.h" @@ -38,7 +38,8 @@ using namespace Shared::Util; using namespace Shared::Platform; using namespace Shared::CompressionUtil; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { string GameSettings::playerDisconnectedText = ""; Game *thisGamePtr = NULL; @@ -56,7 +57,7 @@ const int CANCEL_SWITCH_TEAM = -1; const int CANCEL_DISCONNECT_PLAYER = -1; -const float Game::highlightTime= 0.5f; +const float Game::highlightTime = 0.5f; int fadeMusicMilliseconds = 3500; @@ -66,7121 +67,8818 @@ const int NETWORK_PLAYER_CONNECTION_CHECK_SECONDS = 5; int GAME_STATS_DUMP_INTERVAL = 60 * 10; Game::Game() : ProgramState(NULL) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - originalDisplayMsgCallback = NULL; - aiInterfaces.clear(); - videoPlayer = NULL; - playingStaticVideo = false; - - mouse2d=0; - mouseX=0; - mouseY=0; - updateFps=0; - lastUpdateFps=0; - avgUpdateFps=0; - framesToCatchUpAsClient=0; - framesToSlowDownAsClient=0; - totalRenderFps=0; - renderFps=0; - lastRenderFps=0; - avgRenderFps=0; - currentAvgRenderFpsTotal=0; - paused=false; - networkPauseGameForLaggedClientsRequested=false; - networkResumeGameForLaggedClientsRequested=false; - pausedForJoinGame=false; - pausedBeforeJoinGame=false; - pauseRequestSent=false; - resumeRequestSent=false; - pauseStateChanged=false; - gameOver=false; - renderNetworkStatus=false; - renderInGamePerformance=false; - showFullConsole=false; - setMarker=false; - cameraDragAllowed=false; - mouseMoved=false; - scrollSpeed=0; - camLeftButtonDown=false; - camRightButtonDown=false; - camUpButtonDown=false; - camDownButtonDown=false; - this->speed=1; - weatherParticleSystem=NULL; - isFirstRender=false; - quitTriggeredIndicator=false; - quitPendingIndicator=false; - original_updateFps=0; - original_cameraFps=0; - captureAvgTestStatus=false; - updateFpsAvgTest=0; - renderFpsAvgTest=0; - renderExtraTeamColor=0; - photoModeEnabled=false; - healthbarMode=hbvUndefined; - visibleHUD=false; - timeDisplay=false; - withRainEffect=false; - program=NULL; - gameStarted=false; - this->initialResumeSpeedLoops=false; - - highlightCellTexture=NULL; - lastMasterServerGameStatsDump=0; - lastMaxUnitCalcTime=0; - lastRenderLog2d=0; - playerIndexDisconnect=0; - tickCount=0; - currentCameraFollowUnit=NULL; - - popupMenu.setEnabled(false); - popupMenu.setVisible(false); - - popupMenuSwitchTeams.setEnabled(false); - popupMenuSwitchTeams.setVisible(false); - - popupMenuDisconnectPlayer.setEnabled(false); - popupMenuDisconnectPlayer.setVisible(false); - - switchTeamConfirmMessageBox.setEnabled(false); - disconnectPlayerConfirmMessageBox.setEnabled(false); - - disconnectPlayerIndexMap.clear(); - - exitGamePopupMenuIndex = -1; - joinTeamPopupMenuIndex = -1; - pauseGamePopupMenuIndex = -1; - saveGamePopupMenuIndex = -1; - loadGamePopupMenuIndex = -1; - keyboardSetupPopupMenuIndex = -1; - disconnectPlayerPopupMenuIndex = -1; - - isMarkCellEnabled = false; - isMarkCellTextEnabled = false; - - markCellTexture = NULL; - isUnMarkCellEnabled = false; - unmarkCellTexture = NULL; - - masterserverMode = false; - currentUIState=NULL; - currentAmbientSound=NULL; - //printf("In [%s:%s] Line: %d currentAmbientSound = [%p]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,currentAmbientSound); - - loadGameNode = NULL; - lastworldFrameCountForReplay = -1; - lastNetworkPlayerConnectionCheck = time(NULL); - inJoinGameLoading = false; - quitGameCalled = false; - disableSpeedChange = false; - - for( int i=0;ispeed = 1; + weatherParticleSystem = NULL; + isFirstRender = false; + quitTriggeredIndicator = false; + quitPendingIndicator = false; + original_updateFps = 0; + original_cameraFps = 0; + captureAvgTestStatus = false; + updateFpsAvgTest = 0; + renderFpsAvgTest = 0; + renderExtraTeamColor = 0; + photoModeEnabled = false; + healthbarMode = hbvUndefined; + visibleHUD = false; + timeDisplay = false; + withRainEffect = false; + program = NULL; + gameStarted = false; + this->initialResumeSpeedLoops = false; + + highlightCellTexture = NULL; + lastMasterServerGameStatsDump = 0; + lastMaxUnitCalcTime = 0; + lastRenderLog2d = 0; + playerIndexDisconnect = 0; + tickCount = 0; + currentCameraFollowUnit = NULL; + + popupMenu.setEnabled(false); + popupMenu.setVisible(false); + + popupMenuSwitchTeams.setEnabled(false); + popupMenuSwitchTeams.setVisible(false); + + popupMenuDisconnectPlayer.setEnabled(false); + popupMenuDisconnectPlayer.setVisible(false); + + switchTeamConfirmMessageBox.setEnabled(false); + disconnectPlayerConfirmMessageBox.setEnabled(false); + + disconnectPlayerIndexMap.clear(); + + exitGamePopupMenuIndex = -1; + joinTeamPopupMenuIndex = -1; + pauseGamePopupMenuIndex = -1; + saveGamePopupMenuIndex = -1; + loadGamePopupMenuIndex = -1; + keyboardSetupPopupMenuIndex = -1; + disconnectPlayerPopupMenuIndex = -1; + + isMarkCellEnabled = false; + isMarkCellTextEnabled = false; + + markCellTexture = NULL; + isUnMarkCellEnabled = false; + unmarkCellTexture = NULL; + + masterserverMode = false; + currentUIState = NULL; + currentAmbientSound = NULL; + // printf("In [%s:%s] Line: %d currentAmbientSound = + // [%p]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,currentAmbientSound); + + loadGameNode = NULL; + lastworldFrameCountForReplay = -1; + lastNetworkPlayerConnectionCheck = time(NULL); + inJoinGameLoading = false; + quitGameCalled = false; + disableSpeedChange = false; + + for (int i = 0; i < GameConstants::networkSmoothInterval; i++) { + receivedTooEarlyInFrames[i] = -1; + framesNeededToWaitForServerMessage[i] = -1; + } + + fadeMusicMilliseconds = + Config::getInstance().getInt("GameStartStopFadeSoundMilliseconds", + intToStr(fadeMusicMilliseconds).c_str()); + GAME_STATS_DUMP_INTERVAL = + Config::getInstance().getInt("GameStatsDumpIntervalSeconds", + intToStr(GAME_STATS_DUMP_INTERVAL).c_str()); } void Game::resetMembers() { - Unit::setGame(this); - gameStarted = false; - this->initialResumeSpeedLoops = false; - - original_updateFps = GameConstants::updateFps; - original_cameraFps = GameConstants::cameraFps; - GameConstants::updateFps= 40; - GameConstants::cameraFps= 100; - captureAvgTestStatus = false; - updateFpsAvgTest=0; - renderFpsAvgTest=0; - lastRenderLog2d = 0; - playerIndexDisconnect=0; - lastMasterServerGameStatsDump=0; - highlightCellTexture=NULL; - totalRenderFps =0; - lastMaxUnitCalcTime =0; - renderExtraTeamColor =0; - - mouseMoved= false; - quitTriggeredIndicator = false; - quitPendingIndicator=false; - originalDisplayMsgCallback = NULL; - thisGamePtr = this; - - popupMenu.setEnabled(false); - popupMenu.setVisible(false); - - popupMenuSwitchTeams.setEnabled(false); - popupMenuSwitchTeams.setVisible(false); - - popupMenuDisconnectPlayer.setEnabled(false); - popupMenuDisconnectPlayer.setVisible(false); - - switchTeamConfirmMessageBox.setEnabled(false); - disconnectPlayerConfirmMessageBox.setEnabled(false); - - disconnectPlayerIndexMap.clear(); - - exitGamePopupMenuIndex = -1; - joinTeamPopupMenuIndex = -1; - pauseGamePopupMenuIndex = -1; - saveGamePopupMenuIndex = -1; - loadGamePopupMenuIndex = -1; - keyboardSetupPopupMenuIndex = -1; - disconnectPlayerPopupMenuIndex = -1; - - isMarkCellEnabled = false; - isMarkCellTextEnabled = false; - - markCellTexture = NULL; - isUnMarkCellEnabled = false; - unmarkCellTexture = NULL; - - currentUIState = NULL; - - scrollSpeed = Config::getInstance().getFloat("UiScrollSpeed","1.5"); - photoModeEnabled = Config::getInstance().getBool("PhotoMode","false"); - healthbarMode = Config::getInstance().getInt("HealthBarMode","4"); - visibleHUD = Config::getInstance().getBool("VisibleHud","true"); - timeDisplay = Config::getInstance().getBool("TimeDisplay","true"); - withRainEffect = Config::getInstance().getBool("RainEffect","true"); - //MIN_RENDER_FPS_ALLOWED = Config::getInstance().getInt("MIN_RENDER_FPS_ALLOWED",intToStr(MIN_RENDER_FPS_ALLOWED).c_str()); - - mouseX=0; - mouseY=0; - mouse2d= 0; - loadingText=""; - weatherParticleSystem= NULL; - updateFps=0; - renderFps=0; - lastUpdateFps=0; - framesToCatchUpAsClient=0; - framesToSlowDownAsClient=0; - lastRenderFps=-1; - avgUpdateFps=-1; - avgRenderFps=-1; - currentAvgRenderFpsTotal=0; - tickCount=0; - paused= false; - networkPauseGameForLaggedClientsRequested=false; - networkResumeGameForLaggedClientsRequested=false; - pausedForJoinGame=false; - pausedBeforeJoinGame=false; - resumeRequestSent=false; - pauseRequestSent=false; - pauseStateChanged=false; - gameOver= false; - renderNetworkStatus= false; - renderInGamePerformance=false; - this->speed= 1; - showFullConsole= false; - setMarker = false; - cameraDragAllowed=false; - camLeftButtonDown=false; - camRightButtonDown=false; - camUpButtonDown=false; - camDownButtonDown=false; - - currentCameraFollowUnit=NULL; - currentAmbientSound=NULL; - //printf("In [%s:%s] Line: %d currentAmbientSound = [%p]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,currentAmbientSound); - - loadGameNode = NULL; - lastworldFrameCountForReplay = -1; - - lastNetworkPlayerConnectionCheck = time(NULL); - - inJoinGameLoading = false; - quitGameCalled = false; - disableSpeedChange = false; - - for( int i=0;iinitialResumeSpeedLoops = false; + + original_updateFps = GameConstants::updateFps; + original_cameraFps = GameConstants::cameraFps; + GameConstants::updateFps = 40; + GameConstants::cameraFps = 100; + captureAvgTestStatus = false; + updateFpsAvgTest = 0; + renderFpsAvgTest = 0; + lastRenderLog2d = 0; + playerIndexDisconnect = 0; + lastMasterServerGameStatsDump = 0; + highlightCellTexture = NULL; + totalRenderFps = 0; + lastMaxUnitCalcTime = 0; + renderExtraTeamColor = 0; + + mouseMoved = false; + quitTriggeredIndicator = false; + quitPendingIndicator = false; + originalDisplayMsgCallback = NULL; + thisGamePtr = this; + + popupMenu.setEnabled(false); + popupMenu.setVisible(false); + + popupMenuSwitchTeams.setEnabled(false); + popupMenuSwitchTeams.setVisible(false); + + popupMenuDisconnectPlayer.setEnabled(false); + popupMenuDisconnectPlayer.setVisible(false); + + switchTeamConfirmMessageBox.setEnabled(false); + disconnectPlayerConfirmMessageBox.setEnabled(false); + + disconnectPlayerIndexMap.clear(); + + exitGamePopupMenuIndex = -1; + joinTeamPopupMenuIndex = -1; + pauseGamePopupMenuIndex = -1; + saveGamePopupMenuIndex = -1; + loadGamePopupMenuIndex = -1; + keyboardSetupPopupMenuIndex = -1; + disconnectPlayerPopupMenuIndex = -1; + + isMarkCellEnabled = false; + isMarkCellTextEnabled = false; + + markCellTexture = NULL; + isUnMarkCellEnabled = false; + unmarkCellTexture = NULL; + + currentUIState = NULL; + + scrollSpeed = Config::getInstance().getFloat("UiScrollSpeed", "1.5"); + photoModeEnabled = Config::getInstance().getBool("PhotoMode", "false"); + healthbarMode = Config::getInstance().getInt("HealthBarMode", "4"); + visibleHUD = Config::getInstance().getBool("VisibleHud", "true"); + timeDisplay = Config::getInstance().getBool("TimeDisplay", "true"); + withRainEffect = Config::getInstance().getBool("RainEffect", "true"); + // MIN_RENDER_FPS_ALLOWED = + // Config::getInstance().getInt("MIN_RENDER_FPS_ALLOWED",intToStr(MIN_RENDER_FPS_ALLOWED).c_str()); + + mouseX = 0; + mouseY = 0; + mouse2d = 0; + loadingText = ""; + weatherParticleSystem = NULL; + updateFps = 0; + renderFps = 0; + lastUpdateFps = 0; + framesToCatchUpAsClient = 0; + framesToSlowDownAsClient = 0; + lastRenderFps = -1; + avgUpdateFps = -1; + avgRenderFps = -1; + currentAvgRenderFpsTotal = 0; + tickCount = 0; + paused = false; + networkPauseGameForLaggedClientsRequested = false; + networkResumeGameForLaggedClientsRequested = false; + pausedForJoinGame = false; + pausedBeforeJoinGame = false; + resumeRequestSent = false; + pauseRequestSent = false; + pauseStateChanged = false; + gameOver = false; + renderNetworkStatus = false; + renderInGamePerformance = false; + this->speed = 1; + showFullConsole = false; + setMarker = false; + cameraDragAllowed = false; + camLeftButtonDown = false; + camRightButtonDown = false; + camUpButtonDown = false; + camDownButtonDown = false; + + currentCameraFollowUnit = NULL; + currentAmbientSound = NULL; + // printf("In [%s:%s] Line: %d currentAmbientSound = + // [%p]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,currentAmbientSound); + + loadGameNode = NULL; + lastworldFrameCountForReplay = -1; + + lastNetworkPlayerConnectionCheck = time(NULL); + + inJoinGameLoading = false; + quitGameCalled = false; + disableSpeedChange = false; + + for (int i = 0; i < GameConstants::networkSmoothInterval; i++) { + receivedTooEarlyInFrames[i] = -1; + framesNeededToWaitForServerMessage[i] = -1; + } + + fadeMusicMilliseconds = + Config::getInstance().getInt("GameStartStopFadeSoundMilliseconds", + intToStr(fadeMusicMilliseconds).c_str()); + GAME_STATS_DUMP_INTERVAL = + Config::getInstance().getInt("GameStatsDumpIntervalSeconds", + intToStr(GAME_STATS_DUMP_INTERVAL).c_str()); + + Logger &logger = Logger::getInstance(); + logger.showProgress(); } -Game::Game(Program *program, const GameSettings *gameSettings,bool masterserverMode): - ProgramState(program), lastMousePos(0), isFirstRender(true) -{ - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +Game::Game(Program *program, const GameSettings *gameSettings, + bool masterserverMode) + : ProgramState(program), lastMousePos(0), isFirstRender(true) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + this->masterserverMode = masterserverMode; + videoPlayer = NULL; + playingStaticVideo = false; + highlightCellTexture = NULL; + playerIndexDisconnect = 0; + updateFpsAvgTest = 0; + renderFpsAvgTest = 0; + cameraDragAllowed = false; + + if (this->masterserverMode == true) { + printf("Starting a new game...\n"); + } + + this->program = program; + resetMembers(); + this->gameSettings = *gameSettings; + + Lang::getInstance().setAllowNativeLanguageTechtree( + this->gameSettings.getNetworkAllowNativeLanguageTechtree()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); +} - this->masterserverMode = masterserverMode; - videoPlayer = NULL; - playingStaticVideo = false; - highlightCellTexture = NULL; - playerIndexDisconnect=0; - updateFpsAvgTest=0; - renderFpsAvgTest=0; - cameraDragAllowed=false; +void Game::endGame() { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + quitGame(); + sleep(0); + + Object::setStateCallback(NULL); + thisGamePtr = NULL; + if (originalDisplayMsgCallback != NULL) { + NetworkInterface::setDisplayMessageFunction(originalDisplayMsgCallback); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + Logger &logger = Logger::getInstance(); + Renderer &renderer = Renderer::getInstance(); + + logger.clearHints(); + logger.loadLoadingScreen(""); + logger.setState(Lang::getInstance().getString("Deleting")); + // logger.add("Game", true); + logger.add(Lang::getInstance().getString("LogScreenGameLoading", "", true), + false); + logger.hideProgress(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // Cannot Fade because sound files will be deleted below + SoundRenderer::getInstance().stopAllSounds(fadeMusicMilliseconds); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // deleteValues(aiInterfaces.begin(), aiInterfaces.end()); + // aiInterfaces.clear(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + gui.end(); // selection must be cleared before deleting units + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // world.end(); //must die before selection because of referencers + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] aiInterfaces.size() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, aiInterfaces.size()); + + // MUST DO THIS LAST!!!! Because objects above have pointers to things like + // unit particles and fade them out etc and this end method deletes the + // original object pointers. + renderer.endGame(false); + + GameConstants::updateFps = original_updateFps; + GameConstants::cameraFps = original_cameraFps; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + Unit::setGame(NULL); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] ==== END GAME ==== getCurrentPixelByteCount() " + "= " MG_SIZE_T_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + renderer.getCurrentPixelByteCount()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled) + SystemFlags::OutputDebug(SystemFlags::debugWorldSynch, + "==== END GAME ====\n"); + + FileCRCPreCacheThread *&preCacheCRCThreadPtr = + CacheManager::getCachedItem( + GameConstants::preCacheThreadCacheLookupKey); + if (preCacheCRCThreadPtr != NULL) { + preCacheCRCThreadPtr->setPauseForGame(false); + } + + // this->program->reInitGl(); + // renderer.reinitAll(); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); +} - if(this->masterserverMode == true) { - printf("Starting a new game...\n"); - } +Game::~Game() { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + quitGame(); + + Object::setStateCallback(NULL); + thisGamePtr = NULL; + if (originalDisplayMsgCallback != NULL) { + NetworkInterface::setDisplayMessageFunction(originalDisplayMsgCallback); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + Logger &logger = Logger::getInstance(); + Renderer &renderer = Renderer::getInstance(); + + logger.loadLoadingScreen(""); + logger.setState(Lang::getInstance().getString("Deleting")); + // logger.add("Game", true); + logger.add(Lang::getInstance().getString("LogScreenGameLoading", "", true), + false); + logger.hideProgress(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // Cannot Fade because sound files will be deleted below + SoundRenderer::getInstance().stopAllSounds(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + masterController.clearSlaves(true); + deleteValues(aiInterfaces.begin(), aiInterfaces.end()); + aiInterfaces.clear(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + gui.end(); // selection must be cleared before deleting units + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + world.end(); // must die before selection because of referencers + + BaseColorPickEntity::resetUniqueColors(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] aiInterfaces.size() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, aiInterfaces.size()); + + delete videoPlayer; + videoPlayer = NULL; + playingStaticVideo = false; + + // MUST DO THIS LAST!!!! Because objects above have pointers to things like + // unit particles and fade them out etc and this end method deletes the + // original object pointers. + renderer.endGame(true); + BaseColorPickEntity::cleanupPBO(); + + GameConstants::updateFps = original_updateFps; + GameConstants::cameraFps = original_cameraFps; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + Unit::setGame(NULL); + + Lang::getInstance().setAllowNativeLanguageTechtree(true); + + FileCRCPreCacheThread *&preCacheCRCThreadPtr = + CacheManager::getCachedItem( + GameConstants::preCacheThreadCacheLookupKey); + if (preCacheCRCThreadPtr != NULL) { + preCacheCRCThreadPtr->setPauseForGame(false); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] ==== END GAME ==== getCurrentPixelByteCount() " + "= " MG_SIZE_T_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + renderer.getCurrentPixelByteCount()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled) + SystemFlags::OutputDebug(SystemFlags::debugWorldSynch, + "==== END GAME ====\n"); + + // this->program->reInitGl(); + // renderer.reinitAll(); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); +} - this->program = program; - resetMembers(); - this->gameSettings= *gameSettings; +bool Game::showTranslatedTechTree() const { + return this->gameSettings.getNetworkAllowNativeLanguageTechtree(); +} - Lang::getInstance().setAllowNativeLanguageTechtree(this->gameSettings.getNetworkAllowNativeLanguageTechtree()); +bool Game::quitTriggered() { return quitTriggeredIndicator; } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +Stats Game::quitAndToggleState() { + // quitGame(); + // Program *program = game->getProgram(); + return quitGame(); + // Game::exitGameState(program, endStats); } -void Game::endGame() { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - quitGame(); - sleep(0); +// ==================== init and load ==================== - Object::setStateCallback(NULL); - thisGamePtr = NULL; - if(originalDisplayMsgCallback != NULL) { - NetworkInterface::setDisplayMessageFunction(originalDisplayMsgCallback); - } +int Game::ErrorDisplayMessage(const char *msg, bool exitApp) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] %s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, msg); + + if (thisGamePtr != NULL) { + string text = msg; + thisGamePtr->showErrorMessageBox(text, "Error detected", false); + } + + return 0; +} - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +// Texture2D * Game::findFactionLogoTexture(const GameSettings *settings, Logger +// *logger,string factionLogoFilter, bool useTechDefaultIfFilterNotFound) { +// Texture2D *result = NULL; +// string logoFilename = Game::findFactionLogoFile(settings, +// logger,factionLogoFilter); if(logoFilename == "" && factionLogoFilter != "" +// && useTechDefaultIfFilterNotFound == true) { logoFilename = +// Game::findFactionLogoFile(settings, logger); +// } +// +// result = Renderer::findTexture(logoFilename); +// +// return result; +// } + +string Game::extractScenarioLogoFile(const GameSettings *settings, + string &result, bool &loadingImageUsed, + Logger *logger, string factionLogoFilter) { + string scenarioDir = ""; + if (settings->getScenarioDir() != "") { + scenarioDir = settings->getScenarioDir(); + if (EndsWith(scenarioDir, ".xml") == true) { + scenarioDir = scenarioDir.erase(scenarioDir.size() - 4, 4); + scenarioDir = + scenarioDir.erase(scenarioDir.size() - settings->getScenario().size(), + settings->getScenario().size() + 1); + } - Logger &logger= Logger::getInstance(); - Renderer &renderer= Renderer::getInstance(); + // printf("!!! extractScenarioLogoFile scenarioDir [%s] factionLogoFilter + // [%s]\n",scenarioDir.c_str(),factionLogoFilter.c_str()); + + vector loadScreenList; + string logoFullPathFilter = scenarioDir + factionLogoFilter; + findAll(logoFullPathFilter, loadScreenList, false, false); + if (loadScreenList.empty() == false) { + int bestLogoIndex = 0; + + if (loadScreenList.size() > 1 && + EndsWith(factionLogoFilter, ".xml") == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\nLooking for best logo from a list of: " MG_SIZE_T_SPECIFIER + " using filter: [%s]\n", + loadScreenList.size(), logoFullPathFilter.c_str()); + + int bestMinWidthDiff = INT_MAX; + int bestMinHeightDiff = INT_MAX; + // Now find the best texture for our screen + // Texture2D *result = preloadTexture(logoFilename); + for (unsigned int logoIndex = 0; logoIndex < loadScreenList.size(); + ++logoIndex) { + string senarioLogo = scenarioDir + loadScreenList[bestLogoIndex]; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] looking for loading screen '%s'\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, senarioLogo.c_str()); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Looking for best logo: %u [%s]\n", logoIndex, + senarioLogo.c_str()); + + if (fileExists(senarioLogo) == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] found loading screen '%s'\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, senarioLogo.c_str()); + + Texture2D *checkLogo = Renderer::preloadTexture(senarioLogo); + if (checkLogo != NULL) { + const Metrics &metrics = Metrics::getInstance(); + int minWidthDifference = abs(metrics.getScreenW() - + checkLogo->getPixmapConst()->getW()); + int minHeightDifference = abs( + metrics.getScreenH() - checkLogo->getPixmapConst()->getH()); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Logo info: %d x %d (%d,%d)\n", + checkLogo->getPixmapConst()->getW(), + checkLogo->getPixmapConst()->getH(), minWidthDifference, + minHeightDifference); + + if (minWidthDifference < bestMinWidthDiff) { + bestMinWidthDiff = minWidthDifference; + + bestLogoIndex = logoIndex; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("#1 New best logo is [%s]\n", senarioLogo.c_str()); + } else if (minWidthDifference == bestMinWidthDiff && + minHeightDifference < bestMinHeightDiff) { + bestMinHeightDiff = minHeightDifference; + + bestLogoIndex = logoIndex; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("#2 New best logo is [%s]\n", senarioLogo.c_str()); + } + } + } + } + } + + string senarioLogo = scenarioDir + loadScreenList[bestLogoIndex]; + if (fileExists(senarioLogo) == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s] found scenario loading screen '%s'\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + senarioLogo.c_str()); + + result = senarioLogo; + if (logger != NULL) { + logger->loadLoadingScreen(result); + } + loadingImageUsed = true; + } + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] gameSettings.getScenarioDir() = [%s] " + "gameSettings.getScenario() = [%s] scenarioDir = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, settings->getScenarioDir().c_str(), + settings->getScenario().c_str(), scenarioDir.c_str()); + } + return scenarioDir; +} - logger.clearHints(); - logger.loadLoadingScreen(""); - logger.setState(Lang::getInstance().getString("Deleting")); - //logger.add("Game", true); - logger.add(Lang::getInstance().getString("LogScreenGameLoading","",true), false); - logger.hideProgress(); +string Game::extractFactionLogoFile(bool &loadingImageUsed, + const string &factionName, + string scenarioDir, const string &techName, + Logger *logger, string factionLogoFilter) { + string result = ""; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] Searching for faction loading screen\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + if (factionName == formatString(GameConstants::OBSERVER_SLOTNAME)) { + string data_path = + getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + const string factionLogo = + data_path + "data/core/misc_textures/observer.jpg"; + // printf("In [%s::%s Line: %d] looking for loading screen + // '%s'\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,factionLogo.c_str()); + + if (fileExists(factionLogo) == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] found loading screen '%s'\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, factionLogo.c_str()); + + result = factionLogo; + if (logger != NULL) { + logger->loadLoadingScreen(result); + } + loadingImageUsed = true; + } + } + // else if(settings->getFactionTypeName(i) == + // formatString(GameConstants::RANDOMFACTION_SLOTNAME)) { + else if (factionName == formatString(GameConstants::RANDOMFACTION_SLOTNAME)) { + string data_path = + getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + const string factionLogo = data_path + "data/core/misc_textures/random.jpg"; + + if (fileExists(factionLogo) == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] found loading screen '%s'\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, factionLogo.c_str()); + + result = factionLogo; + if (logger != NULL) { + logger->loadLoadingScreen(result); + } + loadingImageUsed = true; + } + } else { + Config &config = Config::getInstance(); + vector pathList = config.getPathListForType(ptTechs, scenarioDir); + for (int idx = 0; idx < (int)pathList.size(); idx++) { + string currentPath = pathList[idx]; + endPathWithSlash(currentPath); + // string path = currentPath + techName + "/" + "factions" + "/" + + // settings->getFactionTypeName(i); + string path = + currentPath + techName + "/" + "factions" + "/" + factionName; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] possible loading screen dir '%s'\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, path.c_str()); + if (isdir(path.c_str()) == true) { + endPathWithSlash(path); + + vector loadScreenList; + string logoFullPathFilter = path + factionLogoFilter; + findAll(logoFullPathFilter, loadScreenList, false, false); + if (loadScreenList.empty() == false) { + int bestLogoIndex = 0; + + if (loadScreenList.size() > 1 && + EndsWith(factionLogoFilter, ".xml") == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf( + "\nLooking for best logo from a list of: " MG_SIZE_T_SPECIFIER + " using filter: [%s]\n", + loadScreenList.size(), logoFullPathFilter.c_str()); + + int bestMinWidthDiff = INT_MAX; + int bestMinHeightDiff = INT_MAX; + // Now find the best texture for our screen + // Texture2D *result = preloadTexture(logoFilename); + for (unsigned int logoIndex = 0; + logoIndex < (unsigned int)loadScreenList.size(); ++logoIndex) { + string factionLogo = path + loadScreenList[logoIndex]; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] looking for loading screen '%s'\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, factionLogo.c_str()); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Looking for best logo: %u [%s]\n", logoIndex, + factionLogo.c_str()); + + if (fileExists(factionLogo) == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] found loading screen '%s'\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, factionLogo.c_str()); + + Texture2D *checkLogo = Renderer::preloadTexture(factionLogo); + if (checkLogo != NULL) { + const Metrics &metrics = Metrics::getInstance(); + int minWidthDifference = + abs(metrics.getScreenW() - + checkLogo->getPixmapConst()->getW()); + int minHeightDifference = + abs(metrics.getScreenH() - + checkLogo->getPixmapConst()->getH()); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Logo info: %d x %d (%d,%d)\n", + checkLogo->getPixmapConst()->getW(), + checkLogo->getPixmapConst()->getH(), + minWidthDifference, minHeightDifference); + + if (minWidthDifference < bestMinWidthDiff) { + bestMinWidthDiff = minWidthDifference; + + bestLogoIndex = logoIndex; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("#1 New best logo is [%s]\n", factionLogo.c_str()); + } else if (minWidthDifference == bestMinWidthDiff && + minHeightDifference < bestMinHeightDiff) { + bestMinHeightDiff = minHeightDifference; + + bestLogoIndex = logoIndex; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("#2 New best logo is [%s]\n", factionLogo.c_str()); + } + } + } + } + } + + string factionLogo = path + loadScreenList[bestLogoIndex]; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] looking for loading screen '%s'\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, factionLogo.c_str()); + + if (fileExists(factionLogo) == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] found loading screen '%s'\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, factionLogo.c_str()); + + result = factionLogo; + if (logger != NULL) { + logger->loadLoadingScreen(result); + } + loadingImageUsed = true; + break; + } + } + // Check if this is a linked faction + else { + //!!! + string factionXMLFile = path + factionName + ".xml"; + + // printf("A factionXMLFile [%s]\n",factionXMLFile.c_str()); + + if (fileExists(factionXMLFile) == true) { + XmlTree xmlTreeFaction(XML_RAPIDXML_ENGINE); + std::map mapExtraTagReplacementValues; + xmlTreeFaction.load(factionXMLFile, + Properties::getTagReplacementValues( + &mapExtraTagReplacementValues), + true, true); + + const XmlNode *rootNode = xmlTreeFaction.getRootNode(); + + // printf("B factionXMLFile [%s] root name [%s] root first child + // name + // [%s]\n",factionXMLFile.c_str(),rootNode->getName().c_str(),rootNode->getChild(0)->getName().c_str()); + // printf("B factionXMLFile [%s] root name + // [%s]\n",factionXMLFile.c_str(),rootNode->getName().c_str()); + if (rootNode->hasChild("link") == true) { + rootNode = rootNode->getChild("link"); + } + if (rootNode->getName() == "link" && + rootNode->hasChild("techtree") == true) { + const XmlNode *linkNode = rootNode; + + // printf("C factionXMLFile [%s]\n",factionXMLFile.c_str()); + + // if(linkNode->hasChild("techtree") == true) { + const XmlNode *techtreeNode = linkNode->getChild("techtree"); + + string linkedTechTreeName = + techtreeNode->getAttribute("name")->getValue(); + + // printf("D factionXMLFile [%s] linkedTechTreeName + // [%s]\n",factionXMLFile.c_str(),linkedTechTreeName.c_str()); + + if (linkedTechTreeName != "") { + + string linkedTechTreePath = + TechTree::findPath(linkedTechTreeName, pathList); + string techTreePath = linkedTechTreePath; + endPathWithSlash(techTreePath); + + string linkedCurrentPath = + techTreePath + "factions/" + factionName; + endPathWithSlash(linkedCurrentPath); + // string linkedTmppath= linkedCurrentPath + factionName + // +".xml"; + + path = linkedCurrentPath; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] possible loading screen dir '%s'\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, path.c_str()); + + // printf("D1 idx = %d\ncurrentPath [%s]\npath + // [%s]\npathList[idx] + // [%s]\n",idx,currentPath.c_str(),path.c_str(),pathList[idx].c_str()); + + if (isdir(path.c_str()) == true) { + endPathWithSlash(path); + + // printf("E path [%s]\n",path.c_str()); + + loadScreenList.clear(); + findAll(path + factionLogoFilter, loadScreenList, false, + false); + if (loadScreenList.empty() == false) { + string factionLogo = path + loadScreenList[0]; + if (SystemFlags::getSystemSettingType( + SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] looking for loading screen " + "'%s'\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, factionLogo.c_str()); + + // printf("F factionLogo [%s]\n",factionLogo.c_str()); + + if (fileExists(factionLogo) == true) { + if (SystemFlags::getSystemSettingType( + SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] found loading screen '%s'\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, factionLogo.c_str()); + + result = factionLogo; + if (logger != NULL) { + logger->loadLoadingScreen(result); + } + loadingImageUsed = true; + break; + } + } + } + } + //} + } + } + } + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (loadingImageUsed == true) { + break; + } + } + } + // break; + // } + //} + return result; +} - // Cannot Fade because sound files will be deleted below - SoundRenderer::getInstance().stopAllSounds(fadeMusicMilliseconds); +string Game::extractTechLogoFile(string scenarioDir, const string &techName, + bool &loadingImageUsed, Logger *logger, + const string &factionLogoFilter) { + string result = ""; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] Searching for tech loading screen\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + Config &config = Config::getInstance(); + vector pathList = config.getPathListForType(ptTechs, scenarioDir); + for (int idx = 0; idx < (int)pathList.size(); idx++) { + string currentPath = pathList[idx]; + endPathWithSlash(currentPath); + string path = currentPath + techName; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] possible loading screen dir '%s'\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, path.c_str()); + if (isdir(path.c_str()) == true) { + endPathWithSlash(path); + + vector loadScreenList; + findAll(path + factionLogoFilter, loadScreenList, false, false); + if (loadScreenList.empty() == false) { + string factionLogo = path + loadScreenList[0]; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] looking for loading screen '%s'\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, factionLogo.c_str()); + + if (fileExists(factionLogo) == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] found loading screen '%s'\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, factionLogo.c_str()); + + result = factionLogo; + if (logger != NULL) { + logger->loadLoadingScreen(result); + } + loadingImageUsed = true; + break; + } + } + } + if (loadingImageUsed == true) { + break; + } + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + return result; +} -// deleteValues(aiInterfaces.begin(), aiInterfaces.end()); -// aiInterfaces.clear(); +void Game::loadHudTexture(const GameSettings *settings) { + string factionName = ""; + string techName = settings->getTech(); + string scenarioDir = extractDirectoryPathFromFile(settings->getScenarioDir()); + // printf("In loadHudTexture, scenarioDir [%s]\n",scenarioDir.c_str()); + + for (int i = 0; i < settings->getFactionCount(); ++i) { + if ((settings->getFactionControl(i) == ctHuman) || + (settings->getFactionControl(i) == ctNetwork && + settings->getThisFactionIndex() == i)) { + factionName = settings->getFactionTypeName(i); + break; + } + } + if (factionName != "") { + bool hudFound = false; + Config &config = Config::getInstance(); + vector pathList = config.getPathListForType(ptTechs, scenarioDir); + for (int idx = 0; hudFound == false && idx < (int)pathList.size(); idx++) { + string currentPath = pathList[idx]; + endPathWithSlash(currentPath); + + vector hudList; + string path = + currentPath + techName + "/" + "factions" + "/" + factionName; + endPathWithSlash(path); + findAll(path + GameConstants::HUD_SCREEN_FILE_FILTER, hudList, false, + false); + if (hudList.empty() == false) { + for (unsigned int hudIdx = 0; + hudFound == false && hudIdx < (unsigned int)hudList.size(); + ++hudIdx) { + string hudImageFileName = path + hudList[hudIdx]; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] looking for a HUD [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, hudImageFileName.c_str()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] looking for a HUD [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, hudImageFileName.c_str()); + + if (fileExists(hudImageFileName) == true) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] found HUD image [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, hudImageFileName.c_str()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] found HUD image [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, hudImageFileName.c_str()); + + Texture2D *texture = Renderer::findTexture(hudImageFileName); + gui.setHudTexture(texture); + hudFound = true; + // printf("Hud texture found! \n"); + break; + } + } + } + } + } +} - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +string Game::findFactionLogoFile(const GameSettings *settings, Logger *logger, + const string &factionLogoFilter) { + string result = ""; + if (settings == NULL) { + result = ""; + } else { + string mapName = settings->getMap(); + string tilesetName = settings->getTileset(); + string techName = settings->getTech(); + string scenarioName = settings->getScenario(); + bool loadingImageUsed = false; + + if (logger != NULL) { + logger->setState(Lang::getInstance().getString("Loading")); + + if (scenarioName.empty()) { + string scenarioDir = + extractDirectoryPathFromFile(settings->getScenarioDir()); + TechTree techTree( + Config::getInstance().getPathListForType(ptTechs, scenarioDir)); + + logger->setSubtitle(formatString(mapName) + " - " + + formatString(tilesetName) + " - " + + formatString(techTree.getTranslatedName(techName))); + } else { + logger->setSubtitle(formatString(scenarioName)); + } + } - gui.end(); //selection must be cleared before deleting units + // string scenarioDir = ""; + // bool skipCustomLoadScreen = false; + // if(skipCustomLoadScreen == false) { + string scenarioDir = extractScenarioLogoFile( + settings, result, loadingImageUsed, logger, factionLogoFilter); + //} + // try to use a faction related loading screen + // if(skipCustomLoadScreen == false && loadingImageUsed == false) { + if (loadingImageUsed == false) { + for (int i = 0; i < settings->getFactionCount(); ++i) { + if (settings->getFactionControl(i) == ctHuman || + (settings->getFactionControl(i) == ctNetwork && + settings->getThisFactionIndex() == i)) { + + result = extractFactionLogoFile( + loadingImageUsed, settings->getFactionTypeName(i), scenarioDir, + techName, logger, factionLogoFilter); + break; + } + } + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // try to use a tech related loading screen + // if(skipCustomLoadScreen == false && loadingImageUsed == false){ + if (loadingImageUsed == false) { + result = extractTechLogoFile(scenarioDir, techName, loadingImageUsed, + logger, factionLogoFilter); + } + } + return result; +} -// world.end(); //must die before selection because of referencers +vector Game::processTech(string techName) { + vector logoFiles; + bool enableFactionTexturePreview = + Config::getInstance().getBool("FactionPreview", "true"); + if (enableFactionTexturePreview) { + // string currentTechName_factionPreview = techName; + + vector factions; + vector techPaths = + Config::getInstance().getPathListForType(ptTechs); + for (int idx = 0; idx < (int)techPaths.size(); idx++) { + string &techPath = techPaths[idx]; + endPathWithSlash(techPath); + findAll(techPath + techName + "/factions/*.", factions, false, false); + + if (factions.empty() == false) { + for (unsigned int factionIdx = 0; + factionIdx < (unsigned int)factions.size(); ++factionIdx) { + bool loadingImageUsed = false; + string currentFactionName_factionPreview = factions[factionIdx]; + + string factionLogo = Game::extractFactionLogoFile( + loadingImageUsed, currentFactionName_factionPreview, "", techName, + NULL, GameConstants::PREVIEW_SCREEN_FILE_FILTER); + + if (factionLogo == "") { + factionLogo = Game::extractFactionLogoFile( + loadingImageUsed, currentFactionName_factionPreview, "", + techName, NULL, GameConstants::LOADING_SCREEN_FILE_FILTER); + } + if (factionLogo != "") { + Texture2D *texture = Renderer::preloadTexture(factionLogo); + logoFiles.push_back(texture); + } + } + } + } + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] aiInterfaces.size() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,aiInterfaces.size()); + return logoFiles; +} - // MUST DO THIS LAST!!!! Because objects above have pointers to things like - // unit particles and fade them out etc and this end method deletes the original - // object pointers. - renderer.endGame(false); +void Game::load() { load(lgt_All); } - GameConstants::updateFps = original_updateFps; - GameConstants::cameraFps = original_cameraFps; +void Game::load(int loadTypes) { + bool showPerfStats = Config::getInstance().getBool("ShowPerfStats", "false"); + Chrono chronoPerf; + if (showPerfStats) + chronoPerf.start(); + char perfBuf[8096] = ""; + std::vector perfList; + + if (showPerfStats) { + sprintf(perfBuf, "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + FileCRCPreCacheThread *&preCacheCRCThreadPtr = + CacheManager::getCachedItem( + GameConstants::preCacheThreadCacheLookupKey); + if (preCacheCRCThreadPtr != NULL) { + preCacheCRCThreadPtr->setPauseForGame(true); + } + + std::map>> loadedFileList; + originalDisplayMsgCallback = NetworkInterface::getDisplayMessageFunction(); + NetworkInterface::setDisplayMessageFunction(ErrorDisplayMessage); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] loadTypes = %d, gameSettings = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + loadTypes, this->gameSettings.toString().c_str()); + + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + soundRenderer.stopAllSounds(fadeMusicMilliseconds); + + BaseColorPickEntity::resetUniqueColors(); + + Config &config = Config::getInstance(); + Logger &logger = Logger::getInstance(); + + string mapName = gameSettings.getMap(); + string tilesetName = gameSettings.getTileset(); + string techName = gameSettings.getTech(); + string scenarioName = gameSettings.getScenario(); + string data_path = + getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + // loadHints + + if (data_path != "") { + endPathWithSlash(data_path); + } + + string user_data_path = config.getString("UserData_Root", ""); + if (user_data_path != "") { + endPathWithSlash(user_data_path); + } + + string englishFile = getGameCustomCoreDataPath( + data_path, "data/lang/hint/hint_" + + Lang::getInstance().getDefaultLanguage() + ".lng"); + string languageFile = getGameCustomCoreDataPath( + data_path, + "data/lang/hint/hint_" + Lang::getInstance().getLanguage() + ".lng"); + string languageFileUserData = user_data_path + "data/lang/hint/hint_" + + Lang::getInstance().getLanguage() + ".lng"; + + if (fileExists(languageFileUserData) == true) { + languageFile = languageFileUserData; + } + if (fileExists(languageFile) == false) { + // if there is no language specific file use english instead + languageFile = englishFile; + } + if (fileExists(englishFile) == false) { + SystemFlags::OutputDebug( + SystemFlags::debugError, "In [%s::%s Line: %d] file [%s] not found\n", + __FILE__, __FUNCTION__, __LINE__, englishFile.c_str()); + } else { + logger.loadGameHints(englishFile, languageFile, true); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + ::Shared::Platform::Window::handleEvent(); + SDL_PumpEvents(); + } - Unit::setGame(NULL); + if ((loadTypes & lgt_FactionPreview) == lgt_FactionPreview) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + Game::findFactionLogoFile(&gameSettings, &logger); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] ==== END GAME ==== getCurrentPixelByteCount() = " MG_SIZE_T_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderer.getCurrentPixelByteCount()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled) SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"==== END GAME ====\n"); + ::Shared::Platform::Window::handleEvent(); + SDL_PumpEvents(); + } + + if (showPerfStats) { + sprintf(perfBuf, "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + loadHudTexture(&gameSettings); + + const string markCellTextureFilename = + data_path + "data/core/misc_textures/mark_cell.png"; + markCellTexture = Renderer::findTexture(markCellTextureFilename); + const string unmarkCellTextureFilename = + data_path + "data/core/misc_textures/unmark_cell.png"; + unmarkCellTexture = Renderer::findTexture(unmarkCellTextureFilename); + const string highlightCellTextureFilename = + data_path + "data/core/misc_textures/pointer.png"; + highlightCellTexture = Renderer::findTexture(highlightCellTextureFilename); + + string scenarioDir = ""; + if (gameSettings.getScenarioDir() != "") { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + scenarioDir = gameSettings.getScenarioDir(); + if (EndsWith(scenarioDir, ".xml") == true) { + scenarioDir = scenarioDir.erase(scenarioDir.size() - 4, 4); + scenarioDir = scenarioDir.erase(scenarioDir.size() - + gameSettings.getScenario().size(), + gameSettings.getScenario().size() + 1); + } + } + + if (showPerfStats) { + sprintf(perfBuf, "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // tileset + if ((loadTypes & lgt_TileSet) == lgt_TileSet) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + world.loadTileset(config.getPathListForType(ptTilesets, scenarioDir), + tilesetName, &checksum, loadedFileList); + } + + if (showPerfStats) { + sprintf(perfBuf, "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + // give CPU time to update other things to avoid apperance of hanging + sleep(0); + ::Shared::Platform::Window::handleEvent(); + SDL_PumpEvents(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + set factions; + for (int i = 0; i < gameSettings.getFactionCount(); ++i) { + factions.insert(gameSettings.getFactionTypeName(i)); + } + + if (showPerfStats) { + sprintf(perfBuf, "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + if ((loadTypes & lgt_TechTree) == lgt_TechTree) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // tech, load before map because of resources + world.loadTech(config.getPathListForType(ptTechs, scenarioDir), techName, + factions, &checksum, loadedFileList); + + if (world.getTechTree() == NULL || + world.getTechTree()->getNameUntranslated() == "") { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "Line ref: %d, ERROR: Cannot find techtree: [%s]", + __LINE__, techName.c_str()); + + throw megaglest_runtime_error(szBuf, true); + } + } + + if (showPerfStats) { + sprintf(perfBuf, "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + // give CPU time to update other things to avoid apperance of hanging + sleep(0); + ::Shared::Platform::Window::handleEvent(); + SDL_PumpEvents(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // map + if ((loadTypes & lgt_Map) == lgt_Map) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + world.loadMap(Config::getMapPath(mapName, scenarioDir), &checksum); + } + + if (showPerfStats) { + sprintf(perfBuf, "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + // give CPU time to update other things to avoid apperance of hanging + sleep(0); + ::Shared::Platform::Window::handleEvent(); + SDL_PumpEvents(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // scenario + if ((loadTypes & lgt_Scenario) == lgt_Scenario) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + if (scenarioName.empty() == false) { + + bool isTutorial = Scenario::isGameTutorial(gameSettings.getScenarioDir()); + // printf("Loading scenario gameSettings.getScenarioDir() [%s] + // scenarioName [%s] isTutorial: + // %d\n",gameSettings.getScenarioDir().c_str(),scenarioName.c_str(),isTutorial); + + Lang::getInstance().loadScenarioStrings(gameSettings.getScenarioDir(), + scenarioName, isTutorial); + + // printf("In [%s::%s Line: %d] rootNode + // [%p][%s]\n",__FILE__,__FUNCTION__,__LINE__,loadGameNode,(loadGameNode + // != NULL ? loadGameNode->getName().c_str() : "none")); + world.loadScenario(gameSettings.getScenarioDir(), &checksum, false, + loadGameNode); + } + } + + if (showPerfStats) { + sprintf(perfBuf, "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + // give CPU time to update other things to avoid apperance of hanging + sleep(0); + SDL_PumpEvents(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + // good_fpu_control_registers(NULL,extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + if (showPerfStats && chronoPerf.getMillis() >= 50) { + for (unsigned int x = 0; x < perfList.size(); ++x) { + printf("%s", perfList[x].c_str()); + } + } +} - FileCRCPreCacheThread * &preCacheCRCThreadPtr = CacheManager::getCachedItem< FileCRCPreCacheThread * >(GameConstants::preCacheThreadCacheLookupKey); - if(preCacheCRCThreadPtr != NULL) { - preCacheCRCThreadPtr->setPauseForGame(false); - } +void Game::init() { init(false); } - //this->program->reInitGl(); - //renderer.reinitAll(); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); -} +void Game::init(bool initForPreviewOnly) { + bool showPerfStats = Config::getInstance().getBool("ShowPerfStats", "false"); + Chrono chronoPerf; + if (showPerfStats) + chronoPerf.start(); + char perfBuf[8096] = ""; + std::vector perfList; + + if (showPerfStats) { + sprintf(perfBuf, "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] initForPreviewOnly = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, initForPreviewOnly); + + Lang &lang = Lang::getInstance(); + Logger &logger = Logger::getInstance(); + CoreData &coreData = CoreData::getInstance(); + Renderer &renderer = Renderer::getInstance(); + Map *map = world.getMap(); + NetworkManager &networkManager = NetworkManager::getInstance(); + + GameSettings::playerDisconnectedText = "*" + lang.getString("AI") + "* "; + + if (map == NULL) { + throw megaglest_runtime_error("map == NULL"); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (initForPreviewOnly == false) { + logger.setState(lang.getString("Initializing")); + + // message box + mainMessageBox.init(lang.getString("Yes"), lang.getString("No")); + mainMessageBox.setEnabled(false); + + // message box + errorMessageBox.init(lang.getString("Ok")); + errorMessageBox.setEnabled(false); + errorMessageBox.setY(20); + + // init world, and place camera + commander.init(&world); -Game::~Game() { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // give CPU time to update other things to avoid apperance of hanging + sleep(0); + ::Shared::Platform::Window::handleEvent(); + SDL_PumpEvents(); + } + + try { + world.init(this, gameSettings.getDefaultUnits()); + } catch (const megaglest_runtime_error &ex) { + string sErrBuf = ""; + if (ex.wantStackTrace() == true) { + char szErrBuf[8096] = ""; + snprintf(szErrBuf, 8096, "In [%s::%s %d]", __FILE__, __FUNCTION__, + __LINE__); + sErrBuf = string(szErrBuf) + string("\nerror [") + string(ex.what()) + + string("]\n"); + } else { + sErrBuf = ex.what(); + } + SystemFlags::OutputDebug(SystemFlags::debugError, sErrBuf.c_str()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, sErrBuf.c_str()); - quitGame(); + if (errorMessageBox.getEnabled() == false) { + ErrorDisplayMessage(ex.what(), true); + } + } catch (const exception &ex) { + char szErrBuf[8096] = ""; + snprintf(szErrBuf, 8096, "In [%s::%s %d]", __FILE__, __FUNCTION__, + __LINE__); + string sErrBuf = string(szErrBuf) + string("\nerror [") + + string(ex.what()) + string("]\n"); + SystemFlags::OutputDebug(SystemFlags::debugError, sErrBuf.c_str()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, sErrBuf.c_str()); + + if (errorMessageBox.getEnabled() == false) { + ErrorDisplayMessage(ex.what(), true); + } + } - Object::setStateCallback(NULL); - thisGamePtr = NULL; - if(originalDisplayMsgCallback != NULL) { - NetworkInterface::setDisplayMessageFunction(originalDisplayMsgCallback); - } + if (showPerfStats) { + sprintf(perfBuf, "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (loadGameNode != NULL) { + // world.getMapPtr()->loadGame(loadGameNode,&world); + } - Logger &logger= Logger::getInstance(); - Renderer &renderer= Renderer::getInstance(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - logger.loadLoadingScreen(""); - logger.setState(Lang::getInstance().getString("Deleting")); - //logger.add("Game", true); - logger.add(Lang::getInstance().getString("LogScreenGameLoading","",true), false); - logger.hideProgress(); + if (initForPreviewOnly == false) { + // give CPU time to update other things to avoid apperance of hanging + sleep(0); + ::Shared::Platform::Window::handleEvent(); + SDL_PumpEvents(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + gui.init(this); - // Cannot Fade because sound files will be deleted below - SoundRenderer::getInstance().stopAllSounds(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // give CPU time to update other things to avoid apperance of hanging + sleep(0); + // SDL_PumpEvents(); + + chatManager.init(&console, world.getThisTeamIndex()); + console.clearStoredLines(); + } + + if (showPerfStats) { + sprintf(perfBuf, "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + if (this->loadGameNode == NULL) { + initCamera(map); + } else { + gui.loadGame(loadGameNode, &world); + + if (inJoinGameLoading == true) { + initCamera(map); + } + } + + if (showPerfStats) { + sprintf(perfBuf, "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + NetworkRole role = nrIdle; + if (initForPreviewOnly == false) { + // give CPU time to update other things to avoid apperance of hanging + sleep(0); + ::Shared::Platform::Window::handleEvent(); + SDL_PumpEvents(); - masterController.clearSlaves(true); - deleteValues(aiInterfaces.begin(), aiInterfaces.end()); - aiInterfaces.clear(); + scriptManager.init(&world, &gameCamera, loadGameNode); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // good_fpu_control_registers(NULL,extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - gui.end(); //selection must be cleared before deleting units + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] creating AI's\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // create AIs - world.end(); //must die before selection because of referencers + bool enableServerControlledAI = + this->gameSettings.getEnableServerControlledAI(); + bool isNetworkGame = this->gameSettings.isNetworkGame(); + role = networkManager.getNetworkRole(); - BaseColorPickEntity::resetUniqueColors(); + masterController.clearSlaves(true); + deleteValues(aiInterfaces.begin(), aiInterfaces.end()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] aiInterfaces.size() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,aiInterfaces.size()); + std::vector slaveThreadList; + aiInterfaces.resize(world.getFactionCount()); + for (int i = 0; i < world.getFactionCount(); ++i) { + Faction *faction = world.getFaction(i); - delete videoPlayer; - videoPlayer = NULL; - playingStaticVideo = false; + // printf("Controltype = %d for index = + // %d\n",faction->getControlType(),i); - // MUST DO THIS LAST!!!! Because objects above have pointers to things like - // unit particles and fade them out etc and this end method deletes the original - // object pointers. - renderer.endGame(true); - BaseColorPickEntity::cleanupPBO(); + if (faction->getCpuControl(enableServerControlledAI, isNetworkGame, + role) == true) { + // printf("** Loading AI player for Controltype = %d for index = + // %d\n",faction->getControlType(),i); - GameConstants::updateFps = original_updateFps; - GameConstants::cameraFps = original_cameraFps; + aiInterfaces[i] = new AiInterface(*this, i, faction->getTeam()); + if (loadGameNode != NULL) { + aiInterfaces[i]->loadGame(loadGameNode, faction); + } + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + Lang::getInstance() + .getString("LogScreenGameLoadingCreatingAIFaction", "", true) + .c_str(), + i); + logger.add(szBuf, true); + + slaveThreadList.push_back(aiInterfaces[i]->getWorkerThread()); + } else { + aiInterfaces[i] = NULL; + } + } + if (Config::getInstance().getBool("EnableNewThreadManager", "false") == + true) { + masterController.setSlaves(slaveThreadList); + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } - Unit::setGame(NULL); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - Lang::getInstance().setAllowNativeLanguageTechtree(true); + // give CPU time to update other things to avoid apperance of hanging + sleep(0); + ::Shared::Platform::Window::handleEvent(); + SDL_PumpEvents(); - FileCRCPreCacheThread * &preCacheCRCThreadPtr = CacheManager::getCachedItem< FileCRCPreCacheThread * >(GameConstants::preCacheThreadCacheLookupKey); - if(preCacheCRCThreadPtr != NULL) { - preCacheCRCThreadPtr->setPauseForGame(false); - } + if (world.getFactionCount() == 1 && + world.getFaction(0)->getPersonalityType() == fpt_Observer) { + withRainEffect = false; + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] ==== END GAME ==== getCurrentPixelByteCount() = " MG_SIZE_T_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderer.getCurrentPixelByteCount()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled) SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"==== END GAME ====\n"); + if (withRainEffect) { + // weather particle systems + if (world.getTileset()->getWeather() == wRainy) { + logger.add(Lang::getInstance().getString( + "LogScreenGameLoadingCreatingRainParticles", "", true), + true); + weatherParticleSystem = new RainParticleSystem(); + weatherParticleSystem->setSpeed(12.f / GameConstants::updateFps); + weatherParticleSystem->setPos(gameCamera.getPos()); + renderer.manageParticleSystem(weatherParticleSystem, rsGame); + } else if (world.getTileset()->getWeather() == wSnowy) { + logger.add(Lang::getInstance().getString( + "LogScreenGameLoadingCreatingSnowParticles", "", true), + true); + weatherParticleSystem = new SnowParticleSystem(1200); + weatherParticleSystem->setSpeed(1.5f / GameConstants::updateFps); + weatherParticleSystem->setPos(gameCamera.getPos()); + weatherParticleSystem->setTexture(coreData.getSnowTexture()); + renderer.manageParticleSystem(weatherParticleSystem, rsGame); + } + } else if (world.getTileset()->getWeather() == wRainy) { + world.getTileset()->setWeather(wSunny); + } - //this->program->reInitGl(); - //renderer.reinitAll(); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); -} + renderer.manageDeferredParticleSystems(); + } + + if (showPerfStats) { + sprintf(perfBuf, "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + // init renderer state + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s] Initializing renderer\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__); + logger.add(Lang::getInstance().getString("LogScreenGameLoadingInitRenderer", + "", true), + true); + + // printf("Before renderer.initGame\n"); + renderer.initGame(this, this->getGameCameraPtr()); + // printf("After renderer.initGame\n"); + + if (showPerfStats) { + sprintf(perfBuf, "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + for (int i = 0; i < world.getFactionCount(); ++i) { + Faction *faction = world.getFaction(i); + if (faction != NULL) { + faction->deletePixels(); + } + } -bool Game::showTranslatedTechTree() const { - return this->gameSettings.getNetworkAllowNativeLanguageTechtree(); -} + if (showPerfStats) { + sprintf(perfBuf, "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } -bool Game::quitTriggered() { - return quitTriggeredIndicator; -} + if (initForPreviewOnly == false) { + // good_fpu_control_registers(NULL,extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); -Stats Game::quitAndToggleState() { - //quitGame(); - //Program *program = game->getProgram(); - return quitGame(); - //Game::exitGameState(program, endStats); -} + // give CPU time to update other things to avoid apperance of hanging + sleep(0); + ::Shared::Platform::Window::handleEvent(); + SDL_PumpEvents(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s] Waiting for network\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__); + logger.add(Lang::getInstance().getString( + "LogScreenGameLoadingWaitForNetworkPlayers", "", true), + true); + networkManager.getGameNetworkInterface()->waitUntilReady(&checksum); + + // std::string worldLog = world.DumpWorldToLog(true); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] Starting music stream\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + logger.add(Lang::getInstance().getString( + "LogScreenGameLoadingStartingMusic", "", true), + true); + + if (this->masterserverMode == false) { + if (world.getThisFaction() == NULL) { + throw megaglest_runtime_error("world.getThisFaction() == NULL"); + } + if (world.getThisFaction()->getType() == NULL) { + throw megaglest_runtime_error( + "world.getThisFaction()->getType() == NULL"); + } + // if(world.getThisFaction()->getType()->getMusic() == NULL) { + // throw + // megaglest_runtime_error("world.getThisFaction()->getType()->getMusic() + //== NULL"); + // } + } -// ==================== init and load ==================== + // sounds + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + soundRenderer.stopAllSounds(fadeMusicMilliseconds); + soundRenderer = SoundRenderer::getInstance(); + + Tileset *tileset = world.getTileset(); + AmbientSounds *ambientSounds = tileset->getAmbientSounds(); + + // rain + if (tileset->getWeather() == wRainy && ambientSounds->isEnabledRain()) { + logger.add(Lang::getInstance().getString( + "LogScreenGameLoadingStartingAmbient", "", true), + true); + currentAmbientSound = ambientSounds->getRain(); + // printf("In [%s:%s] Line: %d currentAmbientSound = + // [%p]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,currentAmbientSound); + soundRenderer.playAmbient(currentAmbientSound); + } -int Game::ErrorDisplayMessage(const char *msg, bool exitApp) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] %s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,msg); + // snow + if (tileset->getWeather() == wSnowy && ambientSounds->isEnabledSnow()) { + logger.add(Lang::getInstance().getString( + "LogScreenGameLoadingStartingAmbient", "", true), + true); + currentAmbientSound = ambientSounds->getSnow(); + // printf("In [%s:%s] Line: %d currentAmbientSound = + // [%p]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,currentAmbientSound); + soundRenderer.playAmbient(currentAmbientSound); + } - if(thisGamePtr != NULL) { - string text = msg; - thisGamePtr->showErrorMessageBox(text, "Error detected", false); - } + if (this->masterserverMode == false) { + StrSound *gameMusic = world.getThisFaction()->getType()->getMusic(); + soundRenderer.playMusic(gameMusic); + } - return 0; -} + logger.add(Lang::getInstance().getString("LogScreenGameLoadingLaunchGame", + "", true)); + } + + if (showPerfStats) { + sprintf(perfBuf, "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + // throw "test"; + + logger.setCancelLoadingEnabled(false); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "================ STARTING GAME ================\n"); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPathFinder).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugPathFinder, + "================ STARTING GAME ================\n"); + setupPopupMenus(false); + + for (int i = 0; i < world.getFactionCount(); ++i) { + Faction *faction = world.getFaction(i); + + // printf("Check for team switch to observer i = %d, team = %d + // [%d]\n",i,faction->getTeam(),(GameConstants::maxPlayers -1 + + // fpt_Observer)); + if (faction != NULL && + faction->getTeam() == GameConstants::maxPlayers - 1 + fpt_Observer) { + faction->setPersonalityType(fpt_Observer); + world.getStats()->setPersonalityType(i, faction->getPersonalityType()); + } + } -//Texture2D * Game::findFactionLogoTexture(const GameSettings *settings, Logger *logger,string factionLogoFilter, bool useTechDefaultIfFilterNotFound) { -// Texture2D *result = NULL; -// string logoFilename = Game::findFactionLogoFile(settings, logger,factionLogoFilter); -// if(logoFilename == "" && factionLogoFilter != "" && useTechDefaultIfFilterNotFound == true) { -// logoFilename = Game::findFactionLogoFile(settings, logger); -// } -// -// result = Renderer::findTexture(logoFilename); -// -// return result; -//} - -string Game::extractScenarioLogoFile(const GameSettings *settings, string &result, - bool &loadingImageUsed, Logger *logger, string factionLogoFilter) { - string scenarioDir = ""; - if(settings->getScenarioDir() != "") { - scenarioDir = settings->getScenarioDir(); - if(EndsWith(scenarioDir, ".xml") == true) { - scenarioDir = scenarioDir.erase(scenarioDir.size() - 4, 4); - scenarioDir = scenarioDir.erase(scenarioDir.size() - settings->getScenario().size(), settings->getScenario().size() + 1); - } - - //printf("!!! extractScenarioLogoFile scenarioDir [%s] factionLogoFilter [%s]\n",scenarioDir.c_str(),factionLogoFilter.c_str()); - - vector loadScreenList; - string logoFullPathFilter = scenarioDir + factionLogoFilter; - findAll(logoFullPathFilter, loadScreenList, false, false); - if(loadScreenList.empty() == false) { - int bestLogoIndex = 0; - - if(loadScreenList.size() > 1 && EndsWith(factionLogoFilter, ".xml") == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\nLooking for best logo from a list of: " MG_SIZE_T_SPECIFIER " using filter: [%s]\n",loadScreenList.size(),logoFullPathFilter.c_str()); - - int bestMinWidthDiff = INT_MAX; - int bestMinHeightDiff = INT_MAX; - // Now find the best texture for our screen - // Texture2D *result = preloadTexture(logoFilename); - for(unsigned int logoIndex = 0; logoIndex < loadScreenList.size(); ++logoIndex) { - string senarioLogo = scenarioDir + loadScreenList[bestLogoIndex]; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] looking for loading screen '%s'\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,senarioLogo.c_str()); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Looking for best logo: %u [%s]\n",logoIndex,senarioLogo.c_str()); - - if(fileExists(senarioLogo) == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found loading screen '%s'\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,senarioLogo.c_str()); - - Texture2D *checkLogo = Renderer::preloadTexture(senarioLogo); - if(checkLogo != NULL) { - const Metrics &metrics= Metrics::getInstance(); - int minWidthDifference = abs(metrics.getScreenW() - checkLogo->getPixmapConst()->getW()); - int minHeightDifference = abs(metrics.getScreenH() - checkLogo->getPixmapConst()->getH()); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Logo info: %d x %d (%d,%d)\n",checkLogo->getPixmapConst()->getW(),checkLogo->getPixmapConst()->getH(),minWidthDifference,minHeightDifference); - - if(minWidthDifference < bestMinWidthDiff) { - bestMinWidthDiff = minWidthDifference; - - bestLogoIndex = logoIndex; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("#1 New best logo is [%s]\n",senarioLogo.c_str()); - } - else if(minWidthDifference == bestMinWidthDiff && - minHeightDifference < bestMinHeightDiff) { - bestMinHeightDiff = minHeightDifference; - - bestLogoIndex = logoIndex; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("#2 New best logo is [%s]\n",senarioLogo.c_str()); - } - } - } - } - } - - string senarioLogo = scenarioDir + loadScreenList[bestLogoIndex]; - if(fileExists(senarioLogo) == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] found scenario loading screen '%s'\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,senarioLogo.c_str()); - - result = senarioLogo; - if(logger != NULL) { - logger->loadLoadingScreen(result); - } - loadingImageUsed=true; - } - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] gameSettings.getScenarioDir() = [%s] gameSettings.getScenario() = [%s] scenarioDir = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,settings->getScenarioDir().c_str(),settings->getScenario().c_str(),scenarioDir.c_str()); - } - return scenarioDir; -} + if (showPerfStats) { + sprintf(perfBuf, "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } -string Game::extractFactionLogoFile(bool &loadingImageUsed, const string &factionName, - string scenarioDir, const string &techName, Logger *logger, string factionLogoFilter) { - string result = ""; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] Searching for faction loading screen\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(factionName == formatString(GameConstants::OBSERVER_SLOTNAME)) { - string data_path = getGameReadWritePath(GameConstants::path_data_CacheLookupKey); - const string factionLogo = data_path + "data/core/misc_textures/observer.jpg"; - //printf("In [%s::%s Line: %d] looking for loading screen '%s'\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,factionLogo.c_str()); - - if(fileExists(factionLogo) == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found loading screen '%s'\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,factionLogo.c_str()); - - result = factionLogo; - if(logger != NULL) { - logger->loadLoadingScreen(result); - } - loadingImageUsed = true; - } - } - //else if(settings->getFactionTypeName(i) == formatString(GameConstants::RANDOMFACTION_SLOTNAME)) { - else if(factionName == formatString(GameConstants::RANDOMFACTION_SLOTNAME)) { - string data_path = getGameReadWritePath(GameConstants::path_data_CacheLookupKey); - const string factionLogo = data_path + "data/core/misc_textures/random.jpg"; - - if(fileExists(factionLogo) == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found loading screen '%s'\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,factionLogo.c_str()); - - result = factionLogo; - if(logger != NULL) { - logger->loadLoadingScreen(result); - } - loadingImageUsed = true; - } - } - else { - Config &config = Config::getInstance(); - vector pathList = config.getPathListForType(ptTechs,scenarioDir); - for(int idx = 0; idx < (int)pathList.size(); idx++) { - string currentPath = pathList[idx]; - endPathWithSlash(currentPath); - //string path = currentPath + techName + "/" + "factions" + "/" + settings->getFactionTypeName(i); - string path = currentPath + techName + "/" + "factions" + "/" + factionName; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] possible loading screen dir '%s'\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,path.c_str()); - if(isdir(path.c_str()) == true) { - endPathWithSlash(path); - - vector loadScreenList; - string logoFullPathFilter = path + factionLogoFilter; - findAll(logoFullPathFilter, loadScreenList, false, false); - if(loadScreenList.empty() == false) { - int bestLogoIndex = 0; - - if(loadScreenList.size() > 1 && EndsWith(factionLogoFilter, ".xml") == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\nLooking for best logo from a list of: " MG_SIZE_T_SPECIFIER " using filter: [%s]\n",loadScreenList.size(),logoFullPathFilter.c_str()); - - - int bestMinWidthDiff = INT_MAX; - int bestMinHeightDiff = INT_MAX; - // Now find the best texture for our screen - // Texture2D *result = preloadTexture(logoFilename); - for(unsigned int logoIndex = 0; logoIndex < (unsigned int)loadScreenList.size(); ++logoIndex) { - string factionLogo = path + loadScreenList[logoIndex]; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] looking for loading screen '%s'\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,factionLogo.c_str()); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Looking for best logo: %u [%s]\n",logoIndex,factionLogo.c_str()); - - if(fileExists(factionLogo) == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found loading screen '%s'\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,factionLogo.c_str()); - - Texture2D *checkLogo = Renderer::preloadTexture(factionLogo); - if(checkLogo != NULL) { - const Metrics &metrics= Metrics::getInstance(); - int minWidthDifference = abs(metrics.getScreenW() - checkLogo->getPixmapConst()->getW()); - int minHeightDifference = abs(metrics.getScreenH() - checkLogo->getPixmapConst()->getH()); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Logo info: %d x %d (%d,%d)\n",checkLogo->getPixmapConst()->getW(),checkLogo->getPixmapConst()->getH(),minWidthDifference,minHeightDifference); - - if(minWidthDifference < bestMinWidthDiff) { - bestMinWidthDiff = minWidthDifference; - - bestLogoIndex = logoIndex; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("#1 New best logo is [%s]\n",factionLogo.c_str()); - } - else if(minWidthDifference == bestMinWidthDiff && - minHeightDifference < bestMinHeightDiff) { - bestMinHeightDiff = minHeightDifference; - - bestLogoIndex = logoIndex; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("#2 New best logo is [%s]\n",factionLogo.c_str()); - } - } - } - } - } - - string factionLogo = path + loadScreenList[bestLogoIndex]; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] looking for loading screen '%s'\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,factionLogo.c_str()); - - if(fileExists(factionLogo) == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found loading screen '%s'\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,factionLogo.c_str()); - - result = factionLogo; - if(logger != NULL) { - logger->loadLoadingScreen(result); - } - loadingImageUsed = true; - break; - } - } - // Check if this is a linked faction - else { - //!!! - string factionXMLFile = path + factionName + ".xml"; - - //printf("A factionXMLFile [%s]\n",factionXMLFile.c_str()); - - if(fileExists(factionXMLFile) == true) { - XmlTree xmlTreeFaction(XML_RAPIDXML_ENGINE); - std::map mapExtraTagReplacementValues; - xmlTreeFaction.load(factionXMLFile, Properties::getTagReplacementValues(&mapExtraTagReplacementValues),true,true); - - const XmlNode *rootNode= xmlTreeFaction.getRootNode(); - - //printf("B factionXMLFile [%s] root name [%s] root first child name [%s]\n",factionXMLFile.c_str(),rootNode->getName().c_str(),rootNode->getChild(0)->getName().c_str()); - //printf("B factionXMLFile [%s] root name [%s]\n",factionXMLFile.c_str(),rootNode->getName().c_str()); - if(rootNode->hasChild("link") == true) { - rootNode = rootNode->getChild("link"); - } - if(rootNode->getName() == "link" && rootNode->hasChild("techtree") == true) { - const XmlNode *linkNode = rootNode; - - //printf("C factionXMLFile [%s]\n",factionXMLFile.c_str()); - - //if(linkNode->hasChild("techtree") == true) { - const XmlNode *techtreeNode = linkNode->getChild("techtree"); - - string linkedTechTreeName = techtreeNode->getAttribute("name")->getValue(); - - //printf("D factionXMLFile [%s] linkedTechTreeName [%s]\n",factionXMLFile.c_str(),linkedTechTreeName.c_str()); - - if(linkedTechTreeName != "") { - - string linkedTechTreePath=TechTree::findPath(linkedTechTreeName,pathList); - string techTreePath=linkedTechTreePath; - endPathWithSlash(techTreePath); - - string linkedCurrentPath = techTreePath + "factions/" + factionName; - endPathWithSlash(linkedCurrentPath); - //string linkedTmppath= linkedCurrentPath + factionName +".xml"; - - path = linkedCurrentPath; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] possible loading screen dir '%s'\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,path.c_str()); - - //printf("D1 idx = %d\ncurrentPath [%s]\npath [%s]\npathList[idx] [%s]\n",idx,currentPath.c_str(),path.c_str(),pathList[idx].c_str()); - - if(isdir(path.c_str()) == true) { - endPathWithSlash(path); - - //printf("E path [%s]\n",path.c_str()); - - loadScreenList.clear(); - findAll(path + factionLogoFilter, loadScreenList, false, false); - if(loadScreenList.empty() == false) { - string factionLogo = path + loadScreenList[0]; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] looking for loading screen '%s'\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,factionLogo.c_str()); - - //printf("F factionLogo [%s]\n",factionLogo.c_str()); - - if(fileExists(factionLogo) == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found loading screen '%s'\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,factionLogo.c_str()); - - result = factionLogo; - if(logger != NULL) { - logger->loadLoadingScreen(result); - } - loadingImageUsed = true; - break; - } - } - } - } - //} - } - } - } - } - - if(loadingImageUsed == true) { - break; - } - } - } - //break; - //} - //} - return result; -} + if (role == nrClient) { + ClientInterface *clientInterface = + dynamic_cast(networkManager.getClientInterface()); + if (clientInterface != NULL && + clientInterface->getResumeInGameJoin() == true) { -string Game::extractTechLogoFile(string scenarioDir, const string &techName, - bool &loadingImageUsed, Logger *logger,const string &factionLogoFilter) { - string result = ""; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] Searching for tech loading screen\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - Config &config = Config::getInstance(); - vector pathList = config.getPathListForType(ptTechs, scenarioDir); - for(int idx = 0; idx < (int)pathList.size(); idx++) { - string currentPath = pathList[idx]; - endPathWithSlash(currentPath); - string path = currentPath + techName; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] possible loading screen dir '%s'\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,path.c_str()); - if(isdir(path.c_str()) == true) { - endPathWithSlash(path); - - vector loadScreenList; - findAll(path + factionLogoFilter, loadScreenList, false, false); - if(loadScreenList.empty() == false) { - string factionLogo = path + loadScreenList[0]; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] looking for loading screen '%s'\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,factionLogo.c_str()); - - if(fileExists(factionLogo) == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found loading screen '%s'\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,factionLogo.c_str()); - - result = factionLogo; - if(logger != NULL) { - logger->loadLoadingScreen(result); - } - loadingImageUsed = true; - break; - } - } - } - if(loadingImageUsed == true) { - break; - } - } - - return result; -} + // printf("Client sending resume message to server...\n"); -void Game::loadHudTexture(const GameSettings *settings) -{ - string factionName = ""; - string techName = settings->getTech(); - string scenarioDir = extractDirectoryPathFromFile(settings->getScenarioDir()); - //printf("In loadHudTexture, scenarioDir [%s]\n",scenarioDir.c_str()); - - for(int i=0; i < settings->getFactionCount(); ++i ) { - if((settings->getFactionControl(i) == ctHuman) || (settings->getFactionControl(i) == ctNetwork - && settings->getThisFactionIndex() == i)){ - factionName= settings->getFactionTypeName(i); - break; - } - } - if(factionName != "") { - bool hudFound = false; - Config &config= Config::getInstance(); - vector pathList= config.getPathListForType(ptTechs, scenarioDir); - for(int idx= 0; hudFound == false && idx < (int)pathList.size(); idx++){ - string currentPath= pathList[idx]; - endPathWithSlash(currentPath); - - vector hudList; - string path= currentPath + techName + "/" + "factions" + "/" + factionName; - endPathWithSlash(path); - findAll(path + GameConstants::HUD_SCREEN_FILE_FILTER, hudList, false, false); - if(hudList.empty() == false){ - for(unsigned int hudIdx = 0; hudFound == false && hudIdx < (unsigned int)hudList.size(); ++hudIdx) { - string hudImageFileName= path + hudList[hudIdx]; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] looking for a HUD [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,hudImageFileName.c_str()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] looking for a HUD [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,hudImageFileName.c_str()); - - if(fileExists(hudImageFileName) == true){ - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] found HUD image [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,hudImageFileName.c_str()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found HUD image [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,hudImageFileName.c_str()); - - Texture2D* texture= Renderer::findTexture(hudImageFileName); - gui.setHudTexture(texture); - hudFound = true; - //printf("Hud texture found! \n"); - break; - } - } - } - } - } + clientInterface->sendResumeGameMessage(); + // this->initialResumeSpeedLoops = true; + } + } + + printf("Game unique identifier is: %s\n", + this->gameSettings.getGameUUID().c_str()); + + gameStarted = true; + + if (this->masterserverMode == true) { + world.getStats()->setIsMasterserverMode(true); + + printf("New game has started...\n"); + } + + if (isFlagType1BitEnabled(ft1_network_synch_checks_verbose) == true) { + printf("*Note: Monitoring Network CRC VERBOSE synchronization...\n"); + } else if (isFlagType1BitEnabled(ft1_network_synch_checks) == true) { + printf("*Note: Monitoring Network CRC NORMAL synchronization...\n"); + } + + // NetworkRole role = networkManager.getNetworkRole(); + if (role == nrServer) { + networkManager.initServerInterfaces(this); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] ==== START GAME ==== getCurrentPixelByteCount() " + "= " MG_SIZE_T_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + renderer.getCurrentPixelByteCount()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled) + SystemFlags::OutputDebug(SystemFlags::debugWorldSynch, + "=============================================\n"); + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled) + SystemFlags::OutputDebug(SystemFlags::debugWorldSynch, + "==== START GAME ====\n"); + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled) + SystemFlags::OutputDebug(SystemFlags::debugWorldSynch, + "=============================================\n"); + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled) + SystemFlags::OutputDebug(SystemFlags::debugWorldSynch, + "Starting framecount: %d\n", + world.getFrameCount()); + + if (showPerfStats && chronoPerf.getMillis() >= 50) { + for (unsigned int x = 0; x < perfList.size(); ++x) { + printf("%s", perfList[x].c_str()); + } + } } -string Game::findFactionLogoFile(const GameSettings *settings, Logger *logger, - const string &factionLogoFilter) { - string result = ""; - if(settings == NULL) { - result = ""; - } - else { - string mapName = settings->getMap(); - string tilesetName = settings->getTileset(); - string techName = settings->getTech(); - string scenarioName = settings->getScenario(); - bool loadingImageUsed = false; - - if(logger != NULL) { - logger->setState(Lang::getInstance().getString("Loading")); - - if(scenarioName.empty()) { - string scenarioDir = extractDirectoryPathFromFile(settings->getScenarioDir()); - TechTree techTree(Config::getInstance().getPathListForType(ptTechs,scenarioDir)); - - logger->setSubtitle(formatString(mapName) + " - " + - formatString(tilesetName) + " - " + formatString(techTree.getTranslatedName(techName))); - } - else { - logger->setSubtitle(formatString(scenarioName)); - } - } - - //string scenarioDir = ""; - //bool skipCustomLoadScreen = false; - //if(skipCustomLoadScreen == false) { - string scenarioDir = extractScenarioLogoFile(settings, result, loadingImageUsed, - logger, factionLogoFilter); - //} - // try to use a faction related loading screen - //if(skipCustomLoadScreen == false && loadingImageUsed == false) { - if(loadingImageUsed == false) { - for(int i=0; i < settings->getFactionCount(); ++i ) { - if( settings->getFactionControl(i) == ctHuman || - (settings->getFactionControl(i) == ctNetwork && settings->getThisFactionIndex() == i)) { - - result = extractFactionLogoFile(loadingImageUsed, settings->getFactionTypeName(i), - scenarioDir, techName, logger, factionLogoFilter); - break; - } - } - } - - // try to use a tech related loading screen - //if(skipCustomLoadScreen == false && loadingImageUsed == false){ - if(loadingImageUsed == false) { - result = extractTechLogoFile(scenarioDir, techName, - loadingImageUsed, logger, factionLogoFilter); - } - } - return result; +void Game::initCamera(Map *map) { + gameCamera.init(map->getW(), map->getH()); + + // camera default height calculation + if (map->getCameraHeight() > 0 && + gameCamera.getCalculatedDefault() < map->getCameraHeight()) { + gameCamera.setCalculatedDefault(map->getCameraHeight()); + } else if (gameCamera.getCalculatedDefault() < + map->getMaxMapHeight() + 13.0f) { + gameCamera.setCalculatedDefault(map->getMaxMapHeight() + 13.0f); + } + + if (world.getThisFaction() != NULL) { + const Vec2i &v = + map->getStartLocation(world.getThisFaction()->getStartLocationIndex()); + gameCamera.setPos(Vec2f(v.x, v.y + gameCamera.getCalculatedDefault() / 2)); + } } -vector Game::processTech(string techName) { - vector logoFiles; - bool enableFactionTexturePreview = Config::getInstance().getBool("FactionPreview","true"); - if(enableFactionTexturePreview) { - //string currentTechName_factionPreview = techName; - - vector factions; - vector techPaths = Config::getInstance().getPathListForType(ptTechs); - for(int idx = 0; idx < (int)techPaths.size(); idx++) { - string &techPath = techPaths[idx]; - endPathWithSlash(techPath); - findAll(techPath + techName + "/factions/*.", factions, false, false); - - if(factions.empty() == false) { - for(unsigned int factionIdx = 0; factionIdx < (unsigned int)factions.size(); ++factionIdx) { - bool loadingImageUsed = false; - string currentFactionName_factionPreview = factions[factionIdx]; - - string factionLogo = Game::extractFactionLogoFile( - loadingImageUsed, - currentFactionName_factionPreview, - "", - techName, - NULL, - GameConstants::PREVIEW_SCREEN_FILE_FILTER); - - if(factionLogo == "") { - factionLogo = Game::extractFactionLogoFile( - loadingImageUsed, - currentFactionName_factionPreview, - "", - techName, - NULL, - GameConstants::LOADING_SCREEN_FILE_FILTER); - } - if(factionLogo != "") { - Texture2D *texture = Renderer::preloadTexture(factionLogo); - logoFiles.push_back(texture); - } - } - } - } - } - - return logoFiles; -} +// ==================== update ==================== -void Game::load() { - load(lgt_All); -} +void Game::reInitGUI() { gui.init(this); } -void Game::load(int loadTypes) { - bool showPerfStats = Config::getInstance().getBool("ShowPerfStats","false"); - Chrono chronoPerf; - if(showPerfStats) chronoPerf.start(); - char perfBuf[8096]=""; - std::vector perfList; - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - FileCRCPreCacheThread * &preCacheCRCThreadPtr = CacheManager::getCachedItem< FileCRCPreCacheThread * >(GameConstants::preCacheThreadCacheLookupKey); - if(preCacheCRCThreadPtr != NULL) { - preCacheCRCThreadPtr->setPauseForGame(true); - } - - std::map > > loadedFileList; - originalDisplayMsgCallback = NetworkInterface::getDisplayMessageFunction(); - NetworkInterface::setDisplayMessageFunction(ErrorDisplayMessage); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] loadTypes = %d, gameSettings = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,loadTypes,this->gameSettings.toString().c_str()); - - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - soundRenderer.stopAllSounds(fadeMusicMilliseconds); - - BaseColorPickEntity::resetUniqueColors(); - - Config &config = Config::getInstance(); - Logger &logger= Logger::getInstance(); - - string mapName= gameSettings.getMap(); - string tilesetName= gameSettings.getTileset(); - string techName= gameSettings.getTech(); - string scenarioName= gameSettings.getScenario(); - string data_path= getGameReadWritePath(GameConstants::path_data_CacheLookupKey); - // loadHints - - if(data_path != ""){ - endPathWithSlash(data_path); - } - - string user_data_path = config.getString("UserData_Root",""); - if(user_data_path != "") { - endPathWithSlash(user_data_path); - } - - string englishFile=getGameCustomCoreDataPath(data_path, "data/lang/hint/hint_"+Lang::getInstance().getDefaultLanguage()+".lng"); - string languageFile=getGameCustomCoreDataPath(data_path, "data/lang/hint/hint_"+ Lang::getInstance().getLanguage() +".lng"); - string languageFileUserData=user_data_path + "data/lang/hint/hint_"+ Lang::getInstance().getLanguage() +".lng"; - - if(fileExists(languageFileUserData) == true){ - languageFile=languageFileUserData; - } - if(fileExists(languageFile) == false){ - // if there is no language specific file use english instead - languageFile=englishFile; - } - if(fileExists(englishFile) == false){ - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] file [%s] not found\n",__FILE__,__FUNCTION__,__LINE__,englishFile.c_str()); - } - else { - logger.loadGameHints(englishFile,languageFile,true); - - ::Shared::Platform::Window::handleEvent(); - SDL_PumpEvents(); - } - - if((loadTypes & lgt_FactionPreview) == lgt_FactionPreview) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - Game::findFactionLogoFile(&gameSettings, &logger); - - ::Shared::Platform::Window::handleEvent(); - SDL_PumpEvents(); - } - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - loadHudTexture(&gameSettings); - - const string markCellTextureFilename = data_path + "data/core/misc_textures/mark_cell.png"; - markCellTexture = Renderer::findTexture(markCellTextureFilename); - const string unmarkCellTextureFilename = data_path + "data/core/misc_textures/unmark_cell.png"; - unmarkCellTexture = Renderer::findTexture(unmarkCellTextureFilename); - const string highlightCellTextureFilename = data_path + "data/core/misc_textures/pointer.png"; - highlightCellTexture = Renderer::findTexture(highlightCellTextureFilename); - - string scenarioDir = ""; - if(gameSettings.getScenarioDir() != "") { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - scenarioDir = gameSettings.getScenarioDir(); - if(EndsWith(scenarioDir, ".xml") == true) { - scenarioDir = scenarioDir.erase(scenarioDir.size() - 4, 4); - scenarioDir = scenarioDir.erase(scenarioDir.size() - gameSettings.getScenario().size(), gameSettings.getScenario().size() + 1); +void Game::setupPopupMenus(bool checkClientAdminOverrideOnly) { + Lang &lang = Lang::getInstance(); + NetworkManager &networkManager = NetworkManager::getInstance(); + NetworkRole role = networkManager.getNetworkRole(); + ClientInterface *clientInterface = NULL; + ServerInterface *serverInterface = NULL; + + bool allowAdminMenuItems = false; + bool forceJoinInProgressUpdate = false; + if (role == nrServer) { + allowAdminMenuItems = true; + + if (disconnectPlayerPopupMenuIndex == -1) { + serverInterface = + dynamic_cast(networkManager.getServerInterface()); + if (serverInterface != NULL && checkClientAdminOverrideOnly == true) { + for (int i = 0; i < world.getFactionCount(); ++i) { + Faction *faction = world.getFaction(i); + + MutexSafeWrapper safeMutex( + serverInterface->getSlotMutex(faction->getStartLocationIndex()), + CODE_AT_LINE); + ConnectionSlot *slot = + serverInterface->getSlot(faction->getStartLocationIndex(), false); + if (slot != NULL && slot->getConnectHasHandshaked() == true && + slot->getCurrentFrameCount() <= 0) { + // printf("Connected slot can be disconnected: + // %d\n",slot->getPlayerIndex()); + + forceJoinInProgressUpdate = true; + break; + } } + } + } + } else if (role == nrClient) { + clientInterface = + dynamic_cast(networkManager.getClientInterface()); + + if (clientInterface != NULL && + (gameSettings.getMasterserver_admin() == + clientInterface->getSessionKey() || + clientInterface->isMasterServerAdminOverride() == true)) { + allowAdminMenuItems = true; + } + } + + if (checkClientAdminOverrideOnly == false || + forceJoinInProgressUpdate == true || + (clientInterface != NULL && + (gameSettings.getMasterserver_admin() != + clientInterface->getSessionKey() && + clientInterface->isMasterServerAdminOverride() == true))) { + exitGamePopupMenuIndex = -1; + joinTeamPopupMenuIndex = -1; + pauseGamePopupMenuIndex = -1; + saveGamePopupMenuIndex = -1; + loadGamePopupMenuIndex = -1; + keyboardSetupPopupMenuIndex = -1; + disconnectPlayerPopupMenuIndex = -1; + + if (checkClientAdminOverrideOnly == true && clientInterface != NULL) { + gameSettings.setMasterserver_admin(clientInterface->getSessionKey()); + gameSettings.setMasterserver_admin_faction_index( + clientInterface->getPlayerIndex()); + } + // PopupMenu popupMenu; + std::vector menuItems; + menuItems.push_back(" " + lang.getString("ExitGameMenu") + " "); + exitGamePopupMenuIndex = (int)menuItems.size() - 1; + + if ((gameSettings.getFlagTypes1() & ft1_allow_team_switching) == + ft1_allow_team_switching && + world.getThisFaction() != NULL && + world.getThisFaction()->getPersonalityType() != fpt_Observer) { + menuItems.push_back(" " + lang.getString("JoinOtherTeam") + " "); + joinTeamPopupMenuIndex = (int)menuItems.size() - 1; } - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } + if (allowAdminMenuItems == true) { + menuItems.push_back(" " + lang.getString("PauseResumeGame") + " "); + pauseGamePopupMenuIndex = (int)menuItems.size() - 1; + + if (gameSettings.isNetworkGame() == false || + gameSettings.getScenario() != "") { + menuItems.push_back(" " + lang.getString("SaveGame") + " "); + saveGamePopupMenuIndex = (int)menuItems.size() - 1; + } + + if (gameSettings.isNetworkGame() == true) { + menuItems.push_back(" " + lang.getString("DisconnectNetorkPlayer") + + " "); + disconnectPlayerPopupMenuIndex = (int)menuItems.size() - 1; + } + } + menuItems.push_back(" " + lang.getString("KeyboardsetupL") + " "); + keyboardSetupPopupMenuIndex = (int)menuItems.size() - 1; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + menuItems.push_back(" " + lang.getString("Cancel") + " "); - //tileset - if((loadTypes & lgt_TileSet) == lgt_TileSet) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - world.loadTileset( config.getPathListForType(ptTilesets,scenarioDir), - tilesetName, &checksum, loadedFileList); - } + popupMenu.setW(100); + popupMenu.setH(100); + popupMenu.init(" " + lang.getString("GameMenuTitle") + " ", menuItems); + popupMenu.setEnabled(false); + popupMenu.setVisible(false); - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } + popupMenuSwitchTeams.setEnabled(false); + popupMenuSwitchTeams.setVisible(false); - // give CPU time to update other things to avoid apperance of hanging - sleep(0); - ::Shared::Platform::Window::handleEvent(); - SDL_PumpEvents(); + popupMenuDisconnectPlayer.setEnabled(false); + popupMenuDisconnectPlayer.setVisible(false); + } +} - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void Game::processNetworkSynchChecksIfRequired() { + bool isNetworkGame = this->gameSettings.isNetworkGame(); + if (isNetworkGame == true && + NetworkManager::getInstance().getGameNetworkInterface() != NULL) { + GameSettings *settings = world.getGameSettingsPtr(); + if (settings != NULL) { + bool calculateNetworkCRC = false; + + if (isFlagType1BitEnabled(ft1_network_synch_checks) == true || + isFlagType1BitEnabled(ft1_network_synch_checks_verbose) == true) { + calculateNetworkCRC = true; + } + + if (calculateNetworkCRC == true) { + NetworkManager &networkManager = NetworkManager::getInstance(); + NetworkRole role = networkManager.getNetworkRole(); + + NetworkInterface *netIntf = networkManager.getGameNetworkInterface(); + for (int index = 0; index < GameConstants::maxPlayers; ++index) { + if (index < world.getFactionCount()) { + Faction *faction = world.getFaction(index); + netIntf->setNetworkPlayerFactionCRC(index, + faction->getCRC().getSum()); + + if (settings != NULL) { + if (isFlagType1BitEnabled(ft1_network_synch_checks_verbose) == + true) { + faction->addCRC_DetailsForWorldFrame(world.getFrameCount(), + role == nrServer); + } else if (isFlagType1BitEnabled(ft1_network_synch_checks) == + true && + world.getFrameCount() % 20 == 0) { + faction->addCRC_DetailsForWorldFrame(world.getFrameCount(), + role == nrServer); + } + } + } else { + netIntf->setNetworkPlayerFactionCRC(index, 0); + } + } + } + } + } +} - set factions; - for ( int i=0; i < gameSettings.getFactionCount(); ++i ) { - factions.insert(gameSettings.getFactionTypeName(i)); - } +// update +void Game::update() { + try { + if (currentUIState != NULL) { + currentUIState->update(); + } - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } + bool showPerfStats = + Config::getInstance().getBool("ShowPerfStats", "false"); + Chrono chronoPerf; + char perfBuf[8096] = ""; + std::vector perfList; + if (showPerfStats) + chronoPerf.start(); + + if (showPerfStats) { + sprintf(perfBuf, + "=============== FRAME: %d In [%s::%s] Line: %d took " + "msecs: " MG_I64_SPECIFIER "\n", + world.getFrameCount(), + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } - if((loadTypes & lgt_TechTree) == lgt_TechTree) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + Chrono chronoGamePerformanceCounts; + Chrono chrono; + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled) + chrono.start(); + + // a) Updates non dependent on speed + + // set game stats for host + NetworkManager &networkManager = NetworkManager::getInstance(); + NetworkRole role = networkManager.getNetworkRole(); + if (role == nrServer) { + ServerInterface *server = + NetworkManager::getInstance().getServerInterface(false); + if (server != NULL) { + server->setGameStats(world.getStats()); + } + } - //tech, load before map because of resources - world.loadTech( config.getPathListForType(ptTechs,scenarioDir), techName, - factions, &checksum,loadedFileList); + bool pendingQuitError = + (quitPendingIndicator == true || + (NetworkManager::getInstance().getGameNetworkInterface() != NULL && + NetworkManager::getInstance().getGameNetworkInterface()->getQuit())); + + if (pendingQuitError == true && (this->masterserverMode == true || + (mainMessageBox.getEnabled() == false && + errorMessageBox.getEnabled() == false))) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + quitTriggeredIndicator = true; + return; + } - if(world.getTechTree() == NULL || world.getTechTree()->getNameUntranslated() == "") { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Line ref: %d, ERROR: Cannot find techtree: [%s]",__LINE__,techName.c_str()); + if (this->masterserverMode == false) { + if (world.getFactionCount() > 0 && + world.getThisFaction()->getFirstSwitchTeamVote() != NULL) { + const SwitchTeamVote *vote = + world.getThisFaction()->getFirstSwitchTeamVote(); + GameSettings *settings = world.getGameSettingsPtr(); + + Lang &lang = Lang::getInstance(); + + char szBuf[8096] = ""; + if (lang.hasString("AllowPlayerJoinTeam") == true) { + snprintf(szBuf, 8096, lang.getString("AllowPlayerJoinTeam").c_str(), + settings->getNetworkPlayerName(vote->factionIndex).c_str(), + vote->oldTeam, vote->newTeam); + } else { + snprintf(szBuf, 8096, + "Allow player [%s] to join your team\n(changing from team# " + "%d to team# %d)?", + settings->getNetworkPlayerName(vote->factionIndex).c_str(), + vote->oldTeam, vote->newTeam); + } - throw megaglest_runtime_error(szBuf, true); - } + switchTeamConfirmMessageBox.setText(szBuf); + switchTeamConfirmMessageBox.init(lang.getString("Yes"), + lang.getString("No")); + switchTeamConfirmMessageBox.setEnabled(true); + + world.getThisFactionPtr()->setCurrentSwitchTeamVoteFactionIndex( + vote->factionIndex); + } } - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } + // misc + updateFps++; + mouse2d = (mouse2d + 1) % Renderer::maxMouse2dAnim; - // give CPU time to update other things to avoid apperance of hanging - sleep(0); - ::Shared::Platform::Window::handleEvent(); - SDL_PumpEvents(); + // console + console.update(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // b) Updates depandant on speed + int updateLoops = getUpdateLoops(); - //map - if((loadTypes & lgt_Map) == lgt_Map) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - world.loadMap(Config::getMapPath(mapName,scenarioDir), &checksum); - } + // Temp speed boost when player first joins an in progress game + if (this->initialResumeSpeedLoops == true) { + printf("Resume In Progress Game: %d\n", __LINE__); - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } + this->initialResumeSpeedLoops = false; + // updateLoops = 80; + } - // give CPU time to update other things to avoid apperance of hanging - sleep(0); - ::Shared::Platform::Window::handleEvent(); - SDL_PumpEvents(); + chronoGamePerformanceCounts.start(); + bool enableServerControlledAI = + this->gameSettings.getEnableServerControlledAI(); + + if (role == nrClient && updateLoops == 1 && + world.getFrameCount() >= (gameSettings.getNetworkFramePeriod() * 2)) { + ClientInterface *clientInterface = + dynamic_cast(networkManager.getClientInterface()); + if (clientInterface != NULL) { + uint64 lastNetworkFrameFromServer = + clientInterface->getCachedLastPendingFrameCount(); + + ///////////////////////////////// + // TTTT new attempt to make things smoother: + /////////////// + + //////////////////////////////////////////// + // get stats of received/waiting for packages + //////////////////////////////////////////// + // calculate current receive Index slot: + int index = + ((world.getFrameCount() - + (world.getFrameCount() % gameSettings.getNetworkFramePeriod())) / + gameSettings.getNetworkFramePeriod()) % + GameConstants::networkSmoothInterval; + + // clean the next frame slot + receivedTooEarlyInFrames[(index + 1) % + GameConstants::networkSmoothInterval] = -1; + framesNeededToWaitForServerMessage + [(index + 1) % GameConstants::networkSmoothInterval] = -1; + + if (receivedTooEarlyInFrames[index] == -1) { + // we need to check if we already received something for next frame + if (lastNetworkFrameFromServer > 0 && + lastNetworkFrameFromServer > (uint64)world.getFrameCount()) { + receivedTooEarlyInFrames[index] = + lastNetworkFrameFromServer - world.getFrameCount(); + } + } + if (framesNeededToWaitForServerMessage[index] == -1) { + // calc time waiting for message in milliseconds to frames + int64 timeClientWaitedForLastMessage = + clientInterface->getTimeClientWaitedForLastMessage(); + if (timeClientWaitedForLastMessage > 0) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("world.getFrameCount():%d index %d Client waited:%d ms\n", + world.getFrameCount(), index, + (int)timeClientWaitedForLastMessage); + framesNeededToWaitForServerMessage[index] = + timeClientWaitedForLastMessage * GameConstants::updateFps / + 1000; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("ClienttimeClientWaitedForLastMessage:%d ms which is %d " + "frames \n", + (int)timeClientWaitedForLastMessage, + framesNeededToWaitForServerMessage[index]); + } else { + framesNeededToWaitForServerMessage[index] = 0; + } + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + //////////////////////////////////////////// + // use the recorded stats of received/waiting for packages + //////////////////////////////////////////// + // lets see if the client is in front and had to wait for messages ... + + // lets see if all last recorded frames where received too early + int minimum = 0; + int allowedMaxFallback = 5; + int countOfMessagesReceivedTooEarly = 0; + int countOfMessagesReceivedTooLate = 0; + int sumOfTooLateFrames = 0; + bool cleanupStats = false; + + for (int i = 0; i < GameConstants::networkSmoothInterval; i++) { + if (receivedTooEarlyInFrames[i] > allowedMaxFallback) { + countOfMessagesReceivedTooEarly++; + if (minimum == 0 || minimum > receivedTooEarlyInFrames[i]) { + minimum = receivedTooEarlyInFrames[i]; + } + } + if (framesNeededToWaitForServerMessage[i] > 0) { + countOfMessagesReceivedTooLate++; + sumOfTooLateFrames += framesNeededToWaitForServerMessage[i]; + } + } - //scenario - if((loadTypes & lgt_Scenario) == lgt_Scenario) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(scenarioName.empty() == false) { + if (countOfMessagesReceivedTooEarly == + GameConstants::networkSmoothInterval - + 1) // -1 because slot for next frame is already initialized + { // all packages where too early + // we catch up the minimum-catchupInterval of what we recorded + framesToCatchUpAsClient = minimum - allowedMaxFallback; + framesToSlowDownAsClient = 0; + cleanupStats = true; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Worldframe %d : Client will speed up: %d frames\n", + world.getFrameCount(), framesToCatchUpAsClient); + } else if (countOfMessagesReceivedTooLate > 3) { + framesToSlowDownAsClient = + sumOfTooLateFrames / countOfMessagesReceivedTooLate; + framesToCatchUpAsClient = 0; + cleanupStats = true; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Worldframe %d : Client will slow down: %d frames\n", + world.getFrameCount(), framesToSlowDownAsClient); + } - bool isTutorial = Scenario::isGameTutorial(gameSettings.getScenarioDir()); - //printf("Loading scenario gameSettings.getScenarioDir() [%s] scenarioName [%s] isTutorial: %d\n",gameSettings.getScenarioDir().c_str(),scenarioName.c_str(),isTutorial); + if (cleanupStats == true) { + // Once we decided to use the stats to do some correction, we + // reset/cleanup our recorded stats + for (int i = 0; i < GameConstants::networkSmoothInterval; i++) { + receivedTooEarlyInFrames[i] = -1; + framesNeededToWaitForServerMessage[i] = -1; + } + } + } + } + // if game is paused don't try to catch up + if (updateLoops > 0) { + // we catch up a bit smoother with updateLoops = 2 + if (framesToCatchUpAsClient > 0) { + updateLoops = 2; + framesToCatchUpAsClient = framesToCatchUpAsClient - 1; + } + if (framesToSlowDownAsClient > 0) { // slowdown still the hard way. + updateLoops = 0; + framesToSlowDownAsClient = framesToSlowDownAsClient - 1; + } + } - Lang::getInstance().loadScenarioStrings(gameSettings.getScenarioDir(), scenarioName, isTutorial); + addPerformanceCount("CalculateNetworkUpdateLoops", + chronoGamePerformanceCounts.getMillis()); + + 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()); + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } - //printf("In [%s::%s Line: %d] rootNode [%p][%s]\n",__FILE__,__FUNCTION__,__LINE__,loadGameNode,(loadGameNode != NULL ? loadGameNode->getName().c_str() : "none")); - world.loadScenario(gameSettings.getScenarioDir(), &checksum, false,loadGameNode); - } + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s] Line: %d took msecs: %lld [before " + "ReplaceDisconnectedNetworkPlayersWithAI]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, chrono.getMillis()); + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); } - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } + // Check to see if we are playing a network game and if any players + // have disconnected? + bool isNetworkGame = this->gameSettings.isNetworkGame(); + + chronoGamePerformanceCounts.start(); + + ReplaceDisconnectedNetworkPlayersWithAI(isNetworkGame, role); + + addPerformanceCount("ReplaceDisconnectedNetworkPlayersWithAI", + chronoGamePerformanceCounts.getMillis()); + + setupPopupMenus(true); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s] Line: %d took msecs: %lld [after " + "ReplaceDisconnectedNetworkPlayersWithAI]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, chrono.getMillis()); + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } - // give CPU time to update other things to avoid apperance of hanging - sleep(0); - SDL_PumpEvents(); + if (updateLoops > 0) { + // update the frame based timer in the stats with at least one step + world.getStats()->addFramesToCalculatePlaytime(); + + // update + Chrono chronoReplay; + int64 lastReplaySecond = -1; + int replayCommandsPlayed = 0; + int replayTotal = commander.getReplayCommandListForFrameCount(); + if (replayTotal > 0) { + chronoReplay.start(); + } + + do { + if (replayTotal > 0) { + replayCommandsPlayed = + (replayTotal - commander.getReplayCommandListForFrameCount()); + } + for (int i = 0; i < updateLoops; ++i) { + // if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) + // chrono.start(); + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + // AiInterface + if (commander.hasReplayCommandListForFrame() == false) { + chronoGamePerformanceCounts.start(); + + processNetworkSynchChecksIfRequired(); + + addPerformanceCount("CalculateNetworkCRCSynchChecks", + chronoGamePerformanceCounts.getMillis()); + + const bool newThreadManager = Config::getInstance().getBool( + "EnableNewThreadManager", "false"); + if (newThreadManager == true) { + int currentFrameCount = world.getFrameCount(); + masterController.signalSlaves(¤tFrameCount); + // bool slavesCompleted = + // masterController.waitTillSlavesTrigger(20000); + masterController.waitTillSlavesTrigger(20000); + } else { + // Signal the faction threads to do any pre-processing + chronoGamePerformanceCounts.start(); + + bool hasAIPlayer = false; + for (int j = 0; j < world.getFactionCount(); ++j) { + Faction *faction = world.getFaction(j); + + // printf("Faction Index = %d enableServerControlledAI = %d, + // isNetworkGame = %d, role = %d isCPU player = %d + // scriptManager.getPlayerModifiers(j)->getAiEnabled() = + // %d\n",j,enableServerControlledAI,isNetworkGame,role,faction->getCpuControl(enableServerControlledAI,isNetworkGame,role),scriptManager.getPlayerModifiers(j)->getAiEnabled()); + + if (faction->getCpuControl(enableServerControlledAI, + isNetworkGame, role) == true && + scriptManager.getPlayerModifiers(j)->getAiEnabled() == + true) { + + if (SystemFlags::getSystemSettingType( + SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] [i = %d] faction = %d, " + "factionCount = %d, took msecs: %lld [before AI " + "updates]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, i, j, world.getFactionCount(), + chrono.getMillis()); + aiInterfaces[j]->signalWorkerThread(world.getFrameCount()); + hasAIPlayer = true; + } + } + + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER + "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + if (hasAIPlayer == true) { + // sleep(0); + + Chrono chronoAI; + chronoAI.start(); + + const int MAX_FACTION_THREAD_WAIT_MILLISECONDS = 20000; + for (; chronoAI.getMillis() < + MAX_FACTION_THREAD_WAIT_MILLISECONDS;) { + bool workThreadsFinished = true; + for (int j = 0; j < world.getFactionCount(); ++j) { + Faction *faction = world.getFaction(j); + if (faction == NULL) { + throw megaglest_runtime_error("faction == NULL"); + } + if (faction->getCpuControl(enableServerControlledAI, + isNetworkGame, role) == true && + scriptManager.getPlayerModifiers(j)->getAiEnabled() == + true) { + if (aiInterfaces[j]->isWorkerThreadSignalCompleted( + world.getFrameCount()) == false) { + workThreadsFinished = false; + break; + } + } + } + if (workThreadsFinished == false) { + // sleep(0); + } else { + break; + } + } + } + + addPerformanceCount("ProcessAIWorkerThreads", + chronoGamePerformanceCounts.getMillis()); + } + + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + } else { + // Simply show a progress message while replaying commands + if (lastReplaySecond < chronoReplay.getSeconds()) { + lastReplaySecond = chronoReplay.getSeconds(); + Renderer &renderer = Renderer::getInstance(); + renderer.clearBuffers(); + renderer.clearZBuffer(); + renderer.reset2d(); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "Please wait, loading game with replay [%d / %d]...", + replayCommandsPlayed, replayTotal); + string text = szBuf; + if (Renderer::renderText3DEnabled) { + Font3D *font = CoreData::getInstance().getMenuFontBig3D(); + const Metrics &metrics = Metrics::getInstance(); + int w = metrics.getVirtualW(); + int renderX = + (w / 2) - (font->getMetrics()->getTextWidth(text) / 2); + int h = metrics.getVirtualH(); + int renderY = + (h / 2) + (font->getMetrics()->getHeight(text) / 2); + + renderer.renderText3D(text, font, Vec3f(1.f, 1.f, 0.f), renderX, + renderY, false); + } else { + Font2D *font = CoreData::getInstance().getMenuFontBig(); + const Metrics &metrics = Metrics::getInstance(); + int w = metrics.getVirtualW(); + int renderX = (w / 2); + int h = metrics.getVirtualH(); + int renderY = (h / 2); + + renderer.renderText(text, font, Vec3f(1.f, 1.f, 0.f), renderX, + renderY, true); + } + + renderer.swapBuffers(); + } + } + + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s] Line: %d took msecs: %lld [AI updates]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // World + chronoGamePerformanceCounts.start(); + + if (pendingQuitError == false) + world.update(); + + addPerformanceCount("ProcessWorldUpdate", + chronoGamePerformanceCounts.getMillis()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s] Line: %d took msecs: %lld [world update i = %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chrono.getMillis(), i); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + if (currentCameraFollowUnit != NULL) { + Vec3f c = currentCameraFollowUnit->getCurrMidHeightVector(); + int rotation = currentCameraFollowUnit->getRotation(); + float angle = rotation + 180; + + c.z = c.z + 4 * std::cos(degToRad(angle)); + c.x = c.x + 4 * std::sin(degToRad(angle)); + + c.y = c.y + currentCameraFollowUnit->getType()->getHeight() / 2.f + + 2.0f; + + getGameCameraPtr()->setPos(c); + + rotation = (540 - rotation) % 360; + getGameCameraPtr()->rotateToVH(18.0f, rotation); + + if (currentCameraFollowUnit->isAlive() == false) { + currentCameraFollowUnit = NULL; + getGameCameraPtr()->setState(GameCamera::sGame); + } + } + + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + // Commander + chronoGamePerformanceCounts.start(); + + if (pendingQuitError == false) { + commander.signalNetworkUpdate(this); + } + + addPerformanceCount("ProcessNetworkUpdate", + chronoGamePerformanceCounts.getMillis()); + + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s] Line: %d took msecs: %lld [commander " + "updateNetwork i = %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chrono.getMillis(), i); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // Gui + chronoGamePerformanceCounts.start(); + + gui.update(); + + addPerformanceCount("ProcessGUIUpdate", + chronoGamePerformanceCounts.getMillis()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s] Line: %d took msecs: %lld [gui updating i = %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chrono.getMillis(), i); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + // Particle systems + if (weatherParticleSystem != NULL) { + weatherParticleSystem->setPos(gameCamera.getPos()); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s] Line: %d took msecs: %lld [weather particle " + "updating i = %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chrono.getMillis(), i); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + Renderer &renderer = Renderer::getInstance(); + + chronoGamePerformanceCounts.start(); + + renderer.updateParticleManager(rsGame, avgRenderFps); + + addPerformanceCount("ProcessParticleManager", + chronoGamePerformanceCounts.getMillis()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s] Line: %d took msecs: %lld [particle manager " + "updating i = %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chrono.getMillis(), i); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + // good_fpu_control_registers(NULL,extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + } + } while (commander.hasReplayCommandListForFrame() == true); + } + // else if(role == nrClient) { + else { + if (pendingQuitError == false) { + commander.signalNetworkUpdate(this); + } + + if (playingStaticVideo == true) { + if (videoPlayer->isPlaying() == false) { + playingStaticVideo = false; + tryPauseToggle(false); + } + } + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //good_fpu_control_registers(NULL,extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } - if(showPerfStats && chronoPerf.getMillis() >= 50) { - for(unsigned int x = 0; x < perfList.size(); ++x) { - printf("%s",perfList[x].c_str()); - } - } -} + chronoGamePerformanceCounts.start(); + + // call the chat manager + chatManager.updateNetwork(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s] Line: %d took msecs: %lld [chatManager.updateNetwork]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } -void Game::init() { - init(false); -} + updateNetworkMarkedCells(); + updateNetworkUnMarkedCells(); + updateNetworkHighligtedCells(); -void Game::init(bool initForPreviewOnly) { - bool showPerfStats = Config::getInstance().getBool("ShowPerfStats","false"); - Chrono chronoPerf; - if(showPerfStats) chronoPerf.start(); - char perfBuf[8096]=""; - std::vector perfList; - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] initForPreviewOnly = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,initForPreviewOnly); - - Lang &lang= Lang::getInstance(); - Logger &logger= Logger::getInstance(); - CoreData &coreData= CoreData::getInstance(); - Renderer &renderer= Renderer::getInstance(); - Map *map= world.getMap(); - NetworkManager &networkManager= NetworkManager::getInstance(); - - GameSettings::playerDisconnectedText = "*" + lang.getString("AI") + "* "; - - if(map == NULL) { - throw megaglest_runtime_error("map == NULL"); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(initForPreviewOnly == false) { - logger.setState(lang.getString("Initializing")); - - //message box - mainMessageBox.init(lang.getString("Yes"), lang.getString("No")); - mainMessageBox.setEnabled(false); - - //message box - errorMessageBox.init(lang.getString("Ok")); - errorMessageBox.setEnabled(false); - errorMessageBox.setY(20); - - - //init world, and place camera - commander.init(&world); - - // give CPU time to update other things to avoid apperance of hanging - sleep(0); - ::Shared::Platform::Window::handleEvent(); - SDL_PumpEvents(); - } - - try { - world.init(this, gameSettings.getDefaultUnits()); - } - catch(const megaglest_runtime_error &ex) { - string sErrBuf = ""; - if(ex.wantStackTrace() == true) { - char szErrBuf[8096]=""; - snprintf(szErrBuf,8096,"In [%s::%s %d]",__FILE__,__FUNCTION__,__LINE__); - sErrBuf = string(szErrBuf) + string("\nerror [") + string(ex.what()) + string("]\n"); - } - else { - sErrBuf = ex.what(); - } - SystemFlags::OutputDebug(SystemFlags::debugError,sErrBuf.c_str()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,sErrBuf.c_str()); - - if(errorMessageBox.getEnabled() == false) { - ErrorDisplayMessage(ex.what(),true); - } - } - catch(const exception &ex) { - char szErrBuf[8096]=""; - snprintf(szErrBuf,8096,"In [%s::%s %d]",__FILE__,__FUNCTION__,__LINE__); - string sErrBuf = string(szErrBuf) + string("\nerror [") + string(ex.what()) + string("]\n"); - SystemFlags::OutputDebug(SystemFlags::debugError,sErrBuf.c_str()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,sErrBuf.c_str()); - - if(errorMessageBox.getEnabled() == false) { - ErrorDisplayMessage(ex.what(),true); - } - } - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - if(loadGameNode != NULL) { - //world.getMapPtr()->loadGame(loadGameNode,&world); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(initForPreviewOnly == false) { - // give CPU time to update other things to avoid apperance of hanging - sleep(0); - ::Shared::Platform::Window::handleEvent(); - SDL_PumpEvents(); - - gui.init(this); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - // give CPU time to update other things to avoid apperance of hanging - sleep(0); - //SDL_PumpEvents(); - - chatManager.init(&console, world.getThisTeamIndex()); - console.clearStoredLines(); - } - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - if(this->loadGameNode == NULL) { - initCamera(map); - } - else { - gui.loadGame(loadGameNode,&world); - - if(inJoinGameLoading == true) { - initCamera(map); - } - } - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - NetworkRole role = nrIdle; - if(initForPreviewOnly == false) { - // give CPU time to update other things to avoid apperance of hanging - sleep(0); - ::Shared::Platform::Window::handleEvent(); - SDL_PumpEvents(); - - scriptManager.init(&world, &gameCamera,loadGameNode); - - //good_fpu_control_registers(NULL,extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] creating AI's\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //create AIs - - bool enableServerControlledAI = this->gameSettings.getEnableServerControlledAI(); - bool isNetworkGame = this->gameSettings.isNetworkGame(); - role = networkManager.getNetworkRole(); - - masterController.clearSlaves(true); - deleteValues(aiInterfaces.begin(), aiInterfaces.end()); - - std::vector slaveThreadList; - aiInterfaces.resize(world.getFactionCount()); - for(int i=0; i < world.getFactionCount(); ++i) { - Faction *faction= world.getFaction(i); - - //printf("Controltype = %d for index = %d\n",faction->getControlType(),i); - - if(faction->getCpuControl(enableServerControlledAI,isNetworkGame,role) == true) { - //printf("** Loading AI player for Controltype = %d for index = %d\n",faction->getControlType(),i); - - aiInterfaces[i]= new AiInterface(*this, i, faction->getTeam()); - if(loadGameNode != NULL) { - aiInterfaces[i]->loadGame(loadGameNode,faction); - } - char szBuf[8096]=""; - snprintf(szBuf,8096,Lang::getInstance().getString("LogScreenGameLoadingCreatingAIFaction","",true).c_str(),i); - logger.add(szBuf, true); - - slaveThreadList.push_back(aiInterfaces[i]->getWorkerThread()); - } - else { - aiInterfaces[i]= NULL; - } - } - if(Config::getInstance().getBool("EnableNewThreadManager","false") == true) { - masterController.setSlaves(slaveThreadList); - } - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - // give CPU time to update other things to avoid apperance of hanging - sleep(0); - ::Shared::Platform::Window::handleEvent(); - SDL_PumpEvents(); - - if(world.getFactionCount() == 1 && world.getFaction(0)->getPersonalityType() == fpt_Observer) { - withRainEffect = false; - } - - if(withRainEffect) { - //weather particle systems - if(world.getTileset()->getWeather() == wRainy) { - logger.add(Lang::getInstance().getString("LogScreenGameLoadingCreatingRainParticles","",true), true); - weatherParticleSystem= new RainParticleSystem(); - weatherParticleSystem->setSpeed(12.f / GameConstants::updateFps); - weatherParticleSystem->setPos(gameCamera.getPos()); - renderer.manageParticleSystem(weatherParticleSystem, rsGame); - } - else if(world.getTileset()->getWeather() == wSnowy) { - logger.add(Lang::getInstance().getString("LogScreenGameLoadingCreatingSnowParticles","",true), true); - weatherParticleSystem= new SnowParticleSystem(1200); - weatherParticleSystem->setSpeed(1.5f / GameConstants::updateFps); - weatherParticleSystem->setPos(gameCamera.getPos()); - weatherParticleSystem->setTexture(coreData.getSnowTexture()); - renderer.manageParticleSystem(weatherParticleSystem, rsGame); - } - } - else if(world.getTileset()->getWeather() == wRainy) { - world.getTileset()->setWeather(wSunny); - } - - renderer.manageDeferredParticleSystems(); - } - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - //init renderer state - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Initializing renderer\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); - logger.add(Lang::getInstance().getString("LogScreenGameLoadingInitRenderer","",true), true); - - //printf("Before renderer.initGame\n"); - renderer.initGame(this,this->getGameCameraPtr()); - //printf("After renderer.initGame\n"); - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - for(int i=0; i < world.getFactionCount(); ++i) { - Faction *faction= world.getFaction(i); - if(faction != NULL) { - faction->deletePixels(); - } - } - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - if(initForPreviewOnly == false) { - //good_fpu_control_registers(NULL,extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - // give CPU time to update other things to avoid apperance of hanging - sleep(0); - ::Shared::Platform::Window::handleEvent(); - SDL_PumpEvents(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Waiting for network\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); - logger.add(Lang::getInstance().getString("LogScreenGameLoadingWaitForNetworkPlayers","",true), true); - networkManager.getGameNetworkInterface()->waitUntilReady(&checksum); - - //std::string worldLog = world.DumpWorldToLog(true); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] Starting music stream\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - logger.add(Lang::getInstance().getString("LogScreenGameLoadingStartingMusic","",true), true); - - if(this->masterserverMode == false) { - if(world.getThisFaction() == NULL) { - throw megaglest_runtime_error("world.getThisFaction() == NULL"); - } - if(world.getThisFaction()->getType() == NULL) { - throw megaglest_runtime_error("world.getThisFaction()->getType() == NULL"); - } - //if(world.getThisFaction()->getType()->getMusic() == NULL) { - // throw megaglest_runtime_error("world.getThisFaction()->getType()->getMusic() == NULL"); - //} - } - - //sounds - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - soundRenderer.stopAllSounds(fadeMusicMilliseconds); - soundRenderer= SoundRenderer::getInstance(); - - Tileset *tileset= world.getTileset(); - AmbientSounds *ambientSounds= tileset->getAmbientSounds(); - - //rain - if(tileset->getWeather() == wRainy && ambientSounds->isEnabledRain()) { - logger.add(Lang::getInstance().getString("LogScreenGameLoadingStartingAmbient","",true), true); - currentAmbientSound = ambientSounds->getRain(); - //printf("In [%s:%s] Line: %d currentAmbientSound = [%p]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,currentAmbientSound); - soundRenderer.playAmbient(currentAmbientSound); - } - - //snow - if(tileset->getWeather() == wSnowy && ambientSounds->isEnabledSnow()) { - logger.add(Lang::getInstance().getString("LogScreenGameLoadingStartingAmbient","",true), true); - currentAmbientSound = ambientSounds->getSnow(); - //printf("In [%s:%s] Line: %d currentAmbientSound = [%p]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,currentAmbientSound); - soundRenderer.playAmbient(currentAmbientSound); - } - - if(this->masterserverMode == false) { - StrSound *gameMusic= world.getThisFaction()->getType()->getMusic(); - soundRenderer.playMusic(gameMusic); - } - - logger.add(Lang::getInstance().getString("LogScreenGameLoadingLaunchGame","",true)); - } - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - //throw "test"; - - logger.setCancelLoadingEnabled(false); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"================ STARTING GAME ================\n"); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPathFinder).enabled) SystemFlags::OutputDebug(SystemFlags::debugPathFinder,"================ STARTING GAME ================\n"); - setupPopupMenus(false); - - for(int i=0; i < world.getFactionCount(); ++i) { - Faction *faction= world.getFaction(i); - - //printf("Check for team switch to observer i = %d, team = %d [%d]\n",i,faction->getTeam(),(GameConstants::maxPlayers -1 + fpt_Observer)); - if(faction != NULL && faction->getTeam() == GameConstants::maxPlayers -1 + fpt_Observer) { - faction->setPersonalityType(fpt_Observer); - world.getStats()->setPersonalityType(i, faction->getPersonalityType()); - } - } - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - if(role == nrClient) { - ClientInterface *clientInterface = dynamic_cast(networkManager.getClientInterface()); - if(clientInterface != NULL && clientInterface->getResumeInGameJoin() == true) { - - //printf("Client sending resume message to server...\n"); - - clientInterface->sendResumeGameMessage(); - //this->initialResumeSpeedLoops = true; - } - } - - printf("Game unique identifier is: %s\n",this->gameSettings.getGameUUID().c_str()); - - gameStarted = true; - - if(this->masterserverMode == true) { - world.getStats()->setIsMasterserverMode(true); - - printf("New game has started...\n"); - } - - if(isFlagType1BitEnabled(ft1_network_synch_checks_verbose) == true) { - printf("*Note: Monitoring Network CRC VERBOSE synchronization...\n"); - } - else if(isFlagType1BitEnabled(ft1_network_synch_checks) == true) { - printf("*Note: Monitoring Network CRC NORMAL synchronization...\n"); - } - - //NetworkRole role = networkManager.getNetworkRole(); - if(role == nrServer) { - networkManager.initServerInterfaces(this); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] ==== START GAME ==== getCurrentPixelByteCount() = " MG_SIZE_T_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderer.getCurrentPixelByteCount()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled) SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"=============================================\n"); - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled) SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"==== START GAME ====\n"); - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled) SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"=============================================\n"); - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled) SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"Starting framecount: %d\n",world.getFrameCount()); - - if(showPerfStats && chronoPerf.getMillis() >= 50) { - for(unsigned int x = 0; x < perfList.size(); ++x) { - printf("%s",perfList[x].c_str()); - } - } -} + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } -void Game::initCamera(Map *map){ - gameCamera.init(map->getW(), map->getH()); - - // camera default height calculation - if(map->getCameraHeight()>0 && gameCamera.getCalculatedDefault()getCameraHeight()){ - gameCamera.setCalculatedDefault(map->getCameraHeight()); - } - else if(gameCamera.getCalculatedDefault()getMaxMapHeight()+13.0f){ - gameCamera.setCalculatedDefault(map->getMaxMapHeight()+13.0f); - } - - if(world.getThisFaction() != NULL) { - const Vec2i &v= map->getStartLocation(world.getThisFaction()->getStartLocationIndex()); - gameCamera.setPos(Vec2f(v.x, v.y+gameCamera.getCalculatedDefault()/2)); - } -} + // check for quiting status + if (NetworkManager::getInstance().getGameNetworkInterface() != NULL && + NetworkManager::getInstance().getGameNetworkInterface()->getQuit() && + mainMessageBox.getEnabled() == false && + errorMessageBox.getEnabled() == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + quitTriggeredIndicator = true; + return; + } -// ==================== update ==================== + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } -void Game::reInitGUI() { - gui.init(this); -} + addPerformanceCount("ProcessMiscNetwork", + chronoGamePerformanceCounts.getMillis()); -void Game::setupPopupMenus(bool checkClientAdminOverrideOnly) { - Lang &lang= Lang::getInstance(); - NetworkManager &networkManager= NetworkManager::getInstance(); - NetworkRole role = networkManager.getNetworkRole(); - ClientInterface *clientInterface = NULL; - ServerInterface *serverInterface = NULL; - - bool allowAdminMenuItems = false; - bool forceJoinInProgressUpdate = false; - if(role == nrServer) { - allowAdminMenuItems = true; - - if(disconnectPlayerPopupMenuIndex == -1) { - serverInterface = dynamic_cast(networkManager.getServerInterface()); - if(serverInterface != NULL && checkClientAdminOverrideOnly == true) { - for(int i = 0; i < world.getFactionCount(); ++i) { - Faction *faction = world.getFaction(i); - - MutexSafeWrapper safeMutex(serverInterface->getSlotMutex(faction->getStartLocationIndex()),CODE_AT_LINE); - ConnectionSlot *slot = serverInterface->getSlot(faction->getStartLocationIndex(),false); - if(slot != NULL && slot->getConnectHasHandshaked() == true && - slot->getCurrentFrameCount() <= 0) { - //printf("Connected slot can be disconnected: %d\n",slot->getPlayerIndex()); - - forceJoinInProgressUpdate = true; - break; - } - } - } - } - } - else if(role == nrClient) { - clientInterface = dynamic_cast(networkManager.getClientInterface()); - - if(clientInterface != NULL && - (gameSettings.getMasterserver_admin() == clientInterface->getSessionKey() || - clientInterface->isMasterServerAdminOverride() == true)) { - allowAdminMenuItems = true; - } - } - - if(checkClientAdminOverrideOnly == false || - forceJoinInProgressUpdate == true || - (clientInterface != NULL && - (gameSettings.getMasterserver_admin() != clientInterface->getSessionKey() && - clientInterface->isMasterServerAdminOverride() == true))) { - exitGamePopupMenuIndex = -1; - joinTeamPopupMenuIndex = -1; - pauseGamePopupMenuIndex = -1; - saveGamePopupMenuIndex = -1; - loadGamePopupMenuIndex = -1; - keyboardSetupPopupMenuIndex = -1; - disconnectPlayerPopupMenuIndex = -1; - - if(checkClientAdminOverrideOnly == true && clientInterface != NULL) { - gameSettings.setMasterserver_admin(clientInterface->getSessionKey()); - gameSettings.setMasterserver_admin_faction_index(clientInterface->getPlayerIndex()); - } - //PopupMenu popupMenu; - std::vector menuItems; - menuItems.push_back(" " + lang.getString("ExitGameMenu") + " "); - exitGamePopupMenuIndex = (int)menuItems.size()-1; - - if((gameSettings.getFlagTypes1() & ft1_allow_team_switching) == ft1_allow_team_switching && - world.getThisFaction() != NULL && world.getThisFaction()->getPersonalityType() != fpt_Observer) { - menuItems.push_back(" " + lang.getString("JoinOtherTeam") + " "); - joinTeamPopupMenuIndex = (int)menuItems.size()-1; - } - - if(allowAdminMenuItems == true){ - menuItems.push_back(" " + lang.getString("PauseResumeGame") + " "); - pauseGamePopupMenuIndex= (int)menuItems.size() - 1; - - if(gameSettings.isNetworkGame() == false || gameSettings.getScenario() != "") { - menuItems.push_back(" " + lang.getString("SaveGame") + " "); - saveGamePopupMenuIndex= (int)menuItems.size() - 1; - } - - if(gameSettings.isNetworkGame() == true) { - menuItems.push_back(" " + lang.getString("DisconnectNetorkPlayer") + " "); - disconnectPlayerPopupMenuIndex= (int)menuItems.size() - 1; - } - } - menuItems.push_back(" " + lang.getString("KeyboardsetupL") + " "); - keyboardSetupPopupMenuIndex = (int)menuItems.size()-1; - - menuItems.push_back(" " + lang.getString("Cancel") + " "); - - popupMenu.setW(100); - popupMenu.setH(100); - popupMenu.init(" " + lang.getString("GameMenuTitle") + " ",menuItems); - popupMenu.setEnabled(false); - popupMenu.setVisible(false); - - popupMenuSwitchTeams.setEnabled(false); - popupMenuSwitchTeams.setVisible(false); - - popupMenuDisconnectPlayer.setEnabled(false); - popupMenuDisconnectPlayer.setVisible(false); - } -} + // START - Handle joining in progress games + if (role == nrServer) { -void Game::processNetworkSynchChecksIfRequired() { - bool isNetworkGame = this->gameSettings.isNetworkGame(); - if (isNetworkGame == true && NetworkManager::getInstance().getGameNetworkInterface() != NULL) { - GameSettings *settings = world.getGameSettingsPtr(); - if(settings != NULL) { - bool calculateNetworkCRC = false; - - if(isFlagType1BitEnabled(ft1_network_synch_checks) == true || - isFlagType1BitEnabled(ft1_network_synch_checks_verbose) == true) { - calculateNetworkCRC = true; - } - - if(calculateNetworkCRC == true) { - NetworkManager &networkManager = NetworkManager::getInstance(); - NetworkRole role = networkManager.getNetworkRole(); - - NetworkInterface *netIntf = networkManager.getGameNetworkInterface(); - for(int index = 0; index < GameConstants::maxPlayers; ++index) { - if(index < world.getFactionCount()) { - Faction *faction = world.getFaction(index); - netIntf->setNetworkPlayerFactionCRC(index,faction->getCRC().getSum()); - - if(settings != NULL) { - if(isFlagType1BitEnabled(ft1_network_synch_checks_verbose) == true) { - faction->addCRC_DetailsForWorldFrame(world.getFrameCount(),role == nrServer); - } - else if(isFlagType1BitEnabled(ft1_network_synch_checks) == true && - world.getFrameCount() % 20 == 0) { - faction->addCRC_DetailsForWorldFrame(world.getFrameCount(),role == nrServer); - } - } - } - else { - netIntf->setNetworkPlayerFactionCRC(index,0); - } - } - } - } - } -} + if (this->networkPauseGameForLaggedClientsRequested == true) { + this->networkPauseGameForLaggedClientsRequested = false; -//update -void Game::update() { - try { - if(currentUIState != NULL) { - currentUIState->update(); - } - - bool showPerfStats = Config::getInstance().getBool("ShowPerfStats","false"); - Chrono chronoPerf; - char perfBuf[8096]=""; - std::vector perfList; - if(showPerfStats) chronoPerf.start(); - - if(showPerfStats) { - sprintf(perfBuf,"=============== FRAME: %d In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",world.getFrameCount(),extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - Chrono chronoGamePerformanceCounts; - Chrono chrono; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); - - // a) Updates non dependent on speed - - // set game stats for host - NetworkManager &networkManager = NetworkManager::getInstance(); - NetworkRole role = networkManager.getNetworkRole(); - if(role == nrServer) { - ServerInterface *server = NetworkManager::getInstance().getServerInterface(false); - if(server != NULL) { - server->setGameStats(world.getStats()); - } - } - - bool pendingQuitError = (quitPendingIndicator == true || - (NetworkManager::getInstance().getGameNetworkInterface() != NULL && - NetworkManager::getInstance().getGameNetworkInterface()->getQuit())); - - if(pendingQuitError == true && - (this->masterserverMode == true || - (mainMessageBox.getEnabled() == false && errorMessageBox.getEnabled() == false))) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - quitTriggeredIndicator = true; - return; - } - - if(this->masterserverMode == false) { - if(world.getFactionCount() > 0 && world.getThisFaction()->getFirstSwitchTeamVote() != NULL) { - const SwitchTeamVote *vote = world.getThisFaction()->getFirstSwitchTeamVote(); - GameSettings *settings = world.getGameSettingsPtr(); - - Lang &lang= Lang::getInstance(); - - char szBuf[8096]=""; - if(lang.hasString("AllowPlayerJoinTeam") == true) { - snprintf(szBuf,8096,lang.getString("AllowPlayerJoinTeam").c_str(),settings->getNetworkPlayerName(vote->factionIndex).c_str(),vote->oldTeam,vote->newTeam); - } - else { - snprintf(szBuf,8096,"Allow player [%s] to join your team\n(changing from team# %d to team# %d)?",settings->getNetworkPlayerName(vote->factionIndex).c_str(),vote->oldTeam,vote->newTeam); - } - - switchTeamConfirmMessageBox.setText(szBuf); - switchTeamConfirmMessageBox.init(lang.getString("Yes"), lang.getString("No")); - switchTeamConfirmMessageBox.setEnabled(true); - - world.getThisFactionPtr()->setCurrentSwitchTeamVoteFactionIndex(vote->factionIndex); - } - } - - //misc - updateFps++; - mouse2d= (mouse2d+1) % Renderer::maxMouse2dAnim; - - //console - console.update(); - - // b) Updates depandant on speed - int updateLoops= getUpdateLoops(); - - // Temp speed boost when player first joins an in progress game - if(this->initialResumeSpeedLoops == true) { - printf("Resume In Progress Game: %d\n",__LINE__); - - this->initialResumeSpeedLoops = false; - //updateLoops = 80; - } - - chronoGamePerformanceCounts.start(); - bool enableServerControlledAI = this->gameSettings.getEnableServerControlledAI(); - - if(role == nrClient && updateLoops == 1 && world.getFrameCount() >= (gameSettings.getNetworkFramePeriod() * 2) ) { - ClientInterface *clientInterface = dynamic_cast(networkManager.getClientInterface()); - if(clientInterface != NULL) { - uint64 lastNetworkFrameFromServer = clientInterface->getCachedLastPendingFrameCount(); - - ///////////////////////////////// - // TTTT new attempt to make things smoother: - /////////////// - - //////////////////////////////////////////// - //get stats of received/waiting for packages - //////////////////////////////////////////// - // calculate current receive Index slot: - int index = ((world.getFrameCount() - - (world.getFrameCount() - % gameSettings.getNetworkFramePeriod())) - / gameSettings.getNetworkFramePeriod()) - % GameConstants::networkSmoothInterval; - - // clean the next frame slot - receivedTooEarlyInFrames[(index+1)%GameConstants::networkSmoothInterval]=-1; - framesNeededToWaitForServerMessage[(index+1)%GameConstants::networkSmoothInterval]=-1; - - if(receivedTooEarlyInFrames[index]==-1){ - // we need to check if we already received something for next frame - if(lastNetworkFrameFromServer > 0 && lastNetworkFrameFromServer > (uint64)world.getFrameCount()) { - receivedTooEarlyInFrames[index]= lastNetworkFrameFromServer-world.getFrameCount(); - } - } - if(framesNeededToWaitForServerMessage[index]==-1){ - // calc time waiting for message in milliseconds to frames - int64 timeClientWaitedForLastMessage=clientInterface->getTimeClientWaitedForLastMessage(); - if(timeClientWaitedForLastMessage>0){ - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("world.getFrameCount():%d index %d Client waited:%d ms\n",world.getFrameCount(),index,(int)timeClientWaitedForLastMessage); - framesNeededToWaitForServerMessage[index]=timeClientWaitedForLastMessage*GameConstants::updateFps/1000; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("ClienttimeClientWaitedForLastMessage:%d ms which is %d frames \n",(int)timeClientWaitedForLastMessage,framesNeededToWaitForServerMessage[index]); - } - else { - framesNeededToWaitForServerMessage[index]=0; - } - } - - //////////////////////////////////////////// - //use the recorded stats of received/waiting for packages - //////////////////////////////////////////// - //lets see if the client is in front and had to wait for messages ... - - //lets see if all last recorded frames where received too early - int minimum=0; - int allowedMaxFallback=5; - int countOfMessagesReceivedTooEarly=0; - int countOfMessagesReceivedTooLate=0; - int sumOfTooLateFrames=0; - bool cleanupStats=false; - - for( int i=0;iallowedMaxFallback){ - countOfMessagesReceivedTooEarly++; - if ( minimum == 0 || minimum > receivedTooEarlyInFrames[i] ){ - minimum=receivedTooEarlyInFrames[i]; - } - } - if(framesNeededToWaitForServerMessage[i]>0){ - countOfMessagesReceivedTooLate++; - sumOfTooLateFrames+=framesNeededToWaitForServerMessage[i]; - } - } - - if( countOfMessagesReceivedTooEarly==GameConstants::networkSmoothInterval-1 ) // -1 because slot for next frame is already initialized - {// all packages where too early - // we catch up the minimum-catchupInterval of what we recorded - framesToCatchUpAsClient=minimum-allowedMaxFallback; - framesToSlowDownAsClient=0; - cleanupStats=true; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Worldframe %d : Client will speed up: %d frames\n",world.getFrameCount(),framesToCatchUpAsClient); - } - else if(countOfMessagesReceivedTooLate>3){ - framesToSlowDownAsClient=sumOfTooLateFrames/countOfMessagesReceivedTooLate; - framesToCatchUpAsClient=0; - cleanupStats=true; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Worldframe %d : Client will slow down: %d frames\n",world.getFrameCount(),framesToSlowDownAsClient); - } - - if(cleanupStats==true) { - // Once we decided to use the stats to do some correction, we reset/cleanup our recorded stats - for( int i=0;i 0) { - // we catch up a bit smoother with updateLoops = 2 - if(framesToCatchUpAsClient>0) - { - updateLoops = 2; - framesToCatchUpAsClient=framesToCatchUpAsClient-1; - } - if(framesToSlowDownAsClient>0) - {// slowdown still the hard way. - updateLoops = 0; - framesToSlowDownAsClient=framesToSlowDownAsClient-1; - } - } - - addPerformanceCount("CalculateNetworkUpdateLoops",chronoGamePerformanceCounts.getMillis()); - - 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()); - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d took msecs: %lld [before ReplaceDisconnectedNetworkPlayersWithAI]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - // Check to see if we are playing a network game and if any players - // have disconnected? - bool isNetworkGame = this->gameSettings.isNetworkGame(); - - chronoGamePerformanceCounts.start(); - - ReplaceDisconnectedNetworkPlayersWithAI(isNetworkGame, role); - - addPerformanceCount("ReplaceDisconnectedNetworkPlayersWithAI",chronoGamePerformanceCounts.getMillis()); - - setupPopupMenus(true); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d took msecs: %lld [after ReplaceDisconnectedNetworkPlayersWithAI]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - if(updateLoops > 0) { - // update the frame based timer in the stats with at least one step - world.getStats()->addFramesToCalculatePlaytime(); - - //update - Chrono chronoReplay; - int64 lastReplaySecond = -1; - int replayCommandsPlayed = 0; - int replayTotal = commander.getReplayCommandListForFrameCount(); - if(replayTotal > 0) { - chronoReplay.start(); - } - - do { - if(replayTotal > 0) { - replayCommandsPlayed = (replayTotal - commander.getReplayCommandListForFrameCount()); - } - for(int i = 0; i < updateLoops; ++i) { - //if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - //AiInterface - if(commander.hasReplayCommandListForFrame() == false) { - chronoGamePerformanceCounts.start(); - - processNetworkSynchChecksIfRequired(); - - addPerformanceCount("CalculateNetworkCRCSynchChecks",chronoGamePerformanceCounts.getMillis()); - - const bool newThreadManager = Config::getInstance().getBool("EnableNewThreadManager","false"); - if(newThreadManager == true) { - int currentFrameCount = world.getFrameCount(); - masterController.signalSlaves(¤tFrameCount); - //bool slavesCompleted = masterController.waitTillSlavesTrigger(20000); - masterController.waitTillSlavesTrigger(20000); - } - else { - // Signal the faction threads to do any pre-processing - chronoGamePerformanceCounts.start(); - - bool hasAIPlayer = false; - for(int j = 0; j < world.getFactionCount(); ++j) { - Faction *faction = world.getFaction(j); - - //printf("Faction Index = %d enableServerControlledAI = %d, isNetworkGame = %d, role = %d isCPU player = %d scriptManager.getPlayerModifiers(j)->getAiEnabled() = %d\n",j,enableServerControlledAI,isNetworkGame,role,faction->getCpuControl(enableServerControlledAI,isNetworkGame,role),scriptManager.getPlayerModifiers(j)->getAiEnabled()); - - if( faction->getCpuControl(enableServerControlledAI,isNetworkGame,role) == true && - scriptManager.getPlayerModifiers(j)->getAiEnabled() == true) { - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] [i = %d] faction = %d, factionCount = %d, took msecs: %lld [before AI updates]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,j,world.getFactionCount(),chrono.getMillis()); - aiInterfaces[j]->signalWorkerThread(world.getFrameCount()); - hasAIPlayer = true; - } - } - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - if(hasAIPlayer == true) { - //sleep(0); - - Chrono chronoAI; - chronoAI.start(); - - const int MAX_FACTION_THREAD_WAIT_MILLISECONDS = 20000; - for(;chronoAI.getMillis() < MAX_FACTION_THREAD_WAIT_MILLISECONDS;) { - bool workThreadsFinished = true; - for(int j = 0; j < world.getFactionCount(); ++j) { - Faction *faction = world.getFaction(j); - if(faction == NULL) { - throw megaglest_runtime_error("faction == NULL"); - } - if( faction->getCpuControl(enableServerControlledAI,isNetworkGame,role) == true && - scriptManager.getPlayerModifiers(j)->getAiEnabled() == true) { - if(aiInterfaces[j]->isWorkerThreadSignalCompleted(world.getFrameCount()) == false) { - workThreadsFinished = false; - break; - } - } - } - if(workThreadsFinished == false) { - //sleep(0); - } - else { - break; - } - } - } - - addPerformanceCount("ProcessAIWorkerThreads",chronoGamePerformanceCounts.getMillis()); - } - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - } - else { - // Simply show a progress message while replaying commands - if(lastReplaySecond < chronoReplay.getSeconds()) { - lastReplaySecond = chronoReplay.getSeconds(); - Renderer &renderer= Renderer::getInstance(); - renderer.clearBuffers(); - renderer.clearZBuffer(); - renderer.reset2d(); - - char szBuf[8096]=""; - snprintf(szBuf,8096,"Please wait, loading game with replay [%d / %d]...",replayCommandsPlayed,replayTotal); - string text = szBuf; - if(Renderer::renderText3DEnabled) { - Font3D *font = CoreData::getInstance().getMenuFontBig3D(); - const Metrics &metrics= Metrics::getInstance(); - int w= metrics.getVirtualW(); - int renderX = (w / 2) - (font->getMetrics()->getTextWidth(text) / 2); - int h= metrics.getVirtualH(); - int renderY = (h / 2) + (font->getMetrics()->getHeight(text) / 2); - - renderer.renderText3D( - text, font, - Vec3f(1.f, 1.f, 0.f), - renderX, renderY, false); - } - else { - Font2D *font = CoreData::getInstance().getMenuFontBig(); - const Metrics &metrics= Metrics::getInstance(); - int w= metrics.getVirtualW(); - int renderX = (w / 2); - int h= metrics.getVirtualH(); - int renderY = (h / 2); - - renderer.renderText( - text, font, - Vec3f(1.f, 1.f, 0.f), - renderX, renderY, true); - } - - renderer.swapBuffers(); - } - } - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d took msecs: %lld [AI updates]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - //World - chronoGamePerformanceCounts.start(); - - if(pendingQuitError == false) world.update(); - - addPerformanceCount("ProcessWorldUpdate",chronoGamePerformanceCounts.getMillis()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d took msecs: %lld [world update i = %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis(),i); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - if(currentCameraFollowUnit != NULL) { - Vec3f c=currentCameraFollowUnit->getCurrMidHeightVector(); - int rotation=currentCameraFollowUnit->getRotation(); - float angle=rotation+180; - - c.z=c.z+4*std::cos(degToRad(angle)); - c.x=c.x+4*std::sin(degToRad(angle)); - - c.y=c.y+currentCameraFollowUnit->getType()->getHeight()/2.f+2.0f; - - getGameCameraPtr()->setPos(c); - - rotation=(540-rotation)%360; - getGameCameraPtr()->rotateToVH(18.0f,rotation); - - if(currentCameraFollowUnit->isAlive()==false){ - currentCameraFollowUnit=NULL; - getGameCameraPtr()->setState(GameCamera::sGame); - } - } - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - // Commander - chronoGamePerformanceCounts.start(); - - if(pendingQuitError == false) { - commander.signalNetworkUpdate(this); - } - - addPerformanceCount("ProcessNetworkUpdate",chronoGamePerformanceCounts.getMillis()); - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d took msecs: %lld [commander updateNetwork i = %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis(),i); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - //Gui - chronoGamePerformanceCounts.start(); - - gui.update(); - - addPerformanceCount("ProcessGUIUpdate",chronoGamePerformanceCounts.getMillis()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d took msecs: %lld [gui updating i = %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis(),i); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } + if (getPaused() == false) { - //Particle systems - if(weatherParticleSystem != NULL) { - weatherParticleSystem->setPos(gameCamera.getPos()); - } + printf("[CMDR] Pausing game for lagging client(s), current world " + "frame [%d]\n", + world.getFrameCount()); + commander.tryPauseGame(false, false); + } + } else if (this->networkResumeGameForLaggedClientsRequested == true) { + this->networkResumeGameForLaggedClientsRequested = false; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d took msecs: %lld [weather particle updating i = %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis(),i); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); + if (getPaused() == true) { - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } + printf("[CMDR] Resuming game after Pause for lagging client(s), " + "current world frame [%d]\n", + world.getFrameCount()); + commander.tryResumeGame(false, false); + } + } + + ServerInterface *server = + NetworkManager::getInstance().getServerInterface(); + if (server->getPauseForInGameConnection() == true) { + + bool clientNeedsGameSetup = false; + for (int i = 0; i < world.getFactionCount(); ++i) { + Faction *faction = world.getFaction(i); + + MutexSafeWrapper safeMutex( + server->getSlotMutex(faction->getStartLocationIndex()), + CODE_AT_LINE); + ConnectionSlot *slot = + server->getSlot(faction->getStartLocationIndex(), false); + if (slot != NULL && slot->getPauseForInGameConnection() == true) { + clientNeedsGameSetup = true; + break; + } + } - Renderer &renderer= Renderer::getInstance(); + if (pausedForJoinGame == false || clientNeedsGameSetup == true) { + // printf("================= Switching player pausing game\n"); + + for (int i = 0; i < world.getFactionCount(); ++i) { + Faction *faction = world.getFaction(i); + + // printf("Switching player check %d from: %d connected: %d, + // startindex = %d, connected #2: + // %d\n",i,faction->getControlType(),server->isClientConnected(faction->getStartLocationIndex()),faction->getStartLocationIndex(),server->isClientConnected(i)); + // printf("Slot: %d faction name: + // %s\n",i,faction->getType()->getName().c_str()); + + if (faction->getControlType() != ctNetwork && + faction->getControlType() != ctHuman && + server->isClientConnected(faction->getStartLocationIndex()) == + true) { + + // printf("Switching player %d from: %d to + // %d\n",i,faction->getControlType(),ctNetwork); printf("Slot: %d + // faction name: %s GS faction: + // %s\n",i,faction->getType()->getName().c_str(),server->gameSettings.getFactionTypeName(i).c_str()); + + server->gameSettings.setFactionControl(i, ctNetwork); + + MutexSafeWrapper safeMutex( + server->getSlotMutex(faction->getStartLocationIndex()), + CODE_AT_LINE); + ConnectionSlot *slot = + server->getSlot(faction->getStartLocationIndex(), false); + server->gameSettings.setNetworkPlayerName(i, slot->getName()); + server->gameSettings.setNetworkPlayerUUID(i, slot->getUUID()); + server->gameSettings.setNetworkPlayerPlatform( + i, slot->getPlatform()); + safeMutex.ReleaseLock(); + server->gameSettings.setNetworkPlayerStatuses(i, npst_None); + + this->gameSettings.setFactionControl(i, ctNetwork); + this->gameSettings.setNetworkPlayerName( + i, server->gameSettings.getNetworkPlayerName(i)); + this->gameSettings.setNetworkPlayerUUID( + i, server->gameSettings.getNetworkPlayerUUID(i)); + this->gameSettings.setNetworkPlayerPlatform( + i, server->gameSettings.getNetworkPlayerPlatform(i)); + this->gameSettings.setNetworkPlayerStatuses(i, npst_None); + } + } + // printf("#1 Data synch: lmap %u ltile: %d ltech: + // %u\n",gameSettings.getMapCRC(),gameSettings.getTilesetCRC(),gameSettings.getTechCRC()); + // printf("#2 Data synch: lmap %u ltile: %d ltech: + // %u\n",server->gameSettings.getMapCRC(),server->gameSettings.getTilesetCRC(),server->gameSettings.getTechCRC()); + server->broadcastGameSetup(&server->gameSettings, true); + } - chronoGamePerformanceCounts.start(); + for (int i = 0; i < world.getFactionCount(); ++i) { + Faction *faction = world.getFaction(i); + MutexSafeWrapper safeMutex( + server->getSlotMutex(faction->getStartLocationIndex()), + CODE_AT_LINE); + ConnectionSlot *slot = + server->getSlot(faction->getStartLocationIndex(), false); + if (slot != NULL && slot->getPauseForInGameConnection() == true) { + slot->setPauseForInGameConnection(false); + } + } + } else if (server->getStartInGameConnectionLaunch() == true) { + // printf("^^^ getStartInGameConnectionLaunch triggered!\n"); + + // server->setStartInGameConnectionLaunch(false); + + // this->speed = 1; + + // Lang &lang= Lang::getInstance(); + bool pauseAndSaveGameForNewClient = false; + for (int i = 0; i < world.getFactionCount(); ++i) { + Faction *faction = world.getFaction(i); + + MutexSafeWrapper safeMutex( + server->getSlotMutex(faction->getStartLocationIndex()), + CODE_AT_LINE); + ConnectionSlot *slot = + server->getSlot(faction->getStartLocationIndex(), false); + + if (slot != NULL && slot->getStartInGameConnectionLaunch() == true) { + // slot->setStartInGameConnectionLaunch(false); + pauseAndSaveGameForNewClient = true; + } + if (slot != NULL && slot->getJoinGameInProgress() == true) { + // printf("$$$ signalling client to start game [deleting AI player] + // factionIndex: %d slot: %d startlocation: + // %d!\n",i,slot->getPlayerIndex(),faction->getStartLocationIndex()); + safeMutex.ReleaseLock(); + + this->gameSettings.setFactionControl(i, ctNetwork); + this->gameSettings.setNetworkPlayerName( + i, server->gameSettings.getNetworkPlayerName(i)); + this->gameSettings.setNetworkPlayerUUID( + i, server->gameSettings.getNetworkPlayerUUID(i)); + this->gameSettings.setNetworkPlayerPlatform( + i, server->gameSettings.getNetworkPlayerPlatform(i)); + + if (this->gameSettings.getNetworkPlayerStatuses(i) == + npst_Disconnected) { + this->gameSettings.setNetworkPlayerStatuses(i, npst_None); + } + + // printf("START Purging AI player for index: %d\n",i); + masterController.clearSlaves(true); + delete aiInterfaces[i]; + aiInterfaces[i] = NULL; + // printf("END Purging AI player for index: %d\n",i); + + Faction *faction = world.getFaction(i); + faction->setControlType(ctNetwork); + // pauseAndSaveGameForNewClient = true; + } else if ((slot == NULL || slot->isConnected() == false) && + this->gameSettings.getFactionControl(i) == ctNetwork && + aiInterfaces[i] == NULL) { + + safeMutex.ReleaseLock(); + faction->setFactionDisconnectHandled(false); + // this->gameSettings.setNetworkPlayerName(i,lang.getString("AI") + + // intToStr(i+1)); + // server->gameSettings.setNetworkPlayerName(i,lang.getString("AI") + // + intToStr(i+1)); + } else { + safeMutex.ReleaseLock(); + } + } - renderer.updateParticleManager(rsGame,avgRenderFps); + if (pauseAndSaveGameForNewClient == true && + pausedForJoinGame == false && pauseRequestSent == false) { + // printf("Pausing game for join in progress game...\n"); - addPerformanceCount("ProcessParticleManager",chronoGamePerformanceCounts.getMillis()); + commander.tryPauseGame(true, true); + pauseRequestSent = true; + return; + } + } + // else if(server->getPauseForInGameConnection() == true && paused == true + // && + if (pausedForJoinGame == true) { + if (pauseStateChanged == true) { + pauseStateChanged = false; + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d took msecs: %lld [particle manager updating i = %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis(),i); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); + if (server->getUnPauseForInGameConnection() == true) { + // printf("^^^ getUnPauseForInGameConnection triggered!\n"); + + for (int i = 0; i < world.getFactionCount(); ++i) { + Faction *faction = world.getFaction(i); + + MutexSafeWrapper safeMutex( + server->getSlotMutex(faction->getStartLocationIndex()), + CODE_AT_LINE); + ConnectionSlot *slot = + server->getSlot(faction->getStartLocationIndex(), false); + if (slot != NULL && slot->getUnPauseForInGameConnection() == true) { + slot->setUnPauseForInGameConnection(false); + faction->setFactionDisconnectHandled(false); + } + } + // printf("Resuming game for join in progress game resumeRequestSent: + // %d...\n",resumeRequestSent); + + if (pausedBeforeJoinGame == false && resumeRequestSent == false) { + commander.tryResumeGame(true, true); + resumeRequestSent = true; + } + } else if (server->getStartInGameConnectionLaunch() == true) { + bool saveNetworkGame = false; + + ServerInterface *server = + NetworkManager::getInstance().getServerInterface(); + for (int i = 0; i < world.getFactionCount(); ++i) { + Faction *faction = world.getFaction(i); + + MutexSafeWrapper safeMutex( + server->getSlotMutex(faction->getStartLocationIndex()), + CODE_AT_LINE); + ConnectionSlot *slot = + server->getSlot(faction->getStartLocationIndex(), false); + if (slot != NULL && slot->getJoinGameInProgress() == true && + slot->getStartInGameConnectionLaunch() == true && + slot->getSentSavedGameInfo() == false) { + slot->setStartInGameConnectionLaunch(false); + + saveNetworkGame = true; + break; + } + } + + if (saveNetworkGame == true) { + // printf("Saved network game to disk\n"); + + string file = this->saveGame( + GameConstants::saveNetworkGameFileServer, "temp/"); + + string saveGameFilePath = "temp/"; + string saveGameFileCompressed = + saveGameFilePath + + string(GameConstants::saveNetworkGameFileServerCompressed); + if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != + "") { + saveGameFilePath = getGameReadWritePath( + GameConstants::path_logs_CacheLookupKey) + + saveGameFilePath; + saveGameFileCompressed = + saveGameFilePath + + string(GameConstants::saveNetworkGameFileServerCompressed); + } else { + string userData = + Config::getInstance().getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + saveGameFilePath = userData + saveGameFilePath; + saveGameFileCompressed = + saveGameFilePath + + string(GameConstants::saveNetworkGameFileServerCompressed); + } + + bool compressed_result = + compressFileToZIPFile(file, saveGameFileCompressed); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Saved game [%s] compressed to [%s] returned: %d\n", + file.c_str(), saveGameFileCompressed.c_str(), + compressed_result); + + char szBuf[8096] = ""; + Lang &lang = Lang::getInstance(); + snprintf(szBuf, 8096, lang.getString("GameSaved", "", true).c_str(), + file.c_str()); + console.addLine(szBuf); + + for (int i = 0; i < world.getFactionCount(); ++i) { + Faction *faction = world.getFaction(i); + + MutexSafeWrapper safeMutex( + server->getSlotMutex(faction->getStartLocationIndex()), + CODE_AT_LINE); + ConnectionSlot *slot = + server->getSlot(faction->getStartLocationIndex(), false); + if (slot != NULL && slot->getJoinGameInProgress() == true && + slot->getSentSavedGameInfo() == false) { + + safeMutex.ReleaseLock(); + NetworkMessageReady networkMessageReady(0); + slot->sendMessage(&networkMessageReady); + + slot = server->getSlot(faction->getStartLocationIndex(), false); + if (slot != NULL) { + slot->setSentSavedGameInfo(true); + } + } + } + } + } + } + // else { + // handle setting changes from clients + Map *map = world.getMap(); + // printf("switchSetupRequests != NULL\n"); + + bool switchRequested = + switchSetupForSlots(server, 0, map->getMaxPlayers(), false); + switchRequested = switchRequested || + switchSetupForSlots(server, map->getMaxPlayers(), + GameConstants::maxPlayers, true); + + if (switchRequested == true) { + // printf("Send new game setup from switch: %d\n",switchRequested); + + // for(int i= 0; i < gameSettings.getFactionCount(); ++i) { + // printf("#1 Faction Index: %d control: %d startlocation: + // %d\n",i,gameSettings.getFactionControl(i),gameSettings.getStartLocationIndex(i)); + + // printf("#2 Faction Index: %d control: %d startlocation: + // %d\n",i,server->gameSettings.getFactionControl(i),server->gameSettings.getStartLocationIndex(i)); + //} + + server->broadcastGameSetup(&server->gameSettings, true); + } + //} + + // Make the server wait a bit for clients to start. + if (pausedForJoinGame == false && resumeRequestSent == true) { + resumeRequestSent = false; + // sleep(500); + } + } + // END - Handle joining in progress games - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } + // update auto test + if (Config::getInstance().getBool("AutoTest")) { + AutoTest::getInstance().updateGame(this); + return; + } - //good_fpu_control_registers(NULL,extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - } - while (commander.hasReplayCommandListForFrame() == true); - } - //else if(role == nrClient) { - else { - if(pendingQuitError == false) { - commander.signalNetworkUpdate(this); - } + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } - if(playingStaticVideo == true) { - if(videoPlayer->isPlaying() == false) { - playingStaticVideo = false; - tryPauseToggle(false); - } - } - } + if (world.getQueuedScenario() != "") { + string name = world.getQueuedScenario(); + bool keepFactions = world.getQueuedScenarioKeepFactions(); + world.setQueuedScenario("", false); + + // vector results; + const vector &dirList = + Config::getInstance().getPathListForType(ptScenarios); + string scenarioFile = Scenario::getScenarioPath(dirList, name); + + try { + gameStarted = false; + + // printf("\nname [%s] scenarioFile [%s] results.size() = " + // MG_SIZE_T_SPECIFIER + // "\n",name.c_str(),scenarioFile.c_str(),results.size()); + // printf("[%s:%s] Line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + bool isTutorial = Scenario::isGameTutorial(scenarioFile); + ScenarioInfo scenarioInfo; + Scenario::loadScenarioInfo(scenarioFile, &scenarioInfo, isTutorial); + + // printf("[%s:%s] Line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + GameSettings gameSettings; + Scenario::loadGameSettings(dirList, &scenarioInfo, &gameSettings, + scenarioFile); + + // Program *program = world->getGame()->getProgram(); + // program->setState(new Game(program, &gameSettings, false)); + + // world->end(); + + // world->getMapPtr()->end(); + // world.end(); + + if (keepFactions == false) { + world.end(); + + world.cleanup(); + world.clearTileset(); + + SoundRenderer::getInstance().stopAllSounds(); + + masterController.clearSlaves(true); + deleteValues(aiInterfaces.begin(), aiInterfaces.end()); + aiInterfaces.clear(); + gui.end(); // selection must be cleared before deleting units + world.end(); // must die before selection because of referencers + + BaseColorPickEntity::resetUniqueColors(); + // MUST DO THIS LAST!!!! Because objects above have pointers to things + // like unit particles and fade them out etc and this end method + // deletes the original object pointers. + Renderer &renderer = Renderer::getInstance(); + renderer.endGame(true); + + GameConstants::updateFps = original_updateFps; + GameConstants::cameraFps = original_cameraFps; + + this->setGameSettings(&gameSettings); + this->resetMembers(); + this->load(); + this->init(); + } else { + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + // printf("In [%s:%s] Line: %d currentAmbientSound = + // [%p]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,currentAmbientSound); + if (currentAmbientSound) { + soundRenderer.stopAmbient(currentAmbientSound); + } + // soundRenderer.stopAllSounds(); + soundRenderer.stopAllSounds(fadeMusicMilliseconds); + + world.endScenario(); + BaseColorPickEntity::resetUniqueColors(); + + Renderer &renderer = Renderer::getInstance(); + renderer.endScenario(); + world.clearTileset(); + this->setGameSettings(&gameSettings); + this->load(lgt_FactionPreview | lgt_TileSet | lgt_Map | lgt_Scenario); + try { + world.init(this, gameSettings.getDefaultUnits(), false); + } catch (const exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d]\nError [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, szBuf); + + if (errorMessageBox.getEnabled() == false) { + ErrorDisplayMessage(ex.what(), true); + } + } + + world.initUnitsForScenario(); + Map *map = world.getMap(); + gameCamera.init(map->getW(), map->getH()); + + // camera default height calculation + if (map->getCameraHeight() > 0 && + gameCamera.getCalculatedDefault() < map->getCameraHeight()) { + gameCamera.setCalculatedDefault(map->getCameraHeight()); + } else if (gameCamera.getCalculatedDefault() < + map->getMaxMapHeight() + 13.0f) { + gameCamera.setCalculatedDefault(map->getMaxMapHeight() + 13.0f); + } + + scriptManager.init(&world, &gameCamera, loadGameNode); + renderer.initGame(this, this->getGameCameraPtr()); + + // sounds + // soundRenderer.stopAllSounds(fadeMusicMilliseconds); + // soundRenderer.stopAllSounds(); + // soundRenderer= SoundRenderer::getInstance(); + + Tileset *tileset = world.getTileset(); + AmbientSounds *ambientSounds = tileset->getAmbientSounds(); + + // rain + if (tileset->getWeather() == wRainy && + ambientSounds->isEnabledRain()) { + // logger.add("Starting ambient stream", true); + currentAmbientSound = ambientSounds->getRain(); + // printf("In [%s:%s] Line: %d currentAmbientSound = + // [%p]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,currentAmbientSound); + soundRenderer.playAmbient(currentAmbientSound); + } + + // snow + if (tileset->getWeather() == wSnowy && + ambientSounds->isEnabledSnow()) { + // logger.add("Starting ambient stream", true); + currentAmbientSound = ambientSounds->getSnow(); + // printf("In [%s:%s] Line: %d currentAmbientSound = + // [%p]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,currentAmbientSound); + soundRenderer.playAmbient(currentAmbientSound); + } + + if (this->masterserverMode == false) { + StrSound *gameMusic = world.getThisFaction()->getType()->getMusic(); + soundRenderer.playMusic(gameMusic); + } + + gameStarted = true; + } + // this->init(); - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - chronoGamePerformanceCounts.start(); - - //call the chat manager - chatManager.updateNetwork(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d took msecs: %lld [chatManager.updateNetwork]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - updateNetworkMarkedCells(); - updateNetworkUnMarkedCells(); - updateNetworkHighligtedCells(); - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - //check for quiting status - if(NetworkManager::getInstance().getGameNetworkInterface() != NULL && - NetworkManager::getInstance().getGameNetworkInterface()->getQuit() && - mainMessageBox.getEnabled() == false && - errorMessageBox.getEnabled() == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - quitTriggeredIndicator = true; - return; - } - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - addPerformanceCount("ProcessMiscNetwork",chronoGamePerformanceCounts.getMillis()); - - // START - Handle joining in progress games - if(role == nrServer) { - - if(this->networkPauseGameForLaggedClientsRequested == true) { - this->networkPauseGameForLaggedClientsRequested = false; - - if(getPaused() == false) { - - printf("[CMDR] Pausing game for lagging client(s), current world frame [%d]\n",world.getFrameCount()); - commander.tryPauseGame(false,false); - } - } - else if(this->networkResumeGameForLaggedClientsRequested == true) { - this->networkResumeGameForLaggedClientsRequested = false; - - if(getPaused() == true) { - - printf("[CMDR] Resuming game after Pause for lagging client(s), current world frame [%d]\n",world.getFrameCount()); - commander.tryResumeGame(false,false); - } - } - - ServerInterface *server = NetworkManager::getInstance().getServerInterface(); - if(server->getPauseForInGameConnection() == true) { - - bool clientNeedsGameSetup = false; - for(int i = 0; i < world.getFactionCount(); ++i) { - Faction *faction = world.getFaction(i); - - MutexSafeWrapper safeMutex(server->getSlotMutex(faction->getStartLocationIndex()),CODE_AT_LINE); - ConnectionSlot *slot = server->getSlot(faction->getStartLocationIndex(),false); - if(slot != NULL && slot->getPauseForInGameConnection() == true) { - clientNeedsGameSetup = true; - break; - } - } - - if(pausedForJoinGame == false || clientNeedsGameSetup == true) { - //printf("================= Switching player pausing game\n"); - - for(int i = 0; i < world.getFactionCount(); ++i) { - Faction *faction = world.getFaction(i); - - //printf("Switching player check %d from: %d connected: %d, startindex = %d, connected #2: %d\n",i,faction->getControlType(),server->isClientConnected(faction->getStartLocationIndex()),faction->getStartLocationIndex(),server->isClientConnected(i)); - //printf("Slot: %d faction name: %s\n",i,faction->getType()->getName().c_str()); - - if( faction->getControlType() != ctNetwork && - faction->getControlType() != ctHuman && - server->isClientConnected(faction->getStartLocationIndex()) == true) { - - //printf("Switching player %d from: %d to %d\n",i,faction->getControlType(),ctNetwork); - //printf("Slot: %d faction name: %s GS faction: %s\n",i,faction->getType()->getName().c_str(),server->gameSettings.getFactionTypeName(i).c_str()); - - server->gameSettings.setFactionControl(i,ctNetwork); - - MutexSafeWrapper safeMutex(server->getSlotMutex(faction->getStartLocationIndex()),CODE_AT_LINE); - ConnectionSlot *slot = server->getSlot(faction->getStartLocationIndex(),false); - server->gameSettings.setNetworkPlayerName(i,slot->getName()); - server->gameSettings.setNetworkPlayerUUID(i,slot->getUUID()); - server->gameSettings.setNetworkPlayerPlatform(i,slot->getPlatform()); - safeMutex.ReleaseLock(); - server->gameSettings.setNetworkPlayerStatuses(i,npst_None); - - this->gameSettings.setFactionControl(i,ctNetwork); - this->gameSettings.setNetworkPlayerName(i,server->gameSettings.getNetworkPlayerName(i)); - this->gameSettings.setNetworkPlayerUUID(i,server->gameSettings.getNetworkPlayerUUID(i)); - this->gameSettings.setNetworkPlayerPlatform(i,server->gameSettings.getNetworkPlayerPlatform(i)); - this->gameSettings.setNetworkPlayerStatuses(i,npst_None); - } - } - //printf("#1 Data synch: lmap %u ltile: %d ltech: %u\n",gameSettings.getMapCRC(),gameSettings.getTilesetCRC(),gameSettings.getTechCRC()); - //printf("#2 Data synch: lmap %u ltile: %d ltech: %u\n",server->gameSettings.getMapCRC(),server->gameSettings.getTilesetCRC(),server->gameSettings.getTechCRC()); - server->broadcastGameSetup(&server->gameSettings,true); - } - - for(int i = 0; i < world.getFactionCount(); ++i) { - Faction *faction = world.getFaction(i); - MutexSafeWrapper safeMutex(server->getSlotMutex(faction->getStartLocationIndex()),CODE_AT_LINE); - ConnectionSlot *slot = server->getSlot(faction->getStartLocationIndex(),false); - if(slot != NULL && slot->getPauseForInGameConnection() == true) { - slot->setPauseForInGameConnection(false); - } - } - } - else if(server->getStartInGameConnectionLaunch() == true) { - //printf("^^^ getStartInGameConnectionLaunch triggered!\n"); - - //server->setStartInGameConnectionLaunch(false); - - //this->speed = 1; - - //Lang &lang= Lang::getInstance(); - bool pauseAndSaveGameForNewClient = false; - for(int i = 0; i < world.getFactionCount(); ++i) { - Faction *faction = world.getFaction(i); - - MutexSafeWrapper safeMutex(server->getSlotMutex(faction->getStartLocationIndex()),CODE_AT_LINE); - ConnectionSlot *slot = server->getSlot(faction->getStartLocationIndex(),false); - - if(slot != NULL && slot->getStartInGameConnectionLaunch() == true) { - //slot->setStartInGameConnectionLaunch(false); - pauseAndSaveGameForNewClient = true; - } - if(slot != NULL && slot->getJoinGameInProgress() == true) { - //printf("$$$ signalling client to start game [deleting AI player] factionIndex: %d slot: %d startlocation: %d!\n",i,slot->getPlayerIndex(),faction->getStartLocationIndex()); - safeMutex.ReleaseLock(); - - this->gameSettings.setFactionControl(i,ctNetwork); - this->gameSettings.setNetworkPlayerName(i,server->gameSettings.getNetworkPlayerName(i)); - this->gameSettings.setNetworkPlayerUUID(i,server->gameSettings.getNetworkPlayerUUID(i)); - this->gameSettings.setNetworkPlayerPlatform(i,server->gameSettings.getNetworkPlayerPlatform(i)); - - if(this->gameSettings.getNetworkPlayerStatuses(i) == npst_Disconnected) { - this->gameSettings.setNetworkPlayerStatuses(i,npst_None); - } - - //printf("START Purging AI player for index: %d\n",i); - masterController.clearSlaves(true); - delete aiInterfaces[i]; - aiInterfaces[i] = NULL; - //printf("END Purging AI player for index: %d\n",i); - - Faction *faction = world.getFaction(i); - faction->setControlType(ctNetwork); - //pauseAndSaveGameForNewClient = true; - } - else if((slot == NULL || slot->isConnected() == false) && - this->gameSettings.getFactionControl(i) == ctNetwork && - aiInterfaces[i] == NULL) { - - safeMutex.ReleaseLock(); - faction->setFactionDisconnectHandled(false); - //this->gameSettings.setNetworkPlayerName(i,lang.getString("AI") + intToStr(i+1)); - //server->gameSettings.setNetworkPlayerName(i,lang.getString("AI") + intToStr(i+1)); - } - else { - safeMutex.ReleaseLock(); - } - } - - if(pauseAndSaveGameForNewClient == true && pausedForJoinGame == false && - pauseRequestSent == false) { - //printf("Pausing game for join in progress game...\n"); - - commander.tryPauseGame(true,true); - pauseRequestSent = true; - return; - } - } - //else if(server->getPauseForInGameConnection() == true && paused == true && - if(pausedForJoinGame == true) { - if(pauseStateChanged == true) { - pauseStateChanged = false; - } - - if(server->getUnPauseForInGameConnection() == true) { - //printf("^^^ getUnPauseForInGameConnection triggered!\n"); - - for(int i = 0; i < world.getFactionCount(); ++i) { - Faction *faction = world.getFaction(i); - - MutexSafeWrapper safeMutex(server->getSlotMutex(faction->getStartLocationIndex()),CODE_AT_LINE); - ConnectionSlot *slot = server->getSlot(faction->getStartLocationIndex(),false); - if(slot != NULL && slot->getUnPauseForInGameConnection() == true) { - slot->setUnPauseForInGameConnection(false); - faction->setFactionDisconnectHandled(false); - } - } - //printf("Resuming game for join in progress game resumeRequestSent: %d...\n",resumeRequestSent); - - if(pausedBeforeJoinGame == false && resumeRequestSent == false) { - commander.tryResumeGame(true,true); - resumeRequestSent = true; - } - } - else if(server->getStartInGameConnectionLaunch() == true) { - bool saveNetworkGame = false; - - ServerInterface *server = NetworkManager::getInstance().getServerInterface(); - for(int i = 0; i < world.getFactionCount(); ++i) { - Faction *faction = world.getFaction(i); - - MutexSafeWrapper safeMutex(server->getSlotMutex(faction->getStartLocationIndex()),CODE_AT_LINE); - ConnectionSlot *slot = server->getSlot(faction->getStartLocationIndex(),false); - if(slot != NULL && slot->getJoinGameInProgress() == true && - slot->getStartInGameConnectionLaunch() == true && - slot->getSentSavedGameInfo() == false) { - slot->setStartInGameConnectionLaunch(false); - - saveNetworkGame = true; - break; - } - } - - if(saveNetworkGame == true) { - //printf("Saved network game to disk\n"); - - string file = this->saveGame(GameConstants::saveNetworkGameFileServer,"temp/"); - - string saveGameFilePath = "temp/"; - string saveGameFileCompressed = saveGameFilePath + string(GameConstants::saveNetworkGameFileServerCompressed); - if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - saveGameFilePath = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + saveGameFilePath; - saveGameFileCompressed = saveGameFilePath + string(GameConstants::saveNetworkGameFileServerCompressed); - } - else { - string userData = Config::getInstance().getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - saveGameFilePath = userData + saveGameFilePath; - saveGameFileCompressed = saveGameFilePath + string(GameConstants::saveNetworkGameFileServerCompressed); - } - - bool compressed_result = compressFileToZIPFile( - file, saveGameFileCompressed); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Saved game [%s] compressed to [%s] returned: %d\n",file.c_str(),saveGameFileCompressed.c_str(), compressed_result); - - char szBuf[8096]=""; - Lang &lang= Lang::getInstance(); - snprintf(szBuf,8096,lang.getString("GameSaved","",true).c_str(),file.c_str()); - console.addLine(szBuf); - - for(int i = 0; i < world.getFactionCount(); ++i) { - Faction *faction = world.getFaction(i); - - MutexSafeWrapper safeMutex(server->getSlotMutex(faction->getStartLocationIndex()),CODE_AT_LINE); - ConnectionSlot *slot = server->getSlot(faction->getStartLocationIndex(),false); - if(slot != NULL && slot->getJoinGameInProgress() == true && - slot->getSentSavedGameInfo() == false) { - - safeMutex.ReleaseLock(); - NetworkMessageReady networkMessageReady(0); - slot->sendMessage(&networkMessageReady); - - slot = server->getSlot(faction->getStartLocationIndex(),false); - if(slot != NULL) { - slot->setSentSavedGameInfo(true); - } - } - } - } - } - } - //else { - // handle setting changes from clients - Map *map= world.getMap(); - //printf("switchSetupRequests != NULL\n"); - - bool switchRequested = switchSetupForSlots(server, 0, map->getMaxPlayers(), false); - switchRequested = switchRequested || switchSetupForSlots(server, map->getMaxPlayers(), GameConstants::maxPlayers, true); - - if(switchRequested == true) { - //printf("Send new game setup from switch: %d\n",switchRequested); - - //for(int i= 0; i < gameSettings.getFactionCount(); ++i) { - //printf("#1 Faction Index: %d control: %d startlocation: %d\n",i,gameSettings.getFactionControl(i),gameSettings.getStartLocationIndex(i)); - - //printf("#2 Faction Index: %d control: %d startlocation: %d\n",i,server->gameSettings.getFactionControl(i),server->gameSettings.getStartLocationIndex(i)); - //} - - server->broadcastGameSetup(&server->gameSettings,true); - } - //} - - // Make the server wait a bit for clients to start. - if(pausedForJoinGame == false && resumeRequestSent == true) { - resumeRequestSent = false; - //sleep(500); - } - } - // END - Handle joining in progress games - - //update auto test - if(Config::getInstance().getBool("AutoTest")){ - AutoTest::getInstance().updateGame(this); - return; - } - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - if(world.getQueuedScenario() != "") { - string name = world.getQueuedScenario(); - bool keepFactions = world.getQueuedScenarioKeepFactions(); - world.setQueuedScenario("",false); - - //vector results; - const vector &dirList = Config::getInstance().getPathListForType(ptScenarios); - string scenarioFile = Scenario::getScenarioPath(dirList, name); - - - try { - gameStarted = false; - - //printf("\nname [%s] scenarioFile [%s] results.size() = " MG_SIZE_T_SPECIFIER "\n",name.c_str(),scenarioFile.c_str(),results.size()); - //printf("[%s:%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - bool isTutorial = Scenario::isGameTutorial(scenarioFile); - ScenarioInfo scenarioInfo; - Scenario::loadScenarioInfo(scenarioFile, &scenarioInfo, isTutorial); - - //printf("[%s:%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - GameSettings gameSettings; - Scenario::loadGameSettings(dirList,&scenarioInfo, &gameSettings, scenarioFile); - - //Program *program = world->getGame()->getProgram(); - //program->setState(new Game(program, &gameSettings, false)); - - //world->end(); - - //world->getMapPtr()->end(); - //world.end(); - - if(keepFactions == false) { - world.end(); - - world.cleanup(); - world.clearTileset(); - - SoundRenderer::getInstance().stopAllSounds(); - - masterController.clearSlaves(true); - deleteValues(aiInterfaces.begin(), aiInterfaces.end()); - aiInterfaces.clear(); - gui.end(); //selection must be cleared before deleting units - world.end(); //must die before selection because of referencers - - BaseColorPickEntity::resetUniqueColors(); - // MUST DO THIS LAST!!!! Because objects above have pointers to things like - // unit particles and fade them out etc and this end method deletes the original - // object pointers. - Renderer &renderer= Renderer::getInstance(); - renderer.endGame(true); - - GameConstants::updateFps = original_updateFps; - GameConstants::cameraFps = original_cameraFps; - - this->setGameSettings(&gameSettings); - this->resetMembers(); - this->load(); - this->init(); - } - else { - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - //printf("In [%s:%s] Line: %d currentAmbientSound = [%p]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,currentAmbientSound); - if(currentAmbientSound) { - soundRenderer.stopAmbient(currentAmbientSound); - } - //soundRenderer.stopAllSounds(); - soundRenderer.stopAllSounds(fadeMusicMilliseconds); - - world.endScenario(); - BaseColorPickEntity::resetUniqueColors(); - - Renderer &renderer= Renderer::getInstance(); - renderer.endScenario(); - world.clearTileset(); - this->setGameSettings(&gameSettings); - this->load(lgt_FactionPreview | lgt_TileSet | lgt_Map | lgt_Scenario); - try { - world.init(this, gameSettings.getDefaultUnits(),false); - } - catch(const exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d]\nError [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,szBuf); - - if(errorMessageBox.getEnabled() == false) { - ErrorDisplayMessage(ex.what(),true); - } - } - - world.initUnitsForScenario(); - Map *map= world.getMap(); - gameCamera.init(map->getW(), map->getH()); - - // camera default height calculation - if(map->getCameraHeight()>0 && gameCamera.getCalculatedDefault()getCameraHeight()){ - gameCamera.setCalculatedDefault(map->getCameraHeight()); - } - else if(gameCamera.getCalculatedDefault()getMaxMapHeight()+13.0f){ - gameCamera.setCalculatedDefault(map->getMaxMapHeight()+13.0f); - } - - scriptManager.init(&world, &gameCamera,loadGameNode); - renderer.initGame(this,this->getGameCameraPtr()); - - //sounds - //soundRenderer.stopAllSounds(fadeMusicMilliseconds); - //soundRenderer.stopAllSounds(); - //soundRenderer= SoundRenderer::getInstance(); - - Tileset *tileset= world.getTileset(); - AmbientSounds *ambientSounds= tileset->getAmbientSounds(); - - //rain - if(tileset->getWeather() == wRainy && ambientSounds->isEnabledRain()) { - //logger.add("Starting ambient stream", true); - currentAmbientSound = ambientSounds->getRain(); - //printf("In [%s:%s] Line: %d currentAmbientSound = [%p]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,currentAmbientSound); - soundRenderer.playAmbient(currentAmbientSound); - } - - //snow - if(tileset->getWeather() == wSnowy && ambientSounds->isEnabledSnow()) { - //logger.add("Starting ambient stream", true); - currentAmbientSound = ambientSounds->getSnow(); - //printf("In [%s:%s] Line: %d currentAmbientSound = [%p]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,currentAmbientSound); - soundRenderer.playAmbient(currentAmbientSound); - } - - if(this->masterserverMode == false) { - StrSound *gameMusic= world.getThisFaction()->getType()->getMusic(); - soundRenderer.playMusic(gameMusic); - } - - gameStarted = true; - } - //this->init(); - - //printf("[%s:%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //Checksum checksum; - //world->loadScenario(scenarioFile, &checksum, true); - } + // printf("[%s:%s] Line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // Checksum checksum; + // world->loadScenario(scenarioFile, &checksum, true); + } #if defined(WIN32) - catch(const exception) { + catch (const exception) { #else - catch(const exception &ex) { + catch (const exception &ex) { #endif - gameStarted = true; - totalRenderFps++; - - throw; - } - } - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - if(showPerfStats && chronoPerf.getMillis() >= 50) { - for(unsigned int x = 0; x < (unsigned int)perfList.size(); ++x) { - printf("%s",perfList[x].c_str()); - } - } - } - catch(const exception &ex) { - quitPendingIndicator = true; - - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,szBuf); - - //printf("#100 quitPendingIndicator = %d, errorMessageBox.getEnabled() = %d\n",quitPendingIndicator,errorMessageBox.getEnabled()); - - NetworkManager &networkManager= NetworkManager::getInstance(); - if(networkManager.getGameNetworkInterface() != NULL) { - GameNetworkInterface *networkInterface = NetworkManager::getInstance().getGameNetworkInterface(); - networkInterface->sendTextMessage(szBuf,-1,true,""); - sleep(10); - networkManager.getGameNetworkInterface()->quitGame(true); - } - if(errorMessageBox.getEnabled() == false) { - ErrorDisplayMessage(ex.what(),true); - } - } + gameStarted = true; + totalRenderFps++; + + throw; + } + } + + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + if (showPerfStats && chronoPerf.getMillis() >= 50) { + for (unsigned int x = 0; x < (unsigned int)perfList.size(); ++x) { + printf("%s", perfList[x].c_str()); + } + } + } catch (const exception &ex) { + quitPendingIndicator = true; + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, szBuf); + + // printf("#100 quitPendingIndicator = %d, errorMessageBox.getEnabled() = + // %d\n",quitPendingIndicator,errorMessageBox.getEnabled()); + + NetworkManager &networkManager = NetworkManager::getInstance(); + if (networkManager.getGameNetworkInterface() != NULL) { + GameNetworkInterface *networkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + networkInterface->sendTextMessage(szBuf, -1, true, ""); + sleep(10); + networkManager.getGameNetworkInterface()->quitGame(true); + } + if (errorMessageBox.getEnabled() == false) { + ErrorDisplayMessage(ex.what(), true); + } + } } -void Game::addPerformanceCount(string key,int64 value) { - gamePerformanceCounts[key] = value + gamePerformanceCounts[key] / 2; +void Game::addPerformanceCount(string key, int64 value) { + gamePerformanceCounts[key] = value + gamePerformanceCounts[key] / 2; } string Game::getGamePerformanceCounts(bool displayWarnings) const { - if(gamePerformanceCounts.empty() == true) { - return ""; - } - - bool displayWarningHeader = true; - bool WARN_TO_CONSOLE = Config::getInstance().getBool("PerformanceWarningEnabled","false"); - int WARNING_MILLIS = Config::getInstance().getInt("PerformanceWarningMillis","7"); - int WARNING_RENDER_MILLIS = Config::getInstance().getInt("PerformanceWarningRenderMillis","40"); - - string result = ""; - for(std::map::const_iterator iterMap = gamePerformanceCounts.begin(); - iterMap != gamePerformanceCounts.end(); ++iterMap) { - if(iterMap->first == ProgramState::MAIN_PROGRAM_RENDER_KEY) { - if(iterMap->second < WARNING_RENDER_MILLIS) { - continue; - } - //else { - // printf("iterMap->second: " MG_I64_SPECIFIER " WARNING_RENDER_MILLIS = %d\n",iterMap->second,WARNING_RENDER_MILLIS); - //} - } - else if(iterMap->second < WARNING_MILLIS) { - continue; - } - - if(result != "") { - result += "\n"; - } - string perfStat = iterMap->first + " = avg millis: " + intToStr(iterMap->second); - - if(displayWarnings == true && WARN_TO_CONSOLE == true) { - if(displayWarningHeader == true) { - displayWarningHeader = false; - printf("=====================================\nPERFORMANCE WARNINGS for World Frame: %d\n",world.getFrameCount()); - } - - printf("*PERFORMANCE WARNING* %s\n",perfStat.c_str()); - } - - result += perfStat; - } - - return result; + if (gamePerformanceCounts.empty() == true) { + return ""; + } + + bool displayWarningHeader = true; + bool WARN_TO_CONSOLE = + Config::getInstance().getBool("PerformanceWarningEnabled", "false"); + int WARNING_MILLIS = + Config::getInstance().getInt("PerformanceWarningMillis", "7"); + int WARNING_RENDER_MILLIS = + Config::getInstance().getInt("PerformanceWarningRenderMillis", "40"); + + string result = ""; + for (std::map::const_iterator iterMap = + gamePerformanceCounts.begin(); + iterMap != gamePerformanceCounts.end(); ++iterMap) { + if (iterMap->first == ProgramState::MAIN_PROGRAM_RENDER_KEY) { + if (iterMap->second < WARNING_RENDER_MILLIS) { + continue; + } + // else { + // printf("iterMap->second: " MG_I64_SPECIFIER " + // WARNING_RENDER_MILLIS = %d\n",iterMap->second,WARNING_RENDER_MILLIS); + // } + } else if (iterMap->second < WARNING_MILLIS) { + continue; + } + + if (result != "") { + result += "\n"; + } + string perfStat = + iterMap->first + " = avg millis: " + intToStr(iterMap->second); + + if (displayWarnings == true && WARN_TO_CONSOLE == true) { + if (displayWarningHeader == true) { + displayWarningHeader = false; + printf("=====================================\nPERFORMANCE WARNINGS " + "for World Frame: %d\n", + world.getFrameCount()); + } + + printf("*PERFORMANCE WARNING* %s\n", perfStat.c_str()); + } + + result += perfStat; + } + + return result; } -bool Game::switchSetupForSlots(ServerInterface *& serverInterface, - int startIndex, int endIndex, bool onlyNetworkUnassigned) { - bool switchRequested = false; - if(serverInterface == NULL) { - return switchRequested; - } - - MutexSafeWrapper safeMutex(serverInterface->getSwitchSetupRequestsMutex(),CODE_AT_LINE); - SwitchSetupRequest ** switchSetupRequests = serverInterface->getSwitchSetupRequests(); - if(switchSetupRequests == NULL) { - return switchRequested; - } - - Map *map= world.getMap(); - for(int i= startIndex; i < endIndex; ++i) { - if(switchSetupRequests[i] != NULL) { - //printf("Faction Index: %d Switch slot = %d to = %d current control = %d\n",i,switchSetupRequests[i]->getCurrentSlotIndex(),switchSetupRequests[i]->getToSlotIndex(),gameSettings.getFactionControl(i)); - - 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()); - - if(onlyNetworkUnassigned == true && gameSettings.getFactionControl(i) != ctNetworkUnassigned) { - if(i < map->getMaxPlayers() || (i >= map->getMaxPlayers() && gameSettings.getFactionControl(i) != ctNetwork)) { - continue; - } - } - - if(gameSettings.getFactionControl(i) == ctNetwork || - gameSettings.getFactionControl(i) == ctNetworkUnassigned || - //(gameSettings.getFactionControl(i) != ctClosed && gameSettings.getFactionControl(i) != ctHuman)) { - (gameSettings.getFactionControl(i) != ctHuman)) { - 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()); - - if(switchSetupRequests[i]->getToSlotIndex() != -1) { - int newSlotIdx = switchSetupRequests[i]->getToSlotIndex(); - - //printf("switchSlot request from %d to %d\n",switchSetupRequests[i]->getCurrentSlotIndex(),switchSetupRequests[i]->getToSlotIndex()); - - int switchSlotIdx = switchSetupRequests[i]->getCurrentSlotIndex(); - if(serverInterface->switchSlot(switchSlotIdx,newSlotIdx)) { - //printf("switchSlot returned true\n"); - switchRequested = true; - - int oldFactionIndex = gameSettings.getFactionIndexForStartLocation(switchSlotIdx); - int newFactionIndex = gameSettings.getFactionIndexForStartLocation(newSlotIdx); - - //printf("Switching faction for index %d [%d] to %d\n",newSlotIdx,switchSlotIdx,gameSettings.getFactionControl(newFactionIndex)); - - gameSettings.setNetworkPlayerName(oldFactionIndex, ""); - serverInterface->gameSettings.setNetworkPlayerName(oldFactionIndex, ""); - gameSettings.setNetworkPlayerUUID(oldFactionIndex, ""); - serverInterface->gameSettings.setNetworkPlayerUUID(oldFactionIndex, ""); - - gameSettings.setNetworkPlayerPlatform(oldFactionIndex, ""); - serverInterface->gameSettings.setNetworkPlayerPlatform(oldFactionIndex, ""); - - gameSettings.setFactionControl(newFactionIndex,ctNetwork); - serverInterface->gameSettings.setFactionControl(newFactionIndex,ctNetwork); - - //printf("#1a Faction Index: %d control: %d startlocation: %d\n",newFactionIndex,gameSettings.getFactionControl(newFactionIndex),gameSettings.getStartLocationIndex(newFactionIndex)); - //printf("#2a Faction Index: %d control: %d startlocation: %d\n",newFactionIndex,serverInterface->gameSettings.getFactionControl(newFactionIndex),serverInterface->gameSettings.getStartLocationIndex(newFactionIndex)); - - try { - //if(switchSetupRequests[i]->getSelectedFactionName() != "") { - // listBoxFactions[newFactionIdx].setSelectedItem(switchSetupRequests[i]->getSelectedFactionName()); - //} - //if(switchSetupRequests[i]->getToTeam() != -1) { - // listBoxTeams[newFactionIdx].setSelectedItemIndex(switchSetupRequests[i]->getToTeam()); - //} - if(switchSetupRequests[i]->getNetworkPlayerName() != "") { - //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()); - gameSettings.setNetworkPlayerName(newFactionIndex,switchSetupRequests[i]->getNetworkPlayerName()); - serverInterface->gameSettings.setNetworkPlayerName(newFactionIndex,switchSetupRequests[i]->getNetworkPlayerName()); - } - -// if(gameSettings.getFactionControl(switchFactionIdx) == ctNetworkUnassigned) { -// serverInterface->removeSlot(switchFactionIdx); -// //listBoxControls[switchFactionIdx].setSelectedItemIndex(ctClosed); -// gameSettings.getFactionControl(switchFactionIdx) -// -// labelPlayers[switchFactionIdx].setVisible(switchFactionIdx+1 <= mapInfo.players); -// labelPlayerNames[switchFactionIdx].setVisible(switchFactionIdx+1 <= mapInfo.players); -// listBoxControls[switchFactionIdx].setVisible(switchFactionIdx+1 <= mapInfo.players); -// listBoxFactions[switchFactionIdx].setVisible(switchFactionIdx+1 <= mapInfo.players); -// listBoxTeams[switchFactionIdx].setVisible(switchFactionIdx+1 <= mapInfo.players); -// labelNetStatus[switchSlotIdx].setVisible(switchSlotIdx+1 <= mapInfo.players); -// } - } - catch(const runtime_error &e) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what()); - 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()); - } - } - //printf("AFTER switchSlot returned\n"); - } - else { - try { - //if(switchSetupRequests[i]->getSelectedFactionName() != "") { - // listBoxFactions[i].setSelectedItem(switchSetupRequests[i]->getSelectedFactionName()); - //} - //if(switchSetupRequests[i]->getToTeam() != -1) { - // listBoxTeams[i].setSelectedItemIndex(switchSetupRequests[i]->getToTeam()); - //} - - if((switchSetupRequests[i]->getSwitchFlags() & ssrft_NetworkPlayerName) == ssrft_NetworkPlayerName) { - //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()); - - if(switchSetupRequests[i]->getNetworkPlayerName() != GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME) { - //labelPlayerNames[i].setText(switchSetupRequests[i]->getNetworkPlayerName()); - gameSettings.setNetworkPlayerName(i,switchSetupRequests[i]->getNetworkPlayerName()); - serverInterface->gameSettings.setNetworkPlayerName(i,switchSetupRequests[i]->getNetworkPlayerName()); - switchRequested = true; - } - else { - //labelPlayerNames[i].setText(""); - gameSettings.setNetworkPlayerName(i,""); - serverInterface->gameSettings.setNetworkPlayerName(i,""); - switchRequested = true; - } - //SetActivePlayerNameEditor(); - //switchSetupRequests[i]->clearSwitchFlag(ssrft_NetworkPlayerName); - } - } - catch(const runtime_error &e) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what()); - 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()); - } - } - } - - delete switchSetupRequests[i]; - switchSetupRequests[i]=NULL; - } - } - - return switchRequested; +bool Game::switchSetupForSlots(ServerInterface *&serverInterface, + int startIndex, int endIndex, + bool onlyNetworkUnassigned) { + bool switchRequested = false; + if (serverInterface == NULL) { + return switchRequested; + } + + MutexSafeWrapper safeMutex(serverInterface->getSwitchSetupRequestsMutex(), + CODE_AT_LINE); + SwitchSetupRequest **switchSetupRequests = + serverInterface->getSwitchSetupRequests(); + if (switchSetupRequests == NULL) { + return switchRequested; + } + + Map *map = world.getMap(); + for (int i = startIndex; i < endIndex; ++i) { + if (switchSetupRequests[i] != NULL) { + // printf("Faction Index: %d Switch slot = %d to = %d current control = + // %d\n",i,switchSetupRequests[i]->getCurrentSlotIndex(),switchSetupRequests[i]->getToSlotIndex(),gameSettings.getFactionControl(i)); + + 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()); + + if (onlyNetworkUnassigned == true && + gameSettings.getFactionControl(i) != ctNetworkUnassigned) { + if (i < map->getMaxPlayers() || + (i >= map->getMaxPlayers() && + gameSettings.getFactionControl(i) != ctNetwork)) { + continue; + } + } + + if (gameSettings.getFactionControl(i) == ctNetwork || + gameSettings.getFactionControl(i) == ctNetworkUnassigned || + //(gameSettings.getFactionControl(i) != ctClosed && + // gameSettings.getFactionControl(i) != ctHuman)) { + (gameSettings.getFactionControl(i) != ctHuman)) { + 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()); + + if (switchSetupRequests[i]->getToSlotIndex() != -1) { + int newSlotIdx = switchSetupRequests[i]->getToSlotIndex(); + + // printf("switchSlot request from %d to + // %d\n",switchSetupRequests[i]->getCurrentSlotIndex(),switchSetupRequests[i]->getToSlotIndex()); + + int switchSlotIdx = switchSetupRequests[i]->getCurrentSlotIndex(); + if (serverInterface->switchSlot(switchSlotIdx, newSlotIdx)) { + // printf("switchSlot returned true\n"); + switchRequested = true; + + int oldFactionIndex = + gameSettings.getFactionIndexForStartLocation(switchSlotIdx); + int newFactionIndex = + gameSettings.getFactionIndexForStartLocation(newSlotIdx); + + // printf("Switching faction for index %d [%d] to + // %d\n",newSlotIdx,switchSlotIdx,gameSettings.getFactionControl(newFactionIndex)); + + gameSettings.setNetworkPlayerName(oldFactionIndex, ""); + serverInterface->gameSettings.setNetworkPlayerName(oldFactionIndex, + ""); + gameSettings.setNetworkPlayerUUID(oldFactionIndex, ""); + serverInterface->gameSettings.setNetworkPlayerUUID(oldFactionIndex, + ""); + + gameSettings.setNetworkPlayerPlatform(oldFactionIndex, ""); + serverInterface->gameSettings.setNetworkPlayerPlatform( + oldFactionIndex, ""); + + gameSettings.setFactionControl(newFactionIndex, ctNetwork); + serverInterface->gameSettings.setFactionControl(newFactionIndex, + ctNetwork); + + // printf("#1a Faction Index: %d control: %d startlocation: + // %d\n",newFactionIndex,gameSettings.getFactionControl(newFactionIndex),gameSettings.getStartLocationIndex(newFactionIndex)); + // printf("#2a Faction Index: %d control: %d startlocation: + // %d\n",newFactionIndex,serverInterface->gameSettings.getFactionControl(newFactionIndex),serverInterface->gameSettings.getStartLocationIndex(newFactionIndex)); + + try { + // if(switchSetupRequests[i]->getSelectedFactionName() != "") { + // listBoxFactions[newFactionIdx].setSelectedItem(switchSetupRequests[i]->getSelectedFactionName()); + // } + // if(switchSetupRequests[i]->getToTeam() != -1) { + // listBoxTeams[newFactionIdx].setSelectedItemIndex(switchSetupRequests[i]->getToTeam()); + // } + if (switchSetupRequests[i]->getNetworkPlayerName() != "") { + // 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()); + gameSettings.setNetworkPlayerName( + newFactionIndex, + switchSetupRequests[i]->getNetworkPlayerName()); + serverInterface->gameSettings.setNetworkPlayerName( + newFactionIndex, + switchSetupRequests[i]->getNetworkPlayerName()); + } + + // if(gameSettings.getFactionControl(switchFactionIdx) + //== ctNetworkUnassigned) { + // serverInterface->removeSlot(switchFactionIdx); + // //listBoxControls[switchFactionIdx].setSelectedItemIndex(ctClosed); + // gameSettings.getFactionControl(switchFactionIdx) + // + // labelPlayers[switchFactionIdx].setVisible(switchFactionIdx+1 + //<= mapInfo.players); + // labelPlayerNames[switchFactionIdx].setVisible(switchFactionIdx+1 + //<= mapInfo.players); + // listBoxControls[switchFactionIdx].setVisible(switchFactionIdx+1 + //<= mapInfo.players); + // listBoxFactions[switchFactionIdx].setVisible(switchFactionIdx+1 + //<= mapInfo.players); + // listBoxTeams[switchFactionIdx].setVisible(switchFactionIdx+1 + //<= mapInfo.players); + // labelNetStatus[switchSlotIdx].setVisible(switchSlotIdx+1 + //<= mapInfo.players); + // } + } catch (const runtime_error &e) { + SystemFlags::OutputDebug( + SystemFlags::debugError, "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, e.what()); + 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()); + } + } + // printf("AFTER switchSlot returned\n"); + } else { + try { + // if(switchSetupRequests[i]->getSelectedFactionName() != "") { + // listBoxFactions[i].setSelectedItem(switchSetupRequests[i]->getSelectedFactionName()); + // } + // if(switchSetupRequests[i]->getToTeam() != -1) { + // listBoxTeams[i].setSelectedItemIndex(switchSetupRequests[i]->getToTeam()); + // } + + if ((switchSetupRequests[i]->getSwitchFlags() & + ssrft_NetworkPlayerName) == ssrft_NetworkPlayerName) { + // 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()); + + if (switchSetupRequests[i]->getNetworkPlayerName() != + GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME) { + // labelPlayerNames[i].setText(switchSetupRequests[i]->getNetworkPlayerName()); + gameSettings.setNetworkPlayerName( + i, switchSetupRequests[i]->getNetworkPlayerName()); + serverInterface->gameSettings.setNetworkPlayerName( + i, switchSetupRequests[i]->getNetworkPlayerName()); + switchRequested = true; + } else { + // labelPlayerNames[i].setText(""); + gameSettings.setNetworkPlayerName(i, ""); + serverInterface->gameSettings.setNetworkPlayerName(i, ""); + switchRequested = true; + } + // SetActivePlayerNameEditor(); + // switchSetupRequests[i]->clearSwitchFlag(ssrft_NetworkPlayerName); + } + } catch (const runtime_error &e) { + SystemFlags::OutputDebug( + SystemFlags::debugError, "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, e.what()); + 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()); + } + } + } + + delete switchSetupRequests[i]; + switchSetupRequests[i] = NULL; + } + } + + return switchRequested; } void Game::updateNetworkMarkedCells() { - try { - GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); - - if(gameNetworkInterface != NULL && - gameNetworkInterface->getMarkedCellList(false).empty() == false) { - - std::vector chatList = gameNetworkInterface->getMarkedCellList(true); - for(int idx = 0; idx < (int)chatList.size(); idx++) { - MarkedCell mc = chatList[idx]; - if(mc.getFactionIndex() >= 0) { - mc.setFaction((const Faction *)world.getFaction(mc.getFactionIndex())); - } - - Map *map= world.getMap(); - Vec2i surfaceCellPos = map->toSurfCoords(mc.getTargetPos()); - mapMarkedCellList[surfaceCellPos] = mc; - } - } - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - throw megaglest_runtime_error(szBuf); - } + try { + GameNetworkInterface *gameNetworkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + + if (gameNetworkInterface != NULL && + gameNetworkInterface->getMarkedCellList(false).empty() == false) { + + std::vector chatList = + gameNetworkInterface->getMarkedCellList(true); + for (int idx = 0; idx < (int)chatList.size(); idx++) { + MarkedCell mc = chatList[idx]; + if (mc.getFactionIndex() >= 0) { + mc.setFaction( + (const Faction *)world.getFaction(mc.getFactionIndex())); + } + + Map *map = world.getMap(); + Vec2i surfaceCellPos = map->toSurfCoords(mc.getTargetPos()); + mapMarkedCellList[surfaceCellPos] = mc; + } + } + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] error [%s]\n", __FILE__, __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + throw megaglest_runtime_error(szBuf); + } } void Game::updateNetworkUnMarkedCells() { - try { - GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); - - if(gameNetworkInterface != NULL && - gameNetworkInterface->getUnMarkedCellList(false).empty() == false) { - //Lang &lang= Lang::getInstance(); - - std::vector chatList = gameNetworkInterface->getUnMarkedCellList(true); - for(int idx = 0; idx < (int)chatList.size(); idx++) { - UnMarkedCell mc = chatList[idx]; - mc.setFaction((const Faction *)world.getFaction(mc.getFactionIndex())); - - Map *map= world.getMap(); - Vec2i surfaceCellPos = map->toSurfCoords(mc.getTargetPos()); - mapMarkedCellList.erase(surfaceCellPos); - } - } - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - throw megaglest_runtime_error(szBuf); - } + try { + GameNetworkInterface *gameNetworkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + + if (gameNetworkInterface != NULL && + gameNetworkInterface->getUnMarkedCellList(false).empty() == false) { + // Lang &lang= Lang::getInstance(); + + std::vector chatList = + gameNetworkInterface->getUnMarkedCellList(true); + for (int idx = 0; idx < (int)chatList.size(); idx++) { + UnMarkedCell mc = chatList[idx]; + mc.setFaction((const Faction *)world.getFaction(mc.getFactionIndex())); + + Map *map = world.getMap(); + Vec2i surfaceCellPos = map->toSurfCoords(mc.getTargetPos()); + mapMarkedCellList.erase(surfaceCellPos); + } + } + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] error [%s]\n", __FILE__, __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + throw megaglest_runtime_error(szBuf); + } } - void Game::updateNetworkHighligtedCells() { - try { - GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); - - //update the current entries - for(int idx = (int)highlightedCells.size()-1; idx >= 0; idx--) { - MarkedCell *mc = &highlightedCells[idx]; - mc->decrementAliveCount(); - if(mc->getAliveCount() < 0) { - highlightedCells.erase(highlightedCells.begin()+idx); - } - } - - if(gameNetworkInterface != NULL && - gameNetworkInterface->getHighlightedCellList(false).empty() == false) { - //Lang &lang= Lang::getInstance(); - std::vector highlighList = gameNetworkInterface->getHighlightedCellList(true); - for(int idx = 0; idx < (int)highlighList.size(); idx++) { - MarkedCell mc = highlighList[idx]; // I want a copy here - if(mc.getFactionIndex() >= 0) { - mc.setFaction((const Faction *)world.getFaction(mc.getFactionIndex())); // set faction pointer - } - addOrReplaceInHighlightedCells(mc); - } - } - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - throw megaglest_runtime_error(szBuf); - } -} + try { + GameNetworkInterface *gameNetworkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + + // update the current entries + for (int idx = (int)highlightedCells.size() - 1; idx >= 0; idx--) { + MarkedCell *mc = &highlightedCells[idx]; + mc->decrementAliveCount(); + if (mc->getAliveCount() < 0) { + highlightedCells.erase(highlightedCells.begin() + idx); + } + } -void Game::addOrReplaceInHighlightedCells(MarkedCell mc){ - if(mc.getFactionIndex() >= 0) { - for(int i = (int)highlightedCells.size()-1; i >= 0; i--) { - MarkedCell *currentMc = &highlightedCells[i]; - if(currentMc->getFactionIndex() == mc.getFactionIndex()) { - highlightedCells.erase(highlightedCells.begin()+i); - } - } - } - if(mc.getAliveCount() <= 0) { - mc.setAliveCount(200); - } - highlightedCells.push_back(mc); - - if (this->masterserverMode == false) { - CoreData &coreData= CoreData::getInstance(); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - - const Faction *faction = mc.getFaction(); - if(getWorld()->getThisFaction() == NULL) { - throw megaglest_runtime_error("getWorld()->getThisFaction() == NULL"); - } - //printf("faction [%p][%s]\n",faction,(faction != NULL ? faction->getType()->getName().c_str() : "")); - if((faction == NULL) || - (faction->getTeam() == getWorld()->getThisFaction()->getTeam())) { - soundRenderer.playFx(coreData.getMarkerSound(),true); - } - } + if (gameNetworkInterface != NULL && + gameNetworkInterface->getHighlightedCellList(false).empty() == false) { + // Lang &lang= Lang::getInstance(); + std::vector highlighList = + gameNetworkInterface->getHighlightedCellList(true); + for (int idx = 0; idx < (int)highlighList.size(); idx++) { + MarkedCell mc = highlighList[idx]; // I want a copy here + if (mc.getFactionIndex() >= 0) { + mc.setFaction((const Faction *)world.getFaction( + mc.getFactionIndex())); // set faction pointer + } + addOrReplaceInHighlightedCells(mc); + } + } + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] error [%s]\n", __FILE__, __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + throw megaglest_runtime_error(szBuf); + } } -void Game::ReplaceDisconnectedNetworkPlayersWithAI(bool isNetworkGame, NetworkRole role) { - if(role == nrServer && isNetworkGame == true && - difftime((long int)time(NULL),lastNetworkPlayerConnectionCheck) >= NETWORK_PLAYER_CONNECTION_CHECK_SECONDS) { - lastNetworkPlayerConnectionCheck = time(NULL); - Logger &logger= Logger::getInstance(); - ServerInterface *server = NetworkManager::getInstance().getServerInterface(); - - bool newAIPlayerCreated = false; - for(int i = 0; i < world.getFactionCount(); ++i) { - Faction *faction = world.getFaction(i); - if( faction->getFactionDisconnectHandled() == false && - (faction->getControlType() == ctNetwork || - faction->getControlType() == ctNetworkCpuEasy || - faction->getControlType() == ctNetworkCpu || - faction->getControlType() == ctNetworkCpuUltra || - faction->getControlType() == ctNetworkCpuMega)) { - - if(aiInterfaces[i] == NULL && - server->isClientConnected(faction->getStartLocationIndex()) == false) { - - if(faction->getPersonalityType() != fpt_Observer) { - DumpCRCWorldLogIfRequired("_faction_" + intToStr(i)); - } - - faction->setFactionDisconnectHandled(true); - - Lang &lang= Lang::getInstance(); - - bool isPlayerObserver = false; - char szBuf[8096]=""; - if(faction->getPersonalityType() != fpt_Observer) { - aiInterfaces[i] = new AiInterface(*this, i, faction->getTeam(), faction->getStartLocationIndex()); - - snprintf(szBuf,8096,Lang::getInstance().getString("LogScreenGameLoadingCreatingAIFaction","",true).c_str(),i); - logger.add(szBuf, true); - - commander.tryNetworkPlayerDisconnected(i); - - newAIPlayerCreated = true; - } - else { - isPlayerObserver = true; - - } - - const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); - for(unsigned int j = 0; j < (unsigned int)languageList.size(); ++j) { - if(isPlayerObserver == false) { - string msg = "Player #%d [%s] has disconnected, switching player to AI mode!"; - if(lang.hasString("GameSwitchPlayerToAI",languageList[j],true)) { - msg = lang.getString("GameSwitchPlayerToAI",languageList[j],true); - } - snprintf(szBuf,8096,msg.c_str(),i+1,this->gameSettings.getNetworkPlayerName(i).c_str()); - } - else { - string msg = "Player #%d [%s] has disconnected, but player was only an observer!"; - if(lang.hasString("GameSwitchPlayerObserverToAI",languageList[j],true)) { - msg = lang.getString("GameSwitchPlayerObserverToAI",languageList[j],true); - } - snprintf(szBuf,8096,msg.c_str(),i+1,this->gameSettings.getNetworkPlayerName(i).c_str()); - } - bool localEcho = (languageList[j] == lang.getLanguage()); - server->sendTextMessage(szBuf,-1,localEcho,languageList[j]); - } - } - } - } - - if(newAIPlayerCreated == true && Config::getInstance().getBool("EnableNewThreadManager","false") == true) { - bool enableServerControlledAI = this->gameSettings.getEnableServerControlledAI(); - - masterController.clearSlaves(true); - - std::vector slaveThreadList; - for(int i=0; i < world.getFactionCount(); ++i) { - Faction *faction= world.getFaction(i); - if(faction->getCpuControl(enableServerControlledAI,isNetworkGame,role) == true) { - slaveThreadList.push_back(aiInterfaces[i]->getWorkerThread()); - } - } - masterController.setSlaves(slaveThreadList); - } - } +void Game::addOrReplaceInHighlightedCells(MarkedCell mc) { + if (mc.getFactionIndex() >= 0) { + for (int i = (int)highlightedCells.size() - 1; i >= 0; i--) { + MarkedCell *currentMc = &highlightedCells[i]; + if (currentMc->getFactionIndex() == mc.getFactionIndex()) { + highlightedCells.erase(highlightedCells.begin() + i); + } + } + } + if (mc.getAliveCount() <= 0) { + mc.setAliveCount(200); + } + highlightedCells.push_back(mc); + + if (this->masterserverMode == false) { + CoreData &coreData = CoreData::getInstance(); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + + const Faction *faction = mc.getFaction(); + if (getWorld()->getThisFaction() == NULL) { + throw megaglest_runtime_error("getWorld()->getThisFaction() == NULL"); + } + // printf("faction [%p][%s]\n",faction,(faction != NULL ? + // faction->getType()->getName().c_str() : "")); + if ((faction == NULL) || + (faction->getTeam() == getWorld()->getThisFaction()->getTeam())) { + soundRenderer.playFx(coreData.getMarkerSound(), true); + } + } } -void Game::updateCamera(){ - if(currentUIState != NULL) { - currentUIState->updateCamera(); - return; - } - gameCamera.update(); -} +void Game::ReplaceDisconnectedNetworkPlayersWithAI(bool isNetworkGame, + NetworkRole role) { + if (role == nrServer && isNetworkGame == true && + difftime((long int)time(NULL), lastNetworkPlayerConnectionCheck) >= + NETWORK_PLAYER_CONNECTION_CHECK_SECONDS) { + lastNetworkPlayerConnectionCheck = time(NULL); + Logger &logger = Logger::getInstance(); + ServerInterface *server = + NetworkManager::getInstance().getServerInterface(); + + bool newAIPlayerCreated = false; + for (int i = 0; i < world.getFactionCount(); ++i) { + Faction *faction = world.getFaction(i); + if (faction->getFactionDisconnectHandled() == false && + (faction->getControlType() == ctNetwork || + faction->getControlType() == ctNetworkCpuEasy || + faction->getControlType() == ctNetworkCpu || + faction->getControlType() == ctNetworkCpuUltra || + faction->getControlType() == ctNetworkCpuMega)) { + + if (aiInterfaces[i] == NULL && + server->isClientConnected(faction->getStartLocationIndex()) == + false) { + + if (faction->getPersonalityType() != fpt_Observer) { + DumpCRCWorldLogIfRequired("_faction_" + intToStr(i)); + } + + faction->setFactionDisconnectHandled(true); + + Lang &lang = Lang::getInstance(); + + bool isPlayerObserver = false; + char szBuf[8096] = ""; + if (faction->getPersonalityType() != fpt_Observer) { + aiInterfaces[i] = new AiInterface(*this, i, faction->getTeam(), + faction->getStartLocationIndex()); + + snprintf(szBuf, 8096, + Lang::getInstance() + .getString("LogScreenGameLoadingCreatingAIFaction", "", + true) + .c_str(), + i); + logger.add(szBuf, true); + + commander.tryNetworkPlayerDisconnected(i); + + newAIPlayerCreated = true; + } else { + isPlayerObserver = true; + } + + const vector languageList = + this->gameSettings.getUniqueNetworkPlayerLanguages(); + for (unsigned int j = 0; j < (unsigned int)languageList.size(); ++j) { + if (isPlayerObserver == false) { + string msg = "Player #%d [%s] has disconnected, switching player " + "to AI mode!"; + if (lang.hasString("GameSwitchPlayerToAI", languageList[j], + true)) { + msg = lang.getString("GameSwitchPlayerToAI", languageList[j], + true); + } + snprintf(szBuf, 8096, msg.c_str(), i + 1, + this->gameSettings.getNetworkPlayerName(i).c_str()); + } else { + string msg = "Player #%d [%s] has disconnected, but player was " + "only an observer!"; + if (lang.hasString("GameSwitchPlayerObserverToAI", + languageList[j], true)) { + msg = lang.getString("GameSwitchPlayerObserverToAI", + languageList[j], true); + } + snprintf(szBuf, 8096, msg.c_str(), i + 1, + this->gameSettings.getNetworkPlayerName(i).c_str()); + } + bool localEcho = (languageList[j] == lang.getLanguage()); + server->sendTextMessage(szBuf, -1, localEcho, languageList[j]); + } + } + } + } + if (newAIPlayerCreated == true && + Config::getInstance().getBool("EnableNewThreadManager", "false") == + true) { + bool enableServerControlledAI = + this->gameSettings.getEnableServerControlledAI(); -// ==================== render ==================== + masterController.clearSlaves(true); -//render -void Game::render() { - // Ensure the camera starts in the right position - if(isFirstRender == true) { - isFirstRender = false; - - if(this->loadGameNode == NULL) { - gameCamera.setState(GameCamera::sGame); - this->restoreToStartXY(); - } - } - - canRender(); - incrementFps(); - - renderFps++; - totalRenderFps++; - - updateWorldStats(); - - //NetworkManager &networkManager= NetworkManager::getInstance(); - if(this->masterserverMode == false) { - renderWorker(); - } - else { - // Titi, uncomment this to watch the game on the masterserver - //renderWorker(); - - // In masterserver mode quit game if no network players left - ServerInterface *server = NetworkManager::getInstance().getServerInterface(); - int connectedClients=0; - for(int i = 0; i < world.getFactionCount(); ++i) { - Faction *faction = world.getFaction(i); - if(server->isClientConnected(faction->getStartLocationIndex()) == true) { - connectedClients++; - } - } - - if(connectedClients == 0) { - quitTriggeredIndicator = true; - } - else { - string str=""; - std::map factionDebugInfo; - - if( difftime((long int)time(NULL),lastMasterServerGameStatsDump) >= GAME_STATS_DUMP_INTERVAL) { - lastMasterServerGameStatsDump = time(NULL); - str = getDebugStats(factionDebugInfo); - - printf("== Current in-game stats (interval %d) ==\n%s\n",GAME_STATS_DUMP_INTERVAL,str.c_str()); - } - } - } + std::vector slaveThreadList; + for (int i = 0; i < world.getFactionCount(); ++i) { + Faction *faction = world.getFaction(i); + if (faction->getCpuControl(enableServerControlledAI, isNetworkGame, + role) == true) { + slaveThreadList.push_back(aiInterfaces[i]->getWorkerThread()); + } + } + masterController.setSlaves(slaveThreadList); + } + } } -void Game::renderWorker() { - if(currentUIState != NULL) { -// Renderer &renderer= Renderer::getInstance(); -// renderer.clearBuffers(); -// -// //3d -// renderer.reset3dMenu(); -// -// renderer.clearZBuffer(); -// //renderer.loadCameraMatrix(menuBackground.getCamera()); -// //renderer.renderMenuBackground(&menuBackground); -// renderer.renderParticleManager(rsMenu); -// -// //2d -// renderer.reset2d(); -// -// currentUIState->render(); -// -// if(renderer.isMasterserverMode() == false) { -// renderer.renderMouse2d(mouseX, mouseY, mouse2dAnim); -// renderer.renderFPSWhenEnabled(lastFps); -// renderer.swapBuffers(); -// } +void Game::updateCamera() { + if (currentUIState != NULL) { + currentUIState->updateCamera(); + return; + } + gameCamera.update(); +} - currentUIState->render(); - return; - } - else { - Renderer &renderer= Renderer::getInstance(); - if(renderer.getCustom3dMenu() != NULL) { - renderer.setCustom3dMenu(NULL); - } - } +// ==================== render ==================== - Chrono chrono; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); +// render +void Game::render() { + // Ensure the camera starts in the right position + if (isFirstRender == true) { + isFirstRender = false; - render3d(); + if (this->loadGameNode == NULL) { + gameCamera.setState(GameCamera::sGame); + this->restoreToStartXY(); + } + } + + canRender(); + incrementFps(); + + renderFps++; + totalRenderFps++; + + updateWorldStats(); + + // NetworkManager &networkManager= NetworkManager::getInstance(); + if (this->masterserverMode == false) { + renderWorker(); + } else { + // Titi, uncomment this to watch the game on the masterserver + // renderWorker(); + + // In masterserver mode quit game if no network players left + ServerInterface *server = + NetworkManager::getInstance().getServerInterface(); + int connectedClients = 0; + for (int i = 0; i < world.getFactionCount(); ++i) { + Faction *faction = world.getFaction(i); + if (server->isClientConnected(faction->getStartLocationIndex()) == true) { + connectedClients++; + } + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] renderFps = %d took msecs: %d [render3d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderFps,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); + if (connectedClients == 0) { + quitTriggeredIndicator = true; + } else { + string str = ""; + std::map factionDebugInfo; - render2d(); + if (difftime((long int)time(NULL), lastMasterServerGameStatsDump) >= + GAME_STATS_DUMP_INTERVAL) { + lastMasterServerGameStatsDump = time(NULL); + str = getDebugStats(factionDebugInfo); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] renderFps = %d took msecs: %d [render2d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderFps,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); + printf("== Current in-game stats (interval %d) ==\n%s\n", + GAME_STATS_DUMP_INTERVAL, str.c_str()); + } + } + } +} - Renderer::getInstance().swapBuffers(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] renderFps = %d took msecs: %d [swap buffers]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderFps,chrono.getMillis()); +void Game::renderWorker() { + if (currentUIState != NULL) { + // Renderer &renderer= Renderer::getInstance(); + // renderer.clearBuffers(); + // + // //3d + // renderer.reset3dMenu(); + // + // renderer.clearZBuffer(); + // //renderer.loadCameraMatrix(menuBackground.getCamera()); + // //renderer.renderMenuBackground(&menuBackground); + // renderer.renderParticleManager(rsMenu); + // + // //2d + // renderer.reset2d(); + // + // currentUIState->render(); + // + // if(renderer.isMasterserverMode() == false) { + // renderer.renderMouse2d(mouseX, mouseY, mouse2dAnim); + // renderer.renderFPSWhenEnabled(lastFps); + // renderer.swapBuffers(); + // } + + currentUIState->render(); + return; + } else { + Renderer &renderer = Renderer::getInstance(); + if (renderer.getCustom3dMenu() != NULL) { + renderer.setCustom3dMenu(NULL); + } + } + + Chrono chrono; + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) + chrono.start(); + + render3d(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] renderFps = %d took msecs: %d [render3d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + renderFps, chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + render2d(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] renderFps = %d took msecs: %d [render2d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + renderFps, chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + Renderer::getInstance().swapBuffers(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] renderFps = %d took msecs: %d [swap buffers]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + renderFps, chrono.getMillis()); } // ==================== tick ==================== void Game::removeUnitFromSelection(const Unit *unit) { - try { - Selection *selection= gui.getSelectionPtr(); - for(int i=0; i < selection->getCount(); ++i) { - const Unit *currentUnit = selection->getUnit(i); - if(currentUnit == unit) { - selection->unSelect(i); - break; - } - } - } - catch(const exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,szBuf); - - if(errorMessageBox.getEnabled() == false) { - ErrorDisplayMessage(ex.what(),true); - } - - //abort(); - } + try { + Selection *selection = gui.getSelectionPtr(); + for (int i = 0; i < selection->getCount(); ++i) { + const Unit *currentUnit = selection->getUnit(i); + if (currentUnit == unit) { + selection->unSelect(i); + break; + } + } + } catch (const exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, szBuf); + + if (errorMessageBox.getEnabled() == false) { + ErrorDisplayMessage(ex.what(), true); + } + + // abort(); + } } bool Game::addUnitToSelection(Unit *unit) { - bool result = false; - try { - Selection *selection= gui.getSelectionPtr(); - if(selection != NULL) { - result = selection->select(unit,true); - } - } - catch(const exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,szBuf); - - if(errorMessageBox.getEnabled() == false) { - ErrorDisplayMessage(ex.what(),true); - } - - //abort(); - } - - return result; + bool result = false; + try { + Selection *selection = gui.getSelectionPtr(); + if (selection != NULL) { + result = selection->select(unit, true); + } + } catch (const exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, szBuf); + + if (errorMessageBox.getEnabled() == false) { + ErrorDisplayMessage(ex.what(), true); + } + + // abort(); + } + + return result; } -void Game::addUnitToGroupSelection(Unit *unit,int groupIndex) { - try { - Selection *selection= gui.getSelectionPtr(); - if(selection != NULL) { - selection->addUnitToGroup(groupIndex,unit); - } - } - catch(const exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,szBuf); - - if(errorMessageBox.getEnabled() == false) { - ErrorDisplayMessage(ex.what(),true); - } - - //abort(); - } +void Game::addUnitToGroupSelection(Unit *unit, int groupIndex) { + try { + Selection *selection = gui.getSelectionPtr(); + if (selection != NULL) { + selection->addUnitToGroup(groupIndex, unit); + } + } catch (const exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, szBuf); + + if (errorMessageBox.getEnabled() == false) { + ErrorDisplayMessage(ex.what(), true); + } + + // abort(); + } } -void Game::removeUnitFromGroupSelection(int unitId,int groupIndex) { - try { - Selection *selection= gui.getSelectionPtr(); - if(selection != NULL) { - selection->removeUnitFromGroup(groupIndex,unitId); - } - } - catch(const exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,szBuf); - - if(errorMessageBox.getEnabled() == false) { - ErrorDisplayMessage(ex.what(),true); - } - - //abort(); - } +void Game::removeUnitFromGroupSelection(int unitId, int groupIndex) { + try { + Selection *selection = gui.getSelectionPtr(); + if (selection != NULL) { + selection->removeUnitFromGroup(groupIndex, unitId); + } + } catch (const exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, szBuf); + + if (errorMessageBox.getEnabled() == false) { + ErrorDisplayMessage(ex.what(), true); + } + + // abort(); + } } void Game::recallGroupSelection(int groupIndex) { - try { - Selection *selection= gui.getSelectionPtr(); - if(selection != NULL) { - selection->recallGroup(groupIndex); - } - } - catch(const exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,szBuf); - - if(errorMessageBox.getEnabled() == false) { - ErrorDisplayMessage(ex.what(),true); - } - - //abort(); - } + try { + Selection *selection = gui.getSelectionPtr(); + if (selection != NULL) { + selection->recallGroup(groupIndex); + } + } catch (const exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, szBuf); + + if (errorMessageBox.getEnabled() == false) { + ErrorDisplayMessage(ex.what(), true); + } + + // abort(); + } } void Game::tick() { - ProgramState::tick(); - - tickCount++; - - if(avgUpdateFps == -1) { - avgUpdateFps = updateFps; - } - else { - avgUpdateFps = (avgUpdateFps + updateFps) / 2; - } - currentAvgRenderFpsTotal += renderFps; - - if(avgRenderFps == -1) { - avgRenderFps = renderFps; - } - // Update the average every x game ticks - const int CHECK_AVG_FPS_EVERY_X_TICKS = 15; - if(tickCount % CHECK_AVG_FPS_EVERY_X_TICKS == 0) { - avgRenderFps = currentAvgRenderFpsTotal / CHECK_AVG_FPS_EVERY_X_TICKS; - currentAvgRenderFpsTotal = 0; - } - - if(captureAvgTestStatus == true) { - if(updateFpsAvgTest == -1) { - updateFpsAvgTest = updateFps; - } - else { - updateFpsAvgTest = (updateFpsAvgTest + updateFps) / 2; - } - if(renderFpsAvgTest == -1) { - renderFpsAvgTest = renderFps; - } - else { - renderFpsAvgTest = (renderFpsAvgTest + renderFps) / 2; - } - } - - lastUpdateFps= updateFps; - lastRenderFps= renderFps; - updateFps= 0; - renderFps= 0; - - //Win/lose check - checkWinner(); - gui.tick(); -} + ProgramState::tick(); + + tickCount++; + + if (avgUpdateFps == -1) { + avgUpdateFps = updateFps; + } else { + avgUpdateFps = (avgUpdateFps + updateFps) / 2; + } + currentAvgRenderFpsTotal += renderFps; + + if (avgRenderFps == -1) { + avgRenderFps = renderFps; + } + // Update the average every x game ticks + const int CHECK_AVG_FPS_EVERY_X_TICKS = 15; + if (tickCount % CHECK_AVG_FPS_EVERY_X_TICKS == 0) { + avgRenderFps = currentAvgRenderFpsTotal / CHECK_AVG_FPS_EVERY_X_TICKS; + currentAvgRenderFpsTotal = 0; + } + + if (captureAvgTestStatus == true) { + if (updateFpsAvgTest == -1) { + updateFpsAvgTest = updateFps; + } else { + updateFpsAvgTest = (updateFpsAvgTest + updateFps) / 2; + } + if (renderFpsAvgTest == -1) { + renderFpsAvgTest = renderFps; + } else { + renderFpsAvgTest = (renderFpsAvgTest + renderFps) / 2; + } + } + lastUpdateFps = updateFps; + lastRenderFps = renderFps; + updateFps = 0; + renderFps = 0; + + // Win/lose check + checkWinner(); + gui.tick(); +} // ==================== events ==================== int Game::getFirstUnusedTeamNumber() { - std::map uniqueTeamNumbersUsed; - for(unsigned int i = 0; i < (unsigned int)world.getFactionCount(); ++i) { - Faction *faction = world.getFaction(i); - uniqueTeamNumbersUsed[faction->getTeam()]=true; - } - - int result = -1; - for(int i = 0; i < GameConstants::maxPlayers; ++i) { - if(uniqueTeamNumbersUsed.find(i) == uniqueTeamNumbersUsed.end()) { - result = i; - break; - } - } - - return result; + std::map uniqueTeamNumbersUsed; + for (unsigned int i = 0; i < (unsigned int)world.getFactionCount(); ++i) { + Faction *faction = world.getFaction(i); + uniqueTeamNumbersUsed[faction->getTeam()] = true; + } + + int result = -1; + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + if (uniqueTeamNumbersUsed.find(i) == uniqueTeamNumbersUsed.end()) { + result = i; + break; + } + } + + return result; } void Game::setupRenderForVideo() { - Renderer &renderer= Renderer::getInstance(); - //renderer.clearBuffers(); - //3d - //renderer.reset3dMenu(); - //renderer.clearZBuffer(); - //2d - //renderer.reset2d(); - renderer.setupRenderForVideo(); + Renderer &renderer = Renderer::getInstance(); + // renderer.clearBuffers(); + // 3d + // renderer.reset3dMenu(); + // renderer.clearZBuffer(); + // 2d + // renderer.reset2d(); + renderer.setupRenderForVideo(); } void Game::tryPauseToggle(bool pauseValue) { - bool allowAdminMenuItems = false; - NetworkManager &networkManager= NetworkManager::getInstance(); - NetworkRole role = networkManager.getNetworkRole(); - if(role == nrServer) { - allowAdminMenuItems = true; - } - else if(role == nrClient) { - ClientInterface *clientInterface = dynamic_cast(networkManager.getClientInterface()); - - if(clientInterface != NULL && - gameSettings.getMasterserver_admin() == clientInterface->getSessionKey()) { - allowAdminMenuItems = true; - } - } - - bool isNetworkGame = this->gameSettings.isNetworkGame(); - //printf("Try Pause allowAdminMenuItems = %d, pauseValue = %d\n",allowAdminMenuItems,pauseValue); - - if(allowAdminMenuItems) { - if(pauseValue == true) { - commander.tryPauseGame(false,false); - } - else { - if(isNetworkGame == false) { - setPaused(pauseValue, true,false,false); - } - else { - commander.tryResumeGame(false,false); - } - } - } + bool allowAdminMenuItems = false; + NetworkManager &networkManager = NetworkManager::getInstance(); + NetworkRole role = networkManager.getNetworkRole(); + if (role == nrServer) { + allowAdminMenuItems = true; + } else if (role == nrClient) { + ClientInterface *clientInterface = + dynamic_cast(networkManager.getClientInterface()); + + if (clientInterface != NULL && gameSettings.getMasterserver_admin() == + clientInterface->getSessionKey()) { + allowAdminMenuItems = true; + } + } + + bool isNetworkGame = this->gameSettings.isNetworkGame(); + // printf("Try Pause allowAdminMenuItems = %d, pauseValue = + // %d\n",allowAdminMenuItems,pauseValue); + + if (allowAdminMenuItems) { + if (pauseValue == true) { + commander.tryPauseGame(false, false); + } else { + if (isNetworkGame == false) { + setPaused(pauseValue, true, false, false); + } else { + commander.tryResumeGame(false, false); + } + } + } } void Game::startMarkCell() { - int totalMarkedCellsForPlayer = 0; - if(world.getThisFaction() != NULL) { - for(std::map::iterator iterMap = mapMarkedCellList.begin(); - iterMap != mapMarkedCellList.end(); ++iterMap) { - MarkedCell &bm = iterMap->second; - if(bm.getPlayerIndex() == world.getThisFaction()->getStartLocationIndex()) { - totalMarkedCellsForPlayer++; - } - } - } - - const int MAX_MARKER_COUNT = 5; - if(totalMarkedCellsForPlayer < MAX_MARKER_COUNT) { - isMarkCellEnabled = true; - } - else { - Lang &lang= Lang::getInstance(); - console.addLine(lang.getString("MaxMarkerCount") + " " + intToStr(MAX_MARKER_COUNT)); - } + int totalMarkedCellsForPlayer = 0; + if (world.getThisFaction() != NULL) { + for (std::map::iterator iterMap = + mapMarkedCellList.begin(); + iterMap != mapMarkedCellList.end(); ++iterMap) { + MarkedCell &bm = iterMap->second; + if (bm.getPlayerIndex() == + world.getThisFaction()->getStartLocationIndex()) { + totalMarkedCellsForPlayer++; + } + } + } + + const int MAX_MARKER_COUNT = 5; + if (totalMarkedCellsForPlayer < MAX_MARKER_COUNT) { + isMarkCellEnabled = true; + } else { + Lang &lang = Lang::getInstance(); + console.addLine(lang.getString("MaxMarkerCount") + " " + + intToStr(MAX_MARKER_COUNT)); + } } void Game::processInputText(string text, bool cancelled) { - isMarkCellTextEnabled = false; - - if(cancelled == false) { - //printf("Note [%s]\n",text.c_str()); - - cellMarkedData.setNote(text); - addCellMarker(cellMarkedPos, cellMarkedData); - -// if(text.find("\\n") != text.npos) { -// replaceAll(text, "\\n", "\n"); -// } -// if(text.find("\\t") != text.npos) { -// replaceAll(text, "\\t", "\t"); -// } -// -// cellMarkedData.setNote(text); -// mapMarkedCellList[cellMarkedPos] = cellMarkedData; -// -// GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); -// -// int factionIndex = -1; -// int playerIndex = -1; -// if(cellMarkedData.getFaction() != NULL) { -// factionIndex = cellMarkedData.getFaction()->getIndex(); -// playerIndex = cellMarkedData.getFaction()->getStartLocationIndex(); -// } -// gameNetworkInterface->sendMarkCellMessage( -// cellMarkedData.getTargetPos(), -// factionIndex, -// cellMarkedData.getNote(), -// playerIndex); -// -// Renderer &renderer= Renderer::getInstance(); -// renderer.forceQuadCacheUpdate(); - } + isMarkCellTextEnabled = false; + + if (cancelled == false) { + // printf("Note [%s]\n",text.c_str()); + + cellMarkedData.setNote(text); + addCellMarker(cellMarkedPos, cellMarkedData); + + // if(text.find("\\n") != text.npos) { + // replaceAll(text, "\\n", "\n"); + // } + // if(text.find("\\t") != text.npos) { + // replaceAll(text, "\\t", "\t"); + // } + // + // cellMarkedData.setNote(text); + // mapMarkedCellList[cellMarkedPos] = cellMarkedData; + // + // GameNetworkInterface *gameNetworkInterface= + // NetworkManager::getInstance().getGameNetworkInterface(); + // + // int factionIndex = -1; + // int playerIndex = -1; + // if(cellMarkedData.getFaction() != NULL) { + // factionIndex = cellMarkedData.getFaction()->getIndex(); + // playerIndex = + // cellMarkedData.getFaction()->getStartLocationIndex(); + // } + // gameNetworkInterface->sendMarkCellMessage( + // cellMarkedData.getTargetPos(), + // factionIndex, + // cellMarkedData.getNote(), + // playerIndex); + // + // Renderer &renderer= Renderer::getInstance(); + // renderer.forceQuadCacheUpdate(); + } } void Game::addCellMarker(Vec2i cellPos, MarkedCell cellData) { - //printf("Note [%s]\n",text.c_str()); - - string text = cellData.getNote(); - if(text.find("\\n") != text.npos) { - replaceAll(text, "\\n", "\n"); - } - if(text.find("\\t") != text.npos) { - replaceAll(text, "\\t", "\t"); - } - - cellData.setNote(text); - mapMarkedCellList[cellPos] = cellData; - - GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); - - int factionIndex = -1; - int playerIndex = -1; - if(cellData.getFaction() != NULL) { - factionIndex = cellData.getFaction()->getIndex(); - playerIndex = cellData.getFaction()->getStartLocationIndex(); - } - - //printf("Adding Cell marker pos [%s] factionIndex [%d] note [%s] playerIndex = %d\n",cellData.getTargetPos().getString().c_str(),factionIndex,cellData.getNote().c_str(),playerIndex); - - gameNetworkInterface->sendMarkCellMessage( - cellData.getTargetPos(), - factionIndex, - cellData.getNote(), - playerIndex); - - Renderer &renderer= Renderer::getInstance(); - renderer.forceQuadCacheUpdate(); + // printf("Note [%s]\n",text.c_str()); + + string text = cellData.getNote(); + if (text.find("\\n") != text.npos) { + replaceAll(text, "\\n", "\n"); + } + if (text.find("\\t") != text.npos) { + replaceAll(text, "\\t", "\t"); + } + + cellData.setNote(text); + mapMarkedCellList[cellPos] = cellData; + + GameNetworkInterface *gameNetworkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + + int factionIndex = -1; + int playerIndex = -1; + if (cellData.getFaction() != NULL) { + factionIndex = cellData.getFaction()->getIndex(); + playerIndex = cellData.getFaction()->getStartLocationIndex(); + } + + // printf("Adding Cell marker pos [%s] factionIndex [%d] note [%s] playerIndex + // = + // %d\n",cellData.getTargetPos().getString().c_str(),factionIndex,cellData.getNote().c_str(),playerIndex); + + gameNetworkInterface->sendMarkCellMessage( + cellData.getTargetPos(), factionIndex, cellData.getNote(), playerIndex); + + Renderer &renderer = Renderer::getInstance(); + renderer.forceQuadCacheUpdate(); } void Game::removeCellMarker(Vec2i surfaceCellPos, const Faction *faction) { - //Vec2i surfaceCellPos = map->toSurfCoords(Vec2i(xCell,yCell)); - Map *map= world.getMap(); - SurfaceCell *sc = map->getSurfaceCell(surfaceCellPos); - Vec3f vertex = sc->getVertex(); - Vec2i targetPos(vertex.x,vertex.z); + // Vec2i surfaceCellPos = map->toSurfCoords(Vec2i(xCell,yCell)); + Map *map = world.getMap(); + SurfaceCell *sc = map->getSurfaceCell(surfaceCellPos); + Vec3f vertex = sc->getVertex(); + Vec2i targetPos(vertex.x, vertex.z); + + // printf("Remove Cell marker lookup pos [%s] factionIndex + // [%d]\n",surfaceCellPos.getString().c_str(),(faction != NULL ? + // faction->getIndex() : -1)); + + if (mapMarkedCellList.find(surfaceCellPos) != mapMarkedCellList.end()) { + MarkedCell mc = mapMarkedCellList[surfaceCellPos]; + if (mc.getFaction() == faction) { + mapMarkedCellList.erase(surfaceCellPos); + GameNetworkInterface *gameNetworkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + + int factionIndex = (faction != NULL ? faction->getIndex() : -1); + + // printf("Remvoing Cell marker pos [%s] factionIndex [%d] note + // [%s]\n",mc.getTargetPos().getString().c_str(),factionIndex,mc.getNote().c_str()); + + gameNetworkInterface->sendUnMarkCellMessage(mc.getTargetPos(), + factionIndex); + } + } + // printf("#1 ADDED in marked list pos [%s] markedCells.size() = " + // MG_SIZE_T_SPECIFIER + // "\n",surfaceCellPos.getString().c_str(),mapMarkedCellList.size()); + + // isUnMarkCellEnabled = false; + + Renderer &renderer = Renderer::getInstance(); + // renderer.updateMarkedCellScreenPosQuadCache(surfaceCellPos); + renderer.forceQuadCacheUpdate(); +} +void Game::showMarker(Vec2i cellPos, MarkedCell cellData) { + // setMarker = true; + // if(setMarker) { + // Vec2i targetPos = cellData.targetPos; + // Vec2i screenPos(x,y-60); + // Renderer &renderer= Renderer::getInstance(); + // renderer.computePosition(screenPos, targetPos); + // Vec2i surfaceCellPos = map->toSurfCoords(targetPos); + + // MarkedCell + // mc(targetPos,world.getThisFaction(),"none",world.getThisFaction()->getStartLocationIndex()); + addOrReplaceInHighlightedCells(cellData); + + GameNetworkInterface *gameNetworkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + gameNetworkInterface->sendHighlightCellMessage(cellData.getTargetPos(), + cellData.getFactionIndex()); + //} +} + +void Game::mouseDownLeft(int x, int y) { + if (this->masterserverMode == true) { + return; + } + cameraDragAllowed = false; + if (currentUIState != NULL) { + currentUIState->mouseDownLeft(x, y); + return; + } + + try { + if (gameStarted == false || totalRenderFps <= 0) { + Logger::getInstance().handleMouseClick(x, y); + return; + } + + Map *map = world.getMap(); + const Metrics &metrics = Metrics::getInstance(); + NetworkManager &networkManager = NetworkManager::getInstance(); + bool messageBoxClick = false; + bool originalIsMarkCellEnabled = isMarkCellEnabled; + bool originalIsUnMarkCellEnabled = isUnMarkCellEnabled; + + if (popupMenu.mouseClick(x, y)) { + std::pair result = popupMenu.mouseClickedMenuItem(x, y); + // printf("In popup callback menuItemSelected [%s] menuIndexSelected = + // %d\n",result.second.c_str(),result.first); + + // printf("popupMenu.mouseClick == true result.first = %d + // disconnectPlayerPopupMenuIndex = + // %d\n",result.first,disconnectPlayerPopupMenuIndex); + + popupMenu.setEnabled(false); + popupMenu.setVisible(false); + + // Exit game + if (result.first == exitGamePopupMenuIndex) { + showMessageBox(Lang::getInstance().getString("ExitBattleQuestion"), "", + true); + } else if (result.first == joinTeamPopupMenuIndex) { + + Lang &lang = Lang::getInstance(); + switchTeamIndexMap.clear(); + std::map uniqueTeamNumbersUsed; + std::vector menuItems; + for (unsigned int i = 0; i < (unsigned int)world.getFactionCount(); + ++i) { + Faction *faction = world.getFaction(i); + + if (faction->getPersonalityType() != fpt_Observer && + uniqueTeamNumbersUsed.find(faction->getTeam()) == + uniqueTeamNumbersUsed.end()) { + uniqueTeamNumbersUsed[faction->getTeam()] = true; + } + + if (faction->getPersonalityType() != fpt_Observer && + world.getThisFaction()->getIndex() != faction->getIndex() && + world.getThisFaction()->getTeam() != faction->getTeam()) { + char szBuf[8096] = ""; + if (lang.hasString("JoinPlayerTeam") == true) { + snprintf(szBuf, 8096, + (" " + lang.getString("JoinPlayerTeam") + " ").c_str(), + faction->getIndex(), + this->gameSettings.getNetworkPlayerName(i).c_str(), + faction->getTeam()); + } else { + snprintf(szBuf, 8096, " Join player #%d - %s on Team: %d ", + faction->getIndex(), + this->gameSettings.getNetworkPlayerName(i).c_str(), + faction->getTeam()); + } + + menuItems.push_back(szBuf); + + switchTeamIndexMap[(int)menuItems.size() - 1] = faction->getTeam(); + } + } + + if ((int)uniqueTeamNumbersUsed.size() < 8) { + menuItems.push_back(" " + lang.getString("CreateNewTeam") + " "); + switchTeamIndexMap[(int)menuItems.size() - 1] = CREATE_NEW_TEAM; + } + menuItems.push_back(" " + lang.getString("Cancel") + " "); + switchTeamIndexMap[(int)menuItems.size() - 1] = CANCEL_SWITCH_TEAM; + + popupMenuSwitchTeams.setW(100); + popupMenuSwitchTeams.setH(100); + popupMenuSwitchTeams.init(" " + lang.getString("SwitchTeams") + " ", + menuItems); + popupMenuSwitchTeams.setEnabled(true); + popupMenuSwitchTeams.setVisible(true); + } else if (result.first == disconnectPlayerPopupMenuIndex) { + Lang &lang = Lang::getInstance(); + + NetworkManager &networkManager = NetworkManager::getInstance(); + NetworkRole role = networkManager.getNetworkRole(); + ServerInterface *serverInterface = NULL; + if (role == nrServer) { + serverInterface = dynamic_cast( + networkManager.getServerInterface()); + } + disconnectPlayerIndexMap.clear(); + std::vector menuItems; + for (unsigned int i = 0; i < (unsigned int)world.getFactionCount(); + ++i) { + Faction *faction = world.getFaction(i); + + // printf("faction->getPersonalityType() = %d index [%d,%d] control + // [%d] networkstatus + // [%d]\n",faction->getPersonalityType(),world.getThisFaction()->getIndex(),faction->getIndex(),faction->getControlType(),this->gameSettings.getNetworkPlayerStatuses(i)); + + bool isSlotJoinInProgressClient = false; + if (serverInterface != NULL) { + + MutexSafeWrapper safeMutex( + serverInterface->getSlotMutex(faction->getStartLocationIndex()), + CODE_AT_LINE); + ConnectionSlot *slot = serverInterface->getSlot( + faction->getStartLocationIndex(), false); + if (slot != NULL && slot->getConnectHasHandshaked() == true && + slot->getCurrentFrameCount() <= 0) { + isSlotJoinInProgressClient = true; + } + } + + // printf("isSlotJoinInProgressClient: %d [%d] [%d][%d] [%d] [%d] + // [%d]\n", + // isSlotJoinInProgressClient,faction->getPersonalityType(),faction->getIndex(),world.getThisFaction()->getIndex(),faction->getControlType(),this->gameSettings.getNetworkPlayerStatuses(i),i); + + if (isSlotJoinInProgressClient == true || + (faction->getPersonalityType() != fpt_Observer && + world.getThisFaction()->getIndex() != faction->getIndex() && + faction->getControlType() == ctNetwork && + this->gameSettings.getNetworkPlayerStatuses(i) != + npst_Disconnected)) { + + char szBuf[8096] = ""; + if (lang.hasString("DisconnectNetorkPlayerIndex") == true) { + snprintf( + szBuf, 8096, + (" " + lang.getString("DisconnectNetorkPlayerIndex") + " ") + .c_str(), + faction->getIndex() + 1, + this->gameSettings.getNetworkPlayerName(i).c_str()); + } else { + snprintf(szBuf, 8096, " Disconnect player #%d - %s: ", + faction->getIndex() + 1, + this->gameSettings.getNetworkPlayerName(i).c_str()); + } + + menuItems.push_back(szBuf); + + // disconnectPlayerIndexMap[menuItems.size()-1] = + // faction->getStartLocationIndex(); + disconnectPlayerIndexMap[(int)menuItems.size() - 1] = + faction->getIndex(); + } + } + + menuItems.push_back(" " + lang.getString("Cancel") + " "); + disconnectPlayerIndexMap[(int)menuItems.size() - 1] = + CANCEL_DISCONNECT_PLAYER; + + popupMenuDisconnectPlayer.setW(100); + popupMenuDisconnectPlayer.setH(100); + popupMenuDisconnectPlayer.init( + " " + lang.getString("DisconnectNetorkPlayer") + " ", menuItems); + popupMenuDisconnectPlayer.setEnabled(true); + popupMenuDisconnectPlayer.setVisible(true); + } else if (result.first == keyboardSetupPopupMenuIndex) { + MainMenu *newMenu = + new MainMenu(program); // open keyboard shortcuts setup screen + currentUIState = newMenu; + Renderer &renderer = Renderer::getInstance(); + renderer.setCustom3dMenu(newMenu); + // currentUIState->load(); + currentUIState->init(); + + // open keyboard shortcuts setup screen + newMenu->setState( + new MenuStateKeysetup(program, newMenu, ¤tUIState)); + } else if (result.first == pauseGamePopupMenuIndex) { + // this->setPaused(!paused); + // printf("popup paused = %d\n",paused); + + bool allowAdminMenuItems = false; + NetworkRole role = networkManager.getNetworkRole(); + if (role == nrServer) { + allowAdminMenuItems = true; + } else if (role == nrClient) { + ClientInterface *clientInterface = dynamic_cast( + networkManager.getClientInterface()); + + if (clientInterface != NULL && gameSettings.getMasterserver_admin() == + clientInterface->getSessionKey()) { + allowAdminMenuItems = true; + } + } + + if (allowAdminMenuItems) { + if (getPaused() == false) { + commander.tryPauseGame(false, false); + } else { + commander.tryResumeGame(false, false); + } + } + } else if (result.first == saveGamePopupMenuIndex) { + saveGame(); + } + // else if(result.first == markCellPopupMenuIndex) { + // startMarkCell(); + // } + // else if(result.first == unmarkCellPopupMenuIndex) { + // isUnMarkCellEnabled = true; + // } + } else if (popupMenuSwitchTeams.mouseClick(x, y)) { + // popupMenuSwitchTeams + std::pair result = + popupMenuSwitchTeams.mouseClickedMenuItem(x, y); + // printf("In popup callback menuItemSelected [%s] menuIndexSelected = + // %d\n",result.second.c_str(),result.first); + + popupMenuSwitchTeams.setEnabled(false); + popupMenuSwitchTeams.setVisible(false); + + // bool isNetworkGame = this->gameSettings.isNetworkGame(); + + int teamIndex = switchTeamIndexMap[result.first]; + switch (teamIndex) { + case CREATE_NEW_TEAM: { + int newTeam = getFirstUnusedTeamNumber(); + // if(isNetworkGame == true) { + const Faction *faction = world.getThisFaction(); + commander.trySwitchTeam(faction, newTeam); + //} + // else { + // const Faction *faction = world.getThisFaction(); + // commander.trySwitchTeam(faction,newTeam); + //} + } break; + case CANCEL_SWITCH_TEAM: + break; + default: + // if(isNetworkGame == true) { + const Faction *faction = world.getThisFaction(); + commander.trySwitchTeam(faction, teamIndex); + //} + // else { + // const Faction *faction = world.getThisFaction(); + // commander.trySwitchTeam(faction,teamIndex); + //} + + break; + } + } else if (popupMenuDisconnectPlayer.mouseClick(x, y)) { + // popupMenuSwitchTeams + std::pair result = + popupMenuDisconnectPlayer.mouseClickedMenuItem(x, y); + // printf("In popup callback menuItemSelected [%s] menuIndexSelected = + // %d\n",result.second.c_str(),result.first); + + popupMenuDisconnectPlayer.setEnabled(false); + popupMenuDisconnectPlayer.setVisible(false); + + // bool isNetworkGame = this->gameSettings.isNetworkGame(); + + // int playerIndex = disconnectPlayerIndexMap[result.first]; + int factionIndex = disconnectPlayerIndexMap[result.first]; + switch (factionIndex) { + case CANCEL_DISCONNECT_PLAYER: + break; + default: + // if(isNetworkGame == true) { + // const Faction *faction = + // world.getThisFaction(); + // commander.trySwitchTeam(faction,teamIndex); + // } + // else { + // const Faction *faction = + // world.getThisFaction(); + // commander.trySwitchTeam(faction,teamIndex); + // } + + GameSettings *settings = world.getGameSettingsPtr(); + Lang &lang = Lang::getInstance(); + + char szBuf[8096] = ""; + if (lang.hasString("DisconnectNetorkPlayerIndexConfirm") == true) { + snprintf(szBuf, 8096, + (" " + + lang.getString("DisconnectNetorkPlayerIndexConfirm") + " ") + .c_str(), + factionIndex + 1, + settings->getNetworkPlayerName(factionIndex).c_str()); + } else { + snprintf(szBuf, 8096, + " Confirm disconnection for player #%d - %s? ", + factionIndex + 1, + settings->getNetworkPlayerName(factionIndex).c_str()); + } + + disconnectPlayerConfirmMessageBox.setText(szBuf); + disconnectPlayerConfirmMessageBox.init(lang.getString("Yes"), + lang.getString("No")); + disconnectPlayerConfirmMessageBox.setEnabled(true); + + playerIndexDisconnect = + world.getFaction(factionIndex)->getStartLocationIndex(); + + GameNetworkInterface *gameNetworkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + if (gameNetworkInterface != NULL) { + Lang &lang = Lang::getInstance(); + const vector languageList = + settings->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < (unsigned int)languageList.size(); ++i) { + char szMsg[8096] = ""; + if (lang.hasString("DisconnectNetorkPlayerIndexConfirmed", + languageList[i]) == true) { + snprintf(szMsg, 8096, + lang.getString("DisconnectNetorkPlayerIndexConfirmed", + languageList[i]) + .c_str(), + factionIndex + 1, + settings->getNetworkPlayerName(factionIndex).c_str()); + } else { + snprintf( + szMsg, 8096, + "Notice - Admin is warning to disconnect player #%d - %s!", + factionIndex + 1, + settings->getNetworkPlayerName(factionIndex).c_str()); + } + bool localEcho = lang.isLanguageLocal(languageList[i]); + gameNetworkInterface->sendTextMessage(szMsg, -1, localEcho, + languageList[i]); + } + + sleep(10); + } + + break; + } + } + + if (switchTeamConfirmMessageBox.getEnabled() == true) { + int button = -1; + if (switchTeamConfirmMessageBox.mouseClick(x, y, button)) { + switchTeamConfirmMessageBox.setEnabled(false); + + SwitchTeamVote *vote = world.getThisFactionPtr()->getSwitchTeamVote( + world.getThisFaction()->getCurrentSwitchTeamVoteFactionIndex()); + vote->voted = true; + vote->allowSwitchTeam = (button == 0); + + const Faction *faction = world.getThisFaction(); + commander.trySwitchTeamVote(faction, vote); + } + } else if (disconnectPlayerConfirmMessageBox.getEnabled() == true) { + int button = -1; + if (disconnectPlayerConfirmMessageBox.mouseClick(x, y, button)) { + disconnectPlayerConfirmMessageBox.setEnabled(false); + + if (button == 0) { + const Faction *faction = world.getThisFaction(); + commander.tryDisconnectNetworkPlayer(faction, playerIndexDisconnect); + } + } + } + + // scrip message box, only if the exit box is not enabled + if (mainMessageBox.getEnabled() == false && + errorMessageBox.getEnabled() == false && + scriptManager.getMessageBox()->getEnabled()) { + int button = 0; + if (scriptManager.getMessageBox()->mouseClick(x, y, button)) { + scriptManager.onMessageBoxOk(); + messageBoxClick = true; + } + } - //printf("Remove Cell marker lookup pos [%s] factionIndex [%d]\n",surfaceCellPos.getString().c_str(),(faction != NULL ? faction->getIndex() : -1)); + // minimap panel + if (messageBoxClick == false) { + if (metrics.isInMinimap(x, y)) { + int xm = x - metrics.getMinimapX(); + int ym = y - metrics.getMinimapY(); + int xCell = static_cast( + xm * (static_cast(map->getW()) / metrics.getMinimapW())); + int yCell = static_cast( + map->getH() - + ym * (static_cast(map->getH()) / metrics.getMinimapH())); + + if (map->isInside(xCell, yCell) && + map->isInsideSurface(map->toSurfCoords(Vec2i(xCell, yCell)))) { + if (gui.isSelectingPos()) { + gui.mouseDownLeftGraphics(xCell, yCell, true); + } else { + if (!setMarker) { + cameraDragAllowed = true; + gameCamera.setPos( + Vec2f(static_cast(xCell), static_cast(yCell))); + } + } + + if (setMarker) { + Vec2i surfaceCellPos = map->toSurfCoords(Vec2i(xCell, yCell)); + SurfaceCell *sc = map->getSurfaceCell(surfaceCellPos); + Vec3f vertex = sc->getVertex(); + Vec2i targetPos(vertex.x, vertex.z); + + MarkedCell mc(targetPos, world.getThisFaction(), "none", + world.getThisFaction()->getStartLocationIndex()); + addOrReplaceInHighlightedCells(mc); + + GameNetworkInterface *gameNetworkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + gameNetworkInterface->sendHighlightCellMessage( + mc.getTargetPos(), mc.getFaction()->getIndex()); + } + + if (originalIsMarkCellEnabled == true && isMarkCellEnabled == true) { + Vec2i surfaceCellPos = map->toSurfCoords(Vec2i(xCell, yCell)); + SurfaceCell *sc = map->getSurfaceCell(surfaceCellPos); + Vec3f vertex = sc->getVertex(); + Vec2i targetPos(vertex.x, vertex.z); + + MarkedCell mc(targetPos, world.getThisFaction(), + "placeholder for note", + world.getThisFaction()->getStartLocationIndex()); + + // GameNetworkInterface *gameNetworkInterface= + // NetworkManager::getInstance().getGameNetworkInterface(); + // gameNetworkInterface->sendMarkCellMessage(mc.getTargetPos(),mc.getFaction()->getIndex(),mc.getNote()); + + // printf("#1 ADDED in marked list pos [%s] markedCells.size() = " + // MG_SIZE_T_SPECIFIER + // "\n",surfaceCellPos.getString().c_str(),mapMarkedCellList.size()); + + isMarkCellEnabled = false; + cellMarkedData = mc; + cellMarkedPos = surfaceCellPos; + isMarkCellTextEnabled = true; + chatManager.switchOnEdit(this, 500); + + Renderer &renderer = Renderer::getInstance(); + // renderer.updateMarkedCellScreenPosQuadCache(surfaceCellPos); + renderer.forceQuadCacheUpdate(); + } + if (originalIsUnMarkCellEnabled == true && + isUnMarkCellEnabled == true) { + Vec2i surfaceCellPos = map->toSurfCoords(Vec2i(xCell, yCell)); + SurfaceCell *sc = map->getSurfaceCell(surfaceCellPos); + Vec3f vertex = sc->getVertex(); + Vec2i targetPos(vertex.x, vertex.z); + + // if(mapMarkedCellList.find(surfaceCellPos) + //!= mapMarkedCellList.end()) { + // MarkedCell mc = mapMarkedCellList[surfaceCellPos]; + // if(mc.getFaction() == world.getThisFaction()) { + // mapMarkedCellList.erase(surfaceCellPos); GameNetworkInterface + //*gameNetworkInterface= + // NetworkManager::getInstance().getGameNetworkInterface(); + // gameNetworkInterface->sendUnMarkCellMessage(mc.getTargetPos(),mc.getFaction()->getIndex()); + // } + // } + + isUnMarkCellEnabled = false; + + removeCellMarker(surfaceCellPos, world.getThisFaction()); + // printf("#1 ADDED in marked list pos [%s] markedCells.size() = " + // MG_SIZE_T_SPECIFIER + // "\n",surfaceCellPos.getString().c_str(),mapMarkedCellList.size()); + + Renderer &renderer = Renderer::getInstance(); + // renderer.updateMarkedCellScreenPosQuadCache(surfaceCellPos); + renderer.forceQuadCacheUpdate(); + } + } + } + // display panel + else if (metrics.isInDisplay(x, y) && !gui.isSelectingPos()) { + int xd = x - metrics.getDisplayX(); + int yd = y - metrics.getDisplayY(); + if (gui.mouseValid(xd, yd)) { + gui.mouseDownLeftDisplay(xd, yd); + } else { + gui.mouseDownLeftGraphics(x, y, false); + } + } + // graphics panel + else { + gui.mouseDownLeftGraphics(x, y, false); + + if (setMarker) { + Vec2i targetPos; + Vec2i screenPos(x, y - 60); + targetPos = getMouseCellPos(); + // Vec2i surfaceCellPos = map->toSurfCoords(targetPos); + + MarkedCell mc(targetPos, world.getThisFaction(), "none", + world.getThisFaction()->getStartLocationIndex()); + addOrReplaceInHighlightedCells(mc); + + GameNetworkInterface *gameNetworkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + gameNetworkInterface->sendHighlightCellMessage( + mc.getTargetPos(), mc.getFaction()->getIndex()); + } - if(mapMarkedCellList.find(surfaceCellPos) != mapMarkedCellList.end()) { - MarkedCell mc = mapMarkedCellList[surfaceCellPos]; - if(mc.getFaction() == faction) { - mapMarkedCellList.erase(surfaceCellPos); - GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); + if (originalIsMarkCellEnabled == true && isMarkCellEnabled == true) { + Vec2i targetPos; + Vec2i screenPos(x, y - 60); + targetPos = getMouseCellPos(); + Vec2i surfaceCellPos = map->toSurfCoords(targetPos); - int factionIndex = (faction != NULL ? faction->getIndex() : -1); + MarkedCell mc(targetPos, world.getThisFaction(), + "placeholder for note", + world.getThisFaction()->getStartLocationIndex()); - //printf("Remvoing Cell marker pos [%s] factionIndex [%d] note [%s]\n",mc.getTargetPos().getString().c_str(),factionIndex,mc.getNote().c_str()); + // printf("#2 ADDED in marked list pos [%s] markedCells.size() = " + // MG_SIZE_T_SPECIFIER + // "\n",surfaceCellPos.getString().c_str(),mapMarkedCellList.size()); - gameNetworkInterface->sendUnMarkCellMessage(mc.getTargetPos(),factionIndex); - } - } - //printf("#1 ADDED in marked list pos [%s] markedCells.size() = " MG_SIZE_T_SPECIFIER "\n",surfaceCellPos.getString().c_str(),mapMarkedCellList.size()); + isMarkCellEnabled = false; + cellMarkedData = mc; + cellMarkedPos = surfaceCellPos; + isMarkCellTextEnabled = true; + chatManager.switchOnEdit(this, 500); - //isUnMarkCellEnabled = false; + // renderer.updateMarkedCellScreenPosQuadCache(surfaceCellPos); + Renderer::getInstance().forceQuadCacheUpdate(); + } - Renderer &renderer= Renderer::getInstance(); - //renderer.updateMarkedCellScreenPosQuadCache(surfaceCellPos); - renderer.forceQuadCacheUpdate(); -} -void Game::showMarker(Vec2i cellPos, MarkedCell cellData) { - //setMarker = true; - //if(setMarker) { - //Vec2i targetPos = cellData.targetPos; - //Vec2i screenPos(x,y-60); - //Renderer &renderer= Renderer::getInstance(); - //renderer.computePosition(screenPos, targetPos); - //Vec2i surfaceCellPos = map->toSurfCoords(targetPos); - - //MarkedCell mc(targetPos,world.getThisFaction(),"none",world.getThisFaction()->getStartLocationIndex()); - addOrReplaceInHighlightedCells(cellData); - - GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); - gameNetworkInterface->sendHighlightCellMessage(cellData.getTargetPos(),cellData.getFactionIndex()); - //} -} + if (originalIsUnMarkCellEnabled == true && + isUnMarkCellEnabled == true) { + Vec2i targetPos; + Vec2i screenPos(x, y - 35); + targetPos = getMouseCellPos(); + Vec2i surfaceCellPos = map->toSurfCoords(targetPos); + + // if(mapMarkedCellList.find(surfaceCellPos) + //!= + // mapMarkedCellList.end()) { MarkedCell mc + // = + // mapMarkedCellList[surfaceCellPos]; + // if(mc.getFaction() == world.getThisFaction()) { + // mapMarkedCellList.erase(surfaceCellPos); GameNetworkInterface + //*gameNetworkInterface= + // NetworkManager::getInstance().getGameNetworkInterface(); + // gameNetworkInterface->sendUnMarkCellMessage(mc.getTargetPos(),mc.getFaction()->getIndex()); + // } + // } + + isUnMarkCellEnabled = false; + removeCellMarker(surfaceCellPos, world.getThisFaction()); + // printf("#1 ADDED in marked list pos [%s] markedCells.size() = " + // MG_SIZE_T_SPECIFIER + // "\n",surfaceCellPos.getString().c_str(),mapMarkedCellList.size()); + + // Renderer &renderer= Renderer::getInstance(); + // renderer.updateMarkedCellScreenPosQuadCache(surfaceCellPos); + Renderer::getInstance().forceQuadCacheUpdate(); + } + } + } -void Game::mouseDownLeft(int x, int y) { - if(this->masterserverMode == true) { - return; - } - cameraDragAllowed=false; - if(currentUIState != NULL) { - currentUIState->mouseDownLeft(x, y); - return; - } - - try { - if(gameStarted == false || totalRenderFps <= 0) { - Logger::getInstance().handleMouseClick(x, y); - return; - } - - Map *map= world.getMap(); - const Metrics &metrics= Metrics::getInstance(); - NetworkManager &networkManager= NetworkManager::getInstance(); - bool messageBoxClick= false; - bool originalIsMarkCellEnabled = isMarkCellEnabled; - bool originalIsUnMarkCellEnabled = isUnMarkCellEnabled; - - if(popupMenu.mouseClick(x, y)) { - std::pair result = popupMenu.mouseClickedMenuItem(x, y); - //printf("In popup callback menuItemSelected [%s] menuIndexSelected = %d\n",result.second.c_str(),result.first); - - //printf("popupMenu.mouseClick == true result.first = %d disconnectPlayerPopupMenuIndex = %d\n",result.first,disconnectPlayerPopupMenuIndex); - - popupMenu.setEnabled(false); - popupMenu.setVisible(false); - - // Exit game - if(result.first == exitGamePopupMenuIndex) { - showMessageBox(Lang::getInstance().getString("ExitBattleQuestion"), "", true); - } - else if(result.first == joinTeamPopupMenuIndex) { - - Lang &lang= Lang::getInstance(); - switchTeamIndexMap.clear(); - std::map uniqueTeamNumbersUsed; - std::vector menuItems; - for(unsigned int i = 0; i < (unsigned int)world.getFactionCount(); ++i) { - Faction *faction = world.getFaction(i); - - if(faction->getPersonalityType() != fpt_Observer && - uniqueTeamNumbersUsed.find(faction->getTeam()) == uniqueTeamNumbersUsed.end()) { - uniqueTeamNumbersUsed[faction->getTeam()] = true; - } - - if(faction->getPersonalityType() != fpt_Observer && - world.getThisFaction()->getIndex() != faction->getIndex() && - world.getThisFaction()->getTeam() != faction->getTeam()) { - char szBuf[8096]=""; - if(lang.hasString("JoinPlayerTeam") == true) { - snprintf(szBuf,8096,(" " + lang.getString("JoinPlayerTeam") + " ").c_str(),faction->getIndex(),this->gameSettings.getNetworkPlayerName(i).c_str(),faction->getTeam()); - } - else { - snprintf(szBuf,8096," Join player #%d - %s on Team: %d ",faction->getIndex(),this->gameSettings.getNetworkPlayerName(i).c_str(),faction->getTeam()); - } - - menuItems.push_back(szBuf); - - switchTeamIndexMap[(int)menuItems.size()-1] = faction->getTeam(); - } - } - - if((int)uniqueTeamNumbersUsed.size() < 8) { - menuItems.push_back(" " + lang.getString("CreateNewTeam") + " "); - switchTeamIndexMap[(int)menuItems.size()-1] = CREATE_NEW_TEAM; - } - menuItems.push_back(" " + lang.getString("Cancel") + " "); - switchTeamIndexMap[(int)menuItems.size()-1] = CANCEL_SWITCH_TEAM; - - popupMenuSwitchTeams.setW(100); - popupMenuSwitchTeams.setH(100); - popupMenuSwitchTeams.init(" " + lang.getString("SwitchTeams") + " ",menuItems); - popupMenuSwitchTeams.setEnabled(true); - popupMenuSwitchTeams.setVisible(true); - } - else if(result.first == disconnectPlayerPopupMenuIndex) { - Lang &lang= Lang::getInstance(); - - NetworkManager &networkManager= NetworkManager::getInstance(); - NetworkRole role = networkManager.getNetworkRole(); - ServerInterface *serverInterface = NULL; - if(role == nrServer) { - serverInterface = dynamic_cast(networkManager.getServerInterface()); - } - disconnectPlayerIndexMap.clear(); - std::vector menuItems; - for(unsigned int i = 0; i < (unsigned int)world.getFactionCount(); ++i) { - Faction *faction = world.getFaction(i); - - //printf("faction->getPersonalityType() = %d index [%d,%d] control [%d] networkstatus [%d]\n",faction->getPersonalityType(),world.getThisFaction()->getIndex(),faction->getIndex(),faction->getControlType(),this->gameSettings.getNetworkPlayerStatuses(i)); - - bool isSlotJoinInProgressClient = false; - if(serverInterface != NULL) { - - MutexSafeWrapper safeMutex(serverInterface->getSlotMutex(faction->getStartLocationIndex()),CODE_AT_LINE); - ConnectionSlot *slot = serverInterface->getSlot(faction->getStartLocationIndex(),false); - if(slot != NULL && slot->getConnectHasHandshaked() == true && - slot->getCurrentFrameCount() <= 0) { - isSlotJoinInProgressClient = true; - } - } - - //printf("isSlotJoinInProgressClient: %d [%d] [%d][%d] [%d] [%d] [%d]\n", - // isSlotJoinInProgressClient,faction->getPersonalityType(),faction->getIndex(),world.getThisFaction()->getIndex(),faction->getControlType(),this->gameSettings.getNetworkPlayerStatuses(i),i); - - if(isSlotJoinInProgressClient == true || - (faction->getPersonalityType() != fpt_Observer && - world.getThisFaction()->getIndex() != faction->getIndex() && - faction->getControlType() == ctNetwork && - this->gameSettings.getNetworkPlayerStatuses(i) != npst_Disconnected)) { - - char szBuf[8096]=""; - if(lang.hasString("DisconnectNetorkPlayerIndex") == true) { - snprintf(szBuf,8096,(" " + lang.getString("DisconnectNetorkPlayerIndex") + " ").c_str(),faction->getIndex()+1,this->gameSettings.getNetworkPlayerName(i).c_str()); - } - else { - snprintf(szBuf,8096," Disconnect player #%d - %s: ",faction->getIndex()+1,this->gameSettings.getNetworkPlayerName(i).c_str()); - } - - menuItems.push_back(szBuf); - - //disconnectPlayerIndexMap[menuItems.size()-1] = faction->getStartLocationIndex(); - disconnectPlayerIndexMap[(int)menuItems.size()-1] = faction->getIndex(); - } - } - - menuItems.push_back(" " + lang.getString("Cancel") + " "); - disconnectPlayerIndexMap[(int)menuItems.size()-1] = CANCEL_DISCONNECT_PLAYER; - - popupMenuDisconnectPlayer.setW(100); - popupMenuDisconnectPlayer.setH(100); - popupMenuDisconnectPlayer.init(" " + lang.getString("DisconnectNetorkPlayer") + " ",menuItems); - popupMenuDisconnectPlayer.setEnabled(true); - popupMenuDisconnectPlayer.setVisible(true); - } - else if(result.first == keyboardSetupPopupMenuIndex) { - MainMenu *newMenu = new MainMenu(program); // open keyboard shortcuts setup screen - currentUIState = newMenu; - Renderer &renderer= Renderer::getInstance(); - renderer.setCustom3dMenu(newMenu); - //currentUIState->load(); - currentUIState->init(); - - // open keyboard shortcuts setup screen - newMenu->setState(new MenuStateKeysetup(program, newMenu, ¤tUIState)); - } - else if(result.first == pauseGamePopupMenuIndex) { - //this->setPaused(!paused); - //printf("popup paused = %d\n",paused); - - bool allowAdminMenuItems = false; - NetworkRole role = networkManager.getNetworkRole(); - if(role == nrServer) { - allowAdminMenuItems = true; - } - else if(role == nrClient) { - ClientInterface *clientInterface = dynamic_cast(networkManager.getClientInterface()); - - if(clientInterface != NULL && - gameSettings.getMasterserver_admin() == clientInterface->getSessionKey()) { - allowAdminMenuItems = true; - } - } - - if(allowAdminMenuItems) { - if(getPaused() == false) { - commander.tryPauseGame(false,false); - } - else { - commander.tryResumeGame(false,false); - } - } - } - else if(result.first == saveGamePopupMenuIndex){ - saveGame(); - } - //else if(result.first == markCellPopupMenuIndex) { - // startMarkCell(); - //} - //else if(result.first == unmarkCellPopupMenuIndex) { - // isUnMarkCellEnabled = true; - //} - } - else if(popupMenuSwitchTeams.mouseClick(x, y)) { - //popupMenuSwitchTeams - std::pair result = popupMenuSwitchTeams.mouseClickedMenuItem(x, y); - //printf("In popup callback menuItemSelected [%s] menuIndexSelected = %d\n",result.second.c_str(),result.first); - - popupMenuSwitchTeams.setEnabled(false); - popupMenuSwitchTeams.setVisible(false); - - //bool isNetworkGame = this->gameSettings.isNetworkGame(); - - int teamIndex = switchTeamIndexMap[result.first]; - switch(teamIndex) { - case CREATE_NEW_TEAM: - { - int newTeam = getFirstUnusedTeamNumber(); - //if(isNetworkGame == true) { - const Faction *faction = world.getThisFaction(); - commander.trySwitchTeam(faction,newTeam); - //} - //else { - // const Faction *faction = world.getThisFaction(); - // commander.trySwitchTeam(faction,newTeam); - //} - } - break; - case CANCEL_SWITCH_TEAM: - break; - default: - //if(isNetworkGame == true) { - const Faction *faction = world.getThisFaction(); - commander.trySwitchTeam(faction,teamIndex); - //} - //else { - // const Faction *faction = world.getThisFaction(); - // commander.trySwitchTeam(faction,teamIndex); - //} - - break; - } - } - else if(popupMenuDisconnectPlayer.mouseClick(x, y)) { - //popupMenuSwitchTeams - std::pair result = popupMenuDisconnectPlayer.mouseClickedMenuItem(x, y); - //printf("In popup callback menuItemSelected [%s] menuIndexSelected = %d\n",result.second.c_str(),result.first); - - popupMenuDisconnectPlayer.setEnabled(false); - popupMenuDisconnectPlayer.setVisible(false); - - //bool isNetworkGame = this->gameSettings.isNetworkGame(); - - //int playerIndex = disconnectPlayerIndexMap[result.first]; - int factionIndex = disconnectPlayerIndexMap[result.first]; - switch(factionIndex) { - case CANCEL_DISCONNECT_PLAYER: - break; - default: -// if(isNetworkGame == true) { -// const Faction *faction = world.getThisFaction(); -// commander.trySwitchTeam(faction,teamIndex); -// } -// else { -// const Faction *faction = world.getThisFaction(); -// commander.trySwitchTeam(faction,teamIndex); -// } - - - GameSettings *settings = world.getGameSettingsPtr(); - Lang &lang= Lang::getInstance(); - - char szBuf[8096]=""; - if(lang.hasString("DisconnectNetorkPlayerIndexConfirm") == true) { - snprintf(szBuf,8096,(" " + lang.getString("DisconnectNetorkPlayerIndexConfirm") + " ").c_str(),factionIndex+1,settings->getNetworkPlayerName(factionIndex).c_str()); - } - else { - snprintf(szBuf,8096," Confirm disconnection for player #%d - %s? ",factionIndex+1,settings->getNetworkPlayerName(factionIndex).c_str()); - } - - disconnectPlayerConfirmMessageBox.setText(szBuf); - disconnectPlayerConfirmMessageBox.init(lang.getString("Yes"), lang.getString("No")); - disconnectPlayerConfirmMessageBox.setEnabled(true); - - playerIndexDisconnect = world.getFaction(factionIndex)->getStartLocationIndex(); - - GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); - if(gameNetworkInterface != NULL) { - Lang &lang= Lang::getInstance(); - const vector languageList = settings->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < (unsigned int)languageList.size(); ++i) { - char szMsg[8096]=""; - if(lang.hasString("DisconnectNetorkPlayerIndexConfirmed",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("DisconnectNetorkPlayerIndexConfirmed",languageList[i]).c_str(),factionIndex+1,settings->getNetworkPlayerName(factionIndex).c_str()); - } - else { - snprintf(szMsg,8096,"Notice - Admin is warning to disconnect player #%d - %s!",factionIndex+1,settings->getNetworkPlayerName(factionIndex).c_str()); - } - bool localEcho = lang.isLanguageLocal(languageList[i]); - gameNetworkInterface->sendTextMessage(szMsg,-1, localEcho,languageList[i]); - } - - sleep(10); - } - - break; - } - } - - if(switchTeamConfirmMessageBox.getEnabled() == true) { - int button= -1; - if(switchTeamConfirmMessageBox.mouseClick(x,y,button)) { - switchTeamConfirmMessageBox.setEnabled(false); - - SwitchTeamVote *vote = world.getThisFactionPtr()->getSwitchTeamVote(world.getThisFaction()->getCurrentSwitchTeamVoteFactionIndex()); - vote->voted = true; - vote->allowSwitchTeam = (button == 0); - - const Faction *faction = world.getThisFaction(); - commander.trySwitchTeamVote(faction,vote); - } - } - else if(disconnectPlayerConfirmMessageBox.getEnabled() == true) { - int button= -1; - if(disconnectPlayerConfirmMessageBox.mouseClick(x,y,button)) { - disconnectPlayerConfirmMessageBox.setEnabled(false); - - if(button == 0) { - const Faction *faction = world.getThisFaction(); - commander.tryDisconnectNetworkPlayer(faction,playerIndexDisconnect); - } - } - } - - //scrip message box, only if the exit box is not enabled - if( mainMessageBox.getEnabled() == false && - errorMessageBox.getEnabled() == false && - scriptManager.getMessageBox()->getEnabled()) { - int button= 0; - if(scriptManager.getMessageBox()->mouseClick(x, y, button)){ - scriptManager.onMessageBoxOk(); - messageBoxClick= true; - } - } - - //minimap panel - if(messageBoxClick == false) { - if(metrics.isInMinimap(x, y)){ - int xm= x - metrics.getMinimapX(); - int ym= y - metrics.getMinimapY(); - int xCell= static_cast(xm * (static_cast(map->getW()) / metrics.getMinimapW())); - int yCell= static_cast(map->getH() - ym * (static_cast(map->getH()) / metrics.getMinimapH())); - - if(map->isInside(xCell, yCell) && map->isInsideSurface(map->toSurfCoords(Vec2i(xCell,yCell)))) { - if(gui.isSelectingPos()){ - gui.mouseDownLeftGraphics(xCell, yCell, true); - } - else - { - if(!setMarker) { - cameraDragAllowed=true; - gameCamera.setPos(Vec2f(static_cast(xCell), static_cast(yCell))); - } - } - - if(setMarker) { - Vec2i surfaceCellPos = map->toSurfCoords(Vec2i(xCell,yCell)); - SurfaceCell *sc = map->getSurfaceCell(surfaceCellPos); - Vec3f vertex = sc->getVertex(); - Vec2i targetPos(vertex.x,vertex.z); - - MarkedCell mc(targetPos,world.getThisFaction(),"none",world.getThisFaction()->getStartLocationIndex()); - addOrReplaceInHighlightedCells(mc); - - GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); - gameNetworkInterface->sendHighlightCellMessage(mc.getTargetPos(),mc.getFaction()->getIndex()); - } - - - if(originalIsMarkCellEnabled == true && isMarkCellEnabled == true) { - Vec2i surfaceCellPos = map->toSurfCoords(Vec2i(xCell,yCell)); - SurfaceCell *sc = map->getSurfaceCell(surfaceCellPos); - Vec3f vertex = sc->getVertex(); - Vec2i targetPos(vertex.x,vertex.z); - - MarkedCell mc(targetPos,world.getThisFaction(),"placeholder for note",world.getThisFaction()->getStartLocationIndex()); - - //GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); - //gameNetworkInterface->sendMarkCellMessage(mc.getTargetPos(),mc.getFaction()->getIndex(),mc.getNote()); - - //printf("#1 ADDED in marked list pos [%s] markedCells.size() = " MG_SIZE_T_SPECIFIER "\n",surfaceCellPos.getString().c_str(),mapMarkedCellList.size()); - - isMarkCellEnabled = false; - cellMarkedData = mc; - cellMarkedPos = surfaceCellPos; - isMarkCellTextEnabled = true; - chatManager.switchOnEdit(this,500); - - Renderer &renderer= Renderer::getInstance(); - //renderer.updateMarkedCellScreenPosQuadCache(surfaceCellPos); - renderer.forceQuadCacheUpdate(); - } - if(originalIsUnMarkCellEnabled == true && isUnMarkCellEnabled == true) { - Vec2i surfaceCellPos = map->toSurfCoords(Vec2i(xCell,yCell)); - SurfaceCell *sc = map->getSurfaceCell(surfaceCellPos); - Vec3f vertex = sc->getVertex(); - Vec2i targetPos(vertex.x,vertex.z); - -// if(mapMarkedCellList.find(surfaceCellPos) != mapMarkedCellList.end()) { -// MarkedCell mc = mapMarkedCellList[surfaceCellPos]; -// if(mc.getFaction() == world.getThisFaction()) { -// mapMarkedCellList.erase(surfaceCellPos); -// GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); -// gameNetworkInterface->sendUnMarkCellMessage(mc.getTargetPos(),mc.getFaction()->getIndex()); -// } -// } - - isUnMarkCellEnabled = false; - - removeCellMarker(surfaceCellPos, world.getThisFaction()); - //printf("#1 ADDED in marked list pos [%s] markedCells.size() = " MG_SIZE_T_SPECIFIER "\n",surfaceCellPos.getString().c_str(),mapMarkedCellList.size()); - - Renderer &renderer= Renderer::getInstance(); - //renderer.updateMarkedCellScreenPosQuadCache(surfaceCellPos); - renderer.forceQuadCacheUpdate(); - } - } - } - //display panel - else if(metrics.isInDisplay(x, y) && !gui.isSelectingPos()) { - int xd= x - metrics.getDisplayX(); - int yd= y - metrics.getDisplayY(); - if(gui.mouseValid(xd, yd)) { - gui.mouseDownLeftDisplay(xd, yd); - } - else { - gui.mouseDownLeftGraphics(x, y, false); - } - } - //graphics panel - else { - gui.mouseDownLeftGraphics(x, y, false); - - if(setMarker) { - Vec2i targetPos; - Vec2i screenPos(x,y-60); - targetPos=getMouseCellPos(); - //Vec2i surfaceCellPos = map->toSurfCoords(targetPos); - - - MarkedCell mc(targetPos,world.getThisFaction(),"none",world.getThisFaction()->getStartLocationIndex()); - addOrReplaceInHighlightedCells(mc); - - GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); - gameNetworkInterface->sendHighlightCellMessage(mc.getTargetPos(),mc.getFaction()->getIndex()); - } - - if(originalIsMarkCellEnabled == true && isMarkCellEnabled == true) { - Vec2i targetPos; - Vec2i screenPos(x,y-60); - targetPos=getMouseCellPos(); - Vec2i surfaceCellPos = map->toSurfCoords(targetPos); - - MarkedCell mc(targetPos,world.getThisFaction(),"placeholder for note",world.getThisFaction()->getStartLocationIndex()); - - //printf("#2 ADDED in marked list pos [%s] markedCells.size() = " MG_SIZE_T_SPECIFIER "\n",surfaceCellPos.getString().c_str(),mapMarkedCellList.size()); - - isMarkCellEnabled = false; - cellMarkedData = mc; - cellMarkedPos = surfaceCellPos; - isMarkCellTextEnabled = true; - chatManager.switchOnEdit(this,500); - - //renderer.updateMarkedCellScreenPosQuadCache(surfaceCellPos); - Renderer::getInstance().forceQuadCacheUpdate(); - } - - if(originalIsUnMarkCellEnabled == true && isUnMarkCellEnabled == true) { - Vec2i targetPos; - Vec2i screenPos(x,y-35); - targetPos=getMouseCellPos(); - Vec2i surfaceCellPos = map->toSurfCoords(targetPos); - -// if(mapMarkedCellList.find(surfaceCellPos) != mapMarkedCellList.end()) { -// MarkedCell mc = mapMarkedCellList[surfaceCellPos]; -// if(mc.getFaction() == world.getThisFaction()) { -// mapMarkedCellList.erase(surfaceCellPos); -// GameNetworkInterface *gameNetworkInterface= NetworkManager::getInstance().getGameNetworkInterface(); -// gameNetworkInterface->sendUnMarkCellMessage(mc.getTargetPos(),mc.getFaction()->getIndex()); -// } -// } - - isUnMarkCellEnabled = false; - removeCellMarker(surfaceCellPos, world.getThisFaction()); - //printf("#1 ADDED in marked list pos [%s] markedCells.size() = " MG_SIZE_T_SPECIFIER "\n",surfaceCellPos.getString().c_str(),mapMarkedCellList.size()); - - //Renderer &renderer= Renderer::getInstance(); - //renderer.updateMarkedCellScreenPosQuadCache(surfaceCellPos); - Renderer::getInstance().forceQuadCacheUpdate(); - } - } - } - - //exit message box, has to be the last thing to do in this function - if(errorMessageBox.getEnabled() == true) { - if(errorMessageBox.mouseClick(x, y)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //close message box - errorMessageBox.setEnabled(false); - } - } - if(mainMessageBox.getEnabled()){ - int button= 0; - if(mainMessageBox.mouseClick(x, y, button)) { - if(button==0) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(networkManager.getGameNetworkInterface() != NULL) { - networkManager.getGameNetworkInterface()->quitGame(true); - } - quitTriggeredIndicator = true; - return; - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //close message box - mainMessageBox.setEnabled(false); - } - } - } - } - catch(const exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,szBuf); - - NetworkManager &networkManager= NetworkManager::getInstance(); - if(networkManager.getGameNetworkInterface() != NULL) { - GameNetworkInterface *networkInterface = NetworkManager::getInstance().getGameNetworkInterface(); - networkInterface->sendTextMessage(szBuf,-1,true,""); - sleep(10); - networkManager.getGameNetworkInterface()->quitGame(true); - } - ErrorDisplayMessage(ex.what(),true); - } + // exit message box, has to be the last thing to do in this function + if (errorMessageBox.getEnabled() == true) { + if (errorMessageBox.mouseClick(x, y)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + // close message box + errorMessageBox.setEnabled(false); + } + } + if (mainMessageBox.getEnabled()) { + int button = 0; + if (mainMessageBox.mouseClick(x, y, button)) { + if (button == 0) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + if (networkManager.getGameNetworkInterface() != NULL) { + networkManager.getGameNetworkInterface()->quitGame(true); + } + quitTriggeredIndicator = true; + return; + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + // close message box + mainMessageBox.setEnabled(false); + } + } + } + } catch (const exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, szBuf); + + NetworkManager &networkManager = NetworkManager::getInstance(); + if (networkManager.getGameNetworkInterface() != NULL) { + GameNetworkInterface *networkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + networkInterface->sendTextMessage(szBuf, -1, true, ""); + sleep(10); + networkManager.getGameNetworkInterface()->quitGame(true); + } + ErrorDisplayMessage(ex.what(), true); + } } void Game::mouseDownRight(int x, int y) { - if(this->masterserverMode == true) { - return; - } - - if(currentUIState != NULL) { - currentUIState->mouseDownRight(x, y); - return; - } - - try { - if(gameStarted == false || totalRenderFps <= 0) { - Logger::getInstance().handleMouseClick(x, y); - return; - } - - Map *map= world.getMap(); - const Metrics &metrics= Metrics::getInstance(); - - if(metrics.isInMinimap(x, y) ){ - int xm= x - metrics.getMinimapX(); - int ym= y - metrics.getMinimapY(); - int xCell= static_cast(xm * (static_cast(map->getW()) / metrics.getMinimapW())); - int yCell= static_cast(map->getH() - ym * (static_cast(map->getH()) / metrics.getMinimapH())); - - if(map->isInside(xCell, yCell) && map->isInsideSurface(map->toSurfCoords(Vec2i(xCell,yCell)))) { - gui.mouseDownRightGraphics(xCell, yCell,true); - } - } - else { - Vec2i targetPos; - Vec2i screenPos(x,y); - targetPos=getMouseCellPos(); - if(isValidMouseCellPos() == true && - map->isInsideSurface(map->toSurfCoords(targetPos)) == true) { - gui.mouseDownRightGraphics(x, y,false); - } - } - } - catch(const exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] Error [%s] x = %d y = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what(),x,y); - - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,szBuf); - - NetworkManager &networkManager= NetworkManager::getInstance(); - if(networkManager.getGameNetworkInterface() != NULL) { - GameNetworkInterface *networkInterface = NetworkManager::getInstance().getGameNetworkInterface(); - networkInterface->sendTextMessage(szBuf,-1,true,""); - sleep(10); - networkManager.getGameNetworkInterface()->quitGame(true); - } - ErrorDisplayMessage(ex.what(),true); - } + if (this->masterserverMode == true) { + return; + } + + if (currentUIState != NULL) { + currentUIState->mouseDownRight(x, y); + return; + } + + try { + if (gameStarted == false || totalRenderFps <= 0) { + Logger::getInstance().handleMouseClick(x, y); + return; + } + + Map *map = world.getMap(); + const Metrics &metrics = Metrics::getInstance(); + + if (metrics.isInMinimap(x, y)) { + int xm = x - metrics.getMinimapX(); + int ym = y - metrics.getMinimapY(); + int xCell = static_cast( + xm * (static_cast(map->getW()) / metrics.getMinimapW())); + int yCell = + static_cast(map->getH() - ym * (static_cast(map->getH()) / + metrics.getMinimapH())); + + if (map->isInside(xCell, yCell) && + map->isInsideSurface(map->toSurfCoords(Vec2i(xCell, yCell)))) { + gui.mouseDownRightGraphics(xCell, yCell, true); + } + } else { + Vec2i targetPos; + Vec2i screenPos(x, y); + targetPos = getMouseCellPos(); + if (isValidMouseCellPos() == true && + map->isInsideSurface(map->toSurfCoords(targetPos)) == true) { + gui.mouseDownRightGraphics(x, y, false); + } + } + } catch (const exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d] Error [%s] x = %d y = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what(), x, y); + + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, szBuf); + + NetworkManager &networkManager = NetworkManager::getInstance(); + if (networkManager.getGameNetworkInterface() != NULL) { + GameNetworkInterface *networkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + networkInterface->sendTextMessage(szBuf, -1, true, ""); + sleep(10); + networkManager.getGameNetworkInterface()->quitGame(true); + } + ErrorDisplayMessage(ex.what(), true); + } } - void Game::mouseUpCenter(int x, int y) { - if(this->masterserverMode == true) { - return; - } - - if(gameStarted == false || totalRenderFps <= 0) { - return; - } - - if(currentUIState != NULL) { - currentUIState->mouseUpCenter(x, y); - return; - } - - if(mouseMoved == false) { - gameCamera.setState(GameCamera::sGame); - } - else { - mouseMoved = false; - } +void Game::mouseUpCenter(int x, int y) { + if (this->masterserverMode == true) { + return; + } + + if (gameStarted == false || totalRenderFps <= 0) { + return; + } + + if (currentUIState != NULL) { + currentUIState->mouseUpCenter(x, y); + return; + } + + if (mouseMoved == false) { + gameCamera.setState(GameCamera::sGame); + } else { + mouseMoved = false; + } } void Game::mouseUpLeft(int x, int y) { - if(this->masterserverMode == true) { - return; - } - - try { - if(gameStarted == false || totalRenderFps <= 0) { - return; - } - - if(currentUIState != NULL) { - currentUIState->mouseUpLeft(x, y); - return; - } - - gui.mouseUpLeftGraphics(x, y); - } - catch(const exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,szBuf); - - NetworkManager &networkManager= NetworkManager::getInstance(); - if(networkManager.getGameNetworkInterface() != NULL) { - GameNetworkInterface *networkInterface = NetworkManager::getInstance().getGameNetworkInterface(); - networkInterface->sendTextMessage(szBuf,-1,true,""); - sleep(10); - networkManager.getGameNetworkInterface()->quitGame(true); - } - ErrorDisplayMessage(ex.what(),true); - } + if (this->masterserverMode == true) { + return; + } + + try { + if (gameStarted == false || totalRenderFps <= 0) { + return; + } + + if (currentUIState != NULL) { + currentUIState->mouseUpLeft(x, y); + return; + } + + gui.mouseUpLeftGraphics(x, y); + } catch (const exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, szBuf); + + NetworkManager &networkManager = NetworkManager::getInstance(); + if (networkManager.getGameNetworkInterface() != NULL) { + GameNetworkInterface *networkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + networkInterface->sendTextMessage(szBuf, -1, true, ""); + sleep(10); + networkManager.getGameNetworkInterface()->quitGame(true); + } + ErrorDisplayMessage(ex.what(), true); + } } void Game::mouseDoubleClickLeft(int x, int y) { - if(this->masterserverMode == true) { - return; - } - - try { - if(gameStarted == false || totalRenderFps <= 0) { - return; - } - if(currentUIState != NULL) { - currentUIState->mouseDoubleClickLeft(x, y); - return; - } - - const Metrics &metrics= Metrics::getInstance(); - - if(metrics.isInMinimap(x, y)){ - // no double click on minimap - } - else { - //display panel - if(metrics.isInDisplay(x, y) && !gui.isSelectingPos()) { - int xd= x - metrics.getDisplayX(); - int yd= y - metrics.getDisplayY(); - if(gui.mouseValid(xd, yd)){ - return; - } - } - //graphics panel - gui.mouseDoubleClickLeftGraphics(x, y); - } - } - catch(const exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,szBuf); - - NetworkManager &networkManager= NetworkManager::getInstance(); - if(networkManager.getGameNetworkInterface() != NULL) { - GameNetworkInterface *networkInterface = NetworkManager::getInstance().getGameNetworkInterface(); - networkInterface->sendTextMessage(szBuf,-1,true,""); - sleep(10); - networkManager.getGameNetworkInterface()->quitGame(true); - } - ErrorDisplayMessage(ex.what(),true); - } + if (this->masterserverMode == true) { + return; + } + + try { + if (gameStarted == false || totalRenderFps <= 0) { + return; + } + if (currentUIState != NULL) { + currentUIState->mouseDoubleClickLeft(x, y); + return; + } + + const Metrics &metrics = Metrics::getInstance(); + + if (metrics.isInMinimap(x, y)) { + // no double click on minimap + } else { + // display panel + if (metrics.isInDisplay(x, y) && !gui.isSelectingPos()) { + int xd = x - metrics.getDisplayX(); + int yd = y - metrics.getDisplayY(); + if (gui.mouseValid(xd, yd)) { + return; + } + } + // graphics panel + gui.mouseDoubleClickLeftGraphics(x, y); + } + } catch (const exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, szBuf); + + NetworkManager &networkManager = NetworkManager::getInstance(); + if (networkManager.getGameNetworkInterface() != NULL) { + GameNetworkInterface *networkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + networkInterface->sendTextMessage(szBuf, -1, true, ""); + sleep(10); + networkManager.getGameNetworkInterface()->quitGame(true); + } + ErrorDisplayMessage(ex.what(), true); + } } void Game::mouseMove(int x, int y, const MouseState *ms) { - if(this->masterserverMode == true) { - return; - } - - try { - if(gameStarted == false || totalRenderFps <= 0) { - return; - } - if(currentUIState != NULL) { - currentUIState->mouseMove(x, y, ms); - return; - } - - popupMenu.mouseMove(x, y); - popupMenuSwitchTeams.mouseMove(x, y); - popupMenuDisconnectPlayer.mouseMove(x, y); - - const Metrics &metrics = Metrics::getInstance(); - - mouseX = x; - mouseY = y; - - if (ms->get(mbCenter)) { - mouseMoved = true; - if(currentCameraFollowUnit == NULL) { - float ymult = 0.2f; - float xmult = 0.2f; - - Vec2i oldPos = ::Shared::Platform::Window::getOldMousePos(); - int oldx= (oldPos.x * metrics.getVirtualW() / metrics.getScreenW()); - int oldy= ((metrics.getScreenH()-oldPos.y) * metrics.getVirtualH() / metrics.getScreenH()); - lastMousePos.x=oldx; - lastMousePos.y=oldy; - gameCamera.transitionVH(-(y - oldy) * ymult, (oldx - x) * xmult); - } - mouseX=lastMousePos.x; - mouseY=lastMousePos.y; - ::Shared::Platform::Window::revertMousePos(); - - return; - } - else if(currentCameraFollowUnit==NULL) { - //if(Window::isKeyDown() == false) - if(!camLeftButtonDown && !camRightButtonDown && !camUpButtonDown && !camDownButtonDown) - { - if(ms->get(mbLeft) && metrics.isInMinimap(x, y)) { - int xm= x - metrics.getMinimapX(); - int ym= y - metrics.getMinimapY(); - - Map *map= world.getMap(); - int xCell= static_cast(xm * (static_cast(map->getW()) / metrics.getMinimapW())); - int yCell= static_cast(map->getH() - ym * (static_cast(map->getH()) / metrics.getMinimapH())); - - if(map->isInside(xCell, yCell) && map->isInsideSurface(map->toSurfCoords(Vec2i(xCell,yCell)))) { - if(gui.isSelectingPos()){ - gui.mouseDownLeftGraphics(xCell, yCell, true); - } - else - { - if(cameraDragAllowed == true) { - gameCamera.setPos(Vec2f(static_cast(xCell), static_cast(yCell))); - } - } - } - } - else { - bool mouseMoveScrollsWorld = Config::getInstance().getBool("MouseMoveScrollsWorld","true"); - if(mouseMoveScrollsWorld == true) { - if (y < 10) { - gameCamera.setMoveZ(-scrollSpeed); - } - else if (y > metrics.getVirtualH() - 10) { - gameCamera.setMoveZ(scrollSpeed); - } - else { - gameCamera.setMoveZ(0); - } - - if (x < 10) { - gameCamera.setMoveX(-scrollSpeed); - } - else if (x > metrics.getVirtualW() - 10) { - gameCamera.setMoveX(scrollSpeed); - } - else { - gameCamera.setMoveX(0); - } - } - } - } - - if(switchTeamConfirmMessageBox.getEnabled() == true) { - switchTeamConfirmMessageBox.mouseMove(x,y); - } - - if(disconnectPlayerConfirmMessageBox.getEnabled() == true) { - disconnectPlayerConfirmMessageBox.mouseMove(x,y); - } - - if (mainMessageBox.getEnabled()) { - mainMessageBox.mouseMove(x, y); - } - if (errorMessageBox.getEnabled()) { - errorMessageBox.mouseMove(x, y); - } - if (scriptManager.getMessageBox()->getEnabled()) { - scriptManager.getMessageBox()->mouseMove(x, y); - } - //else if (saveBox) { - // saveBox->mouseMove(x, y); - //} else { - // //graphics - gui.mouseMoveGraphics(x, y); - //} - } - - //display - if ( !gui.isSelecting() && !gui.isSelectingPos()) { - if (!gui.isSelectingPos()) { - if(metrics.isInDisplay(x, y)){ - gui.mouseMoveDisplay(x - metrics.getDisplayX(), y - metrics.getDisplayY()); - } - else { - gui.mouseMoveOutsideDisplay(); - } - } - } - - lastMousePos.x = mouseX; - lastMousePos.y = mouseY; - - Renderer &renderer= Renderer::getInstance(); - renderer.ccomputePosition(Vec2i(mouseX, mouseY), mouseCellPos); - } - catch(const exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,szBuf); - - NetworkManager &networkManager= NetworkManager::getInstance(); - if(networkManager.getGameNetworkInterface() != NULL) { - GameNetworkInterface *networkInterface = NetworkManager::getInstance().getGameNetworkInterface(); - networkInterface->sendTextMessage(szBuf,-1,true,""); - sleep(10); - networkManager.getGameNetworkInterface()->quitGame(true); - } - ErrorDisplayMessage(ex.what(),true); - } + if (this->masterserverMode == true) { + return; + } + + try { + if (gameStarted == false || totalRenderFps <= 0) { + return; + } + if (currentUIState != NULL) { + currentUIState->mouseMove(x, y, ms); + return; + } + + popupMenu.mouseMove(x, y); + popupMenuSwitchTeams.mouseMove(x, y); + popupMenuDisconnectPlayer.mouseMove(x, y); + + const Metrics &metrics = Metrics::getInstance(); + + mouseX = x; + mouseY = y; + + if (ms->get(mbCenter)) { + mouseMoved = true; + if (currentCameraFollowUnit == NULL) { + float ymult = 0.2f; + float xmult = 0.2f; + + Vec2i oldPos = ::Shared::Platform::Window::getOldMousePos(); + int oldx = (oldPos.x * metrics.getVirtualW() / metrics.getScreenW()); + int oldy = ((metrics.getScreenH() - oldPos.y) * metrics.getVirtualH() / + metrics.getScreenH()); + lastMousePos.x = oldx; + lastMousePos.y = oldy; + gameCamera.transitionVH(-(y - oldy) * ymult, (oldx - x) * xmult); + } + mouseX = lastMousePos.x; + mouseY = lastMousePos.y; + ::Shared::Platform::Window::revertMousePos(); + + return; + } else if (currentCameraFollowUnit == NULL) { + // if(Window::isKeyDown() == false) + if (!camLeftButtonDown && !camRightButtonDown && !camUpButtonDown && + !camDownButtonDown) { + if (ms->get(mbLeft) && metrics.isInMinimap(x, y)) { + int xm = x - metrics.getMinimapX(); + int ym = y - metrics.getMinimapY(); + + Map *map = world.getMap(); + int xCell = static_cast( + xm * (static_cast(map->getW()) / metrics.getMinimapW())); + int yCell = static_cast( + map->getH() - + ym * (static_cast(map->getH()) / metrics.getMinimapH())); + + if (map->isInside(xCell, yCell) && + map->isInsideSurface(map->toSurfCoords(Vec2i(xCell, yCell)))) { + if (gui.isSelectingPos()) { + gui.mouseDownLeftGraphics(xCell, yCell, true); + } else { + if (cameraDragAllowed == true) { + gameCamera.setPos(Vec2f(static_cast(xCell), + static_cast(yCell))); + } + } + } + } else { + bool mouseMoveScrollsWorld = + Config::getInstance().getBool("MouseMoveScrollsWorld", "true"); + if (mouseMoveScrollsWorld == true) { + if (y < 10) { + gameCamera.setMoveZ(-scrollSpeed); + } else if (y > metrics.getVirtualH() - 10) { + gameCamera.setMoveZ(scrollSpeed); + } else { + gameCamera.setMoveZ(0); + } + + if (x < 10) { + gameCamera.setMoveX(-scrollSpeed); + } else if (x > metrics.getVirtualW() - 10) { + gameCamera.setMoveX(scrollSpeed); + } else { + gameCamera.setMoveX(0); + } + } + } + } + + if (switchTeamConfirmMessageBox.getEnabled() == true) { + switchTeamConfirmMessageBox.mouseMove(x, y); + } + + if (disconnectPlayerConfirmMessageBox.getEnabled() == true) { + disconnectPlayerConfirmMessageBox.mouseMove(x, y); + } + + if (mainMessageBox.getEnabled()) { + mainMessageBox.mouseMove(x, y); + } + if (errorMessageBox.getEnabled()) { + errorMessageBox.mouseMove(x, y); + } + if (scriptManager.getMessageBox()->getEnabled()) { + scriptManager.getMessageBox()->mouseMove(x, y); + } + // else if (saveBox) { + // saveBox->mouseMove(x, y); + // } else { + // //graphics + gui.mouseMoveGraphics(x, y); + //} + } + + // display + if (!gui.isSelecting() && !gui.isSelectingPos()) { + if (!gui.isSelectingPos()) { + if (metrics.isInDisplay(x, y)) { + gui.mouseMoveDisplay(x - metrics.getDisplayX(), + y - metrics.getDisplayY()); + } else { + gui.mouseMoveOutsideDisplay(); + } + } + } + + lastMousePos.x = mouseX; + lastMousePos.y = mouseY; + + Renderer &renderer = Renderer::getInstance(); + renderer.ccomputePosition(Vec2i(mouseX, mouseY), mouseCellPos); + } catch (const exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, szBuf); + + NetworkManager &networkManager = NetworkManager::getInstance(); + if (networkManager.getGameNetworkInterface() != NULL) { + GameNetworkInterface *networkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + networkInterface->sendTextMessage(szBuf, -1, true, ""); + sleep(10); + networkManager.getGameNetworkInterface()->quitGame(true); + } + ErrorDisplayMessage(ex.what(), true); + } } -bool Game::isValidMouseCellPos() const{ - if(world.getMap() == NULL){ - return false; - } - else { - return world.getMap()->isInside(mouseCellPos); - } +bool Game::isValidMouseCellPos() const { + if (world.getMap() == NULL) { + return false; + } else { + return world.getMap()->isInside(mouseCellPos); + } } void Game::eventMouseWheel(int x, int y, int zDelta) { - if(this->masterserverMode == true) { - return; - } - - if(currentUIState != NULL) { - currentUIState->eventMouseWheel(x, y, zDelta); - return; - } - - try { - gameCamera.zoom((float)zDelta / 60.0f); - } - catch(const exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,szBuf); - - NetworkManager &networkManager= NetworkManager::getInstance(); - if(networkManager.getGameNetworkInterface() != NULL) { - GameNetworkInterface *networkInterface = NetworkManager::getInstance().getGameNetworkInterface(); - networkInterface->sendTextMessage(szBuf,-1,true,""); - sleep(10); - networkManager.getGameNetworkInterface()->quitGame(true); - } - ErrorDisplayMessage(ex.what(),true); - } + if (this->masterserverMode == true) { + return; + } + + if (currentUIState != NULL) { + currentUIState->eventMouseWheel(x, y, zDelta); + return; + } + + try { + gameCamera.zoom((float)zDelta / 60.0f); + } catch (const exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, szBuf); + + NetworkManager &networkManager = NetworkManager::getInstance(); + if (networkManager.getGameNetworkInterface() != NULL) { + GameNetworkInterface *networkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + networkInterface->sendTextMessage(szBuf, -1, true, ""); + sleep(10); + networkManager.getGameNetworkInterface()->quitGame(true); + } + ErrorDisplayMessage(ex.what(), true); + } } void Game::startCameraFollowUnit() { - Selection *selection= gui.getSelectionPtr(); - if(selection->getCount() == 1) { - Unit *currentUnit = selection->getUnitPtr(0); - if(currentUnit != NULL) { - currentCameraFollowUnit = currentUnit; - getGameCameraPtr()->setState(GameCamera::sUnit); - getGameCameraPtr()->setPos(currentCameraFollowUnit->getCurrMidHeightVector()); - - int rotation=currentCameraFollowUnit->getRotation(); - getGameCameraPtr()->stop(); - getGameCameraPtr()->rotateToVH(0.0f,(540-rotation)%360); - getGameCameraPtr()->setHAng((540-rotation)%360); - getGameCameraPtr()->setVAng(0.0f); - } - } - else { - if(currentCameraFollowUnit != NULL) { - currentCameraFollowUnit = NULL; - } - } + Selection *selection = gui.getSelectionPtr(); + if (selection->getCount() == 1) { + Unit *currentUnit = selection->getUnitPtr(0); + if (currentUnit != NULL) { + currentCameraFollowUnit = currentUnit; + getGameCameraPtr()->setState(GameCamera::sUnit); + getGameCameraPtr()->setPos( + currentCameraFollowUnit->getCurrMidHeightVector()); + + int rotation = currentCameraFollowUnit->getRotation(); + getGameCameraPtr()->stop(); + getGameCameraPtr()->rotateToVH(0.0f, (540 - rotation) % 360); + getGameCameraPtr()->setHAng((540 - rotation) % 360); + getGameCameraPtr()->setVAng(0.0f); + } + } else { + if (currentCameraFollowUnit != NULL) { + currentCameraFollowUnit = NULL; + } + } } bool Game::textInput(std::string text) { - if(chatManager.getEditEnabled() == true) { - return chatManager.textInput(text); - } - return false; + if (chatManager.getEditEnabled() == true) { + return chatManager.textInput(text); + } + return false; } bool Game::sdlKeyDown(SDL_KeyboardEvent key) { - if(this->masterserverMode == true) { - return false; - } - if(gameStarted == false || totalRenderFps <= 0) { - return false; - } - - if(chatManager.getEditEnabled() == true) { - return false; - } - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - //group - for(int idx = 1; idx <= Selection::maxGroups; idx++) { - string keyName = "GroupUnitsKey" + intToStr(idx); - - SDL_Keycode groupHotKey = configKeys.getSDLKey(keyName.c_str()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] keyName [%s] group index = %d, key = [%c] [%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,keyName.c_str(),idx,groupHotKey,groupHotKey); - - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("input.keysym.mod = %d groupHotKey = %d key = %d (%d) [%s] isgroup = %d\n",key.keysym.mod,groupHotKey,key.keysym.sym,key.keysym.unicode,keyName.c_str(),isKeyPressed(groupHotKey,key)); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("input.keysym.mod = %d groupHotKey = %d key = (%d) [%s] isgroup = %d\n",key.keysym.mod,groupHotKey,key.keysym.sym,keyName.c_str(),isKeyPressed(groupHotKey,key)); - //printf(" group key check %d scancode:%d sym:%d groupHotKey=%d \n",idx,key.keysym.scancode,key.keysym.sym,groupHotKey); - if(key.keysym.sym==groupHotKey){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //printf("IS GROUP KEY %d scancode:%d sym:%d groupHotKey=%d \n",idx,key.keysym.scancode,key.keysym.sym,groupHotKey); - gui.groupKey(idx-1); - return true; - } - } - return false; + if (this->masterserverMode == true) { + return false; + } + if (gameStarted == false || totalRenderFps <= 0) { + return false; + } + + if (chatManager.getEditEnabled() == true) { + return false; + } + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + // group + for (int idx = 1; idx <= Selection::maxGroups; idx++) { + string keyName = "GroupUnitsKey" + intToStr(idx); + + SDL_Keycode groupHotKey = configKeys.getSDLKey(keyName.c_str()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] keyName [%s] group index " + "= %d, key = [%c] [%d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, keyName.c_str(), idx, + groupHotKey, groupHotKey); + + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("input.keysym.mod = %d + // groupHotKey = %d key = %d (%d) [%s] isgroup = + // %d\n",key.keysym.mod,groupHotKey,key.keysym.sym,key.keysym.unicode,keyName.c_str(),isKeyPressed(groupHotKey,key)); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("input.keysym.mod = %d groupHotKey = %d key = (%d) [%s] isgroup = " + "%d\n", + key.keysym.mod, groupHotKey, key.keysym.sym, keyName.c_str(), + isKeyPressed(groupHotKey, key)); + // printf(" group key check %d scancode:%d sym:%d groupHotKey=%d + // \n",idx,key.keysym.scancode,key.keysym.sym,groupHotKey); + if (key.keysym.sym == groupHotKey) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + // printf("IS GROUP KEY %d scancode:%d sym:%d groupHotKey=%d + // \n",idx,key.keysym.scancode,key.keysym.sym,groupHotKey); + gui.groupKey(idx - 1); + return true; + } + } + return false; } void Game::keyDown(SDL_KeyboardEvent key) { - if(this->masterserverMode == true) { - return; - } - - //printf("In game checking keypress for key [%d]\n",key.keysym.sym); - - try { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] key = [%c] [%d] gameStarted [%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,key.keysym.sym,key.keysym.sym, gameStarted); - if(gameStarted == false || totalRenderFps <= 0) { - return; - } - if(currentUIState != NULL) { - currentUIState->keyDown(key); - return; - } - - Lang &lang= Lang::getInstance(); - bool formerChatState=chatManager.getEditEnabled(); - //send key to the chat manager - chatManager.keyDown(key); - - if( formerChatState==false && chatManager.getEditEnabled()) { - camUpButtonDown= false; - camDownButtonDown = false; - camLeftButtonDown = false; - camRightButtonDown = false; - - gameCamera.stopMove(); - } - - //printf("GAME KEYDOWN #1\n"); - - if(chatManager.getEditEnabled() == false) { - //printf("GAME KEYDOWN #2\n"); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] key = [%d - %c]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,key.keysym.sym,key.keysym.sym); - - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf ("In [%s::%s Line: %d] key = [%d - %c] pausegame [%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,key,key,configKeys.getCharKey("PauseGame")); - - //printf("SDL [%d] key [%d][%d]\n",configKeys.getSDLKey("SetMarker"),key.keysym.unicode,key.keysym.sym); - bool setMarkerKeyAllowsModifier = false; - if( configKeys.getSDLKey("SetMarker") == SDLK_RALT || - configKeys.getSDLKey("SetMarker") == SDLK_LALT) { - setMarkerKeyAllowsModifier = true; - } - - //printf("In game checking keypress for key [%d] camera left [%d]\n",key.keysym.sym,configKeys.getSDLKey("CameraModeLeft")); - - if(isKeyPressed(configKeys.getSDLKey("RenderInGamePerformance"),key, false) == true) { - renderInGamePerformance = !renderInGamePerformance; - - Config::getInstance().setBool("PerformanceWarningEnabled",renderInGamePerformance, true); - } - //if(key == configKeys.getCharKey("RenderNetworkStatus")) { - else if(isKeyPressed(configKeys.getSDLKey("RenderNetworkStatus"),key, false) == true) { - renderNetworkStatus= !renderNetworkStatus; - } - //else if(key == configKeys.getCharKey("ShowFullConsole")) { - else if(isKeyPressed(configKeys.getSDLKey("ShowFullConsole"),key, false) == true) { - showFullConsole= true; - } - else if(isKeyPressed(configKeys.getSDLKey("SetMarker"),key, setMarkerKeyAllowsModifier) == true) { - setMarker= true; - } - //else if(key == configKeys.getCharKey("TogglePhotoMode")) { - else if(isKeyPressed(configKeys.getSDLKey("TogglePhotoMode"),key, false) == true) { - photoModeEnabled = !photoModeEnabled; - if( photoModeEnabled == true && - this->gameSettings.isNetworkGame() == false) { - gameCamera.setMaxHeight(PHOTO_MODE_MAXHEIGHT); - } - else if(photoModeEnabled == false) { - gameCamera.setMaxHeight(-1); - } - - } - //Toggle Healthbars - else if(isKeyPressed(configKeys.getSDLKey("ToggleHealthbars"),key, false) == true) { - switch (healthbarMode) { - case hbvUndefined: - healthbarMode=hbvOff; - console.addLine(lang.getString("Healthbar2")+": "+lang.getString("HealthbarsOff")); - break; - case hbvOff: - healthbarMode=hbvAlways; - console.addLine(lang.getString("Healthbar2")+": "+lang.getString("HealthbarsAlways")); - break; - case hbvAlways: - healthbarMode=hbvIfNeeded; - console.addLine(lang.getString("Healthbar2")+": "+lang.getString("HealthbarsIfNeeded")); - break; - case hbvIfNeeded: - healthbarMode=hbvSelected; - console.addLine(lang.getString("Healthbar2")+": "+lang.getString("HealthbarsSelected")); - break; - case hbvSelected: - healthbarMode=hbvSelected | hbvIfNeeded; - console.addLine(lang.getString("Healthbar2")+": "+lang.getString("HealthbarsSelectedOrNeeded")); - break; - case (hbvSelected | hbvIfNeeded): - healthbarMode=hbvUndefined; - console.addLine(lang.getString("Healthbar2")+": "+lang.getString("HealthbarsFactionDefault")); - break; - default: - printf("In [%s::%s Line: %d] Toggle Healthbars Hotkey - Invalid Value. Setting to default.\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - healthbarMode=hbvUndefined; - break; - } - } - //Toggle music - //else if(key == configKeys.getCharKey("ToggleMusic")) { - else if(isKeyPressed(configKeys.getSDLKey("ToggleMusic"),key, false) == true) { - - if(this->masterserverMode == false) { - Config &config = Config::getInstance(); - StrSound *gameMusic = world.getThisFaction()->getType()->getMusic(); - if(gameMusic != NULL) { - float configVolume = (config.getInt("SoundVolumeMusic") / 100.f); - float currentVolume = gameMusic->getVolume(); - if(currentVolume > 0) { - gameMusic->setVolume(0); - console.addLine(lang.getString("GameMusic") + " " + lang.getString("Off")); - } - else { - //If the config says zero, use the default music volume - gameMusic->setVolume(configVolume ? configVolume : 0.9); - console.addLine(lang.getString("GameMusic")); - } - } - } - } - //move camera left - //else if(key == configKeys.getCharKey("CameraModeLeft")) { - else if(isKeyPressed(configKeys.getSDLKey("CameraModeLeft"),key, false) == true) { - gameCamera.setMoveX(-1); - camLeftButtonDown=true; - } - //move camera right - //else if(key == configKeys.getCharKey("CameraModeRight")) { - else if(isKeyPressed(configKeys.getSDLKey("CameraModeRight"),key, false) == true) { - gameCamera.setMoveX(1); - camRightButtonDown=true; - } - //move camera up - //else if(key == configKeys.getCharKey("CameraModeUp")) { - else if(isKeyPressed(configKeys.getSDLKey("CameraModeUp"),key, false) == true) { - gameCamera.setMoveZ(1); - camUpButtonDown=true; - } - //move camera down - //else if(key == configKeys.getCharKey("CameraModeDown")) { - else if(isKeyPressed(configKeys.getSDLKey("CameraModeDown"),key, false) == true) { - gameCamera.setMoveZ(-1); - camDownButtonDown=true; - } - //change camera mode - //else if(key == configKeys.getCharKey("FreeCameraMode")) { - else if(isKeyPressed(configKeys.getSDLKey("FreeCameraMode"),key, false) == true) { - if(gameCamera.getState()==GameCamera::sFree) - { - gameCamera.setState(GameCamera::sGame); - string stateString= gameCamera.getState()==GameCamera::sGame? lang.getString("GameCamera"): lang.getString("FreeCamera"); - console.addLine(lang.getString("CameraModeSet")+" "+ stateString); - } - else if(gameCamera.getState()==GameCamera::sGame) - { - gameCamera.setState(GameCamera::sFree); - string stateString= gameCamera.getState()==GameCamera::sGame? lang.getString("GameCamera"): lang.getString("FreeCamera"); - console.addLine(lang.getString("CameraModeSet")+" "+ stateString); - } - //else ignore! - } - //reset camera mode to normal - //else if(key == configKeys.getCharKey("ResetCameraMode")) { - else if(isKeyPressed(configKeys.getSDLKey("ResetCameraMode"),key, false) == true) { - if(currentCameraFollowUnit != NULL) { - currentCameraFollowUnit = NULL; - } - gameCamera.setState(GameCamera::sGame); - } - //pause - //else if(key == configKeys.getCharKey("PauseGame")) { - else if(isKeyPressed(configKeys.getSDLKey("PauseGame"),key, false) == true) { - //printf("Toggle pause paused = %d\n",paused); - //setPaused(!paused); - - bool allowAdminMenuItems = false; - NetworkManager &networkManager= NetworkManager::getInstance(); - NetworkRole role = networkManager.getNetworkRole(); - if(role == nrServer) { - allowAdminMenuItems = true; - } - else if(role == nrClient) { - ClientInterface *clientInterface = dynamic_cast(networkManager.getClientInterface()); - - if(clientInterface != NULL && - gameSettings.getMasterserver_admin() == clientInterface->getSessionKey()) { - allowAdminMenuItems = true; - } - } - - if(allowAdminMenuItems) { - if(getPaused() == false) { - commander.tryPauseGame(false,false); - } - else { - commander.tryResumeGame(false,false); - } - } - } - else if(isKeyPressed(configKeys.getSDLKey("ExtraTeamColorMarker"),key, false) == true) { - //printf("Toggle ExtraTeamColorMarker\n"); - toggleTeamColorMarker(); - } - //switch display color - //else if(key == configKeys.getCharKey("ChangeFontColor")) { - else if(isKeyPressed(configKeys.getSDLKey("ChangeFontColor"),key, false) == true) { - gui.switchToNextDisplayColor(); - } - //increment speed - //else if(key == configKeys.getCharKey("GameSpeedIncrease")) { - else if(isKeyPressed(configKeys.getSDLKey("GameSpeedIncrease"),key, false) == true) { - bool speedChangesAllowed= !NetworkManager::getInstance().isNetworkGameWithConnectedClients(); - if(speedChangesAllowed){ - incSpeed(); - } - } - //decrement speed - //else if(key == configKeys.getCharKey("GameSpeedDecrease")) { - else if(isKeyPressed(configKeys.getSDLKey("GameSpeedDecrease"),key, false) == true) { - bool speedChangesAllowed= !NetworkManager::getInstance().isNetworkGameWithConnectedClients(); - if(speedChangesAllowed){ - decSpeed(); - } - } - else if(isKeyPressed(configKeys.getSDLKey("BookmarkAdd"),key, false) == true) { - startMarkCell(); - } - else if(isKeyPressed(configKeys.getSDLKey("BookmarkRemove"),key, false) == true) { - isUnMarkCellEnabled = true; - } - else if(isKeyPressed(configKeys.getSDLKey("CameraFollowSelectedUnit"),key, false) == true) { - startCameraFollowUnit(); - } - //exit - else if(isKeyPressed(configKeys.getSDLKey("ExitKey"),key, false) == true) { - popupMenu.setEnabled(!popupMenu.getEnabled()); - popupMenu.setVisible(popupMenu.getEnabled()); - } - - //hotkeys - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] gameCamera.getState() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,gameCamera.getState()); - - if(gameCamera.getState() != GameCamera::sFree){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] key = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,key); - - gui.hotKey(key); - } - else { - //rotate camera leftt - //if(key == configKeys.getCharKey("CameraRotateLeft")) { - if(isKeyPressed(configKeys.getSDLKey("CameraRotateLeft"),key) == true) { - gameCamera.setRotate(-1); - } - //rotate camera right - //else if(key == configKeys.getCharKey("CameraRotateRight")){ - else if(isKeyPressed(configKeys.getSDLKey("CameraRotateRight"),key) == true) { - gameCamera.setRotate(1); - } - //camera up - //else if(key == configKeys.getCharKey("CameraRotateUp")) { - else if(isKeyPressed(configKeys.getSDLKey("CameraRotateUp"),key) == true) { - gameCamera.setMoveY(1); - } - //camera down - //else if(key == configKeys.getCharKey("CameraRotateDown")) { - else if(isKeyPressed(configKeys.getSDLKey("CameraRotateDown"),key) == true) { - gameCamera.setMoveY(-1); - } - } - - if(isKeyPressed(configKeys.getSDLKey("SaveGame"),key) == true) { - saveGame(); - } - } - } - catch(const exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,szBuf); - - NetworkManager &networkManager= NetworkManager::getInstance(); - if(networkManager.getGameNetworkInterface() != NULL) { - GameNetworkInterface *networkInterface = NetworkManager::getInstance().getGameNetworkInterface(); - networkInterface->sendTextMessage(szBuf,-1,true,""); - sleep(10); - networkManager.getGameNetworkInterface()->quitGame(true); - } - ErrorDisplayMessage(ex.what(),true); - } + if (this->masterserverMode == true) { + return; + } + + // printf("In game checking keypress for key [%d]\n",key.keysym.sym); + + try { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] key = [%c] [%d] gameStarted [%d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, key.keysym.sym, key.keysym.sym, gameStarted); + if (gameStarted == false || totalRenderFps <= 0) { + return; + } + if (currentUIState != NULL) { + currentUIState->keyDown(key); + return; + } + + Lang &lang = Lang::getInstance(); + bool formerChatState = chatManager.getEditEnabled(); + // send key to the chat manager + chatManager.keyDown(key); + + if (formerChatState == false && chatManager.getEditEnabled()) { + camUpButtonDown = false; + camDownButtonDown = false; + camLeftButtonDown = false; + camRightButtonDown = false; + + gameCamera.stopMove(); + } + + // printf("GAME KEYDOWN #1\n"); + + if (chatManager.getEditEnabled() == false) { + // printf("GAME KEYDOWN #2\n"); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d] key = [%d - %c]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, key.keysym.sym, key.keysym.sym); + + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf ("In [%s::%s Line: %d] key + // = [%d - %c] pausegame + // [%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,key,key,configKeys.getCharKey("PauseGame")); + + // printf("SDL [%d] key + // [%d][%d]\n",configKeys.getSDLKey("SetMarker"),key.keysym.unicode,key.keysym.sym); + bool setMarkerKeyAllowsModifier = false; + if (configKeys.getSDLKey("SetMarker") == SDLK_RALT || + configKeys.getSDLKey("SetMarker") == SDLK_LALT) { + setMarkerKeyAllowsModifier = true; + } + + // printf("In game checking keypress for key [%d] camera left + // [%d]\n",key.keysym.sym,configKeys.getSDLKey("CameraModeLeft")); + + if (isKeyPressed(configKeys.getSDLKey("RenderInGamePerformance"), key, + false) == true) { + renderInGamePerformance = !renderInGamePerformance; + + Config::getInstance().setBool("PerformanceWarningEnabled", + renderInGamePerformance, true); + } + // if(key == configKeys.getCharKey("RenderNetworkStatus")) { + else if (isKeyPressed(configKeys.getSDLKey("RenderNetworkStatus"), key, + false) == true) { + renderNetworkStatus = !renderNetworkStatus; + } + // else if(key == configKeys.getCharKey("ShowFullConsole")) { + else if (isKeyPressed(configKeys.getSDLKey("ShowFullConsole"), key, + false) == true) { + showFullConsole = true; + } else if (isKeyPressed(configKeys.getSDLKey("SetMarker"), key, + setMarkerKeyAllowsModifier) == true) { + setMarker = true; + } + // else if(key == configKeys.getCharKey("TogglePhotoMode")) { + else if (isKeyPressed(configKeys.getSDLKey("TogglePhotoMode"), key, + false) == true) { + photoModeEnabled = !photoModeEnabled; + if (photoModeEnabled == true && + this->gameSettings.isNetworkGame() == false) { + gameCamera.setMaxHeight(PHOTO_MODE_MAXHEIGHT); + } else if (photoModeEnabled == false) { + gameCamera.setMaxHeight(-1); + } + + } + // Toggle Healthbars + else if (isKeyPressed(configKeys.getSDLKey("ToggleHealthbars"), key, + false) == true) { + switch (healthbarMode) { + case hbvUndefined: + healthbarMode = hbvOff; + console.addLine(lang.getString("Healthbar2") + ": " + + lang.getString("HealthbarsOff")); + break; + case hbvOff: + healthbarMode = hbvAlways; + console.addLine(lang.getString("Healthbar2") + ": " + + lang.getString("HealthbarsAlways")); + break; + case hbvAlways: + healthbarMode = hbvIfNeeded; + console.addLine(lang.getString("Healthbar2") + ": " + + lang.getString("HealthbarsIfNeeded")); + break; + case hbvIfNeeded: + healthbarMode = hbvSelected; + console.addLine(lang.getString("Healthbar2") + ": " + + lang.getString("HealthbarsSelected")); + break; + case hbvSelected: + healthbarMode = hbvSelected | hbvIfNeeded; + console.addLine(lang.getString("Healthbar2") + ": " + + lang.getString("HealthbarsSelectedOrNeeded")); + break; + case (hbvSelected | hbvIfNeeded): + healthbarMode = hbvUndefined; + console.addLine(lang.getString("Healthbar2") + ": " + + lang.getString("HealthbarsFactionDefault")); + break; + default: + printf("In [%s::%s Line: %d] Toggle Healthbars Hotkey - Invalid " + "Value. Setting to default.\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + healthbarMode = hbvUndefined; + break; + } + } + // Toggle music + // else if(key == configKeys.getCharKey("ToggleMusic")) { + else if (isKeyPressed(configKeys.getSDLKey("ToggleMusic"), key, false) == + true) { + + if (this->masterserverMode == false) { + Config &config = Config::getInstance(); + StrSound *gameMusic = world.getThisFaction()->getType()->getMusic(); + if (gameMusic != NULL) { + float configVolume = (config.getInt("SoundVolumeMusic") / 100.f); + float currentVolume = gameMusic->getVolume(); + if (currentVolume > 0) { + gameMusic->setVolume(0); + console.addLine(lang.getString("GameMusic") + " " + + lang.getString("Off")); + } else { + // If the config says zero, use the default music volume + gameMusic->setVolume(configVolume ? configVolume : 0.9); + console.addLine(lang.getString("GameMusic")); + } + } + } + } + // move camera left + // else if(key == configKeys.getCharKey("CameraModeLeft")) { + else if (isKeyPressed(configKeys.getSDLKey("CameraModeLeft"), key, + false) == true) { + gameCamera.setMoveX(-1); + camLeftButtonDown = true; + } + // move camera right + // else if(key == configKeys.getCharKey("CameraModeRight")) { + else if (isKeyPressed(configKeys.getSDLKey("CameraModeRight"), key, + false) == true) { + gameCamera.setMoveX(1); + camRightButtonDown = true; + } + // move camera up + // else if(key == configKeys.getCharKey("CameraModeUp")) { + else if (isKeyPressed(configKeys.getSDLKey("CameraModeUp"), key, false) == + true) { + gameCamera.setMoveZ(1); + camUpButtonDown = true; + } + // move camera down + // else if(key == configKeys.getCharKey("CameraModeDown")) { + else if (isKeyPressed(configKeys.getSDLKey("CameraModeDown"), key, + false) == true) { + gameCamera.setMoveZ(-1); + camDownButtonDown = true; + } + // change camera mode + // else if(key == configKeys.getCharKey("FreeCameraMode")) { + else if (isKeyPressed(configKeys.getSDLKey("FreeCameraMode"), key, + false) == true) { + if (gameCamera.getState() == GameCamera::sFree) { + gameCamera.setState(GameCamera::sGame); + string stateString = gameCamera.getState() == GameCamera::sGame + ? lang.getString("GameCamera") + : lang.getString("FreeCamera"); + console.addLine(lang.getString("CameraModeSet") + " " + stateString); + } else if (gameCamera.getState() == GameCamera::sGame) { + gameCamera.setState(GameCamera::sFree); + string stateString = gameCamera.getState() == GameCamera::sGame + ? lang.getString("GameCamera") + : lang.getString("FreeCamera"); + console.addLine(lang.getString("CameraModeSet") + " " + stateString); + } + // else ignore! + } + // reset camera mode to normal + // else if(key == configKeys.getCharKey("ResetCameraMode")) { + else if (isKeyPressed(configKeys.getSDLKey("ResetCameraMode"), key, + false) == true) { + if (currentCameraFollowUnit != NULL) { + currentCameraFollowUnit = NULL; + } + gameCamera.setState(GameCamera::sGame); + } + // pause + // else if(key == configKeys.getCharKey("PauseGame")) { + else if (isKeyPressed(configKeys.getSDLKey("PauseGame"), key, false) == + true) { + // printf("Toggle pause paused = %d\n",paused); + // setPaused(!paused); + + bool allowAdminMenuItems = false; + NetworkManager &networkManager = NetworkManager::getInstance(); + NetworkRole role = networkManager.getNetworkRole(); + if (role == nrServer) { + allowAdminMenuItems = true; + } else if (role == nrClient) { + ClientInterface *clientInterface = dynamic_cast( + networkManager.getClientInterface()); + + if (clientInterface != NULL && gameSettings.getMasterserver_admin() == + clientInterface->getSessionKey()) { + allowAdminMenuItems = true; + } + } + + if (allowAdminMenuItems) { + if (getPaused() == false) { + commander.tryPauseGame(false, false); + } else { + commander.tryResumeGame(false, false); + } + } + } else if (isKeyPressed(configKeys.getSDLKey("ExtraTeamColorMarker"), key, + false) == true) { + // printf("Toggle ExtraTeamColorMarker\n"); + toggleTeamColorMarker(); + } + // switch display color + // else if(key == configKeys.getCharKey("ChangeFontColor")) { + else if (isKeyPressed(configKeys.getSDLKey("ChangeFontColor"), key, + false) == true) { + gui.switchToNextDisplayColor(); + } + // increment speed + // else if(key == configKeys.getCharKey("GameSpeedIncrease")) { + else if (isKeyPressed(configKeys.getSDLKey("GameSpeedIncrease"), key, + false) == true) { + bool speedChangesAllowed = + !NetworkManager::getInstance().isNetworkGameWithConnectedClients(); + if (speedChangesAllowed) { + incSpeed(); + } + } + // decrement speed + // else if(key == configKeys.getCharKey("GameSpeedDecrease")) { + else if (isKeyPressed(configKeys.getSDLKey("GameSpeedDecrease"), key, + false) == true) { + bool speedChangesAllowed = + !NetworkManager::getInstance().isNetworkGameWithConnectedClients(); + if (speedChangesAllowed) { + decSpeed(); + } + } else if (isKeyPressed(configKeys.getSDLKey("BookmarkAdd"), key, + false) == true) { + startMarkCell(); + } else if (isKeyPressed(configKeys.getSDLKey("BookmarkRemove"), key, + false) == true) { + isUnMarkCellEnabled = true; + } else if (isKeyPressed(configKeys.getSDLKey("CameraFollowSelectedUnit"), + key, false) == true) { + startCameraFollowUnit(); + } + // exit + else if (isKeyPressed(configKeys.getSDLKey("ExitKey"), key, false) == + true) { + popupMenu.setEnabled(!popupMenu.getEnabled()); + popupMenu.setVisible(popupMenu.getEnabled()); + } + + // hotkeys + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] gameCamera.getState() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, gameCamera.getState()); + + if (gameCamera.getState() != GameCamera::sFree) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d] key = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, key); + + gui.hotKey(key); + } else { + // rotate camera leftt + // if(key == configKeys.getCharKey("CameraRotateLeft")) { + if (isKeyPressed(configKeys.getSDLKey("CameraRotateLeft"), key) == + true) { + gameCamera.setRotate(-1); + } + // rotate camera right + // else if(key == configKeys.getCharKey("CameraRotateRight")){ + else if (isKeyPressed(configKeys.getSDLKey("CameraRotateRight"), key) == + true) { + gameCamera.setRotate(1); + } + // camera up + // else if(key == configKeys.getCharKey("CameraRotateUp")) { + else if (isKeyPressed(configKeys.getSDLKey("CameraRotateUp"), key) == + true) { + gameCamera.setMoveY(1); + } + // camera down + // else if(key == configKeys.getCharKey("CameraRotateDown")) { + else if (isKeyPressed(configKeys.getSDLKey("CameraRotateDown"), key) == + true) { + gameCamera.setMoveY(-1); + } + } + + if (isKeyPressed(configKeys.getSDLKey("SaveGame"), key) == true) { + saveGame(); + } + } + } catch (const exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, szBuf); + + NetworkManager &networkManager = NetworkManager::getInstance(); + if (networkManager.getGameNetworkInterface() != NULL) { + GameNetworkInterface *networkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + networkInterface->sendTextMessage(szBuf, -1, true, ""); + sleep(10); + networkManager.getGameNetworkInterface()->quitGame(true); + } + ErrorDisplayMessage(ex.what(), true); + } } void Game::keyUp(SDL_KeyboardEvent key) { - if(this->masterserverMode == true) { - return; - } - - try { - if(gameStarted == false || totalRenderFps <= 0) { - return; - } - if(currentUIState != NULL) { - currentUIState->keyUp(key); - return; - } - - if(chatManager.getEditEnabled()) { - //send key to the chat manager - chatManager.keyUp(key); - } - else { - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - - //if(key == configKeys.getCharKey("ShowFullConsole")) { - if(isKeyPressed(configKeys.getSDLKey("ShowFullConsole"),key) == true) { - showFullConsole= false; - } - else if(isKeyPressed(configKeys.getSDLKey("SetMarker"),key) == true) { - setMarker= false; - } - //else if(key == configKeys.getCharKey("CameraRotateLeft") || - // key == configKeys.getCharKey("CameraRotateRight")) { - else if(isKeyPressed(configKeys.getSDLKey("CameraRotateLeft"),key) == true || - isKeyPressed(configKeys.getSDLKey("CameraRotateRight"),key) == true) { - gameCamera.setRotate(0); - } - //else if(key == configKeys.getCharKey("CameraRotateDown") || - // key == configKeys.getCharKey("CameraRotateUp")) { - else if(isKeyPressed(configKeys.getSDLKey("CameraRotateDown"),key) == true || - isKeyPressed(configKeys.getSDLKey("CameraRotateUp"),key) == true) { - - gameCamera.setMoveY(0); - } - //else if(key == configKeys.getCharKey("CameraModeUp")){ - else if(isKeyPressed(configKeys.getSDLKey("CameraModeUp"),key) == true) { - gameCamera.setMoveZ(0); - camUpButtonDown= false; - calcCameraMoveZ(); - } - //else if(key == configKeys.getCharKey("CameraModeDown")){ - else if(isKeyPressed(configKeys.getSDLKey("CameraModeDown"),key) == true) { - gameCamera.setMoveZ(0); - camDownButtonDown= false; - calcCameraMoveZ(); - } - //else if(key == configKeys.getCharKey("CameraModeLeft")){ - else if(isKeyPressed(configKeys.getSDLKey("CameraModeLeft"),key) == true) { - gameCamera.setMoveX(0); - camLeftButtonDown= false; - calcCameraMoveX(); - } - //else if(key == configKeys.getCharKey("CameraModeRight")){ - else if(isKeyPressed(configKeys.getSDLKey("CameraModeRight"),key) == true) { - gameCamera.setMoveX(0); - camRightButtonDown= false; - calcCameraMoveX(); - } - } - } - catch(const exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,szBuf); - - NetworkManager &networkManager= NetworkManager::getInstance(); - if(networkManager.getGameNetworkInterface() != NULL) { - GameNetworkInterface *networkInterface = NetworkManager::getInstance().getGameNetworkInterface(); - networkInterface->sendTextMessage(szBuf,-1,true,""); - sleep(10); - networkManager.getGameNetworkInterface()->quitGame(true); - } - ErrorDisplayMessage(ex.what(),true); - } -} + if (this->masterserverMode == true) { + return; + } -void Game::calcCameraMoveX(){ - //move camera left - if(camLeftButtonDown == true){ - gameCamera.setMoveX(-1); - } - //move camera right - else if(camRightButtonDown == true){ - gameCamera.setMoveX(1); - } + try { + if (gameStarted == false || totalRenderFps <= 0) { + return; + } + if (currentUIState != NULL) { + currentUIState->keyUp(key); + return; + } + + if (chatManager.getEditEnabled()) { + // send key to the chat manager + chatManager.keyUp(key); + } else { + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + + // if(key == configKeys.getCharKey("ShowFullConsole")) { + if (isKeyPressed(configKeys.getSDLKey("ShowFullConsole"), key) == true) { + showFullConsole = false; + } else if (isKeyPressed(configKeys.getSDLKey("SetMarker"), key) == true) { + setMarker = false; + } + // else if(key == configKeys.getCharKey("CameraRotateLeft") || + // key == configKeys.getCharKey("CameraRotateRight")) { + else if (isKeyPressed(configKeys.getSDLKey("CameraRotateLeft"), key) == + true || + isKeyPressed(configKeys.getSDLKey("CameraRotateRight"), key) == + true) { + gameCamera.setRotate(0); + } + // else if(key == configKeys.getCharKey("CameraRotateDown") || + // key == configKeys.getCharKey("CameraRotateUp")) { + else if (isKeyPressed(configKeys.getSDLKey("CameraRotateDown"), key) == + true || + isKeyPressed(configKeys.getSDLKey("CameraRotateUp"), key) == + true) { + + gameCamera.setMoveY(0); + } + // else if(key == configKeys.getCharKey("CameraModeUp")){ + else if (isKeyPressed(configKeys.getSDLKey("CameraModeUp"), key) == + true) { + gameCamera.setMoveZ(0); + camUpButtonDown = false; + calcCameraMoveZ(); + } + // else if(key == configKeys.getCharKey("CameraModeDown")){ + else if (isKeyPressed(configKeys.getSDLKey("CameraModeDown"), key) == + true) { + gameCamera.setMoveZ(0); + camDownButtonDown = false; + calcCameraMoveZ(); + } + // else if(key == configKeys.getCharKey("CameraModeLeft")){ + else if (isKeyPressed(configKeys.getSDLKey("CameraModeLeft"), key) == + true) { + gameCamera.setMoveX(0); + camLeftButtonDown = false; + calcCameraMoveX(); + } + // else if(key == configKeys.getCharKey("CameraModeRight")){ + else if (isKeyPressed(configKeys.getSDLKey("CameraModeRight"), key) == + true) { + gameCamera.setMoveX(0); + camRightButtonDown = false; + calcCameraMoveX(); + } + } + } catch (const exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, szBuf); + + NetworkManager &networkManager = NetworkManager::getInstance(); + if (networkManager.getGameNetworkInterface() != NULL) { + GameNetworkInterface *networkInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + networkInterface->sendTextMessage(szBuf, -1, true, ""); + sleep(10); + networkManager.getGameNetworkInterface()->quitGame(true); + } + ErrorDisplayMessage(ex.what(), true); + } } -void Game::calcCameraMoveZ(){ - //move camera up - if(camUpButtonDown == true){ - gameCamera.setMoveZ(1); - } - //move camera down - else if(camDownButtonDown == true){ - gameCamera.setMoveZ(-1); - } +void Game::calcCameraMoveX() { + // move camera left + if (camLeftButtonDown == true) { + gameCamera.setMoveX(-1); + } + // move camera right + else if (camRightButtonDown == true) { + gameCamera.setMoveX(1); + } +} +void Game::calcCameraMoveZ() { + // move camera up + if (camUpButtonDown == true) { + gameCamera.setMoveZ(1); + } + // move camera down + else if (camDownButtonDown == true) { + gameCamera.setMoveZ(-1); + } } void Game::keyPress(SDL_KeyboardEvent c) { - if(this->masterserverMode == true) { - return; - } - - if(gameStarted == false || totalRenderFps <= 0) { - return; - } - if(currentUIState != NULL) { - currentUIState->keyPress(c); - return; - } - - chatManager.keyPress(c); + if (this->masterserverMode == true) { + return; + } + + if (gameStarted == false || totalRenderFps <= 0) { + return; + } + if (currentUIState != NULL) { + currentUIState->keyPress(c); + return; + } + + chatManager.keyPress(c); } Stats Game::getEndGameStats() { - Stats endStats; - endStats = *(world.getStats()); - //NetworkManager &networkManager= NetworkManager::getInstance(); - if (this->masterserverMode == true) { - endStats.setIsMasterserverMode(true); - } - return endStats; + Stats endStats; + endStats = *(world.getStats()); + // NetworkManager &networkManager= NetworkManager::getInstance(); + if (this->masterserverMode == true) { + endStats.setIsMasterserverMode(true); + } + return endStats; } Stats Game::quitGame() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(quitGameCalled == true) { - Stats endStats = getEndGameStats(); - return endStats; - } - quitGameCalled = true; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (quitGameCalled == true) { + Stats endStats = getEndGameStats(); + return endStats; + } + quitGameCalled = true; + + NetworkManager &networkManager = NetworkManager::getInstance(); + NetworkRole role = networkManager.getNetworkRole(); + string suffix = "_client"; + if (role == nrServer) { + suffix = "_server"; + } + this->DumpCRCWorldLogIfRequired(suffix); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled == + true) { + world.DumpWorldToLog(); + } + // printf("Check savegame\n"); + // printf("Saving...\n"); + if (Config::getInstance().getBool("AutoTest")) { + this->saveGame(GameConstants::saveGameFileAutoTestDefault); + } + + Stats endStats = getEndGameStats(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // printf("In [%s::%s] Line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + NetworkManager::getInstance().end(); + // sleep(0); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + return endStats; +} - NetworkManager &networkManager= NetworkManager::getInstance(); - NetworkRole role = networkManager.getNetworkRole(); - string suffix = "_client"; - if(role == nrServer) { - suffix = "_server"; - } - this->DumpCRCWorldLogIfRequired(suffix); +void Game::DumpCRCWorldLogIfRequired(string fileSuffix) { + bool isNetworkGame = this->gameSettings.isNetworkGame(); + if (isNetworkGame == true) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf( + "Check save world CRC to log. isNetworkGame = %d fileSuffix = %s\n", + isNetworkGame, fileSuffix.c_str()); + + GameSettings *settings = world.getGameSettingsPtr(); + if (settings != NULL && + (isFlagType1BitEnabled(ft1_network_synch_checks_verbose) == true || + isFlagType1BitEnabled(ft1_network_synch_checks) == true)) { + string debugCRCWorldLogFile = Config::getInstance().getString( + "DebugCRCWorldLogFile", "debugCRCWorld.log"); + debugCRCWorldLogFile += fileSuffix; + + if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { + debugCRCWorldLogFile = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + + debugCRCWorldLogFile; + } else { + string userData = Config::getInstance().getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + debugCRCWorldLogFile = userData + debugCRCWorldLogFile; + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled == true) { - world.DumpWorldToLog(); - } - //printf("Check savegame\n"); - //printf("Saving...\n"); - if(Config::getInstance().getBool("AutoTest")){ - this->saveGame(GameConstants::saveGameFileAutoTestDefault); - } + printf("Save to log debugCRCWorldLogFile = %s\n", + debugCRCWorldLogFile.c_str()); - Stats endStats = getEndGameStats(); +#if defined(WIN32) && !defined(__MINGW32__) + FILE *fp = _wfopen(utf8_decode(debugCRCWorldLogFile).c_str(), L"w"); + std::ofstream logFile(fp); +#else + std::ofstream logFile; + logFile.open(debugCRCWorldLogFile.c_str(), + ios_base::out | ios_base::trunc); +#endif + logFile << "World CRC debug information:" << std::endl; + logFile << "============================" << std::endl; + logFile << "Software version: " << glestVersionString << "-" + << getCompilerNameString() << "-" << getGITRevisionString() + << std::endl; + logFile << "Maximum framecount: " + << world.getFaction(0)->getCRC_DetailsForWorldFrameCount() + << std::endl; + + for (unsigned int worldFrameIndex = 0; + worldFrameIndex < + world.getFaction(0)->getCRC_DetailsForWorldFrameCount(); + ++worldFrameIndex) { + // factions (and their related info) + for (int i = 0; i < world.getFactionCount(); ++i) { + logFile << "Faction detail for index: " << i << std::endl; + logFile << "--------------------------" << std::endl; + + std::pair details = + world.getFaction(i)->getCRC_DetailsForWorldFrameIndex( + worldFrameIndex); + + logFile << string("** world frame: ") << details.first << std::endl; + logFile << details.second << std::endl; + } + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + logFile.close(); +#if defined(WIN32) && !defined(__MINGW32__) + if (fp) { + fclose(fp); + } +#endif + } + } +} - //printf("In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - NetworkManager::getInstance().end(); - //sleep(0); +void savePlayerStats(Game *game, Stats &endStats, + PlayerAchievementsInterface *playerStats) { + const double MIN_PLAY_TIME_MINUTES = 10.0; + + // Write out achievements here + double elapsedGameMinutes = + (game->getWorld()->getStats()->getFramesToCalculatePlaytime() / + GameConstants::updateFps / 60.0); + + for (int factionIndex = 0; factionIndex < game->getWorld()->getFactionCount(); + ++factionIndex) { + if (factionIndex == game->getWorld()->getThisFactionIndex()) { + // printf("\nWriting out game stats for Faction Index: %d won status: + // %d\n",factionIndex,endStats.getVictory(factionIndex)); + if (elapsedGameMinutes >= MIN_PLAY_TIME_MINUTES) { + int gamesPlayedCount = + playerStats->getStatAsInt( + EnumParser::getString(games_played).c_str()) + + 1; + playerStats->setStatAsInt( + EnumParser::getString(games_played).c_str(), + gamesPlayedCount); + + if (gamesPlayedCount >= 50 && + playerStats->isUnlocked(EnumParser::getString( + ACH_PLAY_FIFTY_GAMES) + .c_str()) == false) { + playerStats->unlock( + EnumParser::getString(ACH_PLAY_FIFTY_GAMES) + .c_str()); + } + if (gamesPlayedCount >= 100 && + playerStats->isUnlocked(EnumParser::getString( + ACH_PLAY_ONE_HUNDRED_GAMES) + .c_str()) == false) { + playerStats->unlock(EnumParser::getString( + ACH_PLAY_ONE_HUNDRED_GAMES) + .c_str()); + } + if (gamesPlayedCount >= 250 && + playerStats->isUnlocked(EnumParser::getString( + ACH_PLAY_TWO_HUNDRED_FIFTY_GAMES) + .c_str()) == false) { + playerStats->unlock(EnumParser::getString( + ACH_PLAY_TWO_HUNDRED_FIFTY_GAMES) + .c_str()); + } + if (gamesPlayedCount >= 500 && + playerStats->isUnlocked(EnumParser::getString( + ACH_PLAY_FIVE_HUNDRED_GAMES) + .c_str()) == false) { + playerStats->unlock(EnumParser::getString( + ACH_PLAY_FIVE_HUNDRED_GAMES) + .c_str()); + } + if (gamesPlayedCount > 1000 && + playerStats->isUnlocked(EnumParser::getString( + ACH_PLAY_OVER_THOUSAND_GAMES) + .c_str()) == false) { + playerStats->unlock(EnumParser::getString( + ACH_PLAY_OVER_THOUSAND_GAMES) + .c_str()); + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (NetworkManager::getInstance().isNetworkGame()) { + int networkGamesPlayedCount = + playerStats->getStatAsInt( + EnumParser::getString(network_games_played) + .c_str()) + + 1; + playerStats->setStatAsInt( + EnumParser::getString(network_games_played) + .c_str(), + networkGamesPlayedCount); + + if (networkGamesPlayedCount >= 50 && + playerStats->isUnlocked( + EnumParser::getString( + ACH_PLAY_FIFTY_GAMES_ONLINE) + .c_str()) == false) { + playerStats->unlock(EnumParser::getString( + ACH_PLAY_FIFTY_GAMES_ONLINE) + .c_str()); + } + if (networkGamesPlayedCount >= 100 && + playerStats->isUnlocked( + EnumParser::getString( + ACH_PLAY_ONE_HUNDRED_GAMES_ONLINE) + .c_str()) == false) { + playerStats->unlock(EnumParser::getString( + ACH_PLAY_ONE_HUNDRED_GAMES_ONLINE) + .c_str()); + } + if (networkGamesPlayedCount >= 250 && + playerStats->isUnlocked( + EnumParser::getString( + ACH_PLAY_TWO_HUNDRED_FIFTY_GAMES_ONLINE) + .c_str()) == false) { + playerStats->unlock(EnumParser::getString( + ACH_PLAY_TWO_HUNDRED_FIFTY_GAMES_ONLINE) + .c_str()); + } + if (networkGamesPlayedCount >= 500 && + playerStats->isUnlocked( + EnumParser::getString( + ACH_PLAY_FIVE_HUNDRED_GAMES_ONLINE) + .c_str()) == false) { + playerStats->unlock(EnumParser::getString( + ACH_PLAY_FIVE_HUNDRED_GAMES_ONLINE) + .c_str()); + } + if (networkGamesPlayedCount > 1000 && + playerStats->isUnlocked( + EnumParser::getString( + ACH_PLAY_OVER_THOUSAND_GAMES_ONLINE) + .c_str()) == false) { + playerStats->unlock(EnumParser::getString( + ACH_PLAY_OVER_THOUSAND_GAMES_ONLINE) + .c_str()); + } + } - return endStats; + if (endStats.getVictory(factionIndex)) { + if (playerStats->isUnlocked( + EnumParser::getString(ACH_WIN_ONE_GAME) + .c_str()) == false) { + playerStats->unlock( + EnumParser::getString(ACH_WIN_ONE_GAME) + .c_str()); + } + + if (NetworkManager::getInstance().isNetworkGame()) { + int networkGamesWonCount = + playerStats->getStatAsInt("network-games-won") + 1; + playerStats->setStatAsInt("network-games-won", + networkGamesWonCount); + } + + // printf("\nPlayer won the game with at least 10 minutes of play: + // %f!\n",elapsedGameMinutes); + } + } else { + // printf("\nPlayer won the game BUT NOT with at least 10 minutes of + // play: %f!\n",elapsedGameMinutes); + } + } + } + playerStats->storeStats(); } -void Game::DumpCRCWorldLogIfRequired(string fileSuffix) { - bool isNetworkGame = this->gameSettings.isNetworkGame(); - if(isNetworkGame == true) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Check save world CRC to log. isNetworkGame = %d fileSuffix = %s\n",isNetworkGame,fileSuffix.c_str()); - - GameSettings *settings = world.getGameSettingsPtr(); - if(settings != NULL && - (isFlagType1BitEnabled(ft1_network_synch_checks_verbose) == true || - isFlagType1BitEnabled(ft1_network_synch_checks) == true)) { - string debugCRCWorldLogFile = Config::getInstance().getString("DebugCRCWorldLogFile","debugCRCWorld.log"); - debugCRCWorldLogFile += fileSuffix; - - if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - debugCRCWorldLogFile = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + debugCRCWorldLogFile; - } - else { - string userData = Config::getInstance().getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - debugCRCWorldLogFile = userData + debugCRCWorldLogFile; - } - - printf("Save to log debugCRCWorldLogFile = %s\n",debugCRCWorldLogFile.c_str()); - - #if defined(WIN32) && !defined(__MINGW32__) - FILE *fp = _wfopen(utf8_decode(debugCRCWorldLogFile).c_str(), L"w"); - std::ofstream logFile(fp); - #else - std::ofstream logFile; - logFile.open(debugCRCWorldLogFile.c_str(), ios_base::out | ios_base::trunc); - #endif - logFile << "World CRC debug information:" << std::endl; - logFile << "============================" << std::endl; - logFile << "Software version: " << glestVersionString << "-" << getCompilerNameString() << "-" << getGITRevisionString() << std::endl; - logFile << "Maximum framecount: " << world.getFaction(0)->getCRC_DetailsForWorldFrameCount() << std::endl; - - - for(unsigned int worldFrameIndex = 0; worldFrameIndex < world.getFaction(0)->getCRC_DetailsForWorldFrameCount(); ++worldFrameIndex) { - //factions (and their related info) - for(int i = 0; i < world.getFactionCount(); ++i) { - logFile << "Faction detail for index: " << i << std::endl; - logFile << "--------------------------" << std::endl; - - std::pair details = world.getFaction(i)->getCRC_DetailsForWorldFrameIndex(worldFrameIndex); - - logFile << string("** world frame: ") << details.first << std::endl; - logFile << details.second << std::endl; - } - } - - logFile.close(); - #if defined(WIN32) && !defined(__MINGW32__) - if(fp) { - fclose(fp); - } - #endif - - } - } -} +void saveStatsToSteam(Game *game, Stats &endStats) { + Steam *steamInstance = CacheManager::getCachedItem( + GameConstants::steamCacheInstanceKey); + if (steamInstance != NULL) { + printf("\nSTEAM detected, writing out end game stats for player!\n"); + + // Write out stats here + if (NetworkManager::getInstance().isNetworkGame()) { + // printf("\nSTEAM Refresh Stats!\n"); + steamInstance->requestRefreshStats(); + for (int factionIndex = 0; + factionIndex < game->getWorld()->getFactionCount(); ++factionIndex) { + if (factionIndex == game->getWorld()->getThisFactionIndex()) { + // printf("\nWriting out game stats for Faction Index: + // %d!\n",factionIndex); + if (endStats.getVictory(factionIndex)) { + steamInstance->setStatAsInt( + EnumParser::getString(stat_online_wins).c_str(), + steamInstance->getStatAsInt( + EnumParser::getString(stat_online_wins) + .c_str()) + + 1); + } else { + steamInstance->setStatAsInt( + EnumParser::getString(stat_online_loses).c_str(), + steamInstance->getStatAsInt( + EnumParser::getString(stat_online_loses) + .c_str()) + + 1); + } + steamInstance->setStatAsInt( + EnumParser::getString(stat_online_kills).c_str(), + steamInstance->getStatAsInt( + EnumParser::getString(stat_online_kills) + .c_str()) + + endStats.getKills(factionIndex)); + steamInstance->setStatAsInt( + EnumParser::getString(stat_online_kills_enemy) + .c_str(), + steamInstance->getStatAsInt( + EnumParser::getString(stat_online_kills_enemy) + .c_str()) + + endStats.getEnemyKills(factionIndex)); + steamInstance->setStatAsInt( + EnumParser::getString(stat_online_deaths).c_str(), + steamInstance->getStatAsInt( + EnumParser::getString(stat_online_deaths) + .c_str()) + + endStats.getDeaths(factionIndex)); + steamInstance->setStatAsInt( + EnumParser::getString(stat_online_units).c_str(), + steamInstance->getStatAsInt( + EnumParser::getString(stat_online_units) + .c_str()) + + endStats.getUnitsProduced(factionIndex)); + steamInstance->setStatAsInt( + EnumParser::getString( + stat_online_resources_harvested) + .c_str(), + steamInstance->getStatAsInt(EnumParser::getString( + stat_online_resources_harvested) + .c_str()) + + endStats.getResourcesHarvested(factionIndex)); + if (endStats.getPlayerLeftBeforeEnd(factionIndex)) { + steamInstance->setStatAsInt( + EnumParser::getString( + stat_online_quit_before_end) + .c_str(), + steamInstance->getStatAsInt( + EnumParser::getString( + stat_online_quit_before_end) + .c_str()) + + 1); + } + steamInstance->setStatAsDouble( + EnumParser::getString(stat_online_minutes_played) + .c_str(), + steamInstance->getStatAsDouble( + EnumParser::getString( + stat_online_minutes_played) + .c_str()) + + getTimeDuationMinutes(endStats.getFramesToCalculatePlaytime(), + GameConstants::updateFps)); + } + } + } -void savePlayerStats(Game* game, Stats& endStats, PlayerAchievementsInterface *playerStats) { - const double MIN_PLAY_TIME_MINUTES = 10.0; - - // Write out achievements here - double elapsedGameMinutes = (game->getWorld()->getStats()->getFramesToCalculatePlaytime() / GameConstants::updateFps / 60.0); - - for (int factionIndex = 0; - factionIndex < game->getWorld()->getFactionCount(); ++factionIndex) { - if (factionIndex == game->getWorld()->getThisFactionIndex()) { - //printf("\nWriting out game stats for Faction Index: %d won status: %d\n",factionIndex,endStats.getVictory(factionIndex)); - if(elapsedGameMinutes >= MIN_PLAY_TIME_MINUTES) { - int gamesPlayedCount = playerStats->getStatAsInt(EnumParser::getString(games_played).c_str()) + 1; - playerStats->setStatAsInt(EnumParser::getString(games_played).c_str(),gamesPlayedCount); - - if(gamesPlayedCount >= 50 && playerStats->isUnlocked(EnumParser::getString(ACH_PLAY_FIFTY_GAMES).c_str()) == false) { - playerStats->unlock(EnumParser::getString(ACH_PLAY_FIFTY_GAMES).c_str()); - } - if(gamesPlayedCount >= 100 && playerStats->isUnlocked(EnumParser::getString(ACH_PLAY_ONE_HUNDRED_GAMES).c_str()) == false) { - playerStats->unlock(EnumParser::getString(ACH_PLAY_ONE_HUNDRED_GAMES).c_str()); - } - if(gamesPlayedCount >= 250 && playerStats->isUnlocked(EnumParser::getString(ACH_PLAY_TWO_HUNDRED_FIFTY_GAMES).c_str()) == false) { - playerStats->unlock(EnumParser::getString(ACH_PLAY_TWO_HUNDRED_FIFTY_GAMES).c_str()); - } - if(gamesPlayedCount >= 500 && playerStats->isUnlocked(EnumParser::getString(ACH_PLAY_FIVE_HUNDRED_GAMES).c_str()) == false) { - playerStats->unlock(EnumParser::getString(ACH_PLAY_FIVE_HUNDRED_GAMES).c_str()); - } - if(gamesPlayedCount > 1000 && playerStats->isUnlocked(EnumParser::getString(ACH_PLAY_OVER_THOUSAND_GAMES).c_str()) == false) { - playerStats->unlock(EnumParser::getString(ACH_PLAY_OVER_THOUSAND_GAMES).c_str()); - } - - if (NetworkManager::getInstance().isNetworkGame()) { - int networkGamesPlayedCount = playerStats->getStatAsInt(EnumParser::getString(network_games_played).c_str()) + 1; - playerStats->setStatAsInt(EnumParser::getString(network_games_played).c_str(),networkGamesPlayedCount); - - if(networkGamesPlayedCount >= 50 && playerStats->isUnlocked(EnumParser::getString(ACH_PLAY_FIFTY_GAMES_ONLINE).c_str()) == false) { - playerStats->unlock(EnumParser::getString(ACH_PLAY_FIFTY_GAMES_ONLINE).c_str()); - } - if(networkGamesPlayedCount >= 100 && playerStats->isUnlocked(EnumParser::getString(ACH_PLAY_ONE_HUNDRED_GAMES_ONLINE).c_str()) == false) { - playerStats->unlock(EnumParser::getString(ACH_PLAY_ONE_HUNDRED_GAMES_ONLINE).c_str()); - } - if(networkGamesPlayedCount >= 250 && playerStats->isUnlocked(EnumParser::getString(ACH_PLAY_TWO_HUNDRED_FIFTY_GAMES_ONLINE).c_str()) == false) { - playerStats->unlock(EnumParser::getString(ACH_PLAY_TWO_HUNDRED_FIFTY_GAMES_ONLINE).c_str()); - } - if(networkGamesPlayedCount >= 500 && playerStats->isUnlocked(EnumParser::getString(ACH_PLAY_FIVE_HUNDRED_GAMES_ONLINE).c_str()) == false) { - playerStats->unlock(EnumParser::getString(ACH_PLAY_FIVE_HUNDRED_GAMES_ONLINE).c_str()); - } - if(networkGamesPlayedCount > 1000 && playerStats->isUnlocked(EnumParser::getString(ACH_PLAY_OVER_THOUSAND_GAMES_ONLINE).c_str()) == false) { - playerStats->unlock(EnumParser::getString(ACH_PLAY_OVER_THOUSAND_GAMES_ONLINE).c_str()); - } - } - - if (endStats.getVictory(factionIndex)) { - if(playerStats->isUnlocked(EnumParser::getString(ACH_WIN_ONE_GAME).c_str()) == false) { - playerStats->unlock(EnumParser::getString(ACH_WIN_ONE_GAME).c_str()); - } - - if (NetworkManager::getInstance().isNetworkGame()) { - int networkGamesWonCount = playerStats->getStatAsInt("network-games-won") + 1; - playerStats->setStatAsInt("network-games-won",networkGamesWonCount); - } - - //printf("\nPlayer won the game with at least 10 minutes of play: %f!\n",elapsedGameMinutes); - } - } - else { - //printf("\nPlayer won the game BUT NOT with at least 10 minutes of play: %f!\n",elapsedGameMinutes); - } - } - } - playerStats->storeStats(); -} + // Write out achievements here + savePlayerStats(game, endStats, steamInstance); + + // printf("\nSTEAM Store Stats!\n"); + // steamInstance->storeStats(); + // printf("\nSTEAM Refresh Stats!\n"); + steamInstance->requestRefreshStats(); + } + // Local Player stats for now just write out to player-stats.ini + // We'll clean this up to use an interface that both steam and lcoal comply + // with so the 'update' logic doesn't need to be duplicated. + else { + printf("\n**STEAM NOT detected, writing out NON STEAM end game stats for " + "player!\n"); + string saveFilePlayerLocalStats = "player-stats.ini"; + if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { + saveFilePlayerLocalStats = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + + saveFilePlayerLocalStats; + } else { + string userData = Config::getInstance().getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + saveFilePlayerLocalStats = userData + saveFilePlayerLocalStats; + } + SteamLocal playerLocalStats(saveFilePlayerLocalStats); + PlayerAchievementsInterface *playerStats = &playerLocalStats; -void saveStatsToSteam(Game* game, Stats& endStats) { - Steam* steamInstance = CacheManager::getCachedItem(GameConstants::steamCacheInstanceKey); - if (steamInstance != NULL) { - printf("\nSTEAM detected, writing out end game stats for player!\n"); - - // Write out stats here - if (NetworkManager::getInstance().isNetworkGame()) { - //printf("\nSTEAM Refresh Stats!\n"); - steamInstance->requestRefreshStats(); - for (int factionIndex = 0; - factionIndex < game->getWorld()->getFactionCount(); ++factionIndex) { - if (factionIndex == game->getWorld()->getThisFactionIndex()) { - //printf("\nWriting out game stats for Faction Index: %d!\n",factionIndex); - if (endStats.getVictory(factionIndex)) { - steamInstance->setStatAsInt(EnumParser::getString(stat_online_wins).c_str(), - steamInstance->getStatAsInt(EnumParser::getString(stat_online_wins).c_str()) - + 1); - } else { - steamInstance->setStatAsInt(EnumParser::getString(stat_online_loses).c_str(), - steamInstance->getStatAsInt(EnumParser::getString(stat_online_loses).c_str()) - + 1); - } - steamInstance->setStatAsInt(EnumParser::getString(stat_online_kills).c_str(), - steamInstance->getStatAsInt(EnumParser::getString(stat_online_kills).c_str()) - + endStats.getKills(factionIndex)); - steamInstance->setStatAsInt(EnumParser::getString(stat_online_kills_enemy).c_str(), - steamInstance->getStatAsInt( - EnumParser::getString(stat_online_kills_enemy).c_str()) - + endStats.getEnemyKills(factionIndex)); - steamInstance->setStatAsInt(EnumParser::getString(stat_online_deaths).c_str(), - steamInstance->getStatAsInt(EnumParser::getString(stat_online_deaths).c_str()) - + endStats.getDeaths(factionIndex)); - steamInstance->setStatAsInt(EnumParser::getString(stat_online_units).c_str(), - steamInstance->getStatAsInt(EnumParser::getString(stat_online_units).c_str()) - + endStats.getUnitsProduced(factionIndex)); - steamInstance->setStatAsInt( - EnumParser::getString(stat_online_resources_harvested).c_str(), - steamInstance->getStatAsInt( - EnumParser::getString(stat_online_resources_harvested).c_str()) - + endStats.getResourcesHarvested( - factionIndex)); - if (endStats.getPlayerLeftBeforeEnd(factionIndex)) { - steamInstance->setStatAsInt( - EnumParser::getString(stat_online_quit_before_end).c_str(), - steamInstance->getStatAsInt( - EnumParser::getString(stat_online_quit_before_end).c_str()) + 1); - } - steamInstance->setStatAsDouble(EnumParser::getString(stat_online_minutes_played).c_str(), - steamInstance->getStatAsDouble( - EnumParser::getString(stat_online_minutes_played).c_str()) - + getTimeDuationMinutes( - endStats.getFramesToCalculatePlaytime(), - GameConstants::updateFps)); - } - } - } - - // Write out achievements here - savePlayerStats(game, endStats, steamInstance); - - //printf("\nSTEAM Store Stats!\n"); - //steamInstance->storeStats(); - //printf("\nSTEAM Refresh Stats!\n"); - steamInstance->requestRefreshStats(); - } - // Local Player stats for now just write out to player-stats.ini - // We'll clean this up to use an interface that both steam and lcoal comply with so the 'update' logic - // doesn't need to be duplicated. - else { - printf("\n**STEAM NOT detected, writing out NON STEAM end game stats for player!\n"); - string saveFilePlayerLocalStats = "player-stats.ini"; - if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - saveFilePlayerLocalStats = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + saveFilePlayerLocalStats; - } - else { - string userData = Config::getInstance().getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - saveFilePlayerLocalStats = userData + saveFilePlayerLocalStats; - } - SteamLocal playerLocalStats(saveFilePlayerLocalStats); - PlayerAchievementsInterface *playerStats = &playerLocalStats; - - // Write out achievements here - savePlayerStats(game, endStats, playerStats); - //playerLocalStats->save(saveFilePlayerLocalStats); - } + // Write out achievements here + savePlayerStats(game, endStats, playerStats); + // playerLocalStats->save(saveFilePlayerLocalStats); + } } void Game::exitGameState(Program *program, Stats &endStats) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - Game *game = dynamic_cast(program->getState()); + Game *game = dynamic_cast(program->getState()); - //printf("game = %p\n",game); + // printf("game = %p\n",game); - if(game) { - game->setEndGameTeamWinnersAndLosers(); - game->endGame(); - } + if (game) { + game->setEndGameTeamWinnersAndLosers(); + game->endGame(); + } - if((game != NULL && game->isMasterserverMode() == true) || - Config::getInstance().getBool("AutoTest") == true) { - printf("Game ending with stats:\n"); - printf("-----------------------\n"); + if ((game != NULL && game->isMasterserverMode() == true) || + Config::getInstance().getBool("AutoTest") == true) { + printf("Game ending with stats:\n"); + printf("-----------------------\n"); - string gameStats = endStats.getStats(); - printf("%s",gameStats.c_str()); + string gameStats = endStats.getStats(); + printf("%s", gameStats.c_str()); - printf("-----------------------\n"); - } + printf("-----------------------\n"); + } - saveStatsToSteam(game, endStats); + saveStatsToSteam(game, endStats); - ProgramState *newState = new BattleEnd(program, &endStats, game); + ProgramState *newState = new BattleEnd(program, &endStats, game); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - program->setState(newState, false); + program->setState(newState, false); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); } // ==================== PRIVATE ==================== -void Game::highlightUnit(int unitId,float radius, float thickness, Vec4f color) { - HighlightSpecialUnitInfo info; - info.radius = radius; - info.thickness = thickness; - info.color = color; - unitHighlightList[unitId] = info; +void Game::highlightUnit(int unitId, float radius, float thickness, + Vec4f color) { + HighlightSpecialUnitInfo info; + info.radius = radius; + info.thickness = thickness; + info.color = color; + unitHighlightList[unitId] = info; } -void Game::unhighlightUnit(int unitId) { - unitHighlightList.erase(unitId); -} +void Game::unhighlightUnit(int unitId) { unitHighlightList.erase(unitId); } // ==================== render ==================== -void Game::render3d(){ - Chrono chrono; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); - - Renderer &renderer= Renderer::getInstance(); - - //init - renderer.reset3d(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] renderFps = %d took msecs: %lld [reset3d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderFps,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - -// renderer.computeVisibleQuad(); -// if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] renderFps = %d took msecs: %lld [computeVisibleQuad]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderFps,chrono.getMillis()); -// if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - renderer.loadGameCameraMatrix(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] renderFps = %d took msecs: %lld [loadGameCameraMatrix]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderFps,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - renderer.computeVisibleQuad(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] renderFps = %d took msecs: %lld [computeVisibleQuad]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderFps,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - renderer.setupLighting(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] renderFps = %d took msecs: %lld [setupLighting]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderFps,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - //shadow map - renderer.renderShadowsToTexture(avgRenderFps); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] renderFps = %d took msecs: %lld [renderShadowsToTexture]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderFps,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - //clear buffers - renderer.clearBuffers(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d renderFps = %d took msecs: %lld\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderFps,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - //surface - renderer.renderSurface(avgRenderFps); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] renderFps = %d took msecs: %lld [renderSurface]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderFps,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - //selection circles - renderer.renderSelectionEffects(healthbarMode); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] renderFps = %d took msecs: %lld [renderSelectionEffects]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderFps,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - // renderTeamColorCircle - if((renderExtraTeamColor&renderTeamColorCircleBit)>0){ - renderer.renderTeamColorCircle(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] renderFps = %d took msecs: %lld [renderObjects]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderFps,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - } - - renderer.renderSpecialHighlightUnits(unitHighlightList); - - // renderTeamColorCircle - renderer.renderMorphEffects(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] renderFps = %d took msecs: %lld [renderObjects]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderFps,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - //objects - renderer.renderObjects(avgRenderFps); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] renderFps = %d took msecs: %lld [renderObjects]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderFps,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - //ground units - renderer.renderUnits(false, avgRenderFps); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] renderFps = %d took msecs: %lld [renderUnits]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderFps,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - //water - renderer.renderWater(); - renderer.renderWaterEffects(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] renderFps = %d took msecs: %lld [renderWater]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderFps,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - //air units - renderer.renderUnits(true, avgRenderFps); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] renderFps = %d took msecs: %lld [renderUnits]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderFps,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - //particles - renderer.renderParticleManager(rsGame); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] renderFps = %d took msecs: %lld [renderParticleManager]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderFps,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - //renderOnTopBars (aka Healthbars) - if(photoModeEnabled == false) { - renderer.renderHealthBars(healthbarMode); - } - - // renderTeamColorPlane - if((renderExtraTeamColor&renderTeamColorPlaneBit)>0){ - renderer.renderTeamColorPlane(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] renderFps = %d took msecs: %lld [renderObjects]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderFps,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - } - - //mouse 3d - renderer.renderMouse3d(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] renderFps = %d took msecs: %lld [renderMouse3d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderFps,chrono.getMillis()); - - renderer.renderUnitsToBuild(avgRenderFps); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] renderFps = %d took msecs: %lld [renderUnitsToBuild]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderFps,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - renderer.setLastRenderFps(lastRenderFps); +void Game::render3d() { + Chrono chrono; + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) + chrono.start(); + + Renderer &renderer = Renderer::getInstance(); + + // init + renderer.reset3d(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] renderFps = %d took msecs: %lld [reset3d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + renderFps, chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // renderer.computeVisibleQuad(); + // if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled + //&& chrono.getMillis() > 0) + // SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: + // %d] renderFps = %d took msecs: %lld + //[computeVisibleQuad]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,renderFps,chrono.getMillis()); + // if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled + //&& chrono.getMillis() > 0) chrono.start(); + + renderer.loadGameCameraMatrix(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] renderFps = %d took msecs: " + "%lld [loadGameCameraMatrix]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, renderFps, + chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + renderer.computeVisibleQuad(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] renderFps = %d took msecs: " + "%lld [computeVisibleQuad]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, renderFps, + chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + renderer.setupLighting(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] renderFps = %d took msecs: " + "%lld [setupLighting]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, renderFps, + chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // shadow map + renderer.renderShadowsToTexture(avgRenderFps); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] renderFps = %d took msecs: " + "%lld [renderShadowsToTexture]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, renderFps, + chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // clear buffers + renderer.clearBuffers(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s] Line: %d renderFps = %d took msecs: %lld\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + renderFps, chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // surface + renderer.renderSurface(avgRenderFps); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] renderFps = %d took msecs: " + "%lld [renderSurface]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, renderFps, + chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // selection circles + renderer.renderSelectionEffects(healthbarMode); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] renderFps = %d took msecs: " + "%lld [renderSelectionEffects]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, renderFps, + chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // renderTeamColorCircle + if ((renderExtraTeamColor & renderTeamColorCircleBit) > 0) { + renderer.renderTeamColorCircle(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] renderFps = %d took " + "msecs: %lld [renderObjects]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, renderFps, + chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + } + + renderer.renderSpecialHighlightUnits(unitHighlightList); + + // renderTeamColorCircle + renderer.renderMorphEffects(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] renderFps = %d took msecs: " + "%lld [renderObjects]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, renderFps, + chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // objects + renderer.renderObjects(avgRenderFps); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] renderFps = %d took msecs: " + "%lld [renderObjects]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, renderFps, + chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // ground units + renderer.renderUnits(false, avgRenderFps); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] renderFps = %d took msecs: %lld [renderUnits]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + renderFps, chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // water + renderer.renderWater(); + renderer.renderWaterEffects(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] renderFps = %d took msecs: %lld [renderWater]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + renderFps, chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // air units + renderer.renderUnits(true, avgRenderFps); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] renderFps = %d took msecs: %lld [renderUnits]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + renderFps, chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // particles + renderer.renderParticleManager(rsGame); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] renderFps = %d took msecs: " + "%lld [renderParticleManager]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, renderFps, + chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // renderOnTopBars (aka Healthbars) + if (photoModeEnabled == false) { + renderer.renderHealthBars(healthbarMode); + } + + // renderTeamColorPlane + if ((renderExtraTeamColor & renderTeamColorPlaneBit) > 0) { + renderer.renderTeamColorPlane(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] renderFps = %d took " + "msecs: %lld [renderObjects]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, renderFps, + chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + } + + // mouse 3d + renderer.renderMouse3d(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] renderFps = %d took msecs: " + "%lld [renderMouse3d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, renderFps, + chrono.getMillis()); + + renderer.renderUnitsToBuild(avgRenderFps); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] renderFps = %d took msecs: " + "%lld [renderUnitsToBuild]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, renderFps, + chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + renderer.setLastRenderFps(lastRenderFps); } void Game::updateWorldStats() { - world.getStats()->setWorldTimeElapsed(world.getTimeFlow()->getTime()); + world.getStats()->setWorldTimeElapsed(world.getTimeFlow()->getTime()); - if(difftime((long int)time(NULL),lastMaxUnitCalcTime) >= 1) { - lastMaxUnitCalcTime = time(NULL); + if (difftime((long int)time(NULL), lastMaxUnitCalcTime) >= 1) { + lastMaxUnitCalcTime = time(NULL); - int totalUnitcount = 0; - for(int i = 0; i < world.getFactionCount(); ++i) { - Faction *faction= world.getFaction(i); - totalUnitcount += faction->getUnitCount(); - } + int totalUnitcount = 0; + for (int i = 0; i < world.getFactionCount(); ++i) { + Faction *faction = world.getFaction(i); + totalUnitcount += faction->getUnitCount(); + } - if(world.getStats()->getMaxConcurrentUnitCount() < totalUnitcount) { - world.getStats()->setMaxConcurrentUnitCount(totalUnitcount); - } - world.getStats()->setTotalEndGameConcurrentUnitCount(totalUnitcount); - world.getStats()->setFramesPlayed(world.getFrameCount()); + if (world.getStats()->getMaxConcurrentUnitCount() < totalUnitcount) { + world.getStats()->setMaxConcurrentUnitCount(totalUnitcount); } + world.getStats()->setTotalEndGameConcurrentUnitCount(totalUnitcount); + world.getStats()->setFramesPlayed(world.getFrameCount()); + } } -string Game::getDebugStats(std::map &factionDebugInfo) { - string str = ""; - - if(this->masterserverMode == false) { - str+= "MouseXY: " + intToStr(mouseX) + "," + intToStr(mouseY)+"\n"; - - if(world.getMap()->isInsideSurface(world.getMap()->toSurfCoords(mouseCellPos)) == true) { - str+= "MouseXY cell coords: " + intToStr(mouseCellPos.x) + "," + intToStr(mouseCellPos.y)+"\n"; - } - - str+= "PosObjWord: " + intToStr(gui.getPosObjWorld().x) + "," + intToStr(gui.getPosObjWorld().y)+"\n"; - } - - str+= "Render FPS: " + intToStr(lastRenderFps) + "[" + intToStr(avgRenderFps) + "]\n"; - str+= "Update FPS: " + intToStr(lastUpdateFps) + "[" + intToStr(avgUpdateFps) + "]\n"; - - if(this->masterserverMode == false) { - str+= "GameCamera pos: " + floatToStr(gameCamera.getPos().x)+","+floatToStr(gameCamera.getPos().y)+","+floatToStr(gameCamera.getPos().z)+"\n"; - //str+= "Cached surfacedata: " + intToStr(renderer.getCachedSurfaceDataSize())+"\n"; - } - - //intToStr(stats.getFramesToCalculatePlaytime()/GameConstants::updateFps/60 - str+= "Time: " + floatToStr(world.getTimeFlow()->getTime(),2) + " [" + floatToStr((double)world.getStats()->getFramesToCalculatePlaytime() / (float)GameConstants::updateFps / 60.0,2) + "]\n"; - - if(SystemFlags::getThreadedLoggerRunning() == true) { - str+= "Log buffer count: " + intToStr(SystemFlags::getLogEntryBufferCount())+"\n"; - } - - str+= "UnitRangeCellsLookupItemCache: " + world.getUnitUpdater()->getUnitRangeCellsLookupItemCacheStats()+"\n"; - str+= "ExploredCellsLookupItemCache: " + world.getExploredCellsLookupItemCacheStats()+"\n"; - str+= "FowAlphaCellsLookupItemCache: " + world.getFowAlphaCellsLookupItemCacheStats()+"\n"; - - const string selectionType = toLower(Config::getInstance().getString("SelectionType",Config::colorPicking)); - str += "Selection type: " + toLower(selectionType) + "\n"; - - if(selectionType == Config::colorPicking) { - str += "Color picking used color list size: " + intToStr(BaseColorPickEntity::getUsedColorIDListSize()) +"\n"; - } - - //str+= "AllFactionsCacheStats: " + world.getAllFactionsCacheStats()+"\n"; - //str+= "AttackWarningCount: " + intToStr(world.getUnitUpdater()->getAttackWarningCount()) + "\n"; - - str+= "Map: " + gameSettings.getMap() +"\n"; - str+= "Tileset: " + gameSettings.getTileset() +"\n"; - str+= "Techtree: " + gameSettings.getTech() +"\n"; - - if(this->masterserverMode == false) { - Renderer &renderer= Renderer::getInstance(); - str+= "Triangle count: " + intToStr(renderer.getTriangleCount())+"\n"; - str+= "Vertex count: " + intToStr(renderer.getPointCount())+"\n"; - } - - str+= "Frame count:" + intToStr(world.getFrameCount())+"\n"; - - //visible quad - if(this->masterserverMode == false) { - Renderer &renderer= Renderer::getInstance(); - Quad2i visibleQuad= renderer.getVisibleQuad(); - //Quad2i visibleQuadCamera= renderer.getVisibleQuadFromCamera(); - - str+= "Visible quad: "; - for(int i= 0; i<4; ++i){ - str+= "(" + intToStr(visibleQuad.p[i].x) + "," +intToStr(visibleQuad.p[i].y) + ") "; - } - // str+= "\n"; - // str+= "Visible quad camera: "; - // for(int i= 0; i<4; ++i){ - // str+= "(" + intToStr(visibleQuadCamera.p[i].x) + "," +intToStr(visibleQuadCamera.p[i].y) + ") "; - // } - str+= "\n"; - - str+= "Visible quad area: " + floatToStr(visibleQuad.area()) +"\n"; - // str+= "Visible quad camera area: " + floatToStr(visibleQuadCamera.area()) +"\n"; - - // Rect2i boundingRect= visibleQuad.computeBoundingRect(); - // Rect2i scaledRect= boundingRect/Map::cellScale; - // scaledRect.clamp(0, 0, world.getMap()->getSurfaceW()-1, world.getMap()->getSurfaceH()-1); - // renderer.renderText3D("#1", coreData.getMenuFontNormal3D(), Vec3f(1.0f), scaledRect.p[0].x, scaledRect.p[0].y, false); - // renderer.renderText3D("#2", coreData.getMenuFontNormal3D(), Vec3f(1.0f), scaledRect.p[1].x, scaledRect.p[1].y, false); - } - - int totalUnitcount = 0; - for(int i = 0; i < world.getFactionCount(); ++i) { - Faction *faction= world.getFaction(i); - totalUnitcount += faction->getUnitCount(); - } - - if(this->masterserverMode == false) { - Renderer &renderer= Renderer::getInstance(); - VisibleQuadContainerCache &qCache =renderer.getQuadCache(); - int visibleUnitCount = (int)qCache.visibleQuadUnitList.size(); - str+= "Visible unit count: " + intToStr(visibleUnitCount) + " total: " + intToStr(totalUnitcount) + "\n"; - - int visibleObjectCount = (int)qCache.visibleObjectList.size(); - str+= "Visible object count: " + intToStr(visibleObjectCount) +"\n"; - } - else { - str+= "Total unit count: " + intToStr(totalUnitcount) + "\n"; - } - - // resources - for(int i = 0; i < world.getFactionCount(); ++i) { - string factionInfo = this->gameSettings.getNetworkPlayerName(i); - //factionInfo += " [" + this->gameSettings.getNetworkPlayerUUID(i) + "]"; - float multi=world.getStats()->getResourceMultiplier(i); - string multiplier="["+floatToStr(multi,1)+"]"; - switch(this->gameSettings.getFactionControl(i)) { - case ctCpuEasy: - factionInfo += " CPU Easy"+multiplier; - break; - case ctCpu: - factionInfo += " CPU Normal"+multiplier; - break; - case ctCpuUltra: - factionInfo += " CPU Ultra"+multiplier; - break; - case ctCpuMega: - factionInfo += " CPU Mega"+multiplier; - break; - } - - factionInfo += " [" + formatString(this->gameSettings.getFactionTypeName(i)) + - " team: " + intToStr(this->gameSettings.getTeam(i)) + "]"; - -// bool showResourceDebugInfo = true; -// if(showResourceDebugInfo == true) { -// factionInfo +=" res: "; -// for(int j = 0; j < world.getTechTree()->getResourceTypeCount(); ++j) { -// factionInfo += world.getFaction(i)->getResource(j)->getType()->getName()+":"+intToStr(world.getFaction(i)->getResource(j)->getAmount()); -// factionInfo += " "; -// } -// } +string Game::getDebugStats(std::map &factionDebugInfo) { + string str = ""; + + if (this->masterserverMode == false) { + str += "MouseXY: " + intToStr(mouseX) + "," + intToStr(mouseY) + "\n"; + + if (world.getMap()->isInsideSurface( + world.getMap()->toSurfCoords(mouseCellPos)) == true) { + str += "MouseXY cell coords: " + intToStr(mouseCellPos.x) + "," + + intToStr(mouseCellPos.y) + "\n"; + } + + str += "PosObjWord: " + intToStr(gui.getPosObjWorld().x) + "," + + intToStr(gui.getPosObjWorld().y) + "\n"; + } + + str += "Render FPS: " + intToStr(lastRenderFps) + "[" + + intToStr(avgRenderFps) + "]\n"; + str += "Update FPS: " + intToStr(lastUpdateFps) + "[" + + intToStr(avgUpdateFps) + "]\n"; + + if (this->masterserverMode == false) { + str += "GameCamera pos: " + floatToStr(gameCamera.getPos().x) + "," + + floatToStr(gameCamera.getPos().y) + "," + + floatToStr(gameCamera.getPos().z) + "\n"; + // str+= "Cached surfacedata: " + + // intToStr(renderer.getCachedSurfaceDataSize())+"\n"; + } + + // intToStr(stats.getFramesToCalculatePlaytime()/GameConstants::updateFps/60 + str += "Time: " + floatToStr(world.getTimeFlow()->getTime(), 2) + " [" + + floatToStr((double)world.getStats()->getFramesToCalculatePlaytime() / + (float)GameConstants::updateFps / 60.0, + 2) + + "]\n"; + + if (SystemFlags::getThreadedLoggerRunning() == true) { + str += + "Log buffer count: " + intToStr(SystemFlags::getLogEntryBufferCount()) + + "\n"; + } + + str += "UnitRangeCellsLookupItemCache: " + + world.getUnitUpdater()->getUnitRangeCellsLookupItemCacheStats() + "\n"; + str += "ExploredCellsLookupItemCache: " + + world.getExploredCellsLookupItemCacheStats() + "\n"; + str += "FowAlphaCellsLookupItemCache: " + + world.getFowAlphaCellsLookupItemCacheStats() + "\n"; + + const string selectionType = toLower( + Config::getInstance().getString("SelectionType", Config::colorPicking)); + str += "Selection type: " + toLower(selectionType) + "\n"; + + if (selectionType == Config::colorPicking) { + str += "Color picking used color list size: " + + intToStr(BaseColorPickEntity::getUsedColorIDListSize()) + "\n"; + } + + // str+= "AllFactionsCacheStats: " + + // world.getAllFactionsCacheStats()+"\n"; str+= "AttackWarningCount: " + + // intToStr(world.getUnitUpdater()->getAttackWarningCount()) + "\n"; + + str += "Map: " + gameSettings.getMap() + "\n"; + str += "Tileset: " + gameSettings.getTileset() + "\n"; + str += "Techtree: " + gameSettings.getTech() + "\n"; + + if (this->masterserverMode == false) { + Renderer &renderer = Renderer::getInstance(); + str += "Triangle count: " + intToStr(renderer.getTriangleCount()) + "\n"; + str += "Vertex count: " + intToStr(renderer.getPointCount()) + "\n"; + } + + str += "Frame count:" + intToStr(world.getFrameCount()) + "\n"; + + // visible quad + if (this->masterserverMode == false) { + Renderer &renderer = Renderer::getInstance(); + Quad2i visibleQuad = renderer.getVisibleQuad(); + // Quad2i visibleQuadCamera= renderer.getVisibleQuadFromCamera(); + + str += "Visible quad: "; + for (int i = 0; i < 4; ++i) { + str += "(" + intToStr(visibleQuad.p[i].x) + "," + + intToStr(visibleQuad.p[i].y) + ") "; + } + // str+= "\n"; + // str+= "Visible quad camera: "; + // for(int i= 0; i<4; ++i){ + // str+= "(" + intToStr(visibleQuadCamera.p[i].x) + "," + //+intToStr(visibleQuadCamera.p[i].y) + ") "; + // } + str += "\n"; + + str += "Visible quad area: " + floatToStr(visibleQuad.area()) + "\n"; + // str+= "Visible quad camera area: " + + // floatToStr(visibleQuadCamera.area()) +"\n"; + + // Rect2i boundingRect= visibleQuad.computeBoundingRect(); + // Rect2i scaledRect= boundingRect/Map::cellScale; + // scaledRect.clamp(0, 0, world.getMap()->getSurfaceW()-1, + // world.getMap()->getSurfaceH()-1); + // renderer.renderText3D("#1", coreData.getMenuFontNormal3D(), Vec3f(1.0f), + // scaledRect.p[0].x, scaledRect.p[0].y, false); + // renderer.renderText3D("#2", coreData.getMenuFontNormal3D(), Vec3f(1.0f), + // scaledRect.p[1].x, scaledRect.p[1].y, false); + } + + int totalUnitcount = 0; + for (int i = 0; i < world.getFactionCount(); ++i) { + Faction *faction = world.getFaction(i); + totalUnitcount += faction->getUnitCount(); + } + + if (this->masterserverMode == false) { + Renderer &renderer = Renderer::getInstance(); + VisibleQuadContainerCache &qCache = renderer.getQuadCache(); + int visibleUnitCount = (int)qCache.visibleQuadUnitList.size(); + str += "Visible unit count: " + intToStr(visibleUnitCount) + + " total: " + intToStr(totalUnitcount) + "\n"; + + int visibleObjectCount = (int)qCache.visibleObjectList.size(); + str += "Visible object count: " + intToStr(visibleObjectCount) + "\n"; + } else { + str += "Total unit count: " + intToStr(totalUnitcount) + "\n"; + } + + // resources + for (int i = 0; i < world.getFactionCount(); ++i) { + string factionInfo = this->gameSettings.getNetworkPlayerName(i); + // factionInfo += " [" + this->gameSettings.getNetworkPlayerUUID(i) + "]"; + float multi = world.getStats()->getResourceMultiplier(i); + string multiplier = "[" + floatToStr(multi, 1) + "]"; + switch (this->gameSettings.getFactionControl(i)) { + case ctCpuEasy: + factionInfo += " CPU Easy" + multiplier; + break; + case ctCpu: + factionInfo += " CPU Normal" + multiplier; + break; + case ctCpuUltra: + factionInfo += " CPU Ultra" + multiplier; + break; + case ctCpuMega: + factionInfo += " CPU Mega" + multiplier; + break; + } + + factionInfo += " [" + + formatString(this->gameSettings.getFactionTypeName(i)) + + " team: " + intToStr(this->gameSettings.getTeam(i)) + "]"; + + // bool showResourceDebugInfo = true; + // if(showResourceDebugInfo == true) { + // factionInfo +=" res: "; + // for(int j = 0; j < world.getTechTree()->getResourceTypeCount(); + //++j) { factionInfo += + // world.getFaction(i)->getResource(j)->getType()->getName()+":"+intToStr(world.getFaction(i)->getResource(j)->getAmount()); + // factionInfo += " "; + // } + // } - factionDebugInfo[i] = factionInfo; - } + factionDebugInfo[i] = factionInfo; + } - return str; + return str; } void Game::render2d() { - Renderer &renderer= Renderer::getInstance(); - //Config &config= Config::getInstance(); - CoreData &coreData= CoreData::getInstance(); - - //init - renderer.reset2d(); - - //HUD - if(visibleHUD == true && photoModeEnabled == false) { - renderer.renderHud(); - } - //display - renderer.renderDisplay(); - - //minimap - if(photoModeEnabled == false) { - renderer.renderMinimap(); - } - - renderer.renderVisibleMarkedCells(); - renderer.renderVisibleMarkedCells(true,lastMousePos.x,lastMousePos.y); - - //selection - renderer.renderSelectionQuad(); - - //highlighted Cells - renderer.renderHighlightedCellsOnMinimap(); - - if(switchTeamConfirmMessageBox.getEnabled() == true) { - renderer.renderMessageBox(&switchTeamConfirmMessageBox); - } - - if(disconnectPlayerConfirmMessageBox.getEnabled() == true) { - renderer.renderMessageBox(&disconnectPlayerConfirmMessageBox); - } - - //exit message box - if(errorMessageBox.getEnabled()) { - renderer.renderMessageBox(&errorMessageBox); - } - if(mainMessageBox.getEnabled()) { - renderer.renderMessageBox(&mainMessageBox); - } - - //script message box - if( mainMessageBox.getEnabled() == false && - errorMessageBox.getEnabled() == false && - scriptManager.getMessageBoxEnabled()) { - renderer.renderMessageBox(scriptManager.getMessageBox()); - } - - //script display text - if(!scriptManager.getDisplayText().empty() && !scriptManager.getMessageBoxEnabled()){ - Vec4f fontColor = getGui()->getDisplay()->getColor(); - - if(Renderer::renderText3DEnabled == true) { - renderer.renderText3D( - scriptManager.getDisplayText(), coreData.getMenuFontNormal3D(), - Vec3f(fontColor.x,fontColor.y,fontColor.z), 200, 660, false); - } - else { - renderer.renderText( - scriptManager.getDisplayText(), coreData.getMenuFontNormal(), - Vec3f(fontColor.x,fontColor.y,fontColor.z), 200, 660, false); - } - } - - renderVideoPlayer(); - - renderer.renderPopupMenu(&popupMenu); - renderer.renderPopupMenu(&popupMenuSwitchTeams); - renderer.renderPopupMenu(&popupMenuDisconnectPlayer); - - if(program != NULL) program->renderProgramMsgBox(); - - renderer.renderChatManager(&chatManager); - - //debug info - bool perfLogging = false; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled == true || - SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true) { - perfLogging = true; - } - - string str=""; - std::map factionDebugInfo; - - if( renderer.getShowDebugUI() == true || - (perfLogging == true && difftime((long int)time(NULL),lastRenderLog2d) >= 1)) { - str = getDebugStats(factionDebugInfo); - } - - if(this->getRenderInGamePerformance() == true) { - renderer.renderPerformanceStats(); - } - else { - static time_t lastGamePerfCheck = time(NULL); - if(difftime((long int)time(NULL),lastGamePerfCheck) > 3) { - lastGamePerfCheck = time(NULL); - - getGamePerformanceCounts(true); - } - } - - if(renderer.getShowDebugUI() == true) { - const Metrics &metrics= Metrics::getInstance(); - int mh= metrics.getMinimapH(); - - if(this->getRenderInGamePerformance() == true) { - mh = mh + ((int)gamePerformanceCounts.size() * 14); - } - - const Vec4f fontColor=getGui()->getDisplay()->getColor(); - - if(Renderer::renderText3DEnabled == true) { - renderer.renderTextShadow3D(str, coreData.getMenuFontNormal3D(), - fontColor, 10, metrics.getVirtualH() - mh - 60, false); - } - else { - renderer.renderTextShadow(str, coreData.getMenuFontNormal(), - fontColor, 10, metrics.getVirtualH() - mh - 60, false); - } - - vector lineTokens; - Tokenize(str,lineTokens,"\n"); - int fontHeightNormal = (Renderer::renderText3DEnabled == true ? coreData.getMenuFontNormal3D()->getMetrics()->getHeight("W") : coreData.getMenuFontNormal()->getMetrics()->getHeight("W")); - int fontHeightBig = (Renderer::renderText3DEnabled == true ? coreData.getMenuFontBig3D()->getMetrics()->getHeight("W") : coreData.getMenuFontBig()->getMetrics()->getHeight("W")); - int playerPosY = (int)lineTokens.size() * fontHeightNormal; - - //printf("lineTokens.size() = %d\n",lineTokens.size()); - - for(int i = 0; i < world.getFactionCount(); ++i) { - string factionInfo = factionDebugInfo[i]; - Vec3f playerColor = world.getFaction(i)->getTexture()->getPixmapConst()->getPixel3f(0, 0); - - if(Renderer::renderText3DEnabled == true) { - renderer.renderText3D(factionInfo, coreData.getMenuFontBig3D(), - Vec4f(playerColor.x,playerColor.y,playerColor.z,1.0), - 10, - //metrics.getVirtualH() - mh - 90 - 280 - (i * 16), - metrics.getVirtualH() - mh - 60 - playerPosY - fontHeightBig - (fontHeightBig * i), - false); - } - else { - renderer.renderText(factionInfo, coreData.getMenuFontBig(), - Vec4f(playerColor.x,playerColor.y,playerColor.z,1.0), - 10, - //metrics.getVirtualH() - mh - 90 - 280 - (i * 16), - metrics.getVirtualH() - mh - 60 - playerPosY - fontHeightBig - (fontHeightBig * i), - false); - } - } - - if((renderer.getShowDebugUILevel() & debugui_unit_titles) == debugui_unit_titles) { - if(renderer.getAllowRenderUnitTitles() == false) { - renderer.setAllowRenderUnitTitles(true); - } - - if(Renderer::renderText3DEnabled == true) { - renderer.renderUnitTitles3D(coreData.getMenuFontNormal3D(),Vec3f(1.0f)); - } - else { - renderer.renderUnitTitles(coreData.getMenuFontNormal(),Vec3f(1.0f)); - } - } - } - - //network status - if(renderNetworkStatus == true) { - if(NetworkManager::getInstance().getGameNetworkInterface() != NULL) { - const Metrics &metrics= Metrics::getInstance(); - int mx= metrics.getMinimapX(); - //int my= metrics.getMinimapY(); - int mw= metrics.getMinimapW(); - //int mh= metrics.getMinimapH(); - const Vec4f fontColor=getGui()->getDisplay()->getColor(); - - if(Renderer::renderText3DEnabled == true) { - renderer.renderTextShadow3D( - NetworkManager::getInstance().getGameNetworkInterface()->getNetworkStatus(), - coreData.getMenuFontNormal3D(), - fontColor, mx + mw + 5 , metrics.getVirtualH()-30-20, false); - } - else { - renderer.renderTextShadow( - NetworkManager::getInstance().getGameNetworkInterface()->getNetworkStatus(), - coreData.getMenuFontNormal(), - fontColor, mx + mw + 5 , metrics.getVirtualH()-30-20, false); - } - } - } - - // clock - if(photoModeEnabled == false && timeDisplay == true) { - renderer.renderClock(); - } - - //resource info - if(photoModeEnabled == false) { - if(this->masterserverMode == false) { - renderer.renderResourceStatus(); - } - renderer.renderConsole(&console,showFullConsole?consoleFull:consoleNormal); - } - - //2d mouse - renderer.renderMouse2d(mouseX, mouseY, mouse2d, gui.isSelectingPos()? 1.f: 0.f); - - if(perfLogging == true && difftime((long int)time(NULL),lastRenderLog2d) >= 1) { - lastRenderLog2d = time(NULL); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] Statistics: %s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,str.c_str()); - } -} + Renderer &renderer = Renderer::getInstance(); + // Config &config= Config::getInstance(); + CoreData &coreData = CoreData::getInstance(); + + // init + renderer.reset2d(); + + // HUD + if (visibleHUD == true && photoModeEnabled == false) { + renderer.renderHud(); + } + // display + renderer.renderDisplay(); + + // minimap + if (photoModeEnabled == false) { + renderer.renderMinimap(); + } + + renderer.renderVisibleMarkedCells(); + renderer.renderVisibleMarkedCells(true, lastMousePos.x, lastMousePos.y); + + // selection + renderer.renderSelectionQuad(); + + // highlighted Cells + renderer.renderHighlightedCellsOnMinimap(); + + if (switchTeamConfirmMessageBox.getEnabled() == true) { + renderer.renderMessageBox(&switchTeamConfirmMessageBox); + } + + if (disconnectPlayerConfirmMessageBox.getEnabled() == true) { + renderer.renderMessageBox(&disconnectPlayerConfirmMessageBox); + } + + // exit message box + if (errorMessageBox.getEnabled()) { + renderer.renderMessageBox(&errorMessageBox); + } + if (mainMessageBox.getEnabled()) { + renderer.renderMessageBox(&mainMessageBox); + } + + // script message box + if (mainMessageBox.getEnabled() == false && + errorMessageBox.getEnabled() == false && + scriptManager.getMessageBoxEnabled()) { + renderer.renderMessageBox(scriptManager.getMessageBox()); + } + + // script display text + if (!scriptManager.getDisplayText().empty() && + !scriptManager.getMessageBoxEnabled()) { + Vec4f fontColor = getGui()->getDisplay()->getColor(); + + if (Renderer::renderText3DEnabled == true) { + renderer.renderText3D( + scriptManager.getDisplayText(), coreData.getMenuFontNormal3D(), + Vec3f(fontColor.x, fontColor.y, fontColor.z), 200, 660, false); + } else { + renderer.renderText( + scriptManager.getDisplayText(), coreData.getMenuFontNormal(), + Vec3f(fontColor.x, fontColor.y, fontColor.z), 200, 660, false); + } + } + + renderVideoPlayer(); + + renderer.renderPopupMenu(&popupMenu); + renderer.renderPopupMenu(&popupMenuSwitchTeams); + renderer.renderPopupMenu(&popupMenuDisconnectPlayer); + + if (program != NULL) + program->renderProgramMsgBox(); + + renderer.renderChatManager(&chatManager); + + // debug info + bool perfLogging = false; + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled == true || + SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == + true) { + perfLogging = true; + } + + string str = ""; + std::map factionDebugInfo; + + if (renderer.getShowDebugUI() == true || + (perfLogging == true && + difftime((long int)time(NULL), lastRenderLog2d) >= 1)) { + str = getDebugStats(factionDebugInfo); + } + + if (this->getRenderInGamePerformance() == true) { + renderer.renderPerformanceStats(); + } else { + static time_t lastGamePerfCheck = time(NULL); + if (difftime((long int)time(NULL), lastGamePerfCheck) > 3) { + lastGamePerfCheck = time(NULL); + + getGamePerformanceCounts(true); + } + } + if (renderer.getShowDebugUI() == true) { + const Metrics &metrics = Metrics::getInstance(); + int mh = metrics.getMinimapH(); + + if (this->getRenderInGamePerformance() == true) { + mh = mh + ((int)gamePerformanceCounts.size() * 14); + } + + const Vec4f fontColor = getGui()->getDisplay()->getColor(); + + if (Renderer::renderText3DEnabled == true) { + renderer.renderTextShadow3D(str, coreData.getMenuFontNormal3D(), + fontColor, 10, + metrics.getVirtualH() - mh - 60, false); + } else { + renderer.renderTextShadow(str, coreData.getMenuFontNormal(), fontColor, + 10, metrics.getVirtualH() - mh - 60, false); + } + + vector lineTokens; + Tokenize(str, lineTokens, "\n"); + int fontHeightNormal = + (Renderer::renderText3DEnabled == true + ? coreData.getMenuFontNormal3D()->getMetrics()->getHeight("W") + : coreData.getMenuFontNormal()->getMetrics()->getHeight("W")); + int fontHeightBig = + (Renderer::renderText3DEnabled == true + ? coreData.getMenuFontBig3D()->getMetrics()->getHeight("W") + : coreData.getMenuFontBig()->getMetrics()->getHeight("W")); + int playerPosY = (int)lineTokens.size() * fontHeightNormal; + + // printf("lineTokens.size() = %d\n",lineTokens.size()); + + for (int i = 0; i < world.getFactionCount(); ++i) { + string factionInfo = factionDebugInfo[i]; + Vec3f playerColor = + world.getFaction(i)->getTexture()->getPixmapConst()->getPixel3f(0, 0); + + if (Renderer::renderText3DEnabled == true) { + renderer.renderText3D( + factionInfo, coreData.getMenuFontBig3D(), + Vec4f(playerColor.x, playerColor.y, playerColor.z, 1.0), 10, + // metrics.getVirtualH() - mh - 90 - 280 - (i * 16), + metrics.getVirtualH() - mh - 60 - playerPosY - fontHeightBig - + (fontHeightBig * i), + false); + } else { + renderer.renderText( + factionInfo, coreData.getMenuFontBig(), + Vec4f(playerColor.x, playerColor.y, playerColor.z, 1.0), 10, + // metrics.getVirtualH() - mh - 90 - 280 - (i * 16), + metrics.getVirtualH() - mh - 60 - playerPosY - fontHeightBig - + (fontHeightBig * i), + false); + } + } + + if ((renderer.getShowDebugUILevel() & debugui_unit_titles) == + debugui_unit_titles) { + if (renderer.getAllowRenderUnitTitles() == false) { + renderer.setAllowRenderUnitTitles(true); + } + + if (Renderer::renderText3DEnabled == true) { + renderer.renderUnitTitles3D(coreData.getMenuFontNormal3D(), + Vec3f(1.0f)); + } else { + renderer.renderUnitTitles(coreData.getMenuFontNormal(), Vec3f(1.0f)); + } + } + } + + // network status + if (renderNetworkStatus == true) { + if (NetworkManager::getInstance().getGameNetworkInterface() != NULL) { + const Metrics &metrics = Metrics::getInstance(); + int mx = metrics.getMinimapX(); + // int my= metrics.getMinimapY(); + int mw = metrics.getMinimapW(); + // int mh= metrics.getMinimapH(); + const Vec4f fontColor = getGui()->getDisplay()->getColor(); + + if (Renderer::renderText3DEnabled == true) { + renderer.renderTextShadow3D(NetworkManager::getInstance() + .getGameNetworkInterface() + ->getNetworkStatus(), + coreData.getMenuFontNormal3D(), fontColor, + mx + mw + 5, + metrics.getVirtualH() - 30 - 20, false); + } else { + renderer.renderTextShadow(NetworkManager::getInstance() + .getGameNetworkInterface() + ->getNetworkStatus(), + coreData.getMenuFontNormal(), fontColor, + mx + mw + 5, metrics.getVirtualH() - 30 - 20, + false); + } + } + } + + // clock + if (photoModeEnabled == false && timeDisplay == true) { + renderer.renderClock(); + } + + // resource info + if (photoModeEnabled == false) { + if (this->masterserverMode == false) { + renderer.renderResourceStatus(); + } + renderer.renderConsole(&console, + showFullConsole ? consoleFull : consoleNormal); + } + + // 2d mouse + renderer.renderMouse2d(mouseX, mouseY, mouse2d, + gui.isSelectingPos() ? 1.f : 0.f); + + if (perfLogging == true && + difftime((long int)time(NULL), lastRenderLog2d) >= 1) { + lastRenderLog2d = time(NULL); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] Statistics: %s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, str.c_str()); + } +} // ==================== misc ==================== void Game::checkWinner() { - // lookup int is team #, value is players alive on team - std::map teamsAlive = getTeamsAlive(); - - if(gameOver == false || teamsAlive.size() > 1) { - if(gameSettings.getDefaultVictoryConditions()) { - checkWinnerStandard(); - } - else { - checkWinnerScripted(); - } - } + // lookup int is team #, value is players alive on team + std::map teamsAlive = getTeamsAlive(); + + if (gameOver == false || teamsAlive.size() > 1) { + if (gameSettings.getDefaultVictoryConditions()) { + checkWinnerStandard(); + } else { + checkWinnerScripted(); + } + } } void Game::setEndGameTeamWinnersAndLosers() { - //bool lose= false; - bool checkTeamIndex = !(this->masterserverMode == false && world.getThisFaction()->getPersonalityType() != fpt_Observer); - - // lookup int is team #, value is players alive on team - std::map teamsAlive; - for(int i = 0; i < world.getFactionCount(); ++i) { - if(checkTeamIndex == false || i != world.getThisFactionIndex()) { - if(factionLostGame(world.getFaction(i)) == false) { - teamsAlive[world.getFaction(i)->getTeam()] = teamsAlive[world.getFaction(i)->getTeam()] + 1; - } - } - } - - // did some team win - if(teamsAlive.size() <= 1) { - for(int i=0; i< world.getFactionCount(); ++i) { - if(checkTeamIndex == false || i != world.getThisFactionIndex()) { - if(teamsAlive.find(world.getFaction(i)->getTeam()) != teamsAlive.end()) { - world.getStats()->setVictorious(i); - } - else if(i == world.getThisFactionIndex()) { - //lose= true; - } - } - } - bool firstGameOverTrigger = false; - if(gameOver == false) { - firstGameOverTrigger = true; - gameOver= true; - } - if( this->gameSettings.isNetworkGame() == false || - this->gameSettings.getEnableObserverModeAtEndGame() == true) { - // Let the happy winner view everything left in the world - - // This caused too much LAG for network games - if(this->gameSettings.isNetworkGame() == false) { - Renderer::getInstance().setPhotoMode(true); - gameCamera.setMaxHeight(PHOTO_MODE_MAXHEIGHT); - } - // END - } - - if(firstGameOverTrigger == true) { - scriptManager.onGameOver(true); - } - - if(world.getFactionCount() == 1 && world.getFaction(0)->getPersonalityType() == fpt_Observer) { - //printf("!!!!!!!!!!!!!!!!!!!!"); - - //gameCamera.setMoveY(100.0); - gameCamera.zoom(-300); - //gameCamera.update(); - } -// else { -// if(lose == true) { -// showLoseMessageBox(); -// } -// else { -// showWinMessageBox(); -// } -// } - } + // bool lose= false; + bool checkTeamIndex = + !(this->masterserverMode == false && + world.getThisFaction()->getPersonalityType() != fpt_Observer); + + // lookup int is team #, value is players alive on team + std::map teamsAlive; + for (int i = 0; i < world.getFactionCount(); ++i) { + if (checkTeamIndex == false || i != world.getThisFactionIndex()) { + if (factionLostGame(world.getFaction(i)) == false) { + teamsAlive[world.getFaction(i)->getTeam()] = + teamsAlive[world.getFaction(i)->getTeam()] + 1; + } + } + } + + // did some team win + if (teamsAlive.size() <= 1) { + for (int i = 0; i < world.getFactionCount(); ++i) { + if (checkTeamIndex == false || i != world.getThisFactionIndex()) { + if (teamsAlive.find(world.getFaction(i)->getTeam()) != + teamsAlive.end()) { + world.getStats()->setVictorious(i); + } else if (i == world.getThisFactionIndex()) { + // lose= true; + } + } + } + bool firstGameOverTrigger = false; + if (gameOver == false) { + firstGameOverTrigger = true; + gameOver = true; + } + if (this->gameSettings.isNetworkGame() == false || + this->gameSettings.getEnableObserverModeAtEndGame() == true) { + // Let the happy winner view everything left in the world + + // This caused too much LAG for network games + if (this->gameSettings.isNetworkGame() == false) { + Renderer::getInstance().setPhotoMode(true); + gameCamera.setMaxHeight(PHOTO_MODE_MAXHEIGHT); + } + // END + } + + if (firstGameOverTrigger == true) { + scriptManager.onGameOver(true); + } + + if (world.getFactionCount() == 1 && + world.getFaction(0)->getPersonalityType() == fpt_Observer) { + // printf("!!!!!!!!!!!!!!!!!!!!"); + + // gameCamera.setMoveY(100.0); + gameCamera.zoom(-300); + // gameCamera.update(); + } + // else { + // if(lose == true) { + // showLoseMessageBox(); + // } + // else { + // showWinMessageBox(); + // } + // } + } } std::map Game::getTeamsAlive() { - std::map teamsAlive; - for (int factionIndex = 0; factionIndex < world.getFactionCount(); ++factionIndex) { - if (factionIndex != world.getThisFactionIndex()) { - if (factionLostGame(world.getFaction(factionIndex)) == false) { - teamsAlive[world.getFaction(factionIndex)->getTeam()] = - teamsAlive[world.getFaction(factionIndex)->getTeam()] + 1; - } - } - } - // did some team win - return teamsAlive; + std::map teamsAlive; + for (int factionIndex = 0; factionIndex < world.getFactionCount(); + ++factionIndex) { + if (factionIndex != world.getThisFactionIndex()) { + if (factionLostGame(world.getFaction(factionIndex)) == false) { + teamsAlive[world.getFaction(factionIndex)->getTeam()] = + teamsAlive[world.getFaction(factionIndex)->getTeam()] + 1; + } + } + } + // did some team win + return teamsAlive; } void Game::checkWinnerStandardHeadlessOrObserver() { - // lookup int is team #, value is players alive on team - std::map teamsAlive = getTeamsAlive(); - - // did some team win - if (teamsAlive.size() <= 1) { - if (this->masterserverMode == true) { - printf("Game finished...\n"); - } - for (int factionIndex = 0; factionIndex < world.getFactionCount(); ++factionIndex) { - - Faction* faction = world.getFaction(factionIndex); - if (factionIndex != world.getThisFactionIndex() && - teamsAlive.find(faction->getTeam()) != teamsAlive.end()) { - - world.getStats()->setVictorious(factionIndex); - if (this->masterserverMode == true) { - - printf("Player: %s is on the winning team #: %d\n", - this->gameSettings.getNetworkPlayerName(factionIndex).c_str(), - faction->getTeam()); - } - } - } - bool wasGameOverAlready = gameOver; - gameOver = true; - - // Only need to process this once - if(wasGameOverAlready == false) { - if (this->gameSettings.isNetworkGame() == false || - this->gameSettings.getEnableObserverModeAtEndGame() == true) { - - // Let the happy winner view everything left in the world - // This caused too much LAG for network games - if (this->gameSettings.isNetworkGame() == false) { - - Renderer::getInstance().setPhotoMode(true); - gameCamera.setMaxHeight(PHOTO_MODE_MAXHEIGHT); - } - // END - } - scriptManager.onGameOver(true); - if (world.getFactionCount() == 1 && - world.getFaction(0)->getPersonalityType() == fpt_Observer) { - gameCamera.zoom(-300); - } - else { - showWinMessageBox(); - } - } - } + // lookup int is team #, value is players alive on team + std::map teamsAlive = getTeamsAlive(); + + // did some team win + if (teamsAlive.size() <= 1) { + if (this->masterserverMode == true) { + printf("Game finished...\n"); + } + for (int factionIndex = 0; factionIndex < world.getFactionCount(); + ++factionIndex) { + + Faction *faction = world.getFaction(factionIndex); + if (factionIndex != world.getThisFactionIndex() && + teamsAlive.find(faction->getTeam()) != teamsAlive.end()) { + + world.getStats()->setVictorious(factionIndex); + if (this->masterserverMode == true) { + + printf("Player: %s is on the winning team #: %d\n", + this->gameSettings.getNetworkPlayerName(factionIndex).c_str(), + faction->getTeam()); + } + } + } + bool wasGameOverAlready = gameOver; + gameOver = true; + + // Only need to process this once + if (wasGameOverAlready == false) { + if (this->gameSettings.isNetworkGame() == false || + this->gameSettings.getEnableObserverModeAtEndGame() == true) { + + // Let the happy winner view everything left in the world + // This caused too much LAG for network games + if (this->gameSettings.isNetworkGame() == false) { + + Renderer::getInstance().setPhotoMode(true); + gameCamera.setMaxHeight(PHOTO_MODE_MAXHEIGHT); + } + // END + } + scriptManager.onGameOver(true); + if (world.getFactionCount() == 1 && + world.getFaction(0)->getPersonalityType() == fpt_Observer) { + gameCamera.zoom(-300); + } else { + showWinMessageBox(); + } + } + } } void Game::checkWinnerStandardPlayer() { - //lose - bool lose = false; - if (factionLostGame(world.getThisFaction()) == true) { - - bool playerLostGame = true; - // Team Shared units enabled? - if(isFlagType1BitEnabled(ft1_allow_shared_team_units) == true) { - - // Check if all team members have lost? - for (int factionIndex = 0; factionIndex < world.getFactionCount(); ++factionIndex) { - - if (world.getFaction(factionIndex)->getPersonalityType() != fpt_Observer) { - if (world.getFaction(factionIndex)->isAlly(world.getThisFaction()) == true && - factionLostGame(world.getFaction(factionIndex)) == false) { - - playerLostGame = false; - break; - } - } - } - } - - if(playerLostGame == true) { - lose = true; - for (int factionIndex = 0; factionIndex < world.getFactionCount(); ++factionIndex) { - - if (world.getFaction(factionIndex)->getPersonalityType() != fpt_Observer) { - if (world.getFaction(factionIndex)->isAlly(world.getThisFaction()) == false && - factionLostGame(world.getFaction(factionIndex)) == false) { - - world.getStats()->setVictorious(factionIndex); - } - } - } - bool wasGameOverAlready = gameOver; - gameOver = true; - - // Only need to process losing once - if(wasGameOverAlready == false) { - if (this->gameSettings.isNetworkGame() == false || - this->gameSettings.getEnableObserverModeAtEndGame() - == true) { - // Let the poor user watch everything unfold - // This caused too much LAG for network games - if (this->gameSettings.isNetworkGame() == false) { - Renderer::getInstance().setPhotoMode(true); - gameCamera.setMaxHeight(PHOTO_MODE_MAXHEIGHT); - } - // END - // but don't let him cheat via teamchat - chatManager.setDisableTeamMode(true); - } - scriptManager.onGameOver(!lose); - showLoseMessageBox(); - } - } - } - - //win - if (lose == false) { - bool win = true; - for (int factionIndex = 0; factionIndex < world.getFactionCount(); ++factionIndex) { - - if (factionIndex != world.getThisFactionIndex()) { - if (world.getFaction(factionIndex)->getPersonalityType() != fpt_Observer) { - - if (factionLostGame(world.getFaction(factionIndex)) == false && - world.getFaction(factionIndex)->isAlly(world.getThisFaction()) == false) { - - win = false; - } - } - } - } - - if (win) { - for (int factionIndex = 0; factionIndex < world.getFactionCount(); ++factionIndex) { - if (world.getFaction(factionIndex)->getPersonalityType() != fpt_Observer) { - if (world.getFaction(factionIndex)->isAlly(world.getThisFaction())) { - - world.getStats()->setVictorious(factionIndex); - } - } - } - - bool wasGameOverAlready = gameOver; - gameOver = true; - - // Only need to process winning once - if(wasGameOverAlready == false) { - if (this->gameSettings.isNetworkGame() == false || - this->gameSettings.getEnableObserverModeAtEndGame() == true) { - // Let the happy winner view everything left in the world - - // This caused too much LAG for network games - if (this->gameSettings.isNetworkGame() == false) { - Renderer::getInstance().setPhotoMode(true); - gameCamera.setMaxHeight(PHOTO_MODE_MAXHEIGHT); - } - // END - } - scriptManager.onGameOver(win); - showWinMessageBox(); - } - } - } + // lose + bool lose = false; + if (factionLostGame(world.getThisFaction()) == true) { + + bool playerLostGame = true; + // Team Shared units enabled? + if (isFlagType1BitEnabled(ft1_allow_shared_team_units) == true) { + + // Check if all team members have lost? + for (int factionIndex = 0; factionIndex < world.getFactionCount(); + ++factionIndex) { + + if (world.getFaction(factionIndex)->getPersonalityType() != + fpt_Observer) { + if (world.getFaction(factionIndex)->isAlly(world.getThisFaction()) == + true && + factionLostGame(world.getFaction(factionIndex)) == false) { + + playerLostGame = false; + break; + } + } + } + } + + if (playerLostGame == true) { + lose = true; + for (int factionIndex = 0; factionIndex < world.getFactionCount(); + ++factionIndex) { + + if (world.getFaction(factionIndex)->getPersonalityType() != + fpt_Observer) { + if (world.getFaction(factionIndex)->isAlly(world.getThisFaction()) == + false && + factionLostGame(world.getFaction(factionIndex)) == false) { + + world.getStats()->setVictorious(factionIndex); + } + } + } + bool wasGameOverAlready = gameOver; + gameOver = true; + + // Only need to process losing once + if (wasGameOverAlready == false) { + if (this->gameSettings.isNetworkGame() == false || + this->gameSettings.getEnableObserverModeAtEndGame() == true) { + // Let the poor user watch everything unfold + // This caused too much LAG for network games + if (this->gameSettings.isNetworkGame() == false) { + Renderer::getInstance().setPhotoMode(true); + gameCamera.setMaxHeight(PHOTO_MODE_MAXHEIGHT); + } + // END + // but don't let him cheat via teamchat + chatManager.setDisableTeamMode(true); + } + scriptManager.onGameOver(!lose); + showLoseMessageBox(); + } + } + } + + // win + if (lose == false) { + bool win = true; + for (int factionIndex = 0; factionIndex < world.getFactionCount(); + ++factionIndex) { + + if (factionIndex != world.getThisFactionIndex()) { + if (world.getFaction(factionIndex)->getPersonalityType() != + fpt_Observer) { + + if (factionLostGame(world.getFaction(factionIndex)) == false && + world.getFaction(factionIndex)->isAlly(world.getThisFaction()) == + false) { + + win = false; + } + } + } + } + + if (win) { + for (int factionIndex = 0; factionIndex < world.getFactionCount(); + ++factionIndex) { + if (world.getFaction(factionIndex)->getPersonalityType() != + fpt_Observer) { + if (world.getFaction(factionIndex)->isAlly(world.getThisFaction())) { + + world.getStats()->setVictorious(factionIndex); + } + } + } + + bool wasGameOverAlready = gameOver; + gameOver = true; + + // Only need to process winning once + if (wasGameOverAlready == false) { + if (this->gameSettings.isNetworkGame() == false || + this->gameSettings.getEnableObserverModeAtEndGame() == true) { + // Let the happy winner view everything left in the world + + // This caused too much LAG for network games + if (this->gameSettings.isNetworkGame() == false) { + Renderer::getInstance().setPhotoMode(true); + gameCamera.setMaxHeight(PHOTO_MODE_MAXHEIGHT); + } + // END + } + scriptManager.onGameOver(win); + showWinMessageBox(); + } + } + } } void Game::checkWinnerStandard() { - if(world.getFactionCount() <= 0) { - return; - } - if(this->masterserverMode == true || - world.getThisFaction()->getPersonalityType() == fpt_Observer) { - checkWinnerStandardHeadlessOrObserver(); - } - else { - checkWinnerStandardPlayer(); - } + if (world.getFactionCount() <= 0) { + return; + } + if (this->masterserverMode == true || + world.getThisFaction()->getPersonalityType() == fpt_Observer) { + checkWinnerStandardHeadlessOrObserver(); + } else { + checkWinnerStandardPlayer(); + } } void Game::checkWinnerScripted() { - if(scriptManager.getIsGameOver()) { - bool wasGameOverAlready = gameOver; - gameOver = true; - - - for(int index = 0; index < world.getFactionCount(); ++index) { - if(scriptManager.getPlayerModifiers(index)->getWinner()) { - - world.getStats()->setVictorious(index); - } - } - - // Only need to process winning once - if(wasGameOverAlready == false) { - if( this->gameSettings.isNetworkGame() == false || - this->gameSettings.getEnableObserverModeAtEndGame() == true) { - - // Let the happy winner view everything left in the world - // This caused too much LAG for network games - if(this->gameSettings.isNetworkGame() == false) { - Renderer::getInstance().setPhotoMode(true); - gameCamera.setMaxHeight(PHOTO_MODE_MAXHEIGHT); - } - // END - } - - if(this->masterserverMode == true || - world.getThisFaction()->getPersonalityType() == fpt_Observer) { - showWinMessageBox(); - } - else { - scriptManager.onGameOver(scriptManager.getPlayerModifiers(world.getThisFactionIndex())->getWinner()); - - if(scriptManager.getPlayerModifiers(world.getThisFactionIndex())->getWinner()){ - showWinMessageBox(); - } - else { - showLoseMessageBox(); - } - } - } - } + if (scriptManager.getIsGameOver()) { + bool wasGameOverAlready = gameOver; + gameOver = true; + + for (int index = 0; index < world.getFactionCount(); ++index) { + if (scriptManager.getPlayerModifiers(index)->getWinner()) { + + world.getStats()->setVictorious(index); + } + } + + // Only need to process winning once + if (wasGameOverAlready == false) { + if (this->gameSettings.isNetworkGame() == false || + this->gameSettings.getEnableObserverModeAtEndGame() == true) { + + // Let the happy winner view everything left in the world + // This caused too much LAG for network games + if (this->gameSettings.isNetworkGame() == false) { + Renderer::getInstance().setPhotoMode(true); + gameCamera.setMaxHeight(PHOTO_MODE_MAXHEIGHT); + } + // END + } + + if (this->masterserverMode == true || + world.getThisFaction()->getPersonalityType() == fpt_Observer) { + showWinMessageBox(); + } else { + scriptManager.onGameOver( + scriptManager.getPlayerModifiers(world.getThisFactionIndex()) + ->getWinner()); + + if (scriptManager.getPlayerModifiers(world.getThisFactionIndex()) + ->getWinner()) { + showWinMessageBox(); + } else { + showLoseMessageBox(); + } + } + } + } } bool Game::isFlagType1BitEnabled(FlagTypes1 type) const { - return ((gameSettings.getFlagTypes1() & (uint32)type) == (uint32)type); + return ((gameSettings.getFlagTypes1() & (uint32)type) == (uint32)type); } bool Game::factionLostGame(int factionIndex) { - return factionLostGame(world.getFaction(factionIndex)); + return factionLostGame(world.getFaction(factionIndex)); } bool Game::factionLostGame(const Faction *faction) { - if(faction != NULL) { - for(int factionIndex=0; factionIndexgetUnitCount(); ++factionIndex) { - const UnitType *ut = faction->getUnit(factionIndex)->getType(); - if(ut->getCountInVictoryConditions() == ucvcNotSet) { - if(faction->getUnit(factionIndex)->getType()->hasSkillClass(scBeBuilt)) { - return false; - } - } - else if(ut->getCountInVictoryConditions() == ucvcTrue) { - return false; - } - } - } - return true; + if (faction != NULL) { + for (int factionIndex = 0; factionIndex < faction->getUnitCount(); + ++factionIndex) { + const UnitType *ut = faction->getUnit(factionIndex)->getType(); + if (ut->getCountInVictoryConditions() == ucvcNotSet) { + if (faction->getUnit(factionIndex) + ->getType() + ->hasSkillClass(scBeBuilt)) { + return false; + } + } else if (ut->getCountInVictoryConditions() == ucvcTrue) { + return false; + } + } + } + return true; } -//bool Game::hasBuilding(const Faction *faction) { +// bool Game::hasBuilding(const Faction *faction) { // if(faction != NULL) { // for(int i=0; igetUnitCount(); ++i) { -// if(faction->getUnit(i)->getType()->hasSkillClass(scBeBuilt)) { -// return true; +// if(faction->getUnit(i)->getType()->hasSkillClass(scBeBuilt)) +//{ return true; // } // } // } // return false; -//} +// } void Game::incSpeed() { - if(disableSpeedChange == true) { - return; - } - - Lang &lang= Lang::getInstance(); - - if(this->speed < Config::getInstance().getInt("FastSpeedLoops")) { - if(this->speed == 0) { - this->speed = 1; - } - else { - this->speed++; - } - console.addLine(lang.getString("GameSpeedSet")+" "+((this->speed == 0)?lang.getString("Slow") : (this->speed == 1)?lang.getString("Normal"):"x"+intToStr(this->speed))); - } + if (disableSpeedChange == true) { + return; + } + + Lang &lang = Lang::getInstance(); + + if (this->speed < Config::getInstance().getInt("FastSpeedLoops")) { + if (this->speed == 0) { + this->speed = 1; + } else { + this->speed++; + } + console.addLine(lang.getString("GameSpeedSet") + " " + + ((this->speed == 0) ? lang.getString("Slow") + : (this->speed == 1) ? lang.getString("Normal") + : "x" + intToStr(this->speed))); + } } void Game::decSpeed() { - if(disableSpeedChange == true) { - return; - } - - Lang &lang= Lang::getInstance(); - if(this->speed > 0) { - this->speed--; - console.addLine(lang.getString("GameSpeedSet")+" "+((this->speed == 0)?lang.getString("Slow") : (this->speed == 1)?lang.getString("Normal"):"x"+intToStr(this->speed))); - } + if (disableSpeedChange == true) { + return; + } + + Lang &lang = Lang::getInstance(); + if (this->speed > 0) { + this->speed--; + console.addLine(lang.getString("GameSpeedSet") + " " + + ((this->speed == 0) ? lang.getString("Slow") + : (this->speed == 1) ? lang.getString("Normal") + : "x" + intToStr(this->speed))); + } } -void Game::setPaused(bool value,bool forceAllowPauseStateChange,bool clearCaches, bool joinNetworkGame) { - bool speedChangesAllowed= !NetworkManager::getInstance().isNetworkGame(); - //printf("Toggle pause value = %d, speedChangesAllowed = %d, forceAllowPauseStateChange = %d\n",value,speedChangesAllowed,forceAllowPauseStateChange); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled) SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"game.cpp line: %d setPaused value: %d clearCaches: %d forceAllowPauseStateChange: %d speedChangesAllowed: %d pausedForJoinGame: %d joinNetworkGame: %d\n",__LINE__,value,clearCaches,forceAllowPauseStateChange,speedChangesAllowed,pausedForJoinGame,joinNetworkGame); - //printf("Line: %d setPaused value: %d clearCaches: %d forceAllowPauseStateChange: %d speedChangesAllowed: %d pausedForJoinGame: %d joinNetworkGame: %d\n",__LINE__,value,clearCaches,forceAllowPauseStateChange,speedChangesAllowed,pausedForJoinGame,joinNetworkGame); - - if(forceAllowPauseStateChange == true || speedChangesAllowed == true) { - //printf("setPaused paused = %d, value = %d\n",paused,value); - - NetworkManager &networkManager= NetworkManager::getInstance(); - - // Cannot change pause state while client is joining in progress game - if(pausedForJoinGame == true && joinNetworkGame == false && - networkManager.getNetworkRole() == nrServer) { - - ServerInterface *server = NetworkManager::getInstance().getServerInterface(); - Lang &lang= Lang::getInstance(); - const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); - - bool haveClientConnectedButNoReady = false; - for(int i = 0; i < world.getFactionCount(); ++i) { - Faction *faction = world.getFaction(i); - - MutexSafeWrapper safeMutex(server->getSlotMutex(faction->getStartLocationIndex()),CODE_AT_LINE); - ConnectionSlot *slot = server->getSlot(faction->getStartLocationIndex(),false); - if(slot != NULL && slot->isConnected() == true && slot->isReady() == false) { - for(unsigned int i = 0; i < languageList.size(); ++i) { - - char szMsg[8096]=""; - if(lang.hasString("JoinPlayerToCurrentGameLaunch",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("JoinPlayerToCurrentGameLaunch",languageList[i]).c_str(), slot->getName().c_str()); - } - else { - snprintf(szMsg,8096,"Player: %s is about to join the game, please wait...",slot->getName().c_str()); - } - - safeMutex.ReleaseLock(); - - bool localEcho = lang.isLanguageLocal(languageList[i]); - server->sendTextMessage(szMsg,-1, localEcho,languageList[i]); - sleep(1); - - haveClientConnectedButNoReady = true; - } - } - } - - if(haveClientConnectedButNoReady == true) { - return; - } - } - - Lang &lang= Lang::getInstance(); - if(value == false) { - console.addLine(lang.getString("GameResumed")); - - bool wasPausedForJoinGame = pausedForJoinGame; - paused= false; - pausedForJoinGame = false; - pausedBeforeJoinGame = false; - pauseStateChanged = true; - - if(clearCaches == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled) SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"game.cpp line: %d Clear Caches for resume in progress game\n",__LINE__); - //printf("Line: %d Clear Caches for resume in progress game\n",__LINE__); - - world.clearCaches(); - for(int i = 0; i < world.getFactionCount(); ++i) { - Faction *faction = world.getFaction(i); - faction->clearCaches(); - } - world.refreshAllUnitExplorations(); - } - setupPopupMenus(false); - - if(networkManager.getNetworkRole() == nrClient && - wasPausedForJoinGame == true) { - initialResumeSpeedLoops = true; - } - - commander.setPauseNetworkCommands(false); - } - else { - console.addLine(lang.getString("GamePaused")); - - if(joinNetworkGame == true) { - pausedBeforeJoinGame = paused; - } - paused= true; - pausedForJoinGame = joinNetworkGame; - pauseStateChanged = true; - - if(clearCaches == true) { - //printf("Line: %d Clear Caches for resume in progress game\n",__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled) SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"game.cpp line: %d Clear Caches for resume in progress game\n",__LINE__); - - world.clearCaches(); - for(int i = 0; i < world.getFactionCount(); ++i) { - Faction *faction = world.getFaction(i); - faction->clearCaches(); - } - world.refreshAllUnitExplorations(); - } - pauseRequestSent=false; - - commander.setPauseNetworkCommands(joinNetworkGame); - } - //printf("setPaused new paused = %d\n",paused); - } +void Game::setPaused(bool value, bool forceAllowPauseStateChange, + bool clearCaches, bool joinNetworkGame) { + bool speedChangesAllowed = !NetworkManager::getInstance().isNetworkGame(); + // printf("Toggle pause value = %d, speedChangesAllowed = %d, + // forceAllowPauseStateChange = + // %d\n",value,speedChangesAllowed,forceAllowPauseStateChange); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugWorldSynch, + "game.cpp line: %d setPaused value: %d clearCaches: %d " + "forceAllowPauseStateChange: %d speedChangesAllowed: %d " + "pausedForJoinGame: %d joinNetworkGame: %d\n", + __LINE__, value, clearCaches, forceAllowPauseStateChange, + speedChangesAllowed, pausedForJoinGame, joinNetworkGame); + // printf("Line: %d setPaused value: %d clearCaches: %d + // forceAllowPauseStateChange: %d speedChangesAllowed: %d pausedForJoinGame: + // %d joinNetworkGame: + // %d\n",__LINE__,value,clearCaches,forceAllowPauseStateChange,speedChangesAllowed,pausedForJoinGame,joinNetworkGame); + + if (forceAllowPauseStateChange == true || speedChangesAllowed == true) { + // printf("setPaused paused = %d, value = %d\n",paused,value); + + NetworkManager &networkManager = NetworkManager::getInstance(); + + // Cannot change pause state while client is joining in progress game + if (pausedForJoinGame == true && joinNetworkGame == false && + networkManager.getNetworkRole() == nrServer) { + + ServerInterface *server = + NetworkManager::getInstance().getServerInterface(); + Lang &lang = Lang::getInstance(); + const vector languageList = + this->gameSettings.getUniqueNetworkPlayerLanguages(); + + bool haveClientConnectedButNoReady = false; + for (int i = 0; i < world.getFactionCount(); ++i) { + Faction *faction = world.getFaction(i); + + MutexSafeWrapper safeMutex( + server->getSlotMutex(faction->getStartLocationIndex()), + CODE_AT_LINE); + ConnectionSlot *slot = + server->getSlot(faction->getStartLocationIndex(), false); + if (slot != NULL && slot->isConnected() == true && + slot->isReady() == false) { + for (unsigned int i = 0; i < languageList.size(); ++i) { + + char szMsg[8096] = ""; + if (lang.hasString("JoinPlayerToCurrentGameLaunch", + languageList[i]) == true) { + snprintf(szMsg, 8096, + lang.getString("JoinPlayerToCurrentGameLaunch", + languageList[i]) + .c_str(), + slot->getName().c_str()); + } else { + snprintf(szMsg, 8096, + "Player: %s is about to join the game, please wait...", + slot->getName().c_str()); + } + + safeMutex.ReleaseLock(); + + bool localEcho = lang.isLanguageLocal(languageList[i]); + server->sendTextMessage(szMsg, -1, localEcho, languageList[i]); + sleep(1); + + haveClientConnectedButNoReady = true; + } + } + } + + if (haveClientConnectedButNoReady == true) { + return; + } + } + + Lang &lang = Lang::getInstance(); + if (value == false) { + console.addLine(lang.getString("GameResumed")); + + bool wasPausedForJoinGame = pausedForJoinGame; + paused = false; + pausedForJoinGame = false; + pausedBeforeJoinGame = false; + pauseStateChanged = true; + + if (clearCaches == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugWorldSynch, + "game.cpp line: %d Clear Caches for resume in progress game\n", + __LINE__); + // printf("Line: %d Clear Caches for resume in progress + // game\n",__LINE__); + + world.clearCaches(); + for (int i = 0; i < world.getFactionCount(); ++i) { + Faction *faction = world.getFaction(i); + faction->clearCaches(); + } + world.refreshAllUnitExplorations(); + } + setupPopupMenus(false); + + if (networkManager.getNetworkRole() == nrClient && + wasPausedForJoinGame == true) { + initialResumeSpeedLoops = true; + } + + commander.setPauseNetworkCommands(false); + } else { + console.addLine(lang.getString("GamePaused")); + + if (joinNetworkGame == true) { + pausedBeforeJoinGame = paused; + } + paused = true; + pausedForJoinGame = joinNetworkGame; + pauseStateChanged = true; + + if (clearCaches == true) { + // printf("Line: %d Clear Caches for resume in progress + // game\n",__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugWorldSynch, + "game.cpp line: %d Clear Caches for resume in progress game\n", + __LINE__); + + world.clearCaches(); + for (int i = 0; i < world.getFactionCount(); ++i) { + Faction *faction = world.getFaction(i); + faction->clearCaches(); + } + world.refreshAllUnitExplorations(); + } + pauseRequestSent = false; + + commander.setPauseNetworkCommands(joinNetworkGame); + } + // printf("setPaused new paused = %d\n",paused); + } } -bool Game::getPaused() -{ - bool speedChangesAllowed= !NetworkManager::getInstance().isNetworkGame(); - if(speedChangesAllowed){ - if(popupMenu.getVisible() == true || popupMenuSwitchTeams.getVisible() == true){ - return true; - } -// if(mainMessageBox.getEnabled() == true || errorMessageBox.getEnabled() == true){ -// return true; -// } - if(currentUIState != NULL) { - return true; - } - } - return paused; +bool Game::getPaused() { + bool speedChangesAllowed = !NetworkManager::getInstance().isNetworkGame(); + if (speedChangesAllowed) { + if (popupMenu.getVisible() == true || + popupMenuSwitchTeams.getVisible() == true) { + return true; + } + // if(mainMessageBox.getEnabled() == true || + //errorMessageBox.getEnabled() + //== true){ return true; + // } + if (currentUIState != NULL) { + return true; + } + } + return paused; } int Game::getUpdateLoops() { - if(commander.hasReplayCommandListForFrame() == true) { - return 1; - } - - if(getPaused()) { - return 0; - } - else if(this->speed == 0) { - return updateFps % 2 == 0? 1: 0; - } - else - return this->speed; + if (commander.hasReplayCommandListForFrame() == true) { + return 1; + } + + if (getPaused()) { + return 0; + } else if (this->speed == 0) { + return updateFps % 2 == 0 ? 1 : 0; + } else + return this->speed; } void Game::showLoseMessageBox() { - Lang &lang= Lang::getInstance(); - - NetworkManager &networkManager= NetworkManager::getInstance(); - if(networkManager.isNetworkGame() == true && networkManager.getNetworkRole() == nrServer) { - showMessageBox(lang.getString("YouLose")+" "+lang.getString("ExitBattleServerQuestion"), lang.getString("BattleOver"), false); - } - else { - showMessageBox(lang.getString("YouLose")+" "+lang.getString("ExitBattleQuestion"), lang.getString("BattleOver"), false); - } + Lang &lang = Lang::getInstance(); + + NetworkManager &networkManager = NetworkManager::getInstance(); + if (networkManager.isNetworkGame() == true && + networkManager.getNetworkRole() == nrServer) { + showMessageBox(lang.getString("YouLose") + " " + + lang.getString("ExitBattleServerQuestion"), + lang.getString("BattleOver"), false); + } else { + showMessageBox(lang.getString("YouLose") + " " + + lang.getString("ExitBattleQuestion"), + lang.getString("BattleOver"), false); + } } void Game::showWinMessageBox() { - Lang &lang= Lang::getInstance(); - - if(this->masterserverMode == true || world.getThisFaction()->getPersonalityType() == fpt_Observer) { - showMessageBox(lang.getString("GameOver")+" "+lang.getString("ExitBattleQuestion"), lang.getString("BattleOver"), false); - } - else { - showMessageBox(lang.getString("YouWin")+" "+lang.getString("ExitBattleQuestion"), lang.getString("BattleOver"), false); - } + Lang &lang = Lang::getInstance(); + + if (this->masterserverMode == true || + world.getThisFaction()->getPersonalityType() == fpt_Observer) { + showMessageBox(lang.getString("GameOver") + " " + + lang.getString("ExitBattleQuestion"), + lang.getString("BattleOver"), false); + } else { + showMessageBox(lang.getString("YouWin") + " " + + lang.getString("ExitBattleQuestion"), + lang.getString("BattleOver"), false); + } } -void Game::showMessageBox(const string &text, const string &header, bool toggle) { - if(toggle == false) { - mainMessageBox.setEnabled(false); - } - - if(mainMessageBox.getEnabled() == false) { - mainMessageBox.setText(text); - mainMessageBox.setHeader(header); - mainMessageBox.setEnabled(true); - } - else { - mainMessageBox.setEnabled(false); - } +void Game::showMessageBox(const string &text, const string &header, + bool toggle) { + if (toggle == false) { + mainMessageBox.setEnabled(false); + } + + if (mainMessageBox.getEnabled() == false) { + mainMessageBox.setText(text); + mainMessageBox.setHeader(header); + mainMessageBox.setEnabled(true); + } else { + mainMessageBox.setEnabled(false); + } } -void Game::showErrorMessageBox(const string &text, const string &header, bool toggle) { - if(toggle == false) { - errorMessageBox.setEnabled(false); - } - - if(errorMessageBox.getEnabled() == false) { - errorMessageBox.setText(text); - errorMessageBox.setHeader(header); - errorMessageBox.setEnabled(true); - } - else { - errorMessageBox.setEnabled(false); - } +void Game::showErrorMessageBox(const string &text, const string &header, + bool toggle) { + if (toggle == false) { + errorMessageBox.setEnabled(false); + } + + if (errorMessageBox.getEnabled() == false) { + errorMessageBox.setText(text); + errorMessageBox.setHeader(header); + errorMessageBox.setEnabled(true); + } else { + errorMessageBox.setEnabled(false); + } } void Game::startPerformanceTimer() { - captureAvgTestStatus = true; - updateFpsAvgTest = -1; - renderFpsAvgTest = -1; + captureAvgTestStatus = true; + updateFpsAvgTest = -1; + renderFpsAvgTest = -1; } -void Game::endPerformanceTimer() { - captureAvgTestStatus = false; -} +void Game::endPerformanceTimer() { captureAvgTestStatus = false; } Vec2i Game::getPerformanceTimerResults() { - Vec2i results(this->updateFpsAvgTest,this->renderFpsAvgTest); - return results; + Vec2i results(this->updateFpsAvgTest, this->renderFpsAvgTest); + return results; } -void Game::consoleAddLine(string line) { - console.addLine(line); -} +void Game::consoleAddLine(string line) { console.addLine(line); } void Game::toggleTeamColorMarker() { - renderExtraTeamColor++; - renderExtraTeamColor=renderExtraTeamColor%4; + renderExtraTeamColor++; + renderExtraTeamColor = renderExtraTeamColor % 4; } -void Game::addNetworkCommandToReplayList(NetworkCommand* networkCommand, int worldFrameCount) { - Config &config= Config::getInstance(); - if(config.getBool("SaveCommandsForReplay","false") == true) { - replayCommandList.push_back(make_pair(worldFrameCount,*networkCommand)); - } +void Game::addNetworkCommandToReplayList(NetworkCommand *networkCommand, + int worldFrameCount) { + Config &config = Config::getInstance(); + if (config.getBool("SaveCommandsForReplay", "false") == true) { + replayCommandList.push_back(make_pair(worldFrameCount, *networkCommand)); + } } void Game::renderVideoPlayer() { - if(videoPlayer != NULL) { - if(videoPlayer->isPlaying() == true) { - videoPlayer->playFrame(false); - } - else { - delete videoPlayer; - videoPlayer = NULL; - } - } + if (videoPlayer != NULL) { + if (videoPlayer->isPlaying() == true) { + videoPlayer->playFrame(false); + } else { + delete videoPlayer; + videoPlayer = NULL; + } + } } void Game::playStaticVideo(const string &playVideo) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && - ::Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == true) { - - //togglePauseGame(true,true); - tryPauseToggle(true); - setupRenderForVideo(); - - -// Context *c= GraphicsInterface::getInstance().getCurrentContext(); -// SDL_Surface *screen = static_cast(c)->getPlatformContextGlPtr()->getScreen(); -// -// string vlcPluginsPath = Config::getInstance().getString("VideoPlayerPluginsPath",""); -// //printf("screen->w = %d screen->h = %d screen->format->BitsPerPixel = %d\n",screen->w,screen->h,screen->format->BitsPerPixel); -// Shared::Graphics::VideoPlayer player(playVideo.c_str(), -// screen, -// 0,0, -// screen->w, -// screen->h, -// screen->format->BitsPerPixel, -// vlcPluginsPath, -// SystemFlags::VERBOSE_MODE_ENABLED); -// player.PlayVideo(); - //} - //tryPauseToggle(false); - - playStreamingVideo(playVideo); - playingStaticVideo = true; - } + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && + ::Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == true) { + + // togglePauseGame(true,true); + tryPauseToggle(true); + setupRenderForVideo(); + + // Context *c= + // GraphicsInterface::getInstance().getCurrentContext(); SDL_Surface + // *screen = + //static_cast(c)->getPlatformContextGlPtr()->getScreen(); + // + // string vlcPluginsPath = + // Config::getInstance().getString("VideoPlayerPluginsPath",""); + // //printf("screen->w = %d screen->h = %d screen->format->BitsPerPixel + //= %d\n",screen->w,screen->h,screen->format->BitsPerPixel); + // Shared::Graphics::VideoPlayer player(playVideo.c_str(), + // screen, + // 0,0, + // screen->w, + // screen->h, + // screen->format->BitsPerPixel, + // vlcPluginsPath, + // SystemFlags::VERBOSE_MODE_ENABLED); + // player.PlayVideo(); + //} + // tryPauseToggle(false); + + playStreamingVideo(playVideo); + playingStaticVideo = true; + } } void Game::playStreamingVideo(const string &playVideo) { - if(videoPlayer == NULL) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && - ::Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == true) { - Context *c= GraphicsInterface::getInstance().getCurrentContext(); - PlatformContextGl *glCtx = static_cast(c)->getPlatformContextGlPtr(); - SDL_Window *window = glCtx->getScreenWindow(); - SDL_Surface *screen = glCtx->getScreenSurface(); - - string vlcPluginsPath = Config::getInstance().getString("VideoPlayerPluginsPath",""); - - videoPlayer = new ::Shared::Graphics::VideoPlayer( - &Renderer::getInstance(), - playVideo, - "", - window, - 0,0, - screen->w, - screen->h, - screen->format->BitsPerPixel, - false, - vlcPluginsPath, - SystemFlags::VERBOSE_MODE_ENABLED); - } - } - else { - if(videoPlayer->isPlaying() == false) { - delete videoPlayer; - videoPlayer = NULL; - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && - ::Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == true) { - Context *c= GraphicsInterface::getInstance().getCurrentContext(); - PlatformContextGl *glCtx = static_cast(c)->getPlatformContextGlPtr(); - SDL_Window *window = glCtx->getScreenWindow(); - SDL_Surface *screen = glCtx->getScreenSurface(); - - string vlcPluginsPath = Config::getInstance().getString("VideoPlayerPluginsPath",""); - - videoPlayer = new ::Shared::Graphics::VideoPlayer( - &Renderer::getInstance(), - playVideo, - "", - window, - 0,0, - screen->w, - screen->h, - screen->format->BitsPerPixel, - false, - vlcPluginsPath, - SystemFlags::VERBOSE_MODE_ENABLED); - } - } - } - - if(videoPlayer != NULL) { - videoPlayer->initPlayer(); - } + if (videoPlayer == NULL) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && + ::Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == true) { + Context *c = GraphicsInterface::getInstance().getCurrentContext(); + PlatformContextGl *glCtx = + static_cast(c)->getPlatformContextGlPtr(); + SDL_Window *window = glCtx->getScreenWindow(); + SDL_Surface *screen = glCtx->getScreenSurface(); + + string vlcPluginsPath = + Config::getInstance().getString("VideoPlayerPluginsPath", ""); + + videoPlayer = new ::Shared::Graphics::VideoPlayer( + &Renderer::getInstance(), playVideo, "", window, 0, 0, screen->w, + screen->h, screen->format->BitsPerPixel, false, vlcPluginsPath, + SystemFlags::VERBOSE_MODE_ENABLED); + } + } else { + if (videoPlayer->isPlaying() == false) { + delete videoPlayer; + videoPlayer = NULL; + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && + ::Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == true) { + Context *c = GraphicsInterface::getInstance().getCurrentContext(); + PlatformContextGl *glCtx = + static_cast(c)->getPlatformContextGlPtr(); + SDL_Window *window = glCtx->getScreenWindow(); + SDL_Surface *screen = glCtx->getScreenSurface(); + + string vlcPluginsPath = + Config::getInstance().getString("VideoPlayerPluginsPath", ""); + + videoPlayer = new ::Shared::Graphics::VideoPlayer( + &Renderer::getInstance(), playVideo, "", window, 0, 0, screen->w, + screen->h, screen->format->BitsPerPixel, false, vlcPluginsPath, + SystemFlags::VERBOSE_MODE_ENABLED); + } + } + } + + if (videoPlayer != NULL) { + videoPlayer->initPlayer(); + } } void Game::stopStreamingVideo(const string &playVideo) { - if(videoPlayer != NULL) { - videoPlayer->StopVideo(); - } + if (videoPlayer != NULL) { + videoPlayer->StopVideo(); + } } void Game::stopAllVideo() { - if(videoPlayer != NULL) { - videoPlayer->StopVideo(); - } + if (videoPlayer != NULL) { + videoPlayer->StopVideo(); + } } -bool Game::clientLagHandler(int slotIndex,bool networkPauseGameForLaggedClients) { - if(networkPauseGameForLaggedClients == true) { - printf("**WARNING** Detected lag from client: %d networkPauseGameForLaggedClients: %d\n",slotIndex,networkPauseGameForLaggedClients); - } - else { - printf("==> Requested Resume Game after Pause for lagging client(s)...\n"); - } - - this->networkPauseGameForLaggedClientsRequested = networkPauseGameForLaggedClients; - this->networkResumeGameForLaggedClientsRequested = !networkPauseGameForLaggedClients; - return true; +bool Game::clientLagHandler(int slotIndex, + bool networkPauseGameForLaggedClients) { + if (networkPauseGameForLaggedClients == true) { + printf("**WARNING** Detected lag from client: %d " + "networkPauseGameForLaggedClients: %d\n", + slotIndex, networkPauseGameForLaggedClients); + } else { + printf("==> Requested Resume Game after Pause for lagging client(s)...\n"); + } + + this->networkPauseGameForLaggedClientsRequested = + networkPauseGameForLaggedClients; + this->networkResumeGameForLaggedClientsRequested = + !networkPauseGameForLaggedClients; + return true; } -void Game::saveGame(){ - string file = this->saveGame(GameConstants::saveGameFilePattern); - char szBuf[8096]=""; - Lang &lang= Lang::getInstance(); - snprintf(szBuf,8096,lang.getString("GameSaved","",true).c_str(),file.c_str()); - console.addLine(szBuf); - - Config &config= Config::getInstance(); - config.setString("LastSavedGame",file); - config.save(); +void Game::saveGame() { + string file = this->saveGame(GameConstants::saveGameFilePattern); + char szBuf[8096] = ""; + Lang &lang = Lang::getInstance(); + snprintf(szBuf, 8096, lang.getString("GameSaved", "", true).c_str(), + file.c_str()); + console.addLine(szBuf); + + Config &config = Config::getInstance(); + config.setString("LastSavedGame", file); + config.save(); } string Game::saveGame(string name, const string &path) { - Config &config= Config::getInstance(); - // auto name file if using saved file pattern string - if(name == GameConstants::saveGameFilePattern) { - //time_t curTime = time(NULL); - //struct tm *loctime = localtime (&curTime); - struct tm loctime = threadsafe_localtime(systemtime_now()); - char szBuf2[100]=""; - strftime(szBuf2,100,"%Y%m%d_%H%M%S",&loctime); - - char szBuf[8096]=""; - snprintf(szBuf,8096,name.c_str(),szBuf2); - name = szBuf; - } - else if(name == GameConstants::saveGameFileAutoTestDefault) { - //time_t curTime = time(NULL); - //struct tm *loctime = localtime (&curTime); - struct tm loctime = threadsafe_localtime(systemtime_now()); - char szBuf2[100]=""; - strftime(szBuf2,100,"%Y%m%d_%H%M%S",&loctime); - - char szBuf[8096]=""; - snprintf(szBuf,8096,name.c_str(),szBuf2); - name = szBuf; - } - - // Save the file now - string saveGameFile = path + name; - if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - saveGameFile = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + saveGameFile; - } - else { - string userData = config.getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - saveGameFile = userData + saveGameFile; - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Saving game to [%s]\n",saveGameFile.c_str()); - - // This condition will re-play all the commands from a replay file - // INSTEAD of saving from a saved game. - if(config.getBool("SaveCommandsForReplay","false") == true) { - std::map mapTagReplacements; - XmlTree xmlTreeSaveGame(XML_RAPIDXML_ENGINE); - - xmlTreeSaveGame.init("megaglest-saved-game"); - XmlNode *rootNodeReplay = xmlTreeSaveGame.getRootNode(); - - //std::map mapTagReplacements; - //time_t now = time(NULL); - //struct tm *loctime = localtime (&now); - struct tm loctime = threadsafe_localtime(systemtime_now()); - char szBuf[4096]=""; - strftime(szBuf,4095,"%Y-%m-%d %H:%M:%S",&loctime); - - rootNodeReplay->addAttribute("version",glestVersionString, mapTagReplacements); - rootNodeReplay->addAttribute("timestamp",szBuf, mapTagReplacements); - - XmlNode *gameNodeReplay = rootNodeReplay->addChild("Game"); - gameSettings.saveGame(gameNodeReplay); - - gameNodeReplay->addAttribute("LastWorldFrameCount",intToStr(world.getFrameCount()), mapTagReplacements); - - for(unsigned int i = 0; i < replayCommandList.size(); ++i) { - std::pair &cmd = replayCommandList[i]; - XmlNode *networkCommandNode = cmd.second.saveGame(gameNodeReplay); - networkCommandNode->addAttribute("worldFrameCount",intToStr(cmd.first), mapTagReplacements); - } - - string replayFile = saveGameFile + ".replay"; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Saving game replay commands to [%s]\n",replayFile.c_str()); - xmlTreeSaveGame.save(replayFile); - } - - XmlTree xmlTree; - xmlTree.init("megaglest-saved-game"); - XmlNode *rootNode = xmlTree.getRootNode(); - - std::map mapTagReplacements; - //time_t now = time(NULL); - //struct tm *loctime = localtime (&now); - struct tm loctime = threadsafe_localtime(systemtime_now()); - char szBuf[4096]=""; - strftime(szBuf,4095,"%Y-%m-%d %H:%M:%S",&loctime); - - rootNode->addAttribute("version",glestVersionString, mapTagReplacements); - rootNode->addAttribute("timestamp",szBuf, mapTagReplacements); - - XmlNode *gameNode = rootNode->addChild("Game"); - //World world; - world.saveGame(gameNode); - //AiInterfaces aiInterfaces; - for(unsigned int i = 0; i < aiInterfaces.size(); ++i) { - AiInterface *aiIntf = aiInterfaces[i]; - if(aiIntf != NULL) { - aiIntf->saveGame(gameNode); - } - } - //Gui gui; - gui.saveGame(gameNode); - //GameCamera gameCamera; - gameCamera.saveGame(gameNode); - //Commander commander; - //Console console; - //ChatManager chatManager; - //ScriptManager scriptManager; - scriptManager.saveGame(gameNode); - - //misc - //Checksum checksum; - gameNode->addAttribute("checksum",intToStr(checksum.getSum()), mapTagReplacements); - //string loadingText; -// int mouse2d; - gameNode->addAttribute("mouse2d",intToStr(mouse2d), mapTagReplacements); -// int mouseX; - gameNode->addAttribute("mouseX",intToStr(mouseX), mapTagReplacements); -// int mouseY; //coords win32Api - gameNode->addAttribute("mouseY",intToStr(mouseY), mapTagReplacements); -// Vec2i mouseCellPos; - gameNode->addAttribute("mouseCellPos",mouseCellPos.getString(), mapTagReplacements); -// int updateFps, lastUpdateFps, avgUpdateFps; -// int totalRenderFps, renderFps, lastRenderFps, avgRenderFps,currentAvgRenderFpsTotal; - //Uint64 tickCount; - gameNode->addAttribute("tickCount",intToStr(tickCount), mapTagReplacements); - - //bool paused; - gameNode->addAttribute("paused",intToStr(paused), mapTagReplacements); - //bool gameOver; - gameNode->addAttribute("gameOver",intToStr(gameOver), mapTagReplacements); - //bool renderNetworkStatus; - //bool showFullConsole; - //bool mouseMoved; - //float scrollSpeed; - gameNode->addAttribute("scrollSpeed",floatToStr(scrollSpeed,6), mapTagReplacements); - //bool camLeftButtonDown; - //bool camRightButtonDown; - //bool camUpButtonDown; - //bool camDownButtonDown; - - //Speed speed; - gameNode->addAttribute("speed",intToStr(speed), mapTagReplacements); - - //GraphicMessageBox mainMessageBox; - //GraphicMessageBox errorMessageBox; - - //misc ptr - //ParticleSystem *weatherParticleSystem; - if(weatherParticleSystem != NULL) { - weatherParticleSystem->saveGame(gameNode); - } - //GameSettings gameSettings; - gameSettings.saveGame(gameNode); - //Vec2i lastMousePos; - gameNode->addAttribute("lastMousePos",lastMousePos.getString(), mapTagReplacements); - //time_t lastRenderLog2d; - gameNode->addAttribute("lastRenderLog2d",intToStr(lastRenderLog2d), mapTagReplacements); - //DisplayMessageFunction originalDisplayMsgCallback; - //bool isFirstRender; - gameNode->addAttribute("isFirstRender",intToStr(isFirstRender), mapTagReplacements); - - //bool quitTriggeredIndicator; - //int original_updateFps; - gameNode->addAttribute("original_updateFps",intToStr(original_updateFps), mapTagReplacements); - //int original_cameraFps; - gameNode->addAttribute("original_cameraFps",intToStr(original_cameraFps), mapTagReplacements); - - //bool captureAvgTestStatus; - gameNode->addAttribute("captureAvgTestStatus",intToStr(captureAvgTestStatus), mapTagReplacements); - //int updateFpsAvgTest; - gameNode->addAttribute("updateFpsAvgTest",intToStr(updateFpsAvgTest), mapTagReplacements); - //int renderFpsAvgTest; - gameNode->addAttribute("renderFpsAvgTest",intToStr(renderFpsAvgTest), mapTagReplacements); - - //int renderExtraTeamColor; - gameNode->addAttribute("renderExtraTeamColor",intToStr(renderExtraTeamColor), mapTagReplacements); - - //static const int renderTeamColorCircleBit=1; - //static const int renderTeamColorPlaneBit=2; - - //bool photoModeEnabled; - gameNode->addAttribute("photoModeEnabled",intToStr(photoModeEnabled), mapTagReplacements); - //bool visibleHUD; - gameNode->addAttribute("visibleHUD",intToStr(visibleHUD), mapTagReplacements); - - //bool timeDisplay - gameNode->addAttribute("timeDisplay",intToStr(timeDisplay), mapTagReplacements); - - //bool withRainEffect; - gameNode->addAttribute("withRainEffect",intToStr(withRainEffect), mapTagReplacements); - //Program *program; - - //bool gameStarted; - gameNode->addAttribute("gameStarted",intToStr(gameStarted), mapTagReplacements); - - //time_t lastMaxUnitCalcTime; - gameNode->addAttribute("lastMaxUnitCalcTime",intToStr(lastMaxUnitCalcTime), mapTagReplacements); - - //PopupMenu popupMenu; - //PopupMenu popupMenuSwitchTeams; - - //std::map switchTeamIndexMap; - //GraphicMessageBox switchTeamConfirmMessageBox; - - //int exitGamePopupMenuIndex; - //int joinTeamPopupMenuIndex; - //int pauseGamePopupMenuIndex; - //int keyboardSetupPopupMenuIndex; - //GLuint statelist3dMenu; - //ProgramState *currentUIState; - - //bool masterserverMode; - - //StrSound *currentAmbientSound; - - //time_t lastNetworkPlayerConnectionCheck; - gameNode->addAttribute("lastNetworkPlayerConnectionCheck",intToStr(lastNetworkPlayerConnectionCheck), mapTagReplacements); - - //time_t lastMasterServerGameStatsDump; - gameNode->addAttribute("lastMasterServerGameStatsDump",intToStr(lastMasterServerGameStatsDump), mapTagReplacements); - - XmlNode *unitHighlightListNode = gameNode->addChild("unitHighlightList"); - //for(unsigned int i = 0; i < unitHighlightList.size(); ++i) { - for(std::map::iterator iterMap = unitHighlightList.begin(); - iterMap != unitHighlightList.end(); ++iterMap) { - HighlightSpecialUnitInfo &info = iterMap->second; - XmlNode *infoNode = unitHighlightListNode->addChild("info"); - infoNode->addAttribute("unitid",intToStr(iterMap->first), mapTagReplacements); - infoNode->addAttribute("radius",floatToStr(info.radius,6), mapTagReplacements); - infoNode->addAttribute("thickness",floatToStr(info.thickness,6), mapTagReplacements); - infoNode->addAttribute("color",info.color.getString(), mapTagReplacements); - } - - gameNode->addAttribute("disableSpeedChange",intToStr(disableSpeedChange), mapTagReplacements); - - xmlTree.save(saveGameFile); - - if(masterserverMode == false) { - // take Screenshot - string jpgFileName=saveGameFile+".jpg"; - // menu is already disabled, last rendered screen is still with enabled one. Lets render again: - render3d(); - render2d(); - Renderer::getInstance().saveScreen(jpgFileName,config.getInt("SaveGameScreenshotWidth","800"),config.getInt("SaveGameScreenshotHeight","600")); - } - - return saveGameFile; + Config &config = Config::getInstance(); + // auto name file if using saved file pattern string + if (name == GameConstants::saveGameFilePattern) { + // time_t curTime = time(NULL); + // struct tm *loctime = localtime (&curTime); + struct tm loctime = threadsafe_localtime(systemtime_now()); + char szBuf2[100] = ""; + strftime(szBuf2, 100, "%Y%m%d_%H%M%S", &loctime); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, name.c_str(), szBuf2); + name = szBuf; + } else if (name == GameConstants::saveGameFileAutoTestDefault) { + // time_t curTime = time(NULL); + // struct tm *loctime = localtime (&curTime); + struct tm loctime = threadsafe_localtime(systemtime_now()); + char szBuf2[100] = ""; + strftime(szBuf2, 100, "%Y%m%d_%H%M%S", &loctime); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, name.c_str(), szBuf2); + name = szBuf; + } + + // Save the file now + string saveGameFile = path + name; + if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { + saveGameFile = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + + saveGameFile; + } else { + string userData = config.getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + saveGameFile = userData + saveGameFile; + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Saving game to [%s]\n", saveGameFile.c_str()); + + // This condition will re-play all the commands from a replay file + // INSTEAD of saving from a saved game. + if (config.getBool("SaveCommandsForReplay", "false") == true) { + std::map mapTagReplacements; + XmlTree xmlTreeSaveGame(XML_RAPIDXML_ENGINE); + + xmlTreeSaveGame.init("megaglest-saved-game"); + XmlNode *rootNodeReplay = xmlTreeSaveGame.getRootNode(); + + // std::map mapTagReplacements; + // time_t now = time(NULL); + // struct tm *loctime = localtime (&now); + struct tm loctime = threadsafe_localtime(systemtime_now()); + char szBuf[4096] = ""; + strftime(szBuf, 4095, "%Y-%m-%d %H:%M:%S", &loctime); + + rootNodeReplay->addAttribute("version", glestVersionString, + mapTagReplacements); + rootNodeReplay->addAttribute("timestamp", szBuf, mapTagReplacements); + + XmlNode *gameNodeReplay = rootNodeReplay->addChild("Game"); + gameSettings.saveGame(gameNodeReplay); + + gameNodeReplay->addAttribute("LastWorldFrameCount", + intToStr(world.getFrameCount()), + mapTagReplacements); + + for (unsigned int i = 0; i < replayCommandList.size(); ++i) { + std::pair &cmd = replayCommandList[i]; + XmlNode *networkCommandNode = cmd.second.saveGame(gameNodeReplay); + networkCommandNode->addAttribute("worldFrameCount", intToStr(cmd.first), + mapTagReplacements); + } + + string replayFile = saveGameFile + ".replay"; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Saving game replay commands to [%s]\n", replayFile.c_str()); + xmlTreeSaveGame.save(replayFile); + } + + XmlTree xmlTree; + xmlTree.init("megaglest-saved-game"); + XmlNode *rootNode = xmlTree.getRootNode(); + + std::map mapTagReplacements; + // time_t now = time(NULL); + // struct tm *loctime = localtime (&now); + struct tm loctime = threadsafe_localtime(systemtime_now()); + char szBuf[4096] = ""; + strftime(szBuf, 4095, "%Y-%m-%d %H:%M:%S", &loctime); + + rootNode->addAttribute("version", glestVersionString, mapTagReplacements); + rootNode->addAttribute("timestamp", szBuf, mapTagReplacements); + + XmlNode *gameNode = rootNode->addChild("Game"); + // World world; + world.saveGame(gameNode); + // AiInterfaces aiInterfaces; + for (unsigned int i = 0; i < aiInterfaces.size(); ++i) { + AiInterface *aiIntf = aiInterfaces[i]; + if (aiIntf != NULL) { + aiIntf->saveGame(gameNode); + } + } + // Gui gui; + gui.saveGame(gameNode); + // GameCamera gameCamera; + gameCamera.saveGame(gameNode); + // Commander commander; + // Console console; + // ChatManager chatManager; + // ScriptManager scriptManager; + scriptManager.saveGame(gameNode); + + // misc + // Checksum checksum; + gameNode->addAttribute("checksum", intToStr(checksum.getSum()), + mapTagReplacements); + // string loadingText; + // int mouse2d; + gameNode->addAttribute("mouse2d", intToStr(mouse2d), mapTagReplacements); + // int mouseX; + gameNode->addAttribute("mouseX", intToStr(mouseX), mapTagReplacements); + // int mouseY; //coords win32Api + gameNode->addAttribute("mouseY", intToStr(mouseY), mapTagReplacements); + // Vec2i mouseCellPos; + gameNode->addAttribute("mouseCellPos", mouseCellPos.getString(), + mapTagReplacements); + // int updateFps, lastUpdateFps, avgUpdateFps; + // int totalRenderFps, renderFps, lastRenderFps, + // avgRenderFps,currentAvgRenderFpsTotal; Uint64 tickCount; + gameNode->addAttribute("tickCount", intToStr(tickCount), mapTagReplacements); + + // bool paused; + gameNode->addAttribute("paused", intToStr(paused), mapTagReplacements); + // bool gameOver; + gameNode->addAttribute("gameOver", intToStr(gameOver), mapTagReplacements); + // bool renderNetworkStatus; + // bool showFullConsole; + // bool mouseMoved; + // float scrollSpeed; + gameNode->addAttribute("scrollSpeed", floatToStr(scrollSpeed, 6), + mapTagReplacements); + // bool camLeftButtonDown; + // bool camRightButtonDown; + // bool camUpButtonDown; + // bool camDownButtonDown; + + // Speed speed; + gameNode->addAttribute("speed", intToStr(speed), mapTagReplacements); + + // GraphicMessageBox mainMessageBox; + // GraphicMessageBox errorMessageBox; + + // misc ptr + // ParticleSystem *weatherParticleSystem; + if (weatherParticleSystem != NULL) { + weatherParticleSystem->saveGame(gameNode); + } + // GameSettings gameSettings; + gameSettings.saveGame(gameNode); + // Vec2i lastMousePos; + gameNode->addAttribute("lastMousePos", lastMousePos.getString(), + mapTagReplacements); + // time_t lastRenderLog2d; + gameNode->addAttribute("lastRenderLog2d", intToStr(lastRenderLog2d), + mapTagReplacements); + // DisplayMessageFunction originalDisplayMsgCallback; + // bool isFirstRender; + gameNode->addAttribute("isFirstRender", intToStr(isFirstRender), + mapTagReplacements); + + // bool quitTriggeredIndicator; + // int original_updateFps; + gameNode->addAttribute("original_updateFps", intToStr(original_updateFps), + mapTagReplacements); + // int original_cameraFps; + gameNode->addAttribute("original_cameraFps", intToStr(original_cameraFps), + mapTagReplacements); + + // bool captureAvgTestStatus; + gameNode->addAttribute("captureAvgTestStatus", intToStr(captureAvgTestStatus), + mapTagReplacements); + // int updateFpsAvgTest; + gameNode->addAttribute("updateFpsAvgTest", intToStr(updateFpsAvgTest), + mapTagReplacements); + // int renderFpsAvgTest; + gameNode->addAttribute("renderFpsAvgTest", intToStr(renderFpsAvgTest), + mapTagReplacements); + + // int renderExtraTeamColor; + gameNode->addAttribute("renderExtraTeamColor", intToStr(renderExtraTeamColor), + mapTagReplacements); + + // static const int renderTeamColorCircleBit=1; + // static const int renderTeamColorPlaneBit=2; + + // bool photoModeEnabled; + gameNode->addAttribute("photoModeEnabled", intToStr(photoModeEnabled), + mapTagReplacements); + // bool visibleHUD; + gameNode->addAttribute("visibleHUD", intToStr(visibleHUD), + mapTagReplacements); + + // bool timeDisplay + gameNode->addAttribute("timeDisplay", intToStr(timeDisplay), + mapTagReplacements); + + // bool withRainEffect; + gameNode->addAttribute("withRainEffect", intToStr(withRainEffect), + mapTagReplacements); + // Program *program; + + // bool gameStarted; + gameNode->addAttribute("gameStarted", intToStr(gameStarted), + mapTagReplacements); + + // time_t lastMaxUnitCalcTime; + gameNode->addAttribute("lastMaxUnitCalcTime", intToStr(lastMaxUnitCalcTime), + mapTagReplacements); + + // PopupMenu popupMenu; + // PopupMenu popupMenuSwitchTeams; + + // std::map switchTeamIndexMap; + // GraphicMessageBox switchTeamConfirmMessageBox; + + // int exitGamePopupMenuIndex; + // int joinTeamPopupMenuIndex; + // int pauseGamePopupMenuIndex; + // int keyboardSetupPopupMenuIndex; + // GLuint statelist3dMenu; + // ProgramState *currentUIState; + + // bool masterserverMode; + + // StrSound *currentAmbientSound; + + // time_t lastNetworkPlayerConnectionCheck; + gameNode->addAttribute("lastNetworkPlayerConnectionCheck", + intToStr(lastNetworkPlayerConnectionCheck), + mapTagReplacements); + + // time_t lastMasterServerGameStatsDump; + gameNode->addAttribute("lastMasterServerGameStatsDump", + intToStr(lastMasterServerGameStatsDump), + mapTagReplacements); + + XmlNode *unitHighlightListNode = gameNode->addChild("unitHighlightList"); + // for(unsigned int i = 0; i < unitHighlightList.size(); ++i) { + for (std::map::iterator iterMap = + unitHighlightList.begin(); + iterMap != unitHighlightList.end(); ++iterMap) { + HighlightSpecialUnitInfo &info = iterMap->second; + XmlNode *infoNode = unitHighlightListNode->addChild("info"); + infoNode->addAttribute("unitid", intToStr(iterMap->first), + mapTagReplacements); + infoNode->addAttribute("radius", floatToStr(info.radius, 6), + mapTagReplacements); + infoNode->addAttribute("thickness", floatToStr(info.thickness, 6), + mapTagReplacements); + infoNode->addAttribute("color", info.color.getString(), mapTagReplacements); + } + + gameNode->addAttribute("disableSpeedChange", intToStr(disableSpeedChange), + mapTagReplacements); + + xmlTree.save(saveGameFile); + + if (masterserverMode == false) { + // take Screenshot + string jpgFileName = saveGameFile + ".jpg"; + // menu is already disabled, last rendered screen is still with enabled one. + // Lets render again: + render3d(); + render2d(); + Renderer::getInstance().saveScreen( + jpgFileName, config.getInt("SaveGameScreenshotWidth", "800"), + config.getInt("SaveGameScreenshotHeight", "600")); + } + + return saveGameFile; } -void Game::loadGame(string name,Program *programPtr,bool isMasterserverMode,const GameSettings *joinGameSettings) { - Config &config= Config::getInstance(); - // This condition will re-play all the commands from a replay file - // INSTEAD of saving from a saved game. - if(joinGameSettings == NULL && config.getBool("SaveCommandsForReplay","false") == true) { - XmlTree xmlTreeReplay(XML_RAPIDXML_ENGINE); - std::map mapExtraTagReplacementValues; - xmlTreeReplay.load(name + ".replay", Properties::getTagReplacementValues(&mapExtraTagReplacementValues),true); - - const XmlNode *rootNode= xmlTreeReplay.getRootNode(); - - if(rootNode->hasChild("megaglest-saved-game") == true) { - rootNode = rootNode->getChild("megaglest-saved-game"); - } - - //const XmlNode *versionNode= rootNode->getChild("megaglest-saved-game"); - const XmlNode *versionNode= rootNode; - - Lang &lang= Lang::getInstance(); - string gameVer = versionNode->getAttribute("version")->getValue(); - if(gameVer != glestVersionString && checkVersionComptability(gameVer, glestVersionString) == false){ - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("SavedGameBadVersion").c_str(),gameVer.c_str(),glestVersionString.c_str()); - throw megaglest_runtime_error(szBuf,true); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Found saved game version that matches your application version: [%s] --> [%s]\n",gameVer.c_str(),glestVersionString.c_str()); - - XmlNode *gameNode = rootNode->getChild("Game"); - - GameSettings newGameSettingsReplay; - newGameSettingsReplay.loadGame(gameNode); - //printf("Loading scenario [%s]\n",newGameSettingsReplay.getScenarioDir().c_str()); - if(newGameSettingsReplay.getScenarioDir() != "" && fileExists(newGameSettingsReplay.getScenarioDir()) == false) { - newGameSettingsReplay.setScenarioDir(Scenario::getScenarioPath(Config::getInstance().getPathListForType(ptScenarios),newGameSettingsReplay.getScenario())); - - //printf("Loading scenario #2 [%s]\n",newGameSettingsReplay.getScenarioDir().c_str()); - } - - //GameSettings newGameSettings; - //newGameSettings.loadGame(gameNode); - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Game settings loaded\n"); - - NetworkManager &networkManager= NetworkManager::getInstance(); - networkManager.end(); - networkManager.init(nrServer,true); - - Game *newGame = new Game(programPtr, &newGameSettingsReplay, isMasterserverMode); - newGame->lastworldFrameCountForReplay = gameNode->getAttribute("LastWorldFrameCount")->getIntValue(); - - vector networkCommandNodeList = gameNode->getChildList("NetworkCommand"); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("networkCommandNodeList.size() = " MG_SIZE_T_SPECIFIER "\n",networkCommandNodeList.size()); - for(unsigned int i = 0; i < networkCommandNodeList.size(); ++i) { - XmlNode *node = networkCommandNodeList[i]; - int worldFrameCount = node->getAttribute("worldFrameCount")->getIntValue(); - NetworkCommand command; - command.loadGame(node); - newGame->commander.addToReplayCommandList(command,worldFrameCount); - } - - programPtr->setState(newGame); - return; - } - - XmlTree xmlTree(XML_RAPIDXML_ENGINE); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Before load of XML\n"); - std::map mapExtraTagReplacementValues; - xmlTree.load(name, Properties::getTagReplacementValues(&mapExtraTagReplacementValues),true); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("After load of XML\n"); - - const XmlNode *rootNode= xmlTree.getRootNode(); - if(rootNode->hasChild("megaglest-saved-game") == true) { - rootNode = rootNode->getChild("megaglest-saved-game"); - } - - //const XmlNode *versionNode= rootNode->getChild("megaglest-saved-game"); - const XmlNode *versionNode= rootNode; - - Lang &lang= Lang::getInstance(); - string gameVer = versionNode->getAttribute("version")->getValue(); - // this is the version check for loading normal save games from menu_state_load_game - if (gameVer != glestVersionString - && (compareMajorMinorVersion(gameVer, lastCompatibleSaveGameVersionString) < 0 - || compareMajorMinorVersion(glestVersionString, gameVer) < 0)) { - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("SavedGameBadVersion").c_str(),gameVer.c_str(),glestVersionString.c_str()); - throw megaglest_runtime_error(szBuf,true); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Found saved game version that matches your application version: [%s] --> [%s]\n",gameVer.c_str(),glestVersionString.c_str()); - - XmlNode *gameNode = rootNode->getChild("Game"); - GameSettings newGameSettings; - if(joinGameSettings != NULL) { - newGameSettings = *joinGameSettings; - - XmlNode *worldNode = gameNode->getChild("World"); - XmlNode *guiNode = gameNode->getChild("Gui"); - XmlNode *selectionNode = guiNode->getChild("Selection"); - XmlNode *statsNode = worldNode->getChild("Stats"); - XmlNode *minimapNode = worldNode->getChild("Minimap"); - - if(gameVer != glestVersionString && checkVersionComptability(gameVer, glestVersionString) == false){ - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("SavedGameBadVersion").c_str(),gameVer.c_str(),glestVersionString.c_str()); - throw megaglest_runtime_error(szBuf,true); - } - // This is explored fog of war for the host player, clear it - minimapNode->clearChild("fowPixmap1"); - - NetworkManager &networkManager= NetworkManager::getInstance(); - //NetworkRole role = networkManager.getNetworkRole(); - ClientInterface *clientInterface = dynamic_cast(networkManager.getClientInterface()); - - for(int i= 0; igetPlayerIndex()) { - newGameSettings.setThisFactionIndex(i); - newGameSettings.setFactionControl(i, ctNetwork); - - worldNode->getAttribute("thisFactionIndex")->setValue(intToStr(i)); - //worldNode->getAttribute("thisTeamIndex")->setValue(intToStr(newGameSettings.getTeam(i))); - - XmlNode *factionNode = worldNode->getChild("Faction",i); - factionNode->getAttribute("thisFaction")->setValue(intToStr(i)); - factionNode->getAttribute("control")->setValue(intToStr(ctNetwork)); - - selectionNode->getAttribute("factionIndex")->setValue(intToStr(i)); - //selectionNode->getAttribute("teamIndex")->setValue(intToStr(newGameSettings.getTeam(i))); - - statsNode->getAttribute("thisFactionIndex")->setValue(intToStr(i)); - } - else { - XmlNode *factionNode = worldNode->getChild("Faction",i); - factionNode->getAttribute("thisFaction")->setValue(intToStr(0)); - } - } - } - else { - newGameSettings.loadGame(gameNode); - //printf("Loading scenario [%s]\n",newGameSettings.getScenarioDir().c_str()); - if(newGameSettings.getScenarioDir() != "" && fileExists(newGameSettings.getScenarioDir()) == false) { - newGameSettings.setScenarioDir(Scenario::getScenarioPath(Config::getInstance().getPathListForType(ptScenarios),newGameSettings.getScenario())); - - //printf("Loading scenario #2 [%s]\n",newGameSettings.getScenarioDir().c_str()); - } - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Game settings loaded\n"); - - if(joinGameSettings == NULL) { - NetworkManager &networkManager= NetworkManager::getInstance(); - networkManager.end(); - networkManager.init(nrServer,true); - } - - Game *newGame = new Game(programPtr, &newGameSettings, isMasterserverMode); - - newGame->loadGameNode = gameNode; - newGame->inJoinGameLoading = (joinGameSettings != NULL); - -// newGame->mouse2d = gameNode->getAttribute("mouse2d")->getIntValue(); -// int mouseX; -// newGame->mouseX = gameNode->getAttribute("mouseX")->getIntValue(); -// int mouseY; //coords win32Api -// newGame->mouseY = gameNode->getAttribute("mouseY")->getIntValue(); -// Vec2i mouseCellPos; -// newGame->mouseCellPos = Vec2i::strToVec2(gameNode->getAttribute("mouseCellPos")->getValue()); -// int updateFps, lastUpdateFps, avgUpdateFps; -// int totalRenderFps, renderFps, lastRenderFps, avgRenderFps,currentAvgRenderFpsTotal; - //Uint64 tickCount; - newGame->tickCount = gameNode->getAttribute("tickCount")->getIntValue(); - - //bool paused; - if(newGame->inJoinGameLoading==true){ - newGame->paused = gameNode->getAttribute("paused")->getIntValue() != 0; - }else{ - //newGame->paused = gameNode->getAttribute("paused")->getIntValue() != 0; - newGame->paused = true; - } - if(newGame->paused) newGame->console.addLine(lang.getString("GamePaused")); - //bool gameOver; - newGame->gameOver = gameNode->getAttribute("gameOver")->getIntValue() != 0; - //bool renderNetworkStatus; - //bool showFullConsole; - //bool mouseMoved; - //float scrollSpeed; -// newGame->scrollSpeed = gameNode->getAttribute("scrollSpeed")->getFloatValue(); - //bool camLeftButtonDown; - //bool camRightButtonDown; - //bool camUpButtonDown; - //bool camDownButtonDown; - - //Speed speed; - //gameNode->addAttribute("speed",intToStr(speed), mapTagReplacements); - - //GraphicMessageBox mainMessageBox; - //GraphicMessageBox errorMessageBox; - - //misc ptr - //ParticleSystem *weatherParticleSystem; -// if(weatherParticleSystem != NULL) { -// weatherParticleSystem->saveGame(gameNode); -// } - //GameSettings gameSettings; -// gameSettings.saveGame(gameNode); - //Vec2i lastMousePos; -// gameNode->addAttribute("lastMousePos",lastMousePos.getString(), mapTagReplacements); - //time_t lastRenderLog2d; -// gameNode->addAttribute("lastRenderLog2d",intToStr(lastRenderLog2d), mapTagReplacements); - //DisplayMessageFunction originalDisplayMsgCallback; - //bool isFirstRender; -// gameNode->addAttribute("isFirstRender",intToStr(isFirstRender), mapTagReplacements); - - //bool quitTriggeredIndicator; - //int original_updateFps; -// gameNode->addAttribute("original_updateFps",intToStr(original_updateFps), mapTagReplacements); - //int original_cameraFps; -// gameNode->addAttribute("original_cameraFps",intToStr(original_cameraFps), mapTagReplacements); - - //bool captureAvgTestStatus; -// gameNode->addAttribute("captureAvgTestStatus",intToStr(captureAvgTestStatus), mapTagReplacements); - //int updateFpsAvgTest; -// gameNode->addAttribute("updateFpsAvgTest",intToStr(updateFpsAvgTest), mapTagReplacements); - //int renderFpsAvgTest; -// gameNode->addAttribute("renderFpsAvgTest",intToStr(renderFpsAvgTest), mapTagReplacements); - - //int renderExtraTeamColor; - newGame->renderExtraTeamColor = gameNode->getAttribute("renderExtraTeamColor")->getIntValue(); - - //static const int renderTeamColorCircleBit=1; - //static const int renderTeamColorPlaneBit=2; - - //bool photoModeEnabled; - //gameNode->addAttribute("photoModeEnabled",intToStr(photoModeEnabled), mapTagReplacements); - newGame->photoModeEnabled = gameNode->getAttribute("photoModeEnabled")->getIntValue() != 0; - //bool visibleHUD; - //gameNode->addAttribute("visibleHUD",intToStr(visibleHUD), mapTagReplacements); - newGame->visibleHUD = gameNode->getAttribute("visibleHUD")->getIntValue() != 0; - newGame->timeDisplay = gameNode->getAttribute("timeDisplay")->getIntValue() != 0; - //bool withRainEffect; - //gameNode->addAttribute("withRainEffect",intToStr(withRainEffect), mapTagReplacements); - newGame->withRainEffect = gameNode->getAttribute("withRainEffect")->getIntValue() != 0; - //Program *program; - - if(joinGameSettings == NULL) { - if(gameNode->hasChild("unitHighlightList") == true) { - XmlNode *unitHighlightListNode = gameNode->getChild("unitHighlightList"); - vector infoNodeList = unitHighlightListNode->getChildList("info"); - for(unsigned int i = 0; i < infoNodeList.size(); ++i) { - XmlNode *infoNode = infoNodeList[i]; - - int unitId = infoNode->getAttribute("radius")->getIntValue(); - HighlightSpecialUnitInfo info; - info.radius = infoNode->getAttribute("radius")->getFloatValue(); - info.thickness = infoNode->getAttribute("thickness")->getFloatValue(); - info.color = Vec4f::strToVec4(infoNode->getAttribute("color")->getValue()); - - newGame->unitHighlightList[unitId] = info; - } - } - } - - newGame->timeDisplay = gameNode->getAttribute("timeDisplay")->getIntValue() != 0; - - if(gameNode->hasAttribute("disableSpeedChange") == true) { - newGame->disableSpeedChange = gameNode->getAttribute("disableSpeedChange")->getIntValue() != 0; - } - - //bool gameStarted; - //gameNode->addAttribute("gameStarted",intToStr(gameStarted), mapTagReplacements); -// newGame->gameStarted = gameNode->getAttribute("gameStarted")->getIntValue(); - - //time_t lastMaxUnitCalcTime; - //gameNode->addAttribute("lastMaxUnitCalcTime",intToStr(lastMaxUnitCalcTime), mapTagReplacements); - - //PopupMenu popupMenu; - //PopupMenu popupMenuSwitchTeams; - - //std::map switchTeamIndexMap; - //GraphicMessageBox switchTeamConfirmMessageBox; - - //int exitGamePopupMenuIndex; - //int joinTeamPopupMenuIndex; - //int pauseGamePopupMenuIndex; - //int keyboardSetupPopupMenuIndex; - //GLuint statelist3dMenu; - //ProgramState *currentUIState; - - //bool masterserverMode; - - //StrSound *currentAmbientSound; - - //time_t lastNetworkPlayerConnectionCheck; - //gameNode->addAttribute("lastNetworkPlayerConnectionCheck",intToStr(lastNetworkPlayerConnectionCheck), mapTagReplacements); - - //time_t lastMasterServerGameStatsDump; - //gameNode->addAttribute("lastMasterServerGameStatsDump",intToStr(lastMasterServerGameStatsDump), mapTagReplacements); - - if(joinGameSettings == NULL) { - newGame->gameCamera.loadGame(gameNode); - } - - const XmlNode *worldNode = gameNode->getChild("World"); - newGame->world.loadGame(worldNode); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Starting Game ...\n"); - programPtr->setState(newGame); +void Game::loadGame(string name, Program *programPtr, bool isMasterserverMode, + const GameSettings *joinGameSettings) { + Config &config = Config::getInstance(); + // This condition will re-play all the commands from a replay file + // INSTEAD of saving from a saved game. + if (joinGameSettings == NULL && + config.getBool("SaveCommandsForReplay", "false") == true) { + XmlTree xmlTreeReplay(XML_RAPIDXML_ENGINE); + std::map mapExtraTagReplacementValues; + xmlTreeReplay.load( + name + ".replay", + Properties::getTagReplacementValues(&mapExtraTagReplacementValues), + true); + + const XmlNode *rootNode = xmlTreeReplay.getRootNode(); + + if (rootNode->hasChild("megaglest-saved-game") == true) { + rootNode = rootNode->getChild("megaglest-saved-game"); + } + + // const XmlNode *versionNode= rootNode->getChild("megaglest-saved-game"); + const XmlNode *versionNode = rootNode; + + Lang &lang = Lang::getInstance(); + string gameVer = versionNode->getAttribute("version")->getValue(); + if (gameVer != glestVersionString && + checkVersionComptability(gameVer, glestVersionString) == false) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, lang.getString("SavedGameBadVersion").c_str(), + gameVer.c_str(), glestVersionString.c_str()); + throw megaglest_runtime_error(szBuf, true); + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Found saved game version that matches your application version: " + "[%s] --> [%s]\n", + gameVer.c_str(), glestVersionString.c_str()); + + XmlNode *gameNode = rootNode->getChild("Game"); + + GameSettings newGameSettingsReplay; + newGameSettingsReplay.loadGame(gameNode); + // printf("Loading scenario + // [%s]\n",newGameSettingsReplay.getScenarioDir().c_str()); + if (newGameSettingsReplay.getScenarioDir() != "" && + fileExists(newGameSettingsReplay.getScenarioDir()) == false) { + newGameSettingsReplay.setScenarioDir(Scenario::getScenarioPath( + Config::getInstance().getPathListForType(ptScenarios), + newGameSettingsReplay.getScenario())); + + // printf("Loading scenario #2 + // [%s]\n",newGameSettingsReplay.getScenarioDir().c_str()); + } + + // GameSettings newGameSettings; + // newGameSettings.loadGame(gameNode); + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Game settings loaded\n"); + + NetworkManager &networkManager = NetworkManager::getInstance(); + networkManager.end(); + networkManager.init(nrServer, true); + + Game *newGame = + new Game(programPtr, &newGameSettingsReplay, isMasterserverMode); + newGame->lastworldFrameCountForReplay = + gameNode->getAttribute("LastWorldFrameCount")->getIntValue(); + + vector networkCommandNodeList = + gameNode->getChildList("NetworkCommand"); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("networkCommandNodeList.size() = " MG_SIZE_T_SPECIFIER "\n", + networkCommandNodeList.size()); + for (unsigned int i = 0; i < networkCommandNodeList.size(); ++i) { + XmlNode *node = networkCommandNodeList[i]; + int worldFrameCount = + node->getAttribute("worldFrameCount")->getIntValue(); + NetworkCommand command; + command.loadGame(node); + newGame->commander.addToReplayCommandList(command, worldFrameCount); + } + + programPtr->setState(newGame); + return; + } + + XmlTree xmlTree(XML_RAPIDXML_ENGINE); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Before load of XML\n"); + std::map mapExtraTagReplacementValues; + xmlTree.load( + name, Properties::getTagReplacementValues(&mapExtraTagReplacementValues), + true); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("After load of XML\n"); + + const XmlNode *rootNode = xmlTree.getRootNode(); + if (rootNode->hasChild("megaglest-saved-game") == true) { + rootNode = rootNode->getChild("megaglest-saved-game"); + } + + // const XmlNode *versionNode= rootNode->getChild("megaglest-saved-game"); + const XmlNode *versionNode = rootNode; + + Lang &lang = Lang::getInstance(); + string gameVer = versionNode->getAttribute("version")->getValue(); + // this is the version check for loading normal save games from + // menu_state_load_game + if (gameVer != glestVersionString && + (compareMajorMinorVersion(gameVer, lastCompatibleSaveGameVersionString) < + 0 || + compareMajorMinorVersion(glestVersionString, gameVer) < 0)) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, lang.getString("SavedGameBadVersion").c_str(), + gameVer.c_str(), glestVersionString.c_str()); + throw megaglest_runtime_error(szBuf, true); + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Found saved game version that matches your application version: " + "[%s] --> [%s]\n", + gameVer.c_str(), glestVersionString.c_str()); + + XmlNode *gameNode = rootNode->getChild("Game"); + GameSettings newGameSettings; + if (joinGameSettings != NULL) { + newGameSettings = *joinGameSettings; + + XmlNode *worldNode = gameNode->getChild("World"); + XmlNode *guiNode = gameNode->getChild("Gui"); + XmlNode *selectionNode = guiNode->getChild("Selection"); + XmlNode *statsNode = worldNode->getChild("Stats"); + XmlNode *minimapNode = worldNode->getChild("Minimap"); + + if (gameVer != glestVersionString && + checkVersionComptability(gameVer, glestVersionString) == false) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, lang.getString("SavedGameBadVersion").c_str(), + gameVer.c_str(), glestVersionString.c_str()); + throw megaglest_runtime_error(szBuf, true); + } + // This is explored fog of war for the host player, clear it + minimapNode->clearChild("fowPixmap1"); + + NetworkManager &networkManager = NetworkManager::getInstance(); + // NetworkRole role = networkManager.getNetworkRole(); + ClientInterface *clientInterface = + dynamic_cast(networkManager.getClientInterface()); + + for (int i = 0; i < newGameSettings.getFactionCount(); ++i) { + // replace by network + if (newGameSettings.getFactionControl(i) == ctHuman) { + newGameSettings.setFactionControl(i, ctNetwork); + } + + // set the faction index + if (newGameSettings.getStartLocationIndex(i) == + clientInterface->getPlayerIndex()) { + newGameSettings.setThisFactionIndex(i); + newGameSettings.setFactionControl(i, ctNetwork); + + worldNode->getAttribute("thisFactionIndex")->setValue(intToStr(i)); + // worldNode->getAttribute("thisTeamIndex")->setValue(intToStr(newGameSettings.getTeam(i))); + + XmlNode *factionNode = worldNode->getChild("Faction", i); + factionNode->getAttribute("thisFaction")->setValue(intToStr(i)); + factionNode->getAttribute("control")->setValue(intToStr(ctNetwork)); + + selectionNode->getAttribute("factionIndex")->setValue(intToStr(i)); + // selectionNode->getAttribute("teamIndex")->setValue(intToStr(newGameSettings.getTeam(i))); + + statsNode->getAttribute("thisFactionIndex")->setValue(intToStr(i)); + } else { + XmlNode *factionNode = worldNode->getChild("Faction", i); + factionNode->getAttribute("thisFaction")->setValue(intToStr(0)); + } + } + } else { + newGameSettings.loadGame(gameNode); + // printf("Loading scenario + // [%s]\n",newGameSettings.getScenarioDir().c_str()); + if (newGameSettings.getScenarioDir() != "" && + fileExists(newGameSettings.getScenarioDir()) == false) { + newGameSettings.setScenarioDir(Scenario::getScenarioPath( + Config::getInstance().getPathListForType(ptScenarios), + newGameSettings.getScenario())); + + // printf("Loading scenario #2 + // [%s]\n",newGameSettings.getScenarioDir().c_str()); + } + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Game settings loaded\n"); + + if (joinGameSettings == NULL) { + NetworkManager &networkManager = NetworkManager::getInstance(); + networkManager.end(); + networkManager.init(nrServer, true); + } + + Game *newGame = new Game(programPtr, &newGameSettings, isMasterserverMode); + + newGame->loadGameNode = gameNode; + newGame->inJoinGameLoading = (joinGameSettings != NULL); + + // newGame->mouse2d = gameNode->getAttribute("mouse2d")->getIntValue(); + // int mouseX; + // newGame->mouseX = gameNode->getAttribute("mouseX")->getIntValue(); + // int mouseY; //coords win32Api + // newGame->mouseY = gameNode->getAttribute("mouseY")->getIntValue(); + // Vec2i mouseCellPos; + // newGame->mouseCellPos = + // Vec2i::strToVec2(gameNode->getAttribute("mouseCellPos")->getValue()); + // int updateFps, lastUpdateFps, avgUpdateFps; int totalRenderFps, + // renderFps, lastRenderFps, avgRenderFps,currentAvgRenderFpsTotal; Uint64 + // tickCount; + newGame->tickCount = gameNode->getAttribute("tickCount")->getIntValue(); + + // bool paused; + if (newGame->inJoinGameLoading == true) { + newGame->paused = gameNode->getAttribute("paused")->getIntValue() != 0; + } else { + // newGame->paused = gameNode->getAttribute("paused")->getIntValue() != 0; + newGame->paused = true; + } + if (newGame->paused) + newGame->console.addLine(lang.getString("GamePaused")); + // bool gameOver; + newGame->gameOver = gameNode->getAttribute("gameOver")->getIntValue() != 0; + // bool renderNetworkStatus; + // bool showFullConsole; + // bool mouseMoved; + // float scrollSpeed; + // newGame->scrollSpeed = + // gameNode->getAttribute("scrollSpeed")->getFloatValue(); bool + // camLeftButtonDown; bool camRightButtonDown; bool camUpButtonDown; bool + // camDownButtonDown; + + // Speed speed; + // gameNode->addAttribute("speed",intToStr(speed), mapTagReplacements); + + // GraphicMessageBox mainMessageBox; + // GraphicMessageBox errorMessageBox; + + // misc ptr + // ParticleSystem *weatherParticleSystem; + // if(weatherParticleSystem != NULL) { + // weatherParticleSystem->saveGame(gameNode); + // } + // GameSettings gameSettings; + // gameSettings.saveGame(gameNode); + // Vec2i lastMousePos; + // gameNode->addAttribute("lastMousePos",lastMousePos.getString(), + // mapTagReplacements); time_t lastRenderLog2d; + // gameNode->addAttribute("lastRenderLog2d",intToStr(lastRenderLog2d), + // mapTagReplacements); DisplayMessageFunction originalDisplayMsgCallback; + // bool + // isFirstRender; + // gameNode->addAttribute("isFirstRender",intToStr(isFirstRender), + // mapTagReplacements); + + // bool quitTriggeredIndicator; + // int original_updateFps; + // gameNode->addAttribute("original_updateFps",intToStr(original_updateFps), + // mapTagReplacements); int original_cameraFps; + // gameNode->addAttribute("original_cameraFps",intToStr(original_cameraFps), + // mapTagReplacements); + + // bool captureAvgTestStatus; + // gameNode->addAttribute("captureAvgTestStatus",intToStr(captureAvgTestStatus), + // mapTagReplacements); int updateFpsAvgTest; + // gameNode->addAttribute("updateFpsAvgTest",intToStr(updateFpsAvgTest), + // mapTagReplacements); int renderFpsAvgTest; + // gameNode->addAttribute("renderFpsAvgTest",intToStr(renderFpsAvgTest), + // mapTagReplacements); + + // int renderExtraTeamColor; + newGame->renderExtraTeamColor = + gameNode->getAttribute("renderExtraTeamColor")->getIntValue(); + + // static const int renderTeamColorCircleBit=1; + // static const int renderTeamColorPlaneBit=2; + + // bool photoModeEnabled; + // gameNode->addAttribute("photoModeEnabled",intToStr(photoModeEnabled), + // mapTagReplacements); + newGame->photoModeEnabled = + gameNode->getAttribute("photoModeEnabled")->getIntValue() != 0; + // bool visibleHUD; + // gameNode->addAttribute("visibleHUD",intToStr(visibleHUD), + // mapTagReplacements); + newGame->visibleHUD = + gameNode->getAttribute("visibleHUD")->getIntValue() != 0; + newGame->timeDisplay = + gameNode->getAttribute("timeDisplay")->getIntValue() != 0; + // bool withRainEffect; + // gameNode->addAttribute("withRainEffect",intToStr(withRainEffect), + // mapTagReplacements); + newGame->withRainEffect = + gameNode->getAttribute("withRainEffect")->getIntValue() != 0; + // Program *program; + + if (joinGameSettings == NULL) { + if (gameNode->hasChild("unitHighlightList") == true) { + XmlNode *unitHighlightListNode = gameNode->getChild("unitHighlightList"); + vector infoNodeList = + unitHighlightListNode->getChildList("info"); + for (unsigned int i = 0; i < infoNodeList.size(); ++i) { + XmlNode *infoNode = infoNodeList[i]; + + int unitId = infoNode->getAttribute("radius")->getIntValue(); + HighlightSpecialUnitInfo info; + info.radius = infoNode->getAttribute("radius")->getFloatValue(); + info.thickness = infoNode->getAttribute("thickness")->getFloatValue(); + info.color = + Vec4f::strToVec4(infoNode->getAttribute("color")->getValue()); + + newGame->unitHighlightList[unitId] = info; + } + } + } + + newGame->timeDisplay = + gameNode->getAttribute("timeDisplay")->getIntValue() != 0; + + if (gameNode->hasAttribute("disableSpeedChange") == true) { + newGame->disableSpeedChange = + gameNode->getAttribute("disableSpeedChange")->getIntValue() != 0; + } + + // bool gameStarted; + // gameNode->addAttribute("gameStarted",intToStr(gameStarted), + // mapTagReplacements); + // newGame->gameStarted = + // gameNode->getAttribute("gameStarted")->getIntValue(); + + // time_t lastMaxUnitCalcTime; + // gameNode->addAttribute("lastMaxUnitCalcTime",intToStr(lastMaxUnitCalcTime), + // mapTagReplacements); + + // PopupMenu popupMenu; + // PopupMenu popupMenuSwitchTeams; + + // std::map switchTeamIndexMap; + // GraphicMessageBox switchTeamConfirmMessageBox; + + // int exitGamePopupMenuIndex; + // int joinTeamPopupMenuIndex; + // int pauseGamePopupMenuIndex; + // int keyboardSetupPopupMenuIndex; + // GLuint statelist3dMenu; + // ProgramState *currentUIState; + + // bool masterserverMode; + + // StrSound *currentAmbientSound; + + // time_t lastNetworkPlayerConnectionCheck; + // gameNode->addAttribute("lastNetworkPlayerConnectionCheck",intToStr(lastNetworkPlayerConnectionCheck), + // mapTagReplacements); + + // time_t lastMasterServerGameStatsDump; + // gameNode->addAttribute("lastMasterServerGameStatsDump",intToStr(lastMasterServerGameStatsDump), + // mapTagReplacements); + + if (joinGameSettings == NULL) { + newGame->gameCamera.loadGame(gameNode); + } + + const XmlNode *worldNode = gameNode->getChild("World"); + newGame->world.loadGame(worldNode); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Starting Game ...\n"); + programPtr->setState(newGame); } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/game/game.h b/source/glest_game/game/game.h index fbcb64552..15337cc41 100644 --- a/source/glest_game/game/game.h +++ b/source/glest_game/game/game.h @@ -13,45 +13,49 @@ #define _GLEST_GAME_GAME_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include -#include "gui.h" -#include "game_camera.h" -#include "world.h" #include "ai_interface.h" -#include "program.h" #include "chat_manager.h" -#include "script_manager.h" +#include "data_types.h" +#include "game_camera.h" #include "game_settings.h" +#include "gui.h" +#include "leak_dumper.h" #include "network_interface.h" -#include "data_types.h" +#include "program.h" +#include "script_manager.h" #include "selection.h" -#include "leak_dumper.h" +#include "world.h" +#include using std::vector; using namespace Shared::Platform; using namespace Shared::PlatformCommon; -namespace Shared { namespace Graphics { - class VideoPlayer; -}}; +namespace Shared { +namespace Graphics { +class VideoPlayer; +} +}; // namespace Shared -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { class GraphicMessageBox; class ServerInterface; enum LoadGameItem { - lgt_FactionPreview = 0x01, - lgt_TileSet = 0x02, - lgt_TechTree = 0x04, - lgt_Map = 0x08, - lgt_Scenario = 0x10, - - lgt_All = (lgt_FactionPreview | lgt_TileSet | lgt_TechTree | lgt_Map | lgt_Scenario) + lgt_FactionPreview = 0x01, + lgt_TileSet = 0x02, + lgt_TechTree = 0x04, + lgt_Map = 0x08, + lgt_Scenario = 0x10, + + lgt_All = + (lgt_FactionPreview | lgt_TileSet | lgt_TechTree | lgt_Map | lgt_Scenario) }; // ===================================================== @@ -59,363 +63,399 @@ enum LoadGameItem { // // Main game class // ===================================================== -class Game: public ProgramState, public FileCRCPreCacheThreadCallbackInterface, - public CustomInputCallbackInterface, public ClientLagCallbackInterface { +class Game : public ProgramState, + public FileCRCPreCacheThreadCallbackInterface, + public CustomInputCallbackInterface, + public ClientLagCallbackInterface { public: - static const float highlightTime; + static const float highlightTime; private: - typedef vector Ais; - typedef vector AiInterfaces; + typedef vector Ais; + typedef vector AiInterfaces; private: - //main data - World world; - AiInterfaces aiInterfaces; - Gui gui; - GameCamera gameCamera; - Commander commander; - Console console; - ChatManager chatManager; - ScriptManager scriptManager; - - //misc - Checksum checksum; - string loadingText; - int mouse2d; - int mouseX; - int mouseY; //coords win32Api - Vec2i mouseCellPos; - - int updateFps, lastUpdateFps, avgUpdateFps; - int framesToCatchUpAsClient; - int framesToSlowDownAsClient; - int receivedTooEarlyInFrames[GameConstants::networkSmoothInterval]; - int framesNeededToWaitForServerMessage[GameConstants::networkSmoothInterval]; - int totalRenderFps, renderFps, lastRenderFps, avgRenderFps,currentAvgRenderFpsTotal; - uint64 tickCount; - bool paused; - bool pauseRequestSent; - bool resumeRequestSent; - bool pauseStateChanged; - bool pausedForJoinGame; - bool pausedBeforeJoinGame; - - bool gameOver; - bool renderNetworkStatus; - bool renderInGamePerformance; - bool showFullConsole; - bool setMarker; - bool cameraDragAllowed; - bool mouseMoved; - float scrollSpeed; - bool camLeftButtonDown; - bool camRightButtonDown; - bool camUpButtonDown; - bool camDownButtonDown; - - int speed; - GraphicMessageBox mainMessageBox; - GraphicMessageBox errorMessageBox; - - //misc ptr - ParticleSystem *weatherParticleSystem; - GameSettings gameSettings; - Vec2i lastMousePos; - time_t lastRenderLog2d; - DisplayMessageFunction originalDisplayMsgCallback; - bool isFirstRender; - - bool quitTriggeredIndicator; - bool quitPendingIndicator; - - int original_updateFps; - int original_cameraFps; - - bool captureAvgTestStatus; - int updateFpsAvgTest; - int renderFpsAvgTest; - - int renderExtraTeamColor; - static const int renderTeamColorCircleBit=1; - static const int renderTeamColorPlaneBit=2; - - bool photoModeEnabled; - int healthbarMode; - bool visibleHUD; - bool timeDisplay; - bool withRainEffect; - Program *program; - - bool gameStarted; - - time_t lastMaxUnitCalcTime; - - PopupMenu popupMenu; - PopupMenu popupMenuSwitchTeams; - PopupMenu popupMenuDisconnectPlayer; - - std::map switchTeamIndexMap; - GraphicMessageBox switchTeamConfirmMessageBox; - - std::map disconnectPlayerIndexMap; - int playerIndexDisconnect; - GraphicMessageBox disconnectPlayerConfirmMessageBox; - - int exitGamePopupMenuIndex; - int joinTeamPopupMenuIndex; - int pauseGamePopupMenuIndex; - int saveGamePopupMenuIndex; - int loadGamePopupMenuIndex; - //int markCellPopupMenuIndex; - //int unmarkCellPopupMenuIndex; - int keyboardSetupPopupMenuIndex; - int disconnectPlayerPopupMenuIndex; - //GLuint statelist3dMenu; - ProgramState *currentUIState; - - bool isMarkCellEnabled; - Vec2i cellMarkedPos; - MarkedCell cellMarkedData; - bool isMarkCellTextEnabled; - - Texture2D *markCellTexture; - bool isUnMarkCellEnabled; - Texture2D *unmarkCellTexture; - std::map mapMarkedCellList; - Texture2D *highlightCellTexture; - std::vector highlightedCells; - bool masterserverMode; - - StrSound *currentAmbientSound; - - time_t lastNetworkPlayerConnectionCheck; - - time_t lastMasterServerGameStatsDump; - - XmlNode *loadGameNode; - int lastworldFrameCountForReplay; - std::vector > replayCommandList; - - std::vector streamingVideos; - ::Shared::Graphics::VideoPlayer *videoPlayer; - bool playingStaticVideo; + // main data + World world; + AiInterfaces aiInterfaces; + Gui gui; + GameCamera gameCamera; + Commander commander; + Console console; + ChatManager chatManager; + ScriptManager scriptManager; + + // misc + Checksum checksum; + string loadingText; + int mouse2d; + int mouseX; + int mouseY; // coords win32Api + Vec2i mouseCellPos; + + int updateFps, lastUpdateFps, avgUpdateFps; + int framesToCatchUpAsClient; + int framesToSlowDownAsClient; + int receivedTooEarlyInFrames[GameConstants::networkSmoothInterval]; + int framesNeededToWaitForServerMessage[GameConstants::networkSmoothInterval]; + int totalRenderFps, renderFps, lastRenderFps, avgRenderFps, + currentAvgRenderFpsTotal; + uint64 tickCount; + bool paused; + bool pauseRequestSent; + bool resumeRequestSent; + bool pauseStateChanged; + bool pausedForJoinGame; + bool pausedBeforeJoinGame; + + bool gameOver; + bool renderNetworkStatus; + bool renderInGamePerformance; + bool showFullConsole; + bool setMarker; + bool cameraDragAllowed; + bool mouseMoved; + float scrollSpeed; + bool camLeftButtonDown; + bool camRightButtonDown; + bool camUpButtonDown; + bool camDownButtonDown; + + int speed; + GraphicMessageBox mainMessageBox; + GraphicMessageBox errorMessageBox; + + // misc ptr + ParticleSystem *weatherParticleSystem; + GameSettings gameSettings; + Vec2i lastMousePos; + time_t lastRenderLog2d; + DisplayMessageFunction originalDisplayMsgCallback; + bool isFirstRender; + + bool quitTriggeredIndicator; + bool quitPendingIndicator; + + int original_updateFps; + int original_cameraFps; + + bool captureAvgTestStatus; + int updateFpsAvgTest; + int renderFpsAvgTest; + + int renderExtraTeamColor; + static const int renderTeamColorCircleBit = 1; + static const int renderTeamColorPlaneBit = 2; + + bool photoModeEnabled; + int healthbarMode; + bool visibleHUD; + bool timeDisplay; + bool withRainEffect; + Program *program; + + bool gameStarted; + + time_t lastMaxUnitCalcTime; + + PopupMenu popupMenu; + PopupMenu popupMenuSwitchTeams; + PopupMenu popupMenuDisconnectPlayer; + + std::map switchTeamIndexMap; + GraphicMessageBox switchTeamConfirmMessageBox; + + std::map disconnectPlayerIndexMap; + int playerIndexDisconnect; + GraphicMessageBox disconnectPlayerConfirmMessageBox; + + int exitGamePopupMenuIndex; + int joinTeamPopupMenuIndex; + int pauseGamePopupMenuIndex; + int saveGamePopupMenuIndex; + int loadGamePopupMenuIndex; + // int markCellPopupMenuIndex; + // int unmarkCellPopupMenuIndex; + int keyboardSetupPopupMenuIndex; + int disconnectPlayerPopupMenuIndex; + // GLuint statelist3dMenu; + ProgramState *currentUIState; + + bool isMarkCellEnabled; + Vec2i cellMarkedPos; + MarkedCell cellMarkedData; + bool isMarkCellTextEnabled; + + Texture2D *markCellTexture; + bool isUnMarkCellEnabled; + Texture2D *unmarkCellTexture; + std::map mapMarkedCellList; + Texture2D *highlightCellTexture; + std::vector highlightedCells; + bool masterserverMode; + + StrSound *currentAmbientSound; + + time_t lastNetworkPlayerConnectionCheck; + + time_t lastMasterServerGameStatsDump; + + XmlNode *loadGameNode; + int lastworldFrameCountForReplay; + std::vector> replayCommandList; + + std::vector streamingVideos; + ::Shared::Graphics::VideoPlayer *videoPlayer; + bool playingStaticVideo; - Unit *currentCameraFollowUnit; - - std::map unitHighlightList; + Unit *currentCameraFollowUnit; + + std::map unitHighlightList; - MasterSlaveThreadController masterController; + MasterSlaveThreadController masterController; - bool inJoinGameLoading; - bool initialResumeSpeedLoops; + bool inJoinGameLoading; + bool initialResumeSpeedLoops; - bool quitGameCalled; - bool disableSpeedChange; + bool quitGameCalled; + bool disableSpeedChange; - std::map teamFowAlphaCellsLookupItem; - std::map gamePerformanceCounts; + std::map teamFowAlphaCellsLookupItem; + std::map gamePerformanceCounts; - bool networkPauseGameForLaggedClientsRequested; - bool networkResumeGameForLaggedClientsRequested; + bool networkPauseGameForLaggedClientsRequested; + bool networkResumeGameForLaggedClientsRequested; public: - Game(); - Game(Program *program, const GameSettings *gameSettings, bool masterserverMode); - ~Game(); - - void reInitGUI(); - bool isFlagType1BitEnabled(FlagTypes1 type) const; - - bool isMarkCellMode() const { return isMarkCellEnabled; } - const Texture2D * getMarkCellTexture() const { return markCellTexture; } - bool isUnMarkCellMode() const { return isUnMarkCellEnabled; } - const Texture2D * getUnMarkCellTexture() const { return unmarkCellTexture; } - - std::map getMapMarkedCellList() const { return mapMarkedCellList; } - - const Texture2D * getHighlightCellTexture() const { return highlightCellTexture; } - const std::vector * getHighlightedCells() const { return &highlightedCells; } - void addOrReplaceInHighlightedCells(MarkedCell mc); - - bool isMasterserverMode() const { return masterserverMode; } - //get - GameSettings *getGameSettings() {return &gameSettings;} - void setGameSettings(GameSettings *settings) { gameSettings = *settings;} - const GameSettings *getReadOnlyGameSettings() const {return &gameSettings;} - void setQuitPendingIndicator() { quitPendingIndicator = true;} - - const GameCamera *getGameCamera() const {return &gameCamera;} - GameCamera *getGameCameraPtr() {return &gameCamera;} - const Commander *getCommander() const {return &commander;} - Gui *getGuiPtr() {return &gui;} - const Gui *getGui() const {return &gui;} - Commander *getCommander() {return &commander;} - Console *getConsole() {return &console;} - ScriptManager *getScriptManager() {return &scriptManager;} - World *getWorld() {return &world;} - const World *getWorld() const {return &world;} - - Program *getProgram() {return program;} - - Vec2i getMouseCellPos() const {return mouseCellPos;} - bool isValidMouseCellPos() const; - - void removeUnitFromSelection(const Unit *unit); - bool addUnitToSelection(Unit *unit); - void addUnitToGroupSelection(Unit *unit,int groupIndex); - void removeUnitFromGroupSelection(int unitId,int groupIndex); - void recallGroupSelection(int groupIndex); - - Uint64 getTickCount() {return tickCount;} - bool getPaused(); - void setPaused(bool value, bool forceAllowPauseStateChange,bool clearCaches,bool joinNetworkGame); - void tryPauseToggle(bool pause); - void setupRenderForVideo(); - void saveGame(); - const int getTotalRenderFps() const {return totalRenderFps;} - - void toggleTeamColorMarker(); - //init - void resetMembers(); - virtual void load(int loadTypes); - virtual void load(); - virtual void init(); - virtual void init(bool initForPreviewOnly); - virtual void update(); - virtual void updateCamera(); - virtual void render(); - virtual void tick(); - - //event managing - virtual bool textInput(std::string text); - virtual bool sdlKeyDown(SDL_KeyboardEvent key); - virtual void keyDown(SDL_KeyboardEvent key); - virtual void keyUp(SDL_KeyboardEvent key); - virtual void keyPress(SDL_KeyboardEvent c); - virtual void mouseDownLeft(int x, int y); - virtual void mouseDownRight(int x, int y); - virtual void mouseUpCenter(int x, int y); - virtual void mouseUpLeft(int x, int y); - virtual void mouseDoubleClickLeft(int x, int y); - virtual void eventMouseWheel(int x, int y, int zDelta); - virtual void mouseMove(int x, int y, const MouseState *mouseState); - - virtual bool isInSpecialKeyCaptureEvent() { return chatManager.getEditEnabled(); } - - virtual bool quitTriggered(); - virtual Stats quitAndToggleState(); - Stats quitGame(); - static void exitGameState(Program *program, Stats &endStats); - - void startPerformanceTimer(); - void endPerformanceTimer(); - Vec2i getPerformanceTimerResults(); - - //static Texture2D * findFactionLogoTexture(const GameSettings *settings, Logger *logger=NULL,string factionLogoFilter=GameConstants::LOADING_SCREEN_FILE_FILTER, bool useTechDefaultIfFilterNotFound=true); - static string findFactionLogoFile(const GameSettings *settings, Logger *logger=NULL, const string &factionLogoFilter=GameConstants::LOADING_SCREEN_FILE_FILTER); - static string extractScenarioLogoFile(const GameSettings *settings, string &result, bool &loadingImageUsed, Logger *logger=NULL, string factionLogoFilter=GameConstants::LOADING_SCREEN_FILE_FILTER); - static string extractFactionLogoFile(bool &loadingImageUsed, const string &factionName, string scenarioDir, const string &techName, Logger *logger=NULL, string factionLogoFilter=GameConstants::LOADING_SCREEN_FILE_FILTER); - static string extractTechLogoFile(string scenarioDir, const string &techName, bool &loadingImageUsed, Logger *logger=NULL,const string &factionLogoFilter=GameConstants::LOADING_SCREEN_FILE_FILTER); - - void loadHudTexture(const GameSettings *settings); - - bool getGameOver() { return gameOver; } - bool hasGameStarted() { return gameStarted;} - virtual vector processTech(string techName); - virtual void consoleAddLine(string line); - - void endGame(); - - void playStaticVideo(const string &playVideo); - void playStreamingVideo(const string &playVideo); - void stopStreamingVideo(const string &playVideo); - void stopAllVideo(); - - string saveGame(string name, const string &path="saved/"); - static void loadGame(string name,Program *programPtr,bool isMasterserverMode, const GameSettings *joinGameSettings=NULL); - - void addNetworkCommandToReplayList(NetworkCommand* networkCommand,int worldFrameCount); - - bool factionLostGame(int factionIndex); - - void addCellMarker(Vec2i cellPos, MarkedCell cellData); - void removeCellMarker(Vec2i surfaceCellPos, const Faction *faction); - void showMarker(Vec2i cellPos, MarkedCell cellData); - - void highlightUnit(int unitId,float radius, float thickness, Vec4f color); - void unhighlightUnit(int unitId); - - bool showTranslatedTechTree() const; - - void DumpCRCWorldLogIfRequired(string fileSuffix=""); - - bool getDisableSpeedChange() const { return disableSpeedChange; } - void setDisableSpeedChange(bool value) { disableSpeedChange = value; } - - string getGamePerformanceCounts(bool displayWarnings) const; - virtual void addPerformanceCount(string key,int64 value); - bool getRenderInGamePerformance() const { return renderInGamePerformance; } + Game(); + Game(Program *program, const GameSettings *gameSettings, + bool masterserverMode); + ~Game(); + + void reInitGUI(); + bool isFlagType1BitEnabled(FlagTypes1 type) const; + + bool isMarkCellMode() const { return isMarkCellEnabled; } + const Texture2D *getMarkCellTexture() const { return markCellTexture; } + bool isUnMarkCellMode() const { return isUnMarkCellEnabled; } + const Texture2D *getUnMarkCellTexture() const { return unmarkCellTexture; } + + std::map getMapMarkedCellList() const { + return mapMarkedCellList; + } + + const Texture2D *getHighlightCellTexture() const { + return highlightCellTexture; + } + const std::vector *getHighlightedCells() const { + return &highlightedCells; + } + void addOrReplaceInHighlightedCells(MarkedCell mc); + + bool isMasterserverMode() const { return masterserverMode; } + // get + GameSettings *getGameSettings() { return &gameSettings; } + void setGameSettings(GameSettings *settings) { gameSettings = *settings; } + const GameSettings *getReadOnlyGameSettings() const { return &gameSettings; } + void setQuitPendingIndicator() { quitPendingIndicator = true; } + + const GameCamera *getGameCamera() const { return &gameCamera; } + GameCamera *getGameCameraPtr() { return &gameCamera; } + const Commander *getCommander() const { return &commander; } + Gui *getGuiPtr() { return &gui; } + const Gui *getGui() const { return &gui; } + Commander *getCommander() { return &commander; } + Console *getConsole() { return &console; } + ScriptManager *getScriptManager() { return &scriptManager; } + World *getWorld() { return &world; } + const World *getWorld() const { return &world; } + + Program *getProgram() { return program; } + + Vec2i getMouseCellPos() const { return mouseCellPos; } + bool isValidMouseCellPos() const; + + void removeUnitFromSelection(const Unit *unit); + bool addUnitToSelection(Unit *unit); + void addUnitToGroupSelection(Unit *unit, int groupIndex); + void removeUnitFromGroupSelection(int unitId, int groupIndex); + void recallGroupSelection(int groupIndex); + + Uint64 getTickCount() { return tickCount; } + bool getPaused(); + void setPaused(bool value, bool forceAllowPauseStateChange, bool clearCaches, + bool joinNetworkGame); + void tryPauseToggle(bool pause); + void setupRenderForVideo(); + void saveGame(); + const int getTotalRenderFps() const { return totalRenderFps; } + + void toggleTeamColorMarker(); + // init + void resetMembers(); + virtual void load(int loadTypes); + virtual void load(); + virtual void init(); + virtual void init(bool initForPreviewOnly); + virtual void update(); + virtual void updateCamera(); + virtual void render(); + virtual void tick(); + + // event managing + virtual bool textInput(std::string text); + virtual bool sdlKeyDown(SDL_KeyboardEvent key); + virtual void keyDown(SDL_KeyboardEvent key); + virtual void keyUp(SDL_KeyboardEvent key); + virtual void keyPress(SDL_KeyboardEvent c); + virtual void mouseDownLeft(int x, int y); + virtual void mouseDownRight(int x, int y); + virtual void mouseUpCenter(int x, int y); + virtual void mouseUpLeft(int x, int y); + virtual void mouseDoubleClickLeft(int x, int y); + virtual void eventMouseWheel(int x, int y, int zDelta); + virtual void mouseMove(int x, int y, const MouseState *mouseState); + + virtual bool isInSpecialKeyCaptureEvent() { + return chatManager.getEditEnabled(); + } + + virtual bool quitTriggered(); + virtual Stats quitAndToggleState(); + Stats quitGame(); + static void exitGameState(Program *program, Stats &endStats); + + void startPerformanceTimer(); + void endPerformanceTimer(); + Vec2i getPerformanceTimerResults(); + + // static Texture2D * findFactionLogoTexture(const GameSettings *settings, + // Logger *logger=NULL,string + // factionLogoFilter=GameConstants::LOADING_SCREEN_FILE_FILTER, bool + // useTechDefaultIfFilterNotFound=true); + static string + findFactionLogoFile(const GameSettings *settings, Logger *logger = NULL, + const string &factionLogoFilter = + GameConstants::LOADING_SCREEN_FILE_FILTER); + static string extractScenarioLogoFile( + const GameSettings *settings, string &result, bool &loadingImageUsed, + Logger *logger = NULL, + string factionLogoFilter = GameConstants::LOADING_SCREEN_FILE_FILTER); + static string extractFactionLogoFile( + bool &loadingImageUsed, const string &factionName, string scenarioDir, + const string &techName, Logger *logger = NULL, + string factionLogoFilter = GameConstants::LOADING_SCREEN_FILE_FILTER); + static string + extractTechLogoFile(string scenarioDir, const string &techName, + bool &loadingImageUsed, Logger *logger = NULL, + const string &factionLogoFilter = + GameConstants::LOADING_SCREEN_FILE_FILTER); + + void loadHudTexture(const GameSettings *settings); + + bool getGameOver() { return gameOver; } + bool hasGameStarted() { return gameStarted; } + virtual vector processTech(string techName); + virtual void consoleAddLine(string line); + + void endGame(); + + void playStaticVideo(const string &playVideo); + void playStreamingVideo(const string &playVideo); + void stopStreamingVideo(const string &playVideo); + void stopAllVideo(); + + string saveGame(string name, const string &path = "saved/"); + static void loadGame(string name, Program *programPtr, + bool isMasterserverMode, + const GameSettings *joinGameSettings = NULL); + + void addNetworkCommandToReplayList(NetworkCommand *networkCommand, + int worldFrameCount); + + bool factionLostGame(int factionIndex); + + void addCellMarker(Vec2i cellPos, MarkedCell cellData); + void removeCellMarker(Vec2i surfaceCellPos, const Faction *faction); + void showMarker(Vec2i cellPos, MarkedCell cellData); + + void highlightUnit(int unitId, float radius, float thickness, Vec4f color); + void unhighlightUnit(int unitId); + + bool showTranslatedTechTree() const; + + void DumpCRCWorldLogIfRequired(string fileSuffix = ""); + + bool getDisableSpeedChange() const { return disableSpeedChange; } + void setDisableSpeedChange(bool value) { disableSpeedChange = value; } + + string getGamePerformanceCounts(bool displayWarnings) const; + virtual void addPerformanceCount(string key, int64 value); + bool getRenderInGamePerformance() const { return renderInGamePerformance; } private: - //render - void render3d(); - void render2d(); + // render + void render3d(); + void render2d(); - //misc - void checkWinner(); - void checkWinnerStandard(); - void checkWinnerScripted(); - void setEndGameTeamWinnersAndLosers(); + // misc + void checkWinner(); + void checkWinnerStandard(); + void checkWinnerScripted(); + void setEndGameTeamWinnersAndLosers(); - //bool hasBuilding(const Faction *faction); - bool factionLostGame(const Faction *faction); - void incSpeed(); - void decSpeed(); - int getUpdateLoops(); + // bool hasBuilding(const Faction *faction); + bool factionLostGame(const Faction *faction); + void incSpeed(); + void decSpeed(); + int getUpdateLoops(); - void showLoseMessageBox(); - void showWinMessageBox(); - void showMessageBox(const string &text, const string &header, bool toggle); - void showErrorMessageBox(const string &text, const string &header, bool toggle); + void showLoseMessageBox(); + void showWinMessageBox(); + void showMessageBox(const string &text, const string &header, bool toggle); + void showErrorMessageBox(const string &text, const string &header, + bool toggle); - void renderWorker(); - static int ErrorDisplayMessage(const char *msg, bool exitApp); + void renderWorker(); + static int ErrorDisplayMessage(const char *msg, bool exitApp); - void ReplaceDisconnectedNetworkPlayersWithAI(bool isNetworkGame, NetworkRole role); - void calcCameraMoveX(); - void calcCameraMoveZ(); + void ReplaceDisconnectedNetworkPlayersWithAI(bool isNetworkGame, + NetworkRole role); + void calcCameraMoveX(); + void calcCameraMoveZ(); - int getFirstUnusedTeamNumber(); - void updateWorldStats(); + int getFirstUnusedTeamNumber(); + void updateWorldStats(); - void setupPopupMenus(bool checkClientAdminOverrideOnly); + void setupPopupMenus(bool checkClientAdminOverrideOnly); - string getDebugStats(std::map &factionDebugInfo); + string getDebugStats(std::map &factionDebugInfo); - void renderVideoPlayer(); + void renderVideoPlayer(); - void updateNetworkMarkedCells(); - void updateNetworkUnMarkedCells(); - void updateNetworkHighligtedCells(); + void updateNetworkMarkedCells(); + void updateNetworkUnMarkedCells(); + void updateNetworkHighligtedCells(); - virtual void processInputText(string text, bool cancelled); + virtual void processInputText(string text, bool cancelled); - void startMarkCell(); - void startCameraFollowUnit(); + void startMarkCell(); + void startCameraFollowUnit(); - bool switchSetupForSlots(ServerInterface *& serverInterface, - int startIndex, int endIndex, bool onlyNetworkUnassigned); - void processNetworkSynchChecksIfRequired(); - Stats getEndGameStats(); - void checkWinnerStandardHeadlessOrObserver(); - void checkWinnerStandardPlayer(); - std::map getTeamsAlive(); - void initCamera(Map *map); + bool switchSetupForSlots(ServerInterface *&serverInterface, int startIndex, + int endIndex, bool onlyNetworkUnassigned); + void processNetworkSynchChecksIfRequired(); + Stats getEndGameStats(); + void checkWinnerStandardHeadlessOrObserver(); + void checkWinnerStandardPlayer(); + std::map getTeamsAlive(); + void initCamera(Map *map); - virtual bool clientLagHandler(int slotIndex,bool networkPauseGameForLaggedClients); + virtual bool clientLagHandler(int slotIndex, + bool networkPauseGameForLaggedClients); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/game/game_camera.cpp b/source/glest_game/game/game_camera.cpp index 1f9a643fc..c0c613688 100644 --- a/source/glest_game/game/game_camera.cpp +++ b/source/glest_game/game/game_camera.cpp @@ -14,569 +14,642 @@ #include #include "config.h" -#include "game_constants.h" -#include "xml_parser.h" #include "conversion.h" -#include "platform_common.h" +#include "game_constants.h" #include "leak_dumper.h" +#include "platform_common.h" #include "randomgen.h" - +#include "xml_parser.h" using namespace Shared::Graphics; using Shared::Xml::XmlNode; using namespace Shared::Util; -namespace Glest { namespace Game { +namespace Glest { +namespace Game { // ===================================================== // class GameCamera // ===================================================== -//static std::map > > cacheVisibleQuad; +// static std::map > > +// cacheVisibleQuad; // ================== PUBLIC ===================== -const float GameCamera::startingVAng= -60.f; -const float GameCamera::startingHAng= 0.f; -const float GameCamera::vTransitionMult= 0.125f; -const float GameCamera::hTransitionMult= 0.125f; -const float GameCamera::defaultHeight= 20.f; -const float GameCamera::centerOffsetZ= 8.0f; -const float GameCamera::shakeDist= 50.f; +const float GameCamera::startingVAng = -60.f; +const float GameCamera::startingHAng = 0.f; +const float GameCamera::vTransitionMult = 0.125f; +const float GameCamera::hTransitionMult = 0.125f; +const float GameCamera::defaultHeight = 20.f; +const float GameCamera::centerOffsetZ = 8.0f; +const float GameCamera::shakeDist = 50.f; // ================= Constructor ================= -GameCamera::GameCamera() : pos(0.f, defaultHeight, 0.f), - destPos(0.f, defaultHeight, 0.f), destAng(startingVAng, startingHAng) { - //Config &config = Config::getInstance(); - calculatedDefault=defaultHeight; - state= sGame; - - cacheVisibleQuad.clear(); - //MaxVisibleQuadItemCache = config.getInt("MaxVisibleQuadItemCache",intToStr(-1).c_str()); - MaxVisibleQuadItemCache = -1; - //if(Config::getInstance().getBool("DisableCaching","false") == true) { - // MaxVisibleQuadItemCache = 0; - //} - - //config - speed= Config::getInstance().getFloat("CameraMoveSpeed","15") / GameConstants::cameraFps; - clampBounds= !Config::getInstance().getBool("PhotoMode"); - clampDisable = false; - - vAng= startingVAng; - hAng= startingHAng; - - rotate=0; - - move= Vec3f(0.f); - - shakeDecrement=0.f; - currentShakeIntensity=0; - shakeOffset= Vec2f(0.f); - - //maxRenderDistance = Config::getInstance().getFloat("RenderDistanceMax","64"); - maxHeight = Config::getInstance().getFloat("CameraMaxDistance","20"); - minHeight = Config::getInstance().getFloat("CameraMinDistance","7"); - //maxCameraDist = maxHeight; - //minCameraDist = minHeight; - minVAng = -Config::getInstance().getFloat("CameraMaxYaw","77.5"); - maxVAng = -Config::getInstance().getFloat("CameraMinYaw","20"); - fov = Config::getInstance().getFloat("CameraFov","45"); - - lastHAng=0; - lastVAng=0; - limitX=0; - limitY=0; +GameCamera::GameCamera() + : pos(0.f, defaultHeight, 0.f), destPos(0.f, defaultHeight, 0.f), + destAng(startingVAng, startingHAng) { + // Config &config = Config::getInstance(); + calculatedDefault = defaultHeight; + state = sGame; + + cacheVisibleQuad.clear(); + // MaxVisibleQuadItemCache = + // config.getInt("MaxVisibleQuadItemCache",intToStr(-1).c_str()); + MaxVisibleQuadItemCache = -1; + // if(Config::getInstance().getBool("DisableCaching","false") == true) { + // MaxVisibleQuadItemCache = 0; + // } + + // config + speed = Config::getInstance().getFloat("CameraMoveSpeed", "15") / + GameConstants::cameraFps; + clampBounds = !Config::getInstance().getBool("PhotoMode"); + clampDisable = false; + + vAng = startingVAng; + hAng = startingHAng; + + rotate = 0; + + move = Vec3f(0.f); + + shakeDecrement = 0.f; + currentShakeIntensity = 0; + shakeOffset = Vec2f(0.f); + + // maxRenderDistance = + // Config::getInstance().getFloat("RenderDistanceMax","64"); + maxHeight = Config::getInstance().getFloat("CameraMaxDistance", "20"); + minHeight = Config::getInstance().getFloat("CameraMinDistance", "7"); + // maxCameraDist = maxHeight; + // minCameraDist = minHeight; + minVAng = -Config::getInstance().getFloat("CameraMaxYaw", "77.5"); + maxVAng = -Config::getInstance().getFloat("CameraMinYaw", "20"); + fov = Config::getInstance().getFloat("CameraFov", "45"); + + lastHAng = 0; + lastVAng = 0; + limitX = 0; + limitY = 0; } -GameCamera::~GameCamera() { - cacheVisibleQuad.clear(); -} +GameCamera::~GameCamera() { cacheVisibleQuad.clear(); } std::string GameCamera::getCameraMovementKey() const { - char szBuf[8096]=""; - snprintf(szBuf,8096,"%s_%f_%f_%f_%s,%f",pos.getString().c_str(),hAng,vAng,rotate,move.getString().c_str(),fov); - return szBuf; + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "%s_%f_%f_%f_%s,%f", pos.getString().c_str(), hAng, + vAng, rotate, move.getString().c_str(), fov); + return szBuf; } void GameCamera::setMaxHeight(float value) { - if(value < 0) { - maxHeight = Config::getInstance().getFloat("CameraMaxDistance","20"); - } - else { - maxHeight = value; - } + if (value < 0) { + maxHeight = Config::getInstance().getFloat("CameraMaxDistance", "20"); + } else { + maxHeight = value; + } } -void GameCamera::setCalculatedDefault(float calculatedDefault){ - this->calculatedDefault= calculatedDefault; - if(maxHeight>0 && maxHeightcalculatedDefault = calculatedDefault; + if (maxHeight > 0 && maxHeight < calculatedDefault) { + setMaxHeight(calculatedDefault); + } + resetPosition(); } -void GameCamera::init(int limitX, int limitY){ - this->limitX= limitX; - this->limitY= limitY; +void GameCamera::init(int limitX, int limitY) { + this->limitX = limitX; + this->limitY = limitY; } // ==================== Misc ===================== -void GameCamera::setPos(Vec2f pos){ - this->pos= Vec3f(pos.x, this->pos.y, pos.y); - clampPosXZ(0.0f, (float)limitX, 0.0f, (float)limitY); - destPos.x = pos.x; - destPos.z = pos.y; +void GameCamera::setPos(Vec2f pos) { + this->pos = Vec3f(pos.x, this->pos.y, pos.y); + clampPosXZ(0.0f, (float)limitX, 0.0f, (float)limitY); + destPos.x = pos.x; + destPos.z = pos.y; } -void GameCamera::setPos(Vec3f pos){ - this->pos= pos; - //clampPosXZ(0.0f, (float)limitX, 0.0f, (float)limitY); - destPos.x = pos.x; - destPos.y = pos.y; - destPos.z = pos.z; +void GameCamera::setPos(Vec3f pos) { + this->pos = pos; + // clampPosXZ(0.0f, (float)limitX, 0.0f, (float)limitY); + destPos.x = pos.x; + destPos.y = pos.y; + destPos.z = pos.z; } -void GameCamera::shake(int shakeDuration, int shakeStartIntensity , bool cameraDistanceAffected, Vec3f unitVector) { - float currentDurationLeft=0; - float incomingShakeIntensity=((float) shakeStartIntensity)/1000; - - // calculate the shake duration which is left - if(this->currentShakeIntensity > 0.f && this->shakeDecrement != 0.f){ - currentDurationLeft=this->currentShakeIntensity / this->shakeDecrement; - } - - // reduce new shake effect camera distance related - if (cameraDistanceAffected) { - incomingShakeIntensity=incomingShakeIntensity*(1.f-unitVector.dist(getPos())/GameCamera::shakeDist); - } - - // add camera shake effect to current one ( if exsists ). - if(this->currentShakeIntensity>0){ - this->currentShakeIntensity = this->currentShakeIntensity+incomingShakeIntensity ; - } - else { - this->currentShakeIntensity = incomingShakeIntensity ; - } - - // use bigger shakeDuration to calculate new shakeDecrement - if(currentDurationLeft < shakeDuration){ - this->shakeDecrement = currentShakeIntensity / ((float) shakeDuration); - } - else if(currentDurationLeft!=0.0f) - { - this->shakeDecrement = currentShakeIntensity / ((float) currentDurationLeft); - } +void GameCamera::shake(int shakeDuration, int shakeStartIntensity, + bool cameraDistanceAffected, Vec3f unitVector) { + float currentDurationLeft = 0; + float incomingShakeIntensity = ((float)shakeStartIntensity) / 1000; + + // calculate the shake duration which is left + if (this->currentShakeIntensity > 0.f && this->shakeDecrement != 0.f) { + currentDurationLeft = this->currentShakeIntensity / this->shakeDecrement; + } + + // reduce new shake effect camera distance related + if (cameraDistanceAffected) { + incomingShakeIntensity = + incomingShakeIntensity * + (1.f - unitVector.dist(getPos()) / GameCamera::shakeDist); + } + + // add camera shake effect to current one ( if exsists ). + if (this->currentShakeIntensity > 0) { + this->currentShakeIntensity = + this->currentShakeIntensity + incomingShakeIntensity; + } else { + this->currentShakeIntensity = incomingShakeIntensity; + } + + // use bigger shakeDuration to calculate new shakeDecrement + if (currentDurationLeft < shakeDuration) { + this->shakeDecrement = currentShakeIntensity / ((float)shakeDuration); + } else if (currentDurationLeft != 0.0f) { + this->shakeDecrement = currentShakeIntensity / ((float)currentDurationLeft); + } } -void GameCamera::shakeCamera(){ - //RandomGen random; - if(currentShakeIntensity > 0.f) { -// pos.x += (((float) (rand() % 50)) / 50.f - 0.5f) * currentShakeIntensity; -// pos.z += (((float) (rand() % 50)) / 50.f - 0.5f) * currentShakeIntensity; - - shakeOffset.x = (((float) (rand() % 50)) / 50.f - 0.5f) * currentShakeIntensity; - shakeOffset.y = (((float) (rand() % 50)) / 50.f - 0.5f) * currentShakeIntensity; - currentShakeIntensity -= shakeDecrement; - } +void GameCamera::shakeCamera() { + // RandomGen random; + if (currentShakeIntensity > 0.f) { + // pos.x += (((float) (rand() % 50)) / 50.f - 0.5f) * + // currentShakeIntensity; pos.z += (((float) (rand() % 50)) / 50.f - 0.5f) + // * currentShakeIntensity; + + shakeOffset.x = + (((float)(rand() % 50)) / 50.f - 0.5f) * currentShakeIntensity; + shakeOffset.y = + (((float)(rand() % 50)) / 50.f - 0.5f) * currentShakeIntensity; + currentShakeIntensity -= shakeDecrement; + } } -void GameCamera::update(){ - //move XZ - if(move.z){ - moveForwardH(speed * move.z, 0.9f); - } - if(move.x){ - moveSideH(speed * move.x, 0.9f); - } - - //free state - if(state==sFree ){ - if(std::fabs(rotate) == 1){ - rotateHV(speed*5*rotate, 0); - } - if(move.y>0){ - moveUp(speed * move.y); - if(clampDisable == false && clampBounds && pos.yminHeight){ - rotateHV(0.f, -speed * 1.7f * move.y); - } - } - } - - //game state - if(abs(destAng.x - vAng) > 0.01f) { - vAng+= (destAng.x - vAng) * hTransitionMult; - } - if(abs(destAng.y - hAng) > 0.01f) { - if(abs(destAng.y - hAng) > 180) { - if(destAng.y > hAng) { - hAng+= (destAng.y - hAng - 360) * vTransitionMult; - } else { - hAng+= (destAng.y - hAng + 360) * vTransitionMult; - } - } else { - hAng+= (destAng.y - hAng) * vTransitionMult; - } - } - if(abs(destPos.x - pos.x) > 0.01f) { - pos.x += (destPos.x - pos.x) / 32.0f; - } - if(abs(destPos.y - pos.y) > 0.01f) { - pos.y += (destPos.y - pos.y) / 32.0f; - } - if(abs(destPos.z - pos.z) > 0.01f) { - pos.z += (destPos.z - pos.z) / 32.0f; - } - clampAng(); - shakeCamera(); - - if(clampDisable == false && clampBounds){ - clampPosXYZ(0.0f, (float)limitX, minHeight, maxHeight, 0.0f, (float)limitY); - } +void GameCamera::update() { + // move XZ + if (move.z) { + moveForwardH(speed * move.z, 0.9f); + } + if (move.x) { + moveSideH(speed * move.x, 0.9f); + } + + // free state + if (state == sFree) { + if (std::fabs(rotate) == 1) { + rotateHV(speed * 5 * rotate, 0); + } + if (move.y > 0) { + moveUp(speed * move.y); + if (clampDisable == false && clampBounds && pos.y < maxHeight) { + rotateHV(0.f, -speed * 1.7f * move.y); + } + } + if (move.y < 0) { + moveUp(speed * move.y); + if (clampDisable == false && clampBounds && pos.y > minHeight) { + rotateHV(0.f, -speed * 1.7f * move.y); + } + } + } + + // game state + if (abs(destAng.x - vAng) > 0.01f) { + vAng += (destAng.x - vAng) * hTransitionMult; + } + if (abs(destAng.y - hAng) > 0.01f) { + if (abs(destAng.y - hAng) > 180) { + if (destAng.y > hAng) { + hAng += (destAng.y - hAng - 360) * vTransitionMult; + } else { + hAng += (destAng.y - hAng + 360) * vTransitionMult; + } + } else { + hAng += (destAng.y - hAng) * vTransitionMult; + } + } + if (abs(destPos.x - pos.x) > 0.01f) { + pos.x += (destPos.x - pos.x) / 32.0f; + } + if (abs(destPos.y - pos.y) > 0.01f) { + pos.y += (destPos.y - pos.y) / 32.0f; + } + if (abs(destPos.z - pos.z) > 0.01f) { + pos.z += (destPos.z - pos.z) / 32.0f; + } + clampAng(); + shakeCamera(); + + if (clampDisable == false && clampBounds) { + clampPosXYZ(0.0f, (float)limitX, minHeight, maxHeight, 0.0f, (float)limitY); + } } Quad2i GameCamera::computeVisibleQuad() { - //printf("\n@@@ hAng [%f] vAng [%f] fov [%f]\n",hAng,vAng,fov); - - if(MaxVisibleQuadItemCache != 0) { - std::map > >::const_iterator iterFind = cacheVisibleQuad.find(fov); - if(iterFind != cacheVisibleQuad.end()) { - std::map >::const_iterator iterFind2 = iterFind->second.find(hAng); - if(iterFind2 != iterFind->second.end()) { - std::map::const_iterator iterFind3 = iterFind2->second.find(pos); - if(iterFind3 != iterFind2->second.end()) { - return iterFind3->second; - } - } - } - } - - float nearDist = 15.f; - float dist = pos.y > nearDist ? pos.y * 1.2f : nearDist; - float farDist = 90.f * (pos.y > nearDist ? pos.y / 15.f : 1.f); - const float viewDegree = 180.f; - - Vec2f v(std::sin(degToRad(viewDegree - hAng)), std::cos(degToRad(viewDegree - hAng))); - Vec2f v1(std::sin(degToRad(viewDegree - hAng - fov)), std::cos(degToRad(viewDegree - hAng - fov))); - Vec2f v2(std::sin(degToRad(viewDegree - hAng + fov)), std::cos(degToRad(viewDegree - hAng + fov))); - - v.normalize(); - v1.normalize(); - v2.normalize(); - - Vec2f p = Vec2f(pos.x, pos.z) - v * dist; - Vec2i p1(static_cast(p.x + v1.x * nearDist), static_cast(p.y + v1.y * nearDist)); - Vec2i p2(static_cast(p.x + v1.x * farDist), static_cast(p.y + v1.y * farDist)); - Vec2i p3(static_cast(p.x + v2.x * nearDist), static_cast(p.y + v2.y * nearDist)); - Vec2i p4(static_cast(p.x + v2.x * farDist), static_cast(p.y + v2.y * farDist)); - - const bool debug = false; - - Quad2i result; - if (hAng >= 135 && hAng <= 225) { - if(debug) printf("Line %d hAng [%f] fov [%f]\n",__LINE__,hAng,fov); - - result = Quad2i(p1, p2, p3, p4); - if(MaxVisibleQuadItemCache != 0 && - (MaxVisibleQuadItemCache < 0 || (int)cacheVisibleQuad[fov][hAng].size() <= MaxVisibleQuadItemCache)) { - cacheVisibleQuad[fov][hAng][pos] = result; - } - } - else if (hAng >= 45 && hAng <= 135) { - if(debug) printf("Line %d hAng [%f] fov [%f]\n",__LINE__,hAng,fov); - - result = Quad2i(p3, p1, p4, p2); - if(MaxVisibleQuadItemCache != 0 && - (MaxVisibleQuadItemCache < 0 || (int)cacheVisibleQuad[fov][hAng].size() <= MaxVisibleQuadItemCache)) { - cacheVisibleQuad[fov][hAng][pos] = result; - } - } - else if (hAng >= 225 && hAng <= 315) { - if(debug) printf("Line %d hAng [%f] fov [%f]\n",__LINE__,hAng,fov); - - result = Quad2i(p2, p4, p1, p3); - if(MaxVisibleQuadItemCache != 0 && - (MaxVisibleQuadItemCache < 0 || (int)cacheVisibleQuad[fov][hAng].size() <= MaxVisibleQuadItemCache)) { - cacheVisibleQuad[fov][hAng][pos] = result; - } - } - else { - if(debug) printf("Line %d hAng [%f] fov [%f]\n",__LINE__,hAng,fov); - - result = Quad2i(p4, p3, p2, p1); - if(MaxVisibleQuadItemCache != 0 && - (MaxVisibleQuadItemCache < 0 || (int)cacheVisibleQuad[fov][hAng].size() <= MaxVisibleQuadItemCache)) { - cacheVisibleQuad[fov][hAng][pos] = Quad2i(p4, p3, p2, p1); - } - } - - return result; + // printf("\n@@@ hAng [%f] vAng [%f] fov [%f]\n",hAng,vAng,fov); + + if (MaxVisibleQuadItemCache != 0) { + std::map>>::const_iterator + iterFind = cacheVisibleQuad.find(fov); + if (iterFind != cacheVisibleQuad.end()) { + std::map>::const_iterator iterFind2 = + iterFind->second.find(hAng); + if (iterFind2 != iterFind->second.end()) { + std::map::const_iterator iterFind3 = + iterFind2->second.find(pos); + if (iterFind3 != iterFind2->second.end()) { + return iterFind3->second; + } + } + } + } + + float nearDist = 15.f; + float dist = pos.y > nearDist ? pos.y * 1.2f : nearDist; + float farDist = 90.f * (pos.y > nearDist ? pos.y / 15.f : 1.f); + const float viewDegree = 180.f; + + Vec2f v(std::sin(degToRad(viewDegree - hAng)), + std::cos(degToRad(viewDegree - hAng))); + Vec2f v1(std::sin(degToRad(viewDegree - hAng - fov)), + std::cos(degToRad(viewDegree - hAng - fov))); + Vec2f v2(std::sin(degToRad(viewDegree - hAng + fov)), + std::cos(degToRad(viewDegree - hAng + fov))); + + v.normalize(); + v1.normalize(); + v2.normalize(); + + Vec2f p = Vec2f(pos.x, pos.z) - v * dist; + Vec2i p1(static_cast(p.x + v1.x * nearDist), + static_cast(p.y + v1.y * nearDist)); + Vec2i p2(static_cast(p.x + v1.x * farDist), + static_cast(p.y + v1.y * farDist)); + Vec2i p3(static_cast(p.x + v2.x * nearDist), + static_cast(p.y + v2.y * nearDist)); + Vec2i p4(static_cast(p.x + v2.x * farDist), + static_cast(p.y + v2.y * farDist)); + + const bool debug = false; + + Quad2i result; + if (hAng >= 135 && hAng <= 225) { + if (debug) + printf("Line %d hAng [%f] fov [%f]\n", __LINE__, hAng, fov); + + result = Quad2i(p1, p2, p3, p4); + if (MaxVisibleQuadItemCache != 0 && + (MaxVisibleQuadItemCache < 0 || + (int)cacheVisibleQuad[fov][hAng].size() <= MaxVisibleQuadItemCache)) { + cacheVisibleQuad[fov][hAng][pos] = result; + } + } else if (hAng >= 45 && hAng <= 135) { + if (debug) + printf("Line %d hAng [%f] fov [%f]\n", __LINE__, hAng, fov); + + result = Quad2i(p3, p1, p4, p2); + if (MaxVisibleQuadItemCache != 0 && + (MaxVisibleQuadItemCache < 0 || + (int)cacheVisibleQuad[fov][hAng].size() <= MaxVisibleQuadItemCache)) { + cacheVisibleQuad[fov][hAng][pos] = result; + } + } else if (hAng >= 225 && hAng <= 315) { + if (debug) + printf("Line %d hAng [%f] fov [%f]\n", __LINE__, hAng, fov); + + result = Quad2i(p2, p4, p1, p3); + if (MaxVisibleQuadItemCache != 0 && + (MaxVisibleQuadItemCache < 0 || + (int)cacheVisibleQuad[fov][hAng].size() <= MaxVisibleQuadItemCache)) { + cacheVisibleQuad[fov][hAng][pos] = result; + } + } else { + if (debug) + printf("Line %d hAng [%f] fov [%f]\n", __LINE__, hAng, fov); + + result = Quad2i(p4, p3, p2, p1); + if (MaxVisibleQuadItemCache != 0 && + (MaxVisibleQuadItemCache < 0 || + (int)cacheVisibleQuad[fov][hAng].size() <= MaxVisibleQuadItemCache)) { + cacheVisibleQuad[fov][hAng][pos] = Quad2i(p4, p3, p2, p1); + } + } + + return result; } -void GameCamera::setState(State s){ - if(s==sGame){ - state = sGame; - setClampDisabled(false); - resetPosition(); - } - else if(s==sUnit){ - state = sUnit; - setClampDisabled(true); - } - else if(s==sFree){ - state = sFree; - setClampDisabled(false); - resetPosition(); - } - else { - abort();//"unknown camera state" - } +void GameCamera::setState(State s) { + if (s == sGame) { + state = sGame; + setClampDisabled(false); + resetPosition(); + } else if (s == sUnit) { + state = sUnit; + setClampDisabled(true); + } else if (s == sFree) { + state = sFree; + setClampDisabled(false); + resetPosition(); + } else { + abort(); //"unknown camera state" + } } -void GameCamera::resetPosition(){ - destAng.x = startingVAng; - destAng.y = startingHAng; - destPos.y = calculatedDefault; +void GameCamera::resetPosition() { + destAng.x = startingVAng; + destAng.y = startingHAng; + destPos.y = calculatedDefault; } -void GameCamera::centerXZ(float x, float z){ - destPos.x = pos.x= x; - destPos.z = pos.z= z+centerOffsetZ; +void GameCamera::centerXZ(float x, float z) { + destPos.x = pos.x = x; + destPos.z = pos.z = z + centerOffsetZ; } -//void GameCamera::transitionXYZ(float x, float y, float z) { +// void GameCamera::transitionXYZ(float x, float y, float z) { // destPos.x += x; // destPos.y += y; // destPos.z += z; -// clampPosXYZ(0.0f, (float)limitX, minHeight, maxHeight, 0.0f, (float)limitY); -//} +// clampPosXYZ(0.0f, (float)limitX, minHeight, maxHeight, 0.0f, +//(float)limitY); +// } void GameCamera::transitionVH(float v, float h) { - destAng.x -= v; - //destPos.y -= v * destPos.y / 100.f; - destAng.y -= h; - clampAng(); + destAng.x -= v; + // destPos.y -= v * destPos.y / 100.f; + destAng.y -= h; + clampAng(); } void GameCamera::rotateToVH(float v, float h) { - destAng.x = v; - destAng.y = h; - clampAng(); + destAng.x = v; + destAng.y = h; + clampAng(); } void GameCamera::zoom(float dist) { - float flatDist = dist * std::cos(degToRad(vAng)); - Vec3f offset(flatDist * std::sin(degToRad(hAng)), dist * std::sin(degToRad(vAng)), flatDist * -std::cos(degToRad(hAng))); + float flatDist = dist * std::cos(degToRad(vAng)); + Vec3f offset(flatDist * std::sin(degToRad(hAng)), + dist * std::sin(degToRad(vAng)), + flatDist * -std::cos(degToRad(hAng))); - destPos += offset; + destPos += offset; } void GameCamera::load(const XmlNode *node) { - //destPos = node->getChildVec3fValue("pos"); - //destAng = node->getChildVec2fValue("angle"); + // destPos = node->getChildVec3fValue("pos"); + // destAng = node->getChildVec2fValue("angle"); } void GameCamera::save(XmlNode *node) const { - //node->addChild("pos", pos); - //node->addChild("angle", Vec2f(vAng, hAng)); + // node->addChild("pos", pos); + // node->addChild("angle", Vec2f(vAng, hAng)); } // ==================== PRIVATE ==================== -void GameCamera::clampPosXZ(float x1, float x2, float z1, float z2){ - if(clampDisable == true) { - return; - } - - if(pos.x < x1) pos.x = x1; - if(destPos.x < x1) destPos.x = x1; - if(pos.z < z1) pos.z = z1; - if(destPos.z < z1) destPos.z = z1; - if(pos.x > x2) pos.x = x2; - if(destPos.x > x2) destPos.x = x2; - if(pos.z > z2) pos.z = z2; - if(destPos.z > z2) destPos.z = z2; +void GameCamera::clampPosXZ(float x1, float x2, float z1, float z2) { + if (clampDisable == true) { + return; + } + + if (pos.x < x1) + pos.x = x1; + if (destPos.x < x1) + destPos.x = x1; + if (pos.z < z1) + pos.z = z1; + if (destPos.z < z1) + destPos.z = z1; + if (pos.x > x2) + pos.x = x2; + if (destPos.x > x2) + destPos.x = x2; + if (pos.z > z2) + pos.z = z2; + if (destPos.z > z2) + destPos.z = z2; } -void GameCamera::clampPosXYZ(float x1, float x2, float y1, float y2, float z1, float z2){ - if(clampDisable == true) { - return; - } - - if(pos.x < x1) pos.x = x1; - if(destPos.x < x1) destPos.x = x1; - if(pos.y < y1) pos.y = y1; - if(destPos.y < y1) destPos.y = y1; - if(pos.z < z1) pos.z = z1; - if(destPos.z < z1) destPos.z = z1; - if(pos.x > x2) pos.x = x2; - if(destPos.x > x2) destPos.x = x2; - if(pos.y > y2) pos.y = y2; - if(destPos.y > y2) destPos.y = y2; - if(pos.z > z2) pos.z = z2; - if(destPos.z > z2) destPos.z = z2; +void GameCamera::clampPosXYZ(float x1, float x2, float y1, float y2, float z1, + float z2) { + if (clampDisable == true) { + return; + } + + if (pos.x < x1) + pos.x = x1; + if (destPos.x < x1) + destPos.x = x1; + if (pos.y < y1) + pos.y = y1; + if (destPos.y < y1) + destPos.y = y1; + if (pos.z < z1) + pos.z = z1; + if (destPos.z < z1) + destPos.z = z1; + if (pos.x > x2) + pos.x = x2; + if (destPos.x > x2) + destPos.x = x2; + if (pos.y > y2) + pos.y = y2; + if (destPos.y > y2) + destPos.y = y2; + if (pos.z > z2) + pos.z = z2; + if (destPos.z > z2) + destPos.z = z2; } -void GameCamera::rotateHV(float h, float v){ - destAng.x = vAng += v; - destAng.y = hAng += h; - clampAng(); +void GameCamera::rotateHV(float h, float v) { + destAng.x = vAng += v; + destAng.y = hAng += h; + clampAng(); } void GameCamera::clampAng() { - if(clampDisable == true && state != sUnit ) { - return; - } - - if(vAng > maxVAng) vAng = maxVAng; - if(destAng.x > maxVAng) destAng.x = maxVAng; - if(vAng < minVAng) vAng = minVAng; - if(destAng.x < minVAng) destAng.x = minVAng; - if(hAng > 360.f) hAng -= 360.f; - if(destAng.y > 360.f) destAng.y -= 360.f; - if(hAng < 0.f) hAng += 360.f; - if(destAng.y < 0.f) destAng.y = 360.f; + if (clampDisable == true && state != sUnit) { + return; + } + + if (vAng > maxVAng) + vAng = maxVAng; + if (destAng.x > maxVAng) + destAng.x = maxVAng; + if (vAng < minVAng) + vAng = minVAng; + if (destAng.x < minVAng) + destAng.x = minVAng; + if (hAng > 360.f) + hAng -= 360.f; + if (destAng.y > 360.f) + destAng.y -= 360.f; + if (hAng < 0.f) + hAng += 360.f; + if (destAng.y < 0.f) + destAng.y = 360.f; } -//move camera forwad but never change heightFactor +// move camera forwad but never change heightFactor void GameCamera::moveForwardH(float d, float response) { - Vec3f offset(std::sin(degToRad(hAng)) * d, 0.f, -std::cos(degToRad(hAng)) * d); - destPos += offset; - pos.x += offset.x * response; - pos.z += offset.z * response; + Vec3f offset(std::sin(degToRad(hAng)) * d, 0.f, + -std::cos(degToRad(hAng)) * d); + destPos += offset; + pos.x += offset.x * response; + pos.z += offset.z * response; } -//move camera to a side but never change heightFactor -void GameCamera::moveSideH(float d, float response){ - Vec3f offset(std::sin(degToRad(hAng+90)) * d, 0.f, -std::cos(degToRad(hAng+90)) * d); - destPos += offset; - pos.x += (destPos.x - pos.x) * response; - pos.z += (destPos.z - pos.z) * response; +// move camera to a side but never change heightFactor +void GameCamera::moveSideH(float d, float response) { + Vec3f offset(std::sin(degToRad(hAng + 90)) * d, 0.f, + -std::cos(degToRad(hAng + 90)) * d); + destPos += offset; + pos.x += (destPos.x - pos.x) * response; + pos.z += (destPos.z - pos.z) * response; } -void GameCamera::moveUp(float d){ -// pos.y+= d; - destPos.y += d; +void GameCamera::moveUp(float d) { + // pos.y+= d; + destPos.y += d; } void GameCamera::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *gamecameraNode = rootNode->addChild("GameCamera"); - -// Vec3f pos; - gamecameraNode->addAttribute("pos",pos.getString(), mapTagReplacements); -// Vec3f destPos; - gamecameraNode->addAttribute("destPos",destPos.getString(), mapTagReplacements); -// -// float hAng; //YZ plane positive -Z axis - gamecameraNode->addAttribute("hAng",floatToStr(hAng,6), mapTagReplacements); -// float vAng; //XZ plane positive +Z axis - gamecameraNode->addAttribute("vAng",floatToStr(vAng,6), mapTagReplacements); -// float lastHAng; - gamecameraNode->addAttribute("lastHAng",floatToStr(lastHAng,6), mapTagReplacements); - -// float lastVAng; - gamecameraNode->addAttribute("lastVAng",floatToStr(lastVAng,6), mapTagReplacements); -// Vec2f destAng; - gamecameraNode->addAttribute("destAng",destAng.getString(), mapTagReplacements); -// float rotate; - gamecameraNode->addAttribute("rotate",floatToStr(rotate,6), mapTagReplacements); -// Vec3f move; - gamecameraNode->addAttribute("move",move.getString(), mapTagReplacements); -// State state; - gamecameraNode->addAttribute("state",intToStr(state), mapTagReplacements); -// int limitX; - gamecameraNode->addAttribute("limitX",intToStr(limitX), mapTagReplacements); -// int limitY; - gamecameraNode->addAttribute("limitY",intToStr(limitY), mapTagReplacements); -// //config -// float speed; - gamecameraNode->addAttribute("speed",floatToStr(speed,6), mapTagReplacements); -// bool clampBounds; - gamecameraNode->addAttribute("clampBounds",intToStr(clampBounds), mapTagReplacements); -// //float maxRenderDistance; -// float maxHeight; - gamecameraNode->addAttribute("maxHeight",floatToStr(maxHeight,6), mapTagReplacements); -// float minHeight; - gamecameraNode->addAttribute("minHeight",floatToStr(minHeight,6), mapTagReplacements); -// //float maxCameraDist; -// //float minCameraDist; -// float minVAng; - gamecameraNode->addAttribute("minVAng",floatToStr(minVAng,6), mapTagReplacements); -// float maxVAng; - gamecameraNode->addAttribute("maxVAng",floatToStr(maxVAng,6), mapTagReplacements); -// float fov; - gamecameraNode->addAttribute("fov",floatToStr(fov,6), mapTagReplacements); -// float calculatedDefault; - gamecameraNode->addAttribute("calculatedDefault",floatToStr(calculatedDefault,6), mapTagReplacements); -// std::map > > cacheVisibleQuad; -// int MaxVisibleQuadItemCache; - gamecameraNode->addAttribute("MaxVisibleQuadItemCache",intToStr(MaxVisibleQuadItemCache), mapTagReplacements); + std::map mapTagReplacements; + XmlNode *gamecameraNode = rootNode->addChild("GameCamera"); + + // Vec3f pos; + gamecameraNode->addAttribute("pos", pos.getString(), mapTagReplacements); + // Vec3f destPos; + gamecameraNode->addAttribute("destPos", destPos.getString(), + mapTagReplacements); + // + // float hAng; //YZ plane positive -Z axis + gamecameraNode->addAttribute("hAng", floatToStr(hAng, 6), mapTagReplacements); + // float vAng; //XZ plane positive +Z axis + gamecameraNode->addAttribute("vAng", floatToStr(vAng, 6), mapTagReplacements); + // float lastHAng; + gamecameraNode->addAttribute("lastHAng", floatToStr(lastHAng, 6), + mapTagReplacements); + + // float lastVAng; + gamecameraNode->addAttribute("lastVAng", floatToStr(lastVAng, 6), + mapTagReplacements); + // Vec2f destAng; + gamecameraNode->addAttribute("destAng", destAng.getString(), + mapTagReplacements); + // float rotate; + gamecameraNode->addAttribute("rotate", floatToStr(rotate, 6), + mapTagReplacements); + // Vec3f move; + gamecameraNode->addAttribute("move", move.getString(), mapTagReplacements); + // State state; + gamecameraNode->addAttribute("state", intToStr(state), mapTagReplacements); + // int limitX; + gamecameraNode->addAttribute("limitX", intToStr(limitX), mapTagReplacements); + // int limitY; + gamecameraNode->addAttribute("limitY", intToStr(limitY), mapTagReplacements); + // //config + // float speed; + gamecameraNode->addAttribute("speed", floatToStr(speed, 6), + mapTagReplacements); + // bool clampBounds; + gamecameraNode->addAttribute("clampBounds", intToStr(clampBounds), + mapTagReplacements); + // //float maxRenderDistance; + // float maxHeight; + gamecameraNode->addAttribute("maxHeight", floatToStr(maxHeight, 6), + mapTagReplacements); + // float minHeight; + gamecameraNode->addAttribute("minHeight", floatToStr(minHeight, 6), + mapTagReplacements); + // //float maxCameraDist; + // //float minCameraDist; + // float minVAng; + gamecameraNode->addAttribute("minVAng", floatToStr(minVAng, 6), + mapTagReplacements); + // float maxVAng; + gamecameraNode->addAttribute("maxVAng", floatToStr(maxVAng, 6), + mapTagReplacements); + // float fov; + gamecameraNode->addAttribute("fov", floatToStr(fov, 6), mapTagReplacements); + // float calculatedDefault; + gamecameraNode->addAttribute("calculatedDefault", + floatToStr(calculatedDefault, 6), + mapTagReplacements); + // std::map > > + // cacheVisibleQuad; int MaxVisibleQuadItemCache; + gamecameraNode->addAttribute("MaxVisibleQuadItemCache", + intToStr(MaxVisibleQuadItemCache), + mapTagReplacements); } void GameCamera::loadGame(const XmlNode *rootNode) { - const XmlNode *gamecameraNode = rootNode->getChild("GameCamera"); - - //firstTime = timeflowNode->getAttribute("firstTime")->getFloatValue(); - - // Vec3f pos; - pos = Vec3f::strToVec3(gamecameraNode->getAttribute("pos")->getValue()); - // Vec3f destPos; - destPos = Vec3f::strToVec3(gamecameraNode->getAttribute("destPos")->getValue()); - // - // float hAng; //YZ plane positive -Z axis - hAng = gamecameraNode->getAttribute("hAng")->getFloatValue(); - // float vAng; //XZ plane positive +Z axis - vAng = gamecameraNode->getAttribute("vAng")->getFloatValue(); - // float lastHAng; - lastHAng = gamecameraNode->getAttribute("lastHAng")->getFloatValue(); - - // float lastVAng; - lastVAng = gamecameraNode->getAttribute("lastVAng")->getFloatValue(); - // Vec2f destAng; - destAng = Vec2f::strToVec2(gamecameraNode->getAttribute("destAng")->getValue()); - // float rotate; - rotate = gamecameraNode->getAttribute("rotate")->getFloatValue(); - // Vec3f move; - move = Vec3f::strToVec3(gamecameraNode->getAttribute("move")->getValue()); - // State state; - state = static_cast(gamecameraNode->getAttribute("state")->getIntValue()); - // int limitX; - limitX = gamecameraNode->getAttribute("limitX")->getIntValue(); - // int limitY; - limitY = gamecameraNode->getAttribute("limitY")->getIntValue(); - // //config - // float speed; - speed = gamecameraNode->getAttribute("speed")->getFloatValue(); - // bool clampBounds; - clampBounds = gamecameraNode->getAttribute("clampBounds")->getIntValue() != 0; - // //float maxRenderDistance; - // float maxHeight; - maxHeight = gamecameraNode->getAttribute("maxHeight")->getFloatValue(); - // float minHeight; - minHeight = gamecameraNode->getAttribute("minHeight")->getFloatValue(); - // //float maxCameraDist; - // //float minCameraDist; - // float minVAng; - minVAng = gamecameraNode->getAttribute("minVAng")->getFloatValue(); - // float maxVAng; - maxVAng = gamecameraNode->getAttribute("maxVAng")->getFloatValue(); - // float fov; - fov = gamecameraNode->getAttribute("fov")->getFloatValue(); - // float calculatedDefault; - calculatedDefault = gamecameraNode->getAttribute("calculatedDefault")->getFloatValue(); - // std::map > > cacheVisibleQuad; - // int MaxVisibleQuadItemCache; - MaxVisibleQuadItemCache = gamecameraNode->getAttribute("MaxVisibleQuadItemCache")->getIntValue(); - + const XmlNode *gamecameraNode = rootNode->getChild("GameCamera"); + + // firstTime = timeflowNode->getAttribute("firstTime")->getFloatValue(); + + // Vec3f pos; + pos = Vec3f::strToVec3(gamecameraNode->getAttribute("pos")->getValue()); + // Vec3f destPos; + destPos = + Vec3f::strToVec3(gamecameraNode->getAttribute("destPos")->getValue()); + // + // float hAng; //YZ plane positive -Z axis + hAng = gamecameraNode->getAttribute("hAng")->getFloatValue(); + // float vAng; //XZ plane positive +Z axis + vAng = gamecameraNode->getAttribute("vAng")->getFloatValue(); + // float lastHAng; + lastHAng = gamecameraNode->getAttribute("lastHAng")->getFloatValue(); + + // float lastVAng; + lastVAng = gamecameraNode->getAttribute("lastVAng")->getFloatValue(); + // Vec2f destAng; + destAng = + Vec2f::strToVec2(gamecameraNode->getAttribute("destAng")->getValue()); + // float rotate; + rotate = gamecameraNode->getAttribute("rotate")->getFloatValue(); + // Vec3f move; + move = Vec3f::strToVec3(gamecameraNode->getAttribute("move")->getValue()); + // State state; + state = + static_cast(gamecameraNode->getAttribute("state")->getIntValue()); + // int limitX; + limitX = gamecameraNode->getAttribute("limitX")->getIntValue(); + // int limitY; + limitY = gamecameraNode->getAttribute("limitY")->getIntValue(); + // //config + // float speed; + speed = gamecameraNode->getAttribute("speed")->getFloatValue(); + // bool clampBounds; + clampBounds = gamecameraNode->getAttribute("clampBounds")->getIntValue() != 0; + // //float maxRenderDistance; + // float maxHeight; + maxHeight = gamecameraNode->getAttribute("maxHeight")->getFloatValue(); + // float minHeight; + minHeight = gamecameraNode->getAttribute("minHeight")->getFloatValue(); + // //float maxCameraDist; + // //float minCameraDist; + // float minVAng; + minVAng = gamecameraNode->getAttribute("minVAng")->getFloatValue(); + // float maxVAng; + maxVAng = gamecameraNode->getAttribute("maxVAng")->getFloatValue(); + // float fov; + fov = gamecameraNode->getAttribute("fov")->getFloatValue(); + // float calculatedDefault; + calculatedDefault = + gamecameraNode->getAttribute("calculatedDefault")->getFloatValue(); + // std::map > > + // cacheVisibleQuad; int MaxVisibleQuadItemCache; + MaxVisibleQuadItemCache = + gamecameraNode->getAttribute("MaxVisibleQuadItemCache")->getIntValue(); } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/game/game_camera.h b/source/glest_game/game/game_camera.h index 68a3cd88f..666569fa9 100644 --- a/source/glest_game/game/game_camera.h +++ b/source/glest_game/game/game_camera.h @@ -13,25 +13,28 @@ #define _GLEST_GAME_GAMECAMERA_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include "vec.h" +#include "leak_dumper.h" #include "math_util.h" +#include "vec.h" #include #include -#include "leak_dumper.h" -namespace Shared { namespace Xml { - class XmlNode; -}} +namespace Shared { +namespace Xml { +class XmlNode; +} +} // namespace Shared -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { using ::Shared::Graphics::Quad2i; -using ::Shared::Graphics::Vec3f; using ::Shared::Graphics::Vec2f; +using ::Shared::Graphics::Vec3f; using ::Shared::Xml::XmlNode; class Config; @@ -44,149 +47,148 @@ class Config; class GameCamera { public: - static const float startingVAng; - static const float startingHAng; - static const float vTransitionMult; - static const float hTransitionMult; - static const float defaultHeight; - static const float centerOffsetZ; - static const float shakeDist; + static const float startingVAng; + static const float startingHAng; + static const float vTransitionMult; + static const float hTransitionMult; + static const float defaultHeight; + static const float centerOffsetZ; + static const float shakeDist; public: - enum State{ - sGame, - sFree, - sUnit - }; + enum State { sGame, sFree, sUnit }; private: - Vec3f pos; - Vec3f destPos; - Vec2f shakeOffset; + Vec3f pos; + Vec3f destPos; + Vec2f shakeOffset; - float hAng; //YZ plane positive -Z axis - float vAng; //XZ plane positive +Z axis - float lastHAng; - float lastVAng; - Vec2f destAng; + float hAng; // YZ plane positive -Z axis + float vAng; // XZ plane positive +Z axis + float lastHAng; + float lastVAng; + Vec2f destAng; - float rotate; + float rotate; - Vec3f move; + Vec3f move; - float shakeDecrement; - float currentShakeIntensity; - State state; + float shakeDecrement; + float currentShakeIntensity; + State state; - int limitX; - int limitY; + int limitX; + int limitY; - //config - float speed; - bool clampBounds; - bool clampDisable; - //float maxRenderDistance; - float maxHeight; - float minHeight; - //float maxCameraDist; - //float minCameraDist; - float minVAng; - float maxVAng; - float fov; + // config + float speed; + bool clampBounds; + bool clampDisable; + // float maxRenderDistance; + float maxHeight; + float minHeight; + // float maxCameraDist; + // float minCameraDist; + float minVAng; + float maxVAng; + float fov; - float calculatedDefault; + float calculatedDefault; - std::map > > cacheVisibleQuad; - int MaxVisibleQuadItemCache; + std::map>> cacheVisibleQuad; + int MaxVisibleQuadItemCache; public: - GameCamera(); - ~GameCamera(); - - void init(int limitX, int limitY); - - //get - float getHAng() const {return hAng;}; - float getVAng() const {return vAng;} - State getState() const {return state;} - void setState(State s); - void resetCamera() {setState(sGame);} - - const Vec3f &getPos() const {return pos;} - float getFov() const {return fov;} - //set - void setRotate(float rotate){this->rotate= rotate;} - void setPos(Vec2f pos); - void setPos(Vec3f pos); - - const Vec2f &getShakeOffset() const {return shakeOffset;} - void shake(int shakeDuration, int shakeStartIntensity , bool cameraDistanceAffected, Vec3f unitVector); - - void setMoveX(float f) {this->move.x= f;} - void setMoveY(float f) {this->move.y= f;} - void setMoveZ(float f) {this->move.z= f;} - - inline bool isMoving() const { - return (this->move.x != 0.0 || this->move.y != 0.0 || this->move.z != 0.0); - } - inline void stopMove() { - this->move.x = 0.0; - this->move.y = 0.0; - this->move.z = 0.0; - } - - void stop() { - destPos = pos; - destAng.x = vAng; - destAng.y = hAng; - } - - std::string getCameraMovementKey() const; - - //other - void update(); - Quad2i computeVisibleQuad(); - - - void centerXZ(float x, float z); - //void transitionXYZ(float x, float y, float z); - void transitionVH(float v, float h); - void rotateToVH(float v, float h); - - void zoom(float dist); - void moveForwardH(float dist, float response); // response: 1.0 for immediate, 0 for full inertia - void moveSideH(float dist, float response); - - void load(const XmlNode *node); - void save(XmlNode *node) const; - - void setMaxHeight(float value); - float getCalculatedDefault() const{ return calculatedDefault; } - void setCalculatedDefault(float calculatedDefault); - - float getMaxHeight() const {return maxHeight;} - void setFov(float value) { fov = value; } - void setMinVAng(float value) { minVAng = value; } - void setMaxVAng(float value) { maxVAng = value; } - - void setHAng(float value) { hAng=value;}; - void setVAng(float value) { vAng=value;} - - void saveGame(XmlNode *rootNode); - void loadGame(const XmlNode *rootNode); + GameCamera(); + ~GameCamera(); + + void init(int limitX, int limitY); + + // get + float getHAng() const { return hAng; }; + float getVAng() const { return vAng; } + State getState() const { return state; } + void setState(State s); + void resetCamera() { setState(sGame); } + + const Vec3f &getPos() const { return pos; } + float getFov() const { return fov; } + // set + void setRotate(float rotate) { this->rotate = rotate; } + void setPos(Vec2f pos); + void setPos(Vec3f pos); + + const Vec2f &getShakeOffset() const { return shakeOffset; } + void shake(int shakeDuration, int shakeStartIntensity, + bool cameraDistanceAffected, Vec3f unitVector); + + void setMoveX(float f) { this->move.x = f; } + void setMoveY(float f) { this->move.y = f; } + void setMoveZ(float f) { this->move.z = f; } + + inline bool isMoving() const { + return (this->move.x != 0.0 || this->move.y != 0.0 || this->move.z != 0.0); + } + inline void stopMove() { + this->move.x = 0.0; + this->move.y = 0.0; + this->move.z = 0.0; + } + + void stop() { + destPos = pos; + destAng.x = vAng; + destAng.y = hAng; + } + + std::string getCameraMovementKey() const; + + // other + void update(); + Quad2i computeVisibleQuad(); + + void centerXZ(float x, float z); + // void transitionXYZ(float x, float y, float z); + void transitionVH(float v, float h); + void rotateToVH(float v, float h); + + void zoom(float dist); + void moveForwardH( + float dist, + float response); // response: 1.0 for immediate, 0 for full inertia + void moveSideH(float dist, float response); + + void load(const XmlNode *node); + void save(XmlNode *node) const; + + void setMaxHeight(float value); + float getCalculatedDefault() const { return calculatedDefault; } + void setCalculatedDefault(float calculatedDefault); + + float getMaxHeight() const { return maxHeight; } + void setFov(float value) { fov = value; } + void setMinVAng(float value) { minVAng = value; } + void setMaxVAng(float value) { maxVAng = value; } + + void setHAng(float value) { hAng = value; }; + void setVAng(float value) { vAng = value; } + + void saveGame(XmlNode *rootNode); + void loadGame(const XmlNode *rootNode); private: - //void setClampBounds(bool value) { clampBounds = value; } - void resetPosition(); - void setClampDisabled(bool value) { clampDisable = value; }; - void clampPosXYZ(float x1, float x2, float y1, float y2, float z1, float z2); - void clampPosXZ(float x1, float x2, float z1, float z2); - void clampAng(); - void moveUp(float dist); - void rotateHV(float h, float v); - void shakeCamera(); + // void setClampBounds(bool value) { clampBounds = value; } + void resetPosition(); + void setClampDisabled(bool value) { clampDisable = value; }; + void clampPosXYZ(float x1, float x2, float y1, float y2, float z1, float z2); + void clampPosXZ(float x1, float x2, float z1, float z2); + void clampAng(); + void moveUp(float dist); + void rotateHV(float h, float v); + void shakeCamera(); }; -}} //end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/game/game_constants.h b/source/glest_game/game/game_constants.h index e903217e0..2586e4f8b 100644 --- a/source/glest_game/game/game_constants.h +++ b/source/glest_game/game/game_constants.h @@ -12,53 +12,52 @@ #ifndef _GLEST_GAME_GAMECONSTANTS_H_ #define _GLEST_GAME_GAMECONSTANTS_H_ -#include -#include +#include "conversion.h" #include "vec.h" +#include #include -#include -#include "conversion.h" #include +#include +#include using namespace Shared::Graphics; using namespace std; using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { -template -class EnumParser { +template class EnumParser { private: - typedef map enumMapType; - typedef typename enumMapType::const_iterator enumMapTypeIter; - EnumParser(); + typedef map enumMapType; + typedef typename enumMapType::const_iterator enumMapTypeIter; + EnumParser(); - enumMapType enumMap; + enumMapType enumMap; public: - - static T getEnum(const string &value) { - static EnumParser parser; - enumMapTypeIter iValue = parser.enumMap.find(value); - if(iValue == parser.enumMap.end()) { - throw std::runtime_error("unknown enum lookup [" + value + "]"); - } - return iValue->second; - } - static string getString(const T &value) { - static EnumParser parser; - for(enumMapTypeIter iValue = parser.enumMap.begin(); - iValue != parser.enumMap.end(); ++iValue) { - if(iValue->second == value) { - return iValue->first; - } - } - throw std::runtime_error("unknown enum lookup [" + intToStr(value) + "]"); + static T getEnum(const string &value) { + static EnumParser parser; + enumMapTypeIter iValue = parser.enumMap.find(value); + if (iValue == parser.enumMap.end()) { + throw std::runtime_error("unknown enum lookup [" + value + "]"); } - static int getCount() { - static EnumParser parser; - return parser.enumMap.size(); + return iValue->second; + } + static string getString(const T &value) { + static EnumParser parser; + for (enumMapTypeIter iValue = parser.enumMap.begin(); + iValue != parser.enumMap.end(); ++iValue) { + if (iValue->second == value) { + return iValue->first; + } } + throw std::runtime_error("unknown enum lookup [" + intToStr(value) + "]"); + } + static int getCount() { + static EnumParser parser; + return parser.enumMap.size(); + } }; // ===================================================== @@ -76,156 +75,138 @@ const Vec4f MAGENTA(1.0f, 0.0f, 1.0f, 1.0f); const Vec4f WHITE(1.0f, 1.0f, 1.0f, 1.0f); const Vec4f ORANGE(1.0f, 0.7f, 0.0f, 1.0f); -enum PathFinderType { - pfBasic -}; +enum PathFinderType { pfBasic }; -enum TravelState { - tsArrived, - tsMoving, - tsBlocked, - tsImpossible -}; +enum TravelState { tsArrived, tsMoving, tsBlocked, tsImpossible }; enum ControlType { - ctClosed, - ctCpuEasy, - ctCpu, - ctCpuUltra, - ctCpuMega, - ctNetwork, - ctNetworkUnassigned, - ctHuman, - - ctNetworkCpuEasy, - ctNetworkCpu, - ctNetworkCpuUltra, - ctNetworkCpuMega + ctClosed, + ctCpuEasy, + ctCpu, + ctCpuUltra, + ctCpuMega, + ctNetwork, + ctNetworkUnassigned, + ctHuman, + + ctNetworkCpuEasy, + ctNetworkCpu, + ctNetworkCpuUltra, + ctNetworkCpuMega }; -enum NetworkRole { - nrServer, - nrClient, - nrIdle -}; +enum NetworkRole { nrServer, nrClient, nrIdle }; enum FactionPersonalityType { - fpt_Normal, - fpt_Observer, + fpt_Normal, + fpt_Observer, - fpt_EndCount + fpt_EndCount }; enum MasterServerGameStatusType { - game_status_waiting_for_players = 0, - game_status_waiting_for_start = 1, - game_status_in_progress = 2, - game_status_finished = 3 + game_status_waiting_for_players = 0, + game_status_waiting_for_start = 1, + game_status_in_progress = 2, + game_status_finished = 3 }; class GameConstants { public: - static const int specialFactions = fpt_EndCount - 1; - static const int maxPlayers = 8; - static const int serverPort = 61357; - static const int serverAdminPort = 61355; - static int updateFps; - static int cameraFps; - - static int networkFramePeriod; - static const int networkPingInterval = 5; - static const int networkSmoothInterval = 30; - static const int maxClientConnectHandshakeSecs = 10; - - static const int cellScale = 2; - static const int clusterSize = 16; - - static const char *folder_path_maps; - static const char *folder_path_scenarios; - static const char *folder_path_techs; - static const char *folder_path_tilesets; - static const char *folder_path_tutorials; - - static const char *NETWORK_SLOT_UNCONNECTED_SLOTNAME; - static const char *NETWORK_SLOT_CLOSED_SLOTNAME; - - static const char *folder_path_screenshots; - static const char *folder_path_setups; - - static const char *OBSERVER_SLOTNAME; - static const char *RANDOMFACTION_SLOTNAME; - - static const char *steamCacheInstanceKey; - static const char *preCacheThreadCacheLookupKey; - static const char *playerTextureCacheLookupKey; - static const char *ircClientCacheLookupKey; - static const char *factionPreviewTextureCacheLookupKey; - static const char *characterMenuScreenPositionListCacheLookupKey; - static const char *pathCacheLookupKey; - static const char *path_data_CacheLookupKey; - static const char *path_ini_CacheLookupKey; - static const char *path_logs_CacheLookupKey; - - static const char *application_name; - - static const char *saveNetworkGameFileServerCompressed; - static const char *saveNetworkGameFileServer; - static const char *saveNetworkGameFileClientCompressed; - static const char *saveNetworkGameFileClient; - static const char *saveGameFileDefault; - static const char *saveGameFileAutoTestDefault; - static const char *saveGameFilePattern; - - // VC++ Chokes on init of non integral static types - static const float normalMultiplier; - static const float easyMultiplier; - static const float ultraMultiplier; - static const float megaMultiplier; - // - - static const char * LOADING_SCREEN_FILE; - static const char * LOADING_SCREEN_FILE_FILTER; - static const char * PREVIEW_SCREEN_FILE; - static const char * PREVIEW_SCREEN_FILE_FILTER; - static const char * HUD_SCREEN_FILE; - static const char * HUD_SCREEN_FILE_FILTER; - + static const int specialFactions = fpt_EndCount - 1; + static const int maxPlayers = 8; + static const int serverPort = 61357; + static const int serverAdminPort = 61355; + static int updateFps; + static int cameraFps; + + static int networkFramePeriod; + static const int networkPingInterval = 5; + static const int networkSmoothInterval = 30; + static const int maxClientConnectHandshakeSecs = 10; + + static const int cellScale = 2; + static const int clusterSize = 16; + + static const char *folder_path_maps; + static const char *folder_path_scenarios; + static const char *folder_path_techs; + static const char *folder_path_tilesets; + static const char *folder_path_tutorials; + + static const char *NETWORK_SLOT_UNCONNECTED_SLOTNAME; + static const char *NETWORK_SLOT_CLOSED_SLOTNAME; + + static const char *folder_path_screenshots; + static const char *folder_path_setups; + + static const char *OBSERVER_SLOTNAME; + static const char *RANDOMFACTION_SLOTNAME; + + static const char *steamCacheInstanceKey; + static const char *preCacheThreadCacheLookupKey; + static const char *playerTextureCacheLookupKey; + static const char *ircClientCacheLookupKey; + static const char *factionPreviewTextureCacheLookupKey; + static const char *characterMenuScreenPositionListCacheLookupKey; + static const char *pathCacheLookupKey; + static const char *path_data_CacheLookupKey; + static const char *path_ini_CacheLookupKey; + static const char *path_logs_CacheLookupKey; + + static const char *application_name; + + static const char *saveNetworkGameFileServerCompressed; + static const char *saveNetworkGameFileServer; + static const char *saveNetworkGameFileClientCompressed; + static const char *saveNetworkGameFileClient; + static const char *saveGameFileDefault; + static const char *saveGameFileAutoTestDefault; + static const char *saveGameFilePattern; + + // VC++ Chokes on init of non integral static types + static const float normalMultiplier; + static const float easyMultiplier; + static const float ultraMultiplier; + static const float megaMultiplier; + // + + static const char *LOADING_SCREEN_FILE; + static const char *LOADING_SCREEN_FILE_FILTER; + static const char *PREVIEW_SCREEN_FILE; + static const char *PREVIEW_SCREEN_FILE_FILTER; + static const char *HUD_SCREEN_FILE; + static const char *HUD_SCREEN_FILE_FILTER; }; -enum PathType { - ptMaps, - ptScenarios, - ptTechs, - ptTilesets, - ptTutorials -}; +enum PathType { ptMaps, ptScenarios, ptTechs, ptTilesets, ptTutorials }; struct CardinalDir { public: - enum Enum { NORTH, EAST, SOUTH, WEST, COUNT }; - - CardinalDir() : value(NORTH) {} - explicit CardinalDir(Enum v) : value(v) {} - explicit CardinalDir(int v) { - assertDirValid(v); - value = static_cast(v); - } - operator Enum() const { return value; } - int asInt() const { return (int)value; } - - static void assertDirValid(int v) { assert(v >= 0 && v < 4); } - void operator++() { - value = static_cast((value + 1) % 4); - } - void operator--() { // mod with negative numbers is a 'grey area', hence the +3 rather than -1 - value = static_cast((value + 3) % 4); - } + enum Enum { NORTH, EAST, SOUTH, WEST, COUNT }; + + CardinalDir() : value(NORTH) {} + explicit CardinalDir(Enum v) : value(v) {} + explicit CardinalDir(int v) { + assertDirValid(v); + value = static_cast(v); + } + operator Enum() const { return value; } + int asInt() const { return (int)value; } + + static void assertDirValid(int v) { assert(v >= 0 && v < 4); } + void operator++() { value = static_cast((value + 1) % 4); } + void operator--() { // mod with negative numbers is a 'grey area', hence the + // +3 rather than -1 + value = static_cast((value + 3) % 4); + } private: - Enum value; + Enum value; }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/game/game_settings.h b/source/glest_game/game/game_settings.h index e3cdaee80..70771e23f 100644 --- a/source/glest_game/game/game_settings.h +++ b/source/glest_game/game/game_settings.h @@ -12,30 +12,24 @@ #ifndef _GLEST_GAME_GAMESETTINGS_H_ #define _GLEST_GAME_GAMESETTINGS_H_ -#include "game_constants.h" -#include "conversion.h" -#include -#include "xml_parser.h" #include "config.h" -#include "platform_common.h" #include "conversion.h" -#include "platform_util.h" +#include "game_constants.h" #include "leak_dumper.h" +#include "platform_common.h" +#include "platform_util.h" +#include "xml_parser.h" +#include using namespace Shared::Util; using namespace Shared::PlatformCommon; using namespace Shared::Platform; using Shared::Xml::XmlNode; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { -enum ModType { - mt_None, - mt_Map, - mt_Tileset, - mt_Techtree, - mt_Scenario -}; +enum ModType { mt_None, mt_Map, mt_Tileset, mt_Techtree, mt_Scenario }; // =============================== // class ModInfo @@ -43,16 +37,17 @@ enum ModType { class ModInfo { public: - string name; - string url; - string imageUrl; - string description; - string count; // used for faction count for example - string crc; - string localCRC; - ModType type; + string name; + string url; + string imageUrl; + string description; + string count; // used for faction count for example + string crc; + string localCRC; + ModType type; + public: - ModInfo(); + ModInfo(); }; // ===================================================== @@ -60,848 +55,1021 @@ class ModInfo { // ===================================================== enum FlagTypes1 { - ft1_none = 0x00, - ft1_show_map_resources = 0x01, - ft1_allow_team_switching = 0x02, - ft1_allow_in_game_joining = 0x04, - ft1_network_synch_checks_verbose = 0x08, - ft1_network_synch_checks = 0x10, - ft1_allow_shared_team_units = 0x20, - ft1_allow_shared_team_resources = 0x40 - //ft1_xxx = 0x80 + ft1_none = 0x00, + ft1_show_map_resources = 0x01, + ft1_allow_team_switching = 0x02, + ft1_allow_in_game_joining = 0x04, + ft1_network_synch_checks_verbose = 0x08, + ft1_network_synch_checks = 0x10, + ft1_allow_shared_team_units = 0x20, + ft1_allow_shared_team_resources = 0x40 + // ft1_xxx = 0x80 }; -inline static bool isFlagType1BitEnabled(uint32 flagValue,FlagTypes1 type) { - return ((flagValue & (uint32)type) == (uint32)type); +inline static bool isFlagType1BitEnabled(uint32 flagValue, FlagTypes1 type) { + return ((flagValue & (uint32)type) == (uint32)type); } enum NetworkPlayerStatusType { - npst_None = 0, - npst_PickSettings = 1, - npst_BeRightBack = 2, - npst_Ready = 3, - npst_Disconnected = 4 + npst_None = 0, + npst_PickSettings = 1, + npst_BeRightBack = 2, + npst_Ready = 3, + npst_Disconnected = 4 }; class GameSettings { private: - string gameName; - string description; - string map; - string tileset; - string tech; - string scenario; - string scenarioDir; - string factionTypeNames[GameConstants::maxPlayers]; //faction names - string networkPlayerNames[GameConstants::maxPlayers]; - string networkPlayerPlatform[GameConstants::maxPlayers]; - int networkPlayerStatuses[GameConstants::maxPlayers]; - string networkPlayerLanguages[GameConstants::maxPlayers]; - int networkPlayerGameStatus[GameConstants::maxPlayers]; - - ControlType factionControls[GameConstants::maxPlayers]; - int resourceMultiplierIndex[GameConstants::maxPlayers]; - string networkPlayerUUID[GameConstants::maxPlayers]; - - - int thisFactionIndex; - int factionCount; - int teams[GameConstants::maxPlayers]; - int startLocationIndex[GameConstants::maxPlayers]; - int mapFilter; - - int fallbackCpuMultiplier; - bool defaultUnits; - bool defaultResources; - bool defaultVictoryConditions; - - bool fogOfWar; - bool allowObservers; - bool enableObserverModeAtEndGame; - bool enableServerControlledAI; - int networkFramePeriod; - bool networkPauseGameForLaggedClients; - PathFinderType pathFinderType; - - uint32 flagTypes1; - - uint32 mapCRC; - uint32 tilesetCRC; - uint32 techCRC; - vector > factionCRCList; - - int aiAcceptSwitchTeamPercentChance; - int masterserver_admin; - - int masterserver_admin_factionIndex; - - bool networkAllowNativeLanguageTechtree; - - string gameUUID; + string gameName; + string description; + string map; + string tileset; + string tech; + string scenario; + string scenarioDir; + string factionTypeNames[GameConstants::maxPlayers]; // faction names + string networkPlayerNames[GameConstants::maxPlayers]; + string networkPlayerPlatform[GameConstants::maxPlayers]; + int networkPlayerStatuses[GameConstants::maxPlayers]; + string networkPlayerLanguages[GameConstants::maxPlayers]; + int networkPlayerGameStatus[GameConstants::maxPlayers]; + + ControlType factionControls[GameConstants::maxPlayers]; + int resourceMultiplierIndex[GameConstants::maxPlayers]; + string networkPlayerUUID[GameConstants::maxPlayers]; + + int thisFactionIndex; + int factionCount; + int teams[GameConstants::maxPlayers]; + int startLocationIndex[GameConstants::maxPlayers]; + int mapFilter; + + int fallbackCpuMultiplier; + bool defaultUnits; + bool defaultResources; + bool defaultVictoryConditions; + + bool fogOfWar; + bool allowObservers; + bool enableObserverModeAtEndGame; + bool enableServerControlledAI; + int networkFramePeriod; + bool networkPauseGameForLaggedClients; + PathFinderType pathFinderType; + + uint32 flagTypes1; + + uint32 mapCRC; + uint32 tilesetCRC; + uint32 techCRC; + vector> factionCRCList; + + int aiAcceptSwitchTeamPercentChance; + int masterserver_admin; + + int masterserver_admin_factionIndex; + + bool networkAllowNativeLanguageTechtree; + + string gameUUID; public: + static string playerDisconnectedText; + + GameSettings() { + defaultUnits = false; + defaultResources = false; + defaultVictoryConditions = false; + mapFilter = 0; + factionCount = 0; + thisFactionIndex = 0; + fogOfWar = true; + allowObservers = false; + enableObserverModeAtEndGame = false; + enableServerControlledAI = false; + networkFramePeriod = GameConstants::networkFramePeriod; + networkPauseGameForLaggedClients = false; + pathFinderType = pfBasic; + + static const string DEFAULT_LANG = "english"; + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + factionTypeNames[i] = ""; + networkPlayerNames[i] = ""; + networkPlayerPlatform[i] = ""; + networkPlayerStatuses[i] = npst_None; + networkPlayerLanguages[i] = DEFAULT_LANG; + factionControls[i] = ctClosed; + resourceMultiplierIndex[i] = 1.0f; + teams[i] = 0; + startLocationIndex[i] = i; + networkPlayerGameStatus[i] = 0; + + networkPlayerUUID[i] = ""; + } - static string playerDisconnectedText; - - GameSettings() { - defaultUnits=false; - defaultResources=false; - defaultVictoryConditions=false; - mapFilter = 0; - factionCount = 0; - thisFactionIndex = 0; - fogOfWar = true; - allowObservers = false; - enableObserverModeAtEndGame = false; - enableServerControlledAI = false; - networkFramePeriod = GameConstants::networkFramePeriod; - networkPauseGameForLaggedClients = false; - pathFinderType = pfBasic; - - static const string DEFAULT_LANG = "english"; - for(int i = 0; i < GameConstants::maxPlayers; ++i) { - factionTypeNames[i] = ""; - networkPlayerNames[i] = ""; - networkPlayerPlatform[i] = ""; - networkPlayerStatuses[i] = npst_None; - networkPlayerLanguages[i] = DEFAULT_LANG; - factionControls[i] = ctClosed; - resourceMultiplierIndex[i] = 1.0f; - teams[i] = 0; - startLocationIndex[i] = i; - networkPlayerGameStatus[i] = 0; - - networkPlayerUUID[i] = ""; - } - - flagTypes1 = ft1_none; - - mapCRC = 0; - tilesetCRC = 0; - techCRC = 0; - factionCRCList.clear(); - aiAcceptSwitchTeamPercentChance = 30; - masterserver_admin = -1; - masterserver_admin_factionIndex = -1; - fallbackCpuMultiplier = 1.5f; - networkAllowNativeLanguageTechtree = true; - } - - // default copy constructor will do fine, and will maintain itself ;) - - //get - const string &getGameName() const {return gameName;} - const string &getDescription() const {return description;} - const string &getMap() const {return map;} - const string &getTileset() const {return tileset;} - const string &getTech() const {return tech;} - const string &getScenario() const {return scenario;} - const string &getScenarioDir() const {return scenarioDir;} - const string &getFactionTypeName(int factionIndex) const { - if(factionIndex == -1) { - static string HEADLESS_FACTION = "headless-server"; - return HEADLESS_FACTION; - } - if(factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s] Invalid factionIndex = %d\n",__FUNCTION__,factionIndex); - throw megaglest_runtime_error(szBuf); - } - return factionTypeNames[factionIndex]; - } - string getNetworkPlayerName(int factionIndex) const { - if(factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s] Invalid factionIndex = %d\n",__FUNCTION__,factionIndex); - throw megaglest_runtime_error(szBuf); - } - - string result = networkPlayerNames[factionIndex]; - if(networkPlayerStatuses[factionIndex] == npst_Disconnected) { - result = playerDisconnectedText + result; - } - return result; - } - string getNetworkPlayerPlatform(int factionIndex) const { - if(factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s] Invalid factionIndex = %d\n",__FUNCTION__,factionIndex); - throw megaglest_runtime_error(szBuf); - } - - string result = networkPlayerPlatform[factionIndex]; - return result; - } - - const int getNetworkPlayerStatuses(int factionIndex) const { - if(factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s] Invalid factionIndex = %d\n",__FUNCTION__,factionIndex); - throw megaglest_runtime_error(szBuf); - } - - return networkPlayerStatuses[factionIndex]; - } - const string getNetworkPlayerLanguages(int factionIndex) const { - if(factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s] Invalid factionIndex = %d\n",__FUNCTION__,factionIndex); - throw megaglest_runtime_error(szBuf); - } - - return networkPlayerLanguages[factionIndex]; - } - - const int getNetworkPlayerGameStatus(int factionIndex) const { - if(factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s] Invalid factionIndex = %d\n",__FUNCTION__,factionIndex); - throw megaglest_runtime_error(szBuf); - } - - return networkPlayerGameStatus[factionIndex]; - } - - const vector getUniqueNetworkPlayerLanguages() const { - vector languageList; - for(int i = 0; i < GameConstants::maxPlayers; ++i) { - if(networkPlayerLanguages[i] != "") { - if(std::find(languageList.begin(),languageList.end(),networkPlayerLanguages[i]) == languageList.end()) { - languageList.push_back(networkPlayerLanguages[i]); - } - } - } - if(languageList.empty() == true) { - languageList.push_back(""); - } - return languageList; - } - - const string getNetworkPlayerNameByPlayerIndex(int playerIndex) const { - string result = ""; - for(int i = 0; i < GameConstants::maxPlayers; ++i) { - if(startLocationIndex[i] == playerIndex) { - result = networkPlayerNames[i]; - break; - } - } - return result; - } - const string getNetworkPlayerPlatformByPlayerIndex(int playerIndex) const { - string result = ""; - for(int i = 0; i < GameConstants::maxPlayers; ++i) { - if(startLocationIndex[i] == playerIndex) { - result = networkPlayerPlatform[i]; - break; - } - } - return result; - } - - ControlType getFactionControl(int factionIndex) const { - if(factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s] Invalid factionIndex = %d\n",__FUNCTION__,factionIndex); - throw megaglest_runtime_error(szBuf); - } - - return factionControls[factionIndex]; - } - int getResourceMultiplierIndex(int factionIndex) const { - if(factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s] Invalid factionIndex = %d\n",__FUNCTION__,factionIndex); - throw megaglest_runtime_error(szBuf); - } - - return resourceMultiplierIndex[factionIndex]; - } - - const string &getNetworkPlayerUUID(int factionIndex) const { - if(factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s] Invalid factionIndex = %d\n",__FUNCTION__,factionIndex); - throw megaglest_runtime_error(szBuf); - } - return networkPlayerUUID[factionIndex]; - } - - bool isNetworkGame() const { - bool result = false; - for(int idx = 0; idx < GameConstants::maxPlayers; ++idx) { - if(factionControls[idx] == ctNetwork || factionControls[idx] == ctNetworkUnassigned || - networkPlayerStatuses[idx] == npst_Disconnected) { - result = true; - break; - } - } - return result; - } - int getThisFactionIndex() const {return thisFactionIndex;} - int getFactionCount() const {return factionCount;} - int getTeam(int factionIndex) const { - if(factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s] Invalid factionIndex = %d\n",__FUNCTION__,factionIndex); - throw megaglest_runtime_error(szBuf); - } - - return teams[factionIndex]; - } - - int getStartLocationIndex(int factionIndex) const { - if(factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s] Invalid factionIndex = %d\n",__FUNCTION__,factionIndex); - throw megaglest_runtime_error(szBuf); - } - - return startLocationIndex[factionIndex]; - } - int getFactionIndexForStartLocation(int startIndex) const { - if(startIndex < 0 || startIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s] Invalid startIndex = %d\n",__FUNCTION__,startIndex); - throw megaglest_runtime_error(szBuf); - } - - for(int i =0; i < GameConstants::maxPlayers; ++i) { - if(startLocationIndex[i] == startIndex) { - return i; - } - } - return -1; - } - - int getMapFilter() const {return mapFilter;} - - bool getDefaultUnits() const {return defaultUnits;} - bool getDefaultResources() const {return defaultResources;} - bool getDefaultVictoryConditions() const {return defaultVictoryConditions;} - - bool getFogOfWar() const {return fogOfWar;} - bool getAllowObservers() const { return allowObservers;} - bool getEnableObserverModeAtEndGame() const {return enableObserverModeAtEndGame;} - bool getEnableServerControlledAI() const {return enableServerControlledAI;} - int getNetworkFramePeriod() const {return networkFramePeriod; } - bool getNetworkPauseGameForLaggedClients() const {return networkPauseGameForLaggedClients; } - PathFinderType getPathFinderType() const { return pathFinderType; } - uint32 getFlagTypes1() const { return flagTypes1;} - - uint32 getMapCRC() const { return mapCRC; } - uint32 getTilesetCRC() const { return tilesetCRC; } - uint32 getTechCRC() const { return techCRC; } - vector > getFactionCRCList() const { return factionCRCList; } - - const string &getGameUUID() const {return gameUUID;} - - //set - void setGameName(const string& gameName) {this->gameName= gameName;} - void setDescription(const string& description) {this->description= description;} - void setMap(const string& map) {this->map= map;} - void setTileset(const string& tileset) {this->tileset= tileset;} - void setTech(const string& tech) {this->tech= tech;} - void setScenario(const string& scenario) {this->scenario= scenario;} - void setScenarioDir(const string& scenarioDir) {this->scenarioDir= scenarioDir;} - - void setFactionTypeName(int factionIndex, const string& factionTypeName) { - if(factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s] Invalid factionIndex = %d\n",__FUNCTION__,factionIndex); - throw megaglest_runtime_error(szBuf); - } - - this->factionTypeNames[factionIndex]= factionTypeName; - } - void setNetworkPlayerName(int factionIndex,const string& playername) { - if(factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s] Invalid factionIndex = %d\n",__FUNCTION__,factionIndex); - throw megaglest_runtime_error(szBuf); - } - - this->networkPlayerNames[factionIndex]= playername; - } - void setNetworkPlayerPlatform(int factionIndex,const string& platform) { - if(factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s] Invalid factionIndex = %d\n",__FUNCTION__,factionIndex); - throw megaglest_runtime_error(szBuf); - } - - this->networkPlayerPlatform[factionIndex]= platform; - } - - void setNetworkPlayerStatuses(int factionIndex,int status) { - if(factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s] Invalid factionIndex = %d\n",__FUNCTION__,factionIndex); - throw megaglest_runtime_error(szBuf); - } - - this->networkPlayerStatuses[factionIndex]= status; - } - - void setNetworkPlayerGameStatus(int factionIndex,int status) { - if(factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s] Invalid factionIndex = %d\n",__FUNCTION__,factionIndex); - throw megaglest_runtime_error(szBuf); - } - - this->networkPlayerGameStatus[factionIndex]= status; - } - void setNetworkPlayerLanguages(int factionIndex, const string &language) { - if(factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s] Invalid factionIndex = %d\n",__FUNCTION__,factionIndex); - throw megaglest_runtime_error(szBuf); - } - - this->networkPlayerLanguages[factionIndex]=language; - } - - void setFactionControl(int factionIndex, ControlType controller) { - if(factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s] Invalid factionIndex = %d\n",__FUNCTION__,factionIndex); - throw megaglest_runtime_error(szBuf); - } - - this->factionControls[factionIndex]= controller; - } - void setResourceMultiplierIndex(int factionIndex, int multiplierIndex) { - if(factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s] Invalid factionIndex = %d\n",__FUNCTION__,factionIndex); - throw megaglest_runtime_error(szBuf); - } - - //if(multiplierIndex >= 45) { - // printf("gamesettings Line: %d multiplier index: %d factionIndex: %d\n",__LINE__,multiplierIndex,factionIndex); - //} - - this->resourceMultiplierIndex[factionIndex]= multiplierIndex; - } - - void setNetworkPlayerUUID(int factionIndex, const string& uuid) { - if(factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s] Invalid factionIndex = %d\n",__FUNCTION__,factionIndex); - throw megaglest_runtime_error(szBuf); - } - - this->networkPlayerUUID[factionIndex]= uuid; - } - - void setThisFactionIndex(int thisFactionIndex) { - this->thisFactionIndex= thisFactionIndex; - } - void setFactionCount(int factionCount) {this->factionCount= factionCount;} - void setTeam(int factionIndex, int team) { - if(factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s] Invalid factionIndex = %d\n",__FUNCTION__,factionIndex); - throw megaglest_runtime_error(szBuf); - } - - this->teams[factionIndex]= team; - } - void setStartLocationIndex(int factionIndex, int startLocationIndex) { - if(factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s] Invalid factionIndex = %d\n",__FUNCTION__,factionIndex); - throw megaglest_runtime_error(szBuf); - } - - this->startLocationIndex[factionIndex]= startLocationIndex; - } - void setMapFilter(int mapFilter) {this->mapFilter=mapFilter;} - - void setDefaultUnits(bool defaultUnits) {this->defaultUnits= defaultUnits;} - void setDefaultResources(bool defaultResources) {this->defaultResources= defaultResources;} - void setDefaultVictoryConditions(bool defaultVictoryConditions) {this->defaultVictoryConditions= defaultVictoryConditions;} - - void setFogOfWar(bool fogOfWar) {this->fogOfWar = fogOfWar;} - void setAllowObservers(bool value) {this->allowObservers = value;} - void setEnableObserverModeAtEndGame(bool value) {this->enableObserverModeAtEndGame = value;} - void setEnableServerControlledAI(bool value) {this->enableServerControlledAI = value;} - void setNetworkFramePeriod(int value) {this->networkFramePeriod = value; } - void setNetworkPauseGameForLaggedClients(bool value) {this->networkPauseGameForLaggedClients = value; } - void setPathFinderType(PathFinderType value) {this->pathFinderType = value; } - - void setFlagTypes1(uint32 value) {this->flagTypes1 = value; } - - void setMapCRC(uint32 value) { mapCRC = value; } - void setTilesetCRC(uint32 value) { tilesetCRC = value; } - void setTechCRC(uint32 value) { techCRC = value; } - - void setFactionCRCList(const vector > &value) { factionCRCList = value; } - - int getAiAcceptSwitchTeamPercentChance() const { return aiAcceptSwitchTeamPercentChance;} - void setAiAcceptSwitchTeamPercentChance(int value) { aiAcceptSwitchTeamPercentChance = value; } - - int getFallbackCpuMultiplier() const { return fallbackCpuMultiplier;} - void setFallbackCpuMultiplier(int value) { fallbackCpuMultiplier = value; } - - int getMasterserver_admin() const { return masterserver_admin;} - void setMasterserver_admin(int value) { masterserver_admin = value; } - - int getMasterserver_admin_faction_index() const { return masterserver_admin_factionIndex;} - void setMasterserver_admin_faction_index(int value) { masterserver_admin_factionIndex = value; } - - bool getNetworkAllowNativeLanguageTechtree() const { return networkAllowNativeLanguageTechtree;} - void setNetworkAllowNativeLanguageTechtree(bool value) { networkAllowNativeLanguageTechtree = value; } - - void setGameUUID(const string& gameUUID) {this->gameUUID= gameUUID;} - - string toString() const { - string result = ""; - - result += "Game ID = " + gameUUID + "\n"; - result += "gameName = " + gameName + "\n"; - result += "description = " + description + "\n"; - result += "mapFilterIndex = " + intToStr(mapFilter) + "\n"; - result += "map = " + map + "\n"; - result += "tileset = " + tileset + "\n"; - result += "tech = " + tech + "\n"; - result += "scenario = " + scenario + "\n"; - result += "scenarioDir = " + scenarioDir + "\n"; - - for(int idx =0; idx < GameConstants::maxPlayers; idx++) { - result += "player index = " + intToStr(idx) + "\n"; - result += "factionTypeName = " + factionTypeNames[idx] + "\n"; - result += "networkPlayerName = " + networkPlayerNames[idx] + "\n"; - result += "networkPlayerPlatform = " + networkPlayerPlatform[idx] + "\n"; - result += "networkPlayerLanguage = " + networkPlayerLanguages[idx] + "\n"; - - result += "factionControl = " + intToStr(factionControls[idx]) + "\n"; - result += "resourceMultiplierIndex = " + intToStr(resourceMultiplierIndex[idx]) + "\n"; - result += "team = " + intToStr(teams[idx]) + "\n"; - result += "startLocationIndex = " + intToStr(startLocationIndex[idx]) + "\n"; - result += "networkPlayerUUID = " + networkPlayerUUID[idx] + "\n"; - } - - result += "thisFactionIndex = " + intToStr(thisFactionIndex) + "\n"; - result += "factionCount = " + intToStr(factionCount) + "\n"; - result += "defaultUnits = " + intToStr(defaultUnits) + "\n"; - result += "defaultResources = " + intToStr(defaultResources) + "\n"; - result += "defaultVictoryConditions = " + intToStr(defaultVictoryConditions) + "\n"; - result += "fogOfWar = " + intToStr(fogOfWar) + "\n"; - result += "allowObservers = " + intToStr(allowObservers) + "\n"; - result += "enableObserverModeAtEndGame = " + intToStr(enableObserverModeAtEndGame) + "\n"; - result += "enableServerControlledAI = " + intToStr(enableServerControlledAI) + "\n"; - result += "networkFramePeriod = " + intToStr(networkFramePeriod) + "\n"; - result += "networkPauseGameForLaggedClients = " + intToStr(networkPauseGameForLaggedClients) + "\n"; - result += "pathFinderType = " + intToStr(pathFinderType) + "\n"; - result += "flagTypes1 = " + uIntToStr(flagTypes1) + "\n"; - result += "mapCRC = " + uIntToStr(mapCRC) + "\n"; - result += "tilesetCRC = " + uIntToStr(tilesetCRC) + "\n"; - result += "techCRC = " + uIntToStr(techCRC) + "\n"; - - for(unsigned int i = 0; i < factionCRCList.size(); ++i) { - result += "factionCRCList name [" + factionCRCList[i].first + "] CRC = " + uIntToStr(factionCRCList[i].second) + "\n"; - } - - result += "aiAcceptSwitchTeamPercentChance = " + intToStr(aiAcceptSwitchTeamPercentChance) + "\n"; - result += "masterserver_admin = " + intToStr(masterserver_admin) + "\n"; - result += "masterserver_admin_factionIndex = " + intToStr(masterserver_admin_factionIndex) + "\n"; - - result += "networkAllowNativeLanguageTechtree = " + intToStr(networkAllowNativeLanguageTechtree) + "\n"; - return result; - } - - void saveGame(XmlNode *rootNode) const { - std::map mapTagReplacements; - XmlNode *gameSettingsNode = rootNode->addChild("GameSettings"); - - gameSettingsNode->addAttribute("gameUUID",gameUUID, mapTagReplacements); - -// string gameName; - gameSettingsNode->addAttribute("gameName",gameName, mapTagReplacements); -// string description; - gameSettingsNode->addAttribute("description",description, mapTagReplacements); -// string map; - gameSettingsNode->addAttribute("map",map, mapTagReplacements); -// string tileset; - gameSettingsNode->addAttribute("tileset",tileset, mapTagReplacements); -// string tech; - gameSettingsNode->addAttribute("tech",tech, mapTagReplacements); -// string scenario; - gameSettingsNode->addAttribute("scenario",scenario, mapTagReplacements); -// string scenarioDir; - gameSettingsNode->addAttribute("scenarioDir",scenarioDir, mapTagReplacements); -// string factionTypeNames[GameConstants::maxPlayers]; //faction names - for(int idx =0; idx < GameConstants::maxPlayers; idx++) { - XmlNode *factionTypeNamesNode = gameSettingsNode->addChild("factionTypeNames"); - factionTypeNamesNode->addAttribute("name",factionTypeNames[idx], mapTagReplacements); - } - -// string networkPlayerNames[GameConstants::maxPlayers]; - for(int idx =0; idx < GameConstants::maxPlayers; idx++) { - XmlNode *networkPlayerNamesNode = gameSettingsNode->addChild("networkPlayerNames"); - networkPlayerNamesNode->addAttribute("name",networkPlayerNames[idx], mapTagReplacements); - } - - for(int idx =0; idx < GameConstants::maxPlayers; idx++) { - XmlNode *networkPlayerNamesNode = gameSettingsNode->addChild("networkPlayerPlatform"); - networkPlayerNamesNode->addAttribute("name",networkPlayerPlatform[idx], mapTagReplacements); - } - -// int networkPlayerStatuses[GameConstants::maxPlayers]; - for(int idx =0; idx < GameConstants::maxPlayers; idx++) { - XmlNode *networkPlayerStatusesNode = gameSettingsNode->addChild("networkPlayerStatuses"); - networkPlayerStatusesNode->addAttribute("status",intToStr(networkPlayerStatuses[idx]), mapTagReplacements); - } - - // int networkPlayerStatuses[GameConstants::maxPlayers]; - for(int idx =0; idx < GameConstants::maxPlayers; idx++) { - XmlNode *networkPlayerStatusesNode = gameSettingsNode->addChild("networkPlayerGameStatus"); - networkPlayerStatusesNode->addAttribute("game_status",intToStr(networkPlayerGameStatus[idx]), mapTagReplacements); - } - -// string networkPlayerLanguages[GameConstants::maxPlayers]; - for(int idx =0; idx < GameConstants::maxPlayers; idx++) { - XmlNode *networkPlayerLanguagesNode = gameSettingsNode->addChild("networkPlayerLanguages"); - networkPlayerLanguagesNode->addAttribute("name",networkPlayerLanguages[idx], mapTagReplacements); - } - -// ControlType factionControls[GameConstants::maxPlayers]; - for(int idx =0; idx < GameConstants::maxPlayers; idx++) { - XmlNode *factionControlsNode = gameSettingsNode->addChild("factionControls"); - factionControlsNode->addAttribute("control",intToStr(factionControls[idx]), mapTagReplacements); - } - -// int resourceMultiplierIndex[GameConstants::maxPlayers]; - for(int idx =0; idx < GameConstants::maxPlayers; idx++) { - XmlNode *resourceMultiplierIndexNode = gameSettingsNode->addChild("resourceMultiplierIndex"); - resourceMultiplierIndexNode->addAttribute("multiplier",intToStr(resourceMultiplierIndex[idx]), mapTagReplacements); - } - -// int thisFactionIndex; - gameSettingsNode->addAttribute("thisFactionIndex",intToStr(thisFactionIndex), mapTagReplacements); -// int factionCount; - gameSettingsNode->addAttribute("factionCount",intToStr(factionCount), mapTagReplacements); -// int teams[GameConstants::maxPlayers]; - for(int idx =0; idx < GameConstants::maxPlayers; idx++) { - XmlNode *teamsNode = gameSettingsNode->addChild("teams"); - teamsNode->addAttribute("team",intToStr(teams[idx]), mapTagReplacements); - } - -// int startLocationIndex[GameConstants::maxPlayers]; - for(int idx =0; idx < GameConstants::maxPlayers; idx++) { - XmlNode *startLocationIndexNode = gameSettingsNode->addChild("startLocationIndex"); - startLocationIndexNode->addAttribute("location",intToStr(startLocationIndex[idx]), mapTagReplacements); - } - - for(int idx =0; idx < GameConstants::maxPlayers; idx++) { - XmlNode *networkPlayerUUIDNode = gameSettingsNode->addChild("networkPlayerUUID"); - networkPlayerUUIDNode->addAttribute("value",networkPlayerUUID[idx], mapTagReplacements); - } - -// int mapFilterIndex; - gameSettingsNode->addAttribute("mapFilterIndex",intToStr(mapFilter), mapTagReplacements); -// -// -// bool defaultUnits; - gameSettingsNode->addAttribute("defaultUnits",intToStr(defaultUnits), mapTagReplacements); -// bool defaultResources; - gameSettingsNode->addAttribute("defaultResources",intToStr(defaultResources), mapTagReplacements); -// bool defaultVictoryConditions; - gameSettingsNode->addAttribute("defaultVictoryConditions",intToStr(defaultVictoryConditions), mapTagReplacements); -// bool fogOfWar; - gameSettingsNode->addAttribute("fogOfWar",intToStr(fogOfWar), mapTagReplacements); -// bool allowObservers; - gameSettingsNode->addAttribute("allowObservers",intToStr(allowObservers), mapTagReplacements); -// bool enableObserverModeAtEndGame; - gameSettingsNode->addAttribute("enableObserverModeAtEndGame",intToStr(enableObserverModeAtEndGame), mapTagReplacements); -// bool enableServerControlledAI; - gameSettingsNode->addAttribute("enableServerControlledAI",intToStr(enableServerControlledAI), mapTagReplacements); -// int networkFramePeriod; - gameSettingsNode->addAttribute("networkFramePeriod",intToStr(networkFramePeriod), mapTagReplacements); -// bool networkPauseGameForLaggedClients; - gameSettingsNode->addAttribute("networkPauseGameForLaggedClients",intToStr(networkPauseGameForLaggedClients), mapTagReplacements); -// PathFinderType pathFinderType; - gameSettingsNode->addAttribute("pathFinderType",intToStr(pathFinderType), mapTagReplacements); -// uint32 flagTypes1; - gameSettingsNode->addAttribute("flagTypes1",uIntToStr(flagTypes1), mapTagReplacements); -// int32 mapCRC; - gameSettingsNode->addAttribute("mapCRC",uIntToStr(mapCRC), mapTagReplacements); -// int32 tilesetCRC; - gameSettingsNode->addAttribute("tilesetCRC",uIntToStr(tilesetCRC), mapTagReplacements); -// int32 techCRC; - gameSettingsNode->addAttribute("techCRC",uIntToStr(techCRC), mapTagReplacements); -// vector > factionCRCList; - for(unsigned int i = 0; i < factionCRCList.size(); ++i) { - const pair &item = factionCRCList[i]; - - XmlNode *factionCRCListNode = gameSettingsNode->addChild("factionCRCList"); - factionCRCListNode->addAttribute("key",item.first, mapTagReplacements); - factionCRCListNode->addAttribute("value",uIntToStr(item.second), mapTagReplacements); - } -// int aiAcceptSwitchTeamPercentChance; - gameSettingsNode->addAttribute("aiAcceptSwitchTeamPercentChance",intToStr(aiAcceptSwitchTeamPercentChance), mapTagReplacements); -// int masterserver_admin; - gameSettingsNode->addAttribute("masterserver_admin",intToStr(masterserver_admin), mapTagReplacements); - - gameSettingsNode->addAttribute("masterserver_admin_factionIndex",intToStr(masterserver_admin_factionIndex), mapTagReplacements); - - gameSettingsNode->addAttribute("networkAllowNativeLanguageTechtree",intToStr(networkAllowNativeLanguageTechtree), mapTagReplacements); - } - - void loadGame(const XmlNode *rootNode) { - const XmlNode *gameSettingsNode = rootNode->getChild("GameSettings"); - - if(gameSettingsNode->hasAttribute("gameUUID") == true) { - gameUUID = gameSettingsNode->getAttribute("gameUUID")->getValue(); - } - -// string gameName; - if(gameSettingsNode->hasAttribute("gameName") == true) { - gameName = gameSettingsNode->getAttribute("gameName")->getValue(); - } - else { - gameName = "oldSavegame"; - } -// string description; - description = gameSettingsNode->getAttribute("description")->getValue(); -// string map; - map = gameSettingsNode->getAttribute("map")->getValue(); -// string tileset; - tileset = gameSettingsNode->getAttribute("tileset")->getValue(); -// string tech; - tech = gameSettingsNode->getAttribute("tech")->getValue(); -// string scenario; - scenario = gameSettingsNode->getAttribute("scenario")->getValue(); -// string scenarioDir; - scenarioDir = gameSettingsNode->getAttribute("scenarioDir")->getValue(); - if(fileExists(scenarioDir) == false) { - scenarioDir = Config::findValidLocalFileFromPath(scenarioDir); - } - -// string factionTypeNames[GameConstants::maxPlayers]; //faction names - for(int idx =0; idx < GameConstants::maxPlayers; idx++) { - const XmlNode *factionTypeNamesNode = gameSettingsNode->getChild("factionTypeNames",idx); - factionTypeNames[idx] = factionTypeNamesNode->getAttribute("name")->getValue(); - } - -// string networkPlayerNames[GameConstants::maxPlayers]; - for(int idx =0; idx < GameConstants::maxPlayers; idx++) { - const XmlNode *networkPlayerNamesNode = gameSettingsNode->getChild("networkPlayerNames",idx); - networkPlayerNames[idx] = networkPlayerNamesNode->getAttribute("name")->getValue(); - } - -// int networkPlayerStatuses[GameConstants::maxPlayers]; - for(int idx =0; idx < GameConstants::maxPlayers; idx++) { - const XmlNode *networkPlayerStatusesNode = gameSettingsNode->getChild("networkPlayerStatuses",idx); - networkPlayerStatuses[idx] = networkPlayerStatusesNode->getAttribute("status")->getIntValue(); - } - - // int networkPlayerStatuses[GameConstants::maxPlayers]; - for(int idx =0; idx < GameConstants::maxPlayers; idx++) { - if(gameSettingsNode->hasChildAtIndex("networkPlayerGameStatus",idx) == true) { - const XmlNode *networkPlayerGameStatusNode = gameSettingsNode->getChild("networkPlayerGameStatus",idx); - networkPlayerGameStatus[idx] = networkPlayerGameStatusNode->getAttribute("game_status")->getIntValue(); - } - } - -// string networkPlayerLanguages[GameConstants::maxPlayers]; - for(int idx =0; idx < GameConstants::maxPlayers; idx++) { - const XmlNode *networkPlayerLanguagesNode = gameSettingsNode->getChild("networkPlayerLanguages",idx); - networkPlayerLanguages[idx] = networkPlayerLanguagesNode->getAttribute("name")->getValue(); - } - -// ControlType factionControls[GameConstants::maxPlayers]; - for(int idx =0; idx < GameConstants::maxPlayers; idx++) { - const XmlNode *factionControlsNode = gameSettingsNode->getChild("factionControls",idx); - factionControls[idx] = static_cast(factionControlsNode->getAttribute("control")->getIntValue()); - } - -// int resourceMultiplierIndex[GameConstants::maxPlayers]; - for(int idx =0; idx < GameConstants::maxPlayers; idx++) { - const XmlNode *resourceMultiplierIndexNode = gameSettingsNode->getChild("resourceMultiplierIndex",idx); - resourceMultiplierIndex[idx] = resourceMultiplierIndexNode->getAttribute("multiplier")->getIntValue(); - } - - for(int idx =0; idx < GameConstants::maxPlayers; idx++) { - if(gameSettingsNode->hasChildAtIndex("networkPlayerUUID",idx) == true) { - const XmlNode *networkPlayerUUIDNode = gameSettingsNode->getChild("networkPlayerUUID",idx); - networkPlayerUUID[idx] = networkPlayerUUIDNode->getAttribute("value")->getValue(); - } - } - -// int thisFactionIndex; - thisFactionIndex = gameSettingsNode->getAttribute("thisFactionIndex")->getIntValue(); -// int factionCount; - factionCount = gameSettingsNode->getAttribute("factionCount")->getIntValue(); -// int teams[GameConstants::maxPlayers]; - for(int idx =0; idx < GameConstants::maxPlayers; idx++) { - const XmlNode *teamsNode = gameSettingsNode->getChild("teams",idx); - teams[idx] = teamsNode->getAttribute("team")->getIntValue(); - } - -// int startLocationIndex[GameConstants::maxPlayers]; - for(int idx =0; idx < GameConstants::maxPlayers; idx++) { - const XmlNode *startLocationIndexNode = gameSettingsNode->getChild("startLocationIndex",idx); - startLocationIndex[idx] = startLocationIndexNode->getAttribute("location")->getIntValue(); - } - -// int mapFilterIndex; - mapFilter = gameSettingsNode->getAttribute("mapFilterIndex")->getIntValue(); -// -// -// bool defaultUnits; - defaultUnits = gameSettingsNode->getAttribute("defaultUnits")->getIntValue() != 0; -// bool defaultResources; - defaultResources = gameSettingsNode->getAttribute("defaultResources")->getIntValue() != 0; -// bool defaultVictoryConditions; - defaultVictoryConditions = gameSettingsNode->getAttribute("defaultVictoryConditions")->getIntValue() != 0; -// bool fogOfWar; - fogOfWar = gameSettingsNode->getAttribute("fogOfWar")->getIntValue() != 0; -// bool allowObservers; - allowObservers = gameSettingsNode->getAttribute("allowObservers")->getIntValue() != 0; -// bool enableObserverModeAtEndGame; - enableObserverModeAtEndGame = gameSettingsNode->getAttribute("enableObserverModeAtEndGame")->getIntValue() != 0; -// bool enableServerControlledAI; - enableServerControlledAI = gameSettingsNode->getAttribute("enableServerControlledAI")->getIntValue() != 0; -// int networkFramePeriod; - networkFramePeriod = gameSettingsNode->getAttribute("networkFramePeriod")->getIntValue(); -// bool networkPauseGameForLaggedClients; - networkPauseGameForLaggedClients = gameSettingsNode->getAttribute("networkPauseGameForLaggedClients")->getIntValue() != 0; -// PathFinderType pathFinderType; - pathFinderType = static_cast(gameSettingsNode->getAttribute("pathFinderType")->getIntValue()); -// uint32 flagTypes1; - flagTypes1 = gameSettingsNode->getAttribute("flagTypes1")->getUIntValue(); -// int32 mapCRC; - mapCRC = gameSettingsNode->getAttribute("mapCRC")->getUIntValue(); -// int32 tilesetCRC; - tilesetCRC = gameSettingsNode->getAttribute("tilesetCRC")->getUIntValue(); -// int32 techCRC; - techCRC = gameSettingsNode->getAttribute("techCRC")->getUIntValue(); -// vector > factionCRCList; -// for(unsigned int i = 0; i < factionCRCList.size(); ++i) { -// const pair &item = factionCRCList[i]; -// -// XmlNode *factionCRCListNode = gameSettingsNode->addChild("factionCRCList"); -// factionCRCListNode->addAttribute("key",item.first, mapTagReplacements); -// factionCRCListNode->addAttribute("value",intToStr(item.second), mapTagReplacements); -// } -// int aiAcceptSwitchTeamPercentChance; - aiAcceptSwitchTeamPercentChance = gameSettingsNode->getAttribute("aiAcceptSwitchTeamPercentChance")->getIntValue(); -// int masterserver_admin; - masterserver_admin = gameSettingsNode->getAttribute("masterserver_admin")->getIntValue(); - - if(gameSettingsNode->hasAttribute("masterserver_admin_factionIndex") == true) { - masterserver_admin_factionIndex = gameSettingsNode->getAttribute("masterserver_admin_factionIndex")->getIntValue(); - } - - if(gameSettingsNode->hasAttribute("networkAllowNativeLanguageTechtree") == true) { - networkAllowNativeLanguageTechtree = gameSettingsNode->getAttribute("networkAllowNativeLanguageTechtree")->getIntValue() != 0; - } - } + flagTypes1 = ft1_none; + + mapCRC = 0; + tilesetCRC = 0; + techCRC = 0; + factionCRCList.clear(); + aiAcceptSwitchTeamPercentChance = 30; + masterserver_admin = -1; + masterserver_admin_factionIndex = -1; + fallbackCpuMultiplier = 1.5f; + networkAllowNativeLanguageTechtree = true; + } + + // default copy constructor will do fine, and will maintain itself ;) + + // get + const string &getGameName() const { return gameName; } + const string &getDescription() const { return description; } + const string &getMap() const { return map; } + const string &getTileset() const { return tileset; } + const string &getTech() const { return tech; } + const string &getScenario() const { return scenario; } + const string &getScenarioDir() const { return scenarioDir; } + const string &getFactionTypeName(int factionIndex) const { + if (factionIndex == -1) { + static string HEADLESS_FACTION = "headless-server"; + return HEADLESS_FACTION; + } + if (factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s] Invalid factionIndex = %d\n", __FUNCTION__, + factionIndex); + throw megaglest_runtime_error(szBuf); + } + return factionTypeNames[factionIndex]; + } + string getNetworkPlayerName(int factionIndex) const { + if (factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s] Invalid factionIndex = %d\n", __FUNCTION__, + factionIndex); + throw megaglest_runtime_error(szBuf); + } + + string result = networkPlayerNames[factionIndex]; + if (networkPlayerStatuses[factionIndex] == npst_Disconnected) { + result = playerDisconnectedText + result; + } + return result; + } + string getNetworkPlayerPlatform(int factionIndex) const { + if (factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s] Invalid factionIndex = %d\n", __FUNCTION__, + factionIndex); + throw megaglest_runtime_error(szBuf); + } + + string result = networkPlayerPlatform[factionIndex]; + return result; + } + + const int getNetworkPlayerStatuses(int factionIndex) const { + if (factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s] Invalid factionIndex = %d\n", __FUNCTION__, + factionIndex); + throw megaglest_runtime_error(szBuf); + } + + return networkPlayerStatuses[factionIndex]; + } + const string getNetworkPlayerLanguages(int factionIndex) const { + if (factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s] Invalid factionIndex = %d\n", __FUNCTION__, + factionIndex); + throw megaglest_runtime_error(szBuf); + } + + return networkPlayerLanguages[factionIndex]; + } + + const int getNetworkPlayerGameStatus(int factionIndex) const { + if (factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s] Invalid factionIndex = %d\n", __FUNCTION__, + factionIndex); + throw megaglest_runtime_error(szBuf); + } + + return networkPlayerGameStatus[factionIndex]; + } + + const vector getUniqueNetworkPlayerLanguages() const { + vector languageList; + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + if (networkPlayerLanguages[i] != "") { + if (std::find(languageList.begin(), languageList.end(), + networkPlayerLanguages[i]) == languageList.end()) { + languageList.push_back(networkPlayerLanguages[i]); + } + } + } + if (languageList.empty() == true) { + languageList.push_back(""); + } + return languageList; + } + + const string getNetworkPlayerNameByPlayerIndex(int playerIndex) const { + string result = ""; + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + if (startLocationIndex[i] == playerIndex) { + result = networkPlayerNames[i]; + break; + } + } + return result; + } + const string getNetworkPlayerPlatformByPlayerIndex(int playerIndex) const { + string result = ""; + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + if (startLocationIndex[i] == playerIndex) { + result = networkPlayerPlatform[i]; + break; + } + } + return result; + } + + ControlType getFactionControl(int factionIndex) const { + if (factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s] Invalid factionIndex = %d\n", __FUNCTION__, + factionIndex); + throw megaglest_runtime_error(szBuf); + } + + return factionControls[factionIndex]; + } + int getResourceMultiplierIndex(int factionIndex) const { + if (factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s] Invalid factionIndex = %d\n", __FUNCTION__, + factionIndex); + throw megaglest_runtime_error(szBuf); + } + + return resourceMultiplierIndex[factionIndex]; + } + + const string &getNetworkPlayerUUID(int factionIndex) const { + if (factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s] Invalid factionIndex = %d\n", __FUNCTION__, + factionIndex); + throw megaglest_runtime_error(szBuf); + } + return networkPlayerUUID[factionIndex]; + } + + bool isNetworkGame() const { + bool result = false; + for (int idx = 0; idx < GameConstants::maxPlayers; ++idx) { + if (factionControls[idx] == ctNetwork || + factionControls[idx] == ctNetworkUnassigned || + networkPlayerStatuses[idx] == npst_Disconnected) { + result = true; + break; + } + } + return result; + } + int getThisFactionIndex() const { return thisFactionIndex; } + int getFactionCount() const { return factionCount; } + int getTeam(int factionIndex) const { + if (factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s] Invalid factionIndex = %d\n", __FUNCTION__, + factionIndex); + throw megaglest_runtime_error(szBuf); + } + + return teams[factionIndex]; + } + + int getStartLocationIndex(int factionIndex) const { + if (factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s] Invalid factionIndex = %d\n", __FUNCTION__, + factionIndex); + throw megaglest_runtime_error(szBuf); + } + + return startLocationIndex[factionIndex]; + } + int getFactionIndexForStartLocation(int startIndex) const { + if (startIndex < 0 || startIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s] Invalid startIndex = %d\n", __FUNCTION__, + startIndex); + throw megaglest_runtime_error(szBuf); + } + + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + if (startLocationIndex[i] == startIndex) { + return i; + } + } + return -1; + } + + int getMapFilter() const { return mapFilter; } + + bool getDefaultUnits() const { return defaultUnits; } + bool getDefaultResources() const { return defaultResources; } + bool getDefaultVictoryConditions() const { return defaultVictoryConditions; } + + bool getFogOfWar() const { return fogOfWar; } + bool getAllowObservers() const { return allowObservers; } + bool getEnableObserverModeAtEndGame() const { + return enableObserverModeAtEndGame; + } + bool getEnableServerControlledAI() const { return enableServerControlledAI; } + int getNetworkFramePeriod() const { return networkFramePeriod; } + bool getNetworkPauseGameForLaggedClients() const { + return networkPauseGameForLaggedClients; + } + PathFinderType getPathFinderType() const { return pathFinderType; } + uint32 getFlagTypes1() const { return flagTypes1; } + + uint32 getMapCRC() const { return mapCRC; } + uint32 getTilesetCRC() const { return tilesetCRC; } + uint32 getTechCRC() const { return techCRC; } + vector> getFactionCRCList() const { + return factionCRCList; + } + + const string &getGameUUID() const { return gameUUID; } + + // set + void setGameName(const string &gameName) { this->gameName = gameName; } + void setDescription(const string &description) { + this->description = description; + } + void setMap(const string &map) { this->map = map; } + void setTileset(const string &tileset) { this->tileset = tileset; } + void setTech(const string &tech) { this->tech = tech; } + void setScenario(const string &scenario) { this->scenario = scenario; } + void setScenarioDir(const string &scenarioDir) { + this->scenarioDir = scenarioDir; + } + + void setFactionTypeName(int factionIndex, const string &factionTypeName) { + if (factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s] Invalid factionIndex = %d\n", __FUNCTION__, + factionIndex); + throw megaglest_runtime_error(szBuf); + } + + this->factionTypeNames[factionIndex] = factionTypeName; + } + void setNetworkPlayerName(int factionIndex, const string &playername) { + if (factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s] Invalid factionIndex = %d\n", __FUNCTION__, + factionIndex); + throw megaglest_runtime_error(szBuf); + } + + this->networkPlayerNames[factionIndex] = playername; + } + void setNetworkPlayerPlatform(int factionIndex, const string &platform) { + if (factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s] Invalid factionIndex = %d\n", __FUNCTION__, + factionIndex); + throw megaglest_runtime_error(szBuf); + } + + this->networkPlayerPlatform[factionIndex] = platform; + } + + void setNetworkPlayerStatuses(int factionIndex, int status) { + if (factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s] Invalid factionIndex = %d\n", __FUNCTION__, + factionIndex); + throw megaglest_runtime_error(szBuf); + } + + this->networkPlayerStatuses[factionIndex] = status; + } + + void setNetworkPlayerGameStatus(int factionIndex, int status) { + if (factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s] Invalid factionIndex = %d\n", __FUNCTION__, + factionIndex); + throw megaglest_runtime_error(szBuf); + } + + this->networkPlayerGameStatus[factionIndex] = status; + } + void setNetworkPlayerLanguages(int factionIndex, const string &language) { + if (factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s] Invalid factionIndex = %d\n", __FUNCTION__, + factionIndex); + throw megaglest_runtime_error(szBuf); + } + + this->networkPlayerLanguages[factionIndex] = language; + } + void setFactionControl(int factionIndex, ControlType controller) { + if (factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s] Invalid factionIndex = %d\n", __FUNCTION__, + factionIndex); + throw megaglest_runtime_error(szBuf); + } + + this->factionControls[factionIndex] = controller; + } + void setResourceMultiplierIndex(int factionIndex, int multiplierIndex) { + if (factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s] Invalid factionIndex = %d\n", __FUNCTION__, + factionIndex); + throw megaglest_runtime_error(szBuf); + } + + // if(multiplierIndex >= 45) { + // printf("gamesettings Line: %d multiplier index: %d factionIndex: + //%d\n",__LINE__,multiplierIndex,factionIndex); + // } + + this->resourceMultiplierIndex[factionIndex] = multiplierIndex; + } + + void setNetworkPlayerUUID(int factionIndex, const string &uuid) { + if (factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s] Invalid factionIndex = %d\n", __FUNCTION__, + factionIndex); + throw megaglest_runtime_error(szBuf); + } + + this->networkPlayerUUID[factionIndex] = uuid; + } + + void setThisFactionIndex(int thisFactionIndex) { + this->thisFactionIndex = thisFactionIndex; + } + void setFactionCount(int factionCount) { this->factionCount = factionCount; } + void setTeam(int factionIndex, int team) { + if (factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s] Invalid factionIndex = %d\n", __FUNCTION__, + factionIndex); + throw megaglest_runtime_error(szBuf); + } + + this->teams[factionIndex] = team; + } + void setStartLocationIndex(int factionIndex, int startLocationIndex) { + if (factionIndex < 0 || factionIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s] Invalid factionIndex = %d\n", __FUNCTION__, + factionIndex); + throw megaglest_runtime_error(szBuf); + } + + this->startLocationIndex[factionIndex] = startLocationIndex; + } + void setMapFilter(int mapFilter) { this->mapFilter = mapFilter; } + + void setDefaultUnits(bool defaultUnits) { this->defaultUnits = defaultUnits; } + void setDefaultResources(bool defaultResources) { + this->defaultResources = defaultResources; + } + void setDefaultVictoryConditions(bool defaultVictoryConditions) { + this->defaultVictoryConditions = defaultVictoryConditions; + } + + void setFogOfWar(bool fogOfWar) { this->fogOfWar = fogOfWar; } + void setAllowObservers(bool value) { this->allowObservers = value; } + void setEnableObserverModeAtEndGame(bool value) { + this->enableObserverModeAtEndGame = value; + } + void setEnableServerControlledAI(bool value) { + this->enableServerControlledAI = value; + } + void setNetworkFramePeriod(int value) { this->networkFramePeriod = value; } + void setNetworkPauseGameForLaggedClients(bool value) { + this->networkPauseGameForLaggedClients = value; + } + void setPathFinderType(PathFinderType value) { this->pathFinderType = value; } + + void setFlagTypes1(uint32 value) { this->flagTypes1 = value; } + + void setMapCRC(uint32 value) { mapCRC = value; } + void setTilesetCRC(uint32 value) { tilesetCRC = value; } + void setTechCRC(uint32 value) { techCRC = value; } + + void setFactionCRCList(const vector> &value) { + factionCRCList = value; + } + + int getAiAcceptSwitchTeamPercentChance() const { + return aiAcceptSwitchTeamPercentChance; + } + void setAiAcceptSwitchTeamPercentChance(int value) { + aiAcceptSwitchTeamPercentChance = value; + } + + int getFallbackCpuMultiplier() const { return fallbackCpuMultiplier; } + void setFallbackCpuMultiplier(int value) { fallbackCpuMultiplier = value; } + + int getMasterserver_admin() const { return masterserver_admin; } + void setMasterserver_admin(int value) { masterserver_admin = value; } + + int getMasterserver_admin_faction_index() const { + return masterserver_admin_factionIndex; + } + void setMasterserver_admin_faction_index(int value) { + masterserver_admin_factionIndex = value; + } + + bool getNetworkAllowNativeLanguageTechtree() const { + return networkAllowNativeLanguageTechtree; + } + void setNetworkAllowNativeLanguageTechtree(bool value) { + networkAllowNativeLanguageTechtree = value; + } + + void setGameUUID(const string &gameUUID) { this->gameUUID = gameUUID; } + + string toString() const { + string result = ""; + + result += "Game ID = " + gameUUID + "\n"; + result += "gameName = " + gameName + "\n"; + result += "description = " + description + "\n"; + result += "mapFilterIndex = " + intToStr(mapFilter) + "\n"; + result += "map = " + map + "\n"; + result += "tileset = " + tileset + "\n"; + result += "tech = " + tech + "\n"; + result += "scenario = " + scenario + "\n"; + result += "scenarioDir = " + scenarioDir + "\n"; + + for (int idx = 0; idx < GameConstants::maxPlayers; idx++) { + result += "player index = " + intToStr(idx) + "\n"; + result += "factionTypeName = " + factionTypeNames[idx] + "\n"; + result += "networkPlayerName = " + networkPlayerNames[idx] + "\n"; + result += "networkPlayerPlatform = " + networkPlayerPlatform[idx] + "\n"; + result += "networkPlayerLanguage = " + networkPlayerLanguages[idx] + "\n"; + + result += "factionControl = " + intToStr(factionControls[idx]) + "\n"; + result += "resourceMultiplierIndex = " + + intToStr(resourceMultiplierIndex[idx]) + "\n"; + result += "team = " + intToStr(teams[idx]) + "\n"; + result += + "startLocationIndex = " + intToStr(startLocationIndex[idx]) + "\n"; + result += "networkPlayerUUID = " + networkPlayerUUID[idx] + "\n"; + } + + result += "thisFactionIndex = " + intToStr(thisFactionIndex) + "\n"; + result += "factionCount = " + intToStr(factionCount) + "\n"; + result += "defaultUnits = " + intToStr(defaultUnits) + "\n"; + result += "defaultResources = " + intToStr(defaultResources) + "\n"; + result += + "defaultVictoryConditions = " + intToStr(defaultVictoryConditions) + + "\n"; + result += "fogOfWar = " + intToStr(fogOfWar) + "\n"; + result += "allowObservers = " + intToStr(allowObservers) + "\n"; + result += "enableObserverModeAtEndGame = " + + intToStr(enableObserverModeAtEndGame) + "\n"; + result += + "enableServerControlledAI = " + intToStr(enableServerControlledAI) + + "\n"; + result += "networkFramePeriod = " + intToStr(networkFramePeriod) + "\n"; + result += "networkPauseGameForLaggedClients = " + + intToStr(networkPauseGameForLaggedClients) + "\n"; + result += "pathFinderType = " + intToStr(pathFinderType) + "\n"; + result += "flagTypes1 = " + uIntToStr(flagTypes1) + "\n"; + result += "mapCRC = " + uIntToStr(mapCRC) + "\n"; + result += "tilesetCRC = " + uIntToStr(tilesetCRC) + "\n"; + result += "techCRC = " + uIntToStr(techCRC) + "\n"; + + for (unsigned int i = 0; i < factionCRCList.size(); ++i) { + result += "factionCRCList name [" + factionCRCList[i].first + + "] CRC = " + uIntToStr(factionCRCList[i].second) + "\n"; + } + + result += "aiAcceptSwitchTeamPercentChance = " + + intToStr(aiAcceptSwitchTeamPercentChance) + "\n"; + result += "masterserver_admin = " + intToStr(masterserver_admin) + "\n"; + result += "masterserver_admin_factionIndex = " + + intToStr(masterserver_admin_factionIndex) + "\n"; + + result += "networkAllowNativeLanguageTechtree = " + + intToStr(networkAllowNativeLanguageTechtree) + "\n"; + return result; + } + + void saveGame(XmlNode *rootNode) const { + std::map mapTagReplacements; + XmlNode *gameSettingsNode = rootNode->addChild("GameSettings"); + + gameSettingsNode->addAttribute("gameUUID", gameUUID, mapTagReplacements); + + // string gameName; + gameSettingsNode->addAttribute("gameName", gameName, mapTagReplacements); + // string description; + gameSettingsNode->addAttribute("description", description, + mapTagReplacements); + // string map; + gameSettingsNode->addAttribute("map", map, mapTagReplacements); + // string tileset; + gameSettingsNode->addAttribute("tileset", tileset, mapTagReplacements); + // string tech; + gameSettingsNode->addAttribute("tech", tech, mapTagReplacements); + // string scenario; + gameSettingsNode->addAttribute("scenario", scenario, mapTagReplacements); + // string scenarioDir; + gameSettingsNode->addAttribute("scenarioDir", scenarioDir, + mapTagReplacements); + // string factionTypeNames[GameConstants::maxPlayers]; //faction + // names + for (int idx = 0; idx < GameConstants::maxPlayers; idx++) { + XmlNode *factionTypeNamesNode = + gameSettingsNode->addChild("factionTypeNames"); + factionTypeNamesNode->addAttribute("name", factionTypeNames[idx], + mapTagReplacements); + } + + // string networkPlayerNames[GameConstants::maxPlayers]; + for (int idx = 0; idx < GameConstants::maxPlayers; idx++) { + XmlNode *networkPlayerNamesNode = + gameSettingsNode->addChild("networkPlayerNames"); + networkPlayerNamesNode->addAttribute("name", networkPlayerNames[idx], + mapTagReplacements); + } + + for (int idx = 0; idx < GameConstants::maxPlayers; idx++) { + XmlNode *networkPlayerNamesNode = + gameSettingsNode->addChild("networkPlayerPlatform"); + networkPlayerNamesNode->addAttribute("name", networkPlayerPlatform[idx], + mapTagReplacements); + } + + // int networkPlayerStatuses[GameConstants::maxPlayers]; + for (int idx = 0; idx < GameConstants::maxPlayers; idx++) { + XmlNode *networkPlayerStatusesNode = + gameSettingsNode->addChild("networkPlayerStatuses"); + networkPlayerStatusesNode->addAttribute( + "status", intToStr(networkPlayerStatuses[idx]), mapTagReplacements); + } + + // int networkPlayerStatuses[GameConstants::maxPlayers]; + for (int idx = 0; idx < GameConstants::maxPlayers; idx++) { + XmlNode *networkPlayerStatusesNode = + gameSettingsNode->addChild("networkPlayerGameStatus"); + networkPlayerStatusesNode->addAttribute( + "game_status", intToStr(networkPlayerGameStatus[idx]), + mapTagReplacements); + } + + // string networkPlayerLanguages[GameConstants::maxPlayers]; + for (int idx = 0; idx < GameConstants::maxPlayers; idx++) { + XmlNode *networkPlayerLanguagesNode = + gameSettingsNode->addChild("networkPlayerLanguages"); + networkPlayerLanguagesNode->addAttribute( + "name", networkPlayerLanguages[idx], mapTagReplacements); + } + + // ControlType factionControls[GameConstants::maxPlayers]; + for (int idx = 0; idx < GameConstants::maxPlayers; idx++) { + XmlNode *factionControlsNode = + gameSettingsNode->addChild("factionControls"); + factionControlsNode->addAttribute( + "control", intToStr(factionControls[idx]), mapTagReplacements); + } + + // int resourceMultiplierIndex[GameConstants::maxPlayers]; + for (int idx = 0; idx < GameConstants::maxPlayers; idx++) { + XmlNode *resourceMultiplierIndexNode = + gameSettingsNode->addChild("resourceMultiplierIndex"); + resourceMultiplierIndexNode->addAttribute( + "multiplier", intToStr(resourceMultiplierIndex[idx]), + mapTagReplacements); + } + + // int thisFactionIndex; + gameSettingsNode->addAttribute( + "thisFactionIndex", intToStr(thisFactionIndex), mapTagReplacements); + // int factionCount; + gameSettingsNode->addAttribute("factionCount", intToStr(factionCount), + mapTagReplacements); + // int teams[GameConstants::maxPlayers]; + for (int idx = 0; idx < GameConstants::maxPlayers; idx++) { + XmlNode *teamsNode = gameSettingsNode->addChild("teams"); + teamsNode->addAttribute("team", intToStr(teams[idx]), mapTagReplacements); + } + + // int startLocationIndex[GameConstants::maxPlayers]; + for (int idx = 0; idx < GameConstants::maxPlayers; idx++) { + XmlNode *startLocationIndexNode = + gameSettingsNode->addChild("startLocationIndex"); + startLocationIndexNode->addAttribute( + "location", intToStr(startLocationIndex[idx]), mapTagReplacements); + } + + for (int idx = 0; idx < GameConstants::maxPlayers; idx++) { + XmlNode *networkPlayerUUIDNode = + gameSettingsNode->addChild("networkPlayerUUID"); + networkPlayerUUIDNode->addAttribute("value", networkPlayerUUID[idx], + mapTagReplacements); + } + + // int mapFilterIndex; + gameSettingsNode->addAttribute("mapFilterIndex", intToStr(mapFilter), + mapTagReplacements); + // + // + // bool defaultUnits; + gameSettingsNode->addAttribute("defaultUnits", intToStr(defaultUnits), + mapTagReplacements); + // bool defaultResources; + gameSettingsNode->addAttribute( + "defaultResources", intToStr(defaultResources), mapTagReplacements); + // bool defaultVictoryConditions; + gameSettingsNode->addAttribute("defaultVictoryConditions", + intToStr(defaultVictoryConditions), + mapTagReplacements); + // bool fogOfWar; + gameSettingsNode->addAttribute("fogOfWar", intToStr(fogOfWar), + mapTagReplacements); + // bool allowObservers; + gameSettingsNode->addAttribute("allowObservers", intToStr(allowObservers), + mapTagReplacements); + // bool enableObserverModeAtEndGame; + gameSettingsNode->addAttribute("enableObserverModeAtEndGame", + intToStr(enableObserverModeAtEndGame), + mapTagReplacements); + // bool enableServerControlledAI; + gameSettingsNode->addAttribute("enableServerControlledAI", + intToStr(enableServerControlledAI), + mapTagReplacements); + // int networkFramePeriod; + gameSettingsNode->addAttribute( + "networkFramePeriod", intToStr(networkFramePeriod), mapTagReplacements); + // bool networkPauseGameForLaggedClients; + gameSettingsNode->addAttribute("networkPauseGameForLaggedClients", + intToStr(networkPauseGameForLaggedClients), + mapTagReplacements); + // PathFinderType pathFinderType; + gameSettingsNode->addAttribute("pathFinderType", intToStr(pathFinderType), + mapTagReplacements); + // uint32 flagTypes1; + gameSettingsNode->addAttribute("flagTypes1", uIntToStr(flagTypes1), + mapTagReplacements); + // int32 mapCRC; + gameSettingsNode->addAttribute("mapCRC", uIntToStr(mapCRC), + mapTagReplacements); + // int32 tilesetCRC; + gameSettingsNode->addAttribute("tilesetCRC", uIntToStr(tilesetCRC), + mapTagReplacements); + // int32 techCRC; + gameSettingsNode->addAttribute("techCRC", uIntToStr(techCRC), + mapTagReplacements); + // vector > factionCRCList; + for (unsigned int i = 0; i < factionCRCList.size(); ++i) { + const pair &item = factionCRCList[i]; + + XmlNode *factionCRCListNode = + gameSettingsNode->addChild("factionCRCList"); + factionCRCListNode->addAttribute("key", item.first, mapTagReplacements); + factionCRCListNode->addAttribute("value", uIntToStr(item.second), + mapTagReplacements); + } + // int aiAcceptSwitchTeamPercentChance; + gameSettingsNode->addAttribute("aiAcceptSwitchTeamPercentChance", + intToStr(aiAcceptSwitchTeamPercentChance), + mapTagReplacements); + // int masterserver_admin; + gameSettingsNode->addAttribute( + "masterserver_admin", intToStr(masterserver_admin), mapTagReplacements); + + gameSettingsNode->addAttribute("masterserver_admin_factionIndex", + intToStr(masterserver_admin_factionIndex), + mapTagReplacements); + + gameSettingsNode->addAttribute("networkAllowNativeLanguageTechtree", + intToStr(networkAllowNativeLanguageTechtree), + mapTagReplacements); + } + + void loadGame(const XmlNode *rootNode) { + const XmlNode *gameSettingsNode = rootNode->getChild("GameSettings"); + + if (gameSettingsNode->hasAttribute("gameUUID") == true) { + gameUUID = gameSettingsNode->getAttribute("gameUUID")->getValue(); + } + + // string gameName; + if (gameSettingsNode->hasAttribute("gameName") == true) { + gameName = gameSettingsNode->getAttribute("gameName")->getValue(); + } else { + gameName = "oldSavegame"; + } + // string description; + description = gameSettingsNode->getAttribute("description")->getValue(); + // string map; + map = gameSettingsNode->getAttribute("map")->getValue(); + // string tileset; + tileset = gameSettingsNode->getAttribute("tileset")->getValue(); + // string tech; + tech = gameSettingsNode->getAttribute("tech")->getValue(); + // string scenario; + scenario = gameSettingsNode->getAttribute("scenario")->getValue(); + // string scenarioDir; + scenarioDir = gameSettingsNode->getAttribute("scenarioDir")->getValue(); + if (fileExists(scenarioDir) == false) { + scenarioDir = Config::findValidLocalFileFromPath(scenarioDir); + } + + // string factionTypeNames[GameConstants::maxPlayers]; //faction + // names + for (int idx = 0; idx < GameConstants::maxPlayers; idx++) { + const XmlNode *factionTypeNamesNode = + gameSettingsNode->getChild("factionTypeNames", idx); + factionTypeNames[idx] = + factionTypeNamesNode->getAttribute("name")->getValue(); + } + + // string networkPlayerNames[GameConstants::maxPlayers]; + for (int idx = 0; idx < GameConstants::maxPlayers; idx++) { + const XmlNode *networkPlayerNamesNode = + gameSettingsNode->getChild("networkPlayerNames", idx); + networkPlayerNames[idx] = + networkPlayerNamesNode->getAttribute("name")->getValue(); + } + + // int networkPlayerStatuses[GameConstants::maxPlayers]; + for (int idx = 0; idx < GameConstants::maxPlayers; idx++) { + const XmlNode *networkPlayerStatusesNode = + gameSettingsNode->getChild("networkPlayerStatuses", idx); + networkPlayerStatuses[idx] = + networkPlayerStatusesNode->getAttribute("status")->getIntValue(); + } + + // int networkPlayerStatuses[GameConstants::maxPlayers]; + for (int idx = 0; idx < GameConstants::maxPlayers; idx++) { + if (gameSettingsNode->hasChildAtIndex("networkPlayerGameStatus", idx) == + true) { + const XmlNode *networkPlayerGameStatusNode = + gameSettingsNode->getChild("networkPlayerGameStatus", idx); + networkPlayerGameStatus[idx] = + networkPlayerGameStatusNode->getAttribute("game_status") + ->getIntValue(); + } + } + + // string networkPlayerLanguages[GameConstants::maxPlayers]; + for (int idx = 0; idx < GameConstants::maxPlayers; idx++) { + const XmlNode *networkPlayerLanguagesNode = + gameSettingsNode->getChild("networkPlayerLanguages", idx); + networkPlayerLanguages[idx] = + networkPlayerLanguagesNode->getAttribute("name")->getValue(); + } + + // ControlType factionControls[GameConstants::maxPlayers]; + for (int idx = 0; idx < GameConstants::maxPlayers; idx++) { + const XmlNode *factionControlsNode = + gameSettingsNode->getChild("factionControls", idx); + factionControls[idx] = static_cast( + factionControlsNode->getAttribute("control")->getIntValue()); + } + + // int resourceMultiplierIndex[GameConstants::maxPlayers]; + for (int idx = 0; idx < GameConstants::maxPlayers; idx++) { + const XmlNode *resourceMultiplierIndexNode = + gameSettingsNode->getChild("resourceMultiplierIndex", idx); + resourceMultiplierIndex[idx] = + resourceMultiplierIndexNode->getAttribute("multiplier") + ->getIntValue(); + } + + for (int idx = 0; idx < GameConstants::maxPlayers; idx++) { + if (gameSettingsNode->hasChildAtIndex("networkPlayerUUID", idx) == true) { + const XmlNode *networkPlayerUUIDNode = + gameSettingsNode->getChild("networkPlayerUUID", idx); + networkPlayerUUID[idx] = + networkPlayerUUIDNode->getAttribute("value")->getValue(); + } + } + + // int thisFactionIndex; + thisFactionIndex = + gameSettingsNode->getAttribute("thisFactionIndex")->getIntValue(); + // int factionCount; + factionCount = + gameSettingsNode->getAttribute("factionCount")->getIntValue(); + // int teams[GameConstants::maxPlayers]; + for (int idx = 0; idx < GameConstants::maxPlayers; idx++) { + const XmlNode *teamsNode = gameSettingsNode->getChild("teams", idx); + teams[idx] = teamsNode->getAttribute("team")->getIntValue(); + } + + // int startLocationIndex[GameConstants::maxPlayers]; + for (int idx = 0; idx < GameConstants::maxPlayers; idx++) { + const XmlNode *startLocationIndexNode = + gameSettingsNode->getChild("startLocationIndex", idx); + startLocationIndex[idx] = + startLocationIndexNode->getAttribute("location")->getIntValue(); + } + + // int mapFilterIndex; + mapFilter = gameSettingsNode->getAttribute("mapFilterIndex")->getIntValue(); + // + // + // bool defaultUnits; + defaultUnits = + gameSettingsNode->getAttribute("defaultUnits")->getIntValue() != 0; + // bool defaultResources; + defaultResources = + gameSettingsNode->getAttribute("defaultResources")->getIntValue() != 0; + // bool defaultVictoryConditions; + defaultVictoryConditions = + gameSettingsNode->getAttribute("defaultVictoryConditions") + ->getIntValue() != 0; + // bool fogOfWar; + fogOfWar = gameSettingsNode->getAttribute("fogOfWar")->getIntValue() != 0; + // bool allowObservers; + allowObservers = + gameSettingsNode->getAttribute("allowObservers")->getIntValue() != 0; + // bool enableObserverModeAtEndGame; + enableObserverModeAtEndGame = + gameSettingsNode->getAttribute("enableObserverModeAtEndGame") + ->getIntValue() != 0; + // bool enableServerControlledAI; + enableServerControlledAI = + gameSettingsNode->getAttribute("enableServerControlledAI") + ->getIntValue() != 0; + // int networkFramePeriod; + networkFramePeriod = + gameSettingsNode->getAttribute("networkFramePeriod")->getIntValue(); + // bool networkPauseGameForLaggedClients; + networkPauseGameForLaggedClients = + gameSettingsNode->getAttribute("networkPauseGameForLaggedClients") + ->getIntValue() != 0; + // PathFinderType pathFinderType; + pathFinderType = static_cast( + gameSettingsNode->getAttribute("pathFinderType")->getIntValue()); + // uint32 flagTypes1; + flagTypes1 = gameSettingsNode->getAttribute("flagTypes1")->getUIntValue(); + // int32 mapCRC; + mapCRC = gameSettingsNode->getAttribute("mapCRC")->getUIntValue(); + // int32 tilesetCRC; + tilesetCRC = gameSettingsNode->getAttribute("tilesetCRC")->getUIntValue(); + // int32 techCRC; + techCRC = gameSettingsNode->getAttribute("techCRC")->getUIntValue(); + // vector > factionCRCList; + // for(unsigned int i = 0; i < factionCRCList.size(); ++i) { + // const pair &item = factionCRCList[i]; + // + // XmlNode *factionCRCListNode = + // gameSettingsNode->addChild("factionCRCList"); + // factionCRCListNode->addAttribute("key",item.first, + // mapTagReplacements); + // factionCRCListNode->addAttribute("value",intToStr(item.second), + // mapTagReplacements); + // } + // int aiAcceptSwitchTeamPercentChance; + aiAcceptSwitchTeamPercentChance = + gameSettingsNode->getAttribute("aiAcceptSwitchTeamPercentChance") + ->getIntValue(); + // int masterserver_admin; + masterserver_admin = + gameSettingsNode->getAttribute("masterserver_admin")->getIntValue(); + + if (gameSettingsNode->hasAttribute("masterserver_admin_factionIndex") == + true) { + masterserver_admin_factionIndex = + gameSettingsNode->getAttribute("masterserver_admin_factionIndex") + ->getIntValue(); + } + + if (gameSettingsNode->hasAttribute("networkAllowNativeLanguageTechtree") == + true) { + networkAllowNativeLanguageTechtree = + gameSettingsNode->getAttribute("networkAllowNativeLanguageTechtree") + ->getIntValue() != 0; + } + } }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/game/script_manager.cpp b/source/glest_game/game/script_manager.cpp index 461657278..37b061b8d 100644 --- a/source/glest_game/game/script_manager.cpp +++ b/source/glest_game/game/script_manager.cpp @@ -11,11 +11,11 @@ #include "script_manager.h" -#include "world.h" -#include "lang.h" -#include "game_camera.h" -#include "game.h" #include "config.h" +#include "game.h" +#include "game_camera.h" +#include "lang.h" +#include "world.h" #include "leak_dumper.h" @@ -23,4304 +23,5055 @@ using namespace Shared::Platform; using namespace Shared::Lua; using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { ScriptManagerMessage::ScriptManagerMessage() : text(""), header("") { - this->factionIndex = -1; - this->teamIndex = -1; - this->messageNotTranslated = true; + this->factionIndex = -1; + this->teamIndex = -1; + this->messageNotTranslated = true; } -ScriptManagerMessage::ScriptManagerMessage(const string &textIn, const string &headerIn, - int factionIndex,int teamIndex, bool messageNotTranslated) : - text(textIn), header(headerIn) { - this->factionIndex = factionIndex; - this->teamIndex = teamIndex; - this->messageNotTranslated = messageNotTranslated; +ScriptManagerMessage::ScriptManagerMessage(const string &textIn, + const string &headerIn, + int factionIndex, int teamIndex, + bool messageNotTranslated) + : text(textIn), header(headerIn) { + this->factionIndex = factionIndex; + this->teamIndex = teamIndex; + this->messageNotTranslated = messageNotTranslated; } void ScriptManagerMessage::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *scriptManagerMessageNode = rootNode->addChild("ScriptManagerMessage"); - - //string text; - scriptManagerMessageNode->addAttribute("text",text, mapTagReplacements); - //string header; - scriptManagerMessageNode->addAttribute("header",header, mapTagReplacements); - scriptManagerMessageNode->addAttribute("factionIndex",intToStr(factionIndex), mapTagReplacements); - scriptManagerMessageNode->addAttribute("teamIndex",intToStr(teamIndex), mapTagReplacements); - scriptManagerMessageNode->addAttribute("messageNotTranslated",intToStr(messageNotTranslated), mapTagReplacements); + std::map mapTagReplacements; + XmlNode *scriptManagerMessageNode = + rootNode->addChild("ScriptManagerMessage"); + + // string text; + scriptManagerMessageNode->addAttribute("text", text, mapTagReplacements); + // string header; + scriptManagerMessageNode->addAttribute("header", header, mapTagReplacements); + scriptManagerMessageNode->addAttribute("factionIndex", intToStr(factionIndex), + mapTagReplacements); + scriptManagerMessageNode->addAttribute("teamIndex", intToStr(teamIndex), + mapTagReplacements); + scriptManagerMessageNode->addAttribute("messageNotTranslated", + intToStr(messageNotTranslated), + mapTagReplacements); } void ScriptManagerMessage::loadGame(const XmlNode *rootNode) { - const XmlNode *scriptManagerMessageNode = rootNode; + const XmlNode *scriptManagerMessageNode = rootNode; - text = scriptManagerMessageNode->getAttribute("text")->getValue(); - header = scriptManagerMessageNode->getAttribute("header")->getValue(); - factionIndex = scriptManagerMessageNode->getAttribute("factionIndex")->getIntValue(); - teamIndex = scriptManagerMessageNode->getAttribute("teamIndex")->getIntValue(); + text = scriptManagerMessageNode->getAttribute("text")->getValue(); + header = scriptManagerMessageNode->getAttribute("header")->getValue(); + factionIndex = + scriptManagerMessageNode->getAttribute("factionIndex")->getIntValue(); + teamIndex = + scriptManagerMessageNode->getAttribute("teamIndex")->getIntValue(); - messageNotTranslated = true; - if(scriptManagerMessageNode->hasAttribute("messageNotTranslated") == true) { - messageNotTranslated = (scriptManagerMessageNode->getAttribute("messageNotTranslated")->getIntValue() != 0); - } + messageNotTranslated = true; + if (scriptManagerMessageNode->hasAttribute("messageNotTranslated") == true) { + messageNotTranslated = + (scriptManagerMessageNode->getAttribute("messageNotTranslated") + ->getIntValue() != 0); + } } // ===================================================== // class PlayerModifiers // ===================================================== -PlayerModifiers::PlayerModifiers(){ - winner = false; - aiEnabled = true; - consumeEnabled = true; +PlayerModifiers::PlayerModifiers() { + winner = false; + aiEnabled = true; + consumeEnabled = true; } void PlayerModifiers::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *playerModifiersNode = rootNode->addChild("PlayerModifiers"); + std::map mapTagReplacements; + XmlNode *playerModifiersNode = rootNode->addChild("PlayerModifiers"); - //bool winner; - playerModifiersNode->addAttribute("winner",intToStr(winner), mapTagReplacements); - //bool aiEnabled; - playerModifiersNode->addAttribute("aiEnabled",intToStr(aiEnabled), mapTagReplacements); - //bool consumeEnabled; - playerModifiersNode->addAttribute("consumeEnabled",intToStr(consumeEnabled), mapTagReplacements); + // bool winner; + playerModifiersNode->addAttribute("winner", intToStr(winner), + mapTagReplacements); + // bool aiEnabled; + playerModifiersNode->addAttribute("aiEnabled", intToStr(aiEnabled), + mapTagReplacements); + // bool consumeEnabled; + playerModifiersNode->addAttribute("consumeEnabled", intToStr(consumeEnabled), + mapTagReplacements); } void PlayerModifiers::loadGame(const XmlNode *rootNode) { - const XmlNode *playerModifiersNode = rootNode; + const XmlNode *playerModifiersNode = rootNode; - winner = playerModifiersNode->getAttribute("winner")->getIntValue() != 0; - aiEnabled = playerModifiersNode->getAttribute("aiEnabled")->getIntValue() != 0; - consumeEnabled = playerModifiersNode->getAttribute("consumeEnabled")->getIntValue() != 0; + winner = playerModifiersNode->getAttribute("winner")->getIntValue() != 0; + aiEnabled = + playerModifiersNode->getAttribute("aiEnabled")->getIntValue() != 0; + consumeEnabled = + playerModifiersNode->getAttribute("consumeEnabled")->getIntValue() != 0; } CellTriggerEvent::CellTriggerEvent() { - type = ctet_Unit; - sourceId = 0; - destId = 0; - //Vec2i destPos; + type = ctet_Unit; + sourceId = 0; + destId = 0; + // Vec2i destPos; - triggerCount = 0; + triggerCount = 0; } void CellTriggerEvent::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *cellTriggerEventNode = rootNode->addChild("CellTriggerEvent"); - -// CellTriggerEventType type; - cellTriggerEventNode->addAttribute("type",intToStr(type), mapTagReplacements); -// int sourceId; - cellTriggerEventNode->addAttribute("sourceId",intToStr(sourceId), mapTagReplacements); -// int destId; - cellTriggerEventNode->addAttribute("destId",intToStr(destId), mapTagReplacements); -// Vec2i destPos; - cellTriggerEventNode->addAttribute("destPos",destPos.getString(), mapTagReplacements); -// int triggerCount; - cellTriggerEventNode->addAttribute("triggerCount",intToStr(triggerCount), mapTagReplacements); - -// Vec2i destPosEnd; - cellTriggerEventNode->addAttribute("destPosEnd",destPosEnd.getString(), mapTagReplacements); + std::map mapTagReplacements; + XmlNode *cellTriggerEventNode = rootNode->addChild("CellTriggerEvent"); + + // CellTriggerEventType type; + cellTriggerEventNode->addAttribute("type", intToStr(type), + mapTagReplacements); + // int sourceId; + cellTriggerEventNode->addAttribute("sourceId", intToStr(sourceId), + mapTagReplacements); + // int destId; + cellTriggerEventNode->addAttribute("destId", intToStr(destId), + mapTagReplacements); + // Vec2i destPos; + cellTriggerEventNode->addAttribute("destPos", destPos.getString(), + mapTagReplacements); + // int triggerCount; + cellTriggerEventNode->addAttribute("triggerCount", intToStr(triggerCount), + mapTagReplacements); + + // Vec2i destPosEnd; + cellTriggerEventNode->addAttribute("destPosEnd", destPosEnd.getString(), + mapTagReplacements); } void CellTriggerEvent::loadGame(const XmlNode *rootNode) { - const XmlNode *cellTriggerEventNode = rootNode->getChild("CellTriggerEvent"); + const XmlNode *cellTriggerEventNode = rootNode->getChild("CellTriggerEvent"); - type = static_cast(cellTriggerEventNode->getAttribute("type")->getIntValue()); - sourceId = cellTriggerEventNode->getAttribute("sourceId")->getIntValue(); - destId = cellTriggerEventNode->getAttribute("destId")->getIntValue(); - destPos = Vec2i::strToVec2(cellTriggerEventNode->getAttribute("destPos")->getValue()); - triggerCount = cellTriggerEventNode->getAttribute("triggerCount")->getIntValue(); + type = static_cast( + cellTriggerEventNode->getAttribute("type")->getIntValue()); + sourceId = cellTriggerEventNode->getAttribute("sourceId")->getIntValue(); + destId = cellTriggerEventNode->getAttribute("destId")->getIntValue(); + destPos = Vec2i::strToVec2( + cellTriggerEventNode->getAttribute("destPos")->getValue()); + triggerCount = + cellTriggerEventNode->getAttribute("triggerCount")->getIntValue(); - if(cellTriggerEventNode->hasAttribute("destPosEnd") == true) { - destPosEnd = Vec2i::strToVec2(cellTriggerEventNode->getAttribute("destPosEnd")->getValue()); - } + if (cellTriggerEventNode->hasAttribute("destPosEnd") == true) { + destPosEnd = Vec2i::strToVec2( + cellTriggerEventNode->getAttribute("destPosEnd")->getValue()); + } } TimerTriggerEvent::TimerTriggerEvent() { - running = false; - startFrame = 0; - endFrame = 0; - triggerSecondsElapsed = 0; + running = false; + startFrame = 0; + endFrame = 0; + triggerSecondsElapsed = 0; } void TimerTriggerEvent::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *timerTriggerEventNode = rootNode->addChild("TimerTriggerEvent"); - -// bool running; - timerTriggerEventNode->addAttribute("running",intToStr(running), mapTagReplacements); -// //time_t startTime; -// //time_t endTime; -// int startFrame; - timerTriggerEventNode->addAttribute("startFrame",intToStr(startFrame), mapTagReplacements); -// int endFrame; - timerTriggerEventNode->addAttribute("endFrame",intToStr(endFrame), mapTagReplacements); - - if(triggerSecondsElapsed > 0) { - timerTriggerEventNode->addAttribute("triggerSecondsElapsed",intToStr(triggerSecondsElapsed), mapTagReplacements); - } + std::map mapTagReplacements; + XmlNode *timerTriggerEventNode = rootNode->addChild("TimerTriggerEvent"); + + // bool running; + timerTriggerEventNode->addAttribute("running", intToStr(running), + mapTagReplacements); + // //time_t startTime; + // //time_t endTime; + // int startFrame; + timerTriggerEventNode->addAttribute("startFrame", intToStr(startFrame), + mapTagReplacements); + // int endFrame; + timerTriggerEventNode->addAttribute("endFrame", intToStr(endFrame), + mapTagReplacements); + + if (triggerSecondsElapsed > 0) { + timerTriggerEventNode->addAttribute("triggerSecondsElapsed", + intToStr(triggerSecondsElapsed), + mapTagReplacements); + } } void TimerTriggerEvent::loadGame(const XmlNode *rootNode) { - const XmlNode *timerTriggerEventNode = rootNode->getChild("TimerTriggerEvent"); + const XmlNode *timerTriggerEventNode = + rootNode->getChild("TimerTriggerEvent"); - running = timerTriggerEventNode->getAttribute("running")->getIntValue() != 0; - startFrame = timerTriggerEventNode->getAttribute("startFrame")->getIntValue(); - endFrame = timerTriggerEventNode->getAttribute("endFrame")->getIntValue(); - if(timerTriggerEventNode->hasAttribute("triggerSecondsElapsed") == true) { - triggerSecondsElapsed = timerTriggerEventNode->getAttribute("triggerSecondsElapsed")->getIntValue(); - } + running = timerTriggerEventNode->getAttribute("running")->getIntValue() != 0; + startFrame = timerTriggerEventNode->getAttribute("startFrame")->getIntValue(); + endFrame = timerTriggerEventNode->getAttribute("endFrame")->getIntValue(); + if (timerTriggerEventNode->hasAttribute("triggerSecondsElapsed") == true) { + triggerSecondsElapsed = + timerTriggerEventNode->getAttribute("triggerSecondsElapsed") + ->getIntValue(); + } } // ===================================================== // class ScriptManager // ===================================================== -ScriptManager* ScriptManager::thisScriptManager = NULL; -const int ScriptManager::messageWrapCount = 35; -const int ScriptManager::displayTextWrapCount = 64; +ScriptManager *ScriptManager::thisScriptManager = NULL; +const int ScriptManager::messageWrapCount = 35; +const int ScriptManager::displayTextWrapCount = 64; ScriptManager::ScriptManager() { - world = NULL; - gameCamera = NULL; - lastCreatedUnitId = -1; - lastDeadUnitId = 0; - lastDeadUnitCauseOfDeath = 0; - lastDeadUnitKillerId = 0; - lastAttackedUnitId = 0; - lastAttackingUnitId = 0; - gameOver = false; - gameWon = false; - currentTimerTriggeredEventId = 0; - currentCellTriggeredEventId = 0; - currentCellTriggeredEventUnitId = 0; - currentEventId = 0; - inCellTriggerEvent = false; - rootNode = NULL; - currentCellTriggeredEventAreaEntryUnitId = 0; - currentCellTriggeredEventAreaExitUnitId = 0; - lastDayNightTriggerStatus = 0; - registeredDayNightEvent = false; - errorCount = 0; - - lastUnitTriggerEventUnitId = -1; - lastUnitTriggerEventType = utet_None; -} - -ScriptManager::~ScriptManager() { - -} - -void ScriptManager::init(World* world, GameCamera *gameCamera, const XmlNode *rootNode) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //printf("In [%s::%s Line: %d] rootNode [%p][%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,rootNode,(rootNode != NULL ? rootNode->getName().c_str() : "none")); - this->rootNode = rootNode; - const Scenario* scenario= world->getScenario(); - - this->world= world; - this->gameCamera= gameCamera; - - //set static instance - thisScriptManager= this; - - //printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - currentEventId = 1; - CellTriggerEventList.clear(); - TimerTriggerEventList.clear(); - - //printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //register functions - luaScript.registerFunction(networkShowMessageForFaction, "networkShowMessageForFaction"); - luaScript.registerFunction(networkShowMessageForTeam, "networkShowMessageForTeam"); - - luaScript.registerFunction(networkSetCameraPositionForFaction, "networkSetCameraPositionForFaction"); - luaScript.registerFunction(networkSetCameraPositionForTeam, "networkSetCameraPositionForTeam"); - - luaScript.registerFunction(showMessage, "showMessage"); - luaScript.registerFunction(setDisplayText, "setDisplayText"); - luaScript.registerFunction(addConsoleText, "addConsoleText"); - luaScript.registerFunction(addConsoleLangText, "addConsoleLangText"); - luaScript.registerFunction(DisplayFormattedText, "DisplayFormattedText"); - luaScript.registerFunction(DisplayFormattedText, "displayFormattedText"); - luaScript.registerFunction(DisplayFormattedLangText, "DisplayFormattedLangText"); - luaScript.registerFunction(DisplayFormattedLangText, "displayFormattedLangText"); - luaScript.registerFunction(clearDisplayText, "clearDisplayText"); - luaScript.registerFunction(setCameraPosition, "setCameraPosition"); - luaScript.registerFunction(shakeCamera, "shakeCamera"); - luaScript.registerFunction(shakeCameraOnUnit, "shakeCameraOnUnit"); - luaScript.registerFunction(createUnit, "createUnit"); - luaScript.registerFunction(createUnitNoSpacing, "createUnitNoSpacing"); - luaScript.registerFunction(setLockedUnitForFaction, "setLockedUnitForFaction"); - luaScript.registerFunction(destroyUnit, "destroyUnit"); - luaScript.registerFunction(giveKills, "giveKills"); - luaScript.registerFunction(morphToUnit, "morphToUnit"); - luaScript.registerFunction(moveToUnit, "moveToUnit"); - - luaScript.registerFunction(playStaticSound, "playStaticSound"); - luaScript.registerFunction(playStreamingSound, "playStreamingSound"); - luaScript.registerFunction(stopStreamingSound, "stopStreamingSound"); - luaScript.registerFunction(stopAllSound, "stopAllSound"); - luaScript.registerFunction(togglePauseGame, "togglePauseGame"); - - luaScript.registerFunction(playStaticVideo, "playStaticVideo"); - //luaScript.registerFunction(playStreamingVideo, "playStreamingVideo"); - //luaScript.registerFunction(stopStreamingVideo, "stopStreamingVideo"); - luaScript.registerFunction(stopAllVideo, "stopAllVideo"); - - luaScript.registerFunction(giveResource, "giveResource"); - luaScript.registerFunction(givePositionCommand, "givePositionCommand"); - luaScript.registerFunction(giveProductionCommand, "giveProductionCommand"); - luaScript.registerFunction(giveAttackCommand, "giveAttackCommand"); - luaScript.registerFunction(giveUpgradeCommand, "giveUpgradeCommand"); - luaScript.registerFunction(giveAttackStoppedCommand, "giveAttackStoppedCommand"); - luaScript.registerFunction(disableAi, "disableAi"); - luaScript.registerFunction(enableAi, "enableAi"); - luaScript.registerFunction(getAiEnabled, "getAiEnabled"); - luaScript.registerFunction(disableConsume, "disableConsume"); - luaScript.registerFunction(enableConsume, "enableConsume"); - luaScript.registerFunction(getConsumeEnabled, "getConsumeEnabled"); - luaScript.registerFunction(setPlayerAsWinner, "setPlayerAsWinner"); - luaScript.registerFunction(endGame, "endGame"); - - luaScript.registerFunction(startPerformanceTimer, "startPerformanceTimer"); - luaScript.registerFunction(endPerformanceTimer, "endPerformanceTimer"); - luaScript.registerFunction(getPerformanceTimerResults, "getPerformanceTimerResults"); - - luaScript.registerFunction(registerCellTriggerEventForUnitToUnit, "registerCellTriggerEventForUnitToUnit"); - luaScript.registerFunction(registerCellTriggerEventForUnitToLocation, "registerCellTriggerEventForUnitToLocation"); - luaScript.registerFunction(registerCellTriggerEventForFactionToUnit, "registerCellTriggerEventForFactionToUnit"); - luaScript.registerFunction(registerCellTriggerEventForFactionToLocation, "registerCellTriggerEventForFactionToLocation"); - - luaScript.registerFunction(registerCellAreaTriggerEventForUnitToLocation, "registerCellAreaTriggerEventForUnitToLocation"); - luaScript.registerFunction(registerCellAreaTriggerEventForFactionToLocation, "registerCellAreaTriggerEventForFactionToLocation"); - luaScript.registerFunction(registerCellAreaTriggerEvent, "registerCellAreaTriggerEvent"); - - luaScript.registerFunction(getCellTriggerEventCount, "getCellTriggerEventCount"); - luaScript.registerFunction(unregisterCellTriggerEvent, "unregisterCellTriggerEvent"); - luaScript.registerFunction(startTimerEvent, "startTimerEvent"); - luaScript.registerFunction(startEfficientTimerEvent, "startEfficientTimerEvent"); - luaScript.registerFunction(resetTimerEvent, "resetTimerEvent"); - luaScript.registerFunction(stopTimerEvent, "stopTimerEvent"); - luaScript.registerFunction(getTimerEventSecondsElapsed, "timerEventSecondsElapsed"); - luaScript.registerFunction(getCellTriggeredEventId, "triggeredCellEventId"); - luaScript.registerFunction(getTimerTriggeredEventId, "triggeredTimerEventId"); - - luaScript.registerFunction(getCellTriggeredEventAreaEntryUnitId, "triggeredEventAreaEntryUnitId"); - luaScript.registerFunction(getCellTriggeredEventAreaExitUnitId, "triggeredEventAreaExitUnitId"); - - luaScript.registerFunction(getCellTriggeredEventUnitId, "triggeredCellEventUnitId"); - - luaScript.registerFunction(setRandomGenInit, "setRandomGenInit"); - luaScript.registerFunction(getRandomGen, "getRandomGen"); - luaScript.registerFunction(getWorldFrameCount, "getWorldFrameCount"); - - luaScript.registerFunction(getStartLocation, "startLocation"); - luaScript.registerFunction(getIsUnitAlive, "isUnitAlive"); - luaScript.registerFunction(getUnitPosition, "unitPosition"); - luaScript.registerFunction(setUnitPosition, "setUnitPosition"); - - luaScript.registerFunction(addCellMarker, "addCellMarker"); - luaScript.registerFunction(removeCellMarker, "removeCellMarker"); - luaScript.registerFunction(showMarker, "showMarker"); - - luaScript.registerFunction(getUnitFaction, "unitFaction"); - luaScript.registerFunction(getUnitName, "unitName"); - luaScript.registerFunction(getResourceAmount, "resourceAmount"); - - luaScript.registerFunction(getLastCreatedUnitName, "lastCreatedUnitName"); - luaScript.registerFunction(getLastCreatedUnitId, "lastCreatedUnit"); - - luaScript.registerFunction(getLastDeadUnitName, "lastDeadUnitName"); - luaScript.registerFunction(getLastDeadUnitId, "lastDeadUnit"); - luaScript.registerFunction(getLastDeadUnitCauseOfDeath, "lastDeadUnitCauseOfDeath"); - luaScript.registerFunction(getLastDeadUnitKillerName, "lastDeadUnitKillerName"); - luaScript.registerFunction(getLastDeadUnitKillerId, "lastDeadUnitKiller"); - - luaScript.registerFunction(getLastAttackedUnitName, "lastAttackedUnitName"); - luaScript.registerFunction(getLastAttackedUnitId, "lastAttackedUnit"); - - luaScript.registerFunction(getLastAttackingUnitName, "lastAttackingUnitName"); - luaScript.registerFunction(getLastAttackingUnitId, "lastAttackingUnit"); - - luaScript.registerFunction(getUnitCount, "unitCount"); - luaScript.registerFunction(getUnitCountOfType, "unitCountOfType"); - - luaScript.registerFunction(getIsGameOver, "isGameOver"); - luaScript.registerFunction(getGameWon, "gameWon"); - - luaScript.registerFunction(getSystemMacroValue, "getSystemMacroValue"); - luaScript.registerFunction(scenarioDir, "scenarioDir"); - luaScript.registerFunction(getPlayerName, "getPlayerName"); - luaScript.registerFunction(getPlayerName, "playerName"); - - luaScript.registerFunction(loadScenario, "loadScenario"); - - luaScript.registerFunction(getUnitsForFaction, "getUnitsForFaction"); - luaScript.registerFunction(getUnitCurrentField, "getUnitCurrentField"); - - luaScript.registerFunction(isFreeCellsOrHasUnit, "isFreeCellsOrHasUnit"); - luaScript.registerFunction(isFreeCells, "isFreeCells"); - - luaScript.registerFunction(getHumanFactionId, "humanFaction"); - - luaScript.registerFunction(highlightUnit, "highlightUnit"); - luaScript.registerFunction(unhighlightUnit, "unhighlightUnit"); - - luaScript.registerFunction(giveStopCommand, "giveStopCommand"); - luaScript.registerFunction(selectUnit, "selectUnit"); - luaScript.registerFunction(unselectUnit, "unselectUnit"); - luaScript.registerFunction(addUnitToGroupSelection, "addUnitToGroupSelection"); - luaScript.registerFunction(recallGroupSelection, "recallGroupSelection"); - luaScript.registerFunction(removeUnitFromGroupSelection, "removeUnitFromGroupSelection"); - luaScript.registerFunction(setAttackWarningsEnabled, "setAttackWarningsEnabled"); - luaScript.registerFunction(getAttackWarningsEnabled, "getAttackWarningsEnabled"); - - luaScript.registerFunction(getIsDayTime, "getIsDayTime"); - luaScript.registerFunction(getIsNightTime, "getIsNightTime"); - luaScript.registerFunction(getTimeOfDay, "getTimeOfDay"); - luaScript.registerFunction(registerDayNightEvent, "registerDayNightEvent"); - luaScript.registerFunction(unregisterDayNightEvent, "unregisterDayNightEvent"); - - luaScript.registerFunction(registerUnitTriggerEvent, "registerUnitTriggerEvent"); - luaScript.registerFunction(unregisterUnitTriggerEvent, "unregisterUnitTriggerEvent"); - luaScript.registerFunction(getLastUnitTriggerEventUnitId, "lastUnitTriggerEventUnit"); - luaScript.registerFunction(getLastUnitTriggerEventType, "lastUnitTriggerEventType"); - luaScript.registerFunction(getUnitProperty, "getUnitProperty"); - luaScript.registerFunction(getUnitPropertyName, "getUnitPropertyName"); - luaScript.registerFunction(disableSpeedChange, "disableSpeedChange"); - luaScript.registerFunction(enableSpeedChange, "enableSpeedChange"); - luaScript.registerFunction(getSpeedChangeEnabled, "getSpeedChangeEnabled"); - - luaScript.registerFunction(storeSaveGameData, "storeSaveGameData"); - luaScript.registerFunction(loadSaveGameData, "loadSaveGameData"); - - luaScript.registerFunction(getFactionPlayerType, "getFactionPlayerType"); - - //load code - for(int i= 0; igetScriptCount(); ++i){ - const Script* script= scenario->getScript(i); - luaScript.loadCode("function " + script->getName() + "()" + script->getCode() + "end\n", script->getName()); - } - - - //!!! -// string data_path= getGameReadWritePath(GameConstants::path_data_CacheLookupKey); -// if(data_path != ""){ -// endPathWithSlash(data_path); -// } -// string sandboxScriptFilename = data_path + "data/core/scripts/sandbox.lua"; -// string sandboxLuaCode = getFileTextContents(sandboxScriptFilename); -// -// //luaScript.loadCode(sandboxLuaCode + "\n", "megaglest_lua_sandbox"); -// luaScript.setSandboxWrapperFunctionName("runsandboxed"); -// luaScript.setSandboxCode(sandboxLuaCode); -// luaScript.runCode(sandboxLuaCode); - -// // Setup the lua security sandbox here -// luaScript.beginCall("megaglest_lua_sandbox"); -// luaScript.endCall(); - - //setup message box - messageBox.init( Lang::getInstance().getString("Ok") ); - messageBox.setEnabled(false); - //messageBox.setAutoWordWrap(false); - - //last created unit - lastCreatedUnitId= -1; - lastDeadUnitName = ""; - lastDeadUnitId= -1; - lastDeadUnitCauseOfDeath = ucodNone; - lastDeadUnitKillerName = ""; - lastDeadUnitKillerId= -1; - - lastAttackedUnitName = ""; - lastAttackedUnitId = -1; - lastAttackingUnitName = ""; - lastAttackingUnitId = -1; - - gameOver= false; - gameWon = false; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - try { - // Setup global functions and vars here - luaScript.beginCall("global"); - luaScript.endCall(); - - //call startup function - if(this->rootNode == NULL) { - luaScript.beginCall("startup"); - luaScript.endCall(); - } - else { - loadGame(this->rootNode); - this->rootNode = NULL; - - if(LuaScript::getDebugModeEnabled() == true) printf("Calling onLoad luaSavedGameData.size() = %d\n",(int)luaSavedGameData.size()); - - luaScript.beginCall("onLoad"); - luaScript.endCall(); - } - } - catch(const megaglest_runtime_error &ex) { - //string sErrBuf = ""; - //if(ex.wantStackTrace() == true) { - char szErrBuf[8096]=""; - //snprintf(szErrBuf,8096,"In [%s::%s %d]",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - string sErrBuf = string(szErrBuf) + string("The game may no longer be stable!\n\n\t [") + string(ex.what()) + string("]\n"); - //} - SystemFlags::OutputDebug(SystemFlags::debugError,sErrBuf.c_str()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,sErrBuf.c_str()); - - thisScriptManager->addMessageToQueue(ScriptManagerMessage(sErrBuf.c_str(), "error",-1,-1,true)); - thisScriptManager->onMessageBoxOk(false); - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); -} - -// ========================== events =============================================== + world = NULL; + gameCamera = NULL; + lastCreatedUnitId = -1; + lastDeadUnitId = 0; + lastDeadUnitCauseOfDeath = 0; + lastDeadUnitKillerId = 0; + lastAttackedUnitId = 0; + lastAttackingUnitId = 0; + gameOver = false; + gameWon = false; + currentTimerTriggeredEventId = 0; + currentCellTriggeredEventId = 0; + currentCellTriggeredEventUnitId = 0; + currentEventId = 0; + inCellTriggerEvent = false; + rootNode = NULL; + currentCellTriggeredEventAreaEntryUnitId = 0; + currentCellTriggeredEventAreaExitUnitId = 0; + lastDayNightTriggerStatus = 0; + registeredDayNightEvent = false; + errorCount = 0; + + lastUnitTriggerEventUnitId = -1; + lastUnitTriggerEventType = utet_None; +} + +ScriptManager::~ScriptManager() {} + +void ScriptManager::init(World *world, GameCamera *gameCamera, + const XmlNode *rootNode) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // printf("In [%s::%s Line: %d] rootNode + // [%p][%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,rootNode,(rootNode + // != NULL ? rootNode->getName().c_str() : "none")); + this->rootNode = rootNode; + const Scenario *scenario = world->getScenario(); + + this->world = world; + this->gameCamera = gameCamera; + + // set static instance + thisScriptManager = this; + + // printf("In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + currentEventId = 1; + CellTriggerEventList.clear(); + TimerTriggerEventList.clear(); + + // printf("In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + // register functions + luaScript.registerFunction(networkShowMessageForFaction, + "networkShowMessageForFaction"); + luaScript.registerFunction(networkShowMessageForTeam, + "networkShowMessageForTeam"); + + luaScript.registerFunction(networkSetCameraPositionForFaction, + "networkSetCameraPositionForFaction"); + luaScript.registerFunction(networkSetCameraPositionForTeam, + "networkSetCameraPositionForTeam"); + + luaScript.registerFunction(showMessage, "showMessage"); + luaScript.registerFunction(setDisplayText, "setDisplayText"); + luaScript.registerFunction(addConsoleText, "addConsoleText"); + luaScript.registerFunction(addConsoleLangText, "addConsoleLangText"); + luaScript.registerFunction(DisplayFormattedText, "DisplayFormattedText"); + luaScript.registerFunction(DisplayFormattedText, "displayFormattedText"); + luaScript.registerFunction(DisplayFormattedLangText, + "DisplayFormattedLangText"); + luaScript.registerFunction(DisplayFormattedLangText, + "displayFormattedLangText"); + luaScript.registerFunction(clearDisplayText, "clearDisplayText"); + luaScript.registerFunction(setCameraPosition, "setCameraPosition"); + luaScript.registerFunction(shakeCamera, "shakeCamera"); + luaScript.registerFunction(shakeCameraOnUnit, "shakeCameraOnUnit"); + luaScript.registerFunction(createUnit, "createUnit"); + luaScript.registerFunction(createUnitNoSpacing, "createUnitNoSpacing"); + luaScript.registerFunction(setLockedUnitForFaction, + "setLockedUnitForFaction"); + luaScript.registerFunction(destroyUnit, "destroyUnit"); + luaScript.registerFunction(giveKills, "giveKills"); + luaScript.registerFunction(morphToUnit, "morphToUnit"); + luaScript.registerFunction(moveToUnit, "moveToUnit"); + + luaScript.registerFunction(playStaticSound, "playStaticSound"); + luaScript.registerFunction(playStreamingSound, "playStreamingSound"); + luaScript.registerFunction(stopStreamingSound, "stopStreamingSound"); + luaScript.registerFunction(stopAllSound, "stopAllSound"); + luaScript.registerFunction(togglePauseGame, "togglePauseGame"); + + luaScript.registerFunction(playStaticVideo, "playStaticVideo"); + // luaScript.registerFunction(playStreamingVideo, "playStreamingVideo"); + // luaScript.registerFunction(stopStreamingVideo, "stopStreamingVideo"); + luaScript.registerFunction(stopAllVideo, "stopAllVideo"); + + luaScript.registerFunction(giveResource, "giveResource"); + luaScript.registerFunction(givePositionCommand, "givePositionCommand"); + luaScript.registerFunction(giveProductionCommand, "giveProductionCommand"); + luaScript.registerFunction(giveAttackCommand, "giveAttackCommand"); + luaScript.registerFunction(giveUpgradeCommand, "giveUpgradeCommand"); + luaScript.registerFunction(giveAttackStoppedCommand, + "giveAttackStoppedCommand"); + luaScript.registerFunction(disableAi, "disableAi"); + luaScript.registerFunction(enableAi, "enableAi"); + luaScript.registerFunction(getAiEnabled, "getAiEnabled"); + luaScript.registerFunction(disableConsume, "disableConsume"); + luaScript.registerFunction(enableConsume, "enableConsume"); + luaScript.registerFunction(getConsumeEnabled, "getConsumeEnabled"); + luaScript.registerFunction(setPlayerAsWinner, "setPlayerAsWinner"); + luaScript.registerFunction(endGame, "endGame"); + + luaScript.registerFunction(startPerformanceTimer, "startPerformanceTimer"); + luaScript.registerFunction(endPerformanceTimer, "endPerformanceTimer"); + luaScript.registerFunction(getPerformanceTimerResults, + "getPerformanceTimerResults"); + + luaScript.registerFunction(registerCellTriggerEventForUnitToUnit, + "registerCellTriggerEventForUnitToUnit"); + luaScript.registerFunction(registerCellTriggerEventForUnitToLocation, + "registerCellTriggerEventForUnitToLocation"); + luaScript.registerFunction(registerCellTriggerEventForFactionToUnit, + "registerCellTriggerEventForFactionToUnit"); + luaScript.registerFunction(registerCellTriggerEventForFactionToLocation, + "registerCellTriggerEventForFactionToLocation"); + + luaScript.registerFunction(registerCellAreaTriggerEventForUnitToLocation, + "registerCellAreaTriggerEventForUnitToLocation"); + luaScript.registerFunction( + registerCellAreaTriggerEventForFactionToLocation, + "registerCellAreaTriggerEventForFactionToLocation"); + luaScript.registerFunction(registerCellAreaTriggerEvent, + "registerCellAreaTriggerEvent"); + + luaScript.registerFunction(getCellTriggerEventCount, + "getCellTriggerEventCount"); + luaScript.registerFunction(unregisterCellTriggerEvent, + "unregisterCellTriggerEvent"); + luaScript.registerFunction(startTimerEvent, "startTimerEvent"); + luaScript.registerFunction(startEfficientTimerEvent, + "startEfficientTimerEvent"); + luaScript.registerFunction(resetTimerEvent, "resetTimerEvent"); + luaScript.registerFunction(stopTimerEvent, "stopTimerEvent"); + luaScript.registerFunction(getTimerEventSecondsElapsed, + "timerEventSecondsElapsed"); + luaScript.registerFunction(getCellTriggeredEventId, "triggeredCellEventId"); + luaScript.registerFunction(getTimerTriggeredEventId, "triggeredTimerEventId"); + + luaScript.registerFunction(getCellTriggeredEventAreaEntryUnitId, + "triggeredEventAreaEntryUnitId"); + luaScript.registerFunction(getCellTriggeredEventAreaExitUnitId, + "triggeredEventAreaExitUnitId"); + + luaScript.registerFunction(getCellTriggeredEventUnitId, + "triggeredCellEventUnitId"); + + luaScript.registerFunction(setRandomGenInit, "setRandomGenInit"); + luaScript.registerFunction(getRandomGen, "getRandomGen"); + luaScript.registerFunction(getWorldFrameCount, "getWorldFrameCount"); + + luaScript.registerFunction(getStartLocation, "startLocation"); + luaScript.registerFunction(getIsUnitAlive, "isUnitAlive"); + luaScript.registerFunction(getUnitPosition, "unitPosition"); + luaScript.registerFunction(setUnitPosition, "setUnitPosition"); + + luaScript.registerFunction(addCellMarker, "addCellMarker"); + luaScript.registerFunction(removeCellMarker, "removeCellMarker"); + luaScript.registerFunction(showMarker, "showMarker"); + + luaScript.registerFunction(getUnitFaction, "unitFaction"); + luaScript.registerFunction(getUnitName, "unitName"); + luaScript.registerFunction(getResourceAmount, "resourceAmount"); + + luaScript.registerFunction(getLastCreatedUnitName, "lastCreatedUnitName"); + luaScript.registerFunction(getLastCreatedUnitId, "lastCreatedUnit"); + + luaScript.registerFunction(getLastDeadUnitName, "lastDeadUnitName"); + luaScript.registerFunction(getLastDeadUnitId, "lastDeadUnit"); + luaScript.registerFunction(getLastDeadUnitCauseOfDeath, + "lastDeadUnitCauseOfDeath"); + luaScript.registerFunction(getLastDeadUnitKillerName, + "lastDeadUnitKillerName"); + luaScript.registerFunction(getLastDeadUnitKillerId, "lastDeadUnitKiller"); + + luaScript.registerFunction(getLastAttackedUnitName, "lastAttackedUnitName"); + luaScript.registerFunction(getLastAttackedUnitId, "lastAttackedUnit"); + + luaScript.registerFunction(getLastAttackingUnitName, "lastAttackingUnitName"); + luaScript.registerFunction(getLastAttackingUnitId, "lastAttackingUnit"); + + luaScript.registerFunction(getUnitCount, "unitCount"); + luaScript.registerFunction(getUnitCountOfType, "unitCountOfType"); + + luaScript.registerFunction(getIsGameOver, "isGameOver"); + luaScript.registerFunction(getGameWon, "gameWon"); + + luaScript.registerFunction(getSystemMacroValue, "getSystemMacroValue"); + luaScript.registerFunction(scenarioDir, "scenarioDir"); + luaScript.registerFunction(getPlayerName, "getPlayerName"); + luaScript.registerFunction(getPlayerName, "playerName"); + + luaScript.registerFunction(loadScenario, "loadScenario"); + + luaScript.registerFunction(getUnitsForFaction, "getUnitsForFaction"); + luaScript.registerFunction(getUnitCurrentField, "getUnitCurrentField"); + + luaScript.registerFunction(isFreeCellsOrHasUnit, "isFreeCellsOrHasUnit"); + luaScript.registerFunction(isFreeCells, "isFreeCells"); + + luaScript.registerFunction(getHumanFactionId, "humanFaction"); + + luaScript.registerFunction(highlightUnit, "highlightUnit"); + luaScript.registerFunction(unhighlightUnit, "unhighlightUnit"); + + luaScript.registerFunction(giveStopCommand, "giveStopCommand"); + luaScript.registerFunction(selectUnit, "selectUnit"); + luaScript.registerFunction(unselectUnit, "unselectUnit"); + luaScript.registerFunction(addUnitToGroupSelection, + "addUnitToGroupSelection"); + luaScript.registerFunction(recallGroupSelection, "recallGroupSelection"); + luaScript.registerFunction(removeUnitFromGroupSelection, + "removeUnitFromGroupSelection"); + luaScript.registerFunction(setAttackWarningsEnabled, + "setAttackWarningsEnabled"); + luaScript.registerFunction(getAttackWarningsEnabled, + "getAttackWarningsEnabled"); + + luaScript.registerFunction(getIsDayTime, "getIsDayTime"); + luaScript.registerFunction(getIsNightTime, "getIsNightTime"); + luaScript.registerFunction(getTimeOfDay, "getTimeOfDay"); + luaScript.registerFunction(registerDayNightEvent, "registerDayNightEvent"); + luaScript.registerFunction(unregisterDayNightEvent, + "unregisterDayNightEvent"); + + luaScript.registerFunction(registerUnitTriggerEvent, + "registerUnitTriggerEvent"); + luaScript.registerFunction(unregisterUnitTriggerEvent, + "unregisterUnitTriggerEvent"); + luaScript.registerFunction(getLastUnitTriggerEventUnitId, + "lastUnitTriggerEventUnit"); + luaScript.registerFunction(getLastUnitTriggerEventType, + "lastUnitTriggerEventType"); + luaScript.registerFunction(getUnitProperty, "getUnitProperty"); + luaScript.registerFunction(getUnitPropertyName, "getUnitPropertyName"); + luaScript.registerFunction(disableSpeedChange, "disableSpeedChange"); + luaScript.registerFunction(enableSpeedChange, "enableSpeedChange"); + luaScript.registerFunction(getSpeedChangeEnabled, "getSpeedChangeEnabled"); + + luaScript.registerFunction(storeSaveGameData, "storeSaveGameData"); + luaScript.registerFunction(loadSaveGameData, "loadSaveGameData"); + + luaScript.registerFunction(getFactionPlayerType, "getFactionPlayerType"); + + // load code + for (int i = 0; i < scenario->getScriptCount(); ++i) { + const Script *script = scenario->getScript(i); + luaScript.loadCode("function " + script->getName() + "()" + + script->getCode() + "end\n", + script->getName()); + } + + //!!! + // string data_path= + // getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + // if(data_path + //!= ""){ endPathWithSlash(data_path); + // } + // string sandboxScriptFilename = data_path + + //"data/core/scripts/sandbox.lua"; string sandboxLuaCode = + // getFileTextContents(sandboxScriptFilename); + // + // //luaScript.loadCode(sandboxLuaCode + "\n", "megaglest_lua_sandbox"); + // luaScript.setSandboxWrapperFunctionName("runsandboxed"); + // luaScript.setSandboxCode(sandboxLuaCode); + // luaScript.runCode(sandboxLuaCode); + + // // Setup the lua security sandbox here + // luaScript.beginCall("megaglest_lua_sandbox"); + // luaScript.endCall(); + + // setup message box + messageBox.init(Lang::getInstance().getString("Ok")); + messageBox.setEnabled(false); + // messageBox.setAutoWordWrap(false); + + // last created unit + lastCreatedUnitId = -1; + lastDeadUnitName = ""; + lastDeadUnitId = -1; + lastDeadUnitCauseOfDeath = ucodNone; + lastDeadUnitKillerName = ""; + lastDeadUnitKillerId = -1; + + lastAttackedUnitName = ""; + lastAttackedUnitId = -1; + lastAttackingUnitName = ""; + lastAttackingUnitId = -1; + + gameOver = false; + gameWon = false; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + try { + // Setup global functions and vars here + luaScript.beginCall("global"); + luaScript.endCall(); + + // call startup function + if (this->rootNode == NULL) { + luaScript.beginCall("startup"); + luaScript.endCall(); + } else { + loadGame(this->rootNode); + this->rootNode = NULL; + + if (LuaScript::getDebugModeEnabled() == true) + printf("Calling onLoad luaSavedGameData.size() = %d\n", + (int)luaSavedGameData.size()); + + luaScript.beginCall("onLoad"); + luaScript.endCall(); + } + } catch (const megaglest_runtime_error &ex) { + // string sErrBuf = ""; + // if(ex.wantStackTrace() == true) { + char szErrBuf[8096] = ""; + // snprintf(szErrBuf,8096,"In [%s::%s + // %d]",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + string sErrBuf = string(szErrBuf) + + string("The game may no longer be stable!\n\n\t [") + + string(ex.what()) + string("]\n"); + //} + SystemFlags::OutputDebug(SystemFlags::debugError, sErrBuf.c_str()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, sErrBuf.c_str()); + + thisScriptManager->addMessageToQueue( + ScriptManagerMessage(sErrBuf.c_str(), "error", -1, -1, true)); + thisScriptManager->onMessageBoxOk(false); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); +} + +// ========================== events +// =============================================== void ScriptManager::onMessageBoxOk(bool popFront) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - Lang &lang= Lang::getInstance(); - - for(int index = 0; messageQueue.empty() == false; ++index) { - //printf("i = %d messageQueue.size() = %d popFront = %d\n",i,messageQueue.size(),popFront); - if(popFront == true) { - messageQueue.pop_front(); - } - if(messageQueue.empty() == false) { -// printf("onMessageBoxOk [%s] factionIndex = %d [%d] teamIndex = %d [%d][%d]\n", -// wrapString(lang.getScenarioString(messageQueue.front().getText()), messageWrapCount).c_str(), -// messageQueue.front().getFactionIndex(), this->world->getThisFactionIndex(), -// messageQueue.front().getTeamIndex(),this->world->getThisTeamIndex(),this->world->getThisFaction()->getTeam()); - - if((messageQueue.front().getFactionIndex() < 0 && messageQueue.front().getTeamIndex() < 0) || - messageQueue.front().getFactionIndex() == this->world->getThisFactionIndex() || - messageQueue.front().getTeamIndex() == this->world->getThisTeamIndex()) { - - messageBox.setEnabled(true); - - string msgText = messageQueue.front().getText(); - string msgHeader = messageQueue.front().getHeader(); - if(messageQueue.front().getMessageNotTranslated() == false) { - - msgText = lang.getScenarioString(messageQueue.front().getText()); - msgHeader = lang.getScenarioString(messageQueue.front().getHeader()); - } - messageBox.setText(msgText); - messageBox.setHeader(msgHeader); - break; - } - popFront = true; - } - } -} - -void ScriptManager::onResourceHarvested(){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(this->rootNode == NULL) { - luaScript.beginCall("resourceHarvested"); - luaScript.endCall(); - } -} - -void ScriptManager::onUnitCreated(const Unit* unit){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(this->rootNode == NULL) { - lastCreatedUnitName= unit->getType()->getName(false); - lastCreatedUnitId= unit->getId(); - luaScript.beginCall("unitCreated"); - luaScript.endCall(); - luaScript.beginCall("unitCreatedOfType_"+unit->getType()->getName()); - luaScript.endCall(); - } -} - -void ScriptManager::onUnitDied(const Unit* unit){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(this->rootNode == NULL) { - if(unit->getLastAttackerUnitId() >= 0) { - Unit *killer = world->findUnitById(unit->getLastAttackerUnitId()); - - if(killer != NULL) { - lastAttackingUnitName= killer->getType()->getName(false); - lastAttackingUnitId= killer->getId(); - - lastDeadUnitKillerName= killer->getType()->getName(false); - lastDeadUnitKillerId= killer->getId(); - } - else { - lastDeadUnitKillerName= ""; - lastDeadUnitKillerId= -1; - } - } - - lastAttackedUnitName= unit->getType()->getName(false); - lastAttackedUnitId= unit->getId(); - - lastDeadUnitName= unit->getType()->getName(false); - lastDeadUnitId= unit->getId(); - lastDeadUnitCauseOfDeath = unit->getCauseOfDeath(); - - luaScript.beginCall("unitDied"); - luaScript.endCall(); - } -} - -void ScriptManager::onUnitAttacked(const Unit* unit) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(this->rootNode == NULL) { - lastAttackedUnitName= unit->getType()->getName(false); - lastAttackedUnitId= unit->getId(); - luaScript.beginCall("unitAttacked"); - luaScript.endCall(); - } -} - -void ScriptManager::onUnitAttacking(const Unit* unit) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(this->rootNode == NULL) { - lastAttackingUnitName= unit->getType()->getName(false); - lastAttackingUnitId= unit->getId(); - luaScript.beginCall("unitAttacking"); - luaScript.endCall(); - } + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + Lang &lang = Lang::getInstance(); + + for (int index = 0; messageQueue.empty() == false; ++index) { + // printf("i = %d messageQueue.size() = %d popFront = + // %d\n",i,messageQueue.size(),popFront); + if (popFront == true) { + messageQueue.pop_front(); + } + if (messageQueue.empty() == false) { + // printf("onMessageBoxOk [%s] factionIndex = %d + //[%d] teamIndex = %d [%d][%d]\n", + // wrapString(lang.getScenarioString(messageQueue.front().getText()), + // messageWrapCount).c_str(), + // messageQueue.front().getFactionIndex(), + // this->world->getThisFactionIndex(), + // messageQueue.front().getTeamIndex(),this->world->getThisTeamIndex(),this->world->getThisFaction()->getTeam()); + + if ((messageQueue.front().getFactionIndex() < 0 && + messageQueue.front().getTeamIndex() < 0) || + messageQueue.front().getFactionIndex() == + this->world->getThisFactionIndex() || + messageQueue.front().getTeamIndex() == + this->world->getThisTeamIndex()) { + + messageBox.setEnabled(true); + + string msgText = messageQueue.front().getText(); + string msgHeader = messageQueue.front().getHeader(); + if (messageQueue.front().getMessageNotTranslated() == false) { + + msgText = lang.getScenarioString(messageQueue.front().getText()); + msgHeader = lang.getScenarioString(messageQueue.front().getHeader()); + } + messageBox.setText(msgText); + messageBox.setHeader(msgHeader); + break; + } + popFront = true; + } + } +} + +void ScriptManager::onResourceHarvested() { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (this->rootNode == NULL) { + luaScript.beginCall("resourceHarvested"); + luaScript.endCall(); + } +} + +void ScriptManager::onUnitCreated(const Unit *unit) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (this->rootNode == NULL) { + lastCreatedUnitName = unit->getType()->getName(false); + lastCreatedUnitId = unit->getId(); + luaScript.beginCall("unitCreated"); + luaScript.endCall(); + luaScript.beginCall("unitCreatedOfType_" + unit->getType()->getName()); + luaScript.endCall(); + } +} + +void ScriptManager::onUnitDied(const Unit *unit) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (this->rootNode == NULL) { + if (unit->getLastAttackerUnitId() >= 0) { + Unit *killer = world->findUnitById(unit->getLastAttackerUnitId()); + + if (killer != NULL) { + lastAttackingUnitName = killer->getType()->getName(false); + lastAttackingUnitId = killer->getId(); + + lastDeadUnitKillerName = killer->getType()->getName(false); + lastDeadUnitKillerId = killer->getId(); + } else { + lastDeadUnitKillerName = ""; + lastDeadUnitKillerId = -1; + } + } + + lastAttackedUnitName = unit->getType()->getName(false); + lastAttackedUnitId = unit->getId(); + + lastDeadUnitName = unit->getType()->getName(false); + lastDeadUnitId = unit->getId(); + lastDeadUnitCauseOfDeath = unit->getCauseOfDeath(); + + luaScript.beginCall("unitDied"); + luaScript.endCall(); + } +} + +void ScriptManager::onUnitAttacked(const Unit *unit) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (this->rootNode == NULL) { + lastAttackedUnitName = unit->getType()->getName(false); + lastAttackedUnitId = unit->getId(); + luaScript.beginCall("unitAttacked"); + luaScript.endCall(); + } +} + +void ScriptManager::onUnitAttacking(const Unit *unit) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (this->rootNode == NULL) { + lastAttackingUnitName = unit->getType()->getName(false); + lastAttackingUnitId = unit->getId(); + luaScript.beginCall("unitAttacking"); + luaScript.endCall(); + } } void ScriptManager::onGameOver(bool won) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - gameWon = won; - luaScript.beginCall("gameOver"); - luaScript.endCall(); + gameWon = won; + luaScript.beginCall("gameOver"); + luaScript.endCall(); } void ScriptManager::onTimerTriggerEvent() { - if(TimerTriggerEventList.empty() == true) { - return; - } - if(this->rootNode != NULL) { - return; - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] TimerTriggerEventList.size() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,TimerTriggerEventList.size()); - - for(std::map::iterator iterMap = TimerTriggerEventList.begin(); - iterMap != TimerTriggerEventList.end(); ++iterMap) { - - TimerTriggerEvent &event = iterMap->second; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] event.running = %d, event.startTime = %lld, event.endTime = %lld, diff = %f\n", - __FILE__,__FUNCTION__,__LINE__,event.running,(long long int)event.startFrame,(long long int)event.endFrame,(event.endFrame - event.startFrame)); - - if(event.running == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - // If using an efficient timer, check if its time to trigger - // on the elapsed check - if(event.triggerSecondsElapsed > 0) { - int elapsed = (world->getFrameCount()-event.startFrame) / GameConstants::updateFps; - if(elapsed < event.triggerSecondsElapsed) { - continue; - } - } - currentTimerTriggeredEventId = iterMap->first; - luaScript.beginCall("timerTriggerEvent"); - luaScript.endCall(); - - if(event.triggerSecondsElapsed > 0) { - int timerId = iterMap->first; - stopTimerEvent(timerId); - } - } - } + if (TimerTriggerEventList.empty() == true) { + return; + } + if (this->rootNode != NULL) { + return; + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, + "In [%s::%s Line: %d] TimerTriggerEventList.size() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + TimerTriggerEventList.size()); + + for (std::map::iterator iterMap = + TimerTriggerEventList.begin(); + iterMap != TimerTriggerEventList.end(); ++iterMap) { + + TimerTriggerEvent &event = iterMap->second; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, + "In [%s::%s Line: %d] event.running = %d, event.startTime = %lld, " + "event.endTime = %lld, diff = %f\n", + __FILE__, __FUNCTION__, __LINE__, event.running, + (long long int)event.startFrame, (long long int)event.endFrame, + (event.endFrame - event.startFrame)); + + if (event.running == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // If using an efficient timer, check if its time to trigger + // on the elapsed check + if (event.triggerSecondsElapsed > 0) { + int elapsed = (world->getFrameCount() - event.startFrame) / + GameConstants::updateFps; + if (elapsed < event.triggerSecondsElapsed) { + continue; + } + } + currentTimerTriggeredEventId = iterMap->first; + luaScript.beginCall("timerTriggerEvent"); + luaScript.endCall(); + + if (event.triggerSecondsElapsed > 0) { + int timerId = iterMap->first; + stopTimerEvent(timerId); + } + } + } } void ScriptManager::onCellTriggerEvent(Unit *movingUnit) { - if(CellTriggerEventList.empty() == true) { - return; - } - if(this->rootNode != NULL) { - return; - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] movingUnit = %p, CellTriggerEventList.size() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,movingUnit,CellTriggerEventList.size()); - - // remove any delayed removals - unregisterCellTriggerEvent(-1); - - inCellTriggerEvent = true; - if(movingUnit != NULL) { - //ScenarioInfo scenarioInfoStart = world->getScenario()->getInfo(); - - for(std::map::iterator iterMap = CellTriggerEventList.begin(); - iterMap != CellTriggerEventList.end(); ++iterMap) { - CellTriggerEvent &event = iterMap->second; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] movingUnit = %d, event.type = %d, movingUnit->getPos() = %s, event.sourceId = %d, event.destId = %d, event.destPos = %s\n", - __FILE__,__FUNCTION__,__LINE__,movingUnit->getId(),event.type,movingUnit->getPos().getString().c_str(), event.sourceId,event.destId,event.destPos.getString().c_str()); - - bool triggerEvent = false; - currentCellTriggeredEventAreaEntryUnitId = 0; - currentCellTriggeredEventAreaExitUnitId = 0; - currentCellTriggeredEventUnitId = 0; - - switch(event.type) { - case ctet_Unit: - { - Unit *destUnit = world->findUnitById(event.destId); - if(destUnit != NULL) { - if(movingUnit->getId() == event.sourceId) { - bool srcInDst = world->getMap()->isInUnitTypeCells(destUnit->getType(), destUnit->getPos(),movingUnit->getPos()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] movingUnit = %d, event.type = %d, movingUnit->getPos() = %s, event.sourceId = %d, event.destId = %d, event.destPos = %s, destUnit->getPos() = %s, srcInDst = %d\n", - __FILE__,__FUNCTION__,__LINE__,movingUnit->getId(), event.type,movingUnit->getPos().getString().c_str(),event.sourceId,event.destId, event.destPos.getString().c_str(), destUnit->getPos().getString().c_str(),srcInDst); - - if(srcInDst == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - else { - srcInDst = world->getMap()->isNextToUnitTypeCells(destUnit->getType(), destUnit->getPos(),movingUnit->getPos()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] movingUnit = %d, event.type = %d, movingUnit->getPos() = %s, event.sourceId = %d, event.destId = %d, event.destPos = %s, destUnit->getPos() = %s, srcInDst = %d\n", - __FILE__,__FUNCTION__,__LINE__,movingUnit->getId(), event.type,movingUnit->getPos().getString().c_str(),event.sourceId,event.destId, event.destPos.getString().c_str(), destUnit->getPos().getString().c_str(),srcInDst); - } - triggerEvent = srcInDst; - if(triggerEvent == true) { - currentCellTriggeredEventUnitId = movingUnit->getId(); - } - } - } - } - break; - case ctet_UnitPos: - { - if(movingUnit->getId() == event.sourceId) { - bool srcInDst = world->getMap()->isInUnitTypeCells(movingUnit->getType(), event.destPos,movingUnit->getPos()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] movingUnit = %d, event.type = %d, movingUnit->getPos() = %s, event.sourceId = %d, event.destId = %d, event.destPos = %s, srcInDst = %d\n", - __FILE__,__FUNCTION__,__LINE__,movingUnit->getId(),event.type,movingUnit->getPos().getString().c_str(),event.sourceId,event.destId,event.destPos.getString().c_str(),srcInDst); - - if(srcInDst == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - triggerEvent = srcInDst; - - if(triggerEvent == true) { - currentCellTriggeredEventUnitId = movingUnit->getId(); - } - } - } - break; - - case ctet_UnitAreaPos: - { - if(movingUnit->getId() == event.sourceId) { - bool srcInDst = false; - - // Cache area lookup so for each unitsize and pos its done only once - bool foundInCache = false; - std::map >::iterator iterFind1 = event.eventLookupCache.find(movingUnit->getType()->getSize()); - if(iterFind1 != event.eventLookupCache.end()) { - std::map::iterator iterFind2 = iterFind1->second.find(movingUnit->getPos()); - if(iterFind2 != iterFind1->second.end()) { - foundInCache = true; - srcInDst = iterFind2->second; - } - } - - if(foundInCache == false) { - for(int x = event.destPos.x; srcInDst == false && x <= event.destPosEnd.x; ++x) { - for(int y = event.destPos.y; srcInDst == false && y <= event.destPosEnd.y; ++y) { - srcInDst = world->getMap()->isInUnitTypeCells(movingUnit->getType(), Vec2i(x,y),movingUnit->getPos()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] movingUnit = %d, event.type = %d, movingUnit->getPos() = %s, event.sourceId = %d, event.destId = %d, event.destPos = %s, srcInDst = %d\n", - __FILE__,__FUNCTION__,__LINE__,movingUnit->getId(),event.type,movingUnit->getPos().getString().c_str(),event.sourceId,event.destId,Vec2i(x,y).getString().c_str(),srcInDst); - } - } - - event.eventLookupCache[movingUnit->getType()->getSize()][movingUnit->getPos()] = srcInDst; - } - - if(srcInDst == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - triggerEvent = srcInDst; - if(triggerEvent == true) { - currentCellTriggeredEventUnitId = movingUnit->getId(); - } - } - } - break; - - case ctet_Faction: - { - Unit *destUnit = world->findUnitById(event.destId); - if(destUnit != NULL && - movingUnit->getFactionIndex() == event.sourceId) { - bool srcInDst = world->getMap()->isInUnitTypeCells(destUnit->getType(), destUnit->getPos(),movingUnit->getPos()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] movingUnit = %d, event.type = %d, movingUnit->getPos() = %s, event.sourceId = %d, event.destId = %d, event.destPos = %s, srcInDst = %d\n", - __FILE__,__FUNCTION__,__LINE__,movingUnit->getId(),event.type,movingUnit->getPos().getString().c_str(),event.sourceId,event.destId,event.destPos.getString().c_str(),srcInDst); - - if(srcInDst == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - else { - srcInDst = world->getMap()->isNextToUnitTypeCells(destUnit->getType(), destUnit->getPos(),movingUnit->getPos()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] movingUnit = %d, event.type = %d, movingUnit->getPos() = %s, event.sourceId = %d, event.destId = %d, event.destPos = %s, destUnit->getPos() = %s, srcInDst = %d\n", - __FILE__,__FUNCTION__,__LINE__,movingUnit->getId(),event.type,movingUnit->getPos().getString().c_str(),event.sourceId,event.destId,event.destPos.getString().c_str(),destUnit->getPos().getString().c_str(),srcInDst); - } - triggerEvent = srcInDst; - if(triggerEvent == true) { - currentCellTriggeredEventUnitId = movingUnit->getId(); - } - } - } - break; - - case ctet_FactionPos: - { - if(movingUnit->getFactionIndex() == event.sourceId) { - //printf("ctet_FactionPos event.destPos = [%s], movingUnit->getPos() [%s]\n",event.destPos.getString().c_str(),movingUnit->getPos().getString().c_str()); - - bool srcInDst = world->getMap()->isInUnitTypeCells(movingUnit->getType(), event.destPos,movingUnit->getPos()); - if(srcInDst == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - triggerEvent = srcInDst; - if(triggerEvent == true) { - currentCellTriggeredEventUnitId = movingUnit->getId(); - } - } - } - break; - - case ctet_FactionAreaPos: - { - if(movingUnit->getFactionIndex() == event.sourceId) { - //if(event.sourceId == 1) printf("ctet_FactionPos event.destPos = [%s], movingUnit->getPos() [%s] Unit id = %d\n",event.destPos.getString().c_str(),movingUnit->getPos().getString().c_str(),movingUnit->getId()); - - bool srcInDst = false; - - // Cache area lookup so for each unitsize and pos its done only once - bool foundInCache = false; - std::map >::iterator iterFind1 = event.eventLookupCache.find(movingUnit->getType()->getSize()); - if(iterFind1 != event.eventLookupCache.end()) { - std::map::iterator iterFind2 = iterFind1->second.find(movingUnit->getPos()); - if(iterFind2 != iterFind1->second.end()) { - foundInCache = true; - srcInDst = iterFind2->second; - } - } - - if(foundInCache == false) { - for(int x = event.destPos.x; srcInDst == false && x <= event.destPosEnd.x; ++x) { - for(int y = event.destPos.y; srcInDst == false && y <= event.destPosEnd.y; ++y) { - - srcInDst = world->getMap()->isInUnitTypeCells(movingUnit->getType(), Vec2i(x,y),movingUnit->getPos()); - if(srcInDst == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - } - } - - event.eventLookupCache[movingUnit->getType()->getSize()][movingUnit->getPos()] = srcInDst; - } - - triggerEvent = srcInDst; - if(triggerEvent == true) { - //printf("!!!UNIT IN AREA!!! Faction area pos, moving unit faction= %d, trigger faction = %d, unit id = %d\n",movingUnit->getFactionIndex(),event.sourceId,movingUnit->getId()); - currentCellTriggeredEventUnitId = movingUnit->getId(); - } - } - } - break; - - case ctet_AreaPos: - { - // Is the unit already in the cell range? If no check if they are entering it - if(event.eventStateInfo.find(movingUnit->getId()) == event.eventStateInfo.end()) { - //printf("ctet_FactionPos event.destPos = [%s], movingUnit->getPos() [%s]\n",event.destPos.getString().c_str(),movingUnit->getPos().getString().c_str()); - - bool srcInDst = false; - for(int x = event.destPos.x; srcInDst == false && x <= event.destPosEnd.x; ++x) { - for(int y = event.destPos.y; srcInDst == false && y <= event.destPosEnd.y; ++y) { - - srcInDst = world->getMap()->isInUnitTypeCells(movingUnit->getType(), Vec2i(x,y),movingUnit->getPos()); - if(srcInDst == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - currentCellTriggeredEventAreaEntryUnitId = movingUnit->getId(); - event.eventStateInfo[movingUnit->getId()] = Vec2i(x,y).getString(); - } - } - } - triggerEvent = srcInDst; - if(triggerEvent == true) { - currentCellTriggeredEventUnitId = movingUnit->getId(); - } - } - // If unit is already in cell range check if they are leaving? - else { - bool srcInDst = false; - for(int x = event.destPos.x; srcInDst == false && x <= event.destPosEnd.x; ++x) { - for(int y = event.destPos.y; srcInDst == false && y <= event.destPosEnd.y; ++y) { - - srcInDst = world->getMap()->isInUnitTypeCells(movingUnit->getType(), Vec2i(x,y),movingUnit->getPos()); - if(srcInDst == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //event.eventStateInfo[movingUnit->getId()] = Vec2i(x,y); - } - } - } - triggerEvent = (srcInDst == false); - if(triggerEvent == true) { - currentCellTriggeredEventUnitId = movingUnit->getId(); - } - - if(triggerEvent == true) { - currentCellTriggeredEventAreaExitUnitId = movingUnit->getId(); - - event.eventStateInfo.erase(movingUnit->getId()); - } - } - } - break; - - } - - if(triggerEvent == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - currentCellTriggeredEventId = iterMap->first; - event.triggerCount++; - - luaScript.beginCall("cellTriggerEvent"); - luaScript.endCall(); - } - -// ScenarioInfo scenarioInfoEnd = world->getScenario()->getInfo(); -// if(scenarioInfoStart.file != scenarioInfoEnd.file) { -// break; -// } - } - } - - inCellTriggerEvent = false; -} - -// ========================== lua wrappers =============================================== + if (CellTriggerEventList.empty() == true) { + return; + } + if (this->rootNode != NULL) { + return; + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d] movingUnit = %p, " + "CellTriggerEventList.size() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, movingUnit, + CellTriggerEventList.size()); + + // remove any delayed removals + unregisterCellTriggerEvent(-1); + + inCellTriggerEvent = true; + if (movingUnit != NULL) { + // ScenarioInfo scenarioInfoStart = world->getScenario()->getInfo(); + + for (std::map::iterator iterMap = + CellTriggerEventList.begin(); + iterMap != CellTriggerEventList.end(); ++iterMap) { + CellTriggerEvent &event = iterMap->second; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, + "In [%s::%s Line: %d] movingUnit = %d, event.type = %d, " + "movingUnit->getPos() = %s, event.sourceId = %d, event.destId = " + "%d, event.destPos = %s\n", + __FILE__, __FUNCTION__, __LINE__, movingUnit->getId(), event.type, + movingUnit->getPos().getString().c_str(), event.sourceId, + event.destId, event.destPos.getString().c_str()); + + bool triggerEvent = false; + currentCellTriggeredEventAreaEntryUnitId = 0; + currentCellTriggeredEventAreaExitUnitId = 0; + currentCellTriggeredEventUnitId = 0; + + switch (event.type) { + case ctet_Unit: { + Unit *destUnit = world->findUnitById(event.destId); + if (destUnit != NULL) { + if (movingUnit->getId() == event.sourceId) { + bool srcInDst = world->getMap()->isInUnitTypeCells( + destUnit->getType(), destUnit->getPos(), movingUnit->getPos()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, + "In [%s::%s Line: %d] movingUnit = %d, event.type = %d, " + "movingUnit->getPos() = %s, event.sourceId = %d, " + "event.destId = %d, event.destPos = %s, destUnit->getPos() = " + "%s, srcInDst = %d\n", + __FILE__, __FUNCTION__, __LINE__, movingUnit->getId(), + event.type, movingUnit->getPos().getString().c_str(), + event.sourceId, event.destId, + event.destPos.getString().c_str(), + destUnit->getPos().getString().c_str(), srcInDst); + + if (srcInDst == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + } else { + srcInDst = world->getMap()->isNextToUnitTypeCells( + destUnit->getType(), destUnit->getPos(), + movingUnit->getPos()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, + "In [%s::%s Line: %d] movingUnit = %d, event.type = %d, " + "movingUnit->getPos() = %s, event.sourceId = %d, " + "event.destId = %d, event.destPos = %s, destUnit->getPos() " + "= %s, srcInDst = %d\n", + __FILE__, __FUNCTION__, __LINE__, movingUnit->getId(), + event.type, movingUnit->getPos().getString().c_str(), + event.sourceId, event.destId, + event.destPos.getString().c_str(), + destUnit->getPos().getString().c_str(), srcInDst); + } + triggerEvent = srcInDst; + if (triggerEvent == true) { + currentCellTriggeredEventUnitId = movingUnit->getId(); + } + } + } + } break; + case ctet_UnitPos: { + if (movingUnit->getId() == event.sourceId) { + bool srcInDst = world->getMap()->isInUnitTypeCells( + movingUnit->getType(), event.destPos, movingUnit->getPos()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, + "In [%s::%s Line: %d] movingUnit = %d, event.type = %d, " + "movingUnit->getPos() = %s, event.sourceId = %d, event.destId " + "= %d, event.destPos = %s, srcInDst = %d\n", + __FILE__, __FUNCTION__, __LINE__, movingUnit->getId(), + event.type, movingUnit->getPos().getString().c_str(), + event.sourceId, event.destId, event.destPos.getString().c_str(), + srcInDst); + + if (srcInDst == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } + triggerEvent = srcInDst; + + if (triggerEvent == true) { + currentCellTriggeredEventUnitId = movingUnit->getId(); + } + } + } break; + + case ctet_UnitAreaPos: { + if (movingUnit->getId() == event.sourceId) { + bool srcInDst = false; + + // Cache area lookup so for each unitsize and pos its done only once + bool foundInCache = false; + std::map>::iterator iterFind1 = + event.eventLookupCache.find(movingUnit->getType()->getSize()); + if (iterFind1 != event.eventLookupCache.end()) { + std::map::iterator iterFind2 = + iterFind1->second.find(movingUnit->getPos()); + if (iterFind2 != iterFind1->second.end()) { + foundInCache = true; + srcInDst = iterFind2->second; + } + } + + if (foundInCache == false) { + for (int x = event.destPos.x; + srcInDst == false && x <= event.destPosEnd.x; ++x) { + for (int y = event.destPos.y; + srcInDst == false && y <= event.destPosEnd.y; ++y) { + srcInDst = world->getMap()->isInUnitTypeCells( + movingUnit->getType(), Vec2i(x, y), movingUnit->getPos()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, + "In [%s::%s Line: %d] movingUnit = %d, event.type = %d, " + "movingUnit->getPos() = %s, event.sourceId = %d, " + "event.destId = %d, event.destPos = %s, srcInDst = %d\n", + __FILE__, __FUNCTION__, __LINE__, movingUnit->getId(), + event.type, movingUnit->getPos().getString().c_str(), + event.sourceId, event.destId, + Vec2i(x, y).getString().c_str(), srcInDst); + } + } + + event.eventLookupCache[movingUnit->getType()->getSize()] + [movingUnit->getPos()] = srcInDst; + } + + if (srcInDst == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } + triggerEvent = srcInDst; + if (triggerEvent == true) { + currentCellTriggeredEventUnitId = movingUnit->getId(); + } + } + } break; + + case ctet_Faction: { + Unit *destUnit = world->findUnitById(event.destId); + if (destUnit != NULL && + movingUnit->getFactionIndex() == event.sourceId) { + bool srcInDst = world->getMap()->isInUnitTypeCells( + destUnit->getType(), destUnit->getPos(), movingUnit->getPos()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, + "In [%s::%s Line: %d] movingUnit = %d, event.type = %d, " + "movingUnit->getPos() = %s, event.sourceId = %d, event.destId " + "= %d, event.destPos = %s, srcInDst = %d\n", + __FILE__, __FUNCTION__, __LINE__, movingUnit->getId(), + event.type, movingUnit->getPos().getString().c_str(), + event.sourceId, event.destId, event.destPos.getString().c_str(), + srcInDst); + + if (srcInDst == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } else { + srcInDst = world->getMap()->isNextToUnitTypeCells( + destUnit->getType(), destUnit->getPos(), movingUnit->getPos()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, + "In [%s::%s Line: %d] movingUnit = %d, event.type = %d, " + "movingUnit->getPos() = %s, event.sourceId = %d, " + "event.destId = %d, event.destPos = %s, destUnit->getPos() = " + "%s, srcInDst = %d\n", + __FILE__, __FUNCTION__, __LINE__, movingUnit->getId(), + event.type, movingUnit->getPos().getString().c_str(), + event.sourceId, event.destId, + event.destPos.getString().c_str(), + destUnit->getPos().getString().c_str(), srcInDst); + } + triggerEvent = srcInDst; + if (triggerEvent == true) { + currentCellTriggeredEventUnitId = movingUnit->getId(); + } + } + } break; + + case ctet_FactionPos: { + if (movingUnit->getFactionIndex() == event.sourceId) { + // printf("ctet_FactionPos event.destPos = [%s], movingUnit->getPos() + // [%s]\n",event.destPos.getString().c_str(),movingUnit->getPos().getString().c_str()); + + bool srcInDst = world->getMap()->isInUnitTypeCells( + movingUnit->getType(), event.destPos, movingUnit->getPos()); + if (srcInDst == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } + triggerEvent = srcInDst; + if (triggerEvent == true) { + currentCellTriggeredEventUnitId = movingUnit->getId(); + } + } + } break; + + case ctet_FactionAreaPos: { + if (movingUnit->getFactionIndex() == event.sourceId) { + // if(event.sourceId == 1) printf("ctet_FactionPos event.destPos = + // [%s], movingUnit->getPos() [%s] Unit id = + // %d\n",event.destPos.getString().c_str(),movingUnit->getPos().getString().c_str(),movingUnit->getId()); + + bool srcInDst = false; + + // Cache area lookup so for each unitsize and pos its done only once + bool foundInCache = false; + std::map>::iterator iterFind1 = + event.eventLookupCache.find(movingUnit->getType()->getSize()); + if (iterFind1 != event.eventLookupCache.end()) { + std::map::iterator iterFind2 = + iterFind1->second.find(movingUnit->getPos()); + if (iterFind2 != iterFind1->second.end()) { + foundInCache = true; + srcInDst = iterFind2->second; + } + } + + if (foundInCache == false) { + for (int x = event.destPos.x; + srcInDst == false && x <= event.destPosEnd.x; ++x) { + for (int y = event.destPos.y; + srcInDst == false && y <= event.destPosEnd.y; ++y) { + + srcInDst = world->getMap()->isInUnitTypeCells( + movingUnit->getType(), Vec2i(x, y), movingUnit->getPos()); + if (srcInDst == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + } + } + } + + event.eventLookupCache[movingUnit->getType()->getSize()] + [movingUnit->getPos()] = srcInDst; + } + + triggerEvent = srcInDst; + if (triggerEvent == true) { + // printf("!!!UNIT IN AREA!!! Faction area pos, moving unit faction= + // %d, trigger faction = %d, unit id = + // %d\n",movingUnit->getFactionIndex(),event.sourceId,movingUnit->getId()); + currentCellTriggeredEventUnitId = movingUnit->getId(); + } + } + } break; + + case ctet_AreaPos: { + // Is the unit already in the cell range? If no check if they are + // entering it + if (event.eventStateInfo.find(movingUnit->getId()) == + event.eventStateInfo.end()) { + // printf("ctet_FactionPos event.destPos = [%s], movingUnit->getPos() + // [%s]\n",event.destPos.getString().c_str(),movingUnit->getPos().getString().c_str()); + + bool srcInDst = false; + for (int x = event.destPos.x; + srcInDst == false && x <= event.destPosEnd.x; ++x) { + for (int y = event.destPos.y; + srcInDst == false && y <= event.destPosEnd.y; ++y) { + + srcInDst = world->getMap()->isInUnitTypeCells( + movingUnit->getType(), Vec2i(x, y), movingUnit->getPos()); + if (srcInDst == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + currentCellTriggeredEventAreaEntryUnitId = movingUnit->getId(); + event.eventStateInfo[movingUnit->getId()] = + Vec2i(x, y).getString(); + } + } + } + triggerEvent = srcInDst; + if (triggerEvent == true) { + currentCellTriggeredEventUnitId = movingUnit->getId(); + } + } + // If unit is already in cell range check if they are leaving? + else { + bool srcInDst = false; + for (int x = event.destPos.x; + srcInDst == false && x <= event.destPosEnd.x; ++x) { + for (int y = event.destPos.y; + srcInDst == false && y <= event.destPosEnd.y; ++y) { + + srcInDst = world->getMap()->isInUnitTypeCells( + movingUnit->getType(), Vec2i(x, y), movingUnit->getPos()); + if (srcInDst == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // event.eventStateInfo[movingUnit->getId()] = Vec2i(x,y); + } + } + } + triggerEvent = (srcInDst == false); + if (triggerEvent == true) { + currentCellTriggeredEventUnitId = movingUnit->getId(); + } + + if (triggerEvent == true) { + currentCellTriggeredEventAreaExitUnitId = movingUnit->getId(); + + event.eventStateInfo.erase(movingUnit->getId()); + } + } + } break; + } + + if (triggerEvent == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + currentCellTriggeredEventId = iterMap->first; + event.triggerCount++; + + luaScript.beginCall("cellTriggerEvent"); + luaScript.endCall(); + } + + // ScenarioInfo scenarioInfoEnd = + // world->getScenario()->getInfo(); + // if(scenarioInfoStart.file != scenarioInfoEnd.file) { + // break; + // } + } + } + + inCellTriggerEvent = false; +} + +// ========================== lua wrappers +// =============================================== string ScriptManager::wrapString(const string &str, int wrapCount) { - string returnString; + string returnString; - int letterCount= 0; - for(int i= 0; i < (int)str.size(); ++i){ - if(letterCount>wrapCount && str[i]==' ') { - returnString += '\n'; - letterCount= 0; - } - else - { - returnString += str[i]; - } - ++letterCount; - } + int letterCount = 0; + for (int i = 0; i < (int)str.size(); ++i) { + if (letterCount > wrapCount && str[i] == ' ') { + returnString += '\n'; + letterCount = 0; + } else { + returnString += str[i]; + } + ++letterCount; + } - return returnString; + return returnString; } -void ScriptManager::networkShowMessageForFaction(const string &text, const string &header,int factionIndex) { - messageQueue.push_back(ScriptManagerMessage(text, header, factionIndex)); - thisScriptManager->onMessageBoxOk(false); +void ScriptManager::networkShowMessageForFaction(const string &text, + const string &header, + int factionIndex) { + messageQueue.push_back(ScriptManagerMessage(text, header, factionIndex)); + thisScriptManager->onMessageBoxOk(false); } -void ScriptManager::networkShowMessageForTeam(const string &text, const string &header,int teamIndex) { - // Team indexes are 0 based internally (but 1 based in the lua script) so convert - teamIndex--; - messageQueue.push_back(ScriptManagerMessage(text, header, -1, teamIndex)); - thisScriptManager->onMessageBoxOk(false); +void ScriptManager::networkShowMessageForTeam(const string &text, + const string &header, + int teamIndex) { + // Team indexes are 0 based internally (but 1 based in the lua script) so + // convert + teamIndex--; + messageQueue.push_back(ScriptManagerMessage(text, header, -1, teamIndex)); + thisScriptManager->onMessageBoxOk(false); } -void ScriptManager::networkSetCameraPositionForFaction(int factionIndex, const Vec2i &pos) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void ScriptManager::networkSetCameraPositionForFaction(int factionIndex, + const Vec2i &pos) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - if(factionIndex == this->world->getThisFactionIndex()) { - gameCamera->centerXZ(pos.x, pos.y); - } + if (factionIndex == this->world->getThisFactionIndex()) { + gameCamera->centerXZ(pos.x, pos.y); + } } -void ScriptManager::networkSetCameraPositionForTeam(int teamIndex, const Vec2i &pos) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void ScriptManager::networkSetCameraPositionForTeam(int teamIndex, + const Vec2i &pos) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - if(teamIndex == this->world->getThisTeamIndex()) { - gameCamera->centerXZ(pos.x, pos.y); - } + if (teamIndex == this->world->getThisTeamIndex()) { + gameCamera->centerXZ(pos.x, pos.y); + } } -void ScriptManager::showMessage(const string &text, const string &header){ - messageQueue.push_back(ScriptManagerMessage(text, header)); - thisScriptManager->onMessageBoxOk(false); +void ScriptManager::showMessage(const string &text, const string &header) { + messageQueue.push_back(ScriptManagerMessage(text, header)); + thisScriptManager->onMessageBoxOk(false); } -void ScriptManager::clearDisplayText(){ - displayText= ""; -} +void ScriptManager::clearDisplayText() { displayText = ""; } -void ScriptManager::setDisplayText(const string &text){ - displayText= wrapString(Lang::getInstance().getScenarioString(text), displayTextWrapCount); +void ScriptManager::setDisplayText(const string &text) { + displayText = wrapString(Lang::getInstance().getScenarioString(text), + displayTextWrapCount); } -void ScriptManager::addConsoleText(const string &text){ - world->addConsoleText(text); +void ScriptManager::addConsoleText(const string &text) { + world->addConsoleText(text); } -void ScriptManager::addConsoleLangText(const char *fmt, ...){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - va_list argList; - va_start(argList, fmt); +void ScriptManager::addConsoleLangText(const char *fmt, ...) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + va_list argList; + va_start(argList, fmt); - const int max_debug_buffer_size = 8096; - char szBuf[max_debug_buffer_size]=""; - vsnprintf(szBuf,max_debug_buffer_size-1,fmt, argList); + const int max_debug_buffer_size = 8096; + char szBuf[max_debug_buffer_size] = ""; + vsnprintf(szBuf, max_debug_buffer_size - 1, fmt, argList); - world->addConsoleTextWoLang(szBuf); - va_end(argList); - + world->addConsoleTextWoLang(szBuf); + va_end(argList); } void ScriptManager::DisplayFormattedText(const char *fmt, ...) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - va_list argList; - va_start(argList, fmt); + va_list argList; + va_start(argList, fmt); - const int max_debug_buffer_size = 8096; - char szBuf[max_debug_buffer_size]=""; - vsnprintf(szBuf,max_debug_buffer_size-1,fmt, argList); + const int max_debug_buffer_size = 8096; + char szBuf[max_debug_buffer_size] = ""; + vsnprintf(szBuf, max_debug_buffer_size - 1, fmt, argList); - displayText=szBuf; + displayText = szBuf; - va_end(argList); + va_end(argList); } void ScriptManager::DisplayFormattedLangText(const char *fmt, ...) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - va_list argList; - va_start(argList, fmt); - - const int max_debug_buffer_size = 8096; - char szBuf[max_debug_buffer_size]=""; - vsnprintf(szBuf,max_debug_buffer_size-1,fmt, argList); - - displayText=szBuf; - - va_end(argList); -} -void ScriptManager::setCameraPosition(const Vec2i &pos){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - gameCamera->centerXZ(pos.x, pos.y); -} - -void ScriptManager::shakeCamera(int shakeIntensity, int shakeDuration, bool cameraDistanceAffected, int unitId){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if (cameraDistanceAffected) { - Unit *unit = world->findUnitById(unitId); - if(unit) { - gameCamera->shake(shakeDuration, shakeIntensity,cameraDistanceAffected, unit->getCurrMidHeightVector()); - } - } - else { - gameCamera->shake(shakeDuration, shakeIntensity,cameraDistanceAffected, Vec3f(0.f,0.f,0.f)); - } -} - -void ScriptManager::createUnit(const string &unitName, int factionIndex, Vec2i pos){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] unit [%s] factionIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,unitName.c_str(),factionIndex); - world->createUnit(unitName, factionIndex, pos); -} - -void ScriptManager::createUnitNoSpacing(const string &unitName, int factionIndex, Vec2i pos){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] unit [%s] factionIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,unitName.c_str(),factionIndex); - world->createUnit(unitName, factionIndex, pos, false); -} - -void ScriptManager::setLockedUnitForFaction(const string &unitName, int factionIndex , bool lock){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] unit [%s] factionIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,unitName.c_str(),factionIndex); - if(world->getFactionCount()>factionIndex) { - const UnitType *ut= world->getFaction(factionIndex)->getType()->getUnitType(unitName); - world->getFaction(factionIndex)->setLockedUnitForFaction(ut,lock); - } else { - throw megaglest_runtime_error("Invalid faction index in setLockedUnitForFaction: " + intToStr(factionIndex),true); - } -} - -void ScriptManager::destroyUnit(int unitId){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] unit [%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,unitId); - Unit *unit = world->findUnitById(unitId); - if(unit != NULL) { - // Make sure they die - bool unit_dead = unit->decHp(unit->getHp() * unit->getHp()); - if(unit_dead == false) { - throw megaglest_runtime_error("unit_dead == false",true); - } - unit->kill(); - // If called from an existing die event we get a stack overflow - //onUnitDied(unit); - } -} -void ScriptManager::giveKills (int unitId, int amount){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] unit [%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,unitId); - Unit *unit = world->findUnitById(unitId); - if(unit != NULL) { - for(int index = 1; index <= amount; ++index) { - unit->incKills(-1); - } - } + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + va_list argList; + va_start(argList, fmt); + + const int max_debug_buffer_size = 8096; + char szBuf[max_debug_buffer_size] = ""; + vsnprintf(szBuf, max_debug_buffer_size - 1, fmt, argList); + + displayText = szBuf; + + va_end(argList); +} +void ScriptManager::setCameraPosition(const Vec2i &pos) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + gameCamera->centerXZ(pos.x, pos.y); +} + +void ScriptManager::shakeCamera(int shakeIntensity, int shakeDuration, + bool cameraDistanceAffected, int unitId) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (cameraDistanceAffected) { + Unit *unit = world->findUnitById(unitId); + if (unit) { + gameCamera->shake(shakeDuration, shakeIntensity, cameraDistanceAffected, + unit->getCurrMidHeightVector()); + } + } else { + gameCamera->shake(shakeDuration, shakeIntensity, cameraDistanceAffected, + Vec3f(0.f, 0.f, 0.f)); + } +} + +void ScriptManager::createUnit(const string &unitName, int factionIndex, + Vec2i pos) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, + "In [%s::%s Line: %d] unit [%s] factionIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + unitName.c_str(), factionIndex); + world->createUnit(unitName, factionIndex, pos); +} + +void ScriptManager::createUnitNoSpacing(const string &unitName, + int factionIndex, Vec2i pos) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, + "In [%s::%s Line: %d] unit [%s] factionIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + unitName.c_str(), factionIndex); + world->createUnit(unitName, factionIndex, pos, false); +} + +void ScriptManager::setLockedUnitForFaction(const string &unitName, + int factionIndex, bool lock) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, + "In [%s::%s Line: %d] unit [%s] factionIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + unitName.c_str(), factionIndex); + if (world->getFactionCount() > factionIndex) { + const UnitType *ut = + world->getFaction(factionIndex)->getType()->getUnitType(unitName); + world->getFaction(factionIndex)->setLockedUnitForFaction(ut, lock); + } else { + throw megaglest_runtime_error( + "Invalid faction index in setLockedUnitForFaction: " + + intToStr(factionIndex), + true); + } +} + +void ScriptManager::destroyUnit(int unitId) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d] unit [%d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, unitId); + Unit *unit = world->findUnitById(unitId); + if (unit != NULL) { + // Make sure they die + bool unit_dead = unit->decHp(unit->getHp() * unit->getHp()); + if (unit_dead == false) { + throw megaglest_runtime_error("unit_dead == false", true); + } + unit->kill(); + // If called from an existing die event we get a stack overflow + // onUnitDied(unit); + } +} +void ScriptManager::giveKills(int unitId, int amount) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d] unit [%d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, unitId); + Unit *unit = world->findUnitById(unitId); + if (unit != NULL) { + for (int index = 1; index <= amount; ++index) { + unit->incKills(-1); + } + } } void ScriptManager::playStaticSound(const string &playSound) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] playSound [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playSound.c_str()); - world->playStaticSound(playSound); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d] playSound [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, playSound.c_str()); + world->playStaticSound(playSound); } void ScriptManager::playStreamingSound(const string &playSound) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] playSound [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playSound.c_str()); - world->playStreamingSound(playSound); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d] playSound [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, playSound.c_str()); + world->playStreamingSound(playSound); } void ScriptManager::stopStreamingSound(const string &playSound) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] playSound [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playSound.c_str()); - world->stopStreamingSound(playSound); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d] playSound [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, playSound.c_str()); + world->stopStreamingSound(playSound); } void ScriptManager::stopAllSound() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - world->stopAllSound(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + world->stopAllSound(); } void ScriptManager::playStaticVideo(const string &playVideo) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] playVideo [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playVideo.c_str()); - world->playStaticVideo(playVideo); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d] playVideo [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, playVideo.c_str()); + world->playStaticVideo(playVideo); } void ScriptManager::playStreamingVideo(const string &playVideo) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] playVideo [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playVideo.c_str()); - world->playStreamingVideo(playVideo); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d] playVideo [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, playVideo.c_str()); + world->playStreamingVideo(playVideo); } void ScriptManager::stopStreamingVideo(const string &playVideo) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] playVideo [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playVideo.c_str()); - world->stopStreamingVideo(playVideo); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d] playVideo [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, playVideo.c_str()); + world->stopStreamingVideo(playVideo); } void ScriptManager::stopAllVideo() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - world->stopAllVideo(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + world->stopAllVideo(); } void ScriptManager::togglePauseGame(int pauseStatus) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] pauseStatus = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,pauseStatus); - world->togglePauseGame((pauseStatus != 0),true); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d] pauseStatus = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, pauseStatus); + world->togglePauseGame((pauseStatus != 0), true); } -void ScriptManager::morphToUnit(int unitId,const string &morphName, int ignoreRequirements) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] unit [%d] morphName [%s] forceUpgradesIfRequired = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,unitId,morphName.c_str(),ignoreRequirements); +void ScriptManager::morphToUnit(int unitId, const string &morphName, + int ignoreRequirements) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d] unit [%d] morphName [%s] " + "forceUpgradesIfRequired = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, unitId, morphName.c_str(), + ignoreRequirements); - world->morphToUnit(unitId,morphName,(ignoreRequirements == 1)); + world->morphToUnit(unitId, morphName, (ignoreRequirements == 1)); } -void ScriptManager::moveToUnit(int unitId,int destUnitId) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] unit [%d] destUnitId [%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,unitId,destUnitId); +void ScriptManager::moveToUnit(int unitId, int destUnitId) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d] unit [%d] destUnitId [%d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, unitId, destUnitId); - world->moveToUnit(unitId,destUnitId); + world->moveToUnit(unitId, destUnitId); } -void ScriptManager::giveResource(const string &resourceName, int factionIndex, int amount){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void ScriptManager::giveResource(const string &resourceName, int factionIndex, + int amount) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - world->giveResource(resourceName, factionIndex, amount); + world->giveResource(resourceName, factionIndex, amount); } -void ScriptManager::givePositionCommand(int unitId, const string &commandName, const Vec2i &pos){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void ScriptManager::givePositionCommand(int unitId, const string &commandName, + const Vec2i &pos) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - world->givePositionCommand(unitId, commandName, pos); + world->givePositionCommand(unitId, commandName, pos); } void ScriptManager::giveAttackCommand(int unitId, int unitToAttackId) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - world->giveAttackCommand(unitId, unitToAttackId); + world->giveAttackCommand(unitId, unitToAttackId); } -void ScriptManager::giveProductionCommand(int unitId, const string &producedName){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void ScriptManager::giveProductionCommand(int unitId, + const string &producedName) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - world->giveProductionCommand(unitId, producedName); + world->giveProductionCommand(unitId, producedName); } -void ScriptManager::giveUpgradeCommand(int unitId, const string &producedName){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void ScriptManager::giveUpgradeCommand(int unitId, const string &producedName) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - world->giveUpgradeCommand(unitId, producedName); + world->giveUpgradeCommand(unitId, producedName); } -void ScriptManager::giveAttackStoppedCommand(int unitId, const string &itemName,int ignoreRequirements) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void ScriptManager::giveAttackStoppedCommand(int unitId, const string &itemName, + int ignoreRequirements) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - world->giveAttackStoppedCommand(unitId, itemName, (ignoreRequirements == 1)); + world->giveAttackStoppedCommand(unitId, itemName, (ignoreRequirements == 1)); } -void ScriptManager::disableAi(int factionIndex){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void ScriptManager::disableAi(int factionIndex) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - if(factionIndex >= 0 && factionIndex < GameConstants::maxPlayers) { - playerModifiers[factionIndex].disableAi(); - disableConsume(factionIndex); // by this we stay somehow compatible with old behaviour - } + if (factionIndex >= 0 && factionIndex < GameConstants::maxPlayers) { + playerModifiers[factionIndex].disableAi(); + disableConsume( + factionIndex); // by this we stay somehow compatible with old behaviour + } } -void ScriptManager::enableAi(int factionIndex){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void ScriptManager::enableAi(int factionIndex) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - if(factionIndex >= 0 && factionIndex < GameConstants::maxPlayers) { - playerModifiers[factionIndex].enableAi(); - } + if (factionIndex >= 0 && factionIndex < GameConstants::maxPlayers) { + playerModifiers[factionIndex].enableAi(); + } } bool ScriptManager::getAiEnabled(int factionIndex) { - if(factionIndex >= 0 && factionIndex < GameConstants::maxPlayers) { - return playerModifiers[factionIndex].getAiEnabled(); - } - return false; + if (factionIndex >= 0 && factionIndex < GameConstants::maxPlayers) { + return playerModifiers[factionIndex].getAiEnabled(); + } + return false; } void ScriptManager::disableConsume(int factionIndex) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - if(factionIndex >= 0 && factionIndex < GameConstants::maxPlayers) { - playerModifiers[factionIndex].disableConsume(); - } + if (factionIndex >= 0 && factionIndex < GameConstants::maxPlayers) { + playerModifiers[factionIndex].disableConsume(); + } } void ScriptManager::enableConsume(int factionIndex) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - if(factionIndex >= 0 && factionIndex < GameConstants::maxPlayers) { - playerModifiers[factionIndex].enableConsume(); - } + if (factionIndex >= 0 && factionIndex < GameConstants::maxPlayers) { + playerModifiers[factionIndex].enableConsume(); + } } bool ScriptManager::getConsumeEnabled(int factionIndex) { - if(factionIndex >= 0 && factionIndex < GameConstants::maxPlayers) { - return playerModifiers[factionIndex].getConsumeEnabled(); - } - return false; -} - -int ScriptManager::registerCellTriggerEventForUnitToUnit(int sourceUnitId, int destUnitId) { - CellTriggerEvent trigger; - trigger.type = ctet_Unit; - trigger.sourceId = sourceUnitId; - trigger.destId = destUnitId; + if (factionIndex >= 0 && factionIndex < GameConstants::maxPlayers) { + return playerModifiers[factionIndex].getConsumeEnabled(); + } + return false; +} + +int ScriptManager::registerCellTriggerEventForUnitToUnit(int sourceUnitId, + int destUnitId) { + CellTriggerEvent trigger; + trigger.type = ctet_Unit; + trigger.sourceId = sourceUnitId; + trigger.destId = destUnitId; + + int eventId = currentEventId++; + CellTriggerEventList[eventId] = trigger; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d] Unit: %d will trigger cell " + "event when reaching unit: %d, eventId = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, sourceUnitId, destUnitId, + eventId); + + return eventId; +} + +int ScriptManager::registerCellTriggerEventForUnitToLocation(int sourceUnitId, + const Vec2i &pos) { + CellTriggerEvent trigger; + trigger.type = ctet_UnitPos; + trigger.sourceId = sourceUnitId; + trigger.destPos = pos; + + int eventId = currentEventId++; + CellTriggerEventList[eventId] = trigger; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d] Unit: %d will trigger cell " + "event when reaching pos: %s, eventId = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, sourceUnitId, + pos.getString().c_str(), eventId); + + return eventId; +} + +int ScriptManager::registerCellAreaTriggerEventForUnitToLocation( + int sourceUnitId, const Vec4i &pos) { + CellTriggerEvent trigger; + trigger.type = ctet_UnitAreaPos; + trigger.sourceId = sourceUnitId; + trigger.destPos.x = pos.x; + trigger.destPos.y = pos.y; + trigger.destPosEnd.x = pos.z; + trigger.destPosEnd.y = pos.w; + + int eventId = currentEventId++; + CellTriggerEventList[eventId] = trigger; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d] Unit: %d will trigger cell " + "event when reaching pos: %s, eventId = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, sourceUnitId, + pos.getString().c_str(), eventId); + + return eventId; +} + +int ScriptManager::registerCellTriggerEventForFactionToUnit(int sourceFactionId, + int destUnitId) { + CellTriggerEvent trigger; + trigger.type = ctet_Faction; + trigger.sourceId = sourceFactionId; + trigger.destId = destUnitId; + + int eventId = currentEventId++; + CellTriggerEventList[eventId] = trigger; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, + "In [%s::%s Line: %d] Faction: %d will trigger cell event when " + "reaching unit: %d, eventId = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + sourceFactionId, destUnitId, eventId); + + return eventId; +} + +int ScriptManager::registerCellTriggerEventForFactionToLocation( + int sourceFactionId, const Vec2i &pos) { + CellTriggerEvent trigger; + trigger.type = ctet_FactionPos; + trigger.sourceId = sourceFactionId; + trigger.destPos = pos; + + int eventId = currentEventId++; + CellTriggerEventList[eventId] = trigger; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d]Faction: %d will trigger " + "cell event when reaching pos: %s, eventId = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, sourceFactionId, + pos.getString().c_str(), eventId); + + return eventId; +} + +int ScriptManager::registerCellAreaTriggerEventForFactionToLocation( + int sourceFactionId, const Vec4i &pos) { + CellTriggerEvent trigger; + trigger.type = ctet_FactionAreaPos; + trigger.sourceId = sourceFactionId; + trigger.destPos.x = pos.x; + trigger.destPos.y = pos.y; + trigger.destPosEnd.x = pos.z; + trigger.destPosEnd.y = pos.w; - int eventId = currentEventId++; - CellTriggerEventList[eventId] = trigger; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] Unit: %d will trigger cell event when reaching unit: %d, eventId = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,sourceUnitId,destUnitId,eventId); - - return eventId; -} - -int ScriptManager::registerCellTriggerEventForUnitToLocation(int sourceUnitId, const Vec2i &pos) { - CellTriggerEvent trigger; - trigger.type = ctet_UnitPos; - trigger.sourceId = sourceUnitId; - trigger.destPos = pos; - - int eventId = currentEventId++; - CellTriggerEventList[eventId] = trigger; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] Unit: %d will trigger cell event when reaching pos: %s, eventId = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,sourceUnitId,pos.getString().c_str(),eventId); - - return eventId; -} - -int ScriptManager::registerCellAreaTriggerEventForUnitToLocation(int sourceUnitId, const Vec4i &pos) { - CellTriggerEvent trigger; - trigger.type = ctet_UnitAreaPos; - trigger.sourceId = sourceUnitId; - trigger.destPos.x = pos.x; - trigger.destPos.y = pos.y; - trigger.destPosEnd.x = pos.z; - trigger.destPosEnd.y = pos.w; - - int eventId = currentEventId++; - CellTriggerEventList[eventId] = trigger; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] Unit: %d will trigger cell event when reaching pos: %s, eventId = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,sourceUnitId,pos.getString().c_str(),eventId); - - return eventId; -} - -int ScriptManager::registerCellTriggerEventForFactionToUnit(int sourceFactionId, int destUnitId) { - CellTriggerEvent trigger; - trigger.type = ctet_Faction; - trigger.sourceId = sourceFactionId; - trigger.destId = destUnitId; - - int eventId = currentEventId++; - CellTriggerEventList[eventId] = trigger; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] Faction: %d will trigger cell event when reaching unit: %d, eventId = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,sourceFactionId,destUnitId,eventId); - - return eventId; -} - -int ScriptManager::registerCellTriggerEventForFactionToLocation(int sourceFactionId, const Vec2i &pos) { - CellTriggerEvent trigger; - trigger.type = ctet_FactionPos; - trigger.sourceId = sourceFactionId; - trigger.destPos = pos; - - int eventId = currentEventId++; - CellTriggerEventList[eventId] = trigger; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]Faction: %d will trigger cell event when reaching pos: %s, eventId = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,sourceFactionId,pos.getString().c_str(),eventId); - - return eventId; -} - -int ScriptManager::registerCellAreaTriggerEventForFactionToLocation(int sourceFactionId, const Vec4i &pos) { - CellTriggerEvent trigger; - trigger.type = ctet_FactionAreaPos; - trigger.sourceId = sourceFactionId; - trigger.destPos.x = pos.x; - trigger.destPos.y = pos.y; - trigger.destPosEnd.x = pos.z; - trigger.destPosEnd.y = pos.w; - - int eventId = currentEventId++; - CellTriggerEventList[eventId] = trigger; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]Faction: %d will trigger cell event when reaching pos: %s, eventId = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,sourceFactionId,pos.getString().c_str(),eventId); - - return eventId; + int eventId = currentEventId++; + CellTriggerEventList[eventId] = trigger; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d]Faction: %d will trigger " + "cell event when reaching pos: %s, eventId = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, sourceFactionId, + pos.getString().c_str(), eventId); + + return eventId; } int ScriptManager::registerCellAreaTriggerEvent(const Vec4i &pos) { - CellTriggerEvent trigger; - trigger.type = ctet_AreaPos; - trigger.sourceId = -1; - trigger.destPos.x = pos.x; - trigger.destPos.y = pos.y; - trigger.destPosEnd.x = pos.z; - trigger.destPosEnd.y = pos.w; + CellTriggerEvent trigger; + trigger.type = ctet_AreaPos; + trigger.sourceId = -1; + trigger.destPos.x = pos.x; + trigger.destPos.y = pos.y; + trigger.destPosEnd.x = pos.z; + trigger.destPosEnd.y = pos.w; - int eventId = currentEventId++; - CellTriggerEventList[eventId] = trigger; + int eventId = currentEventId++; + CellTriggerEventList[eventId] = trigger; - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] trigger cell event when reaching pos: %s, eventId = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,pos.getString().c_str(),eventId); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d] trigger cell event when " + "reaching pos: %s, eventId = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, pos.getString().c_str(), + eventId); - return eventId; + return eventId; } int ScriptManager::getCellTriggerEventCount(int eventId) { - int result = 0; - if(CellTriggerEventList.find(eventId) != CellTriggerEventList.end()) { - result = CellTriggerEventList[eventId].triggerCount; - } + int result = 0; + if (CellTriggerEventList.find(eventId) != CellTriggerEventList.end()) { + result = CellTriggerEventList[eventId].triggerCount; + } - return result; + return result; } void ScriptManager::unregisterCellTriggerEvent(int eventId) { - if(CellTriggerEventList.find(eventId) != CellTriggerEventList.end()) { - if(inCellTriggerEvent == false) { - CellTriggerEventList.erase(eventId); - } - else { - unRegisterCellTriggerEventList.push_back(eventId); - } - } - - if(inCellTriggerEvent == false) { - if(unRegisterCellTriggerEventList.empty() == false) { - for(int i = 0; i < (int)unRegisterCellTriggerEventList.size(); ++i) { - int delayedEventId = unRegisterCellTriggerEventList[i]; - CellTriggerEventList.erase(delayedEventId); - } - unRegisterCellTriggerEventList.clear(); - } - } + if (CellTriggerEventList.find(eventId) != CellTriggerEventList.end()) { + if (inCellTriggerEvent == false) { + CellTriggerEventList.erase(eventId); + } else { + unRegisterCellTriggerEventList.push_back(eventId); + } + } + + if (inCellTriggerEvent == false) { + if (unRegisterCellTriggerEventList.empty() == false) { + for (int i = 0; i < (int)unRegisterCellTriggerEventList.size(); ++i) { + int delayedEventId = unRegisterCellTriggerEventList[i]; + CellTriggerEventList.erase(delayedEventId); + } + unRegisterCellTriggerEventList.clear(); + } + } } int ScriptManager::startTimerEvent() { - TimerTriggerEvent trigger; - trigger.running = true; - //trigger.startTime = time(NULL); - trigger.startFrame = world->getFrameCount(); - //trigger.endTime = 0; - trigger.endFrame = 0; + TimerTriggerEvent trigger; + trigger.running = true; + // trigger.startTime = time(NULL); + trigger.startFrame = world->getFrameCount(); + // trigger.endTime = 0; + trigger.endFrame = 0; - int eventId = currentEventId++; - TimerTriggerEventList[eventId] = trigger; + int eventId = currentEventId++; + TimerTriggerEventList[eventId] = trigger; - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] TimerTriggerEventList.size() = %d, eventId = %d, trigger.startTime = %lld, trigger.endTime = %lld\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,TimerTriggerEventList.size(),eventId,(long long int)trigger.startFrame,(long long int)trigger.endFrame); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, + "In [%s::%s Line: %d] TimerTriggerEventList.size() = %d, eventId = %d, " + "trigger.startTime = %lld, trigger.endTime = %lld\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + TimerTriggerEventList.size(), eventId, + (long long int)trigger.startFrame, (long long int)trigger.endFrame); - return eventId; + return eventId; } int ScriptManager::startEfficientTimerEvent(int triggerSecondsElapsed) { - TimerTriggerEvent trigger; - trigger.running = true; - //trigger.startTime = time(NULL); - trigger.startFrame = world->getFrameCount(); - //trigger.endTime = 0; - trigger.endFrame = 0; - trigger.triggerSecondsElapsed = triggerSecondsElapsed; + TimerTriggerEvent trigger; + trigger.running = true; + // trigger.startTime = time(NULL); + trigger.startFrame = world->getFrameCount(); + // trigger.endTime = 0; + trigger.endFrame = 0; + trigger.triggerSecondsElapsed = triggerSecondsElapsed; - int eventId = currentEventId++; - TimerTriggerEventList[eventId] = trigger; + int eventId = currentEventId++; + TimerTriggerEventList[eventId] = trigger; - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] TimerTriggerEventList.size() = %d, eventId = %d, trigger.startTime = %lld, trigger.endTime = %lld\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,TimerTriggerEventList.size(),eventId,(long long int)trigger.startFrame,(long long int)trigger.endFrame); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, + "In [%s::%s Line: %d] TimerTriggerEventList.size() = %d, eventId = %d, " + "trigger.startTime = %lld, trigger.endTime = %lld\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + TimerTriggerEventList.size(), eventId, + (long long int)trigger.startFrame, (long long int)trigger.endFrame); - return eventId; + return eventId; } int ScriptManager::resetTimerEvent(int eventId) { - int result = 0; - if(TimerTriggerEventList.find(eventId) != TimerTriggerEventList.end()) { - TimerTriggerEvent &trigger = TimerTriggerEventList[eventId]; - result = getTimerEventSecondsElapsed(eventId); - - //trigger.startTime = time(NULL); - trigger.startFrame = world->getFrameCount(); - //trigger.endTime = 0; - trigger.endFrame = 0; - trigger.running = true; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] TimerTriggerEventList.size() = %d, eventId = %d, trigger.startTime = %lld, trigger.endTime = %lld, result = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,TimerTriggerEventList.size(),eventId,(long long int)trigger.startFrame,(long long int)trigger.endFrame,result); - } - return result; + int result = 0; + if (TimerTriggerEventList.find(eventId) != TimerTriggerEventList.end()) { + TimerTriggerEvent &trigger = TimerTriggerEventList[eventId]; + result = getTimerEventSecondsElapsed(eventId); + + // trigger.startTime = time(NULL); + trigger.startFrame = world->getFrameCount(); + // trigger.endTime = 0; + trigger.endFrame = 0; + trigger.running = true; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, + "In [%s::%s Line: %d] TimerTriggerEventList.size() = %d, eventId = " + "%d, trigger.startTime = %lld, trigger.endTime = %lld, result = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, TimerTriggerEventList.size(), eventId, + (long long int)trigger.startFrame, (long long int)trigger.endFrame, + result); + } + return result; } int ScriptManager::stopTimerEvent(int eventId) { - int result = 0; - if(TimerTriggerEventList.find(eventId) != TimerTriggerEventList.end()) { - TimerTriggerEvent &trigger = TimerTriggerEventList[eventId]; - //trigger.endTime = time(NULL); - trigger.endFrame = world->getFrameCount(); - trigger.running = false; - result = getTimerEventSecondsElapsed(eventId); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] TimerTriggerEventList.size() = %d, eventId = %d, trigger.startTime = %lld, trigger.endTime = %lld, result = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,TimerTriggerEventList.size(),eventId,(long long int)trigger.startFrame,(long long int)trigger.endFrame,result); - } - - return result; + int result = 0; + if (TimerTriggerEventList.find(eventId) != TimerTriggerEventList.end()) { + TimerTriggerEvent &trigger = TimerTriggerEventList[eventId]; + // trigger.endTime = time(NULL); + trigger.endFrame = world->getFrameCount(); + trigger.running = false; + result = getTimerEventSecondsElapsed(eventId); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, + "In [%s::%s Line: %d] TimerTriggerEventList.size() = %d, eventId = " + "%d, trigger.startTime = %lld, trigger.endTime = %lld, result = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, TimerTriggerEventList.size(), eventId, + (long long int)trigger.startFrame, (long long int)trigger.endFrame, + result); + } + + return result; } int ScriptManager::getTimerEventSecondsElapsed(int eventId) { - int result = 0; - if(TimerTriggerEventList.find(eventId) != TimerTriggerEventList.end()) { - TimerTriggerEvent &trigger = TimerTriggerEventList[eventId]; - if(trigger.running) { - //result = (int)difftime(time(NULL),trigger.startTime); - result = (world->getFrameCount()-trigger.startFrame) / GameConstants::updateFps; - } - else { - //result = (int)difftime(trigger.endTime,trigger.startTime); - result = (trigger.endFrame-trigger.startFrame) / GameConstants::updateFps; - } + int result = 0; + if (TimerTriggerEventList.find(eventId) != TimerTriggerEventList.end()) { + TimerTriggerEvent &trigger = TimerTriggerEventList[eventId]; + if (trigger.running) { + // result = (int)difftime(time(NULL),trigger.startTime); + result = (world->getFrameCount() - trigger.startFrame) / + GameConstants::updateFps; + } else { + // result = (int)difftime(trigger.endTime,trigger.startTime); + result = + (trigger.endFrame - trigger.startFrame) / GameConstants::updateFps; + } - //printf("Timer event id = %d seconmds elapsed = %d\n",eventId,result); - } + // printf("Timer event id = %d seconmds elapsed = %d\n",eventId,result); + } - return result; + return result; } void ScriptManager::setPlayerAsWinner(int factionIndex) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - if(factionIndex >= 0 && factionIndex < GameConstants::maxPlayers) { - playerModifiers[factionIndex].setAsWinner(); - } + if (factionIndex >= 0 && factionIndex < GameConstants::maxPlayers) { + playerModifiers[factionIndex].setAsWinner(); + } } void ScriptManager::endGame() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - gameOver= true; + gameOver = true; } void ScriptManager::startPerformanceTimer() { - if(world->getGame() == NULL) { - throw megaglest_runtime_error("#1 world->getGame() == NULL",true); - } - world->getGame()->startPerformanceTimer(); - + if (world->getGame() == NULL) { + throw megaglest_runtime_error("#1 world->getGame() == NULL", true); + } + world->getGame()->startPerformanceTimer(); } void ScriptManager::endPerformanceTimer() { - if(world->getGame() == NULL) { - throw megaglest_runtime_error("#2 world->getGame() == NULL",true); - } - world->getGame()->endPerformanceTimer(); - + if (world->getGame() == NULL) { + throw megaglest_runtime_error("#2 world->getGame() == NULL", true); + } + world->getGame()->endPerformanceTimer(); } Vec2i ScriptManager::getPerformanceTimerResults() { - if(world->getGame() == NULL) { - throw megaglest_runtime_error("#3 world->getGame() == NULL",true); - } - return world->getGame()->getPerformanceTimerResults(); + if (world->getGame() == NULL) { + throw megaglest_runtime_error("#3 world->getGame() == NULL", true); + } + return world->getGame()->getPerformanceTimerResults(); } Vec2i ScriptManager::getStartLocation(int factionIndex) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return world->getStartLocation(factionIndex); + return world->getStartLocation(factionIndex); } - Vec2i ScriptManager::getUnitPosition(int unitId) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - Vec2i result = world->getUnitPosition(unitId); + Vec2i result = world->getUnitPosition(unitId); - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s] unitId = %d, pos [%s]\n",__FUNCTION__,unitId,result.getString().c_str()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s] unitId = %d, pos [%s]\n", __FUNCTION__, + unitId, result.getString().c_str()); - return result; + return result; } void ScriptManager::setUnitPosition(int unitId, Vec2i pos) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - world->setUnitPosition(unitId,pos); + world->setUnitPosition(unitId, pos); } -void ScriptManager::addCellMarker(Vec2i pos, int factionIndex, const string ¬e, const string &textureFile) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void ScriptManager::addCellMarker(Vec2i pos, int factionIndex, + const string ¬e, + const string &textureFile) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - world->addCellMarker(pos,factionIndex, note, textureFile); + world->addCellMarker(pos, factionIndex, note, textureFile); } void ScriptManager::removeCellMarker(Vec2i pos, int factionIndex) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - world->removeCellMarker(pos,factionIndex); + world->removeCellMarker(pos, factionIndex); } -void ScriptManager::showMarker(Vec2i pos, int factionIndex, const string ¬e, const string &textureFile, int flashCount) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void ScriptManager::showMarker(Vec2i pos, int factionIndex, const string ¬e, + const string &textureFile, int flashCount) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - world->showMarker(pos,factionIndex, note, textureFile, flashCount); + world->showMarker(pos, factionIndex, note, textureFile, flashCount); } int ScriptManager::getIsUnitAlive(int unitId) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return world->getIsUnitAlive(unitId); + return world->getIsUnitAlive(unitId); } int ScriptManager::getUnitFaction(int unitId) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return world->getUnitFactionIndex(unitId); + return world->getUnitFactionIndex(unitId); } const string ScriptManager::getUnitName(int unitId) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - string result = ""; - Unit *unit = world->findUnitById(unitId); - if(unit) { - result = world->findUnitById(unitId)->getType()->getName(false); - } - return result; + string result = ""; + Unit *unit = world->findUnitById(unitId); + if (unit) { + result = world->findUnitById(unitId)->getType()->getName(false); + } + return result; } const string ScriptManager::getUnitDisplayName(int unitId) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return world->getUnitName(unitId); + return world->getUnitName(unitId); } -int ScriptManager::getResourceAmount(const string &resourceName, int factionIndex) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +int ScriptManager::getResourceAmount(const string &resourceName, + int factionIndex) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return world->getResourceAmount(resourceName, factionIndex); + return world->getResourceAmount(resourceName, factionIndex); } const string &ScriptManager::getLastCreatedUnitName() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return lastCreatedUnitName; + return lastCreatedUnitName; } int ScriptManager::getCellTriggeredEventId() { - return currentCellTriggeredEventId; + return currentCellTriggeredEventId; } int ScriptManager::getTimerTriggeredEventId() { - return currentTimerTriggeredEventId; + return currentTimerTriggeredEventId; } int ScriptManager::getCellTriggeredEventAreaEntryUnitId() { - return currentCellTriggeredEventAreaEntryUnitId; + return currentCellTriggeredEventAreaEntryUnitId; } int ScriptManager::getCellTriggeredEventAreaExitUnitId() { - return currentCellTriggeredEventAreaExitUnitId; + return currentCellTriggeredEventAreaExitUnitId; } int ScriptManager::getCellTriggeredEventUnitId() { - return currentCellTriggeredEventUnitId; + return currentCellTriggeredEventUnitId; } -void ScriptManager::setRandomGenInit(int seed) { - - random.init(seed); -} +void ScriptManager::setRandomGenInit(int seed) { random.init(seed); } int ScriptManager::getRandomGen(int minVal, int maxVal) { - return random.randRange(minVal,maxVal); + return random.randRange(minVal, maxVal); } -int ScriptManager::getWorldFrameCount() { +int ScriptManager::getWorldFrameCount() { return world->getFrameCount(); } - return world->getFrameCount(); -} +bool ScriptManager::getGameWon() const { return gameWon; } -bool ScriptManager::getGameWon() const { - - return gameWon; -} - -bool ScriptManager::getIsGameOver() const { - - return gameOver; -} +bool ScriptManager::getIsGameOver() const { return gameOver; } int ScriptManager::getLastCreatedUnitId() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return lastCreatedUnitId; + return lastCreatedUnitId; } const string &ScriptManager::getLastDeadUnitName() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return lastDeadUnitName; + return lastDeadUnitName; } int ScriptManager::getLastDeadUnitId() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return lastDeadUnitId; + return lastDeadUnitId; } int ScriptManager::getLastDeadUnitCauseOfDeath() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return lastDeadUnitCauseOfDeath; + return lastDeadUnitCauseOfDeath; } const string &ScriptManager::getLastDeadUnitKillerName() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return lastDeadUnitKillerName; + return lastDeadUnitKillerName; } int ScriptManager::getLastDeadUnitKillerId() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return lastDeadUnitKillerId; + return lastDeadUnitKillerId; } const string &ScriptManager::getLastAttackedUnitName() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return lastAttackedUnitName; + return lastAttackedUnitName; } int ScriptManager::getLastAttackedUnitId() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return lastAttackedUnitId; + return lastAttackedUnitId; } const string &ScriptManager::getLastAttackingUnitName() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return lastAttackingUnitName; + return lastAttackingUnitName; } int ScriptManager::getLastAttackingUnitId() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return lastAttackingUnitId; + return lastAttackingUnitId; } int ScriptManager::getUnitCount(int factionIndex) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return world->getUnitCount(factionIndex); + return world->getUnitCount(factionIndex); } -int ScriptManager::getUnitCountOfType(int factionIndex, const string &typeName) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +int ScriptManager::getUnitCountOfType(int factionIndex, + const string &typeName) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return world->getUnitCountOfType(factionIndex, typeName); + return world->getUnitCountOfType(factionIndex, typeName); } const string ScriptManager::getSystemMacroValue(const string &key) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return world->getSystemMacroValue(key); + return world->getSystemMacroValue(key); } const string ScriptManager::getPlayerName(int factionIndex) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return world->getPlayerName(factionIndex); + return world->getPlayerName(factionIndex); } void ScriptManager::loadScenario(const string &name, bool keepFactions) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - - world->setQueuedScenario(name,keepFactions); + world->setQueuedScenario(name, keepFactions); } -vector ScriptManager::getUnitsForFaction(int factionIndex,const string& commandTypeName, int field) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - +vector ScriptManager::getUnitsForFaction(int factionIndex, + const string &commandTypeName, + int field) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return world->getUnitsForFaction(factionIndex,commandTypeName, field); + return world->getUnitsForFaction(factionIndex, commandTypeName, field); } int ScriptManager::getUnitCurrentField(int unitId) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return world->getUnitCurrentField(unitId); + return world->getUnitCurrentField(unitId); } int ScriptManager::isFreeCellsOrHasUnit(int field, int unitId, Vec2i pos) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + Unit *unit = world->findUnitById(unitId); + if (unit == NULL) { + throw megaglest_runtime_error("unit == NULL", true); + } + int result = world->getMap()->isFreeCellsOrHasUnit( + pos, unit->getType()->getSize(), static_cast(field), unit); - Unit* unit= world->findUnitById(unitId); - if(unit == NULL) { - throw megaglest_runtime_error("unit == NULL",true); - } - int result = world->getMap()->isFreeCellsOrHasUnit(pos,unit->getType()->getSize(),static_cast(field),unit); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, + "In [%s] unitId = %d, [%s] pos [%s] field = %d result = %d\n", + __FUNCTION__, unitId, unit->getType()->getName(false).c_str(), + pos.getString().c_str(), field, result); - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s] unitId = %d, [%s] pos [%s] field = %d result = %d\n",__FUNCTION__,unitId,unit->getType()->getName(false).c_str(),pos.getString().c_str(),field,result); - - return result; + return result; } int ScriptManager::isFreeCells(int unitSize, int field, Vec2i pos) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - int result = world->getMap()->isFreeCellsOrHasUnit(pos,unitSize,static_cast(field),NULL); + int result = world->getMap()->isFreeCellsOrHasUnit( + pos, unitSize, static_cast(field), NULL); - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s] unitSize = %d, pos [%s] field = %d result = %d\n",__FUNCTION__,unitSize,pos.getString().c_str(),field,result); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, + "In [%s] unitSize = %d, pos [%s] field = %d result = %d\n", + __FUNCTION__, unitSize, pos.getString().c_str(), field, result); - return result; + return result; } int ScriptManager::getHumanFactionId() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return this->world->getThisFactionIndex(); + return this->world->getThisFactionIndex(); } -void ScriptManager::highlightUnit(int unitId, float radius, float thickness, Vec4f color) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - +void ScriptManager::highlightUnit(int unitId, float radius, float thickness, + Vec4f color) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - world->highlightUnit(unitId, radius, thickness, color); + world->highlightUnit(unitId, radius, thickness, color); } void ScriptManager::unhighlightUnit(int unitId) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - world->unhighlightUnit(unitId); + world->unhighlightUnit(unitId); } void ScriptManager::giveStopCommand(int unitId) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - world->giveStopCommand(unitId); + world->giveStopCommand(unitId); } bool ScriptManager::selectUnit(int unitId) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return world->selectUnit(unitId); + return world->selectUnit(unitId); } void ScriptManager::unselectUnit(int unitId) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - world->unselectUnit(unitId); + world->unselectUnit(unitId); } -void ScriptManager::addUnitToGroupSelection(int unitId,int groupIndex) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void ScriptManager::addUnitToGroupSelection(int unitId, int groupIndex) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - world->addUnitToGroupSelection(unitId,groupIndex); + world->addUnitToGroupSelection(unitId, groupIndex); } void ScriptManager::recallGroupSelection(int groupIndex) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - world->recallGroupSelection(groupIndex); + world->recallGroupSelection(groupIndex); } -void ScriptManager::removeUnitFromGroupSelection(int unitId,int groupIndex) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void ScriptManager::removeUnitFromGroupSelection(int unitId, int groupIndex) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - world->removeUnitFromGroupSelection(unitId,groupIndex); + world->removeUnitFromGroupSelection(unitId, groupIndex); } void ScriptManager::setAttackWarningsEnabled(bool enabled) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - world->setAttackWarningsEnabled(enabled); + world->setAttackWarningsEnabled(enabled); } bool ScriptManager::getAttackWarningsEnabled() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - return world->getAttackWarningsEnabled(); + return world->getAttackWarningsEnabled(); } void ScriptManager::registerUnitTriggerEvent(int unitId) { - UnitTriggerEventList[unitId]=utet_None; + UnitTriggerEventList[unitId] = utet_None; } void ScriptManager::unregisterUnitTriggerEvent(int unitId) { - UnitTriggerEventList.erase(unitId); + UnitTriggerEventList.erase(unitId); } int ScriptManager::getLastUnitTriggerEventUnitId() { - return lastUnitTriggerEventUnitId; + return lastUnitTriggerEventUnitId; } UnitTriggerEventType ScriptManager::getLastUnitTriggerEventType() { - return lastUnitTriggerEventType; + return lastUnitTriggerEventType; } int ScriptManager::getUnitProperty(int unitId, UnitTriggerEventType type) { - int result = -1; - - //printf("File: %s line: %d type: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,type); - - Unit *unit= world->findUnitById(unitId); - if(unit != NULL) { - switch(type) { - case utet_None: - result = -2; - break; - case utet_HPChanged: - result = unit->getHp(); - break; - case utet_EPChanged: - result = unit->getEp(); - break; - case utet_LevelChanged: - result = -3; - if(unit->getLevel() != NULL) { - result = unit->getLevel()->getKills(); - } - break; - case utet_FieldChanged: - result = unit->getCurrField(); - break; - case utet_SkillChanged: - result = -4; - if(unit->getCurrSkill() != NULL) { - result = unit->getCurrSkill()->getClass(); - } - break; - default: - result = -1000; - break; - } - } - //printf("File: %s line: %d result: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,result); - return result; -} -const string ScriptManager::getUnitPropertyName(int unitId, UnitTriggerEventType type) { - string result = ""; - Unit *unit= world->findUnitById(unitId); - if(unit != NULL) { - switch(type) { - case utet_None: - result = ""; - break; - case utet_HPChanged: - result = ""; - break; - case utet_EPChanged: - result = ""; - break; - case utet_LevelChanged: - result = ""; - if(unit->getLevel() != NULL) { - result = unit->getLevel()->getName(false); - } - break; - case utet_FieldChanged: - result = ""; - break; - case utet_SkillChanged: - result = ""; - if(unit->getCurrSkill() != NULL) { - result = unit->getCurrSkill()->getName(); - } - break; - default: - result = "???"; - break; - } - } - return result; -} - -void ScriptManager::onUnitTriggerEvent(const Unit *unit, UnitTriggerEventType event) { - //static bool inEvent = false; - //if(inEvent == true) { - // printf("\n\n!!!!!!!!!!!!!!! File: %s line: %d unit [%d - %s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,unit->getId(),unit->getType()->getName().c_str()); - // return; - //} - //inEvent = true; - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - if(UnitTriggerEventList.empty() == false) { - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - std::map::iterator iterFind = UnitTriggerEventList.find(unit->getId()); - if(iterFind != UnitTriggerEventList.end()) { - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - - lastUnitTriggerEventUnitId = unit->getId(); - lastUnitTriggerEventType = event; - - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - - luaScript.beginCall("unitTriggerEvent"); - luaScript.endCall(); - - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } - } - //inEvent = false; - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); -} - -void ScriptManager::registerDayNightEvent() { - registeredDayNightEvent = true; -} + int result = -1; + + // printf("File: %s line: %d type: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,type); + + Unit *unit = world->findUnitById(unitId); + if (unit != NULL) { + switch (type) { + case utet_None: + result = -2; + break; + case utet_HPChanged: + result = unit->getHp(); + break; + case utet_EPChanged: + result = unit->getEp(); + break; + case utet_LevelChanged: + result = -3; + if (unit->getLevel() != NULL) { + result = unit->getLevel()->getKills(); + } + break; + case utet_FieldChanged: + result = unit->getCurrField(); + break; + case utet_SkillChanged: + result = -4; + if (unit->getCurrSkill() != NULL) { + result = unit->getCurrSkill()->getClass(); + } + break; + default: + result = -1000; + break; + } + } + // printf("File: %s line: %d result: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,result); + return result; +} +const string ScriptManager::getUnitPropertyName(int unitId, + UnitTriggerEventType type) { + string result = ""; + Unit *unit = world->findUnitById(unitId); + if (unit != NULL) { + switch (type) { + case utet_None: + result = ""; + break; + case utet_HPChanged: + result = ""; + break; + case utet_EPChanged: + result = ""; + break; + case utet_LevelChanged: + result = ""; + if (unit->getLevel() != NULL) { + result = unit->getLevel()->getName(false); + } + break; + case utet_FieldChanged: + result = ""; + break; + case utet_SkillChanged: + result = ""; + if (unit->getCurrSkill() != NULL) { + result = unit->getCurrSkill()->getName(); + } + break; + default: + result = "???"; + break; + } + } + return result; +} + +void ScriptManager::onUnitTriggerEvent(const Unit *unit, + UnitTriggerEventType event) { + // static bool inEvent = false; + // if(inEvent == true) { + // printf("\n\n!!!!!!!!!!!!!!! File: %s line: %d unit [%d - + //%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,unit->getId(),unit->getType()->getName().c_str()); + // return; + // } + // inEvent = true; + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + if (UnitTriggerEventList.empty() == false) { + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + std::map::iterator iterFind = + UnitTriggerEventList.find(unit->getId()); + if (iterFind != UnitTriggerEventList.end()) { + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + + lastUnitTriggerEventUnitId = unit->getId(); + lastUnitTriggerEventType = event; + + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + + luaScript.beginCall("unitTriggerEvent"); + luaScript.endCall(); + + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + } + } + // inEvent = false; + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); +} + +void ScriptManager::registerDayNightEvent() { registeredDayNightEvent = true; } void ScriptManager::unregisterDayNightEvent() { - registeredDayNightEvent = false; + registeredDayNightEvent = false; } void ScriptManager::onDayNightTriggerEvent() { - if(registeredDayNightEvent == true) { - bool isDay = (this->getIsDayTime() == 1); - if((lastDayNightTriggerStatus != 1 && isDay == true) || - (lastDayNightTriggerStatus != 2 && isDay == false)) { - if(isDay == true) { - lastDayNightTriggerStatus = 1; - } - else { - lastDayNightTriggerStatus = 2; - } + if (registeredDayNightEvent == true) { + bool isDay = (this->getIsDayTime() == 1); + if ((lastDayNightTriggerStatus != 1 && isDay == true) || + (lastDayNightTriggerStatus != 2 && isDay == false)) { + if (isDay == true) { + lastDayNightTriggerStatus = 1; + } else { + lastDayNightTriggerStatus = 2; + } - printf("Triggering daynight event isDay: %d [%f]\n",isDay,getTimeOfDay()); + printf("Triggering daynight event isDay: %d [%f]\n", isDay, + getTimeOfDay()); - luaScript.beginCall("dayNightTriggerEvent"); - luaScript.endCall(); - } - } + luaScript.beginCall("dayNightTriggerEvent"); + luaScript.endCall(); + } + } } int ScriptManager::getIsDayTime() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - const TimeFlow *tf= world->getTimeFlow(); - if(tf == NULL) { - throw megaglest_runtime_error("#1 tf == NULL",true); - } - return tf->isDay(); + const TimeFlow *tf = world->getTimeFlow(); + if (tf == NULL) { + throw megaglest_runtime_error("#1 tf == NULL", true); + } + return tf->isDay(); } int ScriptManager::getIsNightTime() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - const TimeFlow *tf= world->getTimeFlow(); - if(tf == NULL) { - throw megaglest_runtime_error("#2 tf == NULL",true); - } - return tf->isNight(); + const TimeFlow *tf = world->getTimeFlow(); + if (tf == NULL) { + throw megaglest_runtime_error("#2 tf == NULL", true); + } + return tf->isNight(); } float ScriptManager::getTimeOfDay() { - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - - const TimeFlow *tf= world->getTimeFlow(); - if(tf == NULL) { - throw megaglest_runtime_error("#3 tf == NULL",true); - } - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - return tf->getTime(); + const TimeFlow *tf = world->getTimeFlow(); + if (tf == NULL) { + throw megaglest_runtime_error("#3 tf == NULL", true); + } + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + return tf->getTime(); } void ScriptManager::disableSpeedChange() { - if(world->getGame() == NULL) { - throw megaglest_runtime_error("#4 world->getGame() == NULL"); - } - world->getGame()->setDisableSpeedChange(true); + if (world->getGame() == NULL) { + throw megaglest_runtime_error("#4 world->getGame() == NULL"); + } + world->getGame()->setDisableSpeedChange(true); } void ScriptManager::enableSpeedChange() { - if(world->getGame() == NULL) { - throw megaglest_runtime_error("#5 world->getGame() == NULL"); - } - world->getGame()->setDisableSpeedChange(false); + if (world->getGame() == NULL) { + throw megaglest_runtime_error("#5 world->getGame() == NULL"); + } + world->getGame()->setDisableSpeedChange(false); } bool ScriptManager::getSpeedChangeEnabled() { - if(world->getGame() == NULL) { - throw megaglest_runtime_error("#6 world->getGame() == NULL"); - } - return world->getGame()->getDisableSpeedChange(); + if (world->getGame() == NULL) { + throw megaglest_runtime_error("#6 world->getGame() == NULL"); + } + return world->getGame()->getDisableSpeedChange(); } void ScriptManager::addMessageToQueue(ScriptManagerMessage msg) { - messageQueue.push_back(msg); + messageQueue.push_back(msg); } void ScriptManager::storeSaveGameData(string name, string value) { - if(LuaScript::getDebugModeEnabled() == true) printf("storeSaveGameData name [%s] value [%s]\n",name.c_str(),value.c_str()); + if (LuaScript::getDebugModeEnabled() == true) + printf("storeSaveGameData name [%s] value [%s]\n", name.c_str(), + value.c_str()); - luaSavedGameData[name] = value; + luaSavedGameData[name] = value; } string ScriptManager::loadSaveGameData(string name) { - string value = luaSavedGameData[name]; + string value = luaSavedGameData[name]; - if(LuaScript::getDebugModeEnabled() == true) printf("loadSaveGameData result name [%s] value [%s]\n",name.c_str(),value.c_str()); + if (LuaScript::getDebugModeEnabled() == true) + printf("loadSaveGameData result name [%s] value [%s]\n", name.c_str(), + value.c_str()); - return value; + return value; } ControlType ScriptManager::getFactionPlayerType(int factionIndex) { - Faction *faction = world->getFaction(factionIndex); - if(faction != NULL) { - return faction->getControlType(); - } - return ctClosed; + Faction *faction = world->getFaction(factionIndex); + if (faction != NULL) { + return faction->getControlType(); + } + return ctClosed; } -// ========================== lua callbacks =============================================== +// ========================== lua callbacks +// =============================================== -int ScriptManager::showMessage(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - thisScriptManager->showMessage(luaArguments.getString(-2), luaArguments.getString(-1)); - return luaArguments.getReturnCount(); +int ScriptManager::showMessage(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + thisScriptManager->showMessage(luaArguments.getString(-2), + luaArguments.getString(-1)); + return luaArguments.getReturnCount(); } -int ScriptManager::networkShowMessageForFaction(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); +int ScriptManager::networkShowMessageForFaction(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->networkShowMessageForFaction(luaArguments.getString(-3), luaArguments.getString(-2), luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + try { + thisScriptManager->networkShowMessageForFaction(luaArguments.getString(-3), + luaArguments.getString(-2), + luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::networkShowMessageForTeam(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); +int ScriptManager::networkShowMessageForTeam(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->networkShowMessageForTeam(luaArguments.getString(-3), luaArguments.getString(-2), luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + try { + thisScriptManager->networkShowMessageForTeam(luaArguments.getString(-3), + luaArguments.getString(-2), + luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::networkSetCameraPositionForFaction(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); +int ScriptManager::networkSetCameraPositionForFaction(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->networkSetCameraPositionForFaction(luaArguments.getInt(-2), luaArguments.getVec2i(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + try { + thisScriptManager->networkSetCameraPositionForFaction( + luaArguments.getInt(-2), luaArguments.getVec2i(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::networkSetCameraPositionForTeam(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); +int ScriptManager::networkSetCameraPositionForTeam(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->networkSetCameraPositionForTeam(luaArguments.getInt(-2), luaArguments.getVec2i(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + try { + thisScriptManager->networkSetCameraPositionForTeam( + luaArguments.getInt(-2), luaArguments.getVec2i(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } +int ScriptManager::setDisplayText(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); -int ScriptManager::setDisplayText(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - - try { - thisScriptManager->setDisplayText(luaArguments.getString(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + try { + thisScriptManager->setDisplayText(luaArguments.getString(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::addConsoleText(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); +int ScriptManager::addConsoleText(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->addConsoleText(luaArguments.getString(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + try { + thisScriptManager->addConsoleText(luaArguments.getString(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::clearDisplayText(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); +int ScriptManager::clearDisplayText(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->clearDisplayText(); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + try { + thisScriptManager->clearDisplayText(); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::setCameraPosition(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); +int ScriptManager::setCameraPosition(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->setCameraPosition(Vec2i(luaArguments.getVec2i(-1))); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + try { + thisScriptManager->setCameraPosition(Vec2i(luaArguments.getVec2i(-1))); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::shakeCamera(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); +int ScriptManager::shakeCamera(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->shakeCamera(luaArguments.getInt(-2),luaArguments.getInt(-1),false,0); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + try { + thisScriptManager->shakeCamera(luaArguments.getInt(-2), + luaArguments.getInt(-1), false, 0); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::shakeCameraOnUnit(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); +int ScriptManager::shakeCameraOnUnit(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->shakeCamera(luaArguments.getInt(-3),luaArguments.getInt(-2),true,luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + try { + thisScriptManager->shakeCamera(luaArguments.getInt(-3), + luaArguments.getInt(-2), true, + luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::createUnit(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); +int ScriptManager::createUnit(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] unit [%s] factionIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,luaArguments.getString(-3).c_str(),luaArguments.getInt(-2)); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, + "In [%s::%s Line: %d] unit [%s] factionIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + luaArguments.getString(-3).c_str(), luaArguments.getInt(-2)); - try { - thisScriptManager->createUnit( - luaArguments.getString(-3), - luaArguments.getInt(-2), - luaArguments.getVec2i(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + try { + thisScriptManager->createUnit(luaArguments.getString(-3), + luaArguments.getInt(-2), + luaArguments.getVec2i(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -void ScriptManager::error(LuaHandle* luaHandle,const megaglest_runtime_error *mgErr, const char* file, const char* function, int line){ - char szErrBuf[8096]=""; - char szErrBuf2[8096]=""; - - int luaLine=-1; - const char* luaSource=""; +void ScriptManager::error(LuaHandle *luaHandle, + const megaglest_runtime_error *mgErr, + const char *file, const char *function, int line) { + char szErrBuf[8096] = ""; + char szErrBuf2[8096] = ""; - if(luaHandle != NULL){ - lua_Debug ar; - lua_getstack(luaHandle, 1, &ar); - lua_getinfo(luaHandle, "nSl", &ar); + int luaLine = -1; + const char *luaSource = ""; - luaLine = ar.currentline; - luaSource=ar.source; + if (luaHandle != NULL) { + lua_Debug ar; + lua_getstack(luaHandle, 1, &ar); + lua_getinfo(luaHandle, "nSl", &ar); - } - snprintf(szErrBuf,8096,"in %s::%s %d ",extractFileFromDirectoryPath(file).c_str(),function,line); - snprintf(szErrBuf2,8096,"Lua: tag=<%s> line=%d ",luaSource,luaLine-1); - string sErrBuf = string("Error! The game may no longer be stable!\n\n") - + string(szErrBuf) + "\n"+ string(szErrBuf2) + "\n\n" - + string(mgErr->what()); + luaLine = ar.currentline; + luaSource = ar.source; + } + snprintf(szErrBuf, 8096, "in %s::%s %d ", + extractFileFromDirectoryPath(file).c_str(), function, line); + snprintf(szErrBuf2, 8096, "Lua: tag=<%s> line=%d ", luaSource, luaLine - 1); + string sErrBuf = string("Error! The game may no longer be stable!\n\n") + + string(szErrBuf) + "\n" + string(szErrBuf2) + "\n\n" + + string(mgErr->what()); - SystemFlags::OutputDebug(SystemFlags::debugError,sErrBuf.c_str()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,sErrBuf.c_str()); + SystemFlags::OutputDebug(SystemFlags::debugError, sErrBuf.c_str()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, sErrBuf.c_str()); - thisScriptManager->addMessageToQueue(ScriptManagerMessage(sErrBuf.c_str(), "error " + intToStr(thisScriptManager->errorCount),-1,-1,true)); - thisScriptManager->errorCount++; - thisScriptManager->onMessageBoxOk(false); + thisScriptManager->addMessageToQueue(ScriptManagerMessage( + sErrBuf.c_str(), "error " + intToStr(thisScriptManager->errorCount), -1, + -1, true)); + thisScriptManager->errorCount++; + thisScriptManager->onMessageBoxOk(false); } -int ScriptManager::createUnitNoSpacing(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] unit [%s] factionIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,luaArguments.getString(-3).c_str(),luaArguments.getInt(-2)); - - try { - thisScriptManager->createUnitNoSpacing( - luaArguments.getString(-3), - luaArguments.getInt(-2), - luaArguments.getVec2i(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} +int ScriptManager::createUnitNoSpacing(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); -int ScriptManager::destroyUnit(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, + "In [%s::%s Line: %d] unit [%s] factionIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + luaArguments.getString(-3).c_str(), luaArguments.getInt(-2)); + + try { + thisScriptManager->createUnitNoSpacing(luaArguments.getString(-3), + luaArguments.getInt(-2), + luaArguments.getVec2i(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::destroyUnit(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d] unit [%d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, luaArguments.getInt(-1)); + + try { + thisScriptManager->destroyUnit(luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::setLockedUnitForFaction(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, + "In [%s::%s Line: %d] unit [%s] factionIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + luaArguments.getString(-3).c_str(), luaArguments.getInt(-2)); + + try { + thisScriptManager->setLockedUnitForFaction( + luaArguments.getString(-3), luaArguments.getInt(-2), + (luaArguments.getInt(-1) == 0 ? false : true)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::giveKills(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d] unit [%d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, luaArguments.getInt(-1)); + + try { + thisScriptManager->giveKills(luaArguments.getInt(-2), + luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::morphToUnit(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, + "In [%s::%s Line: %d] unit [%d] morphName [%s] forceUpgrade = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + luaArguments.getInt(-3), luaArguments.getString(-2).c_str(), + luaArguments.getInt(-1)); + + try { + thisScriptManager->morphToUnit(luaArguments.getInt(-3), + luaArguments.getString(-2), + luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::moveToUnit(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d] unit [%d] dest unit [%d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, luaArguments.getInt(-2), + luaArguments.getInt(-1)); + + try { + thisScriptManager->moveToUnit(luaArguments.getInt(-2), + luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::playStaticSound(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, "In [%s::%s Line: %d] sound [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + luaArguments.getString(-1).c_str()); + + try { + thisScriptManager->playStaticSound(luaArguments.getString(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::playStreamingSound(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, "In [%s::%s Line: %d] sound [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + luaArguments.getString(-1).c_str()); + + try { + thisScriptManager->playStreamingSound(luaArguments.getString(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] unit [%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,luaArguments.getInt(-1)); +int ScriptManager::stopStreamingSound(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, "In [%s::%s Line: %d] sound [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + luaArguments.getString(-1).c_str()); + + try { + thisScriptManager->stopStreamingSound(luaArguments.getString(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::stopAllSound(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + try { + thisScriptManager->stopAllSound(); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::playStaticVideo(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, "In [%s::%s Line: %d] sound [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + luaArguments.getString(-1).c_str()); + + try { + thisScriptManager->playStaticVideo(luaArguments.getString(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::playStreamingVideo(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, "In [%s::%s Line: %d] sound [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + luaArguments.getString(-1).c_str()); + + try { + thisScriptManager->playStreamingVideo(luaArguments.getString(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::stopStreamingVideo(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, "In [%s::%s Line: %d] sound [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + luaArguments.getString(-1).c_str()); + + try { + thisScriptManager->stopStreamingVideo(luaArguments.getString(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::stopAllVideo(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + try { + thisScriptManager->stopAllVideo(); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::togglePauseGame(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d] value = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, luaArguments.getInt(-1)); + + try { + thisScriptManager->togglePauseGame(luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - try { - thisScriptManager->destroyUnit(luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + return luaArguments.getReturnCount(); +} +int ScriptManager::giveResource(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->giveResource(luaArguments.getString(-3), + luaArguments.getInt(-2), + luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::setLockedUnitForFaction(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] unit [%s] factionIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,luaArguments.getString(-3).c_str(),luaArguments.getInt(-2)); +int ScriptManager::givePositionCommand(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->givePositionCommand(luaArguments.getInt(-3), + luaArguments.getString(-2), + luaArguments.getVec2i(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - try { - thisScriptManager->setLockedUnitForFaction( - luaArguments.getString(-3), - luaArguments.getInt(-2), - (luaArguments.getInt(-1) == 0 ? false : true)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + return luaArguments.getReturnCount(); +} + +int ScriptManager::giveAttackCommand(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->giveAttackCommand(luaArguments.getInt(-2), + luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::giveProductionCommand(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->giveProductionCommand(luaArguments.getInt(-2), + luaArguments.getString(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::giveKills(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); +int ScriptManager::giveUpgradeCommand(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->giveUpgradeCommand(luaArguments.getInt(-2), + luaArguments.getString(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] unit [%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,luaArguments.getInt(-1)); +int ScriptManager::giveAttackStoppedCommand(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->giveAttackStoppedCommand(luaArguments.getInt(-3), + luaArguments.getString(-2), + luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::disableAi(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->disableAi(luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::enableAi(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->enableAi(luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::getAiEnabled(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + bool result = thisScriptManager->getAiEnabled(luaArguments.getInt(-1)); + luaArguments.returnInt(result); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::disableConsume(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->disableConsume(luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::enableConsume(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->enableConsume(luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::getConsumeEnabled(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + bool result = thisScriptManager->getConsumeEnabled(luaArguments.getInt(-1)); + luaArguments.returnInt(result); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::registerCellTriggerEventForUnitToUnit(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + int result = thisScriptManager->registerCellTriggerEventForUnitToUnit( + luaArguments.getInt(-2), luaArguments.getInt(-1)); + luaArguments.returnInt(result); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::registerCellTriggerEventForUnitToLocation( + LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + int result = thisScriptManager->registerCellTriggerEventForUnitToLocation( + luaArguments.getInt(-2), luaArguments.getVec2i(-1)); + luaArguments.returnInt(result); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::registerCellAreaTriggerEventForUnitToLocation( + LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + int result = + thisScriptManager->registerCellAreaTriggerEventForUnitToLocation( + luaArguments.getInt(-2), luaArguments.getVec4i(-1)); + luaArguments.returnInt(result); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::registerCellTriggerEventForFactionToUnit( + LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + int result = thisScriptManager->registerCellTriggerEventForFactionToUnit( + luaArguments.getInt(-2), luaArguments.getInt(-1)); + luaArguments.returnInt(result); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::registerCellTriggerEventForFactionToLocation( + LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + int result = + thisScriptManager->registerCellTriggerEventForFactionToLocation( + luaArguments.getInt(-2), luaArguments.getVec2i(-1)); + luaArguments.returnInt(result); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::registerCellAreaTriggerEventForFactionToLocation( + LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + int result = + thisScriptManager->registerCellAreaTriggerEventForFactionToLocation( + luaArguments.getInt(-2), luaArguments.getVec4i(-1)); + luaArguments.returnInt(result); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::registerCellAreaTriggerEvent(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + int result = thisScriptManager->registerCellAreaTriggerEvent( + luaArguments.getVec4i(-1)); + luaArguments.returnInt(result); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::getCellTriggerEventCount(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + int result = + thisScriptManager->getCellTriggerEventCount(luaArguments.getInt(-1)); + luaArguments.returnInt(result); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::unregisterCellTriggerEvent(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->unregisterCellTriggerEvent(luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::startTimerEvent(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + int result = thisScriptManager->startTimerEvent(); + luaArguments.returnInt(result); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::startEfficientTimerEvent(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + int result = + thisScriptManager->startEfficientTimerEvent(luaArguments.getInt(-1)); + luaArguments.returnInt(result); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::stopTimerEvent(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + int result = thisScriptManager->stopTimerEvent(luaArguments.getInt(-1)); + luaArguments.returnInt(result); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::resetTimerEvent(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + int result = thisScriptManager->resetTimerEvent(luaArguments.getInt(-1)); + luaArguments.returnInt(result); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - try { - thisScriptManager->giveKills(luaArguments.getInt(-2),luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + return luaArguments.getReturnCount(); +} + +int ScriptManager::getTimerEventSecondsElapsed(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + int result = + thisScriptManager->getTimerEventSecondsElapsed(luaArguments.getInt(-1)); + luaArguments.returnInt(result); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::morphToUnit(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); +int ScriptManager::setPlayerAsWinner(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->setPlayerAsWinner(luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] unit [%d] morphName [%s] forceUpgrade = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,luaArguments.getInt(-3),luaArguments.getString(-2).c_str(),luaArguments.getInt(-1)); + return luaArguments.getReturnCount(); +} - try { - thisScriptManager->morphToUnit(luaArguments.getInt(-3),luaArguments.getString(-2),luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::endGame(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->endGame(); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::moveToUnit(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); +int ScriptManager::startPerformanceTimer(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->startPerformanceTimer(); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] unit [%d] dest unit [%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,luaArguments.getInt(-2),luaArguments.getInt(-1)); + return luaArguments.getReturnCount(); +} - try { - thisScriptManager->moveToUnit(luaArguments.getInt(-2),luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::endPerformanceTimer(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->endPerformanceTimer(); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::playStaticSound(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] sound [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,luaArguments.getString(-1).c_str()); - - try { - thisScriptManager->playStaticSound(luaArguments.getString(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::getPerformanceTimerResults(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + Vec2i results = thisScriptManager->getPerformanceTimerResults(); + luaArguments.returnVec2i(results); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::playStreamingSound(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] sound [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,luaArguments.getString(-1).c_str()); +int ScriptManager::getStartLocation(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + Vec2i pos = thisScriptManager->getStartLocation(luaArguments.getInt(-1)); + luaArguments.returnVec2i(pos); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - try { - thisScriptManager->playStreamingSound(luaArguments.getString(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::stopStreamingSound(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] sound [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,luaArguments.getString(-1).c_str()); - - try { - thisScriptManager->stopStreamingSound(luaArguments.getString(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::getUnitPosition(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + Vec2i pos = thisScriptManager->getUnitPosition(luaArguments.getInt(-1)); + luaArguments.returnVec2i(pos); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::stopAllSound(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - try { - thisScriptManager->stopAllSound(); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::setUnitPosition(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->setUnitPosition(luaArguments.getInt(-2), + luaArguments.getVec2i(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::playStaticVideo(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] sound [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,luaArguments.getString(-1).c_str()); +int ScriptManager::addCellMarker(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->playStaticVideo(luaArguments.getString(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + try { + // printf("LUA addCellMarker --> START\n"); - return luaArguments.getReturnCount(); -} - -int ScriptManager::playStreamingVideo(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] sound [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,luaArguments.getString(-1).c_str()); + int factionIndex = luaArguments.getInt(-4); - try { - thisScriptManager->playStreamingVideo(luaArguments.getString(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + // printf("LUA addCellMarker --> START 1\n"); - return luaArguments.getReturnCount(); -} + Vec2i pos = luaArguments.getVec2i(-1); -int ScriptManager::stopStreamingVideo(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] sound [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,luaArguments.getString(-1).c_str()); + // printf("LUA addCellMarker --> START 2\n"); - try { - thisScriptManager->stopStreamingVideo(luaArguments.getString(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + string note = luaArguments.getString(-3); - return luaArguments.getReturnCount(); -} + // printf("LUA addCellMarker --> START 3\n"); -int ScriptManager::stopAllVideo(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); + string texture = luaArguments.getString(-2); - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // printf("LUA addCellMarker --> faction [%d] pos [%s] note [%s] texture + // [%s]\n",factionIndex,pos.getString().c_str(),note.c_str(),texture.c_str()); - try { - thisScriptManager->stopAllVideo(); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + thisScriptManager->addCellMarker(pos, factionIndex, note, texture); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::togglePauseGame(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] value = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,luaArguments.getInt(-1)); +int ScriptManager::removeCellMarker(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->togglePauseGame(luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + try { + int factionIndex = luaArguments.getInt(-2); + Vec2i pos = luaArguments.getVec2i(-1); - return luaArguments.getReturnCount(); -} -int ScriptManager::giveResource(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->giveResource(luaArguments.getString(-3), luaArguments.getInt(-2), luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + thisScriptManager->removeCellMarker(pos, factionIndex); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::givePositionCommand(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->givePositionCommand( - luaArguments.getInt(-3), - luaArguments.getString(-2), - luaArguments.getVec2i(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::showMarker(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); - return luaArguments.getReturnCount(); -} + try { + int flashCount = luaArguments.getInt(-5); + // printf("LUA addCellMarker --> START\n"); -int ScriptManager::giveAttackCommand(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->giveAttackCommand( - luaArguments.getInt(-2), - luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::giveProductionCommand(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->giveProductionCommand( - luaArguments.getInt(-2), - luaArguments.getString(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::giveUpgradeCommand(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->giveUpgradeCommand( - luaArguments.getInt(-2), - luaArguments.getString(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::giveAttackStoppedCommand(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->giveAttackStoppedCommand( - luaArguments.getInt(-3), - luaArguments.getString(-2), - luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::disableAi(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->disableAi(luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::enableAi(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->enableAi(luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::getAiEnabled(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - bool result = thisScriptManager->getAiEnabled(luaArguments.getInt(-1)); - luaArguments.returnInt(result); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::disableConsume(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->disableConsume(luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::enableConsume(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->enableConsume(luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::getConsumeEnabled(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - bool result = thisScriptManager->getConsumeEnabled(luaArguments.getInt(-1)); - luaArguments.returnInt(result); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::registerCellTriggerEventForUnitToUnit(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - int result = thisScriptManager->registerCellTriggerEventForUnitToUnit(luaArguments.getInt(-2),luaArguments.getInt(-1)); - luaArguments.returnInt(result); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::registerCellTriggerEventForUnitToLocation(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - int result = thisScriptManager->registerCellTriggerEventForUnitToLocation(luaArguments.getInt(-2),luaArguments.getVec2i(-1)); - luaArguments.returnInt(result); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::registerCellAreaTriggerEventForUnitToLocation(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - int result = thisScriptManager->registerCellAreaTriggerEventForUnitToLocation(luaArguments.getInt(-2),luaArguments.getVec4i(-1)); - luaArguments.returnInt(result); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::registerCellTriggerEventForFactionToUnit(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - int result = thisScriptManager->registerCellTriggerEventForFactionToUnit(luaArguments.getInt(-2),luaArguments.getInt(-1)); - luaArguments.returnInt(result); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::registerCellTriggerEventForFactionToLocation(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - int result = thisScriptManager->registerCellTriggerEventForFactionToLocation(luaArguments.getInt(-2),luaArguments.getVec2i(-1)); - luaArguments.returnInt(result); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::registerCellAreaTriggerEventForFactionToLocation(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - int result = thisScriptManager->registerCellAreaTriggerEventForFactionToLocation(luaArguments.getInt(-2),luaArguments.getVec4i(-1)); - luaArguments.returnInt(result); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::registerCellAreaTriggerEvent(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - int result = thisScriptManager->registerCellAreaTriggerEvent(luaArguments.getVec4i(-1)); - luaArguments.returnInt(result); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::getCellTriggerEventCount(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - int result = thisScriptManager->getCellTriggerEventCount(luaArguments.getInt(-1)); - luaArguments.returnInt(result); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::unregisterCellTriggerEvent(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->unregisterCellTriggerEvent(luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::startTimerEvent(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - int result = thisScriptManager->startTimerEvent(); - luaArguments.returnInt(result); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::startEfficientTimerEvent(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - int result = thisScriptManager->startEfficientTimerEvent(luaArguments.getInt(-1)); - luaArguments.returnInt(result); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::stopTimerEvent(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - int result = thisScriptManager->stopTimerEvent(luaArguments.getInt(-1)); - luaArguments.returnInt(result); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::resetTimerEvent(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - int result = thisScriptManager->resetTimerEvent(luaArguments.getInt(-1)); - luaArguments.returnInt(result); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::getTimerEventSecondsElapsed(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - int result = thisScriptManager->getTimerEventSecondsElapsed(luaArguments.getInt(-1)); - luaArguments.returnInt(result); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::setPlayerAsWinner(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->setPlayerAsWinner(luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + int factionIndex = luaArguments.getInt(-4); - return luaArguments.getReturnCount(); -} + // printf("LUA addCellMarker --> START 1\n"); -int ScriptManager::endGame(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->endGame(); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + Vec2i pos = luaArguments.getVec2i(-1); - return luaArguments.getReturnCount(); -} + // printf("LUA addCellMarker --> START 2\n"); -int ScriptManager::startPerformanceTimer(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->startPerformanceTimer(); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + string note = luaArguments.getString(-3); - return luaArguments.getReturnCount(); -} + // printf("LUA addCellMarker --> START 3\n"); -int ScriptManager::endPerformanceTimer(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->endPerformanceTimer(); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + string texture = luaArguments.getString(-2); - return luaArguments.getReturnCount(); -} + // printf("LUA addCellMarker --> faction [%d] pos [%s] note [%s] texture + // [%s]\n",factionIndex,pos.getString().c_str(),note.c_str(),texture.c_str()); -int ScriptManager::getPerformanceTimerResults(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - Vec2i results= thisScriptManager->getPerformanceTimerResults(); - luaArguments.returnVec2i(results); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + thisScriptManager->showMarker(pos, factionIndex, note, texture, flashCount); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::getStartLocation(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - Vec2i pos= thisScriptManager->getStartLocation(luaArguments.getInt(-1)); - luaArguments.returnVec2i(pos); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::getUnitFaction(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + int factionIndex = + thisScriptManager->getUnitFaction(luaArguments.getInt(-1)); + luaArguments.returnInt(factionIndex); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::getUnitPosition(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - Vec2i pos= thisScriptManager->getUnitPosition(luaArguments.getInt(-1)); - luaArguments.returnVec2i(pos); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::getUnitName(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + const string unitname = + thisScriptManager->getUnitName(luaArguments.getInt(-1)); + luaArguments.returnString(unitname); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::setUnitPosition(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->setUnitPosition(luaArguments.getInt(-2),luaArguments.getVec2i(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::getUnitDisplayName(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + const string unitname = + thisScriptManager->getUnitDisplayName(luaArguments.getInt(-1)); + luaArguments.returnString(unitname); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::addCellMarker(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - - try { - //printf("LUA addCellMarker --> START\n"); - - int factionIndex = luaArguments.getInt(-4); - - //printf("LUA addCellMarker --> START 1\n"); - - Vec2i pos = luaArguments.getVec2i(-1); - - //printf("LUA addCellMarker --> START 2\n"); +int ScriptManager::getResourceAmount(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt(thisScriptManager->getResourceAmount( + luaArguments.getString(-2), luaArguments.getInt(-1))); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - string note = luaArguments.getString(-3); - - //printf("LUA addCellMarker --> START 3\n"); - - string texture = luaArguments.getString(-2); - - //printf("LUA addCellMarker --> faction [%d] pos [%s] note [%s] texture [%s]\n",factionIndex,pos.getString().c_str(),note.c_str(),texture.c_str()); - - thisScriptManager->addCellMarker(pos,factionIndex,note,texture); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::removeCellMarker(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - - try { - int factionIndex = luaArguments.getInt(-2); - Vec2i pos = luaArguments.getVec2i(-1); +int ScriptManager::getLastCreatedUnitName(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnString(thisScriptManager->getLastCreatedUnitName()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - thisScriptManager->removeCellMarker(pos,factionIndex); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::showMarker(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - - try { - int flashCount = luaArguments.getInt(-5); - //printf("LUA addCellMarker --> START\n"); - - int factionIndex = luaArguments.getInt(-4); - - //printf("LUA addCellMarker --> START 1\n"); - - Vec2i pos = luaArguments.getVec2i(-1); - - //printf("LUA addCellMarker --> START 2\n"); - - string note = luaArguments.getString(-3); +int ScriptManager::getLastCreatedUnitId(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt(thisScriptManager->getLastCreatedUnitId()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - //printf("LUA addCellMarker --> START 3\n"); - - string texture = luaArguments.getString(-2); - - //printf("LUA addCellMarker --> faction [%d] pos [%s] note [%s] texture [%s]\n",factionIndex,pos.getString().c_str(),note.c_str(),texture.c_str()); - - thisScriptManager->showMarker(pos,factionIndex,note,texture,flashCount); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::getUnitFaction(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - int factionIndex= thisScriptManager->getUnitFaction(luaArguments.getInt(-1)); - luaArguments.returnInt(factionIndex); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::getCellTriggeredEventId(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt(thisScriptManager->getCellTriggeredEventId()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::getUnitName(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - const string unitname = thisScriptManager->getUnitName(luaArguments.getInt(-1)); - luaArguments.returnString(unitname); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::getTimerTriggeredEventId(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt(thisScriptManager->getTimerTriggeredEventId()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::getUnitDisplayName(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - const string unitname = thisScriptManager->getUnitDisplayName(luaArguments.getInt(-1)); - luaArguments.returnString(unitname); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::getCellTriggeredEventAreaEntryUnitId(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt( + thisScriptManager->getCellTriggeredEventAreaEntryUnitId()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } +int ScriptManager::getCellTriggeredEventAreaExitUnitId(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt( + thisScriptManager->getCellTriggeredEventAreaExitUnitId()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } -int ScriptManager::getResourceAmount(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getResourceAmount(luaArguments.getString(-2), luaArguments.getInt(-1))); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::getLastCreatedUnitName(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnString(thisScriptManager->getLastCreatedUnitName()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::getCellTriggeredEventUnitId(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt(thisScriptManager->getCellTriggeredEventUnitId()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::getLastCreatedUnitId(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getLastCreatedUnitId()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::setRandomGenInit(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->setRandomGenInit(luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::getCellTriggeredEventId(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getCellTriggeredEventId()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::getRandomGen(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt(thisScriptManager->getRandomGen( + luaArguments.getInt(-2), luaArguments.getInt(-1))); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::getTimerTriggeredEventId(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getTimerTriggeredEventId()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::getWorldFrameCount(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt(thisScriptManager->getWorldFrameCount()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::getCellTriggeredEventAreaEntryUnitId(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getCellTriggeredEventAreaEntryUnitId()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::getLastDeadUnitName(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnString(thisScriptManager->getLastDeadUnitName()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::getCellTriggeredEventAreaExitUnitId(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getCellTriggeredEventAreaExitUnitId()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::getLastDeadUnitId(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt(thisScriptManager->getLastDeadUnitId()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::getCellTriggeredEventUnitId(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getCellTriggeredEventUnitId()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::getLastDeadUnitCauseOfDeath(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt(thisScriptManager->getLastDeadUnitCauseOfDeath()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::setRandomGenInit(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->setRandomGenInit(luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::getLastDeadUnitKillerName(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnString(thisScriptManager->getLastDeadUnitKillerName()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::getRandomGen(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getRandomGen(luaArguments.getInt(-2),luaArguments.getInt(-1))); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::getLastDeadUnitKillerId(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt(thisScriptManager->getLastDeadUnitKillerId()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::getWorldFrameCount(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getWorldFrameCount()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::getLastAttackedUnitName(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnString(thisScriptManager->getLastAttackedUnitName()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::getLastDeadUnitName(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnString(thisScriptManager->getLastDeadUnitName()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::getLastAttackedUnitId(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt(thisScriptManager->getLastAttackedUnitId()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::getLastDeadUnitId(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getLastDeadUnitId()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::getLastAttackingUnitName(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnString(thisScriptManager->getLastAttackingUnitName()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::getLastDeadUnitCauseOfDeath(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getLastDeadUnitCauseOfDeath()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::getLastAttackingUnitId(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt(thisScriptManager->getLastAttackingUnitId()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::getSystemMacroValue(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnString( + thisScriptManager->getSystemMacroValue(luaArguments.getString(-1))); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::scenarioDir(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnString( + thisScriptManager->getSystemMacroValue("$SCENARIO_PATH")); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::getPlayerName(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnString( + thisScriptManager->getPlayerName(luaArguments.getInt(-1))); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::getUnitCount(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt( + thisScriptManager->getUnitCount(luaArguments.getInt(-1))); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::getUnitCountOfType(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt(thisScriptManager->getUnitCountOfType( + luaArguments.getInt(-2), luaArguments.getString(-1))); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::DisplayFormattedText(LuaHandle *luaHandle) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + try { + // const char *ret; + // lua_lock(luaHandle); + // luaC_checkGC(luaHandle); + + int args = lua_gettop(luaHandle); + if (lua_checkstack(luaHandle, args + 1)) { + LuaArguments luaArguments(luaHandle); + string fmt = luaArguments.getString(-args); + // va_list argList; + // va_start(argList, fmt.c_str() ); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "DisplayFormattedText args = %d!\n", args); + + const int max_args_allowed = 8; + if (args == 1) { + thisScriptManager->DisplayFormattedText(fmt.c_str()); + } else if (args == 2) { + thisScriptManager->DisplayFormattedText( + fmt.c_str(), luaArguments.getGenericData(-args + 1)); + } else if (args == 3) { + thisScriptManager->DisplayFormattedText( + fmt.c_str(), luaArguments.getGenericData(-args + 1), + luaArguments.getGenericData(-args + 2)); + } else if (args == 4) { + thisScriptManager->DisplayFormattedText( + fmt.c_str(), luaArguments.getGenericData(-args + 1), + luaArguments.getGenericData(-args + 2), + luaArguments.getGenericData(-args + 3)); + } else if (args == 5) { + thisScriptManager->DisplayFormattedText( + fmt.c_str(), luaArguments.getGenericData(-args + 1), + luaArguments.getGenericData(-args + 2), + luaArguments.getGenericData(-args + 3), + luaArguments.getGenericData(-args + 4)); + } else if (args == 6) { + thisScriptManager->DisplayFormattedText( + fmt.c_str(), luaArguments.getGenericData(-args + 1), + luaArguments.getGenericData(-args + 2), + luaArguments.getGenericData(-args + 3), + luaArguments.getGenericData(-args + 4), + luaArguments.getGenericData(-args + 5)); + } else if (args == 7) { + thisScriptManager->DisplayFormattedText( + fmt.c_str(), luaArguments.getGenericData(-args + 1), + luaArguments.getGenericData(-args + 2), + luaArguments.getGenericData(-args + 3), + luaArguments.getGenericData(-args + 4), + luaArguments.getGenericData(-args + 5), + luaArguments.getGenericData(-args + 6)); + } else if (args == max_args_allowed) { + thisScriptManager->DisplayFormattedText( + fmt.c_str(), luaArguments.getGenericData(-args + 1), + luaArguments.getGenericData(-args + 2), + luaArguments.getGenericData(-args + 3), + luaArguments.getGenericData(-args + 4), + luaArguments.getGenericData(-args + 5), + luaArguments.getGenericData(-args + 6), + luaArguments.getGenericData(-args + 7)); + } else { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "Invalid parameter count in method [%s] args = %d [argument " + "count must be between 1 and %d]", + __FUNCTION__, args, max_args_allowed); + throw megaglest_runtime_error(szBuf); + } + + // va_end(argList); + } + // lua_unlock(luaHandle); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return 1; + + /* + int args=lua_gettop(luaHandle); + if(lua_checkstack(luaHandle, args+1)) + { + va_list argList; + int i; + //lua_getfield(luaHandle, LUA_GLOBALSINDEX, "print"); + for(i = 1;i <= args; i++) { + lua_pushvalue(luaHandle, i); + } + lua_call(luaHandle, args, 0); + } + else + { + return luaL_error(luaHandle, "cannot grow stack"); + } + */ + + /* + luax_getfunction(L, mod, fn); + for (int i = 0; i < n; i++) { + lua_pushvalue(L, idxs[i]); // The arguments. + } + lua_call(L, n, 1); // Call the function, n args, one return + value. lua_replace(L, idxs[0]); // Replace the initial argument with the + new object. return 0; + */ +} + +int ScriptManager::addConsoleLangText(LuaHandle *luaHandle) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + try { + // const char *ret; + // lua_lock(luaHandle); + // luaC_checkGC(luaHandle); + + int args = lua_gettop(luaHandle); + if (lua_checkstack(luaHandle, args + 1)) { + LuaArguments luaArguments(luaHandle); + string fmt = luaArguments.getString(-args); + // va_list argList; + // va_start(argList, fmt.c_str() ); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "DisplayFormattedText args = %d!\n", args); + + const int max_args_allowed = 8; + if (args == 1) { + thisScriptManager->addConsoleLangText( + Lang::getInstance().getScenarioString(fmt).c_str()); + } else if (args == 2) { + thisScriptManager->addConsoleLangText( + Lang::getInstance().getScenarioString(fmt).c_str(), + luaArguments.getGenericData(-args + 1)); + } else if (args == 3) { + thisScriptManager->addConsoleLangText( + Lang::getInstance().getScenarioString(fmt).c_str(), + luaArguments.getGenericData(-args + 1), + luaArguments.getGenericData(-args + 2)); + } else if (args == 4) { + thisScriptManager->addConsoleLangText( + Lang::getInstance().getScenarioString(fmt).c_str(), + luaArguments.getGenericData(-args + 1), + luaArguments.getGenericData(-args + 2), + luaArguments.getGenericData(-args + 3)); + } else if (args == 5) { + thisScriptManager->addConsoleLangText( + Lang::getInstance().getScenarioString(fmt).c_str(), + luaArguments.getGenericData(-args + 1), + luaArguments.getGenericData(-args + 2), + luaArguments.getGenericData(-args + 3), + luaArguments.getGenericData(-args + 4)); + } else if (args == 6) { + thisScriptManager->addConsoleLangText( + Lang::getInstance().getScenarioString(fmt).c_str(), + luaArguments.getGenericData(-args + 1), + luaArguments.getGenericData(-args + 2), + luaArguments.getGenericData(-args + 3), + luaArguments.getGenericData(-args + 4), + luaArguments.getGenericData(-args + 5)); + } else if (args == 7) { + thisScriptManager->addConsoleLangText( + Lang::getInstance().getScenarioString(fmt).c_str(), + luaArguments.getGenericData(-args + 1), + luaArguments.getGenericData(-args + 2), + luaArguments.getGenericData(-args + 3), + luaArguments.getGenericData(-args + 4), + luaArguments.getGenericData(-args + 5), + luaArguments.getGenericData(-args + 6)); + } else if (args == max_args_allowed) { + thisScriptManager->addConsoleLangText( + Lang::getInstance().getScenarioString(fmt).c_str(), + luaArguments.getGenericData(-args + 1), + luaArguments.getGenericData(-args + 2), + luaArguments.getGenericData(-args + 3), + luaArguments.getGenericData(-args + 4), + luaArguments.getGenericData(-args + 5), + luaArguments.getGenericData(-args + 6), + luaArguments.getGenericData(-args + 7)); + } else { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "Invalid parameter count in method [%s] args = %d [argument " + "count must be between 1 and %d]", + __FUNCTION__, args, max_args_allowed); + throw megaglest_runtime_error(szBuf); + } + + // va_end(argList); + } + // lua_unlock(luaHandle); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return 1; +} + +int ScriptManager::DisplayFormattedLangText(LuaHandle *luaHandle) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + try { + // const char *ret; + // lua_lock(luaHandle); + // luaC_checkGC(luaHandle); + + int args = lua_gettop(luaHandle); + if (lua_checkstack(luaHandle, args + 1)) { + LuaArguments luaArguments(luaHandle); + string fmt = luaArguments.getString(-args); + // va_list argList; + // va_start(argList, fmt.c_str() ); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "DisplayFormattedText args = %d!\n", args); + + const int max_args_allowed = 8; + if (args == 1) { + thisScriptManager->DisplayFormattedLangText( + Lang::getInstance().getScenarioString(fmt).c_str()); + } else if (args == 2) { + thisScriptManager->DisplayFormattedLangText( + Lang::getInstance().getScenarioString(fmt).c_str(), + luaArguments.getGenericData(-args + 1)); + } else if (args == 3) { + thisScriptManager->DisplayFormattedLangText( + Lang::getInstance().getScenarioString(fmt).c_str(), + luaArguments.getGenericData(-args + 1), + luaArguments.getGenericData(-args + 2)); + } else if (args == 4) { + thisScriptManager->DisplayFormattedLangText( + Lang::getInstance().getScenarioString(fmt).c_str(), + luaArguments.getGenericData(-args + 1), + luaArguments.getGenericData(-args + 2), + luaArguments.getGenericData(-args + 3)); + } else if (args == 5) { + thisScriptManager->DisplayFormattedLangText( + Lang::getInstance().getScenarioString(fmt).c_str(), + luaArguments.getGenericData(-args + 1), + luaArguments.getGenericData(-args + 2), + luaArguments.getGenericData(-args + 3), + luaArguments.getGenericData(-args + 4)); + } else if (args == 6) { + thisScriptManager->DisplayFormattedLangText( + Lang::getInstance().getScenarioString(fmt).c_str(), + luaArguments.getGenericData(-args + 1), + luaArguments.getGenericData(-args + 2), + luaArguments.getGenericData(-args + 3), + luaArguments.getGenericData(-args + 4), + luaArguments.getGenericData(-args + 5)); + } else if (args == 7) { + thisScriptManager->DisplayFormattedLangText( + Lang::getInstance().getScenarioString(fmt).c_str(), + luaArguments.getGenericData(-args + 1), + luaArguments.getGenericData(-args + 2), + luaArguments.getGenericData(-args + 3), + luaArguments.getGenericData(-args + 4), + luaArguments.getGenericData(-args + 5), + luaArguments.getGenericData(-args + 6)); + } else if (args == max_args_allowed) { + thisScriptManager->DisplayFormattedLangText( + Lang::getInstance().getScenarioString(fmt).c_str(), + luaArguments.getGenericData(-args + 1), + luaArguments.getGenericData(-args + 2), + luaArguments.getGenericData(-args + 3), + luaArguments.getGenericData(-args + 4), + luaArguments.getGenericData(-args + 5), + luaArguments.getGenericData(-args + 6), + luaArguments.getGenericData(-args + 7)); + } else { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "Invalid parameter count in method [%s] args = %d [argument " + "count must be between 1 and %d]", + __FUNCTION__, args, max_args_allowed); + throw megaglest_runtime_error(szBuf); + } + + // va_end(argList); + } + // lua_unlock(luaHandle); + + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return 1; +} + +int ScriptManager::getGameWon(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt(thisScriptManager->getGameWon()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::getIsGameOver(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt(thisScriptManager->getIsGameOver()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::loadScenario(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->loadScenario(luaArguments.getString(-2), + luaArguments.getInt(-1) != 0); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::getUnitsForFaction(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + vector units = thisScriptManager->getUnitsForFaction( + luaArguments.getInt(-3), luaArguments.getString(-2), + luaArguments.getInt(-1)); + luaArguments.returnVectorInt(units); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::getUnitCurrentField(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt( + thisScriptManager->getUnitCurrentField(luaArguments.getInt(-1))); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::getIsUnitAlive(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt( + thisScriptManager->getIsUnitAlive(luaArguments.getInt(-1))); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::isFreeCellsOrHasUnit(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + + try { + int result = thisScriptManager->isFreeCellsOrHasUnit( + luaArguments.getInt(-3), luaArguments.getInt(-2), + luaArguments.getVec2i(-1)); - return luaArguments.getReturnCount(); -} + luaArguments.returnInt(result); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } -int ScriptManager::getLastDeadUnitKillerName(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnString(thisScriptManager->getLastDeadUnitKillerName()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::getLastDeadUnitKillerId(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getLastDeadUnitKillerId()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::isFreeCells(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); - return luaArguments.getReturnCount(); -} + try { + int result = thisScriptManager->isFreeCells(luaArguments.getInt(-3), + luaArguments.getInt(-2), + luaArguments.getVec2i(-1)); -int ScriptManager::getLastAttackedUnitName(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnString(thisScriptManager->getLastAttackedUnitName()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } + luaArguments.returnInt(result); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::getLastAttackedUnitId(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getLastAttackedUnitId()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::getHumanFactionId(LuaHandle *luaHandle) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt(thisScriptManager->getHumanFactionId()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::getLastAttackingUnitName(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnString(thisScriptManager->getLastAttackingUnitName()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::getLastAttackingUnitId(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getLastAttackingUnitId()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::getSystemMacroValue(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnString(thisScriptManager->getSystemMacroValue(luaArguments.getString(-1))); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::scenarioDir(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnString(thisScriptManager->getSystemMacroValue("$SCENARIO_PATH")); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::getPlayerName(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnString(thisScriptManager->getPlayerName(luaArguments.getInt(-1))); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::getUnitCount(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getUnitCount(luaArguments.getInt(-1))); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::getUnitCountOfType(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getUnitCountOfType(luaArguments.getInt(-2), luaArguments.getString(-1))); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::DisplayFormattedText(LuaHandle* luaHandle) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - try { - //const char *ret; - //lua_lock(luaHandle); - //luaC_checkGC(luaHandle); - - int args = lua_gettop(luaHandle); - if(lua_checkstack(luaHandle, args+1)) { - LuaArguments luaArguments(luaHandle); - string fmt = luaArguments.getString(-args); - //va_list argList; - //va_start(argList, fmt.c_str() ); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"DisplayFormattedText args = %d!\n",args); - - const int max_args_allowed = 8; - if(args == 1) { - thisScriptManager->DisplayFormattedText(fmt.c_str()); - } - else if(args == 2) { - thisScriptManager->DisplayFormattedText(fmt.c_str(), - luaArguments.getGenericData(-args+1)); - } - else if(args == 3) { - thisScriptManager->DisplayFormattedText(fmt.c_str(), - luaArguments.getGenericData(-args+1), - luaArguments.getGenericData(-args+2)); - } - else if(args == 4) { - thisScriptManager->DisplayFormattedText(fmt.c_str(), - luaArguments.getGenericData(-args+1), - luaArguments.getGenericData(-args+2), - luaArguments.getGenericData(-args+3)); - } - else if(args == 5) { - thisScriptManager->DisplayFormattedText(fmt.c_str(), - luaArguments.getGenericData(-args+1), - luaArguments.getGenericData(-args+2), - luaArguments.getGenericData(-args+3), - luaArguments.getGenericData(-args+4)); - } - else if(args == 6) { - thisScriptManager->DisplayFormattedText(fmt.c_str(), - luaArguments.getGenericData(-args+1), - luaArguments.getGenericData(-args+2), - luaArguments.getGenericData(-args+3), - luaArguments.getGenericData(-args+4), - luaArguments.getGenericData(-args+5)); - } - else if(args == 7) { - thisScriptManager->DisplayFormattedText(fmt.c_str(), - luaArguments.getGenericData(-args+1), - luaArguments.getGenericData(-args+2), - luaArguments.getGenericData(-args+3), - luaArguments.getGenericData(-args+4), - luaArguments.getGenericData(-args+5), - luaArguments.getGenericData(-args+6)); - } - else if(args == max_args_allowed) { - thisScriptManager->DisplayFormattedText(fmt.c_str(), - luaArguments.getGenericData(-args+1), - luaArguments.getGenericData(-args+2), - luaArguments.getGenericData(-args+3), - luaArguments.getGenericData(-args+4), - luaArguments.getGenericData(-args+5), - luaArguments.getGenericData(-args+6), - luaArguments.getGenericData(-args+7)); - } - else { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Invalid parameter count in method [%s] args = %d [argument count must be between 1 and %d]",__FUNCTION__,args,max_args_allowed); - throw megaglest_runtime_error(szBuf); - } - - //va_end(argList); - } - //lua_unlock(luaHandle); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return 1; - -/* - int args=lua_gettop(luaHandle); - if(lua_checkstack(luaHandle, args+1)) - { - va_list argList; - int i; - //lua_getfield(luaHandle, LUA_GLOBALSINDEX, "print"); - for(i = 1;i <= args; i++) { - lua_pushvalue(luaHandle, i); - } - lua_call(luaHandle, args, 0); - } - else - { - return luaL_error(luaHandle, "cannot grow stack"); - } -*/ - -/* - luax_getfunction(L, mod, fn); - for (int i = 0; i < n; i++) { - lua_pushvalue(L, idxs[i]); // The arguments. - } - lua_call(L, n, 1); // Call the function, n args, one return value. - lua_replace(L, idxs[0]); // Replace the initial argument with the new object. - return 0; -*/ -} - -int ScriptManager::addConsoleLangText(LuaHandle* luaHandle){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - try { - //const char *ret; - //lua_lock(luaHandle); - //luaC_checkGC(luaHandle); - - int args = lua_gettop(luaHandle); - if(lua_checkstack(luaHandle, args+1)) { - LuaArguments luaArguments(luaHandle); - string fmt = luaArguments.getString(-args); - //va_list argList; - //va_start(argList, fmt.c_str() ); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"DisplayFormattedText args = %d!\n",args); - - const int max_args_allowed = 8; - if(args == 1) { - thisScriptManager->addConsoleLangText(Lang::getInstance().getScenarioString(fmt).c_str()); - } - else if(args == 2) { - thisScriptManager->addConsoleLangText(Lang::getInstance().getScenarioString(fmt).c_str(), - luaArguments.getGenericData(-args+1)); - } - else if(args == 3) { - thisScriptManager->addConsoleLangText(Lang::getInstance().getScenarioString(fmt).c_str(), - luaArguments.getGenericData(-args+1), - luaArguments.getGenericData(-args+2)); - } - else if(args == 4) { - thisScriptManager->addConsoleLangText(Lang::getInstance().getScenarioString(fmt).c_str(), - luaArguments.getGenericData(-args+1), - luaArguments.getGenericData(-args+2), - luaArguments.getGenericData(-args+3)); - } - else if(args == 5) { - thisScriptManager->addConsoleLangText(Lang::getInstance().getScenarioString(fmt).c_str(), - luaArguments.getGenericData(-args+1), - luaArguments.getGenericData(-args+2), - luaArguments.getGenericData(-args+3), - luaArguments.getGenericData(-args+4)); - } - else if(args == 6) { - thisScriptManager->addConsoleLangText(Lang::getInstance().getScenarioString(fmt).c_str(), - luaArguments.getGenericData(-args+1), - luaArguments.getGenericData(-args+2), - luaArguments.getGenericData(-args+3), - luaArguments.getGenericData(-args+4), - luaArguments.getGenericData(-args+5)); - } - else if(args == 7) { - thisScriptManager->addConsoleLangText(Lang::getInstance().getScenarioString(fmt).c_str(), - luaArguments.getGenericData(-args+1), - luaArguments.getGenericData(-args+2), - luaArguments.getGenericData(-args+3), - luaArguments.getGenericData(-args+4), - luaArguments.getGenericData(-args+5), - luaArguments.getGenericData(-args+6)); - } - else if(args == max_args_allowed) { - thisScriptManager->addConsoleLangText(Lang::getInstance().getScenarioString(fmt).c_str(), - luaArguments.getGenericData(-args+1), - luaArguments.getGenericData(-args+2), - luaArguments.getGenericData(-args+3), - luaArguments.getGenericData(-args+4), - luaArguments.getGenericData(-args+5), - luaArguments.getGenericData(-args+6), - luaArguments.getGenericData(-args+7)); - } - else { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Invalid parameter count in method [%s] args = %d [argument count must be between 1 and %d]",__FUNCTION__,args,max_args_allowed); - throw megaglest_runtime_error(szBuf); - } - - //va_end(argList); - } - //lua_unlock(luaHandle); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return 1; -} - -int ScriptManager::DisplayFormattedLangText(LuaHandle* luaHandle) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - try { - //const char *ret; - //lua_lock(luaHandle); - //luaC_checkGC(luaHandle); - - int args = lua_gettop(luaHandle); - if(lua_checkstack(luaHandle, args+1)) { - LuaArguments luaArguments(luaHandle); - string fmt = luaArguments.getString(-args); - //va_list argList; - //va_start(argList, fmt.c_str() ); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"DisplayFormattedText args = %d!\n",args); - - const int max_args_allowed = 8; - if(args == 1) { - thisScriptManager->DisplayFormattedLangText(Lang::getInstance().getScenarioString(fmt).c_str()); - } - else if(args == 2) { - thisScriptManager->DisplayFormattedLangText(Lang::getInstance().getScenarioString(fmt).c_str(), - luaArguments.getGenericData(-args+1)); - } - else if(args == 3) { - thisScriptManager->DisplayFormattedLangText(Lang::getInstance().getScenarioString(fmt).c_str(), - luaArguments.getGenericData(-args+1), - luaArguments.getGenericData(-args+2)); - } - else if(args == 4) { - thisScriptManager->DisplayFormattedLangText(Lang::getInstance().getScenarioString(fmt).c_str(), - luaArguments.getGenericData(-args+1), - luaArguments.getGenericData(-args+2), - luaArguments.getGenericData(-args+3)); - } - else if(args == 5) { - thisScriptManager->DisplayFormattedLangText(Lang::getInstance().getScenarioString(fmt).c_str(), - luaArguments.getGenericData(-args+1), - luaArguments.getGenericData(-args+2), - luaArguments.getGenericData(-args+3), - luaArguments.getGenericData(-args+4)); - } - else if(args == 6) { - thisScriptManager->DisplayFormattedLangText(Lang::getInstance().getScenarioString(fmt).c_str(), - luaArguments.getGenericData(-args+1), - luaArguments.getGenericData(-args+2), - luaArguments.getGenericData(-args+3), - luaArguments.getGenericData(-args+4), - luaArguments.getGenericData(-args+5)); - } - else if(args == 7) { - thisScriptManager->DisplayFormattedLangText(Lang::getInstance().getScenarioString(fmt).c_str(), - luaArguments.getGenericData(-args+1), - luaArguments.getGenericData(-args+2), - luaArguments.getGenericData(-args+3), - luaArguments.getGenericData(-args+4), - luaArguments.getGenericData(-args+5), - luaArguments.getGenericData(-args+6)); - } - else if(args == max_args_allowed) { - thisScriptManager->DisplayFormattedLangText(Lang::getInstance().getScenarioString(fmt).c_str(), - luaArguments.getGenericData(-args+1), - luaArguments.getGenericData(-args+2), - luaArguments.getGenericData(-args+3), - luaArguments.getGenericData(-args+4), - luaArguments.getGenericData(-args+5), - luaArguments.getGenericData(-args+6), - luaArguments.getGenericData(-args+7)); - } - else { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Invalid parameter count in method [%s] args = %d [argument count must be between 1 and %d]",__FUNCTION__,args,max_args_allowed); - throw megaglest_runtime_error(szBuf); - } - - //va_end(argList); - } - //lua_unlock(luaHandle); - - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return 1; -} - -int ScriptManager::getGameWon(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getGameWon()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::getIsGameOver(LuaHandle* luaHandle){ - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getIsGameOver()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::loadScenario(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->loadScenario(luaArguments.getString(-2),luaArguments.getInt(-1) != 0); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::getUnitsForFaction(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - vector units= thisScriptManager->getUnitsForFaction(luaArguments.getInt(-3),luaArguments.getString(-2), luaArguments.getInt(-1)); - luaArguments.returnVectorInt(units); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); - -} - -int ScriptManager::getUnitCurrentField(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getUnitCurrentField(luaArguments.getInt(-1))); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::getIsUnitAlive(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getIsUnitAlive(luaArguments.getInt(-1))); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::isFreeCellsOrHasUnit(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - - try { - int result= thisScriptManager->isFreeCellsOrHasUnit( - luaArguments.getInt(-3), - luaArguments.getInt(-2), - luaArguments.getVec2i(-1)); - - luaArguments.returnInt(result); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::highlightUnit(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->highlightUnit( + luaArguments.getInt(-4), luaArguments.getFloat(-3), + luaArguments.getFloat(-2), luaArguments.getVec4f(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::isFreeCells(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); +int ScriptManager::unhighlightUnit(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->unhighlightUnit(luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - try { - int result= thisScriptManager->isFreeCells( - luaArguments.getInt(-3), - luaArguments.getInt(-2), - luaArguments.getVec2i(-1)); - - luaArguments.returnInt(result); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::getHumanFactionId(LuaHandle* luaHandle) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getHumanFactionId()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::giveStopCommand(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->giveStopCommand(luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::highlightUnit(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->highlightUnit(luaArguments.getInt(-4), luaArguments.getFloat(-3), luaArguments.getFloat(-2), luaArguments.getVec4f(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::selectUnit(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt( + thisScriptManager->selectUnit(luaArguments.getInt(-1))); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::unhighlightUnit(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->unhighlightUnit(luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::unselectUnit(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->unselectUnit(luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } -int ScriptManager::giveStopCommand(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->giveStopCommand(luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } +int ScriptManager::addUnitToGroupSelection(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->addUnitToGroupSelection(luaArguments.getInt(-2), + luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } - return luaArguments.getReturnCount(); + return luaArguments.getReturnCount(); } - -int ScriptManager::selectUnit(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->selectUnit(luaArguments.getInt(-1))); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::unselectUnit(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->unselectUnit(luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::addUnitToGroupSelection(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->addUnitToGroupSelection(luaArguments.getInt(-2),luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::recallGroupSelection(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->recallGroupSelection(luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::removeUnitFromGroupSelection(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->removeUnitFromGroupSelection(luaArguments.getInt(-2),luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::setAttackWarningsEnabled(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->setAttackWarningsEnabled((luaArguments.getInt(-1) == 0 ? false : true)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} -int ScriptManager::getAttackWarningsEnabled(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getAttackWarningsEnabled()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::getIsDayTime(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getIsDayTime()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} -int ScriptManager::getIsNightTime(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getIsNightTime()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} -int ScriptManager::getTimeOfDay(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnFloat(thisScriptManager->getTimeOfDay()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::registerDayNightEvent(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->registerDayNightEvent(); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} -int ScriptManager::unregisterDayNightEvent(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->unregisterDayNightEvent(); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::registerUnitTriggerEvent(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->registerUnitTriggerEvent(luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} -int ScriptManager::unregisterUnitTriggerEvent(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->unregisterUnitTriggerEvent(luaArguments.getInt(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} -int ScriptManager::getLastUnitTriggerEventUnitId(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getLastUnitTriggerEventUnitId()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} -int ScriptManager::getLastUnitTriggerEventType(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(static_cast(thisScriptManager->getLastUnitTriggerEventType())); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::getUnitProperty(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - int value = thisScriptManager->getUnitProperty(luaArguments.getInt(-2),static_cast(luaArguments.getInt(-1))); - luaArguments.returnInt(value); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} -int ScriptManager::getUnitPropertyName(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - const string unitname = thisScriptManager->getUnitPropertyName(luaArguments.getInt(-2),static_cast(luaArguments.getInt(-1))); - luaArguments.returnString(unitname); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::disableSpeedChange(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->disableSpeedChange(); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} -int ScriptManager::enableSpeedChange(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->enableSpeedChange(); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} -int ScriptManager::getSpeedChangeEnabled(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getSpeedChangeEnabled()); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::storeSaveGameData(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - thisScriptManager->storeSaveGameData(luaArguments.getString(-2),luaArguments.getString(-1)); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::loadSaveGameData(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnString(thisScriptManager->loadSaveGameData(luaArguments.getString(-1))); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); -} - -int ScriptManager::getFactionPlayerType(LuaHandle* luaHandle) { - LuaArguments luaArguments(luaHandle); - try { - luaArguments.returnInt(thisScriptManager->getFactionPlayerType(luaArguments.getInt(-1))); - } - catch(const megaglest_runtime_error &ex) { - error(luaHandle,&ex,__FILE__,__FUNCTION__,__LINE__); - } - - return luaArguments.getReturnCount(); - + +int ScriptManager::recallGroupSelection(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->recallGroupSelection(luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::removeUnitFromGroupSelection(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->removeUnitFromGroupSelection(luaArguments.getInt(-2), + luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::setAttackWarningsEnabled(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->setAttackWarningsEnabled( + (luaArguments.getInt(-1) == 0 ? false : true)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} +int ScriptManager::getAttackWarningsEnabled(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt(thisScriptManager->getAttackWarningsEnabled()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::getIsDayTime(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt(thisScriptManager->getIsDayTime()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} +int ScriptManager::getIsNightTime(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt(thisScriptManager->getIsNightTime()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} +int ScriptManager::getTimeOfDay(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnFloat(thisScriptManager->getTimeOfDay()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::registerDayNightEvent(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->registerDayNightEvent(); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} +int ScriptManager::unregisterDayNightEvent(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->unregisterDayNightEvent(); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::registerUnitTriggerEvent(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->registerUnitTriggerEvent(luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} +int ScriptManager::unregisterUnitTriggerEvent(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->unregisterUnitTriggerEvent(luaArguments.getInt(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} +int ScriptManager::getLastUnitTriggerEventUnitId(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt(thisScriptManager->getLastUnitTriggerEventUnitId()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} +int ScriptManager::getLastUnitTriggerEventType(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt( + static_cast(thisScriptManager->getLastUnitTriggerEventType())); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::getUnitProperty(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + int value = thisScriptManager->getUnitProperty( + luaArguments.getInt(-2), + static_cast(luaArguments.getInt(-1))); + luaArguments.returnInt(value); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} +int ScriptManager::getUnitPropertyName(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + const string unitname = thisScriptManager->getUnitPropertyName( + luaArguments.getInt(-2), + static_cast(luaArguments.getInt(-1))); + luaArguments.returnString(unitname); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::disableSpeedChange(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->disableSpeedChange(); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} +int ScriptManager::enableSpeedChange(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->enableSpeedChange(); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} +int ScriptManager::getSpeedChangeEnabled(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt(thisScriptManager->getSpeedChangeEnabled()); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::storeSaveGameData(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + thisScriptManager->storeSaveGameData(luaArguments.getString(-2), + luaArguments.getString(-1)); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::loadSaveGameData(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnString( + thisScriptManager->loadSaveGameData(luaArguments.getString(-1))); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); +} + +int ScriptManager::getFactionPlayerType(LuaHandle *luaHandle) { + LuaArguments luaArguments(luaHandle); + try { + luaArguments.returnInt( + thisScriptManager->getFactionPlayerType(luaArguments.getInt(-1))); + } catch (const megaglest_runtime_error &ex) { + error(luaHandle, &ex, __FILE__, __FUNCTION__, __LINE__); + } + + return luaArguments.getReturnCount(); } void ScriptManager::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *scriptManagerNode = rootNode->addChild("ScriptManager"); - - //lua -// string code; - scriptManagerNode->addAttribute("code",code, mapTagReplacements); -// LuaScript luaScript; - - luaScript.beginCall("onSave"); - luaScript.endCall(); - - if(LuaScript::getDebugModeEnabled() == true) printf("After onSave luaSavedGameData.size() = %d\n",(int)luaSavedGameData.size()); - for(std::map::iterator iterMap = luaSavedGameData.begin(); - iterMap != luaSavedGameData.end(); ++iterMap) { - - XmlNode *savedGameDataItemNode = scriptManagerNode->addChild("SavedGameDataItem"); - - savedGameDataItemNode->addAttribute("key",iterMap->first, mapTagReplacements); - savedGameDataItemNode->addAttribute("value",iterMap->second, mapTagReplacements); - } - -// //world -// World *world; -// GameCamera *gameCamera; -// -// //misc -// MessageQueue messageQueue; - for(std::list::iterator it = messageQueue.begin(); it != messageQueue.end(); ++it) { - (*it).saveGame(scriptManagerNode); - } - - //printf("==== ScriptManager Savegame messageBox [%d][%s][%s] displayText [%s]\n",messageBox.getEnabled(),messageBox.getText().c_str(),messageBox.getHeader().c_str(),displayText.c_str()); - -// GraphicMessageBox messageBox; - scriptManagerNode->addAttribute("messageBox_enabled",intToStr(messageBox.getEnabled()), mapTagReplacements); - scriptManagerNode->addAttribute("messageBox_text",messageBox.getText(), mapTagReplacements); - scriptManagerNode->addAttribute("messageBox_header",messageBox.getHeader(), mapTagReplacements); - -// string displayText; - scriptManagerNode->addAttribute("displayText",displayText, mapTagReplacements); -// -// //last created unit -// string lastCreatedUnitName; - scriptManagerNode->addAttribute("lastCreatedUnitName",lastCreatedUnitName, mapTagReplacements); -// int lastCreatedUnitId; - scriptManagerNode->addAttribute("lastCreatedUnitId",intToStr(lastCreatedUnitId), mapTagReplacements); -// -// //last dead unit -// string lastDeadUnitName; - scriptManagerNode->addAttribute("lastDeadUnitName",lastDeadUnitName, mapTagReplacements); -// int lastDeadUnitId; - scriptManagerNode->addAttribute("lastDeadUnitId",intToStr(lastDeadUnitId), mapTagReplacements); -// int lastDeadUnitCauseOfDeath; - scriptManagerNode->addAttribute("lastDeadUnitCauseOfDeath",intToStr(lastDeadUnitCauseOfDeath), mapTagReplacements); -// -// //last dead unit's killer -// string lastDeadUnitKillerName; - scriptManagerNode->addAttribute("lastDeadUnitKillerName",lastDeadUnitKillerName, mapTagReplacements); -// int lastDeadUnitKillerId; - scriptManagerNode->addAttribute("lastDeadUnitKillerId",intToStr(lastDeadUnitKillerId), mapTagReplacements); -// -// //last attacked unit -// string lastAttackedUnitName; - scriptManagerNode->addAttribute("lastAttackedUnitName",lastAttackedUnitName, mapTagReplacements); -// int lastAttackedUnitId; - scriptManagerNode->addAttribute("lastAttackedUnitId",intToStr(lastAttackedUnitId), mapTagReplacements); -// -// //last attacking unit -// string lastAttackingUnitName; - scriptManagerNode->addAttribute("lastAttackingUnitName",lastAttackingUnitName, mapTagReplacements); -// int lastAttackingUnitId; - scriptManagerNode->addAttribute("lastAttackingUnitId",intToStr(lastAttackingUnitId), mapTagReplacements); -// -// // end game state -// bool gameOver; - scriptManagerNode->addAttribute("gameOver",intToStr(gameOver), mapTagReplacements); -// bool gameWon; - scriptManagerNode->addAttribute("gameWon",intToStr(gameWon), mapTagReplacements); -// PlayerModifiers playerModifiers[GameConstants::maxPlayers]; - for(unsigned int i = 0; i < (unsigned int)GameConstants::maxPlayers; ++i) { - PlayerModifiers &player = playerModifiers[i]; - player.saveGame(scriptManagerNode); - } -// int currentTimerTriggeredEventId; - scriptManagerNode->addAttribute("currentTimerTriggeredEventId",intToStr(currentTimerTriggeredEventId), mapTagReplacements); -// int currentCellTriggeredEventId; - scriptManagerNode->addAttribute("currentCellTriggeredEventId",intToStr(currentCellTriggeredEventId), mapTagReplacements); -// int currentEventId; - scriptManagerNode->addAttribute("currentEventId",intToStr(currentEventId), mapTagReplacements); -// std::map CellTriggerEventList; - for(std::map::iterator iterMap = CellTriggerEventList.begin(); - iterMap != CellTriggerEventList.end(); ++iterMap) { - XmlNode *cellTriggerEventListNode = scriptManagerNode->addChild("CellTriggerEventList"); - - cellTriggerEventListNode->addAttribute("key",intToStr(iterMap->first), mapTagReplacements); - iterMap->second.saveGame(cellTriggerEventListNode); - } -// std::map TimerTriggerEventList; - for(std::map::iterator iterMap = TimerTriggerEventList.begin(); - iterMap != TimerTriggerEventList.end(); ++iterMap) { - XmlNode *timerTriggerEventListNode = scriptManagerNode->addChild("TimerTriggerEventList"); - - timerTriggerEventListNode->addAttribute("key",intToStr(iterMap->first), mapTagReplacements); - iterMap->second.saveGame(timerTriggerEventListNode); - } - -// bool inCellTriggerEvent; - scriptManagerNode->addAttribute("inCellTriggerEvent",intToStr(inCellTriggerEvent), mapTagReplacements); -// std::vector unRegisterCellTriggerEventList; - for(unsigned int i = 0; i < unRegisterCellTriggerEventList.size(); ++i) { - XmlNode *unRegisterCellTriggerEventListNode = scriptManagerNode->addChild("unRegisterCellTriggerEventList"); - unRegisterCellTriggerEventListNode->addAttribute("eventId",intToStr(unRegisterCellTriggerEventList[i]), mapTagReplacements); - } - - scriptManagerNode->addAttribute("registeredDayNightEvent",intToStr(registeredDayNightEvent), mapTagReplacements); - scriptManagerNode->addAttribute("lastDayNightTriggerStatus",intToStr(lastDayNightTriggerStatus), mapTagReplacements); - - for(std::map::iterator iterMap = UnitTriggerEventList.begin(); - iterMap != UnitTriggerEventList.end(); ++iterMap) { - XmlNode *unitTriggerEventListNode = scriptManagerNode->addChild("UnitTriggerEventList"); - - unitTriggerEventListNode->addAttribute("unitId",intToStr(iterMap->first), mapTagReplacements); - unitTriggerEventListNode->addAttribute("eventType",intToStr(iterMap->second), mapTagReplacements); - } - scriptManagerNode->addAttribute("lastUnitTriggerEventUnitId",intToStr(lastUnitTriggerEventUnitId), mapTagReplacements); - scriptManagerNode->addAttribute("lastUnitTriggerEventType",intToStr(lastUnitTriggerEventType), mapTagReplacements); - - luaScript.saveGame(scriptManagerNode); + std::map mapTagReplacements; + XmlNode *scriptManagerNode = rootNode->addChild("ScriptManager"); + + // lua + // string code; + scriptManagerNode->addAttribute("code", code, mapTagReplacements); + // LuaScript luaScript; + + luaScript.beginCall("onSave"); + luaScript.endCall(); + + if (LuaScript::getDebugModeEnabled() == true) + printf("After onSave luaSavedGameData.size() = %d\n", + (int)luaSavedGameData.size()); + for (std::map::iterator iterMap = luaSavedGameData.begin(); + iterMap != luaSavedGameData.end(); ++iterMap) { + + XmlNode *savedGameDataItemNode = + scriptManagerNode->addChild("SavedGameDataItem"); + + savedGameDataItemNode->addAttribute("key", iterMap->first, + mapTagReplacements); + savedGameDataItemNode->addAttribute("value", iterMap->second, + mapTagReplacements); + } + + // //world + // World *world; + // GameCamera *gameCamera; + // + // //misc + // MessageQueue messageQueue; + for (std::list::iterator it = messageQueue.begin(); + it != messageQueue.end(); ++it) { + (*it).saveGame(scriptManagerNode); + } + + // printf("==== ScriptManager Savegame messageBox [%d][%s][%s] displayText + // [%s]\n",messageBox.getEnabled(),messageBox.getText().c_str(),messageBox.getHeader().c_str(),displayText.c_str()); + + // GraphicMessageBox messageBox; + scriptManagerNode->addAttribute("messageBox_enabled", + intToStr(messageBox.getEnabled()), + mapTagReplacements); + scriptManagerNode->addAttribute("messageBox_text", messageBox.getText(), + mapTagReplacements); + scriptManagerNode->addAttribute("messageBox_header", messageBox.getHeader(), + mapTagReplacements); + + // string displayText; + scriptManagerNode->addAttribute("displayText", displayText, + mapTagReplacements); + // + // //last created unit + // string lastCreatedUnitName; + scriptManagerNode->addAttribute("lastCreatedUnitName", lastCreatedUnitName, + mapTagReplacements); + // int lastCreatedUnitId; + scriptManagerNode->addAttribute( + "lastCreatedUnitId", intToStr(lastCreatedUnitId), mapTagReplacements); + // + // //last dead unit + // string lastDeadUnitName; + scriptManagerNode->addAttribute("lastDeadUnitName", lastDeadUnitName, + mapTagReplacements); + // int lastDeadUnitId; + scriptManagerNode->addAttribute("lastDeadUnitId", intToStr(lastDeadUnitId), + mapTagReplacements); + // int lastDeadUnitCauseOfDeath; + scriptManagerNode->addAttribute("lastDeadUnitCauseOfDeath", + intToStr(lastDeadUnitCauseOfDeath), + mapTagReplacements); + // + // //last dead unit's killer + // string lastDeadUnitKillerName; + scriptManagerNode->addAttribute("lastDeadUnitKillerName", + lastDeadUnitKillerName, mapTagReplacements); + // int lastDeadUnitKillerId; + scriptManagerNode->addAttribute("lastDeadUnitKillerId", + intToStr(lastDeadUnitKillerId), + mapTagReplacements); + // + // //last attacked unit + // string lastAttackedUnitName; + scriptManagerNode->addAttribute("lastAttackedUnitName", lastAttackedUnitName, + mapTagReplacements); + // int lastAttackedUnitId; + scriptManagerNode->addAttribute( + "lastAttackedUnitId", intToStr(lastAttackedUnitId), mapTagReplacements); + // + // //last attacking unit + // string lastAttackingUnitName; + scriptManagerNode->addAttribute("lastAttackingUnitName", + lastAttackingUnitName, mapTagReplacements); + // int lastAttackingUnitId; + scriptManagerNode->addAttribute( + "lastAttackingUnitId", intToStr(lastAttackingUnitId), mapTagReplacements); + // + // // end game state + // bool gameOver; + scriptManagerNode->addAttribute("gameOver", intToStr(gameOver), + mapTagReplacements); + // bool gameWon; + scriptManagerNode->addAttribute("gameWon", intToStr(gameWon), + mapTagReplacements); + // PlayerModifiers playerModifiers[GameConstants::maxPlayers]; + for (unsigned int i = 0; i < (unsigned int)GameConstants::maxPlayers; ++i) { + PlayerModifiers &player = playerModifiers[i]; + player.saveGame(scriptManagerNode); + } + // int currentTimerTriggeredEventId; + scriptManagerNode->addAttribute("currentTimerTriggeredEventId", + intToStr(currentTimerTriggeredEventId), + mapTagReplacements); + // int currentCellTriggeredEventId; + scriptManagerNode->addAttribute("currentCellTriggeredEventId", + intToStr(currentCellTriggeredEventId), + mapTagReplacements); + // int currentEventId; + scriptManagerNode->addAttribute("currentEventId", intToStr(currentEventId), + mapTagReplacements); + // std::map CellTriggerEventList; + for (std::map::iterator iterMap = + CellTriggerEventList.begin(); + iterMap != CellTriggerEventList.end(); ++iterMap) { + XmlNode *cellTriggerEventListNode = + scriptManagerNode->addChild("CellTriggerEventList"); + + cellTriggerEventListNode->addAttribute("key", intToStr(iterMap->first), + mapTagReplacements); + iterMap->second.saveGame(cellTriggerEventListNode); + } + // std::map TimerTriggerEventList; + for (std::map::iterator iterMap = + TimerTriggerEventList.begin(); + iterMap != TimerTriggerEventList.end(); ++iterMap) { + XmlNode *timerTriggerEventListNode = + scriptManagerNode->addChild("TimerTriggerEventList"); + + timerTriggerEventListNode->addAttribute("key", intToStr(iterMap->first), + mapTagReplacements); + iterMap->second.saveGame(timerTriggerEventListNode); + } + + // bool inCellTriggerEvent; + scriptManagerNode->addAttribute( + "inCellTriggerEvent", intToStr(inCellTriggerEvent), mapTagReplacements); + // std::vector unRegisterCellTriggerEventList; + for (unsigned int i = 0; i < unRegisterCellTriggerEventList.size(); ++i) { + XmlNode *unRegisterCellTriggerEventListNode = + scriptManagerNode->addChild("unRegisterCellTriggerEventList"); + unRegisterCellTriggerEventListNode->addAttribute( + "eventId", intToStr(unRegisterCellTriggerEventList[i]), + mapTagReplacements); + } + + scriptManagerNode->addAttribute("registeredDayNightEvent", + intToStr(registeredDayNightEvent), + mapTagReplacements); + scriptManagerNode->addAttribute("lastDayNightTriggerStatus", + intToStr(lastDayNightTriggerStatus), + mapTagReplacements); + + for (std::map::iterator iterMap = + UnitTriggerEventList.begin(); + iterMap != UnitTriggerEventList.end(); ++iterMap) { + XmlNode *unitTriggerEventListNode = + scriptManagerNode->addChild("UnitTriggerEventList"); + + unitTriggerEventListNode->addAttribute("unitId", intToStr(iterMap->first), + mapTagReplacements); + unitTriggerEventListNode->addAttribute( + "eventType", intToStr(iterMap->second), mapTagReplacements); + } + scriptManagerNode->addAttribute("lastUnitTriggerEventUnitId", + intToStr(lastUnitTriggerEventUnitId), + mapTagReplacements); + scriptManagerNode->addAttribute("lastUnitTriggerEventType", + intToStr(lastUnitTriggerEventType), + mapTagReplacements); + + luaScript.saveGame(scriptManagerNode); } void ScriptManager::loadGame(const XmlNode *rootNode) { - const XmlNode *scriptManagerNode = rootNode->getChild("ScriptManager"); - -// string code; - code = scriptManagerNode->getAttribute("code")->getValue(); -// LuaScript luaScript; - - vector savedGameDataItemNodeList = scriptManagerNode->getChildList("SavedGameDataItem"); - - if(LuaScript::getDebugModeEnabled() == true) printf("In loadGame savedGameDataItemNodeList.size() = %d\n",(int)savedGameDataItemNodeList.size()); - - for(unsigned int i = 0; i < savedGameDataItemNodeList.size(); ++i) { - XmlNode *node = savedGameDataItemNodeList[i]; - string key = node->getAttribute("key")->getValue(); - string value = node->getAttribute("value")->getValue(); - - luaSavedGameData[key] = value; - } - -// //world -// World *world; -// GameCamera *gameCamera; -// -// //misc -// MessageQueue messageQueue; - messageQueue.clear(); - vector messageQueueNodeList = scriptManagerNode->getChildList("ScriptManagerMessage"); - for(unsigned int i = 0; i < messageQueueNodeList.size(); ++i) { - XmlNode *node = messageQueueNodeList[i]; - ScriptManagerMessage msg; - msg.loadGame(node); - messageQueue.push_back(msg); - } - -// GraphicMessageBox messageBox; - messageBox.setEnabled(scriptManagerNode->getAttribute("messageBox_enabled")->getIntValue() != 0); - messageBox.setText(scriptManagerNode->getAttribute("messageBox_text")->getValue()); - messageBox.setHeader(scriptManagerNode->getAttribute("messageBox_header")->getValue()); - -// string displayText; - displayText = scriptManagerNode->getAttribute("displayText")->getValue(); -// -// //last created unit -// string lastCreatedUnitName; - lastCreatedUnitName = scriptManagerNode->getAttribute("lastCreatedUnitName")->getValue(); -// int lastCreatedUnitId; - lastCreatedUnitId = scriptManagerNode->getAttribute("lastCreatedUnitId")->getIntValue(); -// -// //last dead unit -// string lastDeadUnitName; - lastDeadUnitName = scriptManagerNode->getAttribute("lastDeadUnitName")->getValue(); -// int lastDeadUnitId; - lastDeadUnitId = scriptManagerNode->getAttribute("lastDeadUnitId")->getIntValue(); -// int lastDeadUnitCauseOfDeath; - lastDeadUnitCauseOfDeath = scriptManagerNode->getAttribute("lastDeadUnitCauseOfDeath")->getIntValue(); -// -// //last dead unit's killer -// string lastDeadUnitKillerName; - lastDeadUnitKillerName = scriptManagerNode->getAttribute("lastDeadUnitKillerName")->getValue(); -// int lastDeadUnitKillerId; - lastDeadUnitKillerId = scriptManagerNode->getAttribute("lastDeadUnitKillerId")->getIntValue(); -// -// //last attacked unit -// string lastAttackedUnitName; - lastAttackedUnitName = scriptManagerNode->getAttribute("lastAttackedUnitName")->getValue(); -// int lastAttackedUnitId; - lastAttackedUnitId = scriptManagerNode->getAttribute("lastAttackedUnitId")->getIntValue(); -// -// //last attacking unit -// string lastAttackingUnitName; - lastAttackingUnitName = scriptManagerNode->getAttribute("lastAttackingUnitName")->getValue(); -// int lastAttackingUnitId; - lastAttackingUnitId = scriptManagerNode->getAttribute("lastAttackingUnitId")->getIntValue(); -// -// // end game state -// bool gameOver; - gameOver = scriptManagerNode->getAttribute("gameOver")->getIntValue() != 0; -// bool gameWon; - gameWon = scriptManagerNode->getAttribute("gameWon")->getIntValue() != 0; -// PlayerModifiers playerModifiers[GameConstants::maxPlayers]; - vector playerModifiersNodeList = scriptManagerNode->getChildList("PlayerModifiers"); - for(unsigned int i = 0; i < playerModifiersNodeList.size(); ++i) { - XmlNode *node = playerModifiersNodeList[i]; - playerModifiers[i].loadGame(node); - } -// int currentTimerTriggeredEventId; - currentTimerTriggeredEventId = scriptManagerNode->getAttribute("currentTimerTriggeredEventId")->getIntValue(); -// int currentCellTriggeredEventId; - currentCellTriggeredEventId = scriptManagerNode->getAttribute("currentCellTriggeredEventId")->getIntValue(); -// int currentEventId; - currentEventId = scriptManagerNode->getAttribute("currentEventId")->getIntValue(); -// std::map CellTriggerEventList; - vector cellTriggerEventListNodeList = scriptManagerNode->getChildList("CellTriggerEventList"); - for(unsigned int i = 0; i < cellTriggerEventListNodeList.size(); ++i) { - XmlNode *node = cellTriggerEventListNodeList[i]; - CellTriggerEvent event; - event.loadGame(node); - CellTriggerEventList[node->getAttribute("key")->getIntValue()] = event; - } - -// std::map TimerTriggerEventList; - vector timerTriggerEventListNodeList = scriptManagerNode->getChildList("TimerTriggerEventList"); - for(unsigned int i = 0; i < timerTriggerEventListNodeList.size(); ++i) { - XmlNode *node = timerTriggerEventListNodeList[i]; - - TimerTriggerEvent event; - event.loadGame(node); - TimerTriggerEventList[node->getAttribute("key")->getIntValue()] = event; - } - -// bool inCellTriggerEvent; - inCellTriggerEvent = scriptManagerNode->getAttribute("inCellTriggerEvent")->getIntValue() != 0; -// std::vector unRegisterCellTriggerEventList; - vector unRegisterCellTriggerEventListNodeList = scriptManagerNode->getChildList("unRegisterCellTriggerEventList"); - for(unsigned int i = 0; i < unRegisterCellTriggerEventListNodeList.size(); ++i) { - XmlNode *node = unRegisterCellTriggerEventListNodeList[i]; - unRegisterCellTriggerEventList.push_back(node->getAttribute("eventId")->getIntValue()); - } - - if(scriptManagerNode->hasAttribute("registeredDayNightEvent") == true) { - registeredDayNightEvent = scriptManagerNode->getAttribute("registeredDayNightEvent")->getIntValue() != 0; - } - if(scriptManagerNode->hasAttribute("lastDayNightTriggerStatus") == true) { - lastDayNightTriggerStatus = scriptManagerNode->getAttribute("lastDayNightTriggerStatus")->getIntValue(); - } - - vector unitTriggerEventListNodeList = scriptManagerNode->getChildList("UnitTriggerEventList"); - for(unsigned int i = 0; i < unitTriggerEventListNodeList.size(); ++i) { - XmlNode *node = unitTriggerEventListNodeList[i]; - - UnitTriggerEventType eventType = utet_None; - int unitId = node->getAttribute("unitId")->getIntValue(); - if(node->hasAttribute("eventType") == true) { - eventType = static_cast(node->getAttribute("eventType")->getIntValue()); - } - else if(node->hasAttribute("evenType") == true) { - eventType = static_cast(node->getAttribute("evenType")->getIntValue()); - } - UnitTriggerEventList[unitId] = eventType; - } - if(scriptManagerNode->hasAttribute("lastUnitTriggerEventUnitId") == true) { - lastUnitTriggerEventUnitId = scriptManagerNode->getAttribute("lastUnitTriggerEventUnitId")->getIntValue(); - } - if(scriptManagerNode->hasAttribute("lastUnitTriggerEventType") == true) { - lastUnitTriggerEventType = static_cast(scriptManagerNode->getAttribute("lastUnitTriggerEventType")->getIntValue()); - } - - luaScript.loadGame(scriptManagerNode); -} - - -}}//end namespace + const XmlNode *scriptManagerNode = rootNode->getChild("ScriptManager"); + + // string code; + code = scriptManagerNode->getAttribute("code")->getValue(); + // LuaScript luaScript; + + vector savedGameDataItemNodeList = + scriptManagerNode->getChildList("SavedGameDataItem"); + + if (LuaScript::getDebugModeEnabled() == true) + printf("In loadGame savedGameDataItemNodeList.size() = %d\n", + (int)savedGameDataItemNodeList.size()); + + for (unsigned int i = 0; i < savedGameDataItemNodeList.size(); ++i) { + XmlNode *node = savedGameDataItemNodeList[i]; + string key = node->getAttribute("key")->getValue(); + string value = node->getAttribute("value")->getValue(); + + luaSavedGameData[key] = value; + } + + // //world + // World *world; + // GameCamera *gameCamera; + // + // //misc + // MessageQueue messageQueue; + messageQueue.clear(); + vector messageQueueNodeList = + scriptManagerNode->getChildList("ScriptManagerMessage"); + for (unsigned int i = 0; i < messageQueueNodeList.size(); ++i) { + XmlNode *node = messageQueueNodeList[i]; + ScriptManagerMessage msg; + msg.loadGame(node); + messageQueue.push_back(msg); + } + + // GraphicMessageBox messageBox; + messageBox.setEnabled( + scriptManagerNode->getAttribute("messageBox_enabled")->getIntValue() != + 0); + messageBox.setText( + scriptManagerNode->getAttribute("messageBox_text")->getValue()); + messageBox.setHeader( + scriptManagerNode->getAttribute("messageBox_header")->getValue()); + + // string displayText; + displayText = scriptManagerNode->getAttribute("displayText")->getValue(); + // + // //last created unit + // string lastCreatedUnitName; + lastCreatedUnitName = + scriptManagerNode->getAttribute("lastCreatedUnitName")->getValue(); + // int lastCreatedUnitId; + lastCreatedUnitId = + scriptManagerNode->getAttribute("lastCreatedUnitId")->getIntValue(); + // + // //last dead unit + // string lastDeadUnitName; + lastDeadUnitName = + scriptManagerNode->getAttribute("lastDeadUnitName")->getValue(); + // int lastDeadUnitId; + lastDeadUnitId = + scriptManagerNode->getAttribute("lastDeadUnitId")->getIntValue(); + // int lastDeadUnitCauseOfDeath; + lastDeadUnitCauseOfDeath = + scriptManagerNode->getAttribute("lastDeadUnitCauseOfDeath") + ->getIntValue(); + // + // //last dead unit's killer + // string lastDeadUnitKillerName; + lastDeadUnitKillerName = + scriptManagerNode->getAttribute("lastDeadUnitKillerName")->getValue(); + // int lastDeadUnitKillerId; + lastDeadUnitKillerId = + scriptManagerNode->getAttribute("lastDeadUnitKillerId")->getIntValue(); + // + // //last attacked unit + // string lastAttackedUnitName; + lastAttackedUnitName = + scriptManagerNode->getAttribute("lastAttackedUnitName")->getValue(); + // int lastAttackedUnitId; + lastAttackedUnitId = + scriptManagerNode->getAttribute("lastAttackedUnitId")->getIntValue(); + // + // //last attacking unit + // string lastAttackingUnitName; + lastAttackingUnitName = + scriptManagerNode->getAttribute("lastAttackingUnitName")->getValue(); + // int lastAttackingUnitId; + lastAttackingUnitId = + scriptManagerNode->getAttribute("lastAttackingUnitId")->getIntValue(); + // + // // end game state + // bool gameOver; + gameOver = scriptManagerNode->getAttribute("gameOver")->getIntValue() != 0; + // bool gameWon; + gameWon = scriptManagerNode->getAttribute("gameWon")->getIntValue() != 0; + // PlayerModifiers playerModifiers[GameConstants::maxPlayers]; + vector playerModifiersNodeList = + scriptManagerNode->getChildList("PlayerModifiers"); + for (unsigned int i = 0; i < playerModifiersNodeList.size(); ++i) { + XmlNode *node = playerModifiersNodeList[i]; + playerModifiers[i].loadGame(node); + } + // int currentTimerTriggeredEventId; + currentTimerTriggeredEventId = + scriptManagerNode->getAttribute("currentTimerTriggeredEventId") + ->getIntValue(); + // int currentCellTriggeredEventId; + currentCellTriggeredEventId = + scriptManagerNode->getAttribute("currentCellTriggeredEventId") + ->getIntValue(); + // int currentEventId; + currentEventId = + scriptManagerNode->getAttribute("currentEventId")->getIntValue(); + // std::map CellTriggerEventList; + vector cellTriggerEventListNodeList = + scriptManagerNode->getChildList("CellTriggerEventList"); + for (unsigned int i = 0; i < cellTriggerEventListNodeList.size(); ++i) { + XmlNode *node = cellTriggerEventListNodeList[i]; + CellTriggerEvent event; + event.loadGame(node); + CellTriggerEventList[node->getAttribute("key")->getIntValue()] = event; + } + + // std::map TimerTriggerEventList; + vector timerTriggerEventListNodeList = + scriptManagerNode->getChildList("TimerTriggerEventList"); + for (unsigned int i = 0; i < timerTriggerEventListNodeList.size(); ++i) { + XmlNode *node = timerTriggerEventListNodeList[i]; + + TimerTriggerEvent event; + event.loadGame(node); + TimerTriggerEventList[node->getAttribute("key")->getIntValue()] = event; + } + + // bool inCellTriggerEvent; + inCellTriggerEvent = + scriptManagerNode->getAttribute("inCellTriggerEvent")->getIntValue() != 0; + // std::vector unRegisterCellTriggerEventList; + vector unRegisterCellTriggerEventListNodeList = + scriptManagerNode->getChildList("unRegisterCellTriggerEventList"); + for (unsigned int i = 0; i < unRegisterCellTriggerEventListNodeList.size(); + ++i) { + XmlNode *node = unRegisterCellTriggerEventListNodeList[i]; + unRegisterCellTriggerEventList.push_back( + node->getAttribute("eventId")->getIntValue()); + } + + if (scriptManagerNode->hasAttribute("registeredDayNightEvent") == true) { + registeredDayNightEvent = + scriptManagerNode->getAttribute("registeredDayNightEvent") + ->getIntValue() != 0; + } + if (scriptManagerNode->hasAttribute("lastDayNightTriggerStatus") == true) { + lastDayNightTriggerStatus = + scriptManagerNode->getAttribute("lastDayNightTriggerStatus") + ->getIntValue(); + } + + vector unitTriggerEventListNodeList = + scriptManagerNode->getChildList("UnitTriggerEventList"); + for (unsigned int i = 0; i < unitTriggerEventListNodeList.size(); ++i) { + XmlNode *node = unitTriggerEventListNodeList[i]; + + UnitTriggerEventType eventType = utet_None; + int unitId = node->getAttribute("unitId")->getIntValue(); + if (node->hasAttribute("eventType") == true) { + eventType = static_cast( + node->getAttribute("eventType")->getIntValue()); + } else if (node->hasAttribute("evenType") == true) { + eventType = static_cast( + node->getAttribute("evenType")->getIntValue()); + } + UnitTriggerEventList[unitId] = eventType; + } + if (scriptManagerNode->hasAttribute("lastUnitTriggerEventUnitId") == true) { + lastUnitTriggerEventUnitId = + scriptManagerNode->getAttribute("lastUnitTriggerEventUnitId") + ->getIntValue(); + } + if (scriptManagerNode->hasAttribute("lastUnitTriggerEventType") == true) { + lastUnitTriggerEventType = static_cast( + scriptManagerNode->getAttribute("lastUnitTriggerEventType") + ->getIntValue()); + } + + luaScript.loadGame(scriptManagerNode); +} + +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/game/script_manager.h b/source/glest_game/game/script_manager.h index 859e49cc5..d2699b5a4 100644 --- a/source/glest_game/game/script_manager.h +++ b/source/glest_game/game/script_manager.h @@ -13,31 +13,31 @@ #define _GLEST_GAME_SCRIPT_MANAGER_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include -#include -#include "lua_script.h" #include "components.h" #include "game_constants.h" -#include -#include "xml_parser.h" -#include "randomgen.h" #include "leak_dumper.h" +#include "lua_script.h" #include "platform_util.h" +#include "randomgen.h" +#include "xml_parser.h" +#include +#include +#include -using std::string; -using std::list; using Shared::Graphics::Vec2i; -using Shared::Lua::LuaScript; using Shared::Lua::LuaHandle; -using Shared::Xml::XmlNode; +using Shared::Lua::LuaScript; using Shared::Util::RandomGen; +using Shared::Xml::XmlNode; +using std::list; +using std::string; - -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { class World; class Unit; @@ -49,50 +49,51 @@ class GameCamera; class ScriptManagerMessage { private: - string text; - string header; - int factionIndex; - int teamIndex; - bool messageNotTranslated; + string text; + string header; + int factionIndex; + int teamIndex; + bool messageNotTranslated; public: - ScriptManagerMessage(); - ScriptManagerMessage(const string &text, const string &header, int factionIndex=-1,int teamIndex=-1,bool messageNotTranslated=false); - const string &getText() const {return text;} - const string &getHeader() const {return header;} - int getFactionIndex() const {return factionIndex;} - int getTeamIndex() const {return teamIndex;} - bool getMessageNotTranslated() const { return messageNotTranslated; } - - void saveGame(XmlNode *rootNode); - void loadGame(const XmlNode *rootNode); + ScriptManagerMessage(); + ScriptManagerMessage(const string &text, const string &header, + int factionIndex = -1, int teamIndex = -1, + bool messageNotTranslated = false); + const string &getText() const { return text; } + const string &getHeader() const { return header; } + int getFactionIndex() const { return factionIndex; } + int getTeamIndex() const { return teamIndex; } + bool getMessageNotTranslated() const { return messageNotTranslated; } + + void saveGame(XmlNode *rootNode); + void loadGame(const XmlNode *rootNode); }; -class PlayerModifiers{ +class PlayerModifiers { public: - PlayerModifiers(); + PlayerModifiers(); - void disableAi() {aiEnabled= false;} - void enableAi() {aiEnabled= true;} + void disableAi() { aiEnabled = false; } + void enableAi() { aiEnabled = true; } - void setAsWinner() {winner= true;} + void setAsWinner() { winner = true; } - void disableConsume() {consumeEnabled= false;} - void enableConsume() {consumeEnabled= true;} + void disableConsume() { consumeEnabled = false; } + void enableConsume() { consumeEnabled = true; } - bool getWinner() const {return winner;} + bool getWinner() const { return winner; } - bool getAiEnabled() const {return aiEnabled;} - bool getConsumeEnabled() const {return consumeEnabled;} + bool getAiEnabled() const { return aiEnabled; } + bool getConsumeEnabled() const { return consumeEnabled; } - void saveGame(XmlNode *rootNode); - void loadGame(const XmlNode *rootNode); + void saveGame(XmlNode *rootNode); + void loadGame(const XmlNode *rootNode); private: - - bool winner; - bool aiEnabled; - bool consumeEnabled; + bool winner; + bool aiEnabled; + bool consumeEnabled; }; // ===================================================== @@ -100,514 +101,532 @@ class PlayerModifiers{ // ===================================================== enum UnitTriggerEventType { - utet_None = 0, - utet_HPChanged = 1, - utet_EPChanged, - utet_LevelChanged, - utet_FieldChanged, - utet_SkillChanged + utet_None = 0, + utet_HPChanged = 1, + utet_EPChanged, + utet_LevelChanged, + utet_FieldChanged, + utet_SkillChanged }; enum CellTriggerEventType { - ctet_Unit, - ctet_UnitPos, - ctet_Faction, - ctet_FactionPos, - ctet_UnitAreaPos, - ctet_FactionAreaPos, - ctet_AreaPos + ctet_Unit, + ctet_UnitPos, + ctet_Faction, + ctet_FactionPos, + ctet_UnitAreaPos, + ctet_FactionAreaPos, + ctet_AreaPos }; class CellTriggerEvent { public: - CellTriggerEvent(); - CellTriggerEventType type; - int sourceId; - int destId; - Vec2i destPos; - Vec2i destPosEnd; + CellTriggerEvent(); + CellTriggerEventType type; + int sourceId; + int destId; + Vec2i destPos; + Vec2i destPosEnd; - int triggerCount; + int triggerCount; - std::map eventStateInfo; + std::map eventStateInfo; - std::map > eventLookupCache; + std::map> eventLookupCache; - void saveGame(XmlNode *rootNode); - void loadGame(const XmlNode *rootNode); + void saveGame(XmlNode *rootNode); + void loadGame(const XmlNode *rootNode); }; class TimerTriggerEvent { public: - TimerTriggerEvent(); - bool running; - //time_t startTime; - //time_t endTime; - int startFrame; - int endFrame; + TimerTriggerEvent(); + bool running; + // time_t startTime; + // time_t endTime; + int startFrame; + int endFrame; - int triggerSecondsElapsed; + int triggerSecondsElapsed; - void saveGame(XmlNode *rootNode); - void loadGame(const XmlNode *rootNode); + void saveGame(XmlNode *rootNode); + void loadGame(const XmlNode *rootNode); }; class ScriptManager { private: - typedef list MessageQueue; + typedef list MessageQueue; private: + // lua + string code; + LuaScript luaScript; - //lua - string code; - LuaScript luaScript; - - //world - World *world; - GameCamera *gameCamera; + // world + World *world; + GameCamera *gameCamera; - //misc - MessageQueue messageQueue; - GraphicMessageBox messageBox; - string displayText; - int errorCount; + // misc + MessageQueue messageQueue; + GraphicMessageBox messageBox; + string displayText; + int errorCount; - //last created unit - string lastCreatedUnitName; - int lastCreatedUnitId; + // last created unit + string lastCreatedUnitName; + int lastCreatedUnitId; - //last dead unit - string lastDeadUnitName; - int lastDeadUnitId; - int lastDeadUnitCauseOfDeath; + // last dead unit + string lastDeadUnitName; + int lastDeadUnitId; + int lastDeadUnitCauseOfDeath; - //last dead unit's killer - string lastDeadUnitKillerName; - int lastDeadUnitKillerId; + // last dead unit's killer + string lastDeadUnitKillerName; + int lastDeadUnitKillerId; - //last attacked unit - string lastAttackedUnitName; - int lastAttackedUnitId; + // last attacked unit + string lastAttackedUnitName; + int lastAttackedUnitId; - //last attacking unit - string lastAttackingUnitName; - int lastAttackingUnitId; + // last attacking unit + string lastAttackingUnitName; + int lastAttackingUnitId; - // end game state - bool gameOver; - bool gameWon; - PlayerModifiers playerModifiers[GameConstants::maxPlayers]; + // end game state + bool gameOver; + bool gameWon; + PlayerModifiers playerModifiers[GameConstants::maxPlayers]; - int currentTimerTriggeredEventId; - int currentCellTriggeredEventId; - int currentCellTriggeredEventUnitId; + int currentTimerTriggeredEventId; + int currentCellTriggeredEventId; + int currentCellTriggeredEventUnitId; - int currentCellTriggeredEventAreaEntryUnitId; - int currentCellTriggeredEventAreaExitUnitId; + int currentCellTriggeredEventAreaEntryUnitId; + int currentCellTriggeredEventAreaExitUnitId; - int currentEventId; - std::map CellTriggerEventList; - std::map TimerTriggerEventList; - bool inCellTriggerEvent; - std::vector unRegisterCellTriggerEventList; + int currentEventId; + std::map CellTriggerEventList; + std::map TimerTriggerEventList; + bool inCellTriggerEvent; + std::vector unRegisterCellTriggerEventList; - bool registeredDayNightEvent; - int lastDayNightTriggerStatus; + bool registeredDayNightEvent; + int lastDayNightTriggerStatus; - std::map UnitTriggerEventList; - int lastUnitTriggerEventUnitId; - UnitTriggerEventType lastUnitTriggerEventType; + std::map UnitTriggerEventList; + int lastUnitTriggerEventUnitId; + UnitTriggerEventType lastUnitTriggerEventType; - RandomGen random; - const XmlNode *rootNode; + RandomGen random; + const XmlNode *rootNode; - std::map luaSavedGameData; + std::map luaSavedGameData; private: - static ScriptManager* thisScriptManager; + static ScriptManager *thisScriptManager; private: - static const int messageWrapCount; - static const int displayTextWrapCount; + static const int messageWrapCount; + static const int displayTextWrapCount; public: - - ScriptManager(); - ~ScriptManager(); - void init(World* world, GameCamera *gameCamera,const XmlNode *rootNode); - - //message box functions - void addMessageToQueue(ScriptManagerMessage msg); - bool getMessageBoxEnabled() const {return !messageQueue.empty();} - GraphicMessageBox* getMessageBox() {return &messageBox;} - string getDisplayText() const {return displayText;} - const PlayerModifiers *getPlayerModifiers(int factionIndex) const {return &playerModifiers[factionIndex];} - - //events - void onMessageBoxOk(bool popFront=true); - void onResourceHarvested(); - void onUnitCreated(const Unit* unit); - void onUnitDied(const Unit* unit); - void onUnitAttacked(const Unit* unit); - void onUnitAttacking(const Unit* unit); - void onGameOver(bool won); - - void onCellTriggerEvent(Unit *movingUnit); - void onTimerTriggerEvent(); - void onDayNightTriggerEvent(); - void onUnitTriggerEvent(const Unit *unit, UnitTriggerEventType event); - - bool getGameWon() const; - bool getIsGameOver() const; - - void saveGame(XmlNode *rootNode); - void loadGame(const XmlNode *rootNode); + ScriptManager(); + ~ScriptManager(); + void init(World *world, GameCamera *gameCamera, const XmlNode *rootNode); + + // message box functions + void addMessageToQueue(ScriptManagerMessage msg); + bool getMessageBoxEnabled() const { return !messageQueue.empty(); } + GraphicMessageBox *getMessageBox() { return &messageBox; } + string getDisplayText() const { return displayText; } + const PlayerModifiers *getPlayerModifiers(int factionIndex) const { + return &playerModifiers[factionIndex]; + } + + // events + void onMessageBoxOk(bool popFront = true); + void onResourceHarvested(); + void onUnitCreated(const Unit *unit); + void onUnitDied(const Unit *unit); + void onUnitAttacked(const Unit *unit); + void onUnitAttacking(const Unit *unit); + void onGameOver(bool won); + + void onCellTriggerEvent(Unit *movingUnit); + void onTimerTriggerEvent(); + void onDayNightTriggerEvent(); + void onUnitTriggerEvent(const Unit *unit, UnitTriggerEventType event); + + bool getGameWon() const; + bool getIsGameOver() const; + + void saveGame(XmlNode *rootNode); + void loadGame(const XmlNode *rootNode); private: - string wrapString(const string &str, int wrapCount); - - //wrappers, commands - void networkShowMessageForFaction(const string &text, const string &header,int factionIndex); - void networkShowMessageForTeam(const string &text, const string &header,int teamIndex); - - void networkSetCameraPositionForFaction(int factionIndex, const Vec2i &pos); - void networkSetCameraPositionForTeam(int teamIndex, const Vec2i &pos); - - void showMessage(const string &text, const string &header); - void clearDisplayText(); - void setDisplayText(const string &text); - void addConsoleText(const string &text); - void addConsoleLangText(const char *fmt,...); - void DisplayFormattedText(const char *fmt,...); - void DisplayFormattedLangText(const char *fmt,...); - void setCameraPosition(const Vec2i &pos); - void shakeCamera(int shakeIntensity, int shakeDuration, bool cameraDistanceAffected, int unitId); - void createUnit(const string &unitName, int factionIndex, Vec2i pos); - void createUnitNoSpacing(const string &unitName, int factionIndex, Vec2i pos); - - void setLockedUnitForFaction(const string &unitName, int factionIndex , bool lock); - void destroyUnit(int unitId); - void giveKills(int unitId, int amount); - void morphToUnit(int unitId,const string &morphName, int ignoreRequirements); - void moveToUnit(int unitId,int destUnitId); - void giveAttackStoppedCommand(int unitId, const string &valueName,int ignoreRequirements); - void playStaticSound(const string &playSound); - void playStreamingSound(const string &playSound); - void stopStreamingSound(const string &playSound); - void stopAllSound(); - void togglePauseGame(int pauseStatus); - - void playStaticVideo(const string &playVideo); - void playStreamingVideo(const string &playVideo); - void stopStreamingVideo(const string &playVideo); - void stopAllVideo(); - - void giveResource(const string &resourceName, int factionIndex, int amount); - void givePositionCommand(int unitId, const string &producedName, const Vec2i &pos); - void giveProductionCommand(int unitId, const string &producedName); - void giveAttackCommand(int unitId, int unitToAttackId); - void giveUpgradeCommand(int unitId, const string &upgradeName); - void giveStopCommand(int unitId); - - void disableAi(int factionIndex); - void enableAi(int factionIndex); - void disableConsume(int factionIndex); - void enableConsume(int factionIndex); - - int registerCellTriggerEventForUnitToUnit(int sourceUnitId, int destUnitId); - int registerCellTriggerEventForUnitToLocation(int sourceUnitId, const Vec2i &pos); - int registerCellTriggerEventForFactionToUnit(int sourceFactionId, int destUnitId); - int registerCellTriggerEventForFactionToLocation(int sourceFactionId, const Vec2i &pos); - - int registerCellAreaTriggerEventForUnitToLocation(int sourceUnitId, const Vec4i &pos); - int registerCellAreaTriggerEventForFactionToLocation(int sourceFactionId, const Vec4i &pos); - - int registerCellAreaTriggerEvent(const Vec4i &pos); - - int getCellTriggerEventCount(int eventId); - void unregisterCellTriggerEvent(int eventId); - int startTimerEvent(); - int startEfficientTimerEvent(int triggerSecondsElapsed); - int resetTimerEvent(int eventId); - int stopTimerEvent(int eventId); - int getTimerEventSecondsElapsed(int eventId); - - int getCellTriggeredEventId(); - int getTimerTriggeredEventId(); - - int getCellTriggeredEventAreaEntryUnitId(); - int getCellTriggeredEventAreaExitUnitId(); - - int getCellTriggeredEventUnitId(); - - void setRandomGenInit(int seed); - int getRandomGen(int minVal, int maxVal); - int getWorldFrameCount(); - - bool getAiEnabled(int factionIndex); - bool getConsumeEnabled(int factionIndex); - - void setPlayerAsWinner(int factionIndex); - void endGame(); - - void startPerformanceTimer(); - void endPerformanceTimer(); - Vec2i getPerformanceTimerResults(); - - //wrappers, queries - int getIsUnitAlive(int unitId); - Vec2i getStartLocation(int factionIndex); - Vec2i getUnitPosition(int unitId); - int getUnitFaction(int unitId); - const string getUnitName(int unitId); - const string getUnitDisplayName(int unitId); - int getResourceAmount(const string &resourceName, int factionIndex); - const string &getLastCreatedUnitName(); - int getLastCreatedUnitId(); - - void setUnitPosition(int unitId, Vec2i pos); - - void addCellMarker(Vec2i pos, int factionIndex, const string ¬e, const string &textureFile); - void removeCellMarker(Vec2i pos, int factionIndex); - - void showMarker(Vec2i pos, int factionIndex, const string ¬e, const string &textureFile, int flashCount); - - const string &getLastDeadUnitName(); - int getLastDeadUnitId(); - int getLastDeadUnitCauseOfDeath(); - const string &getLastDeadUnitKillerName(); - int getLastDeadUnitKillerId(); - - const string &getLastAttackedUnitName(); - int getLastAttackedUnitId(); - - const string &getLastAttackingUnitName(); - int getLastAttackingUnitId(); - - int getUnitCount(int factionIndex); - int getUnitCountOfType(int factionIndex, const string &typeName); - - const string getSystemMacroValue(const string &key); - const string getPlayerName(int factionIndex); - - vector getUnitsForFaction(int factionIndex,const string& commandTypeName, int field); - int getUnitCurrentField(int unitId); - - void loadScenario(const string &name, bool keepFactions); - - int isFreeCellsOrHasUnit(int field, int unitId,Vec2i pos); - int isFreeCells(int unitSize, int field,Vec2i pos); - - int getHumanFactionId(); - void highlightUnit(int unitId, float radius, float thickness, Vec4f color); - void unhighlightUnit(int unitId); - - bool selectUnit(int unitId); - void unselectUnit(int unitId); - void addUnitToGroupSelection(int unitId,int groupIndex); - void recallGroupSelection(int groupIndex); - void removeUnitFromGroupSelection(int unitId,int group); - void setAttackWarningsEnabled(bool enabled); - bool getAttackWarningsEnabled(); - - int getIsDayTime(); - int getIsNightTime(); - float getTimeOfDay(); - void registerDayNightEvent(); - void unregisterDayNightEvent(); - - void registerUnitTriggerEvent(int unitId); - void unregisterUnitTriggerEvent(int unitId); - int getLastUnitTriggerEventUnitId(); - UnitTriggerEventType getLastUnitTriggerEventType(); - int getUnitProperty(int unitId, UnitTriggerEventType type); - const string getUnitPropertyName(int unitId, UnitTriggerEventType type); - - void disableSpeedChange(); - void enableSpeedChange(); - bool getSpeedChangeEnabled(); - void storeSaveGameData(string name, string value); - string loadSaveGameData(string name); - - ControlType getFactionPlayerType(int factionIndex); - // ----------------------------------------------------------------------- - - static void error(LuaHandle* luaHandle, const megaglest_runtime_error *mgErr, const char* file, const char* function, int line); - - //callbacks, commands - static int networkShowMessageForFaction(LuaHandle* luaHandle); - static int networkShowMessageForTeam(LuaHandle* luaHandle); - - static int networkSetCameraPositionForFaction(LuaHandle* luaHandle); - static int networkSetCameraPositionForTeam(LuaHandle* luaHandle); - - static int showMessage(LuaHandle* luaHandle); - static int setDisplayText(LuaHandle* luaHandle); - static int addConsoleText(LuaHandle* luaHandle); - static int addConsoleLangText(LuaHandle* luaHandle); - static int DisplayFormattedText(LuaHandle* luaHandle); - static int DisplayFormattedLangText(LuaHandle* luaHandle); - static int clearDisplayText(LuaHandle* luaHandle); - static int setCameraPosition(LuaHandle* luaHandle); - static int shakeCamera(LuaHandle* luaHandle); - static int shakeCameraOnUnit(LuaHandle* luaHandle); - static int createUnit(LuaHandle* luaHandle); - static int createUnitNoSpacing(LuaHandle* luaHandle); - - static int setLockedUnitForFaction(LuaHandle* luaHandle); - static int destroyUnit(LuaHandle* luaHandle); - static int giveKills(LuaHandle* luaHandle); - static int morphToUnit(LuaHandle* luaHandle); - static int moveToUnit(LuaHandle* luaHandle); - static int giveAttackStoppedCommand(LuaHandle* luaHandle); - static int playStaticSound(LuaHandle* luaHandle); - static int playStreamingSound(LuaHandle* luaHandle); - static int stopStreamingSound(LuaHandle* luaHandle); - static int stopAllSound(LuaHandle* luaHandle); - static int togglePauseGame(LuaHandle* luaHandle); - - static int playStaticVideo(LuaHandle* luaHandle); - static int playStreamingVideo(LuaHandle* luaHandle); - static int stopStreamingVideo(LuaHandle* luaHandle); - static int stopAllVideo(LuaHandle* luaHandle); - - static int giveResource(LuaHandle* luaHandle); - static int givePositionCommand(LuaHandle* luaHandle); - static int giveProductionCommand(LuaHandle* luaHandle); - static int giveAttackCommand(LuaHandle* luaHandle); - static int giveUpgradeCommand(LuaHandle* luaHandle); - - static int disableAi(LuaHandle* luaHandle); - static int enableAi(LuaHandle* luaHandle); - - static int disableConsume(LuaHandle* luaHandle); - static int enableConsume(LuaHandle* luaHandle); - - static int getAiEnabled(LuaHandle* luaHandle); - static int getConsumeEnabled(LuaHandle* luaHandle); - - static int registerCellTriggerEventForUnitToUnit(LuaHandle* luaHandle); - static int registerCellTriggerEventForUnitToLocation(LuaHandle* luaHandle); - static int registerCellTriggerEventForFactionToUnit(LuaHandle* luaHandle); - static int registerCellTriggerEventForFactionToLocation(LuaHandle* luaHandle); - - static int registerCellAreaTriggerEventForUnitToLocation(LuaHandle* luaHandle); - static int registerCellAreaTriggerEventForFactionToLocation(LuaHandle* luaHandle); - - static int registerCellAreaTriggerEvent(LuaHandle* luaHandle); - - static int getCellTriggerEventCount(LuaHandle* luaHandle); - static int unregisterCellTriggerEvent(LuaHandle* luaHandle); - static int startTimerEvent(LuaHandle* luaHandle); - static int startEfficientTimerEvent(LuaHandle* luaHandle); - static int resetTimerEvent(LuaHandle* luaHandle); - static int stopTimerEvent(LuaHandle* luaHandle); - static int getTimerEventSecondsElapsed(LuaHandle* luaHandle); - - static int getCellTriggeredEventId(LuaHandle* luaHandle); - static int getTimerTriggeredEventId(LuaHandle* luaHandle); - - static int getCellTriggeredEventAreaEntryUnitId(LuaHandle* luaHandle); - static int getCellTriggeredEventAreaExitUnitId(LuaHandle* luaHandle); - - static int getCellTriggeredEventUnitId(LuaHandle* luaHandle); - - static int setRandomGenInit(LuaHandle* luaHandle); - static int getRandomGen(LuaHandle* luaHandle); - static int getWorldFrameCount(LuaHandle* luaHandle); - - static int setPlayerAsWinner(LuaHandle* luaHandle); - static int endGame(LuaHandle* luaHandle); - - static int startPerformanceTimer(LuaHandle* luaHandle); - static int endPerformanceTimer(LuaHandle* luaHandle); - static int getPerformanceTimerResults(LuaHandle* luaHandle); - - //callbacks, queries - static int getIsUnitAlive(LuaHandle* luaHandle); - static int getStartLocation(LuaHandle* luaHandle); - static int getUnitPosition(LuaHandle* luaHandle); - static int getUnitFaction(LuaHandle* luaHandle); - static int getUnitName(LuaHandle* luaHandle); - static int getUnitDisplayName(LuaHandle* luaHandle); - static int getResourceAmount(LuaHandle* luaHandle); - static int getLastCreatedUnitName(LuaHandle* luaHandle); - static int getLastCreatedUnitId(LuaHandle* luaHandle); - - static int setUnitPosition(LuaHandle* luaHandle); - - static int addCellMarker(LuaHandle* luaHandle); - static int removeCellMarker(LuaHandle* luaHandle); - - static int showMarker(LuaHandle* luaHandle); - - static int getLastDeadUnitName(LuaHandle* luaHandle); - static int getLastDeadUnitId(LuaHandle* luaHandle); - static int getLastDeadUnitCauseOfDeath(LuaHandle* luaHandle); - static int getLastDeadUnitKillerName(LuaHandle* luaHandle); - static int getLastDeadUnitKillerId(LuaHandle* luaHandle); - - static int getLastAttackedUnitName(LuaHandle* luaHandle); - static int getLastAttackedUnitId(LuaHandle* luaHandle); - - static int getLastAttackingUnitName(LuaHandle* luaHandle); - static int getLastAttackingUnitId(LuaHandle* luaHandle); - - static int getUnitCount(LuaHandle* luaHandle); - static int getUnitCountOfType(LuaHandle* luaHandle); - - static int getGameWon(LuaHandle* luaHandle); - static int getIsGameOver(LuaHandle* luaHandle); - - static int getSystemMacroValue(LuaHandle* luaHandle); - static int getPlayerName(LuaHandle* luaHandle); - static int scenarioDir(LuaHandle* luaHandle); + string wrapString(const string &str, int wrapCount); + + // wrappers, commands + void networkShowMessageForFaction(const string &text, const string &header, + int factionIndex); + void networkShowMessageForTeam(const string &text, const string &header, + int teamIndex); + + void networkSetCameraPositionForFaction(int factionIndex, const Vec2i &pos); + void networkSetCameraPositionForTeam(int teamIndex, const Vec2i &pos); + + void showMessage(const string &text, const string &header); + void clearDisplayText(); + void setDisplayText(const string &text); + void addConsoleText(const string &text); + void addConsoleLangText(const char *fmt, ...); + void DisplayFormattedText(const char *fmt, ...); + void DisplayFormattedLangText(const char *fmt, ...); + void setCameraPosition(const Vec2i &pos); + void shakeCamera(int shakeIntensity, int shakeDuration, + bool cameraDistanceAffected, int unitId); + void createUnit(const string &unitName, int factionIndex, Vec2i pos); + void createUnitNoSpacing(const string &unitName, int factionIndex, Vec2i pos); + + void setLockedUnitForFaction(const string &unitName, int factionIndex, + bool lock); + void destroyUnit(int unitId); + void giveKills(int unitId, int amount); + void morphToUnit(int unitId, const string &morphName, int ignoreRequirements); + void moveToUnit(int unitId, int destUnitId); + void giveAttackStoppedCommand(int unitId, const string &valueName, + int ignoreRequirements); + void playStaticSound(const string &playSound); + void playStreamingSound(const string &playSound); + void stopStreamingSound(const string &playSound); + void stopAllSound(); + void togglePauseGame(int pauseStatus); + + void playStaticVideo(const string &playVideo); + void playStreamingVideo(const string &playVideo); + void stopStreamingVideo(const string &playVideo); + void stopAllVideo(); + + void giveResource(const string &resourceName, int factionIndex, int amount); + void givePositionCommand(int unitId, const string &producedName, + const Vec2i &pos); + void giveProductionCommand(int unitId, const string &producedName); + void giveAttackCommand(int unitId, int unitToAttackId); + void giveUpgradeCommand(int unitId, const string &upgradeName); + void giveStopCommand(int unitId); + + void disableAi(int factionIndex); + void enableAi(int factionIndex); + void disableConsume(int factionIndex); + void enableConsume(int factionIndex); + + int registerCellTriggerEventForUnitToUnit(int sourceUnitId, int destUnitId); + int registerCellTriggerEventForUnitToLocation(int sourceUnitId, + const Vec2i &pos); + int registerCellTriggerEventForFactionToUnit(int sourceFactionId, + int destUnitId); + int registerCellTriggerEventForFactionToLocation(int sourceFactionId, + const Vec2i &pos); + + int registerCellAreaTriggerEventForUnitToLocation(int sourceUnitId, + const Vec4i &pos); + int registerCellAreaTriggerEventForFactionToLocation(int sourceFactionId, + const Vec4i &pos); + + int registerCellAreaTriggerEvent(const Vec4i &pos); + + int getCellTriggerEventCount(int eventId); + void unregisterCellTriggerEvent(int eventId); + int startTimerEvent(); + int startEfficientTimerEvent(int triggerSecondsElapsed); + int resetTimerEvent(int eventId); + int stopTimerEvent(int eventId); + int getTimerEventSecondsElapsed(int eventId); + + int getCellTriggeredEventId(); + int getTimerTriggeredEventId(); + + int getCellTriggeredEventAreaEntryUnitId(); + int getCellTriggeredEventAreaExitUnitId(); + + int getCellTriggeredEventUnitId(); + + void setRandomGenInit(int seed); + int getRandomGen(int minVal, int maxVal); + int getWorldFrameCount(); + + bool getAiEnabled(int factionIndex); + bool getConsumeEnabled(int factionIndex); + + void setPlayerAsWinner(int factionIndex); + void endGame(); + + void startPerformanceTimer(); + void endPerformanceTimer(); + Vec2i getPerformanceTimerResults(); + + // wrappers, queries + int getIsUnitAlive(int unitId); + Vec2i getStartLocation(int factionIndex); + Vec2i getUnitPosition(int unitId); + int getUnitFaction(int unitId); + const string getUnitName(int unitId); + const string getUnitDisplayName(int unitId); + int getResourceAmount(const string &resourceName, int factionIndex); + const string &getLastCreatedUnitName(); + int getLastCreatedUnitId(); + + void setUnitPosition(int unitId, Vec2i pos); + + void addCellMarker(Vec2i pos, int factionIndex, const string ¬e, + const string &textureFile); + void removeCellMarker(Vec2i pos, int factionIndex); + + void showMarker(Vec2i pos, int factionIndex, const string ¬e, + const string &textureFile, int flashCount); + + const string &getLastDeadUnitName(); + int getLastDeadUnitId(); + int getLastDeadUnitCauseOfDeath(); + const string &getLastDeadUnitKillerName(); + int getLastDeadUnitKillerId(); + + const string &getLastAttackedUnitName(); + int getLastAttackedUnitId(); + + const string &getLastAttackingUnitName(); + int getLastAttackingUnitId(); + + int getUnitCount(int factionIndex); + int getUnitCountOfType(int factionIndex, const string &typeName); + + const string getSystemMacroValue(const string &key); + const string getPlayerName(int factionIndex); + + vector getUnitsForFaction(int factionIndex, + const string &commandTypeName, int field); + int getUnitCurrentField(int unitId); + + void loadScenario(const string &name, bool keepFactions); + + int isFreeCellsOrHasUnit(int field, int unitId, Vec2i pos); + int isFreeCells(int unitSize, int field, Vec2i pos); + + int getHumanFactionId(); + void highlightUnit(int unitId, float radius, float thickness, Vec4f color); + void unhighlightUnit(int unitId); + + bool selectUnit(int unitId); + void unselectUnit(int unitId); + void addUnitToGroupSelection(int unitId, int groupIndex); + void recallGroupSelection(int groupIndex); + void removeUnitFromGroupSelection(int unitId, int group); + void setAttackWarningsEnabled(bool enabled); + bool getAttackWarningsEnabled(); + + int getIsDayTime(); + int getIsNightTime(); + float getTimeOfDay(); + void registerDayNightEvent(); + void unregisterDayNightEvent(); + + void registerUnitTriggerEvent(int unitId); + void unregisterUnitTriggerEvent(int unitId); + int getLastUnitTriggerEventUnitId(); + UnitTriggerEventType getLastUnitTriggerEventType(); + int getUnitProperty(int unitId, UnitTriggerEventType type); + const string getUnitPropertyName(int unitId, UnitTriggerEventType type); + + void disableSpeedChange(); + void enableSpeedChange(); + bool getSpeedChangeEnabled(); + void storeSaveGameData(string name, string value); + string loadSaveGameData(string name); + + ControlType getFactionPlayerType(int factionIndex); + // ----------------------------------------------------------------------- + + static void error(LuaHandle *luaHandle, const megaglest_runtime_error *mgErr, + const char *file, const char *function, int line); + + // callbacks, commands + static int networkShowMessageForFaction(LuaHandle *luaHandle); + static int networkShowMessageForTeam(LuaHandle *luaHandle); + + static int networkSetCameraPositionForFaction(LuaHandle *luaHandle); + static int networkSetCameraPositionForTeam(LuaHandle *luaHandle); + + static int showMessage(LuaHandle *luaHandle); + static int setDisplayText(LuaHandle *luaHandle); + static int addConsoleText(LuaHandle *luaHandle); + static int addConsoleLangText(LuaHandle *luaHandle); + static int DisplayFormattedText(LuaHandle *luaHandle); + static int DisplayFormattedLangText(LuaHandle *luaHandle); + static int clearDisplayText(LuaHandle *luaHandle); + static int setCameraPosition(LuaHandle *luaHandle); + static int shakeCamera(LuaHandle *luaHandle); + static int shakeCameraOnUnit(LuaHandle *luaHandle); + static int createUnit(LuaHandle *luaHandle); + static int createUnitNoSpacing(LuaHandle *luaHandle); + + static int setLockedUnitForFaction(LuaHandle *luaHandle); + static int destroyUnit(LuaHandle *luaHandle); + static int giveKills(LuaHandle *luaHandle); + static int morphToUnit(LuaHandle *luaHandle); + static int moveToUnit(LuaHandle *luaHandle); + static int giveAttackStoppedCommand(LuaHandle *luaHandle); + static int playStaticSound(LuaHandle *luaHandle); + static int playStreamingSound(LuaHandle *luaHandle); + static int stopStreamingSound(LuaHandle *luaHandle); + static int stopAllSound(LuaHandle *luaHandle); + static int togglePauseGame(LuaHandle *luaHandle); + + static int playStaticVideo(LuaHandle *luaHandle); + static int playStreamingVideo(LuaHandle *luaHandle); + static int stopStreamingVideo(LuaHandle *luaHandle); + static int stopAllVideo(LuaHandle *luaHandle); + + static int giveResource(LuaHandle *luaHandle); + static int givePositionCommand(LuaHandle *luaHandle); + static int giveProductionCommand(LuaHandle *luaHandle); + static int giveAttackCommand(LuaHandle *luaHandle); + static int giveUpgradeCommand(LuaHandle *luaHandle); + + static int disableAi(LuaHandle *luaHandle); + static int enableAi(LuaHandle *luaHandle); + + static int disableConsume(LuaHandle *luaHandle); + static int enableConsume(LuaHandle *luaHandle); + + static int getAiEnabled(LuaHandle *luaHandle); + static int getConsumeEnabled(LuaHandle *luaHandle); + + static int registerCellTriggerEventForUnitToUnit(LuaHandle *luaHandle); + static int registerCellTriggerEventForUnitToLocation(LuaHandle *luaHandle); + static int registerCellTriggerEventForFactionToUnit(LuaHandle *luaHandle); + static int registerCellTriggerEventForFactionToLocation(LuaHandle *luaHandle); + + static int + registerCellAreaTriggerEventForUnitToLocation(LuaHandle *luaHandle); + static int + registerCellAreaTriggerEventForFactionToLocation(LuaHandle *luaHandle); + + static int registerCellAreaTriggerEvent(LuaHandle *luaHandle); + + static int getCellTriggerEventCount(LuaHandle *luaHandle); + static int unregisterCellTriggerEvent(LuaHandle *luaHandle); + static int startTimerEvent(LuaHandle *luaHandle); + static int startEfficientTimerEvent(LuaHandle *luaHandle); + static int resetTimerEvent(LuaHandle *luaHandle); + static int stopTimerEvent(LuaHandle *luaHandle); + static int getTimerEventSecondsElapsed(LuaHandle *luaHandle); + + static int getCellTriggeredEventId(LuaHandle *luaHandle); + static int getTimerTriggeredEventId(LuaHandle *luaHandle); + + static int getCellTriggeredEventAreaEntryUnitId(LuaHandle *luaHandle); + static int getCellTriggeredEventAreaExitUnitId(LuaHandle *luaHandle); + + static int getCellTriggeredEventUnitId(LuaHandle *luaHandle); + + static int setRandomGenInit(LuaHandle *luaHandle); + static int getRandomGen(LuaHandle *luaHandle); + static int getWorldFrameCount(LuaHandle *luaHandle); + + static int setPlayerAsWinner(LuaHandle *luaHandle); + static int endGame(LuaHandle *luaHandle); + + static int startPerformanceTimer(LuaHandle *luaHandle); + static int endPerformanceTimer(LuaHandle *luaHandle); + static int getPerformanceTimerResults(LuaHandle *luaHandle); + + // callbacks, queries + static int getIsUnitAlive(LuaHandle *luaHandle); + static int getStartLocation(LuaHandle *luaHandle); + static int getUnitPosition(LuaHandle *luaHandle); + static int getUnitFaction(LuaHandle *luaHandle); + static int getUnitName(LuaHandle *luaHandle); + static int getUnitDisplayName(LuaHandle *luaHandle); + static int getResourceAmount(LuaHandle *luaHandle); + static int getLastCreatedUnitName(LuaHandle *luaHandle); + static int getLastCreatedUnitId(LuaHandle *luaHandle); + + static int setUnitPosition(LuaHandle *luaHandle); + + static int addCellMarker(LuaHandle *luaHandle); + static int removeCellMarker(LuaHandle *luaHandle); + + static int showMarker(LuaHandle *luaHandle); + + static int getLastDeadUnitName(LuaHandle *luaHandle); + static int getLastDeadUnitId(LuaHandle *luaHandle); + static int getLastDeadUnitCauseOfDeath(LuaHandle *luaHandle); + static int getLastDeadUnitKillerName(LuaHandle *luaHandle); + static int getLastDeadUnitKillerId(LuaHandle *luaHandle); + + static int getLastAttackedUnitName(LuaHandle *luaHandle); + static int getLastAttackedUnitId(LuaHandle *luaHandle); + + static int getLastAttackingUnitName(LuaHandle *luaHandle); + static int getLastAttackingUnitId(LuaHandle *luaHandle); + + static int getUnitCount(LuaHandle *luaHandle); + static int getUnitCountOfType(LuaHandle *luaHandle); + + static int getGameWon(LuaHandle *luaHandle); + static int getIsGameOver(LuaHandle *luaHandle); + + static int getSystemMacroValue(LuaHandle *luaHandle); + static int getPlayerName(LuaHandle *luaHandle); + static int scenarioDir(LuaHandle *luaHandle); - static int loadScenario(LuaHandle* luaHandle); + static int loadScenario(LuaHandle *luaHandle); - static int getUnitsForFaction(LuaHandle* luaHandle); - static int getUnitCurrentField(LuaHandle* luaHandle); + static int getUnitsForFaction(LuaHandle *luaHandle); + static int getUnitCurrentField(LuaHandle *luaHandle); - static int isFreeCellsOrHasUnit(LuaHandle* luaHandle); - static int isFreeCells(LuaHandle* luaHandle); + static int isFreeCellsOrHasUnit(LuaHandle *luaHandle); + static int isFreeCells(LuaHandle *luaHandle); - static int getHumanFactionId(LuaHandle* luaHandle); + static int getHumanFactionId(LuaHandle *luaHandle); - static int highlightUnit(LuaHandle* luaHandle); - static int unhighlightUnit(LuaHandle* luaHandle); + static int highlightUnit(LuaHandle *luaHandle); + static int unhighlightUnit(LuaHandle *luaHandle); - static int giveStopCommand(LuaHandle* luaHandle); - static int selectUnit(LuaHandle* luaHandle); - static int unselectUnit(LuaHandle* luaHandle); - static int addUnitToGroupSelection(LuaHandle* luaHandle); - static int recallGroupSelection(LuaHandle* luaHandle); - static int removeUnitFromGroupSelection(LuaHandle* luaHandle); - static int setAttackWarningsEnabled(LuaHandle* luaHandle); - static int getAttackWarningsEnabled(LuaHandle* luaHandle); + static int giveStopCommand(LuaHandle *luaHandle); + static int selectUnit(LuaHandle *luaHandle); + static int unselectUnit(LuaHandle *luaHandle); + static int addUnitToGroupSelection(LuaHandle *luaHandle); + static int recallGroupSelection(LuaHandle *luaHandle); + static int removeUnitFromGroupSelection(LuaHandle *luaHandle); + static int setAttackWarningsEnabled(LuaHandle *luaHandle); + static int getAttackWarningsEnabled(LuaHandle *luaHandle); - static int getIsDayTime(LuaHandle* luaHandle); - static int getIsNightTime(LuaHandle* luaHandle); - static int getTimeOfDay(LuaHandle* luaHandle); - static int registerDayNightEvent(LuaHandle* luaHandle); - static int unregisterDayNightEvent(LuaHandle* luaHandle); + static int getIsDayTime(LuaHandle *luaHandle); + static int getIsNightTime(LuaHandle *luaHandle); + static int getTimeOfDay(LuaHandle *luaHandle); + static int registerDayNightEvent(LuaHandle *luaHandle); + static int unregisterDayNightEvent(LuaHandle *luaHandle); - static int registerUnitTriggerEvent(LuaHandle* luaHandle); - static int unregisterUnitTriggerEvent(LuaHandle* luaHandle); - static int getLastUnitTriggerEventUnitId(LuaHandle* luaHandle); - static int getLastUnitTriggerEventType(LuaHandle* luaHandle); - static int getUnitProperty(LuaHandle* luaHandle); - static int getUnitPropertyName(LuaHandle* luaHandle); + static int registerUnitTriggerEvent(LuaHandle *luaHandle); + static int unregisterUnitTriggerEvent(LuaHandle *luaHandle); + static int getLastUnitTriggerEventUnitId(LuaHandle *luaHandle); + static int getLastUnitTriggerEventType(LuaHandle *luaHandle); + static int getUnitProperty(LuaHandle *luaHandle); + static int getUnitPropertyName(LuaHandle *luaHandle); - static int disableSpeedChange(LuaHandle* luaHandle); - static int enableSpeedChange(LuaHandle* luaHandle); - static int getSpeedChangeEnabled(LuaHandle* luaHandle); + static int disableSpeedChange(LuaHandle *luaHandle); + static int enableSpeedChange(LuaHandle *luaHandle); + static int getSpeedChangeEnabled(LuaHandle *luaHandle); - static int storeSaveGameData(LuaHandle* luaHandle); - static int loadSaveGameData(LuaHandle* luaHandle); + static int storeSaveGameData(LuaHandle *luaHandle); + static int loadSaveGameData(LuaHandle *luaHandle); - static int getFactionPlayerType(LuaHandle* luaHandle); + static int getFactionPlayerType(LuaHandle *luaHandle); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/game/stats.cpp b/source/glest_game/game/stats.cpp index cf7ffdd79..32d633e6b 100644 --- a/source/glest_game/game/stats.cpp +++ b/source/glest_game/game/stats.cpp @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,271 +13,314 @@ #include "lang.h" #include "leak_dumper.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { PlayerStats::PlayerStats() { - control = ctClosed; - resourceMultiplier=1.0f; - //factionTypeName = ""; - personalityType = fpt_Normal; - teamIndex = 0; - victory = false; - kills = 0; - enemykills = 0; - deaths = 0; - unitsProduced = 0; - resourcesHarvested = 0; - //playerName = ""; - playerLeftBeforeEnd = false; - timePlayerLeft = -1; - playerColor = Vec3f(0,0,0); + control = ctClosed; + resourceMultiplier = 1.0f; + // factionTypeName = ""; + personalityType = fpt_Normal; + teamIndex = 0; + victory = false; + kills = 0; + enemykills = 0; + deaths = 0; + unitsProduced = 0; + resourcesHarvested = 0; + // playerName = ""; + playerLeftBeforeEnd = false; + timePlayerLeft = -1; + playerColor = Vec3f(0, 0, 0); } string PlayerStats::getStats() const { - string result = ""; - - Lang &lang= Lang::getInstance(); - string controlString = ""; - - if(personalityType == fpt_Observer) { - controlString= GameConstants::OBSERVER_SLOTNAME; - } - else { - switch(control) { - case ctCpuEasy: - controlString= lang.getString("CpuEasy"); - break; - case ctCpu: - controlString= lang.getString("Cpu"); - break; - case ctCpuUltra: - controlString= lang.getString("CpuUltra"); - break; - case ctCpuMega: - controlString= lang.getString("CpuMega"); - break; - case ctNetwork: - controlString= lang.getString("Network"); - break; - case ctHuman: - controlString= lang.getString("Human"); - break; - - case ctNetworkCpuEasy: - controlString= lang.getString("NetworkCpuEasy"); - break; - case ctNetworkCpu: - controlString= lang.getString("NetworkCpu"); - break; - case ctNetworkCpuUltra: - controlString= lang.getString("NetworkCpuUltra"); - break; - case ctNetworkCpuMega: - controlString= lang.getString("NetworkCpuMega"); - break; - - default: - printf("Error control = %d\n",control); - assert(false); - break; - }; - } - - if((control != ctHuman && control != ctNetwork) || - (control == ctNetwork && playerLeftBeforeEnd == true)) { - controlString += " x " + floatToStr(resourceMultiplier,1); - } - - result += playerName + " (" + controlString + ") "; - if(control == ctNetwork && playerLeftBeforeEnd==true ) { - result += "player left before end "; - } - result += "faction: " + factionTypeName + " "; - result += "Team: " + intToStr(teamIndex) + " "; - result += "victory: " + boolToStr(victory) + " "; - result += "# kills: " + intToStr(kills) + " "; - result += "# enemy kills: " + intToStr(enemykills) + " "; - result += "# deaths: " + intToStr(deaths) + "\n"; - result += "# units produced: " + intToStr(unitsProduced) + " "; - result += "# resources harvested: " + intToStr(resourcesHarvested); - - return result; + string result = ""; + + Lang &lang = Lang::getInstance(); + string controlString = ""; + + if (personalityType == fpt_Observer) { + controlString = GameConstants::OBSERVER_SLOTNAME; + } else { + switch (control) { + case ctCpuEasy: + controlString = lang.getString("CpuEasy"); + break; + case ctCpu: + controlString = lang.getString("Cpu"); + break; + case ctCpuUltra: + controlString = lang.getString("CpuUltra"); + break; + case ctCpuMega: + controlString = lang.getString("CpuMega"); + break; + case ctNetwork: + controlString = lang.getString("Network"); + break; + case ctHuman: + controlString = lang.getString("Human"); + break; + + case ctNetworkCpuEasy: + controlString = lang.getString("NetworkCpuEasy"); + break; + case ctNetworkCpu: + controlString = lang.getString("NetworkCpu"); + break; + case ctNetworkCpuUltra: + controlString = lang.getString("NetworkCpuUltra"); + break; + case ctNetworkCpuMega: + controlString = lang.getString("NetworkCpuMega"); + break; + + default: + printf("Error control = %d\n", control); + assert(false); + break; + }; + } + + if ((control != ctHuman && control != ctNetwork) || + (control == ctNetwork && playerLeftBeforeEnd == true)) { + controlString += " x " + floatToStr(resourceMultiplier, 1); + } + + result += playerName + " (" + controlString + ") "; + if (control == ctNetwork && playerLeftBeforeEnd == true) { + result += "player left before end "; + } + result += "faction: " + factionTypeName + " "; + result += "Team: " + intToStr(teamIndex) + " "; + result += "victory: " + boolToStr(victory) + " "; + result += "# kills: " + intToStr(kills) + " "; + result += "# enemy kills: " + intToStr(enemykills) + " "; + result += "# deaths: " + intToStr(deaths) + "\n"; + result += "# units produced: " + intToStr(unitsProduced) + " "; + result += "# resources harvested: " + intToStr(resourcesHarvested); + + return result; } // ===================================================== // class Stats // ===================================================== -void Stats::init(int factionCount, int thisFactionIndex, const string& description, const string &techName) { - this->thisFactionIndex= thisFactionIndex; - this->factionCount= factionCount; - this->description= description; - this->techName = techName; +void Stats::init(int factionCount, int thisFactionIndex, + const string &description, const string &techName) { + this->thisFactionIndex = thisFactionIndex; + this->factionCount = factionCount; + this->description = description; + this->techName = techName; } -void Stats::setVictorious(int playerIndex){ - playerStats[playerIndex].victory= true; +void Stats::setVictorious(int playerIndex) { + playerStats[playerIndex].victory = true; } -void Stats::kill(int killerFactionIndex, int killedFactionIndex, bool isEnemy, bool isDeathCounted, bool isKillCounted) { - if(isKillCounted == true){ - playerStats[killerFactionIndex].kills++; - } - if(isDeathCounted == true){ - playerStats[killedFactionIndex].deaths++; - } - if(isEnemy == true && isKillCounted == true) { - playerStats[killerFactionIndex].enemykills++; - } +void Stats::kill(int killerFactionIndex, int killedFactionIndex, bool isEnemy, + bool isDeathCounted, bool isKillCounted) { + if (isKillCounted == true) { + playerStats[killerFactionIndex].kills++; + } + if (isDeathCounted == true) { + playerStats[killedFactionIndex].deaths++; + } + if (isEnemy == true && isKillCounted == true) { + playerStats[killerFactionIndex].enemykills++; + } } -void Stats::die(int diedFactionIndex, bool isDeathCounted){ - if(isDeathCounted == true){ - playerStats[diedFactionIndex].deaths++; - } +void Stats::die(int diedFactionIndex, bool isDeathCounted) { + if (isDeathCounted == true) { + playerStats[diedFactionIndex].deaths++; + } } -void Stats::produce(int producerFactionIndex, bool isProductionCounted){ - if(isProductionCounted == true){ - playerStats[producerFactionIndex].unitsProduced++; - } +void Stats::produce(int producerFactionIndex, bool isProductionCounted) { + if (isProductionCounted == true) { + playerStats[producerFactionIndex].unitsProduced++; + } } -void Stats::harvest(int harvesterFactionIndex, int amount){ - playerStats[harvesterFactionIndex].resourcesHarvested+= amount; +void Stats::harvest(int harvesterFactionIndex, int amount) { + playerStats[harvesterFactionIndex].resourcesHarvested += amount; } string Stats::getStats() const { - string result = ""; + string result = ""; - result += "Description: " + description + "\n"; - result += "Faction count: " + intToStr(factionCount) + "\n"; + result += "Description: " + description + "\n"; + result += "Faction count: " + intToStr(factionCount) + "\n"; - result += "Game duration (mins): " + intToStr(getFramesToCalculatePlaytime()/GameConstants::updateFps/60) + "\n"; - result += "Max Concurrent Units: " + intToStr(maxConcurrentUnitCount) + "\n"; - result += "Total EndGame Concurrent Unit Count: " + intToStr(totalEndGameConcurrentUnitCount) + "\n"; + result += + "Game duration (mins): " + + intToStr(getFramesToCalculatePlaytime() / GameConstants::updateFps / 60) + + "\n"; + result += "Max Concurrent Units: " + intToStr(maxConcurrentUnitCount) + "\n"; + result += "Total EndGame Concurrent Unit Count: " + + intToStr(totalEndGameConcurrentUnitCount) + "\n"; - for(unsigned int i = 0; i < (unsigned int)factionCount; ++i) { - const PlayerStats &player = playerStats[i]; + for (unsigned int i = 0; i < (unsigned int)factionCount; ++i) { + const PlayerStats &player = playerStats[i]; - result += "player #" + uIntToStr(i) + " " + player.getStats() + "\n"; - } + result += "player #" + uIntToStr(i) + " " + player.getStats() + "\n"; + } - return result; + return result; } void Stats::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *statsNode = rootNode->addChild("Stats"); - -// PlayerStats playerStats[GameConstants::maxPlayers]; - for(unsigned int i = 0; i < (unsigned int)GameConstants::maxPlayers; ++i) { - PlayerStats &stat = playerStats[i]; - - XmlNode *statsNodePlayer = statsNode->addChild("Player"); - -// ControlType control; - statsNodePlayer->addAttribute("control",intToStr(stat.control), mapTagReplacements); -// float resourceMultiplier; - statsNodePlayer->addAttribute("resourceMultiplier",floatToStr(stat.resourceMultiplier,6), mapTagReplacements); -// string factionTypeName; - statsNodePlayer->addAttribute("factionTypeName",stat.factionTypeName, mapTagReplacements); -// FactionPersonalityType personalityType; - statsNodePlayer->addAttribute("personalityType",intToStr(stat.personalityType), mapTagReplacements); -// int teamIndex; - statsNodePlayer->addAttribute("teamIndex",intToStr(stat.teamIndex), mapTagReplacements); -// bool victory; - statsNodePlayer->addAttribute("victory",intToStr(stat.victory), mapTagReplacements); -// int kills; - statsNodePlayer->addAttribute("kills",intToStr(stat.kills), mapTagReplacements); -// int enemykills; - statsNodePlayer->addAttribute("enemykills",intToStr(stat.enemykills), mapTagReplacements); -// int deaths; - statsNodePlayer->addAttribute("deaths",intToStr(stat.deaths), mapTagReplacements); -// int unitsProduced; - statsNodePlayer->addAttribute("unitsProduced",intToStr(stat.unitsProduced), mapTagReplacements); -// int resourcesHarvested; - statsNodePlayer->addAttribute("resourcesHarvested",intToStr(stat.resourcesHarvested), mapTagReplacements); -// string playerName; - statsNodePlayer->addAttribute("playerName",stat.playerName, mapTagReplacements); -// Vec3f playerColor; - statsNodePlayer->addAttribute("playerColor",stat.playerColor.getString(), mapTagReplacements); - } -// string description; - statsNode->addAttribute("description",description, mapTagReplacements); -// int factionCount; - statsNode->addAttribute("factionCount",intToStr(factionCount), mapTagReplacements); -// int thisFactionIndex; - statsNode->addAttribute("thisFactionIndex",intToStr(thisFactionIndex), mapTagReplacements); -// -// float worldTimeElapsed; - statsNode->addAttribute("worldTimeElapsed",floatToStr(worldTimeElapsed,6), mapTagReplacements); -// int framesPlayed; - statsNode->addAttribute("framesPlayed",intToStr(framesPlayed), mapTagReplacements); -// int framesToCalculatePlaytime; - statsNode->addAttribute("framesToCalculatePlaytime",intToStr(framesToCalculatePlaytime), mapTagReplacements); -// int maxConcurrentUnitCount; - statsNode->addAttribute("maxConcurrentUnitCount",intToStr(maxConcurrentUnitCount), mapTagReplacements); -// int totalEndGameConcurrentUnitCount; - statsNode->addAttribute("totalEndGameConcurrentUnitCount",intToStr(totalEndGameConcurrentUnitCount), mapTagReplacements); -// bool isMasterserverMode; + std::map mapTagReplacements; + XmlNode *statsNode = rootNode->addChild("Stats"); + + // PlayerStats playerStats[GameConstants::maxPlayers]; + for (unsigned int i = 0; i < (unsigned int)GameConstants::maxPlayers; ++i) { + PlayerStats &stat = playerStats[i]; + + XmlNode *statsNodePlayer = statsNode->addChild("Player"); + + // ControlType control; + statsNodePlayer->addAttribute("control", intToStr(stat.control), + mapTagReplacements); + // float resourceMultiplier; + statsNodePlayer->addAttribute("resourceMultiplier", + floatToStr(stat.resourceMultiplier, 6), + mapTagReplacements); + // string factionTypeName; + statsNodePlayer->addAttribute("factionTypeName", stat.factionTypeName, + mapTagReplacements); + // FactionPersonalityType personalityType; + statsNodePlayer->addAttribute( + "personalityType", intToStr(stat.personalityType), mapTagReplacements); + // int teamIndex; + statsNodePlayer->addAttribute("teamIndex", intToStr(stat.teamIndex), + mapTagReplacements); + // bool victory; + statsNodePlayer->addAttribute("victory", intToStr(stat.victory), + mapTagReplacements); + // int kills; + statsNodePlayer->addAttribute("kills", intToStr(stat.kills), + mapTagReplacements); + // int enemykills; + statsNodePlayer->addAttribute("enemykills", intToStr(stat.enemykills), + mapTagReplacements); + // int deaths; + statsNodePlayer->addAttribute("deaths", intToStr(stat.deaths), + mapTagReplacements); + // int unitsProduced; + statsNodePlayer->addAttribute("unitsProduced", intToStr(stat.unitsProduced), + mapTagReplacements); + // int resourcesHarvested; + statsNodePlayer->addAttribute("resourcesHarvested", + intToStr(stat.resourcesHarvested), + mapTagReplacements); + // string playerName; + statsNodePlayer->addAttribute("playerName", stat.playerName, + mapTagReplacements); + // Vec3f playerColor; + statsNodePlayer->addAttribute("playerColor", stat.playerColor.getString(), + mapTagReplacements); + } + // string description; + statsNode->addAttribute("description", description, mapTagReplacements); + // int factionCount; + statsNode->addAttribute("factionCount", intToStr(factionCount), + mapTagReplacements); + // int thisFactionIndex; + statsNode->addAttribute("thisFactionIndex", intToStr(thisFactionIndex), + mapTagReplacements); + // + // float worldTimeElapsed; + statsNode->addAttribute("worldTimeElapsed", floatToStr(worldTimeElapsed, 6), + mapTagReplacements); + // int framesPlayed; + statsNode->addAttribute("framesPlayed", intToStr(framesPlayed), + mapTagReplacements); + // int framesToCalculatePlaytime; + statsNode->addAttribute("framesToCalculatePlaytime", + intToStr(framesToCalculatePlaytime), + mapTagReplacements); + // int maxConcurrentUnitCount; + statsNode->addAttribute("maxConcurrentUnitCount", + intToStr(maxConcurrentUnitCount), mapTagReplacements); + // int totalEndGameConcurrentUnitCount; + statsNode->addAttribute("totalEndGameConcurrentUnitCount", + intToStr(totalEndGameConcurrentUnitCount), + mapTagReplacements); + // bool isMasterserverMode; } void Stats::loadGame(const XmlNode *rootNode) { - const XmlNode *statsNode = rootNode->getChild("Stats"); - - // PlayerStats playerStats[GameConstants::maxPlayers]; - - vector statsNodePlayerList = statsNode->getChildList("Player"); - for(unsigned int i = 0; i < statsNodePlayerList.size(); ++i) { - XmlNode *statsNodePlayer = statsNodePlayerList[i]; - PlayerStats &stat = playerStats[i]; - - // ControlType control; - stat.control = static_cast(statsNodePlayer->getAttribute("control")->getIntValue()); - // float resourceMultiplier; - stat.resourceMultiplier = statsNodePlayer->getAttribute("resourceMultiplier")->getFloatValue(); - // string factionTypeName; - stat.factionTypeName = statsNodePlayer->getAttribute("factionTypeName")->getValue(); - // FactionPersonalityType personalityType; - stat.personalityType = static_cast(statsNodePlayer->getAttribute("personalityType")->getIntValue()); - // int teamIndex; - stat.teamIndex = statsNodePlayer->getAttribute("teamIndex")->getIntValue(); - // bool victory; - stat.victory = statsNodePlayer->getAttribute("victory")->getIntValue() != 0; - // int kills; - stat.kills = statsNodePlayer->getAttribute("kills")->getIntValue(); - // int enemykills; - stat.enemykills = statsNodePlayer->getAttribute("enemykills")->getIntValue(); - // int deaths; - stat.deaths = statsNodePlayer->getAttribute("deaths")->getIntValue(); - // int unitsProduced; - stat.unitsProduced = statsNodePlayer->getAttribute("unitsProduced")->getIntValue(); - // int resourcesHarvested; - stat.resourcesHarvested = statsNodePlayer->getAttribute("resourcesHarvested")->getIntValue(); - // string playerName; - stat.playerName = statsNodePlayer->getAttribute("playerName")->getValue(); - // Vec3f playerColor; - stat.playerColor = Vec3f::strToVec3(statsNodePlayer->getAttribute("playerColor")->getValue()); - } - // string description; - //statsNode->addAttribute("description",description, mapTagReplacements); - description = statsNode->getAttribute("description")->getValue(); - // int factionCount; - factionCount = statsNode->getAttribute("factionCount")->getIntValue(); - // int thisFactionIndex; - thisFactionIndex = statsNode->getAttribute("thisFactionIndex")->getIntValue(); - // - // float worldTimeElapsed; - worldTimeElapsed = statsNode->getAttribute("worldTimeElapsed")->getFloatValue(); - // int framesPlayed; - framesPlayed = statsNode->getAttribute("framesPlayed")->getIntValue(); - // int framesToCalculatePlaytime; - framesToCalculatePlaytime = statsNode->getAttribute("framesToCalculatePlaytime")->getIntValue(); - // int maxConcurrentUnitCount; - maxConcurrentUnitCount = statsNode->getAttribute("maxConcurrentUnitCount")->getIntValue(); - // int totalEndGameConcurrentUnitCount; - totalEndGameConcurrentUnitCount = statsNode->getAttribute("totalEndGameConcurrentUnitCount")->getIntValue(); - // bool isMasterserverMode; + const XmlNode *statsNode = rootNode->getChild("Stats"); + + // PlayerStats playerStats[GameConstants::maxPlayers]; + + vector statsNodePlayerList = statsNode->getChildList("Player"); + for (unsigned int i = 0; i < statsNodePlayerList.size(); ++i) { + XmlNode *statsNodePlayer = statsNodePlayerList[i]; + PlayerStats &stat = playerStats[i]; + + // ControlType control; + stat.control = static_cast( + statsNodePlayer->getAttribute("control")->getIntValue()); + // float resourceMultiplier; + stat.resourceMultiplier = + statsNodePlayer->getAttribute("resourceMultiplier")->getFloatValue(); + // string factionTypeName; + stat.factionTypeName = + statsNodePlayer->getAttribute("factionTypeName")->getValue(); + // FactionPersonalityType personalityType; + stat.personalityType = static_cast( + statsNodePlayer->getAttribute("personalityType")->getIntValue()); + // int teamIndex; + stat.teamIndex = statsNodePlayer->getAttribute("teamIndex")->getIntValue(); + // bool victory; + stat.victory = statsNodePlayer->getAttribute("victory")->getIntValue() != 0; + // int kills; + stat.kills = statsNodePlayer->getAttribute("kills")->getIntValue(); + // int enemykills; + stat.enemykills = + statsNodePlayer->getAttribute("enemykills")->getIntValue(); + // int deaths; + stat.deaths = statsNodePlayer->getAttribute("deaths")->getIntValue(); + // int unitsProduced; + stat.unitsProduced = + statsNodePlayer->getAttribute("unitsProduced")->getIntValue(); + // int resourcesHarvested; + stat.resourcesHarvested = + statsNodePlayer->getAttribute("resourcesHarvested")->getIntValue(); + // string playerName; + stat.playerName = statsNodePlayer->getAttribute("playerName")->getValue(); + // Vec3f playerColor; + stat.playerColor = Vec3f::strToVec3( + statsNodePlayer->getAttribute("playerColor")->getValue()); + } + // string description; + // statsNode->addAttribute("description",description, mapTagReplacements); + description = statsNode->getAttribute("description")->getValue(); + // int factionCount; + factionCount = statsNode->getAttribute("factionCount")->getIntValue(); + // int thisFactionIndex; + thisFactionIndex = statsNode->getAttribute("thisFactionIndex")->getIntValue(); + // + // float worldTimeElapsed; + worldTimeElapsed = + statsNode->getAttribute("worldTimeElapsed")->getFloatValue(); + // int framesPlayed; + framesPlayed = statsNode->getAttribute("framesPlayed")->getIntValue(); + // int framesToCalculatePlaytime; + framesToCalculatePlaytime = + statsNode->getAttribute("framesToCalculatePlaytime")->getIntValue(); + // int maxConcurrentUnitCount; + maxConcurrentUnitCount = + statsNode->getAttribute("maxConcurrentUnitCount")->getIntValue(); + // int totalEndGameConcurrentUnitCount; + totalEndGameConcurrentUnitCount = + statsNode->getAttribute("totalEndGameConcurrentUnitCount")->getIntValue(); + // bool isMasterserverMode; } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/game/stats.h b/source/glest_game/game/stats.h index a460fd0a2..af7245c90 100644 --- a/source/glest_game/game/stats.h +++ b/source/glest_game/game/stats.h @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,43 +13,44 @@ #define _GLEST_GAME_STATS_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include -#include "game_constants.h" #include "faction.h" #include "faction_type.h" -#include "vec.h" +#include "game_constants.h" #include "leak_dumper.h" +#include "vec.h" +#include using std::string; using namespace Shared::Graphics; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { class PlayerStats { public: - PlayerStats(); - - ControlType control; - float resourceMultiplier; - string factionTypeName; - FactionPersonalityType personalityType; - int teamIndex; - bool victory; - int kills; - int enemykills; - int deaths; - int unitsProduced; - int resourcesHarvested; - string playerName; - bool playerLeftBeforeEnd; - int timePlayerLeft; - Vec3f playerColor; - - string getStats() const; + PlayerStats(); + + ControlType control; + float resourceMultiplier; + string factionTypeName; + FactionPersonalityType personalityType; + int teamIndex; + bool victory; + int kills; + int enemykills; + int deaths; + int unitsProduced; + int resourcesHarvested; + string playerName; + bool playerLeftBeforeEnd; + int timePlayerLeft; + Vec3f playerColor; + + string getStats() const; }; // ===================================================== @@ -60,102 +61,158 @@ class PlayerStats { class Stats { private: - PlayerStats playerStats[GameConstants::maxPlayers]; - - string description; - int factionCount; - int thisFactionIndex; - - float worldTimeElapsed; - int framesPlayed; - int framesToCalculatePlaytime; - int maxConcurrentUnitCount; - int totalEndGameConcurrentUnitCount; - bool isMasterserverMode; - string techName; + PlayerStats playerStats[GameConstants::maxPlayers]; -public: + string description; + int factionCount; + int thisFactionIndex; - Stats() { - //description = ""; - factionCount = 0; - thisFactionIndex = 0; - - worldTimeElapsed = 0.0; - framesPlayed = 0; - framesToCalculatePlaytime = 0; - maxConcurrentUnitCount = 0; - totalEndGameConcurrentUnitCount = 0; - isMasterserverMode = false; - //techName = ""; - } - - void init(int factionCount, int thisFactionIndex, const string &description, - const string &techName); - - string getDescription() const {return description;} - int getThisFactionIndex() const {return thisFactionIndex;} - int getFactionCount() const {return factionCount;} - - float getWorldTimeElapsed() const {return worldTimeElapsed;} - int getFramesPlayed() const {return framesPlayed; } - int getFramesToCalculatePlaytime() const {return framesToCalculatePlaytime; } - int getMaxConcurrentUnitCount() const {return maxConcurrentUnitCount; } - int getTotalEndGameConcurrentUnitCount() const {return totalEndGameConcurrentUnitCount; } - - const string &getFactionTypeName(int factionIndex) const {return playerStats[factionIndex].factionTypeName;} - FactionPersonalityType getPersonalityType(int factionIndex) const { return playerStats[factionIndex].personalityType;} - ControlType getControl(int factionIndex) const {return playerStats[factionIndex].control;} - float getResourceMultiplier(int factionIndex) const {return playerStats[factionIndex].resourceMultiplier;} - bool getVictory(int factionIndex) const {return playerStats[factionIndex].victory;} - int getTeam(int factionIndex) const {return playerStats[factionIndex].teamIndex;} - int getKills(int factionIndex) const {return playerStats[factionIndex].kills;} - int getEnemyKills(int factionIndex) const {return playerStats[factionIndex].enemykills;} - int getDeaths(int factionIndex) const {return playerStats[factionIndex].deaths;} - int getUnitsProduced(int factionIndex) const {return playerStats[factionIndex].unitsProduced;} - int getResourcesHarvested(int factionIndex) const {return playerStats[factionIndex].resourcesHarvested;} - string getPlayerName(int factionIndex) const {return playerStats[factionIndex].playerName;} - bool getPlayerLeftBeforeEnd(int factionIndex) const {return playerStats[factionIndex].playerLeftBeforeEnd;} - void setPlayerLeftBeforeEnd(int factionIndex, bool value) {playerStats[factionIndex].playerLeftBeforeEnd = value; } - Vec3f getPlayerColor(int factionIndex) const { return playerStats[factionIndex].playerColor;} - - int getTimePlayerLeft(int factionIndex) const {return playerStats[factionIndex].timePlayerLeft;} - void setTimePlayerLeft(int factionIndex, int value) {playerStats[factionIndex].timePlayerLeft = value; } - - - bool getIsMasterserverMode() const { return isMasterserverMode; } - void setIsMasterserverMode(bool value) { isMasterserverMode = value; } - - void setDescription(const string& description) {this->description = description;} - void setWorldTimeElapsed(float value) {this->worldTimeElapsed = value;} - void setFramesPlayed(int value) {this->framesPlayed = value; } - void setMaxConcurrentUnitCount(int value) {this->maxConcurrentUnitCount = value; } - void setTotalEndGameConcurrentUnitCount(int value) {this->totalEndGameConcurrentUnitCount = value; } - - void setFactionTypeName(int playerIndex, const string& factionTypeName) {playerStats[playerIndex].factionTypeName= factionTypeName;} - void setPersonalityType(int playerIndex, FactionPersonalityType value) {playerStats[playerIndex].personalityType = value;} - void setControl(int playerIndex, ControlType control) {playerStats[playerIndex].control= control;} - void setResourceMultiplier(int playerIndex, float resourceMultiplier) {playerStats[playerIndex].resourceMultiplier= resourceMultiplier;} - void setTeam(int playerIndex, int teamIndex) {playerStats[playerIndex].teamIndex= teamIndex;} - void setVictorious(int playerIndex); - void kill(int killerFactionIndex, int killedFactionIndex, bool isEnemy, bool isDeathCounted, bool isKillCounted); - void die(int diedFactionIndex, bool isDeathCounted); - void produce(int producerFactionIndex, bool isProductionCounted); - void harvest(int harvesterFactionIndex, int amount); - void setPlayerName(int playerIndex, const string &value) {playerStats[playerIndex].playerName = value; } - void setPlayerColor(int playerIndex, Vec3f value) {playerStats[playerIndex].playerColor = value; } - - void addFramesToCalculatePlaytime() {this->framesToCalculatePlaytime++; } - - void setTechName(const string &name) { techName = name; } - string getTechName() const { return techName; } - - string getStats() const; - - void saveGame(XmlNode *rootNode); - void loadGame(const XmlNode *rootNode); + float worldTimeElapsed; + int framesPlayed; + int framesToCalculatePlaytime; + int maxConcurrentUnitCount; + int totalEndGameConcurrentUnitCount; + bool isMasterserverMode; + string techName; + +public: + Stats() { + // description = ""; + factionCount = 0; + thisFactionIndex = 0; + + worldTimeElapsed = 0.0; + framesPlayed = 0; + framesToCalculatePlaytime = 0; + maxConcurrentUnitCount = 0; + totalEndGameConcurrentUnitCount = 0; + isMasterserverMode = false; + // techName = ""; + } + + void init(int factionCount, int thisFactionIndex, const string &description, + const string &techName); + + string getDescription() const { return description; } + int getThisFactionIndex() const { return thisFactionIndex; } + int getFactionCount() const { return factionCount; } + + float getWorldTimeElapsed() const { return worldTimeElapsed; } + int getFramesPlayed() const { return framesPlayed; } + int getFramesToCalculatePlaytime() const { return framesToCalculatePlaytime; } + int getMaxConcurrentUnitCount() const { return maxConcurrentUnitCount; } + int getTotalEndGameConcurrentUnitCount() const { + return totalEndGameConcurrentUnitCount; + } + + const string &getFactionTypeName(int factionIndex) const { + return playerStats[factionIndex].factionTypeName; + } + FactionPersonalityType getPersonalityType(int factionIndex) const { + return playerStats[factionIndex].personalityType; + } + ControlType getControl(int factionIndex) const { + return playerStats[factionIndex].control; + } + float getResourceMultiplier(int factionIndex) const { + return playerStats[factionIndex].resourceMultiplier; + } + bool getVictory(int factionIndex) const { + return playerStats[factionIndex].victory; + } + int getTeam(int factionIndex) const { + return playerStats[factionIndex].teamIndex; + } + int getKills(int factionIndex) const { + return playerStats[factionIndex].kills; + } + int getEnemyKills(int factionIndex) const { + return playerStats[factionIndex].enemykills; + } + int getDeaths(int factionIndex) const { + return playerStats[factionIndex].deaths; + } + int getUnitsProduced(int factionIndex) const { + return playerStats[factionIndex].unitsProduced; + } + int getResourcesHarvested(int factionIndex) const { + return playerStats[factionIndex].resourcesHarvested; + } + string getPlayerName(int factionIndex) const { + return playerStats[factionIndex].playerName; + } + bool getPlayerLeftBeforeEnd(int factionIndex) const { + return playerStats[factionIndex].playerLeftBeforeEnd; + } + void setPlayerLeftBeforeEnd(int factionIndex, bool value) { + playerStats[factionIndex].playerLeftBeforeEnd = value; + } + Vec3f getPlayerColor(int factionIndex) const { + return playerStats[factionIndex].playerColor; + } + + int getTimePlayerLeft(int factionIndex) const { + return playerStats[factionIndex].timePlayerLeft; + } + void setTimePlayerLeft(int factionIndex, int value) { + playerStats[factionIndex].timePlayerLeft = value; + } + + bool getIsMasterserverMode() const { return isMasterserverMode; } + void setIsMasterserverMode(bool value) { isMasterserverMode = value; } + + void setDescription(const string &description) { + this->description = description; + } + void setWorldTimeElapsed(float value) { this->worldTimeElapsed = value; } + void setFramesPlayed(int value) { this->framesPlayed = value; } + void setMaxConcurrentUnitCount(int value) { + this->maxConcurrentUnitCount = value; + } + void setTotalEndGameConcurrentUnitCount(int value) { + this->totalEndGameConcurrentUnitCount = value; + } + + void setFactionTypeName(int playerIndex, const string &factionTypeName) { + playerStats[playerIndex].factionTypeName = factionTypeName; + } + void setPersonalityType(int playerIndex, FactionPersonalityType value) { + playerStats[playerIndex].personalityType = value; + } + void setControl(int playerIndex, ControlType control) { + playerStats[playerIndex].control = control; + } + void setResourceMultiplier(int playerIndex, float resourceMultiplier) { + playerStats[playerIndex].resourceMultiplier = resourceMultiplier; + } + void setTeam(int playerIndex, int teamIndex) { + playerStats[playerIndex].teamIndex = teamIndex; + } + void setVictorious(int playerIndex); + void kill(int killerFactionIndex, int killedFactionIndex, bool isEnemy, + bool isDeathCounted, bool isKillCounted); + void die(int diedFactionIndex, bool isDeathCounted); + void produce(int producerFactionIndex, bool isProductionCounted); + void harvest(int harvesterFactionIndex, int amount); + void setPlayerName(int playerIndex, const string &value) { + playerStats[playerIndex].playerName = value; + } + void setPlayerColor(int playerIndex, Vec3f value) { + playerStats[playerIndex].playerColor = value; + } + + void addFramesToCalculatePlaytime() { this->framesToCalculatePlaytime++; } + + void setTechName(const string &name) { techName = name; } + string getTechName() const { return techName; } + + string getStats() const; + + void saveGame(XmlNode *rootNode); + void loadGame(const XmlNode *rootNode); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/global/config.cpp b/source/glest_game/global/config.cpp index b150f8717..387d9a1f3 100644 --- a/source/glest_game/global/config.cpp +++ b/source/glest_game/global/config.cpp @@ -11,91 +11,98 @@ #include "config.h" -#include "util.h" +#include "conversion.h" #include "game_constants.h" -#include "platform_util.h" #include "game_util.h" -#include -#include "conversion.h" +#include "leak_dumper.h" +#include "platform_util.h" +#include "util.h" #include "window.h" -#include #include -#include "leak_dumper.h" +#include +#include using namespace Shared::Platform; using namespace Shared::Util; using namespace std; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { -int GameConstants::networkFramePeriod = 20; -int GameConstants::updateFps = 40; -int GameConstants::cameraFps = 100; +int GameConstants::networkFramePeriod = 20; +int GameConstants::updateFps = 40; +int GameConstants::cameraFps = 100; -const float GameConstants::normalMultiplier = 1.0f; -const float GameConstants::easyMultiplier = 0.5f; -const float GameConstants::ultraMultiplier = 1.5f; -const float GameConstants::megaMultiplier = 2.5f; +const float GameConstants::normalMultiplier = 1.0f; +const float GameConstants::easyMultiplier = 0.5f; +const float GameConstants::ultraMultiplier = 1.5f; +const float GameConstants::megaMultiplier = 2.5f; -const char *GameConstants::folder_path_maps = "maps"; -const char *GameConstants::folder_path_scenarios = "scenarios"; -const char *GameConstants::folder_path_techs = "techs"; -const char *GameConstants::folder_path_tilesets = "tilesets"; -const char *GameConstants::folder_path_tutorials = "tutorials"; +const char *GameConstants::folder_path_maps = "maps"; +const char *GameConstants::folder_path_scenarios = "scenarios"; +const char *GameConstants::folder_path_techs = "techs"; +const char *GameConstants::folder_path_tilesets = "tilesets"; +const char *GameConstants::folder_path_tutorials = "tutorials"; const char *GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME = "???"; const char *GameConstants::NETWORK_SLOT_CLOSED_SLOTNAME = "Closed"; -const char *GameConstants::folder_path_screenshots = "screens/"; -const char *GameConstants::folder_path_setups = "setups/"; +const char *GameConstants::folder_path_screenshots = "screens/"; +const char *GameConstants::folder_path_setups = "setups/"; -const char *GameConstants::OBSERVER_SLOTNAME = "*Observer*"; -const char *GameConstants::RANDOMFACTION_SLOTNAME = "*Random*"; +const char *GameConstants::OBSERVER_SLOTNAME = "*Observer*"; +const char *GameConstants::RANDOMFACTION_SLOTNAME = "*Random*"; -const char *GameConstants::steamCacheInstanceKey = "steamInstanceCache"; -const char *GameConstants::preCacheThreadCacheLookupKey = "preCacheThreadCache"; -const char *GameConstants::ircClientCacheLookupKey = "ircClientCache"; -const char *GameConstants::playerTextureCacheLookupKey = "playerTextureCache"; -const char *GameConstants::factionPreviewTextureCacheLookupKey = "factionPreviewTextureCache"; -const char *GameConstants::characterMenuScreenPositionListCacheLookupKey = "characterMenuScreenPositionListCache"; -const char *GameConstants::application_name = "MegaGlest"; +const char *GameConstants::steamCacheInstanceKey = "steamInstanceCache"; +const char *GameConstants::preCacheThreadCacheLookupKey = "preCacheThreadCache"; +const char *GameConstants::ircClientCacheLookupKey = "ircClientCache"; +const char *GameConstants::playerTextureCacheLookupKey = "playerTextureCache"; +const char *GameConstants::factionPreviewTextureCacheLookupKey = + "factionPreviewTextureCache"; +const char *GameConstants::characterMenuScreenPositionListCacheLookupKey = + "characterMenuScreenPositionListCache"; +const char *GameConstants::application_name = "MegaGlest"; -const char * GameConstants::LOADING_SCREEN_FILE = "loading_screen"; -const char * GameConstants::LOADING_SCREEN_FILE_FILTER = "loading_screen*.*"; -const char * GameConstants::PREVIEW_SCREEN_FILE = "preview_screen"; -const char * GameConstants::PREVIEW_SCREEN_FILE_FILTER = "preview_screen*.*"; -const char * GameConstants::HUD_SCREEN_FILE = "hud"; -const char * GameConstants::HUD_SCREEN_FILE_FILTER = "hud*.*"; +const char *GameConstants::LOADING_SCREEN_FILE = "loading_screen"; +const char *GameConstants::LOADING_SCREEN_FILE_FILTER = "loading_screen*.*"; +const char *GameConstants::PREVIEW_SCREEN_FILE = "preview_screen"; +const char *GameConstants::PREVIEW_SCREEN_FILE_FILTER = "preview_screen*.*"; +const char *GameConstants::HUD_SCREEN_FILE = "hud"; +const char *GameConstants::HUD_SCREEN_FILE_FILTER = "hud*.*"; +const char *GameConstants::pathCacheLookupKey = "pathCache_"; +const char *GameConstants::path_data_CacheLookupKey = "data"; +const char *GameConstants::path_ini_CacheLookupKey = "ini"; +const char *GameConstants::path_logs_CacheLookupKey = "logs"; -const char *GameConstants::pathCacheLookupKey = "pathCache_"; -const char *GameConstants::path_data_CacheLookupKey = "data"; -const char *GameConstants::path_ini_CacheLookupKey = "ini"; -const char *GameConstants::path_logs_CacheLookupKey = "logs"; +const char *GameConstants::saveNetworkGameFileServer = + "megaglest-saved-server.xml"; +const char *GameConstants::saveNetworkGameFileServerCompressed = + "megaglest-saved-server.zip"; -const char *GameConstants::saveNetworkGameFileServer = "megaglest-saved-server.xml"; -const char *GameConstants::saveNetworkGameFileServerCompressed = "megaglest-saved-server.zip"; +const char *GameConstants::saveNetworkGameFileClient = + "megaglest-saved-client.xml"; +const char *GameConstants::saveNetworkGameFileClientCompressed = + "megaglest-saved-client.zip"; -const char *GameConstants::saveNetworkGameFileClient = "megaglest-saved-client.xml"; -const char *GameConstants::saveNetworkGameFileClientCompressed = "megaglest-saved-client.zip"; +const char *GameConstants::saveGameFileDefault = "megaglest-saved.xml"; +const char *GameConstants::saveGameFileAutoTestDefault = + "megaglest-auto-saved_%s.xml"; +const char *GameConstants::saveGameFilePattern = "megaglest-saved_%s.xml"; -const char *GameConstants::saveGameFileDefault = "megaglest-saved.xml"; -const char *GameConstants::saveGameFileAutoTestDefault = "megaglest-auto-saved_%s.xml"; -const char *GameConstants::saveGameFilePattern = "megaglest-saved_%s.xml"; +const char *Config::glest_ini_filename = "glest.ini"; +const char *Config::glestuser_ini_filename = "glestuser.ini"; -const char *Config::glest_ini_filename = "glest.ini"; -const char *Config::glestuser_ini_filename = "glestuser.ini"; +const char *Config::glestkeys_ini_filename = "glestkeys.ini"; +const char *Config::glestuserkeys_ini_filename = "glestuserkeys.ini"; -const char *Config::glestkeys_ini_filename = "glestkeys.ini"; -const char *Config::glestuserkeys_ini_filename = "glestuserkeys.ini"; +const char *Config::ACTIVE_MOD_PROPERTY_NAME = "current_mod_name"; -const char *Config::ACTIVE_MOD_PROPERTY_NAME = "current_mod_name"; +const char *Config::colorPicking = "color"; +const char *Config::selectBufPicking = "selectbuf"; +const char *Config::frustumPicking = "frustum"; - const char *Config::colorPicking = "color"; - const char *Config::selectBufPicking = "selectbuf"; - const char *Config::frustumPicking = "frustum"; - -map Config::customRuntimeProperties; +map Config::customRuntimeProperties; // ===================================================== // class Config @@ -103,813 +110,919 @@ map Config::customRuntimeProperties; const string defaultNotFoundValue = "~~NOT FOUND~~"; -map Config::configList; +map Config::configList; Config::Config() { - fileLoaded.first = false; - fileLoaded.second = false; - cfgType.first = cfgMainGame; - cfgType.second = cfgUserGame; - fileName.first = ""; - fileName.second = ""; - fileNameParameter.first = ""; - fileNameParameter.second = ""; - custom_path_parameter = ""; + fileLoaded.first = false; + fileLoaded.second = false; + cfgType.first = cfgMainGame; + cfgType.second = cfgUserGame; + fileName.first = ""; + fileName.second = ""; + fileNameParameter.first = ""; + fileNameParameter.second = ""; + custom_path_parameter = ""; } -bool Config::tryCustomPath(std::pair &type, std::pair &file, string custom_path) { - bool wasFound = false; - if((type.first == cfgMainGame && type.second == cfgUserGame && - file.first == glest_ini_filename && file.second == glestuser_ini_filename) || - (type.first == cfgMainKeys && type.second == cfgUserKeys && - file.first == glestkeys_ini_filename && file.second == glestuserkeys_ini_filename)) { - - string linuxPath = custom_path; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("-=-=-=-=-=-=-= looking for file in possible location [%s]\n",linuxPath.c_str()); +bool Config::tryCustomPath(std::pair &type, + std::pair &file, + string custom_path) { + bool wasFound = false; + if ((type.first == cfgMainGame && type.second == cfgUserGame && + file.first == glest_ini_filename && + file.second == glestuser_ini_filename) || + (type.first == cfgMainKeys && type.second == cfgUserKeys && + file.first == glestkeys_ini_filename && + file.second == glestuserkeys_ini_filename)) { + + string linuxPath = custom_path; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("-=-=-=-=-=-=-= looking for file in possible location [%s]\n", + linuxPath.c_str()); #if defined(__linux__) - string nixFile = linuxPath + "linux_" + file.first; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("-=-=-=-=-=-=-= looking for linux specific file in possible location [%s]\n",nixFile.c_str()); - - if(wasFound == false && fileExists(nixFile) == true) { - file.first = nixFile; - file.second = linuxPath + file.second; - wasFound = true; - } + string nixFile = linuxPath + "linux_" + file.first; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("-=-=-=-=-=-=-= looking for linux specific file in possible " + "location [%s]\n", + nixFile.c_str()); + + if (wasFound == false && fileExists(nixFile) == true) { + file.first = nixFile; + file.second = linuxPath + file.second; + wasFound = true; + } #elif defined(__WIN32__) - string winFile = linuxPath + "windows_" + file.first; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("-=-=-=-=-=-=-= looking for windows specific file in possible location [%s]\n",winFile.c_str()); - - if(wasFound == false && fileExists(winFile) == true) { - file.first = winFile; - file.second = linuxPath + file.second; - wasFound = true; - } + string winFile = linuxPath + "windows_" + file.first; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("-=-=-=-=-=-=-= looking for windows specific file in possible " + "location [%s]\n", + winFile.c_str()); + + if (wasFound == false && fileExists(winFile) == true) { + file.first = winFile; + file.second = linuxPath + file.second; + wasFound = true; + } #endif - if(wasFound == false && fileExists(linuxPath + file.first) == true) { - file.first = linuxPath + file.first; - file.second = linuxPath + file.second; - wasFound = true; - } + if (wasFound == false && fileExists(linuxPath + file.first) == true) { + file.first = linuxPath + file.first; + file.second = linuxPath + file.second; + wasFound = true; } - return wasFound; + } + return wasFound; } -Config::Config(std::pair type, std::pair file, std::pair fileMustExist,string custom_path) { - fileLoaded.first = false; - fileLoaded.second = false; - cfgType = type; - fileName = file; - fileNameParameter = file; - custom_path_parameter = custom_path; - - if(getGameReadWritePath(GameConstants::path_ini_CacheLookupKey) != "") { - fileName.first = getGameReadWritePath(GameConstants::path_ini_CacheLookupKey) + fileName.first; - fileName.second = getGameReadWritePath(GameConstants::path_ini_CacheLookupKey) + fileName.second; - } - - bool foundPath = false; - string currentpath = custom_path; - - if(custom_path != "") { - foundPath = tryCustomPath(cfgType, fileName, custom_path); - } - - if(foundPath == false) { - currentpath = extractDirectoryPathFromFile(Properties::getApplicationPath()); - foundPath = tryCustomPath(cfgType, fileName, currentpath); - } +Config::Config(std::pair type, + std::pair file, + std::pair fileMustExist, string custom_path) { + fileLoaded.first = false; + fileLoaded.second = false; + cfgType = type; + fileName = file; + fileNameParameter = file; + custom_path_parameter = custom_path; + + if (getGameReadWritePath(GameConstants::path_ini_CacheLookupKey) != "") { + fileName.first = + getGameReadWritePath(GameConstants::path_ini_CacheLookupKey) + + fileName.first; + fileName.second = + getGameReadWritePath(GameConstants::path_ini_CacheLookupKey) + + fileName.second; + } + + bool foundPath = false; + string currentpath = custom_path; + + if (custom_path != "") { + foundPath = tryCustomPath(cfgType, fileName, custom_path); + } + + if (foundPath == false) { + currentpath = + extractDirectoryPathFromFile(Properties::getApplicationPath()); + foundPath = tryCustomPath(cfgType, fileName, currentpath); + } #if defined(CUSTOM_DATA_INSTALL_PATH) - if(foundPath == false) { + if (foundPath == false) { #ifndef NO_APPIMAGE - foundPath = tryCustomPath(cfgType, fileName, Properties::appendAppDirPath(formatPath(TOSTRING(CUSTOM_DATA_INSTALL_PATH)))); + foundPath = tryCustomPath(cfgType, fileName, + Properties::appendAppDirPath(formatPath( + TOSTRING(CUSTOM_DATA_INSTALL_PATH)))); #else - foundPath = tryCustomPath(cfgType, fileName, formatPath(TOSTRING(CUSTOM_DATA_INSTALL_PATH))); + foundPath = tryCustomPath(cfgType, fileName, + formatPath(TOSTRING(CUSTOM_DATA_INSTALL_PATH))); #endif - } + } #endif #if defined(MG_CMAKE_INSTALL_PREFIX) - if(foundPath == false) { - foundPath = tryCustomPath(cfgType, fileName, formatPath(TOSTRING(MG_CMAKE_INSTALL_PREFIX))); - } + if (foundPath == false) { + foundPath = tryCustomPath(cfgType, fileName, + formatPath(TOSTRING(MG_CMAKE_INSTALL_PREFIX))); + } #endif // Look in standard linux shared paths for ini files #if defined(__linux__) - if(foundPath == false) { - foundPath = tryCustomPath(cfgType, fileName, "/usr/share/megaglest/"); - } - if(foundPath == false) { - foundPath = tryCustomPath(cfgType, fileName, "/usr/share/games/megaglest/"); - } - if(foundPath == false) { - foundPath = tryCustomPath(cfgType, fileName, "/usr/local/share/megaglest/"); - } - if(foundPath == false) { - foundPath = tryCustomPath(cfgType, fileName, "/usr/local/share/games/megaglest/"); - } + if (foundPath == false) { + foundPath = tryCustomPath(cfgType, fileName, "/usr/share/megaglest/"); + } + if (foundPath == false) { + foundPath = tryCustomPath(cfgType, fileName, "/usr/share/games/megaglest/"); + } + if (foundPath == false) { + foundPath = tryCustomPath(cfgType, fileName, "/usr/local/share/megaglest/"); + } + if (foundPath == false) { + foundPath = + tryCustomPath(cfgType, fileName, "/usr/local/share/games/megaglest/"); + } #endif - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("foundPath = [%d]\n",foundPath); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("foundPath = [%d]\n", foundPath); - if(fileMustExist.first == true && fileExists(fileName.first) == false) { - //string currentpath = extractDirectoryPathFromFile(Properties::getApplicationPath()); - fileName.first = currentpath + fileName.first; - } + if (fileMustExist.first == true && fileExists(fileName.first) == false) { + // string currentpath = + // extractDirectoryPathFromFile(Properties::getApplicationPath()); + fileName.first = currentpath + fileName.first; + } #if defined(WIN32) - //string test = "C:\\Code\\megaglest\\mk\\windoze\\.\\..\\..\\data\\glest_game\\glest.ini"; - //updatePathClimbingParts(test); + // string test = + // "C:\\Code\\megaglest\\mk\\windoze\\.\\..\\..\\data\\glest_game\\glest.ini"; + // updatePathClimbingParts(test); - updatePathClimbingParts(fileName.first); + updatePathClimbingParts(fileName.first); #endif - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("-=-=-=-=-=-=-= About to load fileName.first = [%s]\n",fileName.first.c_str()); - - if(fileMustExist.first == true || - (fileMustExist.first == false && fileExists(fileName.first) == true)) { - properties.first.load(fileName.first); - fileLoaded.first = true; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("-=-=-=-=-=-=-= About to load fileName.first = [%s]\n", + fileName.first.c_str()); + + if (fileMustExist.first == true || + (fileMustExist.first == false && fileExists(fileName.first) == true)) { + properties.first.load(fileName.first); + fileLoaded.first = true; + } + + if (cfgType.first == cfgMainGame) { + if (properties.first.getString("UserData_Root", + defaultNotFoundValue.c_str()) != + defaultNotFoundValue) { + string userData = properties.first.getString("UserData_Root"); + if (userData != "") { + endPathWithSlash(userData); + } + fileName.second = userData + fileNameParameter.second; + } else if (properties.first.getString("UserOverrideFile", + defaultNotFoundValue.c_str()) != + defaultNotFoundValue) { + string userData = properties.first.getString("UserOverrideFile"); + if (userData != "") { + endPathWithSlash(userData); + } + fileName.second = userData + fileNameParameter.second; } - if(cfgType.first == cfgMainGame) { - if( properties.first.getString("UserData_Root", defaultNotFoundValue.c_str()) != defaultNotFoundValue) { - string userData = properties.first.getString("UserData_Root"); - if(userData != "") { - endPathWithSlash(userData); - } - fileName.second = userData + fileNameParameter.second; - } - else if(properties.first.getString("UserOverrideFile", defaultNotFoundValue.c_str()) != defaultNotFoundValue) { - string userData = properties.first.getString("UserOverrideFile"); - if(userData != "") { - endPathWithSlash(userData); - } - fileName.second = userData + fileNameParameter.second; - } - #if defined(WIN32) - updatePathClimbingParts(fileName.second); + updatePathClimbingParts(fileName.second); #endif + } else if (cfgType.first == cfgMainKeys) { + Config &mainCfg = Config::getInstance(); + if (mainCfg.getString("UserData_Root", defaultNotFoundValue.c_str()) != + defaultNotFoundValue) { + string userData = mainCfg.getString("UserData_Root"); + if (userData != "") { + endPathWithSlash(userData); + } + fileName.second = userData + fileNameParameter.second; + } else if (mainCfg.getString("UserOverrideFile", + defaultNotFoundValue.c_str()) != + defaultNotFoundValue) { + string userData = mainCfg.getString("UserOverrideFile"); + if (userData != "") { + endPathWithSlash(userData); + } + fileName.second = userData + fileNameParameter.second; } - else if(cfgType.first == cfgMainKeys) { - Config &mainCfg = Config::getInstance(); - if( mainCfg.getString("UserData_Root", defaultNotFoundValue.c_str()) != defaultNotFoundValue) { - string userData = mainCfg.getString("UserData_Root"); - if(userData != "") { - endPathWithSlash(userData); - } - fileName.second = userData + fileNameParameter.second; - } - else if(mainCfg.getString("UserOverrideFile", defaultNotFoundValue.c_str()) != defaultNotFoundValue) { - string userData = mainCfg.getString("UserOverrideFile"); - if(userData != "") { - endPathWithSlash(userData); - } - fileName.second = userData + fileNameParameter.second; - } #if defined(WIN32) - updatePathClimbingParts(fileName.second); + updatePathClimbingParts(fileName.second); #endif - - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("-=-=-=-=-=-=-= About to load fileName.second = [%s]\n",fileName.second.c_str()); - - if(fileMustExist.second == true || - (fileMustExist.second == false && fileExists(fileName.second) == true)) { - properties.second.load(fileName.second); - fileLoaded.second = true; - } - - try { - if(fileName.second != "" && fileExists(fileName.second) == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] attempting to auto-create cfgFile.second = [%s]\n",__FILE__,__FUNCTION__,__LINE__,fileName.second.c_str()); + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("-=-=-=-=-=-=-= About to load fileName.second = [%s]\n", + fileName.second.c_str()); + + if (fileMustExist.second == true || + (fileMustExist.second == false && fileExists(fileName.second) == true)) { + properties.second.load(fileName.second); + fileLoaded.second = true; + } + + try { + if (fileName.second != "" && fileExists(fileName.second) == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] attempting to " + "auto-create cfgFile.second = [%s]\n", + __FILE__, __FUNCTION__, __LINE__, + fileName.second.c_str()); #if defined(WIN32) && !defined(__MINGW32__) - wstring wstr = utf8_decode(fileName.second); - FILE *fp = _wfopen(wstr.c_str(), L"w"); - std::ofstream userFile(fp); + wstring wstr = utf8_decode(fileName.second); + FILE *fp = _wfopen(wstr.c_str(), L"w"); + std::ofstream userFile(fp); #else - std::ofstream userFile; - userFile.open(fileName.second.c_str(), ios_base::out | ios_base::trunc); + std::ofstream userFile; + userFile.open(fileName.second.c_str(), ios_base::out | ios_base::trunc); #endif - userFile.close(); + userFile.close(); #if defined(WIN32) && !defined(__MINGW32__) - if(fp) { - fclose(fp); - } + if (fp) { + fclose(fp); + } #endif - fileLoaded.second = true; - properties.second.load(fileName.second); - } - } - catch(const exception &ex) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] ERROR trying to auto-create cfgFile.second = [%s]\n",__FILE__,__FUNCTION__,__LINE__,fileName.second.c_str()); + fileLoaded.second = true; + properties.second.load(fileName.second); } + } catch (const exception &ex) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", __FILE__, + __FUNCTION__, __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] ERROR trying to " + "auto-create cfgFile.second = [%s]\n", + __FILE__, __FUNCTION__, __LINE__, + fileName.second.c_str()); + } } -Config &Config::getInstance(std::pair type, std::pair file, std::pair fileMustExist, string custom_path) { - if(configList.find(type.first) == configList.end()) { - if(SystemFlags::VERBOSE_MODE_ENABLED) if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - Config config(type, file, fileMustExist, custom_path); - - if(SystemFlags::VERBOSE_MODE_ENABLED) if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - configList.insert(map::value_type(type.first,config)); - - if(SystemFlags::VERBOSE_MODE_ENABLED) if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - } - - return configList.find(type.first)->second; +Config &Config::getInstance(std::pair type, + std::pair file, + std::pair fileMustExist, + string custom_path) { + if (configList.find(type.first) == configList.end()) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + + Config config(type, file, fileMustExist, custom_path); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + + configList.insert(map::value_type(type.first, config)); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + } + + return configList.find(type.first)->second; } void Config::CopyAll(Config *src, Config *dest) { - dest->properties = src->properties; - dest->cfgType = src->cfgType; - dest->fileName = src->fileName; - dest->fileNameParameter = src->fileNameParameter; - dest->fileLoaded = src->fileLoaded; + dest->properties = src->properties; + dest->cfgType = src->cfgType; + dest->fileName = src->fileName; + dest->fileNameParameter = src->fileNameParameter; + dest->fileLoaded = src->fileLoaded; } void Config::reload() { - if(SystemFlags::VERBOSE_MODE_ENABLED) if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - std::pair type = std::make_pair(cfgType.first,cfgType.second); - Config newconfig(type, std::make_pair(fileNameParameter.first,fileNameParameter.second), std::make_pair(true,false), custom_path_parameter); - - if(SystemFlags::VERBOSE_MODE_ENABLED) if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - Config &oldconfig = configList.find(type.first)->second; - CopyAll(&newconfig, &oldconfig); - - if(SystemFlags::VERBOSE_MODE_ENABLED) if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + std::pair type = + std::make_pair(cfgType.first, cfgType.second); + Config newconfig( + type, std::make_pair(fileNameParameter.first, fileNameParameter.second), + std::make_pair(true, false), custom_path_parameter); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + Config &oldconfig = configList.find(type.first)->second; + CopyAll(&newconfig, &oldconfig); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); } -void Config::save(const string &path){ - if(fileLoaded.second == true) { - if(path != "") { - fileName.second = path; - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] save file [%s]\n",__FILE__,__FUNCTION__,__LINE__,fileName.second.c_str()); - properties.second.save(fileName.second); - return; - } - - if(path != "") { - fileName.first = path; - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] save file [%s]\n",__FILE__,__FUNCTION__,__LINE__,fileName.first.c_str()); - properties.first.save(fileName.first); +void Config::save(const string &path) { + if (fileLoaded.second == true) { + if (path != "") { + fileName.second = path; + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] save file [%s]\n", __FILE__, __FUNCTION__, + __LINE__, fileName.second.c_str()); + properties.second.save(fileName.second); + return; + } + + if (path != "") { + fileName.first = path; + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] save file [%s]\n", __FILE__, __FUNCTION__, + __LINE__, fileName.first.c_str()); + properties.first.save(fileName.first); } -int Config::getInt(const char *key,const char *defaultValueIfNotFound) const { - if(tempProperties.getString(key, defaultNotFoundValue.c_str()) != defaultNotFoundValue) { - return tempProperties.getInt(key,defaultValueIfNotFound); - } - if(fileLoaded.second == true && - properties.second.getString(key, defaultNotFoundValue.c_str()) != defaultNotFoundValue) { - return properties.second.getInt(key,defaultValueIfNotFound); - } - return properties.first.getInt(key,defaultValueIfNotFound); +int Config::getInt(const char *key, const char *defaultValueIfNotFound) const { + if (tempProperties.getString(key, defaultNotFoundValue.c_str()) != + defaultNotFoundValue) { + return tempProperties.getInt(key, defaultValueIfNotFound); + } + if (fileLoaded.second == true && + properties.second.getString(key, defaultNotFoundValue.c_str()) != + defaultNotFoundValue) { + return properties.second.getInt(key, defaultValueIfNotFound); + } + return properties.first.getInt(key, defaultValueIfNotFound); } -bool Config::getBool(const char *key,const char *defaultValueIfNotFound) const { - if(tempProperties.getString(key, defaultNotFoundValue.c_str()) != defaultNotFoundValue) { - return tempProperties.getBool(key,defaultValueIfNotFound); - } +bool Config::getBool(const char *key, + const char *defaultValueIfNotFound) const { + if (tempProperties.getString(key, defaultNotFoundValue.c_str()) != + defaultNotFoundValue) { + return tempProperties.getBool(key, defaultValueIfNotFound); + } - if(fileLoaded.second == true && - properties.second.getString(key, defaultNotFoundValue.c_str()) != defaultNotFoundValue) { - return properties.second.getBool(key,defaultValueIfNotFound); - } + if (fileLoaded.second == true && + properties.second.getString(key, defaultNotFoundValue.c_str()) != + defaultNotFoundValue) { + return properties.second.getBool(key, defaultValueIfNotFound); + } - return properties.first.getBool(key,defaultValueIfNotFound); + return properties.first.getBool(key, defaultValueIfNotFound); } -float Config::getFloat(const char *key,const char *defaultValueIfNotFound) const { - if(tempProperties.getString(key, defaultNotFoundValue.c_str()) != defaultNotFoundValue) { - return tempProperties.getFloat(key,defaultValueIfNotFound); - } +float Config::getFloat(const char *key, + const char *defaultValueIfNotFound) const { + if (tempProperties.getString(key, defaultNotFoundValue.c_str()) != + defaultNotFoundValue) { + return tempProperties.getFloat(key, defaultValueIfNotFound); + } - if(fileLoaded.second == true && - properties.second.getString(key, defaultNotFoundValue.c_str()) != defaultNotFoundValue) { - return properties.second.getFloat(key,defaultValueIfNotFound); - } + if (fileLoaded.second == true && + properties.second.getString(key, defaultNotFoundValue.c_str()) != + defaultNotFoundValue) { + return properties.second.getFloat(key, defaultValueIfNotFound); + } - return properties.first.getFloat(key,defaultValueIfNotFound); + return properties.first.getFloat(key, defaultValueIfNotFound); } -const string Config::getString(const char *key,const char *defaultValueIfNotFound) const { - if(tempProperties.getString(key, defaultNotFoundValue.c_str()) != defaultNotFoundValue) { - return tempProperties.getString(key,defaultValueIfNotFound); - } +const string Config::getString(const char *key, + const char *defaultValueIfNotFound) const { + if (tempProperties.getString(key, defaultNotFoundValue.c_str()) != + defaultNotFoundValue) { + return tempProperties.getString(key, defaultValueIfNotFound); + } - if(fileLoaded.second == true && - properties.second.getString(key, defaultNotFoundValue.c_str()) != defaultNotFoundValue) { - return properties.second.getString(key,defaultValueIfNotFound); - } + if (fileLoaded.second == true && + properties.second.getString(key, defaultNotFoundValue.c_str()) != + defaultNotFoundValue) { + return properties.second.getString(key, defaultValueIfNotFound); + } - return properties.first.getString(key,defaultValueIfNotFound); + return properties.first.getString(key, defaultValueIfNotFound); } -int Config::getInt(const string &key,const char *defaultValueIfNotFound) const{ - if(tempProperties.getString(key, defaultNotFoundValue.c_str()) != defaultNotFoundValue) { - return tempProperties.getInt(key,defaultValueIfNotFound); - } +int Config::getInt(const string &key, + const char *defaultValueIfNotFound) const { + if (tempProperties.getString(key, defaultNotFoundValue.c_str()) != + defaultNotFoundValue) { + return tempProperties.getInt(key, defaultValueIfNotFound); + } - if(fileLoaded.second == true && - properties.second.getString(key, defaultNotFoundValue.c_str()) != defaultNotFoundValue) { - return properties.second.getInt(key,defaultValueIfNotFound); - } + if (fileLoaded.second == true && + properties.second.getString(key, defaultNotFoundValue.c_str()) != + defaultNotFoundValue) { + return properties.second.getInt(key, defaultValueIfNotFound); + } - return properties.first.getInt(key,defaultValueIfNotFound); + return properties.first.getInt(key, defaultValueIfNotFound); } -bool Config::getBool(const string &key,const char *defaultValueIfNotFound) const{ - if(tempProperties.getString(key, defaultNotFoundValue.c_str()) != defaultNotFoundValue) { - return tempProperties.getBool(key,defaultValueIfNotFound); - } +bool Config::getBool(const string &key, + const char *defaultValueIfNotFound) const { + if (tempProperties.getString(key, defaultNotFoundValue.c_str()) != + defaultNotFoundValue) { + return tempProperties.getBool(key, defaultValueIfNotFound); + } - if(fileLoaded.second == true && - properties.second.getString(key, defaultNotFoundValue.c_str()) != defaultNotFoundValue) { - return properties.second.getBool(key,defaultValueIfNotFound); - } + if (fileLoaded.second == true && + properties.second.getString(key, defaultNotFoundValue.c_str()) != + defaultNotFoundValue) { + return properties.second.getBool(key, defaultValueIfNotFound); + } - return properties.first.getBool(key,defaultValueIfNotFound); + return properties.first.getBool(key, defaultValueIfNotFound); } -float Config::getFloat(const string &key,const char *defaultValueIfNotFound) const{ - if(tempProperties.getString(key, defaultNotFoundValue.c_str()) != defaultNotFoundValue) { - return tempProperties.getFloat(key,defaultValueIfNotFound); - } +float Config::getFloat(const string &key, + const char *defaultValueIfNotFound) const { + if (tempProperties.getString(key, defaultNotFoundValue.c_str()) != + defaultNotFoundValue) { + return tempProperties.getFloat(key, defaultValueIfNotFound); + } - if(fileLoaded.second == true && - properties.second.getString(key, defaultNotFoundValue.c_str()) != defaultNotFoundValue) { - return properties.second.getFloat(key,defaultValueIfNotFound); - } + if (fileLoaded.second == true && + properties.second.getString(key, defaultNotFoundValue.c_str()) != + defaultNotFoundValue) { + return properties.second.getFloat(key, defaultValueIfNotFound); + } - return properties.first.getFloat(key,defaultValueIfNotFound); + return properties.first.getFloat(key, defaultValueIfNotFound); } -const string Config::getString(const string &key,const char *defaultValueIfNotFound) const{ - if(tempProperties.getString(key, defaultNotFoundValue.c_str()) != defaultNotFoundValue) { - return tempProperties.getString(key,defaultValueIfNotFound); - } +const string Config::getString(const string &key, + const char *defaultValueIfNotFound) const { + if (tempProperties.getString(key, defaultNotFoundValue.c_str()) != + defaultNotFoundValue) { + return tempProperties.getString(key, defaultValueIfNotFound); + } - if(fileLoaded.second == true && - properties.second.getString(key, defaultNotFoundValue.c_str()) != defaultNotFoundValue) { - return properties.second.getString(key,defaultValueIfNotFound); - } + if (fileLoaded.second == true && + properties.second.getString(key, defaultNotFoundValue.c_str()) != + defaultNotFoundValue) { + return properties.second.getString(key, defaultValueIfNotFound); + } - return properties.first.getString(key,defaultValueIfNotFound); + return properties.first.getString(key, defaultValueIfNotFound); } SDL_Keycode Config::translateStringToSDLKey(const string &value) const { - SDL_Keycode result = SDLK_UNKNOWN; - - if(IsNumeric(value.c_str()) == true) { - result = (SDL_Keycode)strToInt(value); - } - else if(value.substr(0,2) == "vk") { - if(value == "vkLeft") { - result = SDLK_LEFT; - } - else if(value == "vkRight") { - result = SDLK_RIGHT; - } - else if(value == "vkUp") { - result = SDLK_UP; - } - else if(value == "vkDown") { - result = SDLK_DOWN; - } - else if(value == "vkAdd") { - result = SDLK_PLUS; - } - else if(value == "vkSubtract") { - result = SDLK_MINUS; - } - else if(value == "vkEscape") { - result = SDLK_ESCAPE; - } - else if(value == "vkF1") { - result = SDLK_F1; - } - else if(value == "vkF2") { - result = SDLK_F2; - } - else if(value == "vkF3") { - result = SDLK_F3; - } - else if(value == "vkF4") { - result = SDLK_F4; - } - else if(value == "vkF5") { - result = SDLK_F5; - } - else if(value == "vkF6") { - result = SDLK_F6; - } - else if(value == "vkF7") { - result = SDLK_F7; - } - else if(value == "vkF8") { - result = SDLK_F8; - } - else if(value == "vkF9") { - result = SDLK_F9; - } - else if(value == "vkF10") { - result = SDLK_F10; - } - else if(value == "vkF11") { - result = SDLK_F11; - } - else if(value == "vkF12") { - result = SDLK_F12; - } - else if(value == "vkPrint") { - result = SDLK_PRINTSCREEN; - } - else if(value == "vkPause") { - result = SDLK_PAUSE; - } - else { - string sError = "Unsupported key translation [" + value + "]"; - throw megaglest_runtime_error(sError.c_str()); - } - } - else if(value.length() >= 1) { - if(value.length() == 3 && value[0] == '\'' && value[2] == '\'') { - result = (SDL_Keycode)value[1]; - } - else { - bool foundKey = false; - if(value.length() > 1) { - SDL_Keycode lookup = SDL_GetKeyFromName(value.c_str()); - if(lookup != SDLK_UNKNOWN) { - result = lookup; - foundKey = true; - } - } - - if(foundKey == false) { - result = (SDL_Keycode)value[0]; - } - } - } - else { - string sError = "Unsupported key translation" + value; - throw megaglest_runtime_error(sError.c_str()); - } - - // Because SDL is based on lower Ascii - //result = tolower(result); - return result; + SDL_Keycode result = SDLK_UNKNOWN; + + if (IsNumeric(value.c_str()) == true) { + result = (SDL_Keycode)strToInt(value); + } else if (value.substr(0, 2) == "vk") { + if (value == "vkLeft") { + result = SDLK_LEFT; + } else if (value == "vkRight") { + result = SDLK_RIGHT; + } else if (value == "vkUp") { + result = SDLK_UP; + } else if (value == "vkDown") { + result = SDLK_DOWN; + } else if (value == "vkAdd") { + result = SDLK_PLUS; + } else if (value == "vkSubtract") { + result = SDLK_MINUS; + } else if (value == "vkEscape") { + result = SDLK_ESCAPE; + } else if (value == "vkF1") { + result = SDLK_F1; + } else if (value == "vkF2") { + result = SDLK_F2; + } else if (value == "vkF3") { + result = SDLK_F3; + } else if (value == "vkF4") { + result = SDLK_F4; + } else if (value == "vkF5") { + result = SDLK_F5; + } else if (value == "vkF6") { + result = SDLK_F6; + } else if (value == "vkF7") { + result = SDLK_F7; + } else if (value == "vkF8") { + result = SDLK_F8; + } else if (value == "vkF9") { + result = SDLK_F9; + } else if (value == "vkF10") { + result = SDLK_F10; + } else if (value == "vkF11") { + result = SDLK_F11; + } else if (value == "vkF12") { + result = SDLK_F12; + } else if (value == "vkPrint") { + result = SDLK_PRINTSCREEN; + } else if (value == "vkPause") { + result = SDLK_PAUSE; + } else { + string sError = "Unsupported key translation [" + value + "]"; + throw megaglest_runtime_error(sError.c_str()); + } + } else if (value.length() >= 1) { + if (value.length() == 3 && value[0] == '\'' && value[2] == '\'') { + result = (SDL_Keycode)value[1]; + } else { + bool foundKey = false; + if (value.length() > 1) { + SDL_Keycode lookup = SDL_GetKeyFromName(value.c_str()); + if (lookup != SDLK_UNKNOWN) { + result = lookup; + foundKey = true; + } + } + + if (foundKey == false) { + result = (SDL_Keycode)value[0]; + } + } + } else { + string sError = "Unsupported key translation" + value; + throw megaglest_runtime_error(sError.c_str()); + } + + // Because SDL is based on lower Ascii + // result = tolower(result); + return result; } SDL_Keycode Config::getSDLKey(const char *key) const { - if(fileLoaded.second == true && - properties.second.getString(key, defaultNotFoundValue.c_str()) != defaultNotFoundValue) { - - string value = properties.second.getString(key); - return translateStringToSDLKey(value); - } - string value = properties.first.getString(key); - return translateStringToSDLKey(value); + if (fileLoaded.second == true && + properties.second.getString(key, defaultNotFoundValue.c_str()) != + defaultNotFoundValue) { + + string value = properties.second.getString(key); + return translateStringToSDLKey(value); + } + string value = properties.first.getString(key); + return translateStringToSDLKey(value); } -//char Config::getCharKey(const char *key) const { +// char Config::getCharKey(const char *key) const { // if(fileLoaded.second == true && -// properties.second.getString(key, defaultNotFoundValue.c_str()) != defaultNotFoundValue) { +// properties.second.getString(key, defaultNotFoundValue.c_str()) +//!= defaultNotFoundValue) { // // string value = properties.second.getString(key); // return translateStringToCharKey(value); // } // string value = properties.first.getString(key); // return translateStringToCharKey(value); -//} +// } void Config::setInt(const string &key, int value, bool tempBuffer) { - if(tempBuffer == true) { - tempProperties.setInt(key, value); - return; - } - if(fileLoaded.second == true) { - properties.second.setInt(key, value); - return; - } - properties.first.setInt(key, value); + if (tempBuffer == true) { + tempProperties.setInt(key, value); + return; + } + if (fileLoaded.second == true) { + properties.second.setInt(key, value); + return; + } + properties.first.setInt(key, value); } void Config::setBool(const string &key, bool value, bool tempBuffer) { - if(tempBuffer == true) { - tempProperties.setBool(key, value); - return; - } + if (tempBuffer == true) { + tempProperties.setBool(key, value); + return; + } - if(fileLoaded.second == true) { - properties.second.setBool(key, value); - return; - } + if (fileLoaded.second == true) { + properties.second.setBool(key, value); + return; + } - properties.first.setBool(key, value); + properties.first.setBool(key, value); } void Config::setFloat(const string &key, float value, bool tempBuffer) { - if(tempBuffer == true) { - tempProperties.setFloat(key, value); - return; - } + if (tempBuffer == true) { + tempProperties.setFloat(key, value); + return; + } - if(fileLoaded.second == true) { - properties.second.setFloat(key, value); - return; - } + if (fileLoaded.second == true) { + properties.second.setFloat(key, value); + return; + } - properties.first.setFloat(key, value); + properties.first.setFloat(key, value); } -void Config::setString(const string &key, const string &value, bool tempBuffer) { - if(tempBuffer == true) { - tempProperties.setString(key, value); - return; - } +void Config::setString(const string &key, const string &value, + bool tempBuffer) { + if (tempBuffer == true) { + tempProperties.setString(key, value); + return; + } - if(fileLoaded.second == true) { - properties.second.setString(key, value); - return; - } + if (fileLoaded.second == true) { + properties.second.setString(key, value); + return; + } - properties.first.setString(key, value); + properties.first.setString(key, value); } -vector > Config::getPropertiesFromContainer(const Properties &propertiesObj) const { - vector > result; +vector> +Config::getPropertiesFromContainer(const Properties &propertiesObj) const { + vector> result; - int count = propertiesObj.getPropertyCount(); - for(int i = 0; i < count; ++i) { - pair property; - property.first = propertiesObj.getKey(i); - property.second = propertiesObj.getString(i); - result.push_back(property); - } + int count = propertiesObj.getPropertyCount(); + for (int i = 0; i < count; ++i) { + pair property; + property.first = propertiesObj.getKey(i); + property.second = propertiesObj.getString(i); + result.push_back(property); + } - return result; + return result; } -vector > Config::getMergedProperties() const { - vector > result = getMasterProperties(); - vector > resultUser = getUserProperties(); - for(unsigned int i = 0; i < resultUser.size(); ++i) { - const pair &propertyUser = resultUser[i]; - bool overrideProperty = false; - for(unsigned int j = 0; j < result.size(); ++j) { - pair &property = result[j]; - // Take the user property and override the original value - if(property.first == propertyUser.first) { - overrideProperty = true; - property.second = propertyUser.second; - break; - } - } - if(overrideProperty == false) { - result.push_back(propertyUser); - } +vector> Config::getMergedProperties() const { + vector> result = getMasterProperties(); + vector> resultUser = getUserProperties(); + for (unsigned int i = 0; i < resultUser.size(); ++i) { + const pair &propertyUser = resultUser[i]; + bool overrideProperty = false; + for (unsigned int j = 0; j < result.size(); ++j) { + pair &property = result[j]; + // Take the user property and override the original value + if (property.first == propertyUser.first) { + overrideProperty = true; + property.second = propertyUser.second; + break; + } + } + if (overrideProperty == false) { + result.push_back(propertyUser); } + } - return result; + return result; } -vector > Config::getMasterProperties() const { - return getPropertiesFromContainer(properties.first); +vector> Config::getMasterProperties() const { + return getPropertiesFromContainer(properties.first); } -vector > Config::getUserProperties() const { - return getPropertiesFromContainer(properties.second); +vector> Config::getUserProperties() const { + return getPropertiesFromContainer(properties.second); } -void Config::setUserProperties(const vector > &valueList) { - Properties &propertiesObj = properties.second; +void Config::setUserProperties(const vector> &valueList) { + Properties &propertiesObj = properties.second; - for(unsigned int idx = 0; idx < valueList.size(); ++ idx) { - const pair &nameValuePair = valueList[idx]; - propertiesObj.setString(nameValuePair.first,nameValuePair.second); - } + for (unsigned int idx = 0; idx < valueList.size(); ++idx) { + const pair &nameValuePair = valueList[idx]; + propertiesObj.setString(nameValuePair.first, nameValuePair.second); + } } string Config::getFileName(bool userFilename) const { - string result = fileName.second; - if(userFilename == false) { - result = fileName.first; - } + string result = fileName.second; + if (userFilename == false) { + result = fileName.first; + } - return result; + return result; } -string Config::toString(){ - return properties.first.toString(); -} +string Config::toString() { return properties.first.toString(); } vector Config::getPathListForType(PathType type, string scenarioDir) { - vector pathList; - string data_path = getGameReadWritePath(GameConstants::path_data_CacheLookupKey); - - string userData = getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - //if(data_path == "") { - // userData = userData; - //} - //else { - // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("extractLastDirectoryFromPath(userData) [%s] from userData [%s]\n",extractLastDirectoryFromPath(userData).c_str(),userData.c_str()); - // userData = data_path + extractLastDirectoryFromPath(userData); - //} - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] userData path [%s]\n",__FILE__,__FUNCTION__,__LINE__,userData.c_str()); - - if(isdir(userData.c_str()) == false) { - createDirectoryPaths(userData); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] creating path [%s]\n",__FILE__,__FUNCTION__,__LINE__,userData.c_str()); - } + vector pathList; + string data_path = + getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + + string userData = getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + // if(data_path == "") { + // userData = userData; + // } + // else { + // if(SystemFlags::VERBOSE_MODE_ENABLED) + // printf("extractLastDirectoryFromPath(userData) [%s] from userData + //[%s]\n",extractLastDirectoryFromPath(userData).c_str(),userData.c_str()); + // userData = data_path + extractLastDirectoryFromPath(userData); + // } + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] + // userData path [%s]\n",__FILE__,__FUNCTION__,__LINE__,userData.c_str()); + + if (isdir(userData.c_str()) == false) { + createDirectoryPaths(userData); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] creating path [%s]\n", __FILE__, + __FUNCTION__, __LINE__, userData.c_str()); + } - string userDataMaps = userData + GameConstants::folder_path_maps; - if(isdir(userDataMaps.c_str()) == false) { - createDirectoryPaths(userDataMaps); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] creating path [%s]\n",__FILE__,__FUNCTION__,__LINE__,userDataMaps.c_str()); - } - string userDataScenarios = userData + GameConstants::folder_path_scenarios; - if(isdir(userDataScenarios.c_str()) == false) { - createDirectoryPaths(userDataScenarios); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] creating path [%s]\n",__FILE__,__FUNCTION__,__LINE__,userDataScenarios.c_str()); - } - string userDataTechs = userData + GameConstants::folder_path_techs; - if(isdir(userDataTechs.c_str()) == false) { - createDirectoryPaths(userDataTechs); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] creating path [%s]\n",__FILE__,__FUNCTION__,__LINE__,userDataTechs.c_str()); - } - string userDataTilesets = userData + GameConstants::folder_path_tilesets; - if(isdir(userDataTilesets.c_str()) == false) { - createDirectoryPaths(userDataTilesets); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] creating path [%s]\n",__FILE__,__FUNCTION__,__LINE__,userDataTilesets.c_str()); - } - string userDataTutorials = userData + GameConstants::folder_path_tutorials; - if(isdir(userDataTutorials.c_str()) == false) { - createDirectoryPaths(userDataTutorials); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] creating path [%s]\n",__FILE__,__FUNCTION__,__LINE__,userDataTutorials.c_str()); - } + string userDataMaps = userData + GameConstants::folder_path_maps; + if (isdir(userDataMaps.c_str()) == false) { + createDirectoryPaths(userDataMaps); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] creating path [%s]\n", __FILE__, + __FUNCTION__, __LINE__, userDataMaps.c_str()); + } + string userDataScenarios = userData + GameConstants::folder_path_scenarios; + if (isdir(userDataScenarios.c_str()) == false) { + createDirectoryPaths(userDataScenarios); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] creating path [%s]\n", __FILE__, + __FUNCTION__, __LINE__, userDataScenarios.c_str()); + } + string userDataTechs = userData + GameConstants::folder_path_techs; + if (isdir(userDataTechs.c_str()) == false) { + createDirectoryPaths(userDataTechs); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] creating path [%s]\n", __FILE__, + __FUNCTION__, __LINE__, userDataTechs.c_str()); } - if(scenarioDir != "") { - if(EndsWith(scenarioDir, ".xml") == true) { - scenarioDir = extractDirectoryPathFromFile(scenarioDir); - } - - //string scenarioLocation = data_path + scenarioDir; - string scenarioLocation = scenarioDir; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Scenario path [%s]\n",scenarioLocation.c_str()); - pathList.push_back(scenarioLocation); + string userDataTilesets = userData + GameConstants::folder_path_tilesets; + if (isdir(userDataTilesets.c_str()) == false) { + createDirectoryPaths(userDataTilesets); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] creating path [%s]\n", __FILE__, + __FUNCTION__, __LINE__, userDataTilesets.c_str()); + } + string userDataTutorials = userData + GameConstants::folder_path_tutorials; + if (isdir(userDataTutorials.c_str()) == false) { + createDirectoryPaths(userDataTutorials); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] creating path [%s]\n", __FILE__, + __FUNCTION__, __LINE__, userDataTutorials.c_str()); + } + } + if (scenarioDir != "") { + if (EndsWith(scenarioDir, ".xml") == true) { + scenarioDir = extractDirectoryPathFromFile(scenarioDir); } - switch(type) { - case ptMaps: - pathList.push_back(data_path+GameConstants::folder_path_maps); - if(userData != "") { - pathList.push_back(userData + string(GameConstants::folder_path_maps)); - } - break; - case ptScenarios: - pathList.push_back(data_path+GameConstants::folder_path_scenarios); - if(userData != "") { - pathList.push_back(userData + string(GameConstants::folder_path_scenarios)); - } - break; - case ptTechs: - pathList.push_back(data_path+GameConstants::folder_path_techs); - if(userData != "") { - pathList.push_back(userData + string(GameConstants::folder_path_techs)); - } - break; - case ptTilesets: - pathList.push_back(data_path+GameConstants::folder_path_tilesets); - if(userData != "") { - pathList.push_back(userData + string(GameConstants::folder_path_tilesets)); - } - break; - case ptTutorials: - pathList.push_back(data_path+GameConstants::folder_path_tutorials); - if(userData != "") { - pathList.push_back(userData + string(GameConstants::folder_path_tutorials)); - } - break; + // string scenarioLocation = data_path + scenarioDir; + string scenarioLocation = scenarioDir; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Scenario path [%s]\n", scenarioLocation.c_str()); + pathList.push_back(scenarioLocation); + } + + switch (type) { + case ptMaps: + pathList.push_back(data_path + GameConstants::folder_path_maps); + if (userData != "") { + pathList.push_back(userData + string(GameConstants::folder_path_maps)); + } + break; + case ptScenarios: + pathList.push_back(data_path + GameConstants::folder_path_scenarios); + if (userData != "") { + pathList.push_back(userData + + string(GameConstants::folder_path_scenarios)); + } + break; + case ptTechs: + pathList.push_back(data_path + GameConstants::folder_path_techs); + if (userData != "") { + pathList.push_back(userData + string(GameConstants::folder_path_techs)); + } + break; + case ptTilesets: + pathList.push_back(data_path + GameConstants::folder_path_tilesets); + if (userData != "") { + pathList.push_back(userData + + string(GameConstants::folder_path_tilesets)); + } + break; + case ptTutorials: + pathList.push_back(data_path + GameConstants::folder_path_tutorials); + if (userData != "") { + pathList.push_back(userData + + string(GameConstants::folder_path_tutorials)); } + break; + } - return pathList; + return pathList; } -bool Config::replaceFileWithLocalFile(const vector &dirList, string fileNamePart, string &resultToReplace) { - bool found = false; - for(unsigned int i = 0; i < dirList.size(); ++i) { - string path = dirList[i]; - endPathWithSlash(path); - string newFileName = path + fileNamePart; - if(fileExists(newFileName) == true) { - resultToReplace = newFileName; - found = true; - break; - } - } - return found; +bool Config::replaceFileWithLocalFile(const vector &dirList, + string fileNamePart, + string &resultToReplace) { + bool found = false; + for (unsigned int i = 0; i < dirList.size(); ++i) { + string path = dirList[i]; + endPathWithSlash(path); + string newFileName = path + fileNamePart; + if (fileExists(newFileName) == true) { + resultToReplace = newFileName; + found = true; + break; + } + } + return found; } - - string Config::findValidLocalFileFromPath(string fileName) { - string result = fileName; - - if(fileName.find("maps/") != fileName.npos ) { - size_t pos = fileName.find("maps/"); - string fileNamePart = fileName.substr(pos+5); - Config &config = Config::getInstance(); - vector dirList = config.getPathListForType(ptMaps); - replaceFileWithLocalFile(dirList, fileNamePart, result); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Found file [%s] @ " MG_SIZE_T_SPECIFIER " [%s]\nNew File [%s]\n",fileName.c_str(),pos,fileNamePart.c_str(),result.c_str()); - } - else if(fileName.find("tilesets/") != fileName.npos ) { - size_t pos = fileName.find("tilesets/"); - string fileNamePart = fileName.substr(pos+9); - Config &config = Config::getInstance(); - vector dirList = config.getPathListForType(ptTilesets); - replaceFileWithLocalFile(dirList, fileNamePart, result); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Found file [%s] @ " MG_SIZE_T_SPECIFIER " [%s]\nNew File [%s]\n",fileName.c_str(),pos,fileNamePart.c_str(),result.c_str()); - } - else if(fileName.find("techs/") != fileName.npos ) { - size_t pos = fileName.find("techs/"); - string fileNamePart = fileName.substr(pos+6); - Config &config = Config::getInstance(); - vector dirList = config.getPathListForType(ptTechs); - replaceFileWithLocalFile(dirList, fileNamePart, result); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Found file [%s] @ " MG_SIZE_T_SPECIFIER " [%s]\nNew File [%s]\n",fileName.c_str(),pos,fileNamePart.c_str(),result.c_str()); - } - else if(fileName.find("scenarios/") != fileName.npos) { - size_t pos = fileName.find("scenarios/"); - string fileNamePart = fileName.substr(pos+10); - Config &config = Config::getInstance(); - vector dirList = config.getPathListForType(ptScenarios); - replaceFileWithLocalFile(dirList, fileNamePart, result); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Found file [%s] @ " MG_SIZE_T_SPECIFIER " [%s]\nNew File [%s]\n",fileName.c_str(),pos,fileNamePart.c_str(),result.c_str()); - } - else if(fileName.find("tutorials/") != fileName.npos) { - size_t pos = fileName.find("tutorials/"); - string fileNamePart = fileName.substr(pos+10); - Config &config = Config::getInstance(); - vector dirList = config.getPathListForType(ptTutorials); - replaceFileWithLocalFile(dirList, fileNamePart, result); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Found file [%s] @ " MG_SIZE_T_SPECIFIER " [%s]\nNew File [%s]\n",fileName.c_str(),pos,fileNamePart.c_str(),result.c_str()); - } - - return result; -} - - -// static -string Config::getMapPath(const string &mapName, string scenarioDir, bool errorOnNotFound) { + string result = fileName; + if (fileName.find("maps/") != fileName.npos) { + size_t pos = fileName.find("maps/"); + string fileNamePart = fileName.substr(pos + 5); + Config &config = Config::getInstance(); + vector dirList = config.getPathListForType(ptMaps); + replaceFileWithLocalFile(dirList, fileNamePart, result); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Found file [%s] @ " MG_SIZE_T_SPECIFIER " [%s]\nNew File [%s]\n", + fileName.c_str(), pos, fileNamePart.c_str(), result.c_str()); + } else if (fileName.find("tilesets/") != fileName.npos) { + size_t pos = fileName.find("tilesets/"); + string fileNamePart = fileName.substr(pos + 9); + Config &config = Config::getInstance(); + vector dirList = config.getPathListForType(ptTilesets); + replaceFileWithLocalFile(dirList, fileNamePart, result); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Found file [%s] @ " MG_SIZE_T_SPECIFIER " [%s]\nNew File [%s]\n", + fileName.c_str(), pos, fileNamePart.c_str(), result.c_str()); + } else if (fileName.find("techs/") != fileName.npos) { + size_t pos = fileName.find("techs/"); + string fileNamePart = fileName.substr(pos + 6); + Config &config = Config::getInstance(); + vector dirList = config.getPathListForType(ptTechs); + replaceFileWithLocalFile(dirList, fileNamePart, result); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Found file [%s] @ " MG_SIZE_T_SPECIFIER " [%s]\nNew File [%s]\n", + fileName.c_str(), pos, fileNamePart.c_str(), result.c_str()); + } else if (fileName.find("scenarios/") != fileName.npos) { + size_t pos = fileName.find("scenarios/"); + string fileNamePart = fileName.substr(pos + 10); + Config &config = Config::getInstance(); + vector dirList = config.getPathListForType(ptScenarios); + replaceFileWithLocalFile(dirList, fileNamePart, result); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Found file [%s] @ " MG_SIZE_T_SPECIFIER " [%s]\nNew File [%s]\n", + fileName.c_str(), pos, fileNamePart.c_str(), result.c_str()); + } else if (fileName.find("tutorials/") != fileName.npos) { + size_t pos = fileName.find("tutorials/"); + string fileNamePart = fileName.substr(pos + 10); Config &config = Config::getInstance(); - vector pathList = config.getPathListForType(ptMaps,scenarioDir); + vector dirList = config.getPathListForType(ptTutorials); + replaceFileWithLocalFile(dirList, fileNamePart, result); - for(int idx = 0; idx < (int)pathList.size(); idx++) { - string map_path = pathList[idx]; - endPathWithSlash(map_path); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Found file [%s] @ " MG_SIZE_T_SPECIFIER " [%s]\nNew File [%s]\n", + fileName.c_str(), pos, fileNamePart.c_str(), result.c_str()); + } - const string mega = map_path + mapName + ".mgm"; - const string glest = map_path + mapName + ".gbm"; - if (fileExists(mega)) { - return mega; - } - else if (fileExists(glest)) { - return glest; - } + return result; +} + +// static +string Config::getMapPath(const string &mapName, string scenarioDir, + bool errorOnNotFound) { + + Config &config = Config::getInstance(); + vector pathList = config.getPathListForType(ptMaps, scenarioDir); + + for (int idx = 0; idx < (int)pathList.size(); idx++) { + string map_path = pathList[idx]; + endPathWithSlash(map_path); + + const string mega = map_path + mapName + ".mgm"; + const string glest = map_path + mapName + ".gbm"; + if (fileExists(mega)) { + return mega; + } else if (fileExists(glest)) { + return glest; } + } - if(errorOnNotFound == true) { - //abort(); - throw megaglest_runtime_error("Map not found [" + mapName + "]\nScenario [" + scenarioDir + "]"); - } + if (errorOnNotFound == true) { + // abort(); + throw megaglest_runtime_error("Map not found [" + mapName + + "]\nScenario [" + scenarioDir + "]"); + } - return ""; + return ""; } -}}// end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/global/config.h b/source/glest_game/global/config.h index 21dea25e3..dac897741 100644 --- a/source/glest_game/global/config.h +++ b/source/glest_game/global/config.h @@ -13,17 +13,18 @@ #define _GLEST_GAME_CONFIG_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include "properties.h" -#include #include "game_constants.h" -#include #include "leak_dumper.h" +#include "properties.h" +#include +#include -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { using Shared::Util::Properties; @@ -34,98 +35,117 @@ using Shared::Util::Properties; // ===================================================== enum ConfigType { - cfgMainGame, - cfgUserGame, - cfgTempGame, - cfgMainKeys, - cfgUserKeys, - cfgTempKeys + cfgMainGame, + cfgUserGame, + cfgTempGame, + cfgMainKeys, + cfgUserKeys, + cfgTempKeys }; class Config { private: + std::pair properties; + Properties tempProperties; + std::pair cfgType; + std::pair fileNameParameter; + std::pair fileName; + std::pair fileLoaded; + string custom_path_parameter; - std::pair properties; - Properties tempProperties; - std::pair cfgType; - std::pair fileNameParameter; - std::pair fileName; - std::pair fileLoaded; - string custom_path_parameter; + static map configList; - static map configList; + static const char *glest_ini_filename; + static const char *glestuser_ini_filename; - static const char *glest_ini_filename; - static const char *glestuser_ini_filename; - - static map customRuntimeProperties; + static map customRuntimeProperties; public: + static const char *glestkeys_ini_filename; + static const char *glestuserkeys_ini_filename; - static const char *glestkeys_ini_filename; - static const char *glestuserkeys_ini_filename; - - static const char *ACTIVE_MOD_PROPERTY_NAME; + static const char *ACTIVE_MOD_PROPERTY_NAME; - static const char *colorPicking; - static const char *selectBufPicking; - static const char *frustumPicking; + static const char *colorPicking; + static const char *selectBufPicking; + static const char *frustumPicking; protected: - - Config(); - Config(std::pair type, std::pair file, std::pair fileMustExist,string custom_path=""); - bool tryCustomPath(std::pair &type, std::pair &file, string custom_path); - static void CopyAll(Config *src,Config *dest); - vector > getPropertiesFromContainer(const Properties &propertiesObj) const; - static bool replaceFileWithLocalFile(const vector &dirList, string fileNamePart, string &resultToReplace); + Config(); + Config(std::pair type, std::pair file, + std::pair fileMustExist, string custom_path = ""); + bool tryCustomPath(std::pair &type, + std::pair &file, string custom_path); + static void CopyAll(Config *src, Config *dest); + vector> + getPropertiesFromContainer(const Properties &propertiesObj) const; + static bool replaceFileWithLocalFile(const vector &dirList, + string fileNamePart, + string &resultToReplace); public: - - static Config &getInstance(std::pair type = std::make_pair(cfgMainGame,cfgUserGame) , - std::pair file = std::make_pair(glest_ini_filename,glestuser_ini_filename) , - std::pair fileMustExist = std::make_pair(true,false),string custom_path="" ); - void save(const string &path=""); - void reload(); - - int getInt(const string &key,const char *defaultValueIfNotFound=NULL) const; - bool getBool(const string &key,const char *defaultValueIfNotFound=NULL) const; - float getFloat(const string &key,const char *defaultValueIfNotFound=NULL) const; - const string getString(const string &key,const char *defaultValueIfNotFound=NULL) const; - - int getInt(const char *key,const char *defaultValueIfNotFound=NULL) const; - bool getBool(const char *key,const char *defaultValueIfNotFound=NULL) const; - float getFloat(const char *key,const char *defaultValueIfNotFound=NULL) const; - const string getString(const char *key,const char *defaultValueIfNotFound=NULL) const; - //char getCharKey(const char *key) const; - SDL_Keycode getSDLKey(const char *key) const; - - void setInt(const string &key, int value, bool tempBuffer=false); - void setBool(const string &key, bool value, bool tempBuffer=false); - void setFloat(const string &key, float value, bool tempBuffer=false); - void setString(const string &key, const string &value, bool tempBuffer=false); - - vector getPathListForType(PathType type, string scenarioDir = ""); - - vector > getMergedProperties() const; - vector > getMasterProperties() const; - vector > getUserProperties() const; - void setUserProperties(const vector > &valueList); - - string getFileName(bool userFilename) const; - - SDL_Keycode translateStringToSDLKey(const string &value) const; - - string toString(); - - static string getCustomRuntimeProperty(string key) { return customRuntimeProperties[key]; } - static void setCustomRuntimeProperty(string key, string value) { customRuntimeProperties[key] = value; } - - static string findValidLocalFileFromPath(string fileName); - - static string getMapPath(const string &mapName, string scenarioDir="", bool errorOnNotFound=true); + static Config &getInstance( + std::pair type = std::make_pair(cfgMainGame, + cfgUserGame), + std::pair file = std::make_pair(glest_ini_filename, + glestuser_ini_filename), + std::pair fileMustExist = std::make_pair(true, false), + string custom_path = ""); + void save(const string &path = ""); + void reload(); + + int getInt(const string &key, + const char *defaultValueIfNotFound = NULL) const; + bool getBool(const string &key, + const char *defaultValueIfNotFound = NULL) const; + float getFloat(const string &key, + const char *defaultValueIfNotFound = NULL) const; + const string getString(const string &key, + const char *defaultValueIfNotFound = NULL) const; + + int getInt(const char *key, const char *defaultValueIfNotFound = NULL) const; + bool getBool(const char *key, + const char *defaultValueIfNotFound = NULL) const; + float getFloat(const char *key, + const char *defaultValueIfNotFound = NULL) const; + const string getString(const char *key, + const char *defaultValueIfNotFound = NULL) const; + // char getCharKey(const char *key) const; + SDL_Keycode getSDLKey(const char *key) const; + + void setInt(const string &key, int value, bool tempBuffer = false); + void setBool(const string &key, bool value, bool tempBuffer = false); + void setFloat(const string &key, float value, bool tempBuffer = false); + void setString(const string &key, const string &value, + bool tempBuffer = false); + + vector getPathListForType(PathType type, string scenarioDir = ""); + + vector> getMergedProperties() const; + vector> getMasterProperties() const; + vector> getUserProperties() const; + void setUserProperties(const vector> &valueList); + + string getFileName(bool userFilename) const; + + SDL_Keycode translateStringToSDLKey(const string &value) const; + + string toString(); + + static string getCustomRuntimeProperty(string key) { + return customRuntimeProperties[key]; + } + static void setCustomRuntimeProperty(string key, string value) { + customRuntimeProperties[key] = value; + } + + static string findValidLocalFileFromPath(string fileName); + + static string getMapPath(const string &mapName, string scenarioDir = "", + bool errorOnNotFound = true); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/global/core_data.cpp b/source/glest_game/global/core_data.cpp index df38329db..4a97b5a3e 100644 --- a/source/glest_game/global/core_data.cpp +++ b/source/glest_game/global/core_data.cpp @@ -11,1139 +11,1102 @@ #include "core_data.h" -#include "logger.h" -#include "renderer.h" -#include "graphics_interface.h" +#include "byte_order.h" #include "config.h" -#include "util.h" -#include "platform_util.h" #include "game_constants.h" +#include "game_settings.h" #include "game_util.h" +#include "graphics_interface.h" #include "lang.h" -#include "game_settings.h" -#include "video_player.h" -#include "byte_order.h" #include "leak_dumper.h" +#include "logger.h" +#include "platform_util.h" +#include "renderer.h" +#include "util.h" +#include "video_player.h" using namespace Shared::Sound; using namespace Shared::Graphics; using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class CoreData // ===================================================== -static string tempDataLocation = getUserHome(); +static string tempDataLocation = getUserHome(); // ===================== PUBLIC ======================== -static const string CORE_PATH = "data/core/"; -static const string CORE_MISC_TEXTURES_PATH = CORE_PATH + "misc_textures/"; +static const string CORE_PATH = "data/core/"; +static const string CORE_MISC_TEXTURES_PATH = CORE_PATH + "misc_textures/"; -static const string CORE_MENU_PATH = CORE_PATH + "menu/"; -static const string CORE_MENU_TEXTURES_PATH = CORE_MENU_PATH + "textures/"; -static const string CORE_MENU_SOUND_PATH = CORE_MENU_PATH + "sound/"; -static const string CORE_MENU_MUSIC_PATH = CORE_MENU_PATH + "music/"; -static const string CORE_MENU_VIDEOS_PATH = CORE_MENU_PATH + "videos/"; +static const string CORE_MENU_PATH = CORE_PATH + "menu/"; +static const string CORE_MENU_TEXTURES_PATH = CORE_MENU_PATH + "textures/"; +static const string CORE_MENU_SOUND_PATH = CORE_MENU_PATH + "sound/"; +static const string CORE_MENU_MUSIC_PATH = CORE_MENU_PATH + "music/"; +static const string CORE_MENU_VIDEOS_PATH = CORE_MENU_PATH + "videos/"; -static const string CORE_WATER_SOUNDS_PATH = CORE_PATH + "/water_sounds/"; +static const string CORE_WATER_SOUNDS_PATH = CORE_PATH + "/water_sounds/"; CoreData &CoreData::getInstance() { - static CoreData coreData; - return coreData; + static CoreData coreData; + return coreData; } CoreData::CoreData() { - logoTexture=NULL; - logoTextureList.clear(); - backgroundTexture=NULL; - fireTexture=NULL; - teamColorTexture=NULL; - snowTexture=NULL; - waterSplashTexture=NULL; - customTexture=NULL; - buttonSmallTexture=NULL; - buttonBigTexture=NULL; - horizontalLineTexture=NULL; - verticalLineTexture=NULL; - checkBoxTexture=NULL; - checkedCheckBoxTexture=NULL; - gameWinnerTexture=NULL; - notOnServerTexture=NULL; - onServerDifferentTexture=NULL; - onServerTexture=NULL; - onServerInstalledTexture=NULL; - statusReadyTexture=NULL; - statusNotReadyTexture=NULL; - statusBRBTexture=NULL; - - healthbarTexture=NULL; - healthbarBackgroundTexture=NULL; - - miscTextureList.clear(); - - displayFont=NULL; - menuFontNormal=NULL; - displayFontSmall=NULL; - menuFontBig=NULL; - menuFontVeryBig=NULL; - consoleFont=NULL; - - displayFont3D=NULL; - menuFontNormal3D=NULL; - displayFontSmall3D=NULL; - menuFontBig3D=NULL; - menuFontVeryBig3D=NULL; - consoleFont3D=NULL; - - introVideoFilename=""; - mainMenuVideoFilename=""; - - battleEndWinVideoFilename=""; - battleEndWinVideoFilenameFallback=""; - battleEndWinMusicFilename=""; - battleEndLoseVideoFilename=""; - battleEndLoseVideoFilenameFallback=""; - battleEndLoseMusicFilename=""; -} - -CoreData::~CoreData() { - cleanup(); -} + logoTexture = NULL; + logoTextureList.clear(); + backgroundTexture = NULL; + fireTexture = NULL; + teamColorTexture = NULL; + snowTexture = NULL; + waterSplashTexture = NULL; + customTexture = NULL; + buttonSmallTexture = NULL; + buttonBigTexture = NULL; + horizontalLineTexture = NULL; + verticalLineTexture = NULL; + checkBoxTexture = NULL; + checkedCheckBoxTexture = NULL; + gameWinnerTexture = NULL; + notOnServerTexture = NULL; + onServerDifferentTexture = NULL; + onServerTexture = NULL; + onServerInstalledTexture = NULL; + statusReadyTexture = NULL; + statusNotReadyTexture = NULL; + statusBRBTexture = NULL; + + healthbarTexture = NULL; + healthbarBackgroundTexture = NULL; + + miscTextureList.clear(); + + displayFont = NULL; + menuFontNormal = NULL; + displayFontSmall = NULL; + menuFontBig = NULL; + menuFontVeryBig = NULL; + consoleFont = NULL; + + displayFont3D = NULL; + menuFontNormal3D = NULL; + displayFontSmall3D = NULL; + menuFontBig3D = NULL; + menuFontVeryBig3D = NULL; + consoleFont3D = NULL; + + introVideoFilename = ""; + mainMenuVideoFilename = ""; + + battleEndWinVideoFilename = ""; + battleEndWinVideoFilenameFallback = ""; + battleEndWinMusicFilename = ""; + battleEndLoseVideoFilename = ""; + battleEndLoseVideoFilenameFallback = ""; + battleEndLoseMusicFilename = ""; +} + +CoreData::~CoreData() { cleanup(); } void CoreData::cleanup() { - deleteValues(waterSounds.getSoundsPtr()->begin(), waterSounds.getSoundsPtr()->end()); - waterSounds.getSoundsPtr()->clear(); + deleteValues(waterSounds.getSoundsPtr()->begin(), + waterSounds.getSoundsPtr()->end()); + waterSounds.getSoundsPtr()->clear(); } Texture2D *CoreData::getTextureBySystemId(TextureSystemType type) { - Texture2D *result = NULL; - switch(type) { - case tsyst_logoTexture: - result = getLogoTexture(); - break; - //std::vector logoTextureList; - case tsyst_backgroundTexture: - result = getBackgroundTexture(); - break; - case tsyst_fireTexture: - result = getFireTexture(); - break; - case tsyst_teamColorTexture: - result = getTeamColorTexture(); - break; - case tsyst_snowTexture: - result = getSnowTexture(); - break; - case tsyst_waterSplashTexture: - result = getWaterSplashTexture(); - break; - case tsyst_customTexture: - result = getCustomTexture(); - break; - case tsyst_buttonSmallTexture: - result = buttonSmallTexture; - break; - case tsyst_buttonBigTexture: - result = buttonBigTexture; - break; - case tsyst_horizontalLineTexture: - result = horizontalLineTexture; - break; - case tsyst_verticalLineTexture: - result = verticalLineTexture; - break; - case tsyst_checkBoxTexture: - result = checkBoxTexture; - break; - case tsyst_checkedCheckBoxTexture: - result = checkedCheckBoxTexture; - break; - case tsyst_gameWinnerTexture: - result = gameWinnerTexture; - break; - case tsyst_notOnServerTexture: - result = notOnServerTexture; - break; - case tsyst_onServerDifferentTexture: - result = onServerDifferentTexture; - break; - case tsyst_onServerTexture: - result = onServerTexture; - break; - case tsyst_onServerInstalledTexture: - result = onServerInstalledTexture; - break; - case tsyst_statusReadyTexture: - result = statusReadyTexture; - break; - case tsyst_statusNotReadyTexture: - result = statusNotReadyTexture; - break; - case tsyst_statusBRBTexture: - result = statusBRBTexture; - break; - case tsyst_healthbarTexture: - result = healthbarTexture; - break; - case tsyst_healthbarBackgroundTexture: - result = healthbarBackgroundTexture; - break; - - //std::vector miscTextureList; - } - return result; + Texture2D *result = NULL; + switch (type) { + case tsyst_logoTexture: + result = getLogoTexture(); + break; + // std::vector logoTextureList; + case tsyst_backgroundTexture: + result = getBackgroundTexture(); + break; + case tsyst_fireTexture: + result = getFireTexture(); + break; + case tsyst_teamColorTexture: + result = getTeamColorTexture(); + break; + case tsyst_snowTexture: + result = getSnowTexture(); + break; + case tsyst_waterSplashTexture: + result = getWaterSplashTexture(); + break; + case tsyst_customTexture: + result = getCustomTexture(); + break; + case tsyst_buttonSmallTexture: + result = buttonSmallTexture; + break; + case tsyst_buttonBigTexture: + result = buttonBigTexture; + break; + case tsyst_horizontalLineTexture: + result = horizontalLineTexture; + break; + case tsyst_verticalLineTexture: + result = verticalLineTexture; + break; + case tsyst_checkBoxTexture: + result = checkBoxTexture; + break; + case tsyst_checkedCheckBoxTexture: + result = checkedCheckBoxTexture; + break; + case tsyst_gameWinnerTexture: + result = gameWinnerTexture; + break; + case tsyst_notOnServerTexture: + result = notOnServerTexture; + break; + case tsyst_onServerDifferentTexture: + result = onServerDifferentTexture; + break; + case tsyst_onServerTexture: + result = onServerTexture; + break; + case tsyst_onServerInstalledTexture: + result = onServerInstalledTexture; + break; + case tsyst_statusReadyTexture: + result = statusReadyTexture; + break; + case tsyst_statusNotReadyTexture: + result = statusNotReadyTexture; + break; + case tsyst_statusBRBTexture: + result = statusBRBTexture; + break; + case tsyst_healthbarTexture: + result = healthbarTexture; + break; + case tsyst_healthbarBackgroundTexture: + result = healthbarBackgroundTexture; + break; + + // std::vector miscTextureList; + } + return result; } void CoreData::cleanupTexture(Texture2D **texture) { - Renderer &renderer= Renderer::getInstance(); - renderer.endTexture(rsGlobal, *texture); - *texture=NULL; -} + Renderer &renderer = Renderer::getInstance(); + renderer.endTexture(rsGlobal, *texture); + *texture = NULL; +} + +void CoreData::loadTextureIfRequired(Texture2D **tex, string data_path, + string uniqueFilePath, int texSystemId, + bool setMipMap, bool setAlpha, + bool loadUniqueFilePath, + bool compressionDisabled) { + if (*tex == NULL) { + bool attemptToLoadTexture = (texSystemId == tsyst_NONE); + if (attemptToLoadTexture == false && + itemLoadAttempted.find(texSystemId) == itemLoadAttempted.end()) { + + attemptToLoadTexture = true; + itemLoadAttempted[texSystemId] = true; + } -void CoreData::loadTextureIfRequired(Texture2D **tex,string data_path, - string uniqueFilePath, int texSystemId, - bool setMipMap, bool setAlpha, - bool loadUniqueFilePath, bool compressionDisabled) { - if(*tex == NULL) { - bool attemptToLoadTexture = (texSystemId == tsyst_NONE); - if(attemptToLoadTexture == false && - itemLoadAttempted.find(texSystemId) == itemLoadAttempted.end()) { - - attemptToLoadTexture = true; - itemLoadAttempted[texSystemId] = true; - } - - if(attemptToLoadTexture == true) { - Renderer &renderer = Renderer::getInstance(); - *tex = renderer.newTexture2D(rsGlobal); - if (*tex) { - - (*tex)->setForceCompressionDisabled(compressionDisabled); - (*tex)->setMipmap(setMipMap); - if(setAlpha == true) { - - (*tex)->setFormat(Texture::fAlpha); - (*tex)->getPixmap()->init(1); - } - - try { - string fileToLoad = uniqueFilePath; - if(loadUniqueFilePath == false) { - - fileToLoad = getGameCustomCoreDataPath(data_path,uniqueFilePath); - } - (*tex)->getPixmap()->load(fileToLoad); - (*tex)->setTextureSystemId(texSystemId); - - renderer.initTexture(rsGlobal,*tex); - } - catch (const megaglest_runtime_error& ex) { - message(ex.what(),GlobalStaticFlags::getIsNonGraphicalModeEnabled(), - tempDataLocation); - cleanupTexture (tex); - } - } - } - } + if (attemptToLoadTexture == true) { + Renderer &renderer = Renderer::getInstance(); + *tex = renderer.newTexture2D(rsGlobal); + if (*tex) { + + (*tex)->setForceCompressionDisabled(compressionDisabled); + (*tex)->setMipmap(setMipMap); + if (setAlpha == true) { + + (*tex)->setFormat(Texture::fAlpha); + (*tex)->getPixmap()->init(1); + } + + try { + string fileToLoad = uniqueFilePath; + if (loadUniqueFilePath == false) { + + fileToLoad = getGameCustomCoreDataPath(data_path, uniqueFilePath); + } + (*tex)->getPixmap()->load(fileToLoad); + (*tex)->setTextureSystemId(texSystemId); + + renderer.initTexture(rsGlobal, *tex); + } catch (const megaglest_runtime_error &ex) { + message(ex.what(), GlobalStaticFlags::getIsNonGraphicalModeEnabled(), + tempDataLocation); + cleanupTexture(tex); + } + } + } + } } string CoreData::getDataPath() { - string data_path = getGameReadWritePath(GameConstants::path_data_CacheLookupKey); - if(data_path != "") { - endPathWithSlash(data_path); - } - return data_path; + string data_path = + getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + if (data_path != "") { + endPathWithSlash(data_path); + } + return data_path; } -Texture2D * CoreData::getBackgroundTexture() { - string data_path = getDataPath(); - loadTextureIfRequired(&backgroundTexture, getDataPath(), - CORE_MENU_TEXTURES_PATH + "back.tga", tsyst_backgroundTexture, - false, false, false); +Texture2D *CoreData::getBackgroundTexture() { + string data_path = getDataPath(); + loadTextureIfRequired(&backgroundTexture, getDataPath(), + CORE_MENU_TEXTURES_PATH + "back.tga", + tsyst_backgroundTexture, false, false, false); - return backgroundTexture; + return backgroundTexture; } Texture2D *CoreData::getFireTexture() { - string data_path = getDataPath(); - loadTextureIfRequired(&fireTexture,data_path, - CORE_MISC_TEXTURES_PATH + "fire_particle.tga", tsyst_fireTexture, - true, true, false); + string data_path = getDataPath(); + loadTextureIfRequired(&fireTexture, data_path, + CORE_MISC_TEXTURES_PATH + "fire_particle.tga", + tsyst_fireTexture, true, true, false); - return fireTexture; + return fireTexture; } Texture2D *CoreData::getTeamColorTexture() { - string data_path = getDataPath(); - loadTextureIfRequired(&teamColorTexture,data_path, - CORE_MISC_TEXTURES_PATH + "team_color_texture.tga", tsyst_teamColorTexture, - true, true, false); + string data_path = getDataPath(); + loadTextureIfRequired(&teamColorTexture, data_path, + CORE_MISC_TEXTURES_PATH + "team_color_texture.tga", + tsyst_teamColorTexture, true, true, false); - return teamColorTexture; + return teamColorTexture; } Texture2D *CoreData::getSnowTexture() { - string data_path = getDataPath(); - loadTextureIfRequired(&snowTexture,data_path, - CORE_MISC_TEXTURES_PATH + "snow_particle.tga", tsyst_snowTexture, - false, true, false); + string data_path = getDataPath(); + loadTextureIfRequired(&snowTexture, data_path, + CORE_MISC_TEXTURES_PATH + "snow_particle.tga", + tsyst_snowTexture, false, true, false); - return snowTexture; + return snowTexture; } Texture2D *CoreData::getLogoTexture() { - string data_path = getDataPath(); - loadTextureIfRequired(&logoTexture,data_path, - CORE_MENU_TEXTURES_PATH + "logo.tga", tsyst_logoTexture, - false, false, false); + string data_path = getDataPath(); + loadTextureIfRequired(&logoTexture, data_path, + CORE_MENU_TEXTURES_PATH + "logo.tga", tsyst_logoTexture, + false, false, false); - return logoTexture; + return logoTexture; } Texture2D *CoreData::getWaterSplashTexture() { - string data_path = getDataPath(); - loadTextureIfRequired(&waterSplashTexture,data_path, - CORE_MISC_TEXTURES_PATH + "water_splash.tga", tsyst_waterSplashTexture, - true, true, false); + string data_path = getDataPath(); + loadTextureIfRequired(&waterSplashTexture, data_path, + CORE_MISC_TEXTURES_PATH + "water_splash.tga", + tsyst_waterSplashTexture, true, true, false); - return waterSplashTexture; + return waterSplashTexture; } Texture2D *CoreData::getCustomTexture() { - string data_path = getDataPath(); - loadTextureIfRequired(&customTexture,data_path, - CORE_MENU_TEXTURES_PATH + "custom_texture.tga", tsyst_customTexture, - true, false, false); + string data_path = getDataPath(); + loadTextureIfRequired(&customTexture, data_path, + CORE_MENU_TEXTURES_PATH + "custom_texture.tga", + tsyst_customTexture, true, false, false); - return customTexture; + return customTexture; } Texture2D *CoreData::getButtonSmallTexture() { - string data_path = getDataPath(); - loadTextureIfRequired(&buttonSmallTexture,data_path, - CORE_MENU_TEXTURES_PATH + "button_small.tga", tsyst_buttonSmallTexture, - true, false, false, true); + string data_path = getDataPath(); + loadTextureIfRequired(&buttonSmallTexture, data_path, + CORE_MENU_TEXTURES_PATH + "button_small.tga", + tsyst_buttonSmallTexture, true, false, false, true); - return buttonSmallTexture; + return buttonSmallTexture; } Texture2D *CoreData::getButtonBigTexture() { - string data_path = getDataPath(); - loadTextureIfRequired(&buttonBigTexture,data_path, - CORE_MENU_TEXTURES_PATH + "button_big.tga", tsyst_buttonBigTexture, - true, false, false, true); + string data_path = getDataPath(); + loadTextureIfRequired(&buttonBigTexture, data_path, + CORE_MENU_TEXTURES_PATH + "button_big.tga", + tsyst_buttonBigTexture, true, false, false, true); - return buttonBigTexture; + return buttonBigTexture; } Texture2D *CoreData::getHorizontalLineTexture() { - string data_path = getDataPath(); - loadTextureIfRequired(&horizontalLineTexture,data_path, - CORE_MENU_TEXTURES_PATH + "line_horizontal.tga", tsyst_horizontalLineTexture, - true, false, false, true); + string data_path = getDataPath(); + loadTextureIfRequired(&horizontalLineTexture, data_path, + CORE_MENU_TEXTURES_PATH + "line_horizontal.tga", + tsyst_horizontalLineTexture, true, false, false, true); - return horizontalLineTexture; + return horizontalLineTexture; } Texture2D *CoreData::getVerticalLineTexture() { - string data_path = getDataPath(); - loadTextureIfRequired(&verticalLineTexture,data_path, - CORE_MENU_TEXTURES_PATH + "line_vertical.tga", tsyst_verticalLineTexture, - true, false, false, true); + string data_path = getDataPath(); + loadTextureIfRequired(&verticalLineTexture, data_path, + CORE_MENU_TEXTURES_PATH + "line_vertical.tga", + tsyst_verticalLineTexture, true, false, false, true); - return verticalLineTexture; + return verticalLineTexture; } Texture2D *CoreData::getCheckBoxTexture() { - string data_path = getDataPath(); - loadTextureIfRequired(&checkBoxTexture,data_path, - CORE_MENU_TEXTURES_PATH + "checkbox.tga", tsyst_checkBoxTexture, - true, false, false, true); + string data_path = getDataPath(); + loadTextureIfRequired(&checkBoxTexture, data_path, + CORE_MENU_TEXTURES_PATH + "checkbox.tga", + tsyst_checkBoxTexture, true, false, false, true); - return checkBoxTexture; + return checkBoxTexture; } Texture2D *CoreData::getCheckedCheckBoxTexture() { - string data_path = getDataPath(); - loadTextureIfRequired(&checkedCheckBoxTexture,data_path, - CORE_MENU_TEXTURES_PATH + "checkbox_checked.tga", tsyst_checkedCheckBoxTexture, - true, false, false, true); + string data_path = getDataPath(); + loadTextureIfRequired(&checkedCheckBoxTexture, data_path, + CORE_MENU_TEXTURES_PATH + "checkbox_checked.tga", + tsyst_checkedCheckBoxTexture, true, false, false, true); - return checkedCheckBoxTexture; + return checkedCheckBoxTexture; } Texture2D *CoreData::getNotOnServerTexture() { - string data_path = getDataPath(); - loadTextureIfRequired(¬OnServerTexture,data_path, - CORE_MENU_TEXTURES_PATH + "not_on_server.tga", tsyst_notOnServerTexture, - true, false, false); + string data_path = getDataPath(); + loadTextureIfRequired(¬OnServerTexture, data_path, + CORE_MENU_TEXTURES_PATH + "not_on_server.tga", + tsyst_notOnServerTexture, true, false, false); - return notOnServerTexture; + return notOnServerTexture; } Texture2D *CoreData::getOnServerDifferentTexture() { - string data_path = getDataPath(); - loadTextureIfRequired(&onServerDifferentTexture,data_path, - CORE_MENU_TEXTURES_PATH + "on_server_different.tga", tsyst_onServerDifferentTexture, - true, false, false); + string data_path = getDataPath(); + loadTextureIfRequired(&onServerDifferentTexture, data_path, + CORE_MENU_TEXTURES_PATH + "on_server_different.tga", + tsyst_onServerDifferentTexture, true, false, false); - return onServerDifferentTexture; + return onServerDifferentTexture; } Texture2D *CoreData::getOnServerTexture() { - string data_path = getDataPath(); - loadTextureIfRequired(&onServerTexture,data_path, - CORE_MENU_TEXTURES_PATH + "on_server.tga", tsyst_onServerTexture, - true, false, false); + string data_path = getDataPath(); + loadTextureIfRequired(&onServerTexture, data_path, + CORE_MENU_TEXTURES_PATH + "on_server.tga", + tsyst_onServerTexture, true, false, false); - return onServerTexture; + return onServerTexture; } Texture2D *CoreData::getOnServerInstalledTexture() { - string data_path = getDataPath(); - loadTextureIfRequired(&onServerInstalledTexture,data_path, - CORE_MENU_TEXTURES_PATH + "on_server_installed.tga", tsyst_onServerInstalledTexture, - true, false, false); + string data_path = getDataPath(); + loadTextureIfRequired(&onServerInstalledTexture, data_path, + CORE_MENU_TEXTURES_PATH + "on_server_installed.tga", + tsyst_onServerInstalledTexture, true, false, false); - return onServerInstalledTexture; + return onServerInstalledTexture; } Texture2D *CoreData::getStatusReadyTexture() { - string data_path = getDataPath(); - loadTextureIfRequired(&statusReadyTexture,data_path, - CORE_MENU_TEXTURES_PATH + "status_ready.png", tsyst_statusReadyTexture, - true, false, false); + string data_path = getDataPath(); + loadTextureIfRequired(&statusReadyTexture, data_path, + CORE_MENU_TEXTURES_PATH + "status_ready.png", + tsyst_statusReadyTexture, true, false, false); - return statusReadyTexture; + return statusReadyTexture; } Texture2D *CoreData::getStatusNotReadyTexture() { - string data_path = getDataPath(); - loadTextureIfRequired(&statusNotReadyTexture,data_path, - CORE_MENU_TEXTURES_PATH + "status_notready.png", tsyst_statusNotReadyTexture, - true, false, false); + string data_path = getDataPath(); + loadTextureIfRequired(&statusNotReadyTexture, data_path, + CORE_MENU_TEXTURES_PATH + "status_notready.png", + tsyst_statusNotReadyTexture, true, false, false); - return statusNotReadyTexture; + return statusNotReadyTexture; } Texture2D *CoreData::getStatusBRBTexture() { - string data_path = getDataPath(); - loadTextureIfRequired(&statusBRBTexture,data_path, - CORE_MENU_TEXTURES_PATH + "status_brb.png", tsyst_statusBRBTexture, - true, false, false); + string data_path = getDataPath(); + loadTextureIfRequired(&statusBRBTexture, data_path, + CORE_MENU_TEXTURES_PATH + "status_brb.png", + tsyst_statusBRBTexture, true, false, false); - return statusBRBTexture; + return statusBRBTexture; } Texture2D *CoreData::getGameWinnerTexture() { - string data_path = getDataPath(); - loadTextureIfRequired(&gameWinnerTexture,data_path, - CORE_MISC_TEXTURES_PATH + "game_winner.png", tsyst_gameWinnerTexture, - true, false, false, true); + string data_path = getDataPath(); + loadTextureIfRequired(&gameWinnerTexture, data_path, + CORE_MISC_TEXTURES_PATH + "game_winner.png", + tsyst_gameWinnerTexture, true, false, false, true); - return gameWinnerTexture; + return gameWinnerTexture; } Texture2D *CoreData::getHealthbarTexture() { - string data_path = getDataPath(); - loadTextureIfRequired(&healthbarTexture,data_path, - CORE_MISC_TEXTURES_PATH + "healthbar.png", tsyst_healthbarTexture, - true, false, false, true); + string data_path = getDataPath(); + loadTextureIfRequired(&healthbarTexture, data_path, + CORE_MISC_TEXTURES_PATH + "healthbar.png", + tsyst_healthbarTexture, true, false, false, true); - return healthbarTexture; + return healthbarTexture; } Texture2D *CoreData::getHealthbarBackgroundTexture() { - string data_path = getDataPath(); - loadTextureIfRequired(&healthbarBackgroundTexture,data_path, - CORE_MISC_TEXTURES_PATH + "healthbarBackground.png", tsyst_healthbarBackgroundTexture, - true, false, false, true); + string data_path = getDataPath(); + loadTextureIfRequired(&healthbarBackgroundTexture, data_path, + CORE_MISC_TEXTURES_PATH + "healthbarBackground.png", + tsyst_healthbarBackgroundTexture, true, false, false, + true); - return healthbarBackgroundTexture; + return healthbarBackgroundTexture; } void CoreData::loadLogoTextureExtraIfRequired() { - int loadAttemptLookupKey = tsyst_COUNT + 1; - if(itemLoadAttempted.find(loadAttemptLookupKey) == itemLoadAttempted.end()) { - - itemLoadAttempted[loadAttemptLookupKey] = true; - - string data_path = getDataPath(); - logoTextureList.clear(); - string logosPath = getGameCustomCoreDataPath(data_path, "") - + CORE_MENU_TEXTURES_PATH + "logo*.*"; - vector logoFilenames; - findAll(logosPath, logoFilenames, false, false); - for (int index = 0; index < (int)logoFilenames.size(); ++index) { - - string logo = logoFilenames[index]; - if (strcmp("logo.tga", logo.c_str()) != 0) { - - Texture2D* logoTextureExtra = NULL; - loadTextureIfRequired(&logoTextureExtra,data_path, - getGameCustomCoreDataPath(data_path, "") + - CORE_MENU_TEXTURES_PATH + logo, tsyst_NONE, - true, false, true); - logoTextureList.push_back(logoTextureExtra); - } - } - if (logoTextureList.empty() == true) { - - logosPath = data_path + CORE_MENU_TEXTURES_PATH + "logo*.*"; - vector logoFilenames; - findAll(logosPath, logoFilenames, false, false); - for (int index = 0; index < (int)logoFilenames.size(); ++index) { - - string logo = logoFilenames[index]; - if (strcmp("logo.tga", logo.c_str()) != 0) { - - Texture2D* logoTextureExtra = NULL; - loadTextureIfRequired(&logoTextureExtra,data_path, - data_path + CORE_MENU_TEXTURES_PATH + logo, tsyst_NONE, - true, false, true); - logoTextureList.push_back(logoTextureExtra); - } - } - } - } + int loadAttemptLookupKey = tsyst_COUNT + 1; + if (itemLoadAttempted.find(loadAttemptLookupKey) == itemLoadAttempted.end()) { + + itemLoadAttempted[loadAttemptLookupKey] = true; + + string data_path = getDataPath(); + logoTextureList.clear(); + string logosPath = getGameCustomCoreDataPath(data_path, "") + + CORE_MENU_TEXTURES_PATH + "logo*.*"; + vector logoFilenames; + findAll(logosPath, logoFilenames, false, false); + for (int index = 0; index < (int)logoFilenames.size(); ++index) { + + string logo = logoFilenames[index]; + if (strcmp("logo.tga", logo.c_str()) != 0) { + + Texture2D *logoTextureExtra = NULL; + loadTextureIfRequired(&logoTextureExtra, data_path, + getGameCustomCoreDataPath(data_path, "") + + CORE_MENU_TEXTURES_PATH + logo, + tsyst_NONE, true, false, true); + logoTextureList.push_back(logoTextureExtra); + } + } + if (logoTextureList.empty() == true) { + + logosPath = data_path + CORE_MENU_TEXTURES_PATH + "logo*.*"; + vector logoFilenames; + findAll(logosPath, logoFilenames, false, false); + for (int index = 0; index < (int)logoFilenames.size(); ++index) { + + string logo = logoFilenames[index]; + if (strcmp("logo.tga", logo.c_str()) != 0) { + + Texture2D *logoTextureExtra = NULL; + loadTextureIfRequired(&logoTextureExtra, data_path, + data_path + CORE_MENU_TEXTURES_PATH + logo, + tsyst_NONE, true, false, true); + logoTextureList.push_back(logoTextureExtra); + } + } + } + } } size_t CoreData::getLogoTextureExtraCount() { - loadLogoTextureExtraIfRequired(); - return logoTextureList.size(); + loadLogoTextureExtraIfRequired(); + return logoTextureList.size(); } Texture2D *CoreData::getLogoTextureExtra(int idx) { - loadLogoTextureExtraIfRequired(); - return logoTextureList[idx]; + loadLogoTextureExtraIfRequired(); + return logoTextureList[idx]; } void CoreData::loadMiscTextureListIfRequired() { - int loadAttemptLookupKey = tsyst_COUNT + 2; - if(itemLoadAttempted.find(loadAttemptLookupKey) == itemLoadAttempted.end()) { - - itemLoadAttempted[loadAttemptLookupKey] = true; - - string data_path = getDataPath(); - - miscTextureList.clear(); - string introPath = getGameCustomCoreDataPath(data_path, "") - + CORE_MENU_TEXTURES_PATH + "intro*.*"; - vector introFilenames; - findAll(introPath, introFilenames, false, false); - for (int i = 0; i < (int)introFilenames.size(); ++i) { - string logo = introFilenames[i]; - - Texture2D* logoTextureExtra = NULL; - loadTextureIfRequired(&logoTextureExtra,data_path, - getGameCustomCoreDataPath(data_path, "") + CORE_MENU_TEXTURES_PATH + - logo, tsyst_NONE, - true, false, true); - miscTextureList.push_back(logoTextureExtra); - } - if (miscTextureList.empty() == true) { - introPath = data_path + CORE_MENU_TEXTURES_PATH + "intro*.*"; - vector introFilenames; - findAll(introPath, introFilenames, false, false); - for (int i = 0; i < (int)introFilenames.size(); ++i) { - string logo = introFilenames[i]; - - Texture2D* logoTextureExtra = NULL; - loadTextureIfRequired(&logoTextureExtra,data_path, - data_path + CORE_MENU_TEXTURES_PATH + logo, tsyst_NONE, - true, false, true); - miscTextureList.push_back(logoTextureExtra); - } - } - - } + int loadAttemptLookupKey = tsyst_COUNT + 2; + if (itemLoadAttempted.find(loadAttemptLookupKey) == itemLoadAttempted.end()) { + + itemLoadAttempted[loadAttemptLookupKey] = true; + + string data_path = getDataPath(); + + miscTextureList.clear(); + string introPath = getGameCustomCoreDataPath(data_path, "") + + CORE_MENU_TEXTURES_PATH + "intro*.*"; + vector introFilenames; + findAll(introPath, introFilenames, false, false); + for (int i = 0; i < (int)introFilenames.size(); ++i) { + string logo = introFilenames[i]; + + Texture2D *logoTextureExtra = NULL; + loadTextureIfRequired(&logoTextureExtra, data_path, + getGameCustomCoreDataPath(data_path, "") + + CORE_MENU_TEXTURES_PATH + logo, + tsyst_NONE, true, false, true); + miscTextureList.push_back(logoTextureExtra); + } + if (miscTextureList.empty() == true) { + introPath = data_path + CORE_MENU_TEXTURES_PATH + "intro*.*"; + vector introFilenames; + findAll(introPath, introFilenames, false, false); + for (int i = 0; i < (int)introFilenames.size(); ++i) { + string logo = introFilenames[i]; + + Texture2D *logoTextureExtra = NULL; + loadTextureIfRequired(&logoTextureExtra, data_path, + data_path + CORE_MENU_TEXTURES_PATH + logo, + tsyst_NONE, true, false, true); + miscTextureList.push_back(logoTextureExtra); + } + } + } } -std::vector & CoreData::getMiscTextureList() { - loadMiscTextureListIfRequired(); - return miscTextureList; +std::vector &CoreData::getMiscTextureList() { + loadMiscTextureListIfRequired(); + return miscTextureList; } void CoreData::loadTextures(string data_path) { - // Required to be loaded at program startup as they may be accessed in - // threads or some other dangerous way so lazy loading is not an option - getCustomTexture(); + // Required to be loaded at program startup as they may be accessed in + // threads or some other dangerous way so lazy loading is not an option + getCustomTexture(); } StaticSound *CoreData::getClickSoundA() { - int loadAttemptLookupKey = tsyst_COUNT + 3; - if(itemLoadAttempted.find(loadAttemptLookupKey) == itemLoadAttempted.end()) { - - itemLoadAttempted[loadAttemptLookupKey] = true; - - try { - string data_path = getDataPath(); - clickSoundA.load(getGameCustomCoreDataPath(data_path, - CORE_MENU_SOUND_PATH + "click_a.wav")); - } - catch (const megaglest_runtime_error& ex) { - message(ex.what(), GlobalStaticFlags::getIsNonGraphicalModeEnabled(), - tempDataLocation); - } - } - return &clickSoundA; + int loadAttemptLookupKey = tsyst_COUNT + 3; + if (itemLoadAttempted.find(loadAttemptLookupKey) == itemLoadAttempted.end()) { + + itemLoadAttempted[loadAttemptLookupKey] = true; + + try { + string data_path = getDataPath(); + clickSoundA.load(getGameCustomCoreDataPath( + data_path, CORE_MENU_SOUND_PATH + "click_a.wav")); + } catch (const megaglest_runtime_error &ex) { + message(ex.what(), GlobalStaticFlags::getIsNonGraphicalModeEnabled(), + tempDataLocation); + } + } + return &clickSoundA; } -StaticSound *CoreData::getClickSoundB() { - int loadAttemptLookupKey = tsyst_COUNT + 4; - if(itemLoadAttempted.find(loadAttemptLookupKey) == itemLoadAttempted.end()) { +StaticSound *CoreData::getClickSoundB() { + int loadAttemptLookupKey = tsyst_COUNT + 4; + if (itemLoadAttempted.find(loadAttemptLookupKey) == itemLoadAttempted.end()) { - itemLoadAttempted[loadAttemptLookupKey] = true; + itemLoadAttempted[loadAttemptLookupKey] = true; - try { - string data_path = getDataPath(); - clickSoundB.load(getGameCustomCoreDataPath(data_path, - CORE_MENU_SOUND_PATH + "click_b.wav")); - } - catch (const megaglest_runtime_error& ex) { - message(ex.what(), GlobalStaticFlags::getIsNonGraphicalModeEnabled(), - tempDataLocation); - } - } + try { + string data_path = getDataPath(); + clickSoundB.load(getGameCustomCoreDataPath( + data_path, CORE_MENU_SOUND_PATH + "click_b.wav")); + } catch (const megaglest_runtime_error &ex) { + message(ex.what(), GlobalStaticFlags::getIsNonGraphicalModeEnabled(), + tempDataLocation); + } + } - return &clickSoundB; + return &clickSoundB; } -StaticSound *CoreData::getClickSoundC() { - int loadAttemptLookupKey = tsyst_COUNT + 5; - if(itemLoadAttempted.find(loadAttemptLookupKey) == itemLoadAttempted.end()) { - - itemLoadAttempted[loadAttemptLookupKey] = true; - - try { - string data_path = getDataPath(); - clickSoundC.load(getGameCustomCoreDataPath(data_path, - CORE_MENU_SOUND_PATH + "click_c.wav")); - } - catch (const megaglest_runtime_error& ex) { - message(ex.what(), GlobalStaticFlags::getIsNonGraphicalModeEnabled(), - tempDataLocation); - } - } - - return &clickSoundC; +StaticSound *CoreData::getClickSoundC() { + int loadAttemptLookupKey = tsyst_COUNT + 5; + if (itemLoadAttempted.find(loadAttemptLookupKey) == itemLoadAttempted.end()) { + + itemLoadAttempted[loadAttemptLookupKey] = true; + + try { + string data_path = getDataPath(); + clickSoundC.load(getGameCustomCoreDataPath( + data_path, CORE_MENU_SOUND_PATH + "click_c.wav")); + } catch (const megaglest_runtime_error &ex) { + message(ex.what(), GlobalStaticFlags::getIsNonGraphicalModeEnabled(), + tempDataLocation); + } + } + + return &clickSoundC; } StaticSound *CoreData::getAttentionSound() { - int loadAttemptLookupKey = tsyst_COUNT + 6; - if(itemLoadAttempted.find(loadAttemptLookupKey) == itemLoadAttempted.end()) { - - itemLoadAttempted[loadAttemptLookupKey] = true; - - try { - string data_path = getDataPath(); - attentionSound.load(getGameCustomCoreDataPath(data_path, - CORE_MENU_SOUND_PATH + "attention.wav")); - } - catch (const megaglest_runtime_error& ex) { - message(ex.what(), GlobalStaticFlags::getIsNonGraphicalModeEnabled(), - tempDataLocation); - } - } - - return &attentionSound; + int loadAttemptLookupKey = tsyst_COUNT + 6; + if (itemLoadAttempted.find(loadAttemptLookupKey) == itemLoadAttempted.end()) { + + itemLoadAttempted[loadAttemptLookupKey] = true; + + try { + string data_path = getDataPath(); + attentionSound.load(getGameCustomCoreDataPath( + data_path, CORE_MENU_SOUND_PATH + "attention.wav")); + } catch (const megaglest_runtime_error &ex) { + message(ex.what(), GlobalStaticFlags::getIsNonGraphicalModeEnabled(), + tempDataLocation); + } + } + + return &attentionSound; } -StaticSound *CoreData::getHighlightSound() { - int loadAttemptLookupKey = tsyst_COUNT + 7; - if(itemLoadAttempted.find(loadAttemptLookupKey) == itemLoadAttempted.end()) { - - itemLoadAttempted[loadAttemptLookupKey] = true; - - try { - string data_path = getDataPath(); - highlightSound.load(getGameCustomCoreDataPath(data_path, - CORE_MENU_SOUND_PATH + "highlight.wav")); - } - catch (const megaglest_runtime_error& ex) { - message(ex.what(), GlobalStaticFlags::getIsNonGraphicalModeEnabled(), - tempDataLocation); - } - } - - return &highlightSound; +StaticSound *CoreData::getHighlightSound() { + int loadAttemptLookupKey = tsyst_COUNT + 7; + if (itemLoadAttempted.find(loadAttemptLookupKey) == itemLoadAttempted.end()) { + + itemLoadAttempted[loadAttemptLookupKey] = true; + + try { + string data_path = getDataPath(); + highlightSound.load(getGameCustomCoreDataPath( + data_path, CORE_MENU_SOUND_PATH + "highlight.wav")); + } catch (const megaglest_runtime_error &ex) { + message(ex.what(), GlobalStaticFlags::getIsNonGraphicalModeEnabled(), + tempDataLocation); + } + } + + return &highlightSound; } StaticSound *CoreData::getMarkerSound() { - int loadAttemptLookupKey = tsyst_COUNT + 8; - if(itemLoadAttempted.find(loadAttemptLookupKey) == itemLoadAttempted.end()) { - - itemLoadAttempted[loadAttemptLookupKey] = true; - - try { - string data_path = getDataPath(); - markerSound.load(getGameCustomCoreDataPath(data_path, - CORE_MENU_SOUND_PATH + "sonar.wav")); - } - catch (const megaglest_runtime_error& ex) { - message(ex.what(), GlobalStaticFlags::getIsNonGraphicalModeEnabled(), - tempDataLocation); - } - } - - return &markerSound; + int loadAttemptLookupKey = tsyst_COUNT + 8; + if (itemLoadAttempted.find(loadAttemptLookupKey) == itemLoadAttempted.end()) { + + itemLoadAttempted[loadAttemptLookupKey] = true; + + try { + string data_path = getDataPath(); + markerSound.load(getGameCustomCoreDataPath( + data_path, CORE_MENU_SOUND_PATH + "sonar.wav")); + } catch (const megaglest_runtime_error &ex) { + message(ex.what(), GlobalStaticFlags::getIsNonGraphicalModeEnabled(), + tempDataLocation); + } + } + + return &markerSound; } void CoreData::loadWaterSoundsIfRequired() { - int loadAttemptLookupKey = tsyst_COUNT + 9; - if(itemLoadAttempted.find(loadAttemptLookupKey) == itemLoadAttempted.end()) { - - itemLoadAttempted[loadAttemptLookupKey] = true; - - string data_path = getDataPath(); - cleanup(); - waterSounds.resize(6); - - for (int index = 0; index < 6; ++index) { - waterSounds[index] = new StaticSound(); - if (waterSounds[index] != NULL) { - try { - waterSounds[index]->load(getGameCustomCoreDataPath(data_path, - CORE_WATER_SOUNDS_PATH + - "water" + intToStr(index) + ".wav")); - } - catch (const megaglest_runtime_error& ex) { - message(ex.what(), - GlobalStaticFlags::getIsNonGraphicalModeEnabled(), - tempDataLocation); - } - } - } - } + int loadAttemptLookupKey = tsyst_COUNT + 9; + if (itemLoadAttempted.find(loadAttemptLookupKey) == itemLoadAttempted.end()) { + + itemLoadAttempted[loadAttemptLookupKey] = true; + + string data_path = getDataPath(); + cleanup(); + waterSounds.resize(6); + + for (int index = 0; index < 6; ++index) { + waterSounds[index] = new StaticSound(); + if (waterSounds[index] != NULL) { + try { + waterSounds[index]->load(getGameCustomCoreDataPath( + data_path, + CORE_WATER_SOUNDS_PATH + "water" + intToStr(index) + ".wav")); + } catch (const megaglest_runtime_error &ex) { + message(ex.what(), GlobalStaticFlags::getIsNonGraphicalModeEnabled(), + tempDataLocation); + } + } + } + } } StaticSound *CoreData::getWaterSound() { - loadWaterSoundsIfRequired(); - return waterSounds.getRandSound(); + loadWaterSoundsIfRequired(); + return waterSounds.getRandSound(); } void CoreData::loadSounds(string data_path) { - // sounds -// try { -// clickSoundA.load( -// getGameCustomCoreDataPath(data_path, -// CORE_MENU_SOUND_PATH + "click_a.wav")); -// clickSoundB.load( -// getGameCustomCoreDataPath(data_path, -// CORE_MENU_SOUND_PATH + "click_b.wav")); -// clickSoundC.load( -// getGameCustomCoreDataPath(data_path, -// CORE_MENU_SOUND_PATH + "click_c.wav")); -// attentionSound.load( -// getGameCustomCoreDataPath(data_path, -// CORE_MENU_SOUND_PATH + "attention.wav")); -// highlightSound.load( -// getGameCustomCoreDataPath(data_path, -// CORE_MENU_SOUND_PATH + "highlight.wav")); -// markerSound.load( -// getGameCustomCoreDataPath(data_path, -// CORE_MENU_SOUND_PATH + "sonar.wav")); -// } -// catch (const megaglest_runtime_error& ex) { -// message(ex.what(), GlobalStaticFlags::getIsNonGraphicalModeEnabled(), -// tempDataLocation); -// } - -// cleanup(); -// waterSounds.resize(6); -// -// for (int i = 0; i < 6; ++i) { -// waterSounds[i] = new StaticSound(); -// if (waterSounds[i]) { -// try { -// waterSounds[i]->load( -// getGameCustomCoreDataPath(data_path, -// CORE_WATER_SOUNDS_PATH + "water" + intToStr(i) -// + ".wav")); -// } catch (const megaglest_runtime_error& ex) { -// message(ex.what(), -// GlobalStaticFlags::getIsNonGraphicalModeEnabled(), -// tempDataLocation); -// } -// } -// } + // sounds + // try { + // clickSoundA.load( + // getGameCustomCoreDataPath(data_path, + // CORE_MENU_SOUND_PATH + + //"click_a.wav")); clickSoundB.load( + //getGameCustomCoreDataPath(data_path, CORE_MENU_SOUND_PATH + "click_b.wav")); + //clickSoundC.load( getGameCustomCoreDataPath(data_path, CORE_MENU_SOUND_PATH + //+ "click_c.wav")); attentionSound.load( + //getGameCustomCoreDataPath(data_path, CORE_MENU_SOUND_PATH + + //"attention.wav")); highlightSound.load( + //getGameCustomCoreDataPath(data_path, CORE_MENU_SOUND_PATH + + //"highlight.wav")); markerSound.load( + //getGameCustomCoreDataPath(data_path, CORE_MENU_SOUND_PATH + "sonar.wav")); + // } + // catch (const megaglest_runtime_error& ex) { + // message(ex.what(), + // GlobalStaticFlags::getIsNonGraphicalModeEnabled(), + // tempDataLocation); + // } + + // cleanup(); + // waterSounds.resize(6); + // + // for (int i = 0; i < 6; ++i) { + // waterSounds[i] = new StaticSound(); + // if (waterSounds[i]) { + // try { + // waterSounds[i]->load( + // getGameCustomCoreDataPath(data_path, + // CORE_WATER_SOUNDS_PATH + "water" + //+ intToStr(i) + // + + //".wav")); } catch (const megaglest_runtime_error& ex) { + //message(ex.what(), GlobalStaticFlags::getIsNonGraphicalModeEnabled(), + // tempDataLocation); + // } + // } + // } } - void CoreData::loadMusicIfRequired() { - int loadAttemptLookupKey = tsyst_COUNT + 10; - if(itemLoadAttempted.find(loadAttemptLookupKey) == itemLoadAttempted.end()) { - - itemLoadAttempted[loadAttemptLookupKey] = true; - - string data_path = getDataPath(); - - XmlTree xmlTree; - xmlTree.load( - getGameCustomCoreDataPath(data_path, CORE_MENU_PATH + "menu.xml"), - Properties::getTagReplacementValues()); - const XmlNode* menuNode = xmlTree.getRootNode(); - string menuMusicPath = "/menu/music/"; - string menuIntroMusicFile = "intro_music.ogg"; - string menuMusicFile = "menu_music.ogg"; - if (menuNode->hasChild("intro") == true) { - const XmlNode* introNode = menuNode->getChild("intro"); - // intro info - const XmlNode* menuPathNode = introNode->getChild("menu-music-path"); - menuMusicPath = - menuPathNode->getAttribute("value")->getRestrictedValue(); - const XmlNode* menuIntroMusicNode = introNode->getChild( - "menu-intro-music"); - menuIntroMusicFile = - menuIntroMusicNode->getAttribute("value")->getRestrictedValue(); - const XmlNode* menuMusicNode = introNode->getChild("menu-music"); - menuMusicFile = - menuMusicNode->getAttribute("value")->getRestrictedValue(); - } - try { - introMusic.open( - getGameCustomCoreDataPath(data_path, - CORE_PATH + menuMusicPath + menuIntroMusicFile)); - introMusic.setNext(&menuMusic); - menuMusic.open( - getGameCustomCoreDataPath(data_path, - CORE_PATH + menuMusicPath + menuMusicFile)); - menuMusic.setNext(&menuMusic); - } - catch (const megaglest_runtime_error& ex) { - message(ex.what(), GlobalStaticFlags::getIsNonGraphicalModeEnabled(), - tempDataLocation); - } - } + int loadAttemptLookupKey = tsyst_COUNT + 10; + if (itemLoadAttempted.find(loadAttemptLookupKey) == itemLoadAttempted.end()) { + + itemLoadAttempted[loadAttemptLookupKey] = true; + + string data_path = getDataPath(); + + XmlTree xmlTree; + xmlTree.load( + getGameCustomCoreDataPath(data_path, CORE_MENU_PATH + "menu.xml"), + Properties::getTagReplacementValues()); + const XmlNode *menuNode = xmlTree.getRootNode(); + string menuMusicPath = "/menu/music/"; + string menuIntroMusicFile = "intro_music.ogg"; + string menuMusicFile = "menu_music.ogg"; + if (menuNode->hasChild("intro") == true) { + const XmlNode *introNode = menuNode->getChild("intro"); + // intro info + const XmlNode *menuPathNode = introNode->getChild("menu-music-path"); + menuMusicPath = menuPathNode->getAttribute("value")->getRestrictedValue(); + const XmlNode *menuIntroMusicNode = + introNode->getChild("menu-intro-music"); + menuIntroMusicFile = + menuIntroMusicNode->getAttribute("value")->getRestrictedValue(); + const XmlNode *menuMusicNode = introNode->getChild("menu-music"); + menuMusicFile = + menuMusicNode->getAttribute("value")->getRestrictedValue(); + } + try { + introMusic.open(getGameCustomCoreDataPath( + data_path, CORE_PATH + menuMusicPath + menuIntroMusicFile)); + introMusic.setNext(&menuMusic); + menuMusic.open(getGameCustomCoreDataPath( + data_path, CORE_PATH + menuMusicPath + menuMusicFile)); + menuMusic.setNext(&menuMusic); + } catch (const megaglest_runtime_error &ex) { + message(ex.what(), GlobalStaticFlags::getIsNonGraphicalModeEnabled(), + tempDataLocation); + } + } } StrSound *CoreData::getIntroMusic() { - loadMusicIfRequired(); - return &introMusic; + loadMusicIfRequired(); + return &introMusic; } StrSound *CoreData::getMenuMusic() { - loadMusicIfRequired(); - return &menuMusic; + loadMusicIfRequired(); + return &menuMusic; } -void CoreData::loadMusic(string data_path) { -} +void CoreData::loadMusic(string data_path) {} void CoreData::loadIntroMedia(string data_path) { - Config &config= Config::getInstance(); - - introVideoFilename = config.getString("IntroVideoURL", ""); - introVideoFilenameFallback = config.getString("IntroVideoURLFallback", ""); - if (introVideoFilename == "") { - string introVideoPath = getGameCustomCoreDataPath(data_path, "") - + CORE_MENU_VIDEOS_PATH + "intro.*"; - vector introVideos; - findAll(introVideoPath, introVideos, false, false); - for (int i = 0; i < (int)introVideos.size(); ++i) { - string video = getGameCustomCoreDataPath(data_path, "") - + CORE_MENU_VIDEOS_PATH + introVideos[i]; - if (SystemFlags::VERBOSE_MODE_ENABLED) - printf("Checking if intro video [%s] exists\n", video.c_str()); - - if (fileExists(video)) { - introVideoFilename = video; - if (SystemFlags::VERBOSE_MODE_ENABLED) - printf("FOUND intro video [%s] will use this file\n", - video.c_str()); - - break; - } - } - if (introVideoFilename == "") { - introVideoPath = data_path + CORE_MENU_VIDEOS_PATH + "intro.*"; - introVideos.clear(); - findAll(introVideoPath, introVideos, false, false); - for (int i = 0; i < (int)introVideos.size(); ++i) { - string video = data_path + CORE_MENU_VIDEOS_PATH - + introVideos[i]; - if (SystemFlags::VERBOSE_MODE_ENABLED) - printf("Checking if intro video [%s] exists\n", - video.c_str()); - - if (fileExists(video)) { - introVideoFilename = video; - if (SystemFlags::VERBOSE_MODE_ENABLED) - printf("FOUND intro video [%s] will use this file\n", - video.c_str()); - - break; - } - } - } - } + Config &config = Config::getInstance(); + + introVideoFilename = config.getString("IntroVideoURL", ""); + introVideoFilenameFallback = config.getString("IntroVideoURLFallback", ""); + if (introVideoFilename == "") { + string introVideoPath = getGameCustomCoreDataPath(data_path, "") + + CORE_MENU_VIDEOS_PATH + "intro.*"; + vector introVideos; + findAll(introVideoPath, introVideos, false, false); + for (int i = 0; i < (int)introVideos.size(); ++i) { + string video = getGameCustomCoreDataPath(data_path, "") + + CORE_MENU_VIDEOS_PATH + introVideos[i]; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Checking if intro video [%s] exists\n", video.c_str()); + + if (fileExists(video)) { + introVideoFilename = video; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("FOUND intro video [%s] will use this file\n", video.c_str()); + + break; + } + } + if (introVideoFilename == "") { + introVideoPath = data_path + CORE_MENU_VIDEOS_PATH + "intro.*"; + introVideos.clear(); + findAll(introVideoPath, introVideos, false, false); + for (int i = 0; i < (int)introVideos.size(); ++i) { + string video = data_path + CORE_MENU_VIDEOS_PATH + introVideos[i]; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Checking if intro video [%s] exists\n", video.c_str()); + + if (fileExists(video)) { + introVideoFilename = video; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("FOUND intro video [%s] will use this file\n", + video.c_str()); + + break; + } + } + } + } } void CoreData::loadMainMenuMedia(string data_path) { - Config &config= Config::getInstance(); - - mainMenuVideoFilename = config.getString("MainMenuVideoURL", ""); - mainMenuVideoFilenameFallback = config.getString("MainMenuVideoURLFallback", - ""); - if (mainMenuVideoFilename == "") { - string mainVideoPath = getGameCustomCoreDataPath(data_path, "") - + CORE_MENU_VIDEOS_PATH + "main.*"; - vector mainVideos; - findAll(mainVideoPath, mainVideos, false, false); - for (int i = 0; i < (int)mainVideos.size(); ++i) { - string video = getGameCustomCoreDataPath(data_path, "") - + CORE_MENU_VIDEOS_PATH + mainVideos[i]; - if (SystemFlags::VERBOSE_MODE_ENABLED) - printf("Checking if mainmenu video [%s] exists\n", - video.c_str()); - - if (fileExists(video)) { - mainMenuVideoFilename = video; - if (SystemFlags::VERBOSE_MODE_ENABLED) - printf("FOUND mainmenu video [%s] will use this file\n", - video.c_str()); - - break; - } - } - if (mainMenuVideoFilename == "") { - mainVideoPath = data_path + CORE_MENU_VIDEOS_PATH + "main.*"; - mainVideos.clear(); - findAll(mainVideoPath, mainVideos, false, false); - for (int i = 0; i < (int)mainVideos.size(); ++i) { - string video = data_path + CORE_MENU_VIDEOS_PATH - + mainVideos[i]; - if (SystemFlags::VERBOSE_MODE_ENABLED) - printf("Checking if mainmenu video [%s] exists\n", - video.c_str()); - - if (fileExists(video)) { - mainMenuVideoFilename = video; - if (SystemFlags::VERBOSE_MODE_ENABLED) - printf("FOUND mainmenu video [%s] will use this file\n", - video.c_str()); - - break; - } - } - } - } + Config &config = Config::getInstance(); + + mainMenuVideoFilename = config.getString("MainMenuVideoURL", ""); + mainMenuVideoFilenameFallback = + config.getString("MainMenuVideoURLFallback", ""); + if (mainMenuVideoFilename == "") { + string mainVideoPath = getGameCustomCoreDataPath(data_path, "") + + CORE_MENU_VIDEOS_PATH + "main.*"; + vector mainVideos; + findAll(mainVideoPath, mainVideos, false, false); + for (int i = 0; i < (int)mainVideos.size(); ++i) { + string video = getGameCustomCoreDataPath(data_path, "") + + CORE_MENU_VIDEOS_PATH + mainVideos[i]; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Checking if mainmenu video [%s] exists\n", video.c_str()); + + if (fileExists(video)) { + mainMenuVideoFilename = video; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("FOUND mainmenu video [%s] will use this file\n", + video.c_str()); + + break; + } + } + if (mainMenuVideoFilename == "") { + mainVideoPath = data_path + CORE_MENU_VIDEOS_PATH + "main.*"; + mainVideos.clear(); + findAll(mainVideoPath, mainVideos, false, false); + for (int i = 0; i < (int)mainVideos.size(); ++i) { + string video = data_path + CORE_MENU_VIDEOS_PATH + mainVideos[i]; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Checking if mainmenu video [%s] exists\n", video.c_str()); + + if (fileExists(video)) { + mainMenuVideoFilename = video; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("FOUND mainmenu video [%s] will use this file\n", + video.c_str()); + + break; + } + } + } + } } void CoreData::loadBattleEndMedia(string data_path) { - Config &config= Config::getInstance(); - - battleEndWinVideoFilename = config.getString("BattleEndWinVideoURL", ""); - battleEndWinVideoFilenameFallback = config.getString( - "BattleEndWinVideoURLFallback", ""); - if (battleEndWinVideoFilename == "") { - string battleEndWinVideoPath = getGameCustomCoreDataPath(data_path, "") - + CORE_MENU_VIDEOS_PATH + "battle_end_win.*"; - vector battleEndWinVideos; - findAll(battleEndWinVideoPath, battleEndWinVideos, false, false); - for (int i = 0; i < (int)battleEndWinVideos.size(); ++i) { - string video = getGameCustomCoreDataPath(data_path, "") - + CORE_MENU_VIDEOS_PATH + battleEndWinVideos[i]; - if (SystemFlags::VERBOSE_MODE_ENABLED) - printf("Checking if battle end win video [%s] exists\n", - video.c_str()); - - if (fileExists(video)) { - battleEndWinVideoFilename = video; - if (SystemFlags::VERBOSE_MODE_ENABLED) - printf( - "FOUND battle end win video [%s] will use this file\n", - video.c_str()); - - break; - } - } - if (battleEndWinVideoFilename == "") { - battleEndWinVideoPath = data_path + CORE_MENU_VIDEOS_PATH - + "battle_end_win.*"; - battleEndWinVideos.clear(); - findAll(battleEndWinVideoPath, battleEndWinVideos, false, false); - for (int i = 0; i < (int)battleEndWinVideos.size(); ++i) { - string video = data_path + CORE_MENU_VIDEOS_PATH - + battleEndWinVideos[i]; - if (SystemFlags::VERBOSE_MODE_ENABLED) - printf("Checking if battle end win video [%s] exists\n", - video.c_str()); - - if (fileExists(video)) { - battleEndWinVideoFilename = video; - if (SystemFlags::VERBOSE_MODE_ENABLED) - printf( - "FOUND battle end video win [%s] will use this file\n", - video.c_str()); - - break; - } - } - } - } - battleEndWinMusicFilename = config.getString("BattleEndWinMusicFilename", - ""); - if (battleEndWinMusicFilename == "") { - string battleEndWinPath = getGameCustomCoreDataPath(data_path, "") - + CORE_MENU_MUSIC_PATH + "battle_end_win.*"; - vector battleEndWinMusic; - findAll(battleEndWinPath, battleEndWinMusic, false, false); - for (int i = 0; i < (int)battleEndWinMusic.size(); ++i) { - string music = getGameCustomCoreDataPath(data_path, "") - + CORE_MENU_MUSIC_PATH + battleEndWinMusic[i]; - if (SystemFlags::VERBOSE_MODE_ENABLED) - printf("Checking if battle end win music [%s] exists\n", - music.c_str()); - - if (fileExists(music)) { - battleEndWinMusicFilename = music; - if (SystemFlags::VERBOSE_MODE_ENABLED) - printf( - "FOUND battle end win music [%s] will use this file\n", - music.c_str()); - - break; - } - } - if (battleEndWinMusicFilename == "") { - battleEndWinPath = data_path + CORE_MENU_MUSIC_PATH - + "battle_end_win.*"; - battleEndWinMusic.clear(); - findAll(battleEndWinPath, battleEndWinMusic, false, false); - for (int i = 0; i < (int)battleEndWinMusic.size(); ++i) { - string music = data_path + CORE_MENU_MUSIC_PATH - + battleEndWinMusic[i]; - if (SystemFlags::VERBOSE_MODE_ENABLED) - printf("Checking if battle end win music [%s] exists\n", - music.c_str()); - - if (fileExists(music)) { - battleEndWinMusicFilename = music; - if (SystemFlags::VERBOSE_MODE_ENABLED) - printf( - "FOUND battle end music win [%s] will use this file\n", - music.c_str()); - - break; - } - } - } - } - battleEndLoseVideoFilename = config.getString("BattleEndLoseVideoURL", ""); - battleEndLoseVideoFilenameFallback = config.getString( - "BattleEndLoseVideoURLFallback", ""); - if (battleEndLoseVideoFilename == "") { - string battleEndLoseVideoPath = getGameCustomCoreDataPath(data_path, "") - + CORE_MENU_VIDEOS_PATH + "battle_end_lose.*"; - vector battleEndLoseVideos; - findAll(battleEndLoseVideoPath, battleEndLoseVideos, false, false); - for (int i = 0; i < (int)battleEndLoseVideos.size(); ++i) { - string video = getGameCustomCoreDataPath(data_path, "") - + CORE_MENU_VIDEOS_PATH + battleEndLoseVideos[i]; - if (SystemFlags::VERBOSE_MODE_ENABLED) - printf("Checking if battle end lose video [%s] exists\n", - video.c_str()); - - if (fileExists(video)) { - battleEndLoseVideoFilename = video; - if (SystemFlags::VERBOSE_MODE_ENABLED) - printf( - "FOUND battle end lose video [%s] will use this file\n", - video.c_str()); - - break; - } - } - if (battleEndLoseVideoFilename == "") { - battleEndLoseVideoPath = data_path + CORE_MENU_VIDEOS_PATH - + "battle_end_lose.*"; - battleEndLoseVideos.clear(); - findAll(battleEndLoseVideoPath, battleEndLoseVideos, false, false); - for (int i = 0; i < (int)battleEndLoseVideos.size(); ++i) { - string video = data_path + CORE_MENU_VIDEOS_PATH - + battleEndLoseVideos[i]; - if (SystemFlags::VERBOSE_MODE_ENABLED) - printf("Checking if battle end lose video [%s] exists\n", - video.c_str()); - - if (fileExists(video)) { - battleEndLoseVideoFilename = video; - if (SystemFlags::VERBOSE_MODE_ENABLED) - printf( - "FOUND battle end video lose [%s] will use this file\n", - video.c_str()); - - break; - } - } - } - } - battleEndLoseMusicFilename = config.getString("BattleEndLoseMusicFilename", - ""); - if (battleEndLoseMusicFilename == "") { - string battleEndLosePath = getGameCustomCoreDataPath(data_path, "") - + CORE_MENU_MUSIC_PATH + "battle_end_lose.*"; - vector battleEndLoseMusic; - findAll(battleEndLosePath, battleEndLoseMusic, false, false); - for (int i = 0; i < (int)battleEndLoseMusic.size(); ++i) { - string music = getGameCustomCoreDataPath(data_path, "") - + CORE_MENU_MUSIC_PATH + battleEndLoseMusic[i]; - if (SystemFlags::VERBOSE_MODE_ENABLED) - printf("Checking if battle end lose music [%s] exists\n", - music.c_str()); - - if (fileExists(music)) { - battleEndLoseMusicFilename = music; - if (SystemFlags::VERBOSE_MODE_ENABLED) - printf( - "FOUND battle end lose music [%s] will use this file\n", - music.c_str()); - - break; - } - } - if (battleEndLoseMusicFilename == "") { - battleEndLosePath = data_path + CORE_MENU_MUSIC_PATH - + "battle_end_lose.*"; - battleEndLoseMusic.clear(); - findAll(battleEndLosePath, battleEndLoseMusic, false, false); - for (int i = 0; i < (int)battleEndLoseMusic.size(); ++i) { - string music = data_path + CORE_MENU_MUSIC_PATH - + battleEndLoseMusic[i]; - if (SystemFlags::VERBOSE_MODE_ENABLED) - printf("Checking if battle end lose music [%s] exists\n", - music.c_str()); - - if (fileExists(music)) { - battleEndLoseMusicFilename = music; - if (SystemFlags::VERBOSE_MODE_ENABLED) - printf( - "FOUND battle end music lose [%s] will use this file\n", - music.c_str()); - - break; - } - } - } - } + Config &config = Config::getInstance(); + + battleEndWinVideoFilename = config.getString("BattleEndWinVideoURL", ""); + battleEndWinVideoFilenameFallback = + config.getString("BattleEndWinVideoURLFallback", ""); + if (battleEndWinVideoFilename == "") { + string battleEndWinVideoPath = getGameCustomCoreDataPath(data_path, "") + + CORE_MENU_VIDEOS_PATH + "battle_end_win.*"; + vector battleEndWinVideos; + findAll(battleEndWinVideoPath, battleEndWinVideos, false, false); + for (int i = 0; i < (int)battleEndWinVideos.size(); ++i) { + string video = getGameCustomCoreDataPath(data_path, "") + + CORE_MENU_VIDEOS_PATH + battleEndWinVideos[i]; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Checking if battle end win video [%s] exists\n", video.c_str()); + + if (fileExists(video)) { + battleEndWinVideoFilename = video; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("FOUND battle end win video [%s] will use this file\n", + video.c_str()); + + break; + } + } + if (battleEndWinVideoFilename == "") { + battleEndWinVideoPath = + data_path + CORE_MENU_VIDEOS_PATH + "battle_end_win.*"; + battleEndWinVideos.clear(); + findAll(battleEndWinVideoPath, battleEndWinVideos, false, false); + for (int i = 0; i < (int)battleEndWinVideos.size(); ++i) { + string video = + data_path + CORE_MENU_VIDEOS_PATH + battleEndWinVideos[i]; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Checking if battle end win video [%s] exists\n", + video.c_str()); + + if (fileExists(video)) { + battleEndWinVideoFilename = video; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("FOUND battle end video win [%s] will use this file\n", + video.c_str()); + + break; + } + } + } + } + battleEndWinMusicFilename = config.getString("BattleEndWinMusicFilename", ""); + if (battleEndWinMusicFilename == "") { + string battleEndWinPath = getGameCustomCoreDataPath(data_path, "") + + CORE_MENU_MUSIC_PATH + "battle_end_win.*"; + vector battleEndWinMusic; + findAll(battleEndWinPath, battleEndWinMusic, false, false); + for (int i = 0; i < (int)battleEndWinMusic.size(); ++i) { + string music = getGameCustomCoreDataPath(data_path, "") + + CORE_MENU_MUSIC_PATH + battleEndWinMusic[i]; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Checking if battle end win music [%s] exists\n", music.c_str()); + + if (fileExists(music)) { + battleEndWinMusicFilename = music; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("FOUND battle end win music [%s] will use this file\n", + music.c_str()); + + break; + } + } + if (battleEndWinMusicFilename == "") { + battleEndWinPath = data_path + CORE_MENU_MUSIC_PATH + "battle_end_win.*"; + battleEndWinMusic.clear(); + findAll(battleEndWinPath, battleEndWinMusic, false, false); + for (int i = 0; i < (int)battleEndWinMusic.size(); ++i) { + string music = data_path + CORE_MENU_MUSIC_PATH + battleEndWinMusic[i]; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Checking if battle end win music [%s] exists\n", + music.c_str()); + + if (fileExists(music)) { + battleEndWinMusicFilename = music; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("FOUND battle end music win [%s] will use this file\n", + music.c_str()); + + break; + } + } + } + } + battleEndLoseVideoFilename = config.getString("BattleEndLoseVideoURL", ""); + battleEndLoseVideoFilenameFallback = + config.getString("BattleEndLoseVideoURLFallback", ""); + if (battleEndLoseVideoFilename == "") { + string battleEndLoseVideoPath = getGameCustomCoreDataPath(data_path, "") + + CORE_MENU_VIDEOS_PATH + "battle_end_lose.*"; + vector battleEndLoseVideos; + findAll(battleEndLoseVideoPath, battleEndLoseVideos, false, false); + for (int i = 0; i < (int)battleEndLoseVideos.size(); ++i) { + string video = getGameCustomCoreDataPath(data_path, "") + + CORE_MENU_VIDEOS_PATH + battleEndLoseVideos[i]; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Checking if battle end lose video [%s] exists\n", + video.c_str()); + + if (fileExists(video)) { + battleEndLoseVideoFilename = video; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("FOUND battle end lose video [%s] will use this file\n", + video.c_str()); + + break; + } + } + if (battleEndLoseVideoFilename == "") { + battleEndLoseVideoPath = + data_path + CORE_MENU_VIDEOS_PATH + "battle_end_lose.*"; + battleEndLoseVideos.clear(); + findAll(battleEndLoseVideoPath, battleEndLoseVideos, false, false); + for (int i = 0; i < (int)battleEndLoseVideos.size(); ++i) { + string video = + data_path + CORE_MENU_VIDEOS_PATH + battleEndLoseVideos[i]; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Checking if battle end lose video [%s] exists\n", + video.c_str()); + + if (fileExists(video)) { + battleEndLoseVideoFilename = video; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("FOUND battle end video lose [%s] will use this file\n", + video.c_str()); + + break; + } + } + } + } + battleEndLoseMusicFilename = + config.getString("BattleEndLoseMusicFilename", ""); + if (battleEndLoseMusicFilename == "") { + string battleEndLosePath = getGameCustomCoreDataPath(data_path, "") + + CORE_MENU_MUSIC_PATH + "battle_end_lose.*"; + vector battleEndLoseMusic; + findAll(battleEndLosePath, battleEndLoseMusic, false, false); + for (int i = 0; i < (int)battleEndLoseMusic.size(); ++i) { + string music = getGameCustomCoreDataPath(data_path, "") + + CORE_MENU_MUSIC_PATH + battleEndLoseMusic[i]; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Checking if battle end lose music [%s] exists\n", + music.c_str()); + + if (fileExists(music)) { + battleEndLoseMusicFilename = music; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("FOUND battle end lose music [%s] will use this file\n", + music.c_str()); + + break; + } + } + if (battleEndLoseMusicFilename == "") { + battleEndLosePath = + data_path + CORE_MENU_MUSIC_PATH + "battle_end_lose.*"; + battleEndLoseMusic.clear(); + findAll(battleEndLosePath, battleEndLoseMusic, false, false); + for (int i = 0; i < (int)battleEndLoseMusic.size(); ++i) { + string music = data_path + CORE_MENU_MUSIC_PATH + battleEndLoseMusic[i]; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Checking if battle end lose music [%s] exists\n", + music.c_str()); + + if (fileExists(music)) { + battleEndLoseMusicFilename = music; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("FOUND battle end music lose [%s] will use this file\n", + music.c_str()); + + break; + } + } + } + } } void CoreData::load() { - string data_path = CoreData::getDataPath(); + string data_path = CoreData::getDataPath(); - Logger::getInstance().add(Lang::getInstance().getString("LogScreenCoreDataLoading","",true)); + Logger::getInstance().add( + Lang::getInstance().getString("LogScreenCoreDataLoading", "", true)); - // textures - loadTextures(data_path); + // textures + loadTextures(data_path); - // fonts - loadFonts(); + // fonts + loadFonts(); - // sounds - loadSounds(data_path); + // sounds + loadSounds(data_path); - // music - loadMusic(data_path); + // music + loadMusic(data_path); - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && - Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == true) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && + Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == true) { - loadIntroMedia(data_path); + loadIntroMedia(data_path); - loadMainMenuMedia(data_path); + loadMainMenuMedia(data_path); - loadBattleEndMedia(data_path); - } + loadBattleEndMedia(data_path); + } } bool CoreData::hasIntroVideoFilename() const { - bool result = (introVideoFilename != ""); - return result; + bool result = (introVideoFilename != ""); + return result; } bool CoreData::hasMainMenuVideoFilename() const { - bool result = (mainMenuVideoFilename != ""); - return result; + bool result = (mainMenuVideoFilename != ""); + return result; } -//bool CoreData::hasBattleEndVideoFilename(bool won) const { +// bool CoreData::hasBattleEndVideoFilename(bool won) const { // bool result = false; // if(won == true) { // result =(battleEndWinVideoFilename != ""); @@ -1152,396 +1115,613 @@ bool CoreData::hasMainMenuVideoFilename() const { // result =(battleEndLoseVideoFilename != ""); // } // return result; -//} - -void CoreData::registerFontChangedCallback(std::string entityName, FontChangedCallbackInterface *cb) { - if(entityName == "") { - printf("Register Font Callback detected a blank entityName!\n"); - throw megaglest_runtime_error("Register Font Callback detected a blank entityName!"); - } - if (entityName != "") { - registeredFontChangedCallbacks[entityName].push_back(cb); - } +// } + +void CoreData::registerFontChangedCallback(std::string entityName, + FontChangedCallbackInterface *cb) { + if (entityName == "") { + printf("Register Font Callback detected a blank entityName!\n"); + throw megaglest_runtime_error( + "Register Font Callback detected a blank entityName!"); + } + if (entityName != "") { + registeredFontChangedCallbacks[entityName].push_back(cb); + } } void CoreData::unRegisterFontChangedCallback(std::string entityName) { - if (entityName == "") { - printf("UnRegister Font Callback detected a blank entityName!\n"); - throw megaglest_runtime_error("UnRegister Font Callback detected a blank entityName!"); - } - if(entityName != "") { - registeredFontChangedCallbacks.erase(entityName); - } -} -void CoreData::triggerFontChangedCallbacks(std::string fontUniqueId, Font *font) { - for (std::map >::const_iterator iterMap = - registeredFontChangedCallbacks.begin(); - iterMap != registeredFontChangedCallbacks.end(); ++iterMap) { - for (unsigned int index = 0; index < iterMap->second.size(); ++index) { - //printf("Font Callback detected calling: Control [%s] for Font: [%s] value [%p]\n",iterMap->first.c_str(),fontUniqueId.c_str(),font); - FontChangedCallbackInterface *cb = iterMap->second[index]; - cb->FontChangedCallback(fontUniqueId, font); - } - } + if (entityName == "") { + printf("UnRegister Font Callback detected a blank entityName!\n"); + throw megaglest_runtime_error( + "UnRegister Font Callback detected a blank entityName!"); + } + if (entityName != "") { + registeredFontChangedCallbacks.erase(entityName); + } +} +void CoreData::triggerFontChangedCallbacks(std::string fontUniqueId, + Font *font) { + for (std::map>::const_iterator + iterMap = registeredFontChangedCallbacks.begin(); + iterMap != registeredFontChangedCallbacks.end(); ++iterMap) { + for (unsigned int index = 0; index < iterMap->second.size(); ++index) { + // printf("Font Callback detected calling: Control [%s] for Font: [%s] + // value [%p]\n",iterMap->first.c_str(),fontUniqueId.c_str(),font); + FontChangedCallbackInterface *cb = iterMap->second[index]; + cb->FontChangedCallback(fontUniqueId, font); + } + } } void CoreData::loadFonts() { - Lang &lang= Lang::getInstance(); - - //display font - Config &config= Config::getInstance(); - - string displayFontNamePrefix = config.getString("FontDisplayPrefix"); - string displayFontNamePostfix = config.getString("FontDisplayPostfix"); - int displayFontSize = computeFontSize(config.getInt("FontDisplayBaseSize")); - - if(lang.hasString("FontDisplayPrefix") == true) { - displayFontNamePrefix = lang.getString("FontDisplayPrefix"); - } - if(lang.hasString("FontDisplayPostfix") == true) { - displayFontNamePostfix = lang.getString("FontDisplayPostfix"); - } - if(lang.hasString("FontDisplayBaseSize") == true) { - displayFontSize = computeFontSize(strToInt(lang.getString("FontDisplayBaseSize"))); - } - string displayFontName = displayFontNamePrefix + intToStr(displayFontSize) + displayFontNamePostfix; - - displayFont = loadFont(displayFont, displayFontName, displayFontSize, "FontDisplay", "FontDisplayFamily", "displayFont"); - displayFont3D = loadFont(displayFont3D, displayFontName, displayFontSize, "FontDisplay", "FontDisplayFamily", "displayFont3D"); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] displayFontName = [%s] displayFontSize = %d\n",__FILE__,__FUNCTION__,__LINE__,displayFontName.c_str(),displayFontSize); - - //menu fonts - string displayFontNameSmallPrefix = config.getString("FontDisplayPrefix"); - string displayFontNameSmallPostfix = config.getString("FontDisplayPostfix"); - int displayFontNameSmallSize = computeFontSize(config.getInt("FontDisplaySmallBaseSize")); - - if(lang.hasString("FontDisplayPrefix") == true) { - displayFontNameSmallPrefix = lang.getString("FontDisplayPrefix"); - } - if(lang.hasString("FontDisplayPostfix") == true) { - displayFontNameSmallPostfix = lang.getString("FontDisplayPostfix"); - } - if(lang.hasString("FontDisplaySmallBaseSize") == true) { - displayFontNameSmallSize = computeFontSize(strToInt(lang.getString("FontDisplaySmallBaseSize"))); - } - string displayFontNameSmall = displayFontNameSmallPrefix + intToStr(displayFontNameSmallSize) + displayFontNameSmallPostfix; - - displayFontSmall = loadFont(displayFontSmall, displayFontNameSmall, displayFontNameSmallSize, "FontSmallDisplay", "FontSmallDisplayFamily", "displayFontSmall"); - displayFontSmall3D = loadFont(displayFontSmall3D, displayFontNameSmall, displayFontNameSmallSize, "FontSmallDisplay", "FontSmallDisplayFamily", "displayFontSmall3D"); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] displayFontSmallName = [%s] displayFontSmallNameSize = %d\n",__FILE__,__FUNCTION__,__LINE__,displayFontNameSmall.c_str(),displayFontNameSmallSize); - - string menuFontNameNormalPrefix = config.getString("FontMenuNormalPrefix"); - string menuFontNameNormalPostfix = config.getString("FontMenuNormalPostfix"); - int menuFontNameNormalSize = computeFontSize(config.getInt("FontMenuNormalBaseSize")); - if(lang.hasString("FontMenuNormalPrefix") == true) { - menuFontNameNormalPrefix = lang.getString("FontMenuNormalPrefix"); - } - if(lang.hasString("FontMenuNormalPostfix") == true) { - menuFontNameNormalPostfix = lang.getString("FontMenuNormalPostfix"); - } - if(lang.hasString("FontMenuNormalBaseSize") == true) { - menuFontNameNormalSize = computeFontSize(strToInt(lang.getString("FontMenuNormalBaseSize"))); - } - string menuFontNameNormal= menuFontNameNormalPrefix + intToStr(menuFontNameNormalSize) + menuFontNameNormalPostfix; - - menuFontNormal = loadFont(menuFontNormal, menuFontNameNormal, menuFontNameNormalSize, "FontMenuNormal", "FontMenuNormalFamily", "menuFontNormal"); - menuFontNormal3D = loadFont(menuFontNormal3D, menuFontNameNormal, menuFontNameNormalSize, "FontMenuNormal", "FontMenuNormalFamily", "menuFontNormal3D"); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] menuFontNormalName = [%s] menuFontNormalNameSize = %d\n",__FILE__,__FUNCTION__,__LINE__,menuFontNameNormal.c_str(),menuFontNameNormalSize); - - string menuFontNameBigPrefix = config.getString("FontMenuBigPrefix"); - string menuFontNameBigPostfix = config.getString("FontMenuBigPostfix"); - int menuFontNameBigSize = computeFontSize(config.getInt("FontMenuBigBaseSize")); - - if(lang.hasString("FontMenuBigPrefix") == true) { - menuFontNameBigPrefix = lang.getString("FontMenuBigPrefix"); - } - if(lang.hasString("FontMenuBigPostfix") == true) { - menuFontNameBigPostfix = lang.getString("FontMenuBigPostfix"); - } - if(lang.hasString("FontMenuBigBaseSize") == true) { - menuFontNameBigSize = computeFontSize(strToInt(lang.getString("FontMenuBigBaseSize"))); - } - string menuFontNameBig= menuFontNameBigPrefix+intToStr(menuFontNameBigSize)+menuFontNameBigPostfix; - - menuFontBig = loadFont(menuFontBig, menuFontNameBig, menuFontNameBigSize, "FontMenuBig", "FontMenuBigFamily", "menuFontBig"); - menuFontBig3D = loadFont(menuFontBig3D, menuFontNameBig, menuFontNameBigSize, "FontMenuBig", "FontMenuBigFamily", "menuFontBig3D"); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] menuFontNameBig = [%s] menuFontNameBigSize = %d\n",__FILE__,__FUNCTION__,__LINE__,menuFontNameBig.c_str(),menuFontNameBigSize); - - string menuFontNameVeryBigPrefix = config.getString("FontMenuBigPrefix"); - string menuFontNameVeryBigPostfix = config.getString("FontMenuBigPostfix"); - int menuFontNameVeryBigSize = computeFontSize(config.getInt("FontMenuVeryBigBaseSize")); - - if(lang.hasString("FontMenuBigPrefix") == true) { - menuFontNameVeryBigPrefix = lang.getString("FontMenuBigPrefix"); - } - if(lang.hasString("FontMenuBigPostfix") == true) { - menuFontNameVeryBigPostfix = lang.getString("FontMenuBigPostfix"); - } - if(lang.hasString("FontMenuVeryBigBaseSize") == true) { - menuFontNameVeryBigSize = computeFontSize(strToInt(lang.getString("FontMenuVeryBigBaseSize"))); - } - string menuFontNameVeryBig= menuFontNameVeryBigPrefix + intToStr(menuFontNameVeryBigSize) + menuFontNameVeryBigPostfix; - - menuFontVeryBig = loadFont(menuFontVeryBig, menuFontNameVeryBig, menuFontNameVeryBigSize, "FontMenuVeryBig", "FontMenuVeryBigFamily", "menuFontVeryBig"); - menuFontVeryBig3D = loadFont(menuFontVeryBig3D, menuFontNameVeryBig, menuFontNameVeryBigSize, "FontMenuVeryBig", "FontMenuVeryBigFamily", "menuFontVeryBig3D"); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] menuFontNameVeryBig = [%s] menuFontNameVeryBigSize = %d\n",__FILE__,__FUNCTION__,__LINE__,menuFontNameVeryBig.c_str(),menuFontNameVeryBigSize); - - //console font - string consoleFontNamePrefix = config.getString("FontConsolePrefix"); - string consoleFontNamePostfix = config.getString("FontConsolePostfix"); - int consoleFontNameSize = computeFontSize(config.getInt("FontConsoleBaseSize")); - - if(lang.hasString("FontConsolePrefix") == true) { - consoleFontNamePrefix = lang.getString("FontConsolePrefix"); - } - if(lang.hasString("FontConsolePostfix") == true) { - consoleFontNamePostfix = lang.getString("FontConsolePostfix"); - } - if(lang.hasString("FontConsoleBaseSize") == true) { - consoleFontNameSize = computeFontSize(strToInt(lang.getString("FontConsoleBaseSize"))); - } - string consoleFontName= consoleFontNamePrefix + intToStr(consoleFontNameSize) + consoleFontNamePostfix; - - consoleFont = loadFont(consoleFont, consoleFontName, consoleFontNameSize, "FontConsole", "FontConsoleFamily", "consoleFont"); - consoleFont3D = loadFont(consoleFont3D, consoleFontName, consoleFontNameSize, "FontConsole", "FontConsoleFamily", "consoleFont3D"); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] consoleFontName = [%s] consoleFontNameSize = %d\n",__FILE__,__FUNCTION__,__LINE__,consoleFontName.c_str(),consoleFontNameSize); -} - - -template T * CoreData::loadFont(Font *menuFont, string menuFontName, - int menuFontNameSize, string fontType, string fontTypeFamily, string fontUniqueKey) { - Renderer &renderer= Renderer::getInstance(); - if(menuFont) { - string fontUniqueId = menuFont->getFontUniqueId(); - renderer.endFont(menuFont, rsGlobal); - menuFont = NULL; - triggerFontChangedCallbacks(fontUniqueId, menuFont); - } - if(Renderer::renderText3DEnabled == false) { - menuFont = renderer.newFont(rsGlobal); - } - else { - menuFont = renderer.newFont3D(rsGlobal); - } - if(menuFont) { - Config &config= Config::getInstance(); - menuFont->setType(menuFontName,config.getString(fontType,""),config.getString(fontTypeFamily,"")); - menuFont->setSize(menuFontNameSize); - menuFont->setWidth(Font::wBold); - menuFont->setFontUniqueId(fontUniqueKey); - triggerFontChangedCallbacks(menuFont->getFontUniqueId(), menuFont); - } - return (T *)menuFont; + Lang &lang = Lang::getInstance(); + + // display font + Config &config = Config::getInstance(); + + string displayFontNamePrefix = config.getString("FontDisplayPrefix"); + string displayFontNamePostfix = config.getString("FontDisplayPostfix"); + int displayFontSize = computeFontSize(config.getInt("FontDisplayBaseSize")); + + if (lang.hasString("FontDisplayPrefix") == true) { + displayFontNamePrefix = lang.getString("FontDisplayPrefix"); + } + if (lang.hasString("FontDisplayPostfix") == true) { + displayFontNamePostfix = lang.getString("FontDisplayPostfix"); + } + if (lang.hasString("FontDisplayBaseSize") == true) { + displayFontSize = + computeFontSize(strToInt(lang.getString("FontDisplayBaseSize"))); + } + string displayFontName = displayFontNamePrefix + intToStr(displayFontSize) + + displayFontNamePostfix; + + displayFont = + loadFont(displayFont, displayFontName, displayFontSize, + "FontDisplay", "FontDisplayFamily", "displayFont"); + displayFont3D = + loadFont(displayFont3D, displayFontName, displayFontSize, + "FontDisplay", "FontDisplayFamily", "displayFont3D"); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] displayFontName = [%s] displayFontSize = %d\n", + __FILE__, __FUNCTION__, __LINE__, displayFontName.c_str(), + displayFontSize); + + // menu fonts + string displayFontNameSmallPrefix = config.getString("FontDisplayPrefix"); + string displayFontNameSmallPostfix = config.getString("FontDisplayPostfix"); + int displayFontNameSmallSize = + computeFontSize(config.getInt("FontDisplaySmallBaseSize")); + + if (lang.hasString("FontDisplayPrefix") == true) { + displayFontNameSmallPrefix = lang.getString("FontDisplayPrefix"); + } + if (lang.hasString("FontDisplayPostfix") == true) { + displayFontNameSmallPostfix = lang.getString("FontDisplayPostfix"); + } + if (lang.hasString("FontDisplaySmallBaseSize") == true) { + displayFontNameSmallSize = + computeFontSize(strToInt(lang.getString("FontDisplaySmallBaseSize"))); + } + string displayFontNameSmall = displayFontNameSmallPrefix + + intToStr(displayFontNameSmallSize) + + displayFontNameSmallPostfix; + + displayFontSmall = loadFont( + displayFontSmall, displayFontNameSmall, displayFontNameSmallSize, + "FontSmallDisplay", "FontSmallDisplayFamily", "displayFontSmall"); + displayFontSmall3D = loadFont( + displayFontSmall3D, displayFontNameSmall, displayFontNameSmallSize, + "FontSmallDisplay", "FontSmallDisplayFamily", "displayFontSmall3D"); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] displayFontSmallName = [%s] " + "displayFontSmallNameSize = %d\n", + __FILE__, __FUNCTION__, __LINE__, + displayFontNameSmall.c_str(), + displayFontNameSmallSize); + + string menuFontNameNormalPrefix = config.getString("FontMenuNormalPrefix"); + string menuFontNameNormalPostfix = config.getString("FontMenuNormalPostfix"); + int menuFontNameNormalSize = + computeFontSize(config.getInt("FontMenuNormalBaseSize")); + if (lang.hasString("FontMenuNormalPrefix") == true) { + menuFontNameNormalPrefix = lang.getString("FontMenuNormalPrefix"); + } + if (lang.hasString("FontMenuNormalPostfix") == true) { + menuFontNameNormalPostfix = lang.getString("FontMenuNormalPostfix"); + } + if (lang.hasString("FontMenuNormalBaseSize") == true) { + menuFontNameNormalSize = + computeFontSize(strToInt(lang.getString("FontMenuNormalBaseSize"))); + } + string menuFontNameNormal = menuFontNameNormalPrefix + + intToStr(menuFontNameNormalSize) + + menuFontNameNormalPostfix; + + menuFontNormal = loadFont(menuFontNormal, menuFontNameNormal, + menuFontNameNormalSize, "FontMenuNormal", + "FontMenuNormalFamily", "menuFontNormal"); + menuFontNormal3D = loadFont( + menuFontNormal3D, menuFontNameNormal, menuFontNameNormalSize, + "FontMenuNormal", "FontMenuNormalFamily", "menuFontNormal3D"); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] menuFontNormalName = [%s] " + "menuFontNormalNameSize = %d\n", + __FILE__, __FUNCTION__, __LINE__, + menuFontNameNormal.c_str(), + menuFontNameNormalSize); + + string menuFontNameBigPrefix = config.getString("FontMenuBigPrefix"); + string menuFontNameBigPostfix = config.getString("FontMenuBigPostfix"); + int menuFontNameBigSize = + computeFontSize(config.getInt("FontMenuBigBaseSize")); + + if (lang.hasString("FontMenuBigPrefix") == true) { + menuFontNameBigPrefix = lang.getString("FontMenuBigPrefix"); + } + if (lang.hasString("FontMenuBigPostfix") == true) { + menuFontNameBigPostfix = lang.getString("FontMenuBigPostfix"); + } + if (lang.hasString("FontMenuBigBaseSize") == true) { + menuFontNameBigSize = + computeFontSize(strToInt(lang.getString("FontMenuBigBaseSize"))); + } + string menuFontNameBig = menuFontNameBigPrefix + + intToStr(menuFontNameBigSize) + + menuFontNameBigPostfix; + + menuFontBig = + loadFont(menuFontBig, menuFontNameBig, menuFontNameBigSize, + "FontMenuBig", "FontMenuBigFamily", "menuFontBig"); + menuFontBig3D = + loadFont(menuFontBig3D, menuFontNameBig, menuFontNameBigSize, + "FontMenuBig", "FontMenuBigFamily", "menuFontBig3D"); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] menuFontNameBig = [%s] " + "menuFontNameBigSize = %d\n", + __FILE__, __FUNCTION__, __LINE__, + menuFontNameBig.c_str(), menuFontNameBigSize); + + string menuFontNameVeryBigPrefix = config.getString("FontMenuBigPrefix"); + string menuFontNameVeryBigPostfix = config.getString("FontMenuBigPostfix"); + int menuFontNameVeryBigSize = + computeFontSize(config.getInt("FontMenuVeryBigBaseSize")); + + if (lang.hasString("FontMenuBigPrefix") == true) { + menuFontNameVeryBigPrefix = lang.getString("FontMenuBigPrefix"); + } + if (lang.hasString("FontMenuBigPostfix") == true) { + menuFontNameVeryBigPostfix = lang.getString("FontMenuBigPostfix"); + } + if (lang.hasString("FontMenuVeryBigBaseSize") == true) { + menuFontNameVeryBigSize = + computeFontSize(strToInt(lang.getString("FontMenuVeryBigBaseSize"))); + } + string menuFontNameVeryBig = menuFontNameVeryBigPrefix + + intToStr(menuFontNameVeryBigSize) + + menuFontNameVeryBigPostfix; + + menuFontVeryBig = loadFont( + menuFontVeryBig, menuFontNameVeryBig, menuFontNameVeryBigSize, + "FontMenuVeryBig", "FontMenuVeryBigFamily", "menuFontVeryBig"); + menuFontVeryBig3D = loadFont( + menuFontVeryBig3D, menuFontNameVeryBig, menuFontNameVeryBigSize, + "FontMenuVeryBig", "FontMenuVeryBigFamily", "menuFontVeryBig3D"); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] menuFontNameVeryBig = [%s] " + "menuFontNameVeryBigSize = %d\n", + __FILE__, __FUNCTION__, __LINE__, + menuFontNameVeryBig.c_str(), + menuFontNameVeryBigSize); + + // console font + string consoleFontNamePrefix = config.getString("FontConsolePrefix"); + string consoleFontNamePostfix = config.getString("FontConsolePostfix"); + int consoleFontNameSize = + computeFontSize(config.getInt("FontConsoleBaseSize")); + + if (lang.hasString("FontConsolePrefix") == true) { + consoleFontNamePrefix = lang.getString("FontConsolePrefix"); + } + if (lang.hasString("FontConsolePostfix") == true) { + consoleFontNamePostfix = lang.getString("FontConsolePostfix"); + } + if (lang.hasString("FontConsoleBaseSize") == true) { + consoleFontNameSize = + computeFontSize(strToInt(lang.getString("FontConsoleBaseSize"))); + } + string consoleFontName = consoleFontNamePrefix + + intToStr(consoleFontNameSize) + + consoleFontNamePostfix; + + consoleFont = + loadFont(consoleFont, consoleFontName, consoleFontNameSize, + "FontConsole", "FontConsoleFamily", "consoleFont"); + consoleFont3D = + loadFont(consoleFont3D, consoleFontName, consoleFontNameSize, + "FontConsole", "FontConsoleFamily", "consoleFont3D"); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] consoleFontName = [%s] " + "consoleFontNameSize = %d\n", + __FILE__, __FUNCTION__, __LINE__, + consoleFontName.c_str(), consoleFontNameSize); +} + +template +T *CoreData::loadFont(Font *menuFont, string menuFontName, int menuFontNameSize, + string fontType, string fontTypeFamily, + string fontUniqueKey) { + Renderer &renderer = Renderer::getInstance(); + if (menuFont) { + string fontUniqueId = menuFont->getFontUniqueId(); + renderer.endFont(menuFont, rsGlobal); + menuFont = NULL; + triggerFontChangedCallbacks(fontUniqueId, menuFont); + } + if (Renderer::renderText3DEnabled == false) { + menuFont = renderer.newFont(rsGlobal); + } else { + menuFont = renderer.newFont3D(rsGlobal); + } + if (menuFont) { + Config &config = Config::getInstance(); + menuFont->setType(menuFontName, config.getString(fontType, ""), + config.getString(fontTypeFamily, "")); + menuFont->setSize(menuFontNameSize); + menuFont->setWidth(Font::wBold); + menuFont->setFontUniqueId(fontUniqueKey); + triggerFontChangedCallbacks(menuFont->getFontUniqueId(), menuFont); + } + return (T *)menuFont; } int CoreData::computeFontSize(int size) { - int rs = size; - Config &config= Config::getInstance(); - if(Font::forceLegacyFonts == true) { - int screenH = config.getInt("ScreenHeight"); - rs = size * screenH / 1024; - } - //FontSizeAdjustment - rs += config.getInt("FontSizeAdjustment"); - if(Font::forceLegacyFonts == false) { - rs += Font::baseSize; //basesize only for new font system - } - if(Font::forceLegacyFonts == true) { - if(rs < 10) { - rs= 10; - } - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] fontsize original %d calculated:%d \n",__FILE__,__FUNCTION__,__LINE__,size,rs); - return rs; -} - -void CoreData::saveGameSettingsToFile(std::string fileName, GameSettings *gameSettings, int advancedIndex) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); - - Config &config = Config::getInstance(); - string saveSetupDir = config.getString("UserData_Root",""); - if(saveSetupDir != "") { - endPathWithSlash(saveSetupDir); + int rs = size; + Config &config = Config::getInstance(); + if (Font::forceLegacyFonts == true) { + int screenH = config.getInt("ScreenHeight"); + rs = size * screenH / 1024; + } + // FontSizeAdjustment + rs += config.getInt("FontSizeAdjustment"); + if (Font::forceLegacyFonts == false) { + rs += Font::baseSize; // basesize only for new font system + } + if (Font::forceLegacyFonts == true) { + if (rs < 10) { + rs = 10; } - fileName = saveSetupDir + fileName; - // create path if non existant - createDirectoryPaths(extractDirectoryPathFromFile(fileName)); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] fileName = [%s]\n",__FILE__,__FUNCTION__,__LINE__,fileName.c_str()); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] fontsize original %d calculated:%d \n", + __FILE__, __FUNCTION__, __LINE__, size, rs); + return rs; +} + +void CoreData::saveGameSettingsToFile(std::string fileName, + GameSettings *gameSettings, + int advancedIndex) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] Line: %d\n", + __FILE__, __FUNCTION__, __LINE__); + + Config &config = Config::getInstance(); + string saveSetupDir = config.getString("UserData_Root", ""); + if (saveSetupDir != "") { + endPathWithSlash(saveSetupDir); + } + fileName = saveSetupDir + fileName; + // create path if non existant + createDirectoryPaths(extractDirectoryPathFromFile(fileName)); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] fileName = [%s]\n", __FILE__, + __FUNCTION__, __LINE__, fileName.c_str()); #if defined(WIN32) && !defined(__MINGW32__) - FILE *fp = _wfopen(utf8_decode(fileName).c_str(), L"w"); - std::ofstream saveGameFile(fp); + FILE *fp = _wfopen(utf8_decode(fileName).c_str(), L"w"); + std::ofstream saveGameFile(fp); #else - std::ofstream saveGameFile; - saveGameFile.open(fileName.c_str(), ios_base::out | ios_base::trunc); + std::ofstream saveGameFile; + saveGameFile.open(fileName.c_str(), ios_base::out | ios_base::trunc); #endif - saveGameFile << "Description=" << gameSettings->getDescription() << std::endl; - saveGameFile << "MapFilterIndex=" << Shared::PlatformByteOrder::toCommonEndian(gameSettings->getMapFilter()) << std::endl; - saveGameFile << "Map=" << gameSettings->getMap() << std::endl; - saveGameFile << "Tileset=" << gameSettings->getTileset() << std::endl; - saveGameFile << "TechTree=" << gameSettings->getTech() << std::endl; - saveGameFile << "DefaultUnits=" << Shared::PlatformByteOrder::toCommonEndian(gameSettings->getDefaultUnits()) << std::endl; - saveGameFile << "DefaultResources=" << Shared::PlatformByteOrder::toCommonEndian(gameSettings->getDefaultResources()) << std::endl; - saveGameFile << "DefaultVictoryConditions=" << Shared::PlatformByteOrder::toCommonEndian(gameSettings->getDefaultVictoryConditions()) << std::endl; - saveGameFile << "FogOfWar=" << Shared::PlatformByteOrder::toCommonEndian(gameSettings->getFogOfWar()) << std::endl; - saveGameFile << "AdvancedIndex=" << Shared::PlatformByteOrder::toCommonEndian(advancedIndex) << std::endl; - saveGameFile << "AllowObservers=" << Shared::PlatformByteOrder::toCommonEndian(gameSettings->getAllowObservers()) << std::endl; - saveGameFile << "FlagTypes1=" << Shared::PlatformByteOrder::toCommonEndian(gameSettings->getFlagTypes1()) << std::endl; - saveGameFile << "EnableObserverModeAtEndGame=" << Shared::PlatformByteOrder::toCommonEndian(gameSettings->getEnableObserverModeAtEndGame()) << std::endl; - saveGameFile << "AiAcceptSwitchTeamPercentChance=" << Shared::PlatformByteOrder::toCommonEndian(gameSettings->getAiAcceptSwitchTeamPercentChance()) << std::endl; - saveGameFile << "FallbackCpuMultiplier=" << Shared::PlatformByteOrder::toCommonEndian(gameSettings->getFallbackCpuMultiplier()) << std::endl; - saveGameFile << "PathFinderType=" << Shared::PlatformByteOrder::toCommonEndian(gameSettings->getPathFinderType()) << std::endl; - saveGameFile << "EnableServerControlledAI=" << Shared::PlatformByteOrder::toCommonEndian(gameSettings->getEnableServerControlledAI()) << std::endl; - saveGameFile << "NetworkFramePeriod=" << Shared::PlatformByteOrder::toCommonEndian(gameSettings->getNetworkFramePeriod()) << std::endl; - saveGameFile << "NetworkPauseGameForLaggedClients=" << Shared::PlatformByteOrder::toCommonEndian(gameSettings->getNetworkPauseGameForLaggedClients()) << std::endl; - - saveGameFile << "FactionThisFactionIndex=" << Shared::PlatformByteOrder::toCommonEndian(gameSettings->getThisFactionIndex()) << std::endl; - saveGameFile << "FactionCount=" << Shared::PlatformByteOrder::toCommonEndian(gameSettings->getFactionCount()) << std::endl; - - saveGameFile << "NetworkAllowNativeLanguageTechtree=" << Shared::PlatformByteOrder::toCommonEndian(gameSettings->getNetworkAllowNativeLanguageTechtree()) << std::endl; - - for(int i = 0; i < GameConstants::maxPlayers; ++i) { - int slotIndex = gameSettings->getStartLocationIndex(i); - - saveGameFile << "FactionControlForIndex" << Shared::PlatformByteOrder::toCommonEndian(slotIndex) << "=" << Shared::PlatformByteOrder::toCommonEndian(gameSettings->getFactionControl(i)) << std::endl; - saveGameFile << "ResourceMultiplierIndex" << Shared::PlatformByteOrder::toCommonEndian(slotIndex) << "=" << Shared::PlatformByteOrder::toCommonEndian(gameSettings->getResourceMultiplierIndex(i)) << std::endl; - saveGameFile << "FactionTeamForIndex" << Shared::PlatformByteOrder::toCommonEndian(slotIndex) << "=" << Shared::PlatformByteOrder::toCommonEndian(gameSettings->getTeam(i)) << std::endl; - saveGameFile << "FactionStartLocationForIndex" << Shared::PlatformByteOrder::toCommonEndian(slotIndex) << "=" << Shared::PlatformByteOrder::toCommonEndian(gameSettings->getStartLocationIndex(i)) << std::endl; - saveGameFile << "FactionTypeNameForIndex" << Shared::PlatformByteOrder::toCommonEndian(slotIndex) << "=" << gameSettings->getFactionTypeName(i) << std::endl; - saveGameFile << "FactionPlayerNameForIndex" << Shared::PlatformByteOrder::toCommonEndian(slotIndex) << "=" << gameSettings->getNetworkPlayerName(i) << std::endl; - - saveGameFile << "FactionPlayerUUIDForIndex" << Shared::PlatformByteOrder::toCommonEndian(slotIndex) << "=" << gameSettings->getNetworkPlayerUUID(i) << std::endl; - } + saveGameFile << "Description=" << gameSettings->getDescription() << std::endl; + saveGameFile << "MapFilterIndex=" + << Shared::PlatformByteOrder::toCommonEndian( + gameSettings->getMapFilter()) + << std::endl; + saveGameFile << "Map=" << gameSettings->getMap() << std::endl; + saveGameFile << "Tileset=" << gameSettings->getTileset() << std::endl; + saveGameFile << "TechTree=" << gameSettings->getTech() << std::endl; + saveGameFile << "DefaultUnits=" + << Shared::PlatformByteOrder::toCommonEndian( + gameSettings->getDefaultUnits()) + << std::endl; + saveGameFile << "DefaultResources=" + << Shared::PlatformByteOrder::toCommonEndian( + gameSettings->getDefaultResources()) + << std::endl; + saveGameFile << "DefaultVictoryConditions=" + << Shared::PlatformByteOrder::toCommonEndian( + gameSettings->getDefaultVictoryConditions()) + << std::endl; + saveGameFile << "FogOfWar=" + << Shared::PlatformByteOrder::toCommonEndian( + gameSettings->getFogOfWar()) + << std::endl; + saveGameFile << "AdvancedIndex=" + << Shared::PlatformByteOrder::toCommonEndian(advancedIndex) + << std::endl; + saveGameFile << "AllowObservers=" + << Shared::PlatformByteOrder::toCommonEndian( + gameSettings->getAllowObservers()) + << std::endl; + saveGameFile << "FlagTypes1=" + << Shared::PlatformByteOrder::toCommonEndian( + gameSettings->getFlagTypes1()) + << std::endl; + saveGameFile << "EnableObserverModeAtEndGame=" + << Shared::PlatformByteOrder::toCommonEndian( + gameSettings->getEnableObserverModeAtEndGame()) + << std::endl; + saveGameFile << "AiAcceptSwitchTeamPercentChance=" + << Shared::PlatformByteOrder::toCommonEndian( + gameSettings->getAiAcceptSwitchTeamPercentChance()) + << std::endl; + saveGameFile << "FallbackCpuMultiplier=" + << Shared::PlatformByteOrder::toCommonEndian( + gameSettings->getFallbackCpuMultiplier()) + << std::endl; + saveGameFile << "PathFinderType=" + << Shared::PlatformByteOrder::toCommonEndian( + gameSettings->getPathFinderType()) + << std::endl; + saveGameFile << "EnableServerControlledAI=" + << Shared::PlatformByteOrder::toCommonEndian( + gameSettings->getEnableServerControlledAI()) + << std::endl; + saveGameFile << "NetworkFramePeriod=" + << Shared::PlatformByteOrder::toCommonEndian( + gameSettings->getNetworkFramePeriod()) + << std::endl; + saveGameFile << "NetworkPauseGameForLaggedClients=" + << Shared::PlatformByteOrder::toCommonEndian( + gameSettings->getNetworkPauseGameForLaggedClients()) + << std::endl; + + saveGameFile << "FactionThisFactionIndex=" + << Shared::PlatformByteOrder::toCommonEndian( + gameSettings->getThisFactionIndex()) + << std::endl; + saveGameFile << "FactionCount=" + << Shared::PlatformByteOrder::toCommonEndian( + gameSettings->getFactionCount()) + << std::endl; + + saveGameFile << "NetworkAllowNativeLanguageTechtree=" + << Shared::PlatformByteOrder::toCommonEndian( + gameSettings->getNetworkAllowNativeLanguageTechtree()) + << std::endl; + + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + int slotIndex = gameSettings->getStartLocationIndex(i); + + saveGameFile << "FactionControlForIndex" + << Shared::PlatformByteOrder::toCommonEndian(slotIndex) << "=" + << Shared::PlatformByteOrder::toCommonEndian( + gameSettings->getFactionControl(i)) + << std::endl; + saveGameFile << "ResourceMultiplierIndex" + << Shared::PlatformByteOrder::toCommonEndian(slotIndex) << "=" + << Shared::PlatformByteOrder::toCommonEndian( + gameSettings->getResourceMultiplierIndex(i)) + << std::endl; + saveGameFile << "FactionTeamForIndex" + << Shared::PlatformByteOrder::toCommonEndian(slotIndex) << "=" + << Shared::PlatformByteOrder::toCommonEndian( + gameSettings->getTeam(i)) + << std::endl; + saveGameFile << "FactionStartLocationForIndex" + << Shared::PlatformByteOrder::toCommonEndian(slotIndex) << "=" + << Shared::PlatformByteOrder::toCommonEndian( + gameSettings->getStartLocationIndex(i)) + << std::endl; + saveGameFile << "FactionTypeNameForIndex" + << Shared::PlatformByteOrder::toCommonEndian(slotIndex) << "=" + << gameSettings->getFactionTypeName(i) << std::endl; + saveGameFile << "FactionPlayerNameForIndex" + << Shared::PlatformByteOrder::toCommonEndian(slotIndex) << "=" + << gameSettings->getNetworkPlayerName(i) << std::endl; + + saveGameFile << "FactionPlayerUUIDForIndex" + << Shared::PlatformByteOrder::toCommonEndian(slotIndex) << "=" + << gameSettings->getNetworkPlayerUUID(i) << std::endl; + } #if defined(WIN32) && !defined(__MINGW32__) - if(fp) fclose(fp); + if (fp) + fclose(fp); #endif - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] Line: %d\n", + __FILE__, __FUNCTION__, __LINE__); } -bool CoreData::loadGameSettingsFromFile(std::string fileName, GameSettings *gameSettings) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); +bool CoreData::loadGameSettingsFromFile(std::string fileName, + GameSettings *gameSettings) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] Line: %d\n", + __FILE__, __FUNCTION__, __LINE__); - bool fileWasFound = false; - Config &config = Config::getInstance(); - string saveSetupDir = config.getString("UserData_Root",""); - if(saveSetupDir != "") { - endPathWithSlash(saveSetupDir); - } + bool fileWasFound = false; + Config &config = Config::getInstance(); + string saveSetupDir = config.getString("UserData_Root", ""); + if (saveSetupDir != "") { + endPathWithSlash(saveSetupDir); + } - if(fileExists(saveSetupDir + fileName) == true) { - fileName = saveSetupDir + fileName; - fileWasFound = true; + if (fileExists(saveSetupDir + fileName) == true) { + fileName = saveSetupDir + fileName; + fileWasFound = true; + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] fileName = [%s]\n", __FILE__, + __FUNCTION__, __LINE__, fileName.c_str()); + + if (fileExists(fileName) == false) { + return false; + } + + fileWasFound = true; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] fileName = [%s]\n", __FILE__, + __FUNCTION__, __LINE__, fileName.c_str()); + + Properties properties; + properties.load(fileName); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] fileName = [%s]\n", __FILE__, + __FUNCTION__, __LINE__, fileName.c_str()); + + gameSettings->setMapFilter(properties.getInt("MapFilterIndex", "0")); + gameSettings->setDescription(properties.getString("Description")); + gameSettings->setMap(properties.getString("Map")); + gameSettings->setTileset(properties.getString("Tileset")); + gameSettings->setTech(properties.getString("TechTree")); + gameSettings->setDefaultUnits(properties.getBool("DefaultUnits")); + gameSettings->setDefaultResources(properties.getBool("DefaultResources")); + gameSettings->setDefaultVictoryConditions( + properties.getBool("DefaultVictoryConditions")); + gameSettings->setFogOfWar(properties.getBool("FogOfWar")); + // listBoxAdvanced.setSelectedItemIndex(properties.getInt("AdvancedIndex","0")); + + gameSettings->setAllowObservers( + properties.getBool("AllowObservers", "false")); + gameSettings->setFlagTypes1(properties.getInt("FlagTypes1", "0")); + + uint32 valueFlags1 = gameSettings->getFlagTypes1(); + if (Config::getInstance().getBool("EnableNetworkGameSynchChecks", "false") == + true) { + // printf("*WARNING* - EnableNetworkGameSynchChecks is enabled\n"); + + valueFlags1 |= ft1_network_synch_checks_verbose; + gameSettings->setFlagTypes1(valueFlags1); + + } else { + valueFlags1 &= ~ft1_network_synch_checks_verbose; + gameSettings->setFlagTypes1(valueFlags1); + } + if (Config::getInstance().getBool("EnableNetworkGameSynchMonitor", "false") == + true) { + // printf("*WARNING* - EnableNetworkGameSynchChecks is enabled\n"); + + valueFlags1 |= ft1_network_synch_checks; + gameSettings->setFlagTypes1(valueFlags1); + + } else { + valueFlags1 &= ~ft1_network_synch_checks; + gameSettings->setFlagTypes1(valueFlags1); + } + + gameSettings->setEnableObserverModeAtEndGame( + properties.getBool("EnableObserverModeAtEndGame")); + gameSettings->setAiAcceptSwitchTeamPercentChance( + properties.getInt("AiAcceptSwitchTeamPercentChance", "30")); + gameSettings->setFallbackCpuMultiplier( + properties.getInt("FallbackCpuMultiplier", "5")); + + gameSettings->setPathFinderType(static_cast( + properties.getInt("PathFinderType", intToStr(pfBasic).c_str()))); + gameSettings->setEnableServerControlledAI( + properties.getBool("EnableServerControlledAI", "true")); + gameSettings->setNetworkFramePeriod( + properties.getInt("NetworkFramePeriod", + intToStr(GameConstants::networkFramePeriod).c_str())); + gameSettings->setNetworkPauseGameForLaggedClients( + properties.getBool("NetworkPauseGameForLaggedClients", "false")); + + gameSettings->setThisFactionIndex( + properties.getInt("FactionThisFactionIndex")); + gameSettings->setFactionCount(properties.getInt("FactionCount")); + + if (properties.hasString("NetworkAllowNativeLanguageTechtree") == true) { + gameSettings->setNetworkAllowNativeLanguageTechtree( + properties.getBool("NetworkAllowNativeLanguageTechtree")); + } else { + gameSettings->setNetworkAllowNativeLanguageTechtree(false); + } + + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + gameSettings->setFactionControl( + i, (ControlType)properties.getInt(string("FactionControlForIndex") + + intToStr(i), + intToStr(ctClosed).c_str())); + + if (gameSettings->getFactionControl(i) == ctNetworkUnassigned) { + gameSettings->setFactionControl(i, ctNetwork); } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] fileName = [%s]\n",__FILE__,__FUNCTION__,__LINE__,fileName.c_str()); - - if(fileExists(fileName) == false) { - return false; + gameSettings->setResourceMultiplierIndex( + i, properties.getInt(string("ResourceMultiplierIndex") + intToStr(i), + "5")); + gameSettings->setTeam( + i, properties.getInt(string("FactionTeamForIndex") + intToStr(i), "0")); + gameSettings->setStartLocationIndex( + i, + properties.getInt(string("FactionStartLocationForIndex") + intToStr(i), + intToStr(i).c_str())); + gameSettings->setFactionTypeName( + i, properties.getString(string("FactionTypeNameForIndex") + intToStr(i), + "?")); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] i = %d, factionTypeName [%s]\n", __FILE__, + __FUNCTION__, __LINE__, i, + gameSettings->getFactionTypeName(i).c_str()); + + if (gameSettings->getFactionControl(i) == ctHuman) { + gameSettings->setNetworkPlayerName( + i, properties.getString( + string("FactionPlayerNameForIndex") + intToStr(i), "")); + } else { + gameSettings->setNetworkPlayerName(i, ""); } - fileWasFound = true; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] fileName = [%s]\n",__FILE__,__FUNCTION__,__LINE__,fileName.c_str()); - - Properties properties; - properties.load(fileName); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] fileName = [%s]\n",__FILE__,__FUNCTION__,__LINE__,fileName.c_str()); - - gameSettings->setMapFilter(properties.getInt("MapFilterIndex","0")); - gameSettings->setDescription(properties.getString("Description")); - gameSettings->setMap(properties.getString("Map")); - gameSettings->setTileset(properties.getString("Tileset")); - gameSettings->setTech(properties.getString("TechTree")); - gameSettings->setDefaultUnits(properties.getBool("DefaultUnits")); - gameSettings->setDefaultResources(properties.getBool("DefaultResources")); - gameSettings->setDefaultVictoryConditions(properties.getBool("DefaultVictoryConditions")); - gameSettings->setFogOfWar(properties.getBool("FogOfWar")); - //listBoxAdvanced.setSelectedItemIndex(properties.getInt("AdvancedIndex","0")); - - gameSettings->setAllowObservers(properties.getBool("AllowObservers","false")); - gameSettings->setFlagTypes1(properties.getInt("FlagTypes1","0")); - - uint32 valueFlags1 = gameSettings->getFlagTypes1(); - if(Config::getInstance().getBool("EnableNetworkGameSynchChecks","false") == true) { - //printf("*WARNING* - EnableNetworkGameSynchChecks is enabled\n"); - - valueFlags1 |= ft1_network_synch_checks_verbose; - gameSettings->setFlagTypes1(valueFlags1); - - } - else { - valueFlags1 &= ~ft1_network_synch_checks_verbose; - gameSettings->setFlagTypes1(valueFlags1); - - } - if(Config::getInstance().getBool("EnableNetworkGameSynchMonitor","false") == true) { - //printf("*WARNING* - EnableNetworkGameSynchChecks is enabled\n"); - - valueFlags1 |= ft1_network_synch_checks; - gameSettings->setFlagTypes1(valueFlags1); - - } - else { - valueFlags1 &= ~ft1_network_synch_checks; - gameSettings->setFlagTypes1(valueFlags1); - - } - - - gameSettings->setEnableObserverModeAtEndGame(properties.getBool("EnableObserverModeAtEndGame")); - gameSettings->setAiAcceptSwitchTeamPercentChance(properties.getInt("AiAcceptSwitchTeamPercentChance","30")); - gameSettings->setFallbackCpuMultiplier(properties.getInt("FallbackCpuMultiplier","5")); - - gameSettings->setPathFinderType(static_cast(properties.getInt("PathFinderType",intToStr(pfBasic).c_str()))); - gameSettings->setEnableServerControlledAI(properties.getBool("EnableServerControlledAI","true")); - gameSettings->setNetworkFramePeriod(properties.getInt("NetworkFramePeriod",intToStr(GameConstants::networkFramePeriod).c_str())); - gameSettings->setNetworkPauseGameForLaggedClients(properties.getBool("NetworkPauseGameForLaggedClients","false")); - - gameSettings->setThisFactionIndex(properties.getInt("FactionThisFactionIndex")); - gameSettings->setFactionCount(properties.getInt("FactionCount")); - - if(properties.hasString("NetworkAllowNativeLanguageTechtree") == true) { - gameSettings->setNetworkAllowNativeLanguageTechtree(properties.getBool("NetworkAllowNativeLanguageTechtree")); - } - else { - gameSettings->setNetworkAllowNativeLanguageTechtree(false); - } - - for(int i = 0; i < GameConstants::maxPlayers; ++i) { - gameSettings->setFactionControl(i,(ControlType)properties.getInt(string("FactionControlForIndex") + intToStr(i),intToStr(ctClosed).c_str()) ); - - if(gameSettings->getFactionControl(i) == ctNetworkUnassigned) { - gameSettings->setFactionControl(i,ctNetwork); - } - - gameSettings->setResourceMultiplierIndex(i,properties.getInt(string("ResourceMultiplierIndex") + intToStr(i),"5")); - gameSettings->setTeam(i,properties.getInt(string("FactionTeamForIndex") + intToStr(i),"0") ); - gameSettings->setStartLocationIndex(i,properties.getInt(string("FactionStartLocationForIndex") + intToStr(i),intToStr(i).c_str()) ); - gameSettings->setFactionTypeName(i,properties.getString(string("FactionTypeNameForIndex") + intToStr(i),"?") ); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] i = %d, factionTypeName [%s]\n",__FILE__,__FUNCTION__,__LINE__,i,gameSettings->getFactionTypeName(i).c_str()); - - if(gameSettings->getFactionControl(i) == ctHuman) { - gameSettings->setNetworkPlayerName(i,properties.getString(string("FactionPlayerNameForIndex") + intToStr(i),"") ); - } - else { - gameSettings->setNetworkPlayerName(i,""); - } - - gameSettings->setNetworkPlayerUUID(i,properties.getString(string("FactionPlayerUUIDForIndex") + intToStr(i),"") ); - } + gameSettings->setNetworkPlayerUUID( + i, properties.getString( + string("FactionPlayerUUIDForIndex") + intToStr(i), "")); + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] Line: %d\n", + __FILE__, __FUNCTION__, __LINE__); - return fileWasFound; + return fileWasFound; } // ================== PRIVATE ======================== -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/global/core_data.h b/source/glest_game/global/core_data.h index 601dff7b9..22ffff7ee 100644 --- a/source/glest_game/global/core_data.h +++ b/source/glest_game/global/core_data.h @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,31 +13,31 @@ #define _GLEST_GAME_COREDATA_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include -#include "sound.h" #include "font.h" -#include "texture.h" -#include "sound_container.h" #include "leak_dumper.h" +#include "sound.h" +#include "sound_container.h" +#include "texture.h" +#include -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { -using ::Shared::Graphics::Texture2D; -using ::Shared::Graphics::Texture3D; using ::Shared::Graphics::Font; using ::Shared::Graphics::Font2D; using ::Shared::Graphics::Font3D; using ::Shared::Graphics::FontChangedCallbackInterface; -using ::Shared::Sound::StrSound; +using ::Shared::Graphics::Texture2D; +using ::Shared::Graphics::Texture3D; using ::Shared::Sound::StaticSound; - +using ::Shared::Sound::StrSound; // ===================================================== -// class CoreData +// class CoreData // /// Data shared among all the ProgramStates // ===================================================== @@ -46,227 +46,246 @@ class GameSettings; class CoreData { private: - std::map itemLoadAttempted; - - StrSound introMusic; - StrSound menuMusic; - StaticSound clickSoundA; - StaticSound clickSoundB; - StaticSound clickSoundC; - StaticSound attentionSound; - StaticSound highlightSound; - StaticSound markerSound; - SoundContainer waterSounds; - - Texture2D *logoTexture; - std::vector logoTextureList; - Texture2D *backgroundTexture; - Texture2D *fireTexture; - Texture2D *teamColorTexture; - Texture2D *snowTexture; - Texture2D *waterSplashTexture; - Texture2D *customTexture; - Texture2D *buttonSmallTexture; - Texture2D *buttonBigTexture; - Texture2D *horizontalLineTexture; - Texture2D *verticalLineTexture; - Texture2D *checkBoxTexture; - Texture2D *checkedCheckBoxTexture; - Texture2D *gameWinnerTexture; - Texture2D *notOnServerTexture; - Texture2D *onServerDifferentTexture; - Texture2D *onServerTexture; - Texture2D *onServerInstalledTexture; - Texture2D *statusReadyTexture; - Texture2D *statusNotReadyTexture; - Texture2D *statusBRBTexture; - - Texture2D *healthbarTexture; - Texture2D *healthbarBackgroundTexture; - - std::vector miscTextureList; - - Font2D *displayFont; - Font2D *menuFontNormal; - Font2D *displayFontSmall; - Font2D *menuFontBig; - Font2D *menuFontVeryBig; - Font2D *consoleFont; - - Font3D *displayFont3D; - Font3D *menuFontNormal3D; - Font3D *displayFontSmall3D; - Font3D *menuFontBig3D; - Font3D *menuFontVeryBig3D; - Font3D *consoleFont3D; - - string introVideoFilename; - string introVideoFilenameFallback; - - string mainMenuVideoFilename; - string mainMenuVideoFilenameFallback; - - string battleEndWinVideoFilename; - string battleEndWinVideoFilenameFallback; - string battleEndWinMusicFilename; - - string battleEndLoseVideoFilename; - string battleEndLoseVideoFilenameFallback; - string battleEndLoseMusicFilename; - - std::map > registeredFontChangedCallbacks; -public: + std::map itemLoadAttempted; + + StrSound introMusic; + StrSound menuMusic; + StaticSound clickSoundA; + StaticSound clickSoundB; + StaticSound clickSoundC; + StaticSound attentionSound; + StaticSound highlightSound; + StaticSound markerSound; + SoundContainer waterSounds; + + Texture2D *logoTexture; + std::vector logoTextureList; + Texture2D *backgroundTexture; + Texture2D *fireTexture; + Texture2D *teamColorTexture; + Texture2D *snowTexture; + Texture2D *waterSplashTexture; + Texture2D *customTexture; + Texture2D *buttonSmallTexture; + Texture2D *buttonBigTexture; + Texture2D *horizontalLineTexture; + Texture2D *verticalLineTexture; + Texture2D *checkBoxTexture; + Texture2D *checkedCheckBoxTexture; + Texture2D *gameWinnerTexture; + Texture2D *notOnServerTexture; + Texture2D *onServerDifferentTexture; + Texture2D *onServerTexture; + Texture2D *onServerInstalledTexture; + Texture2D *statusReadyTexture; + Texture2D *statusNotReadyTexture; + Texture2D *statusBRBTexture; + + Texture2D *healthbarTexture; + Texture2D *healthbarBackgroundTexture; + + std::vector miscTextureList; + + Font2D *displayFont; + Font2D *menuFontNormal; + Font2D *displayFontSmall; + Font2D *menuFontBig; + Font2D *menuFontVeryBig; + Font2D *consoleFont; + + Font3D *displayFont3D; + Font3D *menuFontNormal3D; + Font3D *displayFontSmall3D; + Font3D *menuFontBig3D; + Font3D *menuFontVeryBig3D; + Font3D *consoleFont3D; + + string introVideoFilename; + string introVideoFilenameFallback; + + string mainMenuVideoFilename; + string mainMenuVideoFilenameFallback; + + string battleEndWinVideoFilename; + string battleEndWinVideoFilenameFallback; + string battleEndWinMusicFilename; + + string battleEndLoseVideoFilename; + string battleEndLoseVideoFilenameFallback; + string battleEndLoseMusicFilename; + + std::map> + registeredFontChangedCallbacks; - enum TextureSystemType { - tsyst_NONE, - tsyst_logoTexture, - tsyst_backgroundTexture, - tsyst_fireTexture, - tsyst_teamColorTexture, - tsyst_snowTexture, - tsyst_waterSplashTexture, - tsyst_customTexture, - tsyst_buttonSmallTexture, - tsyst_buttonBigTexture, - tsyst_horizontalLineTexture, - tsyst_verticalLineTexture, - tsyst_checkBoxTexture, - tsyst_checkedCheckBoxTexture, - tsyst_gameWinnerTexture, - tsyst_notOnServerTexture, - tsyst_onServerDifferentTexture, - tsyst_onServerTexture, - tsyst_onServerInstalledTexture, - tsyst_statusReadyTexture, - tsyst_statusNotReadyTexture, - tsyst_statusBRBTexture, - tsyst_healthbarTexture, - tsyst_healthbarBackgroundTexture, - - tsyst_COUNT - }; +public: + enum TextureSystemType { + tsyst_NONE, + tsyst_logoTexture, + tsyst_backgroundTexture, + tsyst_fireTexture, + tsyst_teamColorTexture, + tsyst_snowTexture, + tsyst_waterSplashTexture, + tsyst_customTexture, + tsyst_buttonSmallTexture, + tsyst_buttonBigTexture, + tsyst_horizontalLineTexture, + tsyst_verticalLineTexture, + tsyst_checkBoxTexture, + tsyst_checkedCheckBoxTexture, + tsyst_gameWinnerTexture, + tsyst_notOnServerTexture, + tsyst_onServerDifferentTexture, + tsyst_onServerTexture, + tsyst_onServerInstalledTexture, + tsyst_statusReadyTexture, + tsyst_statusNotReadyTexture, + tsyst_statusBRBTexture, + tsyst_healthbarTexture, + tsyst_healthbarBackgroundTexture, + + tsyst_COUNT + }; public: + ~CoreData(); + static CoreData &getInstance(); + + void load(); + void cleanup(); + void loadFonts(); + + // Textures + Texture2D *getTextureBySystemId(TextureSystemType type); + + Texture2D *getBackgroundTexture(); + Texture2D *getFireTexture(); + Texture2D *getTeamColorTexture(); + Texture2D *getSnowTexture(); + Texture2D *getLogoTexture(); + Texture2D *getWaterSplashTexture(); + Texture2D *getCustomTexture(); + Texture2D *getButtonSmallTexture(); + Texture2D *getButtonBigTexture(); + Texture2D *getHorizontalLineTexture(); + Texture2D *getVerticalLineTexture(); + Texture2D *getCheckBoxTexture(); + Texture2D *getCheckedCheckBoxTexture(); + Texture2D *getNotOnServerTexture(); + Texture2D *getOnServerDifferentTexture(); + Texture2D *getOnServerTexture(); + Texture2D *getOnServerInstalledTexture(); + Texture2D *getStatusReadyTexture(); + Texture2D *getStatusNotReadyTexture(); + Texture2D *getStatusBRBTexture(); + Texture2D *getGameWinnerTexture(); + + Texture2D *getHealthbarTexture(); + Texture2D *getHealthbarBackgroundTexture(); + + size_t getLogoTextureExtraCount(); + Texture2D *getLogoTextureExtra(int idx); + + std::vector &getMiscTextureList(); + + // Sounds and Music + StrSound *getIntroMusic(); + StrSound *getMenuMusic(); + + StaticSound *getClickSoundA(); + StaticSound *getClickSoundB(); + StaticSound *getClickSoundC(); + StaticSound *getAttentionSound(); + StaticSound *getHighlightSound(); + StaticSound *getMarkerSound(); + StaticSound *getWaterSound(); + + // Fonts + Font2D *getDisplayFont() const { return displayFont; } + Font2D *getDisplayFontSmall() const { return displayFontSmall; } + Font2D *getMenuFontNormal() const { return menuFontNormal; } + Font2D *getMenuFontBig() const { return menuFontBig; } + Font2D *getMenuFontVeryBig() const { return menuFontVeryBig; } + Font2D *getConsoleFont() const { return consoleFont; } + + Font3D *getDisplayFont3D() const { return displayFont3D; } + Font3D *getDisplayFontSmall3D() const { return displayFontSmall3D; } + Font3D *getMenuFontNormal3D() const { return menuFontNormal3D; } + Font3D *getMenuFontBig3D() const { return menuFontBig3D; } + Font3D *getMenuFontVeryBig3D() const { return menuFontVeryBig3D; } + Font3D *getConsoleFont3D() const { return consoleFont3D; } + + // Helper functions + string getMainMenuVideoFilename() const { return mainMenuVideoFilename; } + bool hasMainMenuVideoFilename() const; + string getMainMenuVideoFilenameFallback() const { + return mainMenuVideoFilenameFallback; + } + bool hasMainMenuVideoFilenameFallback() const; + + string getIntroVideoFilename() const { return introVideoFilename; } + bool hasIntroVideoFilename() const; + string getIntroVideoFilenameFallback() const { + return introVideoFilenameFallback; + } + bool hasIntroVideoFilenameFallback() const; + + string getBattleEndVideoFilename(bool won) const { + return won == true ? battleEndWinVideoFilename : battleEndLoseVideoFilename; + } + // bool hasBattleEndVideoFilename(bool won) const; + string getBattleEndVideoFilenameFallback(bool won) const { + return won == true ? battleEndWinVideoFilenameFallback + : battleEndLoseVideoFilenameFallback; + } + bool hasBattleEndVideoFilenameFallback(bool won) const; + + string getBattleEndMusicFilename(bool won) const { + return won == true ? battleEndWinMusicFilename : battleEndLoseMusicFilename; + } + + void saveGameSettingsToFile(std::string fileName, GameSettings *gameSettings, + int advancedIndex = 0); + bool loadGameSettingsFromFile(std::string fileName, + GameSettings *gameSettings); + + void registerFontChangedCallback(std::string entityName, + FontChangedCallbackInterface *cb); + void unRegisterFontChangedCallback(std::string entityName); - ~CoreData(); - static CoreData &getInstance(); - - void load(); - void cleanup(); - void loadFonts(); - - // Textures - Texture2D *getTextureBySystemId(TextureSystemType type); - - Texture2D *getBackgroundTexture(); - Texture2D *getFireTexture(); - Texture2D *getTeamColorTexture(); - Texture2D *getSnowTexture(); - Texture2D *getLogoTexture(); - Texture2D *getWaterSplashTexture(); - Texture2D *getCustomTexture(); - Texture2D *getButtonSmallTexture(); - Texture2D *getButtonBigTexture(); - Texture2D *getHorizontalLineTexture(); - Texture2D *getVerticalLineTexture(); - Texture2D *getCheckBoxTexture(); - Texture2D *getCheckedCheckBoxTexture(); - Texture2D *getNotOnServerTexture(); - Texture2D *getOnServerDifferentTexture(); - Texture2D *getOnServerTexture(); - Texture2D *getOnServerInstalledTexture(); - Texture2D *getStatusReadyTexture(); - Texture2D *getStatusNotReadyTexture(); - Texture2D *getStatusBRBTexture(); - Texture2D *getGameWinnerTexture(); - - Texture2D *getHealthbarTexture(); - Texture2D *getHealthbarBackgroundTexture(); - - size_t getLogoTextureExtraCount(); - Texture2D *getLogoTextureExtra(int idx); - - std::vector & getMiscTextureList(); - - // Sounds and Music - StrSound *getIntroMusic(); - StrSound *getMenuMusic(); - - StaticSound *getClickSoundA(); - StaticSound *getClickSoundB(); - StaticSound *getClickSoundC(); - StaticSound *getAttentionSound(); - StaticSound *getHighlightSound(); - StaticSound *getMarkerSound(); - StaticSound *getWaterSound(); - - // Fonts - Font2D *getDisplayFont() const {return displayFont;} - Font2D *getDisplayFontSmall() const {return displayFontSmall;} - Font2D *getMenuFontNormal() const {return menuFontNormal;} - Font2D *getMenuFontBig() const {return menuFontBig;} - Font2D *getMenuFontVeryBig() const {return menuFontVeryBig;} - Font2D *getConsoleFont() const {return consoleFont;} - - Font3D *getDisplayFont3D() const {return displayFont3D;} - Font3D *getDisplayFontSmall3D() const {return displayFontSmall3D;} - Font3D *getMenuFontNormal3D() const {return menuFontNormal3D;} - Font3D *getMenuFontBig3D() const {return menuFontBig3D;} - Font3D *getMenuFontVeryBig3D() const {return menuFontVeryBig3D;} - Font3D *getConsoleFont3D() const {return consoleFont3D;} - - // Helper functions - string getMainMenuVideoFilename() const { return mainMenuVideoFilename; } - bool hasMainMenuVideoFilename() const; - string getMainMenuVideoFilenameFallback() const { return mainMenuVideoFilenameFallback; } - bool hasMainMenuVideoFilenameFallback() const; - - string getIntroVideoFilename() const { return introVideoFilename; } - bool hasIntroVideoFilename() const; - string getIntroVideoFilenameFallback() const { return introVideoFilenameFallback; } - bool hasIntroVideoFilenameFallback() const; - - string getBattleEndVideoFilename(bool won) const { return won == true ? battleEndWinVideoFilename : battleEndLoseVideoFilename; } - //bool hasBattleEndVideoFilename(bool won) const; - string getBattleEndVideoFilenameFallback(bool won) const { return won == true ? battleEndWinVideoFilenameFallback : battleEndLoseVideoFilenameFallback; } - bool hasBattleEndVideoFilenameFallback(bool won) const; - - string getBattleEndMusicFilename(bool won) const { return won == true ? battleEndWinMusicFilename : battleEndLoseMusicFilename; } - - void saveGameSettingsToFile(std::string fileName, GameSettings *gameSettings,int advancedIndex=0); - bool loadGameSettingsFromFile(std::string fileName, GameSettings *gameSettings); - - void registerFontChangedCallback(std::string entityName, FontChangedCallbackInterface *cb); - void unRegisterFontChangedCallback(std::string entityName); private: - - CoreData(); - - int computeFontSize(int size); - void cleanupTexture(Texture2D **texture); - void loadTextures(string data_path); - void loadSounds(string data_path); - void loadMusic(string data_path); - void loadIntroMedia(string data_path); - void loadMainMenuMedia(string data_path); - void loadBattleEndMedia(string data_path); - - string getDataPath(); - void loadTextureIfRequired(Texture2D **tex,string data_path, - string uniqueFilePath, int texSystemId, bool setMipMap, - bool setAlpha, bool loadUniqueFilePath, - bool compressionDisabled = false); - - void loadLogoTextureExtraIfRequired(); - void loadMiscTextureListIfRequired(); - - void loadWaterSoundsIfRequired(); - void loadMusicIfRequired(); - - void triggerFontChangedCallbacks(std::string fontUniqueId, Font *font); - template T * loadFont(Font *menuFontNormal, string menuFontNameNormal, int menuFontNameNormalSize, string fontType, string fontTypeFamily, string fontUniqueKey); + CoreData(); + + int computeFontSize(int size); + void cleanupTexture(Texture2D **texture); + void loadTextures(string data_path); + void loadSounds(string data_path); + void loadMusic(string data_path); + void loadIntroMedia(string data_path); + void loadMainMenuMedia(string data_path); + void loadBattleEndMedia(string data_path); + + string getDataPath(); + void loadTextureIfRequired(Texture2D **tex, string data_path, + string uniqueFilePath, int texSystemId, + bool setMipMap, bool setAlpha, + bool loadUniqueFilePath, + bool compressionDisabled = false); + + void loadLogoTextureExtraIfRequired(); + void loadMiscTextureListIfRequired(); + + void loadWaterSoundsIfRequired(); + void loadMusicIfRequired(); + + void triggerFontChangedCallbacks(std::string fontUniqueId, Font *font); + template + T *loadFont(Font *menuFontNormal, string menuFontNameNormal, + int menuFontNameNormalSize, string fontType, + string fontTypeFamily, string fontUniqueKey); }; -}} //end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/global/lang.cpp b/source/glest_game/global/lang.cpp index 3ef82adcf..5ad8d35a5 100644 --- a/source/glest_game/global/lang.cpp +++ b/source/glest_game/global/lang.cpp @@ -13,26 +13,27 @@ #include -#include "logger.h" -#include "util.h" -#include "platform_util.h" +#include "config.h" +#include "conversion.h" +#include "core_data.h" #include "game_constants.h" #include "game_util.h" -#include "platform_common.h" -#include "conversion.h" #include "gl_wrap.h" -#include "core_data.h" +#include "leak_dumper.h" +#include "logger.h" +#include "platform_common.h" +#include "platform_util.h" #include "renderer.h" -#include -#include "config.h" +#include "util.h" #include "window.h" -#include "leak_dumper.h" +#include using namespace std; using namespace Shared::Util; using namespace Shared::Platform; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { const char *DEFAULT_LANGUAGE = "english"; @@ -41,710 +42,823 @@ const char *DEFAULT_LANGUAGE = "english"; // ===================================================== Lang::Lang() { - language = ""; - is_utf8_language = false; - allowNativeLanguageTechtree = true; - techNameLoaded = ""; + language = ""; + is_utf8_language = false; + allowNativeLanguageTechtree = true; + techNameLoaded = ""; } Lang &Lang::getInstance() { - static Lang lang; - return lang; + static Lang lang; + return lang; } -string Lang::getDefaultLanguage() const { - return DEFAULT_LANGUAGE; -} +string Lang::getDefaultLanguage() const { return DEFAULT_LANGUAGE; } void Lang::loadGameStrings(string uselanguage, bool loadFonts, - bool fallbackToDefault) { - if(uselanguage.length() == 2 || (uselanguage.length() == 5 && uselanguage[2] == '-')) { - uselanguage = getLanguageFile(uselanguage); - } - bool languageChanged = (uselanguage != this->language); - this->language= uselanguage; - loadGameStringProperties(uselanguage, gameStringsAllLanguages[this->language], true, fallbackToDefault); - - if(languageChanged == true) { - Font::resetToDefaults(); - Lang &lang = Lang::getInstance(); - if( lang.hasString("FONT_BASE_SIZE")) { - Font::baseSize = strToInt(lang.getString("FONT_BASE_SIZE")); - } - - if( lang.hasString("FONT_SCALE_SIZE")) { - Font::scaleFontValue = strToFloat(lang.getString("FONT_SCALE_SIZE")); - } - if( lang.hasString("FONT_SCALE_CENTERH_FACTOR")) { - Font::scaleFontValueCenterHFactor = strToFloat(lang.getString("FONT_SCALE_CENTERH_FACTOR")); - } - - if( lang.hasString("FONT_CHARCOUNT")) { - // 256 for English - // 30000 for Chinese - Font::charCount = strToInt(lang.getString("FONT_CHARCOUNT")); - } - if( lang.hasString("FONT_TYPENAME")) { - Font::fontTypeName = lang.getString("FONT_TYPENAME"); - } - if( lang.hasString("FONT_CHARSET")) { - // Example values: - // DEFAULT_CHARSET (English) = 1 - // GB2312_CHARSET (Chinese) = 134 - Shared::Platform::PlatformContextGl::charSet = strToInt(lang.getString("FONT_CHARSET")); - } - if( lang.hasString("FONT_MULTIBYTE")) { - Font::fontIsMultibyte = strToBool(lang.getString("FONT_MULTIBYTE")); - } - - if( lang.hasString("FONT_RIGHTTOLEFT")) { - Font::fontIsRightToLeft = strToBool(lang.getString("FONT_RIGHTTOLEFT")); - } - - if( lang.hasString("FONT_RIGHTTOLEFT_MIXED_SUPPORT")) { - Font::fontSupportMixedRightToLeft = strToBool(lang.getString("FONT_RIGHTTOLEFT_MIXED_SUPPORT")); - } - - if( lang.hasString("MEGAGLEST_FONT")) { - //setenv("MEGAGLEST_FONT","/usr/share/fonts/truetype/ttf-japanese-gothic.ttf",0); // Japanese - #if defined(WIN32) - string newEnvValue = "MEGAGLEST_FONT=" + lang.getString("MEGAGLEST_FONT"); - _putenv(newEnvValue.c_str()); - #else - setenv("MEGAGLEST_FONT",lang.getString("MEGAGLEST_FONT").c_str(),0); - #endif - } - - if( lang.hasString("MEGAGLEST_FONT_FAMILY")) { - #if defined(WIN32) - string newEnvValue = "MEGAGLEST_FONT_FAMILY=" + lang.getString("MEGAGLEST_FONT_FAMILY"); - _putenv(newEnvValue.c_str()); - #else - setenv("MEGAGLEST_FONT_FAMILY",lang.getString("MEGAGLEST_FONT_FAMILY").c_str(),0); - #endif - } - - #if defined(WIN32) - // Win32 overrides for fonts (just in case they must be different) - - if( lang.hasString("FONT_BASE_SIZE_WINDOWS")) { - // 256 for English - // 30000 for Chinese - Font::baseSize = strToInt(lang.getString("FONT_BASE_SIZE_WINDOWS")); - } - - if( lang.hasString("FONT_SCALE_SIZE_WINDOWS")) { - Font::scaleFontValue = strToFloat(lang.getString("FONT_SCALE_SIZE_WINDOWS")); - } - if( lang.hasString("FONT_SCALE_CENTERH_FACTOR_WINDOWS")) { - Font::scaleFontValueCenterHFactor = strToFloat(lang.getString("FONT_SCALE_CENTERH_FACTOR_WINDOWS")); - } - - if( lang.hasString("FONT_HEIGHT_TEXT_WINDOWS")) { - Font::langHeightText = lang.getString("FONT_HEIGHT_TEXT_WINDOWS",Font::langHeightText.c_str()); - } - - if( lang.hasString("FONT_CHARCOUNT_WINDOWS")) { - // 256 for English - // 30000 for Chinese - Font::charCount = strToInt(lang.getString("FONT_CHARCOUNT_WINDOWS")); - } - if( lang.hasString("FONT_TYPENAME_WINDOWS")) { - Font::fontTypeName = lang.getString("FONT_TYPENAME_WINDOWS"); - } - if( lang.hasString("FONT_CHARSET_WINDOWS")) { - // Example values: - // DEFAULT_CHARSET (English) = 1 - // GB2312_CHARSET (Chinese) = 134 - Shared::Platform::PlatformContextGl::charSet = strToInt(lang.getString("FONT_CHARSET_WINDOWS")); - } - if( lang.hasString("FONT_MULTIBYTE_WINDOWS")) { - Font::fontIsMultibyte = strToBool(lang.getString("FONT_MULTIBYTE_WINDOWS")); - } - if( lang.hasString("FONT_RIGHTTOLEFT_WINDOWS")) { - Font::fontIsRightToLeft = strToBool(lang.getString("FONT_RIGHTTOLEFT_WINDOWS")); - } - - if( lang.hasString("MEGAGLEST_FONT_WINDOWS")) { - //setenv("MEGAGLEST_FONT","/usr/share/fonts/truetype/ttf-japanese-gothic.ttf",0); // Japanese - string newEnvValue = "MEGAGLEST_FONT=" + lang.getString("MEGAGLEST_FONT_WINDOWS"); - _putenv(newEnvValue.c_str()); - } - - // end win32 - #endif - - - if( lang.hasString("ALLOWED_SPECIAL_KEYS","",false)) { - string allowedKeys = lang.getString("ALLOWED_SPECIAL_KEYS"); - Window::addAllowedKeys(allowedKeys); - } - else { - Window::clearAllowedKeys(); - } - - if(loadFonts == true) { - CoreData &coreData= CoreData::getInstance(); - coreData.loadFonts(); - } + bool fallbackToDefault) { + if (uselanguage.length() == 2 || + (uselanguage.length() == 5 && uselanguage[2] == '-')) { + uselanguage = getLanguageFile(uselanguage); + } + bool languageChanged = (uselanguage != this->language); + this->language = uselanguage; + loadGameStringProperties(uselanguage, gameStringsAllLanguages[this->language], + true, fallbackToDefault); + + if (languageChanged == true) { + Font::resetToDefaults(); + Lang &lang = Lang::getInstance(); + if (lang.hasString("FONT_BASE_SIZE")) { + Font::baseSize = strToInt(lang.getString("FONT_BASE_SIZE")); } -} -void Lang::loadGameStringProperties(string uselanguage, Properties &properties, bool fileMustExist, - bool fallbackToDefault) { - properties.clear(); - string data_path = getGameReadWritePath(GameConstants::path_data_CacheLookupKey); - //string languageFile = data_path + "data/lang/" + uselanguage + ".lng"; - string languageFile = getGameCustomCoreDataPath(data_path, "data/lang/" + uselanguage + ".lng"); - if(fileMustExist == false && fileExists(languageFile) == false) { - return; - } - else if(fileExists(languageFile) == false && fallbackToDefault == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] path = [%s]\n",__FILE__,__FUNCTION__,__LINE__,languageFile.c_str()); - //throw megaglest_runtime_error("File NOT FOUND, can't open file: [" + languageFile + "]"); - printf("Language file NOT FOUND, can't open file: [%s] switching to default language: %s\n",languageFile.c_str(),DEFAULT_LANGUAGE); - - languageFile = getGameCustomCoreDataPath(data_path, "data/lang/" + string(DEFAULT_LANGUAGE) + ".lng"); - } - is_utf8_language = valid_utf8_file(languageFile.c_str()); - properties.load(languageFile); -} + if (lang.hasString("FONT_SCALE_SIZE")) { + Font::scaleFontValue = strToFloat(lang.getString("FONT_SCALE_SIZE")); + } + if (lang.hasString("FONT_SCALE_CENTERH_FACTOR")) { + Font::scaleFontValueCenterHFactor = + strToFloat(lang.getString("FONT_SCALE_CENTERH_FACTOR")); + } -//bool Lang::isUTF8Language() const { -// return is_utf8_language; -//} + if (lang.hasString("FONT_CHARCOUNT")) { + // 256 for English + // 30000 for Chinese + Font::charCount = strToInt(lang.getString("FONT_CHARCOUNT")); + } + if (lang.hasString("FONT_TYPENAME")) { + Font::fontTypeName = lang.getString("FONT_TYPENAME"); + } + if (lang.hasString("FONT_CHARSET")) { + // Example values: + // DEFAULT_CHARSET (English) = 1 + // GB2312_CHARSET (Chinese) = 134 + Shared::Platform::PlatformContextGl::charSet = + strToInt(lang.getString("FONT_CHARSET")); + } + if (lang.hasString("FONT_MULTIBYTE")) { + Font::fontIsMultibyte = strToBool(lang.getString("FONT_MULTIBYTE")); + } -void Lang::loadScenarioStrings(string scenarioDir, string scenarioName, bool isTutorial) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] scenarioDir = [%s] scenarioName = [%s]\n",__FILE__,__FUNCTION__,__LINE__,scenarioDir.c_str(),scenarioName.c_str()); + if (lang.hasString("FONT_RIGHTTOLEFT")) { + Font::fontIsRightToLeft = strToBool(lang.getString("FONT_RIGHTTOLEFT")); + } - //printf("Loading scenario scenarioDir [%s] scenarioName [%s]\n",scenarioDir.c_str(),scenarioName.c_str()); + if (lang.hasString("FONT_RIGHTTOLEFT_MIXED_SUPPORT")) { + Font::fontSupportMixedRightToLeft = + strToBool(lang.getString("FONT_RIGHTTOLEFT_MIXED_SUPPORT")); + } - // First try to find scenario lng file in userdata - Config &config = Config::getInstance(); - vector scenarioPaths; - if(isTutorial == false) { - scenarioPaths = config.getPathListForType(ptScenarios); + if (lang.hasString("MEGAGLEST_FONT")) { + // setenv("MEGAGLEST_FONT","/usr/share/fonts/truetype/ttf-japanese-gothic.ttf",0); + // // Japanese +#if defined(WIN32) + string newEnvValue = "MEGAGLEST_FONT=" + lang.getString("MEGAGLEST_FONT"); + _putenv(newEnvValue.c_str()); +#else + setenv("MEGAGLEST_FONT", lang.getString("MEGAGLEST_FONT").c_str(), 0); +#endif } - else { - scenarioPaths = config.getPathListForType(ptTutorials); + + if (lang.hasString("MEGAGLEST_FONT_FAMILY")) { +#if defined(WIN32) + string newEnvValue = + "MEGAGLEST_FONT_FAMILY=" + lang.getString("MEGAGLEST_FONT_FAMILY"); + _putenv(newEnvValue.c_str()); +#else + setenv("MEGAGLEST_FONT_FAMILY", + lang.getString("MEGAGLEST_FONT_FAMILY").c_str(), 0); +#endif } - if(scenarioPaths.size() > 1) { - string &scenarioPath = scenarioPaths[1]; - endPathWithSlash(scenarioPath); - string currentPath = scenarioPath; - endPathWithSlash(currentPath); - string scenarioFolder = currentPath + scenarioName + "/"; - string path = scenarioFolder + scenarioName + "_" + language + ".lng"; +#if defined(WIN32) + // Win32 overrides for fonts (just in case they must be different) - //try to load the current language first - if(fileExists(path)) { - scenarioDir = scenarioPath; - } + if (lang.hasString("FONT_BASE_SIZE_WINDOWS")) { + // 256 for English + // 30000 for Chinese + Font::baseSize = strToInt(lang.getString("FONT_BASE_SIZE_WINDOWS")); } - string currentPath = scenarioDir; - endPathWithSlash(currentPath); - string scenarioFolder = currentPath + scenarioName + "/"; - string path = scenarioFolder + scenarioName + "_" + language + ".lng"; - if(EndsWith(scenarioDir, ".xml") == true) { - scenarioFolder = extractDirectoryPathFromFile(scenarioDir); - path = scenarioFolder + scenarioName + "_" + language + ".lng"; + if (lang.hasString("FONT_SCALE_SIZE_WINDOWS")) { + Font::scaleFontValue = + strToFloat(lang.getString("FONT_SCALE_SIZE_WINDOWS")); + } + if (lang.hasString("FONT_SCALE_CENTERH_FACTOR_WINDOWS")) { + Font::scaleFontValueCenterHFactor = + strToFloat(lang.getString("FONT_SCALE_CENTERH_FACTOR_WINDOWS")); + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] path = [%s]\n",__FILE__,__FUNCTION__,__LINE__,path.c_str()); - } + if (lang.hasString("FONT_HEIGHT_TEXT_WINDOWS")) { + Font::langHeightText = lang.getString("FONT_HEIGHT_TEXT_WINDOWS", + Font::langHeightText.c_str()); + } - scenarioStrings.clear(); + if (lang.hasString("FONT_CHARCOUNT_WINDOWS")) { + // 256 for English + // 30000 for Chinese + Font::charCount = strToInt(lang.getString("FONT_CHARCOUNT_WINDOWS")); + } + if (lang.hasString("FONT_TYPENAME_WINDOWS")) { + Font::fontTypeName = lang.getString("FONT_TYPENAME_WINDOWS"); + } + if (lang.hasString("FONT_CHARSET_WINDOWS")) { + // Example values: + // DEFAULT_CHARSET (English) = 1 + // GB2312_CHARSET (Chinese) = 134 + Shared::Platform::PlatformContextGl::charSet = + strToInt(lang.getString("FONT_CHARSET_WINDOWS")); + } + if (lang.hasString("FONT_MULTIBYTE_WINDOWS")) { + Font::fontIsMultibyte = + strToBool(lang.getString("FONT_MULTIBYTE_WINDOWS")); + } + if (lang.hasString("FONT_RIGHTTOLEFT_WINDOWS")) { + Font::fontIsRightToLeft = + strToBool(lang.getString("FONT_RIGHTTOLEFT_WINDOWS")); + } - //try to load the current language first - if(fileExists(path)) { - //printf("#2 Loading scenario path [%s]\n",path.c_str()); + if (lang.hasString("MEGAGLEST_FONT_WINDOWS")) { + // setenv("MEGAGLEST_FONT","/usr/share/fonts/truetype/ttf-japanese-gothic.ttf",0); + // // Japanese + string newEnvValue = + "MEGAGLEST_FONT=" + lang.getString("MEGAGLEST_FONT_WINDOWS"); + _putenv(newEnvValue.c_str()); + } - scenarioStrings.load(path); - } - else{ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] path not found [%s]\n",__FILE__,__FUNCTION__,__LINE__,path.c_str()); + // end win32 +#endif - //try english otherwise - path = scenarioFolder + scenarioName + "_english.lng"; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] path = [%s]\n",__FILE__,__FUNCTION__,__LINE__,path.c_str()); + if (lang.hasString("ALLOWED_SPECIAL_KEYS", "", false)) { + string allowedKeys = lang.getString("ALLOWED_SPECIAL_KEYS"); + Window::addAllowedKeys(allowedKeys); + } else { + Window::clearAllowedKeys(); + } - if(fileExists(path)){ - //printf("#3 Loading scenario path [%s]\n",path.c_str()); + if (loadFonts == true) { + CoreData &coreData = CoreData::getInstance(); + coreData.loadFonts(); + } + } +} - scenarioStrings.load(path); - } - } +void Lang::loadGameStringProperties(string uselanguage, Properties &properties, + bool fileMustExist, + bool fallbackToDefault) { + properties.clear(); + string data_path = + getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + // string languageFile = data_path + "data/lang/" + uselanguage + ".lng"; + string languageFile = + getGameCustomCoreDataPath(data_path, "data/lang/" + uselanguage + ".lng"); + if (fileMustExist == false && fileExists(languageFile) == false) { + return; + } else if (fileExists(languageFile) == false && fallbackToDefault == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] path = [%s]\n", __FILE__, + __FUNCTION__, __LINE__, languageFile.c_str()); + // throw megaglest_runtime_error("File NOT FOUND, can't open file: [" + + // languageFile + "]"); + printf("Language file NOT FOUND, can't open file: [%s] switching to " + "default language: %s\n", + languageFile.c_str(), DEFAULT_LANGUAGE); + + languageFile = getGameCustomCoreDataPath( + data_path, "data/lang/" + string(DEFAULT_LANGUAGE) + ".lng"); + } + is_utf8_language = valid_utf8_file(languageFile.c_str()); + properties.load(languageFile); } -bool Lang::loadTechTreeStrings(string techTree,bool forceLoad) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] techTree = [%s]\n",__FILE__,__FUNCTION__,__LINE__,techTree.c_str()); - - //printf("Line: %d techTree = %s forceLoad = %d\n",__LINE__,techTree.c_str(),forceLoad); - - if(forceLoad == false && techTree == techNameLoaded) { - return true; - } - - bool foundTranslation = false; - - string currentPath = ""; - Config &config = Config::getInstance(); - vector techPaths = config.getPathListForType(ptTechs); - for(int idx = 0; idx < (int)techPaths.size(); idx++) { - string &techPath = techPaths[idx]; - endPathWithSlash(techPath); - - if(folderExists(techPath + techTree) == true) { - currentPath = techPath; - endPathWithSlash(currentPath); - break; - } - } - - string techTreeFolder = currentPath + techTree + "/"; - string path = techTreeFolder + "lang/" + techTree + "_" + language + ".lng"; - string pathDefault = techTreeFolder + "lang/" + techTree + "_default.lng"; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] path = [%s] pathDefault = [%s]\n",__FILE__,__FUNCTION__,__LINE__,path.c_str(),pathDefault.c_str()); - - //techTreeStrings.clear(); - //techTreeStringsDefault.clear(); - - //printf("Line: %d techTree = %s this->language = %s forceLoad = %d path = %s\n",__LINE__,techTree.c_str(),this->language.c_str(),forceLoad,path.c_str()); - - //try to load the current language first - if(fileExists(path)) { - foundTranslation = true; - if(forceLoad == true || - path != techTreeStringsAllLanguages[techTree][this->language].getpath()) { - - //printf("Line: %d techTree = %s forceLoad = %d path = %s\n",__LINE__,techTree.c_str(),forceLoad,path.c_str()); - - techTreeStringsAllLanguages[techTree][this->language].load(path); - techNameLoaded = techTree; - } - else if(path == techTreeStringsAllLanguages[techTree][this->language].getpath() && - techTree != techNameLoaded) { - techNameLoaded = techTree; - } - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] path not found [%s]\n",__FILE__,__FUNCTION__,__LINE__,path.c_str()); - - //try english otherwise - string default_language = "english"; - path = techTreeFolder + "lang/" + techTree + "_" + default_language + ".lng"; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] path = [%s]\n",__FILE__,__FUNCTION__,__LINE__,path.c_str()); - - //printf("Line: %d techTree = %s forceLoad = %d path = %s\n",__LINE__,techTree.c_str(),forceLoad,path.c_str()); - - if(fileExists(path)) { - foundTranslation = true; - if(forceLoad == true || - path != techTreeStringsAllLanguages[techTree][default_language].getpath()) { - //printf("Line: %d techTree = %s forceLoad = %d path = %s\n",__LINE__,techTree.c_str(),forceLoad,path.c_str()); - - techTreeStringsAllLanguages[techTree][default_language].load(path); - techNameLoaded = techTree; - } - else if(path == techTreeStringsAllLanguages[techTree][default_language].getpath() && - techTree != techNameLoaded) { - techNameLoaded = techTree; - } - } - } - - if(fileExists(pathDefault)) { - foundTranslation = true; - string default_language = "default"; - - //printf("Line: %d techTree = %s forceLoad = %d default_language = %s\n",__LINE__,techTree.c_str(),forceLoad,default_language.c_str()); - - if(forceLoad == true || - pathDefault != techTreeStringsAllLanguages[techTree][default_language].getpath()) { - //printf("Line: %d techTree = %s forceLoad = %d pathDefault = %s\n",__LINE__,techTree.c_str(),forceLoad,pathDefault.c_str()); - - techTreeStringsAllLanguages[techTree][default_language].load(pathDefault); - techNameLoaded = techTree; - } - else if(pathDefault == techTreeStringsAllLanguages[techTree][default_language].getpath() && - techTree != techNameLoaded) { - techNameLoaded = techTree; - } - } - - return foundTranslation; +// bool Lang::isUTF8Language() const { +// return is_utf8_language; +// } + +void Lang::loadScenarioStrings(string scenarioDir, string scenarioName, + bool isTutorial) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] scenarioDir = [%s] scenarioName = [%s]\n", + __FILE__, __FUNCTION__, __LINE__, scenarioDir.c_str(), + scenarioName.c_str()); + + // printf("Loading scenario scenarioDir [%s] scenarioName + // [%s]\n",scenarioDir.c_str(),scenarioName.c_str()); + + // First try to find scenario lng file in userdata + Config &config = Config::getInstance(); + vector scenarioPaths; + if (isTutorial == false) { + scenarioPaths = config.getPathListForType(ptScenarios); + } else { + scenarioPaths = config.getPathListForType(ptTutorials); + } + if (scenarioPaths.size() > 1) { + string &scenarioPath = scenarioPaths[1]; + endPathWithSlash(scenarioPath); + + string currentPath = scenarioPath; + endPathWithSlash(currentPath); + string scenarioFolder = currentPath + scenarioName + "/"; + string path = scenarioFolder + scenarioName + "_" + language + ".lng"; + + // try to load the current language first + if (fileExists(path)) { + scenarioDir = scenarioPath; + } + } + + string currentPath = scenarioDir; + endPathWithSlash(currentPath); + string scenarioFolder = currentPath + scenarioName + "/"; + string path = scenarioFolder + scenarioName + "_" + language + ".lng"; + if (EndsWith(scenarioDir, ".xml") == true) { + scenarioFolder = extractDirectoryPathFromFile(scenarioDir); + path = scenarioFolder + scenarioName + "_" + language + ".lng"; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] path = [%s]\n", __FILE__, + __FUNCTION__, __LINE__, path.c_str()); + } + + scenarioStrings.clear(); + + // try to load the current language first + if (fileExists(path)) { + // printf("#2 Loading scenario path [%s]\n",path.c_str()); + + scenarioStrings.load(path); + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] path not found [%s]\n", + __FILE__, __FUNCTION__, __LINE__, path.c_str()); + + // try english otherwise + path = scenarioFolder + scenarioName + "_english.lng"; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] path = [%s]\n", __FILE__, + __FUNCTION__, __LINE__, path.c_str()); + + if (fileExists(path)) { + // printf("#3 Loading scenario path [%s]\n",path.c_str()); + + scenarioStrings.load(path); + } + } +} + +bool Lang::loadTechTreeStrings(string techTree, bool forceLoad) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] techTree = [%s]\n", __FILE__, + __FUNCTION__, __LINE__, techTree.c_str()); + + // printf("Line: %d techTree = %s forceLoad = + // %d\n",__LINE__,techTree.c_str(),forceLoad); + + if (forceLoad == false && techTree == techNameLoaded) { + return true; + } + + bool foundTranslation = false; + + string currentPath = ""; + Config &config = Config::getInstance(); + vector techPaths = config.getPathListForType(ptTechs); + for (int idx = 0; idx < (int)techPaths.size(); idx++) { + string &techPath = techPaths[idx]; + endPathWithSlash(techPath); + + if (folderExists(techPath + techTree) == true) { + currentPath = techPath; + endPathWithSlash(currentPath); + break; + } + } + + string techTreeFolder = currentPath + techTree + "/"; + string path = techTreeFolder + "lang/" + techTree + "_" + language + ".lng"; + string pathDefault = techTreeFolder + "lang/" + techTree + "_default.lng"; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] path = [%s] pathDefault = [%s]\n", __FILE__, + __FUNCTION__, __LINE__, path.c_str(), pathDefault.c_str()); + + // techTreeStrings.clear(); + // techTreeStringsDefault.clear(); + + // printf("Line: %d techTree = %s this->language = %s forceLoad = %d path = + // %s\n",__LINE__,techTree.c_str(),this->language.c_str(),forceLoad,path.c_str()); + + // try to load the current language first + if (fileExists(path)) { + foundTranslation = true; + if (forceLoad == true || + path != + techTreeStringsAllLanguages[techTree][this->language].getpath()) { + + // printf("Line: %d techTree = %s forceLoad = %d path = + // %s\n",__LINE__,techTree.c_str(),forceLoad,path.c_str()); + + techTreeStringsAllLanguages[techTree][this->language].load(path); + techNameLoaded = techTree; + } else if (path == techTreeStringsAllLanguages[techTree][this->language] + .getpath() && + techTree != techNameLoaded) { + techNameLoaded = techTree; + } + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] path not found [%s]\n", + __FILE__, __FUNCTION__, __LINE__, path.c_str()); + + // try english otherwise + string default_language = "english"; + path = + techTreeFolder + "lang/" + techTree + "_" + default_language + ".lng"; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] path = [%s]\n", __FILE__, + __FUNCTION__, __LINE__, path.c_str()); + + // printf("Line: %d techTree = %s forceLoad = %d path = + // %s\n",__LINE__,techTree.c_str(),forceLoad,path.c_str()); + + if (fileExists(path)) { + foundTranslation = true; + if (forceLoad == true || + path != techTreeStringsAllLanguages[techTree][default_language] + .getpath()) { + // printf("Line: %d techTree = %s forceLoad = %d path = + // %s\n",__LINE__,techTree.c_str(),forceLoad,path.c_str()); + + techTreeStringsAllLanguages[techTree][default_language].load(path); + techNameLoaded = techTree; + } else if (path == techTreeStringsAllLanguages[techTree][default_language] + .getpath() && + techTree != techNameLoaded) { + techNameLoaded = techTree; + } + } + } + + if (fileExists(pathDefault)) { + foundTranslation = true; + string default_language = "default"; + + // printf("Line: %d techTree = %s forceLoad = %d default_language = + // %s\n",__LINE__,techTree.c_str(),forceLoad,default_language.c_str()); + + if (forceLoad == true || + pathDefault != + techTreeStringsAllLanguages[techTree][default_language].getpath()) { + // printf("Line: %d techTree = %s forceLoad = %d pathDefault = + // %s\n",__LINE__,techTree.c_str(),forceLoad,pathDefault.c_str()); + + techTreeStringsAllLanguages[techTree][default_language].load(pathDefault); + techNameLoaded = techTree; + } else if (pathDefault == + techTreeStringsAllLanguages[techTree][default_language] + .getpath() && + techTree != techNameLoaded) { + techNameLoaded = techTree; + } + } + + return foundTranslation; } void Lang::loadTilesetStrings(string tileset) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] tileset = [%s]\n",__FILE__,__FUNCTION__,__LINE__,tileset.c_str()); - - string currentPath = ""; - Config &config = Config::getInstance(); - vector tilesetPaths = config.getPathListForType(ptTilesets); - for(int idx = 0; idx < (int)tilesetPaths.size(); idx++) { - string &tilesetPath = tilesetPaths[idx]; - endPathWithSlash(tilesetPath); - - //printf("tilesetPath [%s]\n",tilesetPath.c_str()); - - if(folderExists(tilesetPath + tileset) == true) { - currentPath = tilesetPath; - endPathWithSlash(currentPath); - break; - } - } - - string tilesetFolder = currentPath + tileset + "/"; - string path = tilesetFolder + "lang/" + tileset + "_" + language + ".lng"; - string pathDefault = tilesetFolder + "lang/" + tileset + "_default.lng"; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] path = [%s] pathDefault = [%s]\n",__FILE__,__FUNCTION__,__LINE__,path.c_str(),pathDefault.c_str()); - - tilesetStrings.clear(); - tilesetStringsDefault.clear(); - - //try to load the current language first - if(fileExists(path)) { - tilesetStrings.load(path); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] path not found [%s]\n",__FILE__,__FUNCTION__,__LINE__,path.c_str()); - - //try english otherwise - path = tilesetFolder + "lang/" + tileset + "_english.lng"; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] path = [%s]\n",__FILE__,__FUNCTION__,__LINE__,path.c_str()); - - if(fileExists(path)) { - tilesetStrings.load(path); - } - } - - if(fileExists(pathDefault)) { - tilesetStringsDefault.load(pathDefault); - } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] tileset = [%s]\n", __FILE__, + __FUNCTION__, __LINE__, tileset.c_str()); + + string currentPath = ""; + Config &config = Config::getInstance(); + vector tilesetPaths = config.getPathListForType(ptTilesets); + for (int idx = 0; idx < (int)tilesetPaths.size(); idx++) { + string &tilesetPath = tilesetPaths[idx]; + endPathWithSlash(tilesetPath); + + // printf("tilesetPath [%s]\n",tilesetPath.c_str()); + + if (folderExists(tilesetPath + tileset) == true) { + currentPath = tilesetPath; + endPathWithSlash(currentPath); + break; + } + } + + string tilesetFolder = currentPath + tileset + "/"; + string path = tilesetFolder + "lang/" + tileset + "_" + language + ".lng"; + string pathDefault = tilesetFolder + "lang/" + tileset + "_default.lng"; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] path = [%s] pathDefault = [%s]\n", __FILE__, + __FUNCTION__, __LINE__, path.c_str(), pathDefault.c_str()); + + tilesetStrings.clear(); + tilesetStringsDefault.clear(); + + // try to load the current language first + if (fileExists(path)) { + tilesetStrings.load(path); + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] path not found [%s]\n", + __FILE__, __FUNCTION__, __LINE__, path.c_str()); + + // try english otherwise + path = tilesetFolder + "lang/" + tileset + "_english.lng"; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] path = [%s]\n", __FILE__, + __FUNCTION__, __LINE__, path.c_str()); + + if (fileExists(path)) { + tilesetStrings.load(path); + } + } + + if (fileExists(pathDefault)) { + tilesetStringsDefault.load(pathDefault); + } } -bool Lang::hasString(const string &s, string uselanguage, bool fallbackToDefault) { - bool result = false; - try { - if(uselanguage != "") { - //printf("#a fallbackToDefault = %d [%s] uselanguage [%s] DEFAULT_LANGUAGE [%s] this->language [%s]\n",fallbackToDefault,s.c_str(),uselanguage.c_str(),DEFAULT_LANGUAGE,this->language.c_str()); - if(gameStringsAllLanguages.find(uselanguage) == gameStringsAllLanguages.end()) { - loadGameStringProperties(uselanguage, gameStringsAllLanguages[uselanguage], false); - } - //string result2 = otherLanguageStrings[uselanguage].getString(s); - gameStringsAllLanguages[uselanguage].getString(s); - //printf("#b result2 [%s]\n",result2.c_str()); - - result = true; - } - else { - //string result2 = strings.getString(s); - gameStringsAllLanguages[this->language].getString(s); - result = true; - } - } - catch(exception &ex) { - if(gameStringsAllLanguages[this->language].getpath() != "") { - if(SystemFlags::VERBOSE_MODE_ENABLED) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s] for uselanguage [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what(),uselanguage.c_str()); - } - - //printf("#1 fallbackToDefault = %d [%s] uselanguage [%s] DEFAULT_LANGUAGE [%s] this->language [%s]\n",fallbackToDefault,s.c_str(),uselanguage.c_str(),DEFAULT_LANGUAGE,this->language.c_str()); - if(fallbackToDefault == true && uselanguage != DEFAULT_LANGUAGE && this->language != DEFAULT_LANGUAGE) { - result = hasString(s, DEFAULT_LANGUAGE, false); - } - else { - - } - } - return result; +bool Lang::hasString(const string &s, string uselanguage, + bool fallbackToDefault) { + bool result = false; + try { + if (uselanguage != "") { + // printf("#a fallbackToDefault = %d [%s] uselanguage [%s] + // DEFAULT_LANGUAGE [%s] this->language + // [%s]\n",fallbackToDefault,s.c_str(),uselanguage.c_str(),DEFAULT_LANGUAGE,this->language.c_str()); + if (gameStringsAllLanguages.find(uselanguage) == + gameStringsAllLanguages.end()) { + loadGameStringProperties(uselanguage, + gameStringsAllLanguages[uselanguage], false); + } + // string result2 = otherLanguageStrings[uselanguage].getString(s); + gameStringsAllLanguages[uselanguage].getString(s); + // printf("#b result2 [%s]\n",result2.c_str()); + + result = true; + } else { + // string result2 = strings.getString(s); + gameStringsAllLanguages[this->language].getString(s); + result = true; + } + } catch (exception &ex) { + if (gameStringsAllLanguages[this->language].getpath() != "") { + if (SystemFlags::VERBOSE_MODE_ENABLED) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s] for uselanguage [%s]\n", __FILE__, + __FUNCTION__, __LINE__, ex.what(), uselanguage.c_str()); + } + + // printf("#1 fallbackToDefault = %d [%s] uselanguage [%s] DEFAULT_LANGUAGE + // [%s] this->language + // [%s]\n",fallbackToDefault,s.c_str(),uselanguage.c_str(),DEFAULT_LANGUAGE,this->language.c_str()); + if (fallbackToDefault == true && uselanguage != DEFAULT_LANGUAGE && + this->language != DEFAULT_LANGUAGE) { + result = hasString(s, DEFAULT_LANGUAGE, false); + } else { + } + } + return result; } bool Lang::isLanguageLocal(string compareLanguage) const { - return (compareLanguage == language); + return (compareLanguage == language); } string Lang::parseResult(const string &key, const string &value) { - if(value != "$USE_DEFAULT_LANGUAGE_VALUE") { - return value; - } - string result = Lang::getString(key, DEFAULT_LANGUAGE); - return result; + if (value != "$USE_DEFAULT_LANGUAGE_VALUE") { + return value; + } + string result = Lang::getString(key, DEFAULT_LANGUAGE); + return result; } -string Lang::getString(const string &s, string uselanguage, bool fallbackToDefault) { - try { - string result = ""; - - if(uselanguage != "") { - if(gameStringsAllLanguages.find(uselanguage) == gameStringsAllLanguages.end()) { - loadGameStringProperties(uselanguage, gameStringsAllLanguages[uselanguage], false); - } - result = gameStringsAllLanguages[uselanguage].getString(s); - replaceAll(result, "\\n", "\n"); - } - else { - result = gameStringsAllLanguages[this->language].getString(s); - replaceAll(result, "\\n", "\n"); - } - - return parseResult(s, result);; - } - catch(exception &ex) { - if(gameStringsAllLanguages[this->language].getpath() != "") { - if(fallbackToDefault == false || SystemFlags::VERBOSE_MODE_ENABLED) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s] uselanguage [%s] text [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what(),uselanguage.c_str(),s.c_str()); - } - } - } - - //printf("#2 fallbackToDefault = %d [%s] uselanguage [%s] DEFAULT_LANGUAGE [%s] this->language [%s]\n",fallbackToDefault,s.c_str(),uselanguage.c_str(),DEFAULT_LANGUAGE,this->language.c_str()); - - //if(fallbackToDefault == true && uselanguage != DEFAULT_LANGUAGE && this->language != DEFAULT_LANGUAGE) { - if( uselanguage != DEFAULT_LANGUAGE && this->language != DEFAULT_LANGUAGE) { - return getString(s, DEFAULT_LANGUAGE, false); - } - - //return "???" + s + "???"; - } - return "???" + s + "???"; +string Lang::getString(const string &s, string uselanguage, + bool fallbackToDefault) { + try { + string result = ""; + + if (uselanguage != "") { + if (gameStringsAllLanguages.find(uselanguage) == + gameStringsAllLanguages.end()) { + loadGameStringProperties(uselanguage, + gameStringsAllLanguages[uselanguage], false); + } + result = gameStringsAllLanguages[uselanguage].getString(s); + replaceAll(result, "\\n", "\n"); + } else { + result = gameStringsAllLanguages[this->language].getString(s); + replaceAll(result, "\\n", "\n"); + } + + return parseResult(s, result); + ; + } catch (exception &ex) { + if (gameStringsAllLanguages[this->language].getpath() != "") { + if (fallbackToDefault == false || SystemFlags::VERBOSE_MODE_ENABLED) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s] uselanguage [%s] text [%s]\n", + __FILE__, __FUNCTION__, __LINE__, ex.what(), + uselanguage.c_str(), s.c_str()); + } + } + } + + // printf("#2 fallbackToDefault = %d [%s] uselanguage [%s] DEFAULT_LANGUAGE + // [%s] this->language + // [%s]\n",fallbackToDefault,s.c_str(),uselanguage.c_str(),DEFAULT_LANGUAGE,this->language.c_str()); + + // if(fallbackToDefault == true && uselanguage != DEFAULT_LANGUAGE && + // this->language != DEFAULT_LANGUAGE) { + if (uselanguage != DEFAULT_LANGUAGE && this->language != DEFAULT_LANGUAGE) { + return getString(s, DEFAULT_LANGUAGE, false); + } + + // return "???" + s + "???"; + } + return "???" + s + "???"; } string Lang::getScenarioString(const string &s) { - try{ - string result = scenarioStrings.getString(s); - replaceAll(result, "\\n", "\n"); - return result; - } - catch(exception &ex) { - if(scenarioStrings.getpath() != "") { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - } - return "???" + s + "???"; - } + try { + string result = scenarioStrings.getString(s); + replaceAll(result, "\\n", "\n"); + return result; + } catch (exception &ex) { + if (scenarioStrings.getpath() != "") { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", __FILE__, + __FUNCTION__, __LINE__, ex.what()); + } + return "???" + s + "???"; + } } bool Lang::hasScenarioString(const string &s) { - bool result = false; - try { - scenarioStrings.getString(s); - result = true; - } - catch(exception &ex) { - if(scenarioStrings.getpath() != "") { - if(SystemFlags::VERBOSE_MODE_ENABLED) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - } - } - return result; + bool result = false; + try { + scenarioStrings.getString(s); + result = true; + } catch (exception &ex) { + if (scenarioStrings.getpath() != "") { + if (SystemFlags::VERBOSE_MODE_ENABLED) + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", __FILE__, + __FUNCTION__, __LINE__, ex.what()); + } + } + return result; } -string Lang::getTechTreeString(const string &s,const char *defaultValue) { - try{ - string result = ""; - string default_language = "default"; - - //printf("Line: %d techNameLoaded = %s s = %s this->language = %s\n",__LINE__,techNameLoaded.c_str(),s.c_str(),this->language.c_str()); - - if(allowNativeLanguageTechtree == true && - (techTreeStringsAllLanguages[techNameLoaded][this->language].hasString(s) == true || - defaultValue == NULL)) { - if(techTreeStringsAllLanguages[techNameLoaded][this->language].hasString(s) == false && - techTreeStringsAllLanguages[techNameLoaded][default_language].hasString(s) == true) { - - //printf("Line: %d techNameLoaded = %s s = %s this->language = %s\n",__LINE__,techNameLoaded.c_str(),s.c_str(),this->language.c_str()); - - result = techTreeStringsAllLanguages[techNameLoaded][default_language].getString(s); - } - else { - - //printf("Line: %d techNameLoaded = %s s = %s this->language = %s\n",__LINE__,techNameLoaded.c_str(),s.c_str(),this->language.c_str()); - - result = techTreeStringsAllLanguages[techNameLoaded][this->language].getString(s); - } - } - else if(allowNativeLanguageTechtree == true && - techTreeStringsAllLanguages[techNameLoaded][default_language].hasString(s) == true) { - - //printf("Line: %d techNameLoaded = %s s = %s this->language = %s\n",__LINE__,techNameLoaded.c_str(),s.c_str(),this->language.c_str()); - - result = techTreeStringsAllLanguages[techNameLoaded][default_language].getString(s); - } - else if(defaultValue != NULL) { - result = defaultValue; - } - replaceAll(result, "\\n", "\n"); - return result; - } - catch(exception &ex) { - if(techTreeStringsAllLanguages[techNameLoaded][this->language].getpath() != "") { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - } - //return "???" + s + "???"; - } - return "???" + s + "???"; +string Lang::getTechTreeString(const string &s, const char *defaultValue) { + try { + string result = ""; + string default_language = "default"; + + // printf("Line: %d techNameLoaded = %s s = %s this->language = + // %s\n",__LINE__,techNameLoaded.c_str(),s.c_str(),this->language.c_str()); + + if (allowNativeLanguageTechtree == true && + (techTreeStringsAllLanguages[techNameLoaded][this->language].hasString( + s) == true || + defaultValue == NULL)) { + if (techTreeStringsAllLanguages[techNameLoaded][this->language].hasString( + s) == false && + techTreeStringsAllLanguages[techNameLoaded][default_language] + .hasString(s) == true) { + + // printf("Line: %d techNameLoaded = %s s = %s this->language = + // %s\n",__LINE__,techNameLoaded.c_str(),s.c_str(),this->language.c_str()); + + result = techTreeStringsAllLanguages[techNameLoaded][default_language] + .getString(s); + } else { + + // printf("Line: %d techNameLoaded = %s s = %s this->language = + // %s\n",__LINE__,techNameLoaded.c_str(),s.c_str(),this->language.c_str()); + + result = techTreeStringsAllLanguages[techNameLoaded][this->language] + .getString(s); + } + } else if (allowNativeLanguageTechtree == true && + techTreeStringsAllLanguages[techNameLoaded][default_language] + .hasString(s) == true) { + + // printf("Line: %d techNameLoaded = %s s = %s this->language = + // %s\n",__LINE__,techNameLoaded.c_str(),s.c_str(),this->language.c_str()); + + result = techTreeStringsAllLanguages[techNameLoaded][default_language] + .getString(s); + } else if (defaultValue != NULL) { + result = defaultValue; + } + replaceAll(result, "\\n", "\n"); + return result; + } catch (exception &ex) { + if (techTreeStringsAllLanguages[techNameLoaded][this->language].getpath() != + "") { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", __FILE__, + __FUNCTION__, __LINE__, ex.what()); + } + // return "???" + s + "???"; + } + return "???" + s + "???"; } -string Lang::getTilesetString(const string &s,const char *defaultValue) { - try{ - string result = ""; - - if(tilesetStrings.hasString(s) == true || defaultValue == NULL) { - if(tilesetStrings.hasString(s) == false && tilesetStringsDefault.hasString(s) == true) { - result = tilesetStringsDefault.getString(s); - } - else { - result = tilesetStrings.getString(s); - } - } - else if(tilesetStringsDefault.hasString(s) == true) { - result = tilesetStringsDefault.getString(s); - } - else if(defaultValue != NULL) { - result = defaultValue; - } - replaceAll(result, "\\n", "\n"); - return result; - } - catch(exception &ex) { - if(tilesetStrings.getpath() != "") { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - } - //return "???" + s + "???"; - } - return "???" + s + "???"; +string Lang::getTilesetString(const string &s, const char *defaultValue) { + try { + string result = ""; + + if (tilesetStrings.hasString(s) == true || defaultValue == NULL) { + if (tilesetStrings.hasString(s) == false && + tilesetStringsDefault.hasString(s) == true) { + result = tilesetStringsDefault.getString(s); + } else { + result = tilesetStrings.getString(s); + } + } else if (tilesetStringsDefault.hasString(s) == true) { + result = tilesetStringsDefault.getString(s); + } else if (defaultValue != NULL) { + result = defaultValue; + } + replaceAll(result, "\\n", "\n"); + return result; + } catch (exception &ex) { + if (tilesetStrings.getpath() != "") { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", __FILE__, + __FUNCTION__, __LINE__, ex.what()); + } + // return "???" + s + "???"; + } + return "???" + s + "???"; } bool Lang::fileMatchesISO630Code(string uselanguage, string testLanguageFile) { - bool result = false; - Properties stringsTest; - stringsTest.load(testLanguageFile); - - try { - string iso639 = stringsTest.getString("ISO639-1"); - if(iso639 == uselanguage) { - result = true; - } - } - //catch(const exception &ex) { - catch(...) { - } - - return result; + bool result = false; + Properties stringsTest; + stringsTest.load(testLanguageFile); + + try { + string iso639 = stringsTest.getString("ISO639-1"); + if (iso639 == uselanguage) { + result = true; + } + } + // catch(const exception &ex) { + catch (...) { + } + + return result; } string Lang::getLanguageFile(string uselanguage) { - bool foundMatch = false; - string result = uselanguage; - - string data_path = getGameReadWritePath(GameConstants::path_data_CacheLookupKey); - - vector langResults; - string userDataPath = getGameCustomCoreDataPath(data_path, ""); - findAll(userDataPath + "data/lang/*.lng", langResults, true, false); - for(unsigned int i = 0; i < langResults.size() && foundMatch == false ; ++i) { - string testLanguageFile = userDataPath + "data/lang/" + langResults[i] + ".lng"; - foundMatch = fileMatchesISO630Code(uselanguage, testLanguageFile); - if(foundMatch == true) { - result = langResults[i]; - } - } - if(foundMatch == false) { - langResults.clear(); - findAll(data_path + "data/lang/*.lng", langResults, true); - for(unsigned int i = 0; i < langResults.size() && foundMatch == false ; ++i) { - string testLanguageFile = data_path + "data/lang/" + langResults[i] + ".lng"; - foundMatch = fileMatchesISO630Code(uselanguage, testLanguageFile); - if(foundMatch == true) { - result = langResults[i]; - } - } - } - return result; + bool foundMatch = false; + string result = uselanguage; + + string data_path = + getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + + vector langResults; + string userDataPath = getGameCustomCoreDataPath(data_path, ""); + findAll(userDataPath + "data/lang/*.lng", langResults, true, false); + for (unsigned int i = 0; i < langResults.size() && foundMatch == false; ++i) { + string testLanguageFile = + userDataPath + "data/lang/" + langResults[i] + ".lng"; + foundMatch = fileMatchesISO630Code(uselanguage, testLanguageFile); + if (foundMatch == true) { + result = langResults[i]; + } + } + if (foundMatch == false) { + langResults.clear(); + findAll(data_path + "data/lang/*.lng", langResults, true); + for (unsigned int i = 0; i < langResults.size() && foundMatch == false; + ++i) { + string testLanguageFile = + data_path + "data/lang/" + langResults[i] + ".lng"; + foundMatch = fileMatchesISO630Code(uselanguage, testLanguageFile); + if (foundMatch == true) { + result = langResults[i]; + } + } + } + return result; } -string Lang::getNativeLanguageName(string uselanguage, string testLanguageFile) { - string result = uselanguage; - - static map cachedNativeLanguageNames; - if(cachedNativeLanguageNames.find(testLanguageFile) != cachedNativeLanguageNames.end()) { - result = cachedNativeLanguageNames[testLanguageFile]; - } - else { - Properties stringsTest; - stringsTest.load(testLanguageFile); - - try { - result = stringsTest.getString("NativeLanguageName"); - cachedNativeLanguageNames[testLanguageFile] = result; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Caching native language name for [%s] = [%s]\n",testLanguageFile.c_str(),result.c_str()); - } - catch(const exception &ex) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("ERROR Caching native language name for [%s] msg: [%s]\n",testLanguageFile.c_str(),ex.what()); - } - catch(...) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("ERROR Caching native language name for [%s] msg: [UNKNOWN]\n",testLanguageFile.c_str()); - } - } - - return result; +string Lang::getNativeLanguageName(string uselanguage, + string testLanguageFile) { + string result = uselanguage; + + static map cachedNativeLanguageNames; + if (cachedNativeLanguageNames.find(testLanguageFile) != + cachedNativeLanguageNames.end()) { + result = cachedNativeLanguageNames[testLanguageFile]; + } else { + Properties stringsTest; + stringsTest.load(testLanguageFile); + + try { + result = stringsTest.getString("NativeLanguageName"); + cachedNativeLanguageNames[testLanguageFile] = result; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Caching native language name for [%s] = [%s]\n", + testLanguageFile.c_str(), result.c_str()); + } catch (const exception &ex) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("ERROR Caching native language name for [%s] msg: [%s]\n", + testLanguageFile.c_str(), ex.what()); + } catch (...) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("ERROR Caching native language name for [%s] msg: [UNKNOWN]\n", + testLanguageFile.c_str()); + } + } + + return result; } -pair Lang::getNavtiveNameFromLanguageName(string langName) { - pair result; +pair Lang::getNavtiveNameFromLanguageName(string langName) { + pair result; - //printf("looking for language [%s]\n",langName.c_str()); + // printf("looking for language [%s]\n",langName.c_str()); - map nativeList = Lang::getDiscoveredLanguageList(true); - map::iterator iterMap = nativeList.find(langName); - if(iterMap != nativeList.end()) { - result = make_pair(iterMap->second,iterMap->first); - } - return result; + map nativeList = Lang::getDiscoveredLanguageList(true); + map::iterator iterMap = nativeList.find(langName); + if (iterMap != nativeList.end()) { + result = make_pair(iterMap->second, iterMap->first); + } + return result; } -map Lang::getDiscoveredLanguageList(bool searchKeyIsLangName) { - map result; - - string data_path = getGameReadWritePath(GameConstants::path_data_CacheLookupKey); - string userDataPath = getGameCustomCoreDataPath(data_path, ""); - - vector langResults; - findAll(userDataPath + "data/lang/*.lng", langResults, true, false); - for(unsigned int i = 0; i < langResults.size(); ++i) { - string testLanguage = langResults[i]; - string testLanguageFile = userDataPath + "data/lang/" + testLanguage + ".lng"; - string nativeName = getNativeLanguageName(testLanguage, testLanguageFile); - if(searchKeyIsLangName == false) { - result[nativeName] = testLanguage; - } - else { - result[testLanguage] = nativeName; - } - } - - vector langResults2; - findAll(data_path + "data/lang/*.lng", langResults2, true); - if(langResults2.empty() && langResults.empty()) { - throw megaglest_runtime_error("There are no lang files"); - } - for(unsigned int i = 0; i < langResults2.size(); ++i) { - string testLanguage = langResults2[i]; - if(std::find(langResults.begin(),langResults.end(),testLanguage) == langResults.end()) { - langResults.push_back(testLanguage); - - string testLanguageFile = data_path + "data/lang/" + testLanguage + ".lng"; - string nativeName = getNativeLanguageName(testLanguage, testLanguageFile); - if(searchKeyIsLangName == false) { - result[nativeName] = testLanguage; - } - else { - result[testLanguage] = nativeName; - } - } - } - - return result; +map Lang::getDiscoveredLanguageList(bool searchKeyIsLangName) { + map result; + + string data_path = + getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + string userDataPath = getGameCustomCoreDataPath(data_path, ""); + + vector langResults; + findAll(userDataPath + "data/lang/*.lng", langResults, true, false); + for (unsigned int i = 0; i < langResults.size(); ++i) { + string testLanguage = langResults[i]; + string testLanguageFile = + userDataPath + "data/lang/" + testLanguage + ".lng"; + string nativeName = getNativeLanguageName(testLanguage, testLanguageFile); + if (searchKeyIsLangName == false) { + result[nativeName] = testLanguage; + } else { + result[testLanguage] = nativeName; + } + } + + vector langResults2; + findAll(data_path + "data/lang/*.lng", langResults2, true); + if (langResults2.empty() && langResults.empty()) { + throw megaglest_runtime_error("There are no lang files"); + } + for (unsigned int i = 0; i < langResults2.size(); ++i) { + string testLanguage = langResults2[i]; + if (std::find(langResults.begin(), langResults.end(), testLanguage) == + langResults.end()) { + langResults.push_back(testLanguage); + + string testLanguageFile = + data_path + "data/lang/" + testLanguage + ".lng"; + string nativeName = getNativeLanguageName(testLanguage, testLanguageFile); + if (searchKeyIsLangName == false) { + result[nativeName] = testLanguage; + } else { + result[testLanguage] = nativeName; + } + } + } + + return result; } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/global/lang.h b/source/glest_game/global/lang.h index 3b153ea2a..266329c57 100644 --- a/source/glest_game/global/lang.h +++ b/source/glest_game/global/lang.h @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,14 +13,15 @@ #define _GLEST_GAME_LANG_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include "properties.h" #include "leak_dumper.h" +#include "properties.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { using Shared::Util::Properties; @@ -32,60 +33,71 @@ using Shared::Util::Properties; class Lang { private: + bool is_utf8_language; + string language; + std::map gameStringsAllLanguages; - bool is_utf8_language; - string language; - std::map gameStringsAllLanguages; - - Properties scenarioStrings; + Properties scenarioStrings; - Properties tilesetStrings; - Properties tilesetStringsDefault; + Properties tilesetStrings; + Properties tilesetStringsDefault; - std::map > techTreeStringsAllLanguages; - string techNameLoaded; - bool allowNativeLanguageTechtree; + std::map> techTreeStringsAllLanguages; + string techNameLoaded; + bool allowNativeLanguageTechtree; private: - Lang(); - void loadGameStringProperties(string language, Properties &properties, bool fileMustExist,bool fallbackToDefault=false); - bool fileMatchesISO630Code(string uselanguage, string testLanguageFile); - string getNativeLanguageName(string uselanguage, string testLanguageFile); + Lang(); + void loadGameStringProperties(string language, Properties &properties, + bool fileMustExist, + bool fallbackToDefault = false); + bool fileMatchesISO630Code(string uselanguage, string testLanguageFile); + string getNativeLanguageName(string uselanguage, string testLanguageFile); - string parseResult(const string &key, const string &value); + string parseResult(const string &key, const string &value); public: - static Lang &getInstance(); - - string getTechNameLoaded() const { return techNameLoaded; } - bool getAllowNativeLanguageTechtree() const { return allowNativeLanguageTechtree; } - void setAllowNativeLanguageTechtree(bool value) { allowNativeLanguageTechtree = value; } - - void loadGameStrings(string uselanguage, bool loadFonts=true, bool fallbackToDefault=false); - void loadScenarioStrings(string scenarioDir, string scenarioName, bool isTutorial); - bool loadTechTreeStrings(string techTree, bool forceLoad=false); - void loadTilesetStrings(string tileset); - - string getString(const string &s,string uselanguage="", bool fallbackToDefault=false); - bool hasString(const string &s, string uselanguage="", bool fallbackToDefault=false); - - string getScenarioString(const string &s); - bool hasScenarioString(const string &s); - - string getTechTreeString(const string &s, const char *defaultValue=NULL); - string getTilesetString(const string &s, const char *defaultValue=NULL); - - string getLanguage() const { return language; } - bool isLanguageLocal(string compareLanguage) const; - //bool isUTF8Language() const; - string getDefaultLanguage() const; - - map getDiscoveredLanguageList(bool searchKeyIsLangName=false); - pair getNavtiveNameFromLanguageName(string langName); - - string getLanguageFile(string uselanguage); + static Lang &getInstance(); + + string getTechNameLoaded() const { return techNameLoaded; } + bool getAllowNativeLanguageTechtree() const { + return allowNativeLanguageTechtree; + } + void setAllowNativeLanguageTechtree(bool value) { + allowNativeLanguageTechtree = value; + } + + void loadGameStrings(string uselanguage, bool loadFonts = true, + bool fallbackToDefault = false); + void loadScenarioStrings(string scenarioDir, string scenarioName, + bool isTutorial); + bool loadTechTreeStrings(string techTree, bool forceLoad = false); + void loadTilesetStrings(string tileset); + + string getString(const string &s, string uselanguage = "", + bool fallbackToDefault = false); + bool hasString(const string &s, string uselanguage = "", + bool fallbackToDefault = false); + + string getScenarioString(const string &s); + bool hasScenarioString(const string &s); + + string getTechTreeString(const string &s, const char *defaultValue = NULL); + string getTilesetString(const string &s, const char *defaultValue = NULL); + + string getLanguage() const { return language; } + bool isLanguageLocal(string compareLanguage) const; + // bool isUTF8Language() const; + string getDefaultLanguage() const; + + map + getDiscoveredLanguageList(bool searchKeyIsLangName = false); + pair getNavtiveNameFromLanguageName(string langName); + + string getLanguageFile(string uselanguage); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/global/metrics.cpp b/source/glest_game/global/metrics.cpp index 15bbae3e5..a1031df7e 100644 --- a/source/glest_game/global/metrics.cpp +++ b/source/glest_game/global/metrics.cpp @@ -3,113 +3,105 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== -#include "metrics.h" -#include -#include "platform_util.h" +#include "metrics.h" #include "leak_dumper.h" +#include "platform_util.h" +#include using namespace std; -namespace Glest{ namespace Game{ - +namespace Glest { +namespace Game { // ===================================================== // class Metrics // ===================================================== -Metrics::Metrics() { - reloadData(); -} +Metrics::Metrics() { reloadData(); } void Metrics::reload(int resWidth, int resHeight) { - Metrics *metrics = getInstancePtr(); - metrics->reloadData(resWidth, resHeight); + Metrics *metrics = getInstancePtr(); + metrics->reloadData(resWidth, resHeight); } void Metrics::reloadData(int resWidth, int resHeight) { - Config &config = Config::getInstance(); - - virtualW= 1000; - virtualH= 750; - - if(resWidth > 0) { - screenW= resWidth; - } - else { - screenW= config.getInt("ScreenWidth"); - } - if(resHeight > 0) { - screenH= resHeight; - } - else { - screenH= config.getInt("ScreenHeight"); - } - - minimapX= 10; - minimapY= 750-128-30+16; - minimapW= 128; - minimapH= 128; - - displayX= 800; - displayY= 250; - displayW= 128; - displayH= 480; + Config &config = Config::getInstance(); + + virtualW = 1000; + virtualH = 750; + + if (resWidth > 0) { + screenW = resWidth; + } else { + screenW = config.getInt("ScreenWidth"); + } + if (resHeight > 0) { + screenH = resHeight; + } else { + screenH = config.getInt("ScreenHeight"); + } + + minimapX = 10; + minimapY = 750 - 128 - 30 + 16; + minimapW = 128; + minimapH = 128; + + displayX = 800; + displayY = 250; + displayW = 128; + displayH = 480; } -Metrics * Metrics::getInstancePtr() { - static Metrics metrics; - return &metrics; +Metrics *Metrics::getInstancePtr() { + static Metrics metrics; + return &metrics; } -const Metrics &Metrics::getInstance(){ - Metrics *metrics = getInstancePtr(); - return *metrics; +const Metrics &Metrics::getInstance() { + Metrics *metrics = getInstancePtr(); + return *metrics; } -float Metrics::getAspectRatio() const{ - if(screenH == 0) { - throw megaglest_runtime_error("div by 0 screenH == 0"); - } - return static_cast(screenW)/screenH; +float Metrics::getAspectRatio() const { + if (screenH == 0) { + throw megaglest_runtime_error("div by 0 screenH == 0"); + } + return static_cast(screenW) / screenH; } -int Metrics::toVirtualX(int w) const{ - if(screenW == 0) { - throw megaglest_runtime_error("div by 0 screenW == 0"); - } - return w*virtualW/screenW; +int Metrics::toVirtualX(int w) const { + if (screenW == 0) { + throw megaglest_runtime_error("div by 0 screenW == 0"); + } + return w * virtualW / screenW; } -int Metrics::toVirtualY(int h) const{ - if(screenH == 0) { - throw megaglest_runtime_error("div by 0 screenH == 0"); - } +int Metrics::toVirtualY(int h) const { + if (screenH == 0) { + throw megaglest_runtime_error("div by 0 screenH == 0"); + } - //printf("h [%d] virtualH [%d] screenH [%d] result = %d\n",h,virtualH,screenH,(h*virtualH/screenH)); + // printf("h [%d] virtualH [%d] screenH [%d] result = + // %d\n",h,virtualH,screenH,(h*virtualH/screenH)); - return h*virtualH/screenH; + return h * virtualH / screenH; } -bool Metrics::isInDisplay(int x, int y) const{ - return - x > displayX && - y > displayY && - x < displayX+displayW && - y < displayY+displayH; +bool Metrics::isInDisplay(int x, int y) const { + return x > displayX && y > displayY && x < displayX + displayW && + y < displayY + displayH; } -bool Metrics::isInMinimap(int x, int y) const{ - return - x > minimapX && - y > minimapY && - x < minimapX+minimapW && - y < minimapY+minimapH; +bool Metrics::isInMinimap(int x, int y) const { + return x > minimapX && y > minimapY && x < minimapX + minimapW && + y < minimapY + minimapH; } -}}// end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/global/metrics.h b/source/glest_game/global/metrics.h index 08eba250d..2d6188e30 100644 --- a/source/glest_game/global/metrics.h +++ b/source/glest_game/global/metrics.h @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,65 +13,67 @@ #define _GLEST_GAME_METRICS_H_ #ifdef WIN32 - #include - #include +#include +#include #endif #include "config.h" #include "leak_dumper.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class Metrics // ===================================================== -class Metrics{ +class Metrics { private: - int virtualW; - int virtualH; - int screenW; - int screenH; - int minimapX; - int minimapY; - int minimapW; - int minimapH; - int displayX; - int displayY; - int displayH; - int displayW; + int virtualW; + int virtualH; + int screenW; + int screenH; + int minimapX; + int minimapY; + int minimapW; + int minimapH; + int displayX; + int displayY; + int displayH; + int displayW; private: - Metrics(); - static Metrics *getInstancePtr(); - void reloadData(int resWidth=-1, int resHeight=-1); + Metrics(); + static Metrics *getInstancePtr(); + void reloadData(int resWidth = -1, int resHeight = -1); public: - static const Metrics &getInstance(); - - int getVirtualW() const {return virtualW;} - int getVirtualH() const {return virtualH;} - int getScreenW() const {return screenW;} - int getScreenH() const {return screenH;} - int getMinimapX() const {return minimapX;} - int getMinimapY() const {return minimapY;} - int getMinimapW() const {return minimapW;} - int getMinimapH() const {return minimapH;} - int getDisplayX() const {return displayX;} - int getDisplayY() const {return displayY;} - int getDisplayH() const {return displayH;} - int getDisplayW() const {return displayW;} - float getAspectRatio() const; - - int toVirtualX(int w) const; - int toVirtualY(int h) const; + static const Metrics &getInstance(); - bool isInDisplay(int x, int y) const; - bool isInMinimap(int x, int y) const; + int getVirtualW() const { return virtualW; } + int getVirtualH() const { return virtualH; } + int getScreenW() const { return screenW; } + int getScreenH() const { return screenH; } + int getMinimapX() const { return minimapX; } + int getMinimapY() const { return minimapY; } + int getMinimapW() const { return minimapW; } + int getMinimapH() const { return minimapH; } + int getDisplayX() const { return displayX; } + int getDisplayY() const { return displayY; } + int getDisplayH() const { return displayH; } + int getDisplayW() const { return displayW; } + float getAspectRatio() const; - static void reload(int resWidth=-1, int resHeight=-1); + int toVirtualX(int w) const; + int toVirtualY(int h) const; + + bool isInDisplay(int x, int y) const; + bool isInMinimap(int x, int y) const; + + static void reload(int resWidth = -1, int resHeight = -1); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/graphics/particle_type.cpp b/source/glest_game/graphics/particle_type.cpp index 12caa3560..618cb4b7e 100644 --- a/source/glest_game/graphics/particle_type.cpp +++ b/source/glest_game/graphics/particle_type.cpp @@ -12,529 +12,621 @@ #include "particle_type.h" #include "unit_particle_type.h" -#include "util.h" -#include "core_data.h" -#include "xml_parser.h" -#include "model.h" #include "config.h" -#include "game_constants.h" -#include "util.h" -#include "platform_common.h" #include "conversion.h" +#include "core_data.h" +#include "game_constants.h" #include "leak_dumper.h" +#include "model.h" +#include "platform_common.h" +#include "util.h" +#include "xml_parser.h" using namespace Shared::Xml; using namespace Shared::Graphics; using namespace Shared::Util; using namespace Shared::PlatformCommon; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class ParticleSystemType // ===================================================== const bool checkMemory = false; -static map memoryObjectList; +static map memoryObjectList; ParticleSystemType::ParticleSystemType() { - if(checkMemory) { - printf("++ Create ParticleSystemType [%p]\n",this); - memoryObjectList[this]++; - } - - teamcolorNoEnergy=false; - teamcolorEnergy=false; - alternations=0; - particleSystemStartDelay=0; - texture=NULL; - model=NULL; - minmaxEnabled=false; - minHp=0; - maxHp=0; - minmaxIsPercent=false; - - modelCycle=0; - size=0; - sizeNoEnergy=0; - speed=0; - speedUpRelative=0; - speedUpConstant=0; - gravity=0; - emissionRate=0; - energyMax=0; - energyVar=0; - + if (checkMemory) { + printf("++ Create ParticleSystemType [%p]\n", this); + memoryObjectList[this]++; + } + + teamcolorNoEnergy = false; + teamcolorEnergy = false; + alternations = 0; + particleSystemStartDelay = 0; + texture = NULL; + model = NULL; + minmaxEnabled = false; + minHp = 0; + maxHp = 0; + minmaxIsPercent = false; + + modelCycle = 0; + size = 0; + sizeNoEnergy = 0; + speed = 0; + speedUpRelative = 0; + speedUpConstant = 0; + gravity = 0; + emissionRate = 0; + energyMax = 0; + energyVar = 0; } ParticleSystemType::ParticleSystemType(const ParticleSystemType &src) { - if(checkMemory) { - printf("++ Create ParticleSystemType #2 [%p]\n",this); - memoryObjectList[this]++; - } + if (checkMemory) { + printf("++ Create ParticleSystemType #2 [%p]\n", this); + memoryObjectList[this]++; + } - copyAll(src); + copyAll(src); } -ParticleSystemType & ParticleSystemType::operator=(const ParticleSystemType &src) { - if(checkMemory) { - printf("++ Create ParticleSystemType #3 [%p]\n",this); - memoryObjectList[this]++; - } +ParticleSystemType & +ParticleSystemType::operator=(const ParticleSystemType &src) { + if (checkMemory) { + printf("++ Create ParticleSystemType #3 [%p]\n", this); + memoryObjectList[this]++; + } - copyAll(src); - return *this; + copyAll(src); + return *this; } ParticleSystemType::~ParticleSystemType() { - if(checkMemory) { - printf("-- Delete ParticleSystemType [%p] type = [%s]\n",this,type.c_str()); - memoryObjectList[this]--; - assert(memoryObjectList[this] == 0); - } - for(Children::iterator it = children.begin(); it != children.end(); ++it) { - delete *it; - } - children.clear(); + if (checkMemory) { + printf("-- Delete ParticleSystemType [%p] type = [%s]\n", this, + type.c_str()); + memoryObjectList[this]--; + assert(memoryObjectList[this] == 0); + } + for (Children::iterator it = children.begin(); it != children.end(); ++it) { + delete *it; + } + children.clear(); } void ParticleSystemType::copyAll(const ParticleSystemType &src) { - this->type = src.type; - this->texture = src.texture; - this->model = src.model; - this->modelCycle = src.modelCycle; - this->primitive = src.primitive; - this->offset = src.offset; - this->color = src.color; - this->colorNoEnergy = src.colorNoEnergy; - this->size = src.size; - this->sizeNoEnergy = src.sizeNoEnergy; - this->speed = src.speed; - this->speedUpRelative = src.speedUpRelative; - this->speedUpConstant = src.speedUpConstant; - this->gravity = src.gravity; - this->emissionRate = src.emissionRate; - this->energyMax = src.energyMax; - this->energyVar = src.energyVar; - this->mode = src.mode; - this->teamcolorNoEnergy = src.teamcolorNoEnergy; - this->teamcolorEnergy = src.teamcolorEnergy; - this->alternations = src.alternations; - this->particleSystemStartDelay= src.particleSystemStartDelay; - for(Children::iterator it = children.begin(); it != children.end(); ++it) { - UnitParticleSystemType *child = *it; - - // Deep copy the child particles - UnitParticleSystemType *newCopy = new UnitParticleSystemType(); - *newCopy = *child; - children.push_back(newCopy); - } - - this->minmaxEnabled = src.minmaxEnabled; - this->minHp = src.minHp; - this->maxHp = src.maxHp; - this->minmaxIsPercent = src.minmaxIsPercent; + this->type = src.type; + this->texture = src.texture; + this->model = src.model; + this->modelCycle = src.modelCycle; + this->primitive = src.primitive; + this->offset = src.offset; + this->color = src.color; + this->colorNoEnergy = src.colorNoEnergy; + this->size = src.size; + this->sizeNoEnergy = src.sizeNoEnergy; + this->speed = src.speed; + this->speedUpRelative = src.speedUpRelative; + this->speedUpConstant = src.speedUpConstant; + this->gravity = src.gravity; + this->emissionRate = src.emissionRate; + this->energyMax = src.energyMax; + this->energyVar = src.energyVar; + this->mode = src.mode; + this->teamcolorNoEnergy = src.teamcolorNoEnergy; + this->teamcolorEnergy = src.teamcolorEnergy; + this->alternations = src.alternations; + this->particleSystemStartDelay = src.particleSystemStartDelay; + for (Children::iterator it = children.begin(); it != children.end(); ++it) { + UnitParticleSystemType *child = *it; + + // Deep copy the child particles + UnitParticleSystemType *newCopy = new UnitParticleSystemType(); + *newCopy = *child; + children.push_back(newCopy); + } + + this->minmaxEnabled = src.minmaxEnabled; + this->minHp = src.minHp; + this->maxHp = src.maxHp; + this->minmaxIsPercent = src.minmaxIsPercent; } -void ParticleSystemType::load(const XmlNode *particleSystemNode, const string &dir, - RendererInterface *renderer, std::map > > &loadedFileList, - string parentLoader, string techtreePath) { - - //texture - const XmlNode *textureNode= particleSystemNode->getChild("texture"); - bool textureEnabled= textureNode->getAttribute("value")->getBoolValue(); - - if(textureEnabled){ - texture= renderer->newTexture2D(rsGame); - if(texture) { - if(textureNode->getAttribute("luminance")->getBoolValue()){ - texture->setFormat(Texture::fAlpha); - texture->getPixmap()->init(1); - } - else{ - texture->getPixmap()->init(4); - } - } - string currentPath = dir; - endPathWithSlash(currentPath); - if(texture) { - texture->load(textureNode->getAttribute("path")->getRestrictedValue(currentPath)); - } - loadedFileList[textureNode->getAttribute("path")->getRestrictedValue(currentPath)].push_back(make_pair(parentLoader,textureNode->getAttribute("path")->getRestrictedValue())); - } - else { - texture= NULL; - } - - //model - if(particleSystemNode->hasChild("model")){ - const XmlNode *modelNode= particleSystemNode->getChild("model"); - bool modelEnabled= modelNode->getAttribute("value")->getBoolValue(); - if(modelEnabled) { - string currentPath = dir; - endPathWithSlash(currentPath); - - string path= modelNode->getAttribute("path")->getRestrictedValue(currentPath); - model= renderer->newModel(rsGame,path, false, &loadedFileList, &parentLoader); - loadedFileList[path].push_back(make_pair(parentLoader,modelNode->getAttribute("path")->getRestrictedValue())); - - if(modelNode->hasChild("cycles")) { - modelCycle = modelNode->getChild("cycles")->getAttribute("value")->getFloatValue(); - if(modelCycle < 0.0) - throw megaglest_runtime_error("negative model cycle value is bad"); - } - } - } - else { - model= NULL; - } - - //primitive - const XmlNode *primitiveNode= particleSystemNode->getChild("primitive"); - primitive= primitiveNode->getAttribute("value")->getRestrictedValue(); - - //offset - const XmlNode *offsetNode= particleSystemNode->getChild("offset"); - offset.x= offsetNode->getAttribute("x")->getFloatValue(); - offset.y= offsetNode->getAttribute("y")->getFloatValue(); - offset.z= offsetNode->getAttribute("z")->getFloatValue(); - - //color - const XmlNode *colorNode= particleSystemNode->getChild("color"); - color.x= colorNode->getAttribute("red")->getFloatValue(0.f, 1.0f); - color.y= colorNode->getAttribute("green")->getFloatValue(0.f, 1.0f); - color.z= colorNode->getAttribute("blue")->getFloatValue(0.f, 1.0f); - color.w= colorNode->getAttribute("alpha")->getFloatValue(0.f, 1.0f); - - //color - const XmlNode *colorNoEnergyNode= particleSystemNode->getChild("color-no-energy"); - colorNoEnergy.x= colorNoEnergyNode->getAttribute("red")->getFloatValue(0.f, 1.0f); - colorNoEnergy.y= colorNoEnergyNode->getAttribute("green")->getFloatValue(0.f, 1.0f); - colorNoEnergy.z= colorNoEnergyNode->getAttribute("blue")->getFloatValue(0.f, 1.0f); - colorNoEnergy.w= colorNoEnergyNode->getAttribute("alpha")->getFloatValue(0.f, 1.0f); - - //size - const XmlNode *sizeNode= particleSystemNode->getChild("size"); - size= sizeNode->getAttribute("value")->getFloatValue(); - - //sizeNoEnergy - const XmlNode *sizeNoEnergyNode= particleSystemNode->getChild("size-no-energy"); - sizeNoEnergy= sizeNoEnergyNode->getAttribute("value")->getFloatValue(); - - //speed - const XmlNode *speedNode= particleSystemNode->getChild("speed"); - speed= speedNode->getAttribute("value")->getFloatValue()/GameConstants::updateFps; - - //speedUp - if(particleSystemNode->hasChild("speedUp")){ - const XmlNode *speedUpNode= particleSystemNode->getChild("speedUp"); - if(speedUpNode->hasAttribute("relative")){ - speedUpRelative= speedUpNode->getAttribute("relative")->getFloatValue(); - } - if(speedUpNode->hasAttribute("constant")){ - speedUpConstant= speedUpNode->getAttribute("constant")->getFloatValue(); - } +void ParticleSystemType::load( + const XmlNode *particleSystemNode, const string &dir, + RendererInterface *renderer, + std::map>> &loadedFileList, + string parentLoader, string techtreePath) { + + // texture + const XmlNode *textureNode = particleSystemNode->getChild("texture"); + bool textureEnabled = textureNode->getAttribute("value")->getBoolValue(); + + if (textureEnabled) { + texture = renderer->newTexture2D(rsGame); + if (texture) { + if (textureNode->getAttribute("luminance")->getBoolValue()) { + texture->setFormat(Texture::fAlpha); + texture->getPixmap()->init(1); + } else { + texture->getPixmap()->init(4); + } } - - //gravity - const XmlNode *gravityNode= particleSystemNode->getChild("gravity"); - gravity= gravityNode->getAttribute("value")->getFloatValue()/GameConstants::updateFps; - - //emission rate - const XmlNode *emissionRateNode= particleSystemNode->getChild("emission-rate"); - emissionRate= emissionRateNode->getAttribute("value")->getFloatValue(); - - //energy max - const XmlNode *energyMaxNode= particleSystemNode->getChild("energy-max"); - energyMax= energyMaxNode->getAttribute("value")->getIntValue(); - - //speed - const XmlNode *energyVarNode= particleSystemNode->getChild("energy-var"); - energyVar= energyVarNode->getAttribute("value")->getIntValue(); - - //teamcolorNoEnergy - if(particleSystemNode->hasChild("teamcolorNoEnergy")){ - const XmlNode *teamcolorNoEnergyNode= particleSystemNode->getChild("teamcolorNoEnergy"); - teamcolorNoEnergy= teamcolorNoEnergyNode->getAttribute("value")->getBoolValue(); + string currentPath = dir; + endPathWithSlash(currentPath); + if (texture) { + texture->load( + textureNode->getAttribute("path")->getRestrictedValue(currentPath)); } - //teamcolorEnergy - if(particleSystemNode->hasChild("teamcolorEnergy")){ - const XmlNode *teamcolorEnergyNode= particleSystemNode->getChild("teamcolorEnergy"); - teamcolorEnergy= teamcolorEnergyNode->getAttribute("value")->getBoolValue(); + loadedFileList[textureNode->getAttribute("path")->getRestrictedValue( + currentPath)] + .push_back( + make_pair(parentLoader, + textureNode->getAttribute("path")->getRestrictedValue())); + } else { + texture = NULL; + } + + // model + if (particleSystemNode->hasChild("model")) { + const XmlNode *modelNode = particleSystemNode->getChild("model"); + bool modelEnabled = modelNode->getAttribute("value")->getBoolValue(); + if (modelEnabled) { + string currentPath = dir; + endPathWithSlash(currentPath); + + string path = + modelNode->getAttribute("path")->getRestrictedValue(currentPath); + model = renderer->newModel(rsGame, path, false, &loadedFileList, + &parentLoader); + loadedFileList[path].push_back(make_pair( + parentLoader, modelNode->getAttribute("path")->getRestrictedValue())); + + if (modelNode->hasChild("cycles")) { + modelCycle = modelNode->getChild("cycles") + ->getAttribute("value") + ->getFloatValue(); + if (modelCycle < 0.0) + throw megaglest_runtime_error("negative model cycle value is bad"); + } } - //alternations - if(particleSystemNode->hasChild("alternations")){ - const XmlNode *alternatingNode= particleSystemNode->getChild("alternations"); - alternations= alternatingNode->getAttribute("value")->getIntValue(); - } - //particleSystemStartDelay - if(particleSystemNode->hasChild("particleSystemStartDelay")){ - const XmlNode *node= particleSystemNode->getChild("particleSystemStartDelay"); - particleSystemStartDelay= node->getAttribute("value")->getIntValue(); - } - //mode - if(particleSystemNode->hasChild("mode")) { - const XmlNode *modeNode= particleSystemNode->getChild("mode"); - mode= modeNode->getAttribute("value")->getRestrictedValue(); - } - else { - mode="normal"; - } - - // child particles - if(particleSystemNode->hasChild("child-particles")) { - const XmlNode *childrenNode= particleSystemNode->getChild("child-particles"); - if(childrenNode->getAttribute("value")->getBoolValue()) { - for(unsigned int i = 0; i < childrenNode->getChildCount(); ++i) { - const XmlNode *particleFileNode= childrenNode->getChild("particle-file",i); - string path= particleFileNode->getAttribute("path")->getRestrictedValue(); - UnitParticleSystemType *unitParticleSystemType= new UnitParticleSystemType(); - string childPath= dir; - endPathWithSlash(childPath); - childPath += path; - string childDir = extractDirectoryPathFromFile(childPath); - unitParticleSystemType->load(particleFileNode,childDir,childPath,renderer,loadedFileList,parentLoader,techtreePath); - loadedFileList[childPath].push_back(make_pair(parentLoader,path)); - children.push_back(unitParticleSystemType); - } - } - } + } else { + model = NULL; + } + + // primitive + const XmlNode *primitiveNode = particleSystemNode->getChild("primitive"); + primitive = primitiveNode->getAttribute("value")->getRestrictedValue(); + + // offset + const XmlNode *offsetNode = particleSystemNode->getChild("offset"); + offset.x = offsetNode->getAttribute("x")->getFloatValue(); + offset.y = offsetNode->getAttribute("y")->getFloatValue(); + offset.z = offsetNode->getAttribute("z")->getFloatValue(); + + // color + const XmlNode *colorNode = particleSystemNode->getChild("color"); + color.x = colorNode->getAttribute("red")->getFloatValue(0.f, 1.0f); + color.y = colorNode->getAttribute("green")->getFloatValue(0.f, 1.0f); + color.z = colorNode->getAttribute("blue")->getFloatValue(0.f, 1.0f); + color.w = colorNode->getAttribute("alpha")->getFloatValue(0.f, 1.0f); + + // color + const XmlNode *colorNoEnergyNode = + particleSystemNode->getChild("color-no-energy"); + colorNoEnergy.x = + colorNoEnergyNode->getAttribute("red")->getFloatValue(0.f, 1.0f); + colorNoEnergy.y = + colorNoEnergyNode->getAttribute("green")->getFloatValue(0.f, 1.0f); + colorNoEnergy.z = + colorNoEnergyNode->getAttribute("blue")->getFloatValue(0.f, 1.0f); + colorNoEnergy.w = + colorNoEnergyNode->getAttribute("alpha")->getFloatValue(0.f, 1.0f); + + // size + const XmlNode *sizeNode = particleSystemNode->getChild("size"); + size = sizeNode->getAttribute("value")->getFloatValue(); + + // sizeNoEnergy + const XmlNode *sizeNoEnergyNode = + particleSystemNode->getChild("size-no-energy"); + sizeNoEnergy = sizeNoEnergyNode->getAttribute("value")->getFloatValue(); + + // speed + const XmlNode *speedNode = particleSystemNode->getChild("speed"); + speed = speedNode->getAttribute("value")->getFloatValue() / + GameConstants::updateFps; + + // speedUp + if (particleSystemNode->hasChild("speedUp")) { + const XmlNode *speedUpNode = particleSystemNode->getChild("speedUp"); + if (speedUpNode->hasAttribute("relative")) { + speedUpRelative = speedUpNode->getAttribute("relative")->getFloatValue(); + } + if (speedUpNode->hasAttribute("constant")) { + speedUpConstant = speedUpNode->getAttribute("constant")->getFloatValue(); + } + } + + // gravity + const XmlNode *gravityNode = particleSystemNode->getChild("gravity"); + gravity = gravityNode->getAttribute("value")->getFloatValue() / + GameConstants::updateFps; + + // emission rate + const XmlNode *emissionRateNode = + particleSystemNode->getChild("emission-rate"); + emissionRate = emissionRateNode->getAttribute("value")->getFloatValue(); + + // energy max + const XmlNode *energyMaxNode = particleSystemNode->getChild("energy-max"); + energyMax = energyMaxNode->getAttribute("value")->getIntValue(); + + // speed + const XmlNode *energyVarNode = particleSystemNode->getChild("energy-var"); + energyVar = energyVarNode->getAttribute("value")->getIntValue(); + + // teamcolorNoEnergy + if (particleSystemNode->hasChild("teamcolorNoEnergy")) { + const XmlNode *teamcolorNoEnergyNode = + particleSystemNode->getChild("teamcolorNoEnergy"); + teamcolorNoEnergy = + teamcolorNoEnergyNode->getAttribute("value")->getBoolValue(); + } + // teamcolorEnergy + if (particleSystemNode->hasChild("teamcolorEnergy")) { + const XmlNode *teamcolorEnergyNode = + particleSystemNode->getChild("teamcolorEnergy"); + teamcolorEnergy = + teamcolorEnergyNode->getAttribute("value")->getBoolValue(); + } + // alternations + if (particleSystemNode->hasChild("alternations")) { + const XmlNode *alternatingNode = + particleSystemNode->getChild("alternations"); + alternations = alternatingNode->getAttribute("value")->getIntValue(); + } + // particleSystemStartDelay + if (particleSystemNode->hasChild("particleSystemStartDelay")) { + const XmlNode *node = + particleSystemNode->getChild("particleSystemStartDelay"); + particleSystemStartDelay = node->getAttribute("value")->getIntValue(); + } + // mode + if (particleSystemNode->hasChild("mode")) { + const XmlNode *modeNode = particleSystemNode->getChild("mode"); + mode = modeNode->getAttribute("value")->getRestrictedValue(); + } else { + mode = "normal"; + } + + // child particles + if (particleSystemNode->hasChild("child-particles")) { + const XmlNode *childrenNode = + particleSystemNode->getChild("child-particles"); + if (childrenNode->getAttribute("value")->getBoolValue()) { + for (unsigned int i = 0; i < childrenNode->getChildCount(); ++i) { + const XmlNode *particleFileNode = + childrenNode->getChild("particle-file", i); + string path = + particleFileNode->getAttribute("path")->getRestrictedValue(); + UnitParticleSystemType *unitParticleSystemType = + new UnitParticleSystemType(); + string childPath = dir; + endPathWithSlash(childPath); + childPath += path; + string childDir = extractDirectoryPathFromFile(childPath); + unitParticleSystemType->load(particleFileNode, childDir, childPath, + renderer, loadedFileList, parentLoader, + techtreePath); + loadedFileList[childPath].push_back(make_pair(parentLoader, path)); + children.push_back(unitParticleSystemType); + } + } + } } -void ParticleSystemType::setValues(AttackParticleSystem *ats){ - // add instances of all children; some settings will cascade to all children - for(Children::iterator i=children.begin(); i!=children.end(); ++i){ - UnitParticleSystem *child = new UnitParticleSystem(); - child->setParticleOwner(ats->getParticleOwner()); - child->setParticleType((*i)); - (*i)->setValues(child); - ats->addChild(child); - child->setState(ParticleSystem::sPlay); - } - ats->setTexture(texture); - ats->setPrimitive(AttackParticleSystem::strToPrimitive(primitive)); - ats->setOffset(offset); - ats->setColor(color); - ats->setColorNoEnergy(colorNoEnergy); - ats->setSpeed(speed); - ats->setSpeedUpRelative(speedUpRelative); - ats->setSpeedUpConstant(speedUpConstant); - ats->setGravity(gravity); - ats->setParticleSize(size); - ats->setSizeNoEnergy(sizeNoEnergy); - ats->setEmissionRate(emissionRate); - ats->setMaxParticleEnergy(energyMax); - ats->setVarParticleEnergy(energyVar); - ats->setModel(model); - ats->setModelCycle(modelCycle); - ats->setTeamcolorNoEnergy(teamcolorNoEnergy); - ats->setTeamcolorEnergy(teamcolorEnergy); - ats->setAlternations(alternations); - ats->setParticleSystemStartDelay(particleSystemStartDelay); - ats->setBlendMode(ParticleSystem::strToBlendMode(mode)); +void ParticleSystemType::setValues(AttackParticleSystem *ats) { + // add instances of all children; some settings will cascade to all children + for (Children::iterator i = children.begin(); i != children.end(); ++i) { + UnitParticleSystem *child = new UnitParticleSystem(); + child->setParticleOwner(ats->getParticleOwner()); + child->setParticleType((*i)); + (*i)->setValues(child); + ats->addChild(child); + child->setState(ParticleSystem::sPlay); + } + ats->setTexture(texture); + ats->setPrimitive(AttackParticleSystem::strToPrimitive(primitive)); + ats->setOffset(offset); + ats->setColor(color); + ats->setColorNoEnergy(colorNoEnergy); + ats->setSpeed(speed); + ats->setSpeedUpRelative(speedUpRelative); + ats->setSpeedUpConstant(speedUpConstant); + ats->setGravity(gravity); + ats->setParticleSize(size); + ats->setSizeNoEnergy(sizeNoEnergy); + ats->setEmissionRate(emissionRate); + ats->setMaxParticleEnergy(energyMax); + ats->setVarParticleEnergy(energyVar); + ats->setModel(model); + ats->setModelCycle(modelCycle); + ats->setTeamcolorNoEnergy(teamcolorNoEnergy); + ats->setTeamcolorEnergy(teamcolorEnergy); + ats->setAlternations(alternations); + ats->setParticleSystemStartDelay(particleSystemStartDelay); + ats->setBlendMode(ParticleSystem::strToBlendMode(mode)); } void ParticleSystemType::loadGame(const XmlNode *rootNode) { - const XmlNode *particleSystemTypeNode = rootNode->getChild("ParticleSystemType"); - - type = particleSystemTypeNode->getAttribute("type")->getIntValue(); - - modelCycle = particleSystemTypeNode->getAttribute("modelCycle")->getFloatValue(); - primitive = particleSystemTypeNode->getAttribute("primitive")->getValue(); - offset = Vec3f::strToVec3(particleSystemTypeNode->getAttribute("offset")->getValue()); - color = Vec4f::strToVec4(particleSystemTypeNode->getAttribute("color")->getValue()); - colorNoEnergy = Vec4f::strToVec4(particleSystemTypeNode->getAttribute("colorNoEnergy")->getValue()); - size = particleSystemTypeNode->getAttribute("size")->getFloatValue(); - sizeNoEnergy = particleSystemTypeNode->getAttribute("sizeNoEnergy")->getFloatValue(); - speed = particleSystemTypeNode->getAttribute("speed")->getFloatValue(); - if(particleSystemTypeNode->hasAttribute("speedUpRelative")){ - speedUpRelative = particleSystemTypeNode->getAttribute("speedUpRelative")->getFloatValue(); - } - if(particleSystemTypeNode->hasAttribute("speedUpConstant")){ - speedUpConstant = particleSystemTypeNode->getAttribute("speedUpConstant")->getFloatValue(); - } - gravity = particleSystemTypeNode->getAttribute("gravity")->getFloatValue(); - emissionRate = particleSystemTypeNode->getAttribute("emissionRate")->getFloatValue(); - energyMax = particleSystemTypeNode->getAttribute("energyMax")->getIntValue(); - energyVar = particleSystemTypeNode->getAttribute("energyVar")->getIntValue(); - mode = particleSystemTypeNode->getAttribute("mode")->getValue(); - teamcolorNoEnergy = (particleSystemTypeNode->getAttribute("teamcolorNoEnergy")->getIntValue() != 0); - teamcolorEnergy = (particleSystemTypeNode->getAttribute("teamcolorEnergy")->getIntValue() != 0); - alternations = particleSystemTypeNode->getAttribute("alternations")->getIntValue(); - particleSystemStartDelay = particleSystemTypeNode->getAttribute("particleSystemStartDelay")->getIntValue(); - - if(particleSystemTypeNode->hasChild("UnitParticleSystemType")) { - vector particleSystemTypeNodeList = particleSystemTypeNode->getChildList("UnitParticleSystemType"); - for(unsigned int i = 0; i < particleSystemTypeNodeList.size(); ++i) { - XmlNode *node = particleSystemTypeNodeList[i]; - - UnitParticleSystemType *child = new UnitParticleSystemType(); - child->loadGame(node); - children.push_back(child); - } - } - minmaxEnabled = (particleSystemTypeNode->getAttribute("minmaxEnabled")->getIntValue() != 0); - minHp = particleSystemTypeNode->getAttribute("minHp")->getIntValue(); - maxHp = particleSystemTypeNode->getAttribute("maxHp")->getIntValue(); - minmaxIsPercent = (particleSystemTypeNode->getAttribute("minmaxIsPercent")->getIntValue() != 0); + const XmlNode *particleSystemTypeNode = + rootNode->getChild("ParticleSystemType"); + + type = particleSystemTypeNode->getAttribute("type")->getIntValue(); + + modelCycle = + particleSystemTypeNode->getAttribute("modelCycle")->getFloatValue(); + primitive = particleSystemTypeNode->getAttribute("primitive")->getValue(); + offset = Vec3f::strToVec3( + particleSystemTypeNode->getAttribute("offset")->getValue()); + color = Vec4f::strToVec4( + particleSystemTypeNode->getAttribute("color")->getValue()); + colorNoEnergy = Vec4f::strToVec4( + particleSystemTypeNode->getAttribute("colorNoEnergy")->getValue()); + size = particleSystemTypeNode->getAttribute("size")->getFloatValue(); + sizeNoEnergy = + particleSystemTypeNode->getAttribute("sizeNoEnergy")->getFloatValue(); + speed = particleSystemTypeNode->getAttribute("speed")->getFloatValue(); + if (particleSystemTypeNode->hasAttribute("speedUpRelative")) { + speedUpRelative = particleSystemTypeNode->getAttribute("speedUpRelative") + ->getFloatValue(); + } + if (particleSystemTypeNode->hasAttribute("speedUpConstant")) { + speedUpConstant = particleSystemTypeNode->getAttribute("speedUpConstant") + ->getFloatValue(); + } + gravity = particleSystemTypeNode->getAttribute("gravity")->getFloatValue(); + emissionRate = + particleSystemTypeNode->getAttribute("emissionRate")->getFloatValue(); + energyMax = particleSystemTypeNode->getAttribute("energyMax")->getIntValue(); + energyVar = particleSystemTypeNode->getAttribute("energyVar")->getIntValue(); + mode = particleSystemTypeNode->getAttribute("mode")->getValue(); + teamcolorNoEnergy = (particleSystemTypeNode->getAttribute("teamcolorNoEnergy") + ->getIntValue() != 0); + teamcolorEnergy = + (particleSystemTypeNode->getAttribute("teamcolorEnergy")->getIntValue() != + 0); + alternations = + particleSystemTypeNode->getAttribute("alternations")->getIntValue(); + particleSystemStartDelay = + particleSystemTypeNode->getAttribute("particleSystemStartDelay") + ->getIntValue(); + + if (particleSystemTypeNode->hasChild("UnitParticleSystemType")) { + vector particleSystemTypeNodeList = + particleSystemTypeNode->getChildList("UnitParticleSystemType"); + for (unsigned int i = 0; i < particleSystemTypeNodeList.size(); ++i) { + XmlNode *node = particleSystemTypeNodeList[i]; + + UnitParticleSystemType *child = new UnitParticleSystemType(); + child->loadGame(node); + children.push_back(child); + } + } + minmaxEnabled = + (particleSystemTypeNode->getAttribute("minmaxEnabled")->getIntValue() != + 0); + minHp = particleSystemTypeNode->getAttribute("minHp")->getIntValue(); + maxHp = particleSystemTypeNode->getAttribute("maxHp")->getIntValue(); + minmaxIsPercent = + (particleSystemTypeNode->getAttribute("minmaxIsPercent")->getIntValue() != + 0); } void ParticleSystemType::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *particleSystemTypeNode = rootNode->addChild("ParticleSystemType"); - -// string type; - particleSystemTypeNode->addAttribute("type",type, mapTagReplacements); -// Texture2D *texture; -// Model *model; -// float modelCycle; - particleSystemTypeNode->addAttribute("modelCycle",floatToStr(modelCycle,6), mapTagReplacements); -// string primitive; - particleSystemTypeNode->addAttribute("primitive",primitive, mapTagReplacements); -// Vec3f offset; - particleSystemTypeNode->addAttribute("offset",offset.getString(), mapTagReplacements); -// Vec4f color; - particleSystemTypeNode->addAttribute("color",color.getString(), mapTagReplacements); -// Vec4f colorNoEnergy; - particleSystemTypeNode->addAttribute("colorNoEnergy",colorNoEnergy.getString(), mapTagReplacements); -// float size; - particleSystemTypeNode->addAttribute("size",floatToStr(size,6), mapTagReplacements); -// float sizeNoEnergy; - particleSystemTypeNode->addAttribute("sizeNoEnergy",floatToStr(sizeNoEnergy,6), mapTagReplacements); -// float speed; - particleSystemTypeNode->addAttribute("speed",floatToStr(speed,6), mapTagReplacements); -// float speedUpRelative; - particleSystemTypeNode->addAttribute("speedUpRelative",floatToStr(speedUpRelative,6), mapTagReplacements); -// float speedUpConstant; - particleSystemTypeNode->addAttribute("speedUpConstant",floatToStr(speedUpConstant,6), mapTagReplacements); -// float gravity; - particleSystemTypeNode->addAttribute("gravity",floatToStr(gravity,6), mapTagReplacements); -// float emissionRate; - particleSystemTypeNode->addAttribute("emissionRate",floatToStr(emissionRate,6), mapTagReplacements); -// int energyMax; - particleSystemTypeNode->addAttribute("energyMax",intToStr(energyMax), mapTagReplacements); -// int energyVar; - particleSystemTypeNode->addAttribute("energyVar",intToStr(energyVar), mapTagReplacements); -// string mode; - particleSystemTypeNode->addAttribute("mode",mode, mapTagReplacements); -// bool teamcolorNoEnergy; - particleSystemTypeNode->addAttribute("teamcolorNoEnergy",intToStr(teamcolorNoEnergy), mapTagReplacements); -// bool teamcolorEnergy; - particleSystemTypeNode->addAttribute("teamcolorEnergy",intToStr(teamcolorEnergy), mapTagReplacements); -// int alternations; - particleSystemTypeNode->addAttribute("alternations",intToStr(alternations), mapTagReplacements); -// int particleSystemStartDelay; - particleSystemTypeNode->addAttribute("particleSystemStartDelay",intToStr(particleSystemStartDelay), mapTagReplacements); -// typedef std::list Children; -// Children children; - for(Children::iterator it = children.begin(); it != children.end(); ++it) { - (*it)->saveGame(particleSystemTypeNode); - } -// bool minmaxEnabled; - particleSystemTypeNode->addAttribute("minmaxEnabled",intToStr(minmaxEnabled), mapTagReplacements); -// int minHp; - particleSystemTypeNode->addAttribute("minHp",intToStr(minHp), mapTagReplacements); -// int maxHp; - particleSystemTypeNode->addAttribute("maxHp",intToStr(maxHp), mapTagReplacements); -// bool minmaxIsPercent; - particleSystemTypeNode->addAttribute("minmaxIsPercent",intToStr(minmaxIsPercent), mapTagReplacements); + std::map mapTagReplacements; + XmlNode *particleSystemTypeNode = rootNode->addChild("ParticleSystemType"); + + // string type; + particleSystemTypeNode->addAttribute("type", type, mapTagReplacements); + // Texture2D *texture; + // Model *model; + // float modelCycle; + particleSystemTypeNode->addAttribute("modelCycle", floatToStr(modelCycle, 6), + mapTagReplacements); + // string primitive; + particleSystemTypeNode->addAttribute("primitive", primitive, + mapTagReplacements); + // Vec3f offset; + particleSystemTypeNode->addAttribute("offset", offset.getString(), + mapTagReplacements); + // Vec4f color; + particleSystemTypeNode->addAttribute("color", color.getString(), + mapTagReplacements); + // Vec4f colorNoEnergy; + particleSystemTypeNode->addAttribute( + "colorNoEnergy", colorNoEnergy.getString(), mapTagReplacements); + // float size; + particleSystemTypeNode->addAttribute("size", floatToStr(size, 6), + mapTagReplacements); + // float sizeNoEnergy; + particleSystemTypeNode->addAttribute( + "sizeNoEnergy", floatToStr(sizeNoEnergy, 6), mapTagReplacements); + // float speed; + particleSystemTypeNode->addAttribute("speed", floatToStr(speed, 6), + mapTagReplacements); + // float speedUpRelative; + particleSystemTypeNode->addAttribute( + "speedUpRelative", floatToStr(speedUpRelative, 6), mapTagReplacements); + // float speedUpConstant; + particleSystemTypeNode->addAttribute( + "speedUpConstant", floatToStr(speedUpConstant, 6), mapTagReplacements); + // float gravity; + particleSystemTypeNode->addAttribute("gravity", floatToStr(gravity, 6), + mapTagReplacements); + // float emissionRate; + particleSystemTypeNode->addAttribute( + "emissionRate", floatToStr(emissionRate, 6), mapTagReplacements); + // int energyMax; + particleSystemTypeNode->addAttribute("energyMax", intToStr(energyMax), + mapTagReplacements); + // int energyVar; + particleSystemTypeNode->addAttribute("energyVar", intToStr(energyVar), + mapTagReplacements); + // string mode; + particleSystemTypeNode->addAttribute("mode", mode, mapTagReplacements); + // bool teamcolorNoEnergy; + particleSystemTypeNode->addAttribute( + "teamcolorNoEnergy", intToStr(teamcolorNoEnergy), mapTagReplacements); + // bool teamcolorEnergy; + particleSystemTypeNode->addAttribute( + "teamcolorEnergy", intToStr(teamcolorEnergy), mapTagReplacements); + // int alternations; + particleSystemTypeNode->addAttribute("alternations", intToStr(alternations), + mapTagReplacements); + // int particleSystemStartDelay; + particleSystemTypeNode->addAttribute("particleSystemStartDelay", + intToStr(particleSystemStartDelay), + mapTagReplacements); + // typedef std::list Children; + // Children children; + for (Children::iterator it = children.begin(); it != children.end(); ++it) { + (*it)->saveGame(particleSystemTypeNode); + } + // bool minmaxEnabled; + particleSystemTypeNode->addAttribute("minmaxEnabled", intToStr(minmaxEnabled), + mapTagReplacements); + // int minHp; + particleSystemTypeNode->addAttribute("minHp", intToStr(minHp), + mapTagReplacements); + // int maxHp; + particleSystemTypeNode->addAttribute("maxHp", intToStr(maxHp), + mapTagReplacements); + // bool minmaxIsPercent; + particleSystemTypeNode->addAttribute( + "minmaxIsPercent", intToStr(minmaxIsPercent), mapTagReplacements); } // =========================================================== // class ParticleSystemTypeProjectile // =========================================================== -ParticleSystemTypeProjectile::ParticleSystemTypeProjectile() : ParticleSystemType() { - trajectorySpeed = 0.0f; - trajectoryScale = 0.0f; - trajectoryFrequency = 0.0f; +ParticleSystemTypeProjectile::ParticleSystemTypeProjectile() + : ParticleSystemType() { + trajectorySpeed = 0.0f; + trajectoryScale = 0.0f; + trajectoryFrequency = 0.0f; } -void ParticleSystemTypeProjectile::load(const XmlNode* particleFileNode, const string &dir, const string &path, - RendererInterface *renderer, std::map > > &loadedFileList, - string parentLoader, string techtreePath) { - - try{ - XmlTree xmlTree; - - std::map mapExtraTagReplacementValues; - mapExtraTagReplacementValues["$COMMONDATAPATH"] = techtreePath + "/commondata/"; - xmlTree.load(path, Properties::getTagReplacementValues(&mapExtraTagReplacementValues)); - loadedFileList[path].push_back(make_pair(parentLoader,parentLoader)); - - const XmlNode *particleSystemNode= xmlTree.getRootNode(); - - if(particleFileNode){ - // immediate children in the particleFileNode will override the particleSystemNode - particleFileNode->setSuper(particleSystemNode); - particleSystemNode= particleFileNode; - } - - ParticleSystemType::load(particleSystemNode, dir, renderer, loadedFileList,parentLoader, techtreePath); - - //trajectory values - const XmlNode *tajectoryNode= particleSystemNode->getChild("trajectory"); - trajectory= tajectoryNode->getAttribute("type")->getRestrictedValue(); - - //trajectory speed - const XmlNode *tajectorySpeedNode= tajectoryNode->getChild("speed"); - trajectorySpeed= tajectorySpeedNode->getAttribute("value")->getFloatValue() / (float)GameConstants::updateFps; - //printf("[%s] trajectorySpeed = %f\n",path.c_str(),trajectorySpeed); - - if(trajectory=="parabolic" || trajectory=="spiral"){ - //trajectory scale - const XmlNode *tajectoryScaleNode= tajectoryNode->getChild("scale"); - trajectoryScale= tajectoryScaleNode->getAttribute("value")->getFloatValue(); - } - else{ - trajectoryScale= 1.0f; - } - - if(trajectory=="spiral"){ - //trajectory frequency - const XmlNode *tajectoryFrequencyNode= tajectoryNode->getChild("frequency"); - trajectoryFrequency= tajectoryFrequencyNode->getAttribute("value")->getFloatValue(); - } - else{ - trajectoryFrequency= 1.0f; - } - } - catch(const exception &e){ - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,e.what()); - throw megaglest_runtime_error("Error loading ParticleSystem: "+ path + "\n" +e.what()); - } +void ParticleSystemTypeProjectile::load( + const XmlNode *particleFileNode, const string &dir, const string &path, + RendererInterface *renderer, + std::map>> &loadedFileList, + string parentLoader, string techtreePath) { + + try { + XmlTree xmlTree; + + std::map mapExtraTagReplacementValues; + mapExtraTagReplacementValues["$COMMONDATAPATH"] = + techtreePath + "/commondata/"; + xmlTree.load(path, Properties::getTagReplacementValues( + &mapExtraTagReplacementValues)); + loadedFileList[path].push_back(make_pair(parentLoader, parentLoader)); + + const XmlNode *particleSystemNode = xmlTree.getRootNode(); + + if (particleFileNode) { + // immediate children in the particleFileNode will override the + // particleSystemNode + particleFileNode->setSuper(particleSystemNode); + particleSystemNode = particleFileNode; + } + + ParticleSystemType::load(particleSystemNode, dir, renderer, loadedFileList, + parentLoader, techtreePath); + + // trajectory values + const XmlNode *tajectoryNode = particleSystemNode->getChild("trajectory"); + trajectory = tajectoryNode->getAttribute("type")->getRestrictedValue(); + + // trajectory speed + const XmlNode *tajectorySpeedNode = tajectoryNode->getChild("speed"); + trajectorySpeed = + tajectorySpeedNode->getAttribute("value")->getFloatValue() / + (float)GameConstants::updateFps; + // printf("[%s] trajectorySpeed = %f\n",path.c_str(),trajectorySpeed); + + if (trajectory == "parabolic" || trajectory == "spiral") { + // trajectory scale + const XmlNode *tajectoryScaleNode = tajectoryNode->getChild("scale"); + trajectoryScale = + tajectoryScaleNode->getAttribute("value")->getFloatValue(); + } else { + trajectoryScale = 1.0f; + } + + if (trajectory == "spiral") { + // trajectory frequency + const XmlNode *tajectoryFrequencyNode = + tajectoryNode->getChild("frequency"); + trajectoryFrequency = + tajectoryFrequencyNode->getAttribute("value")->getFloatValue(); + } else { + trajectoryFrequency = 1.0f; + } + } catch (const exception &e) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", __FILE__, + __FUNCTION__, __LINE__, e.what()); + throw megaglest_runtime_error("Error loading ParticleSystem: " + path + + "\n" + e.what()); + } } -ProjectileParticleSystem *ParticleSystemTypeProjectile::create(ParticleOwner *owner) { - ProjectileParticleSystem *ps= new ProjectileParticleSystem(); - ps->setParticleOwner(owner); - ParticleSystemType::setValues(ps); +ProjectileParticleSystem * +ParticleSystemTypeProjectile::create(ParticleOwner *owner) { + ProjectileParticleSystem *ps = new ProjectileParticleSystem(); + ps->setParticleOwner(owner); + ParticleSystemType::setValues(ps); - ps->setTrajectory(ProjectileParticleSystem::strToTrajectory(trajectory)); + ps->setTrajectory(ProjectileParticleSystem::strToTrajectory(trajectory)); - //printf("Setting trajectorySpeed = %f\n",trajectorySpeed); - ps->setTrajectorySpeed(trajectorySpeed); - ps->setTrajectoryScale(trajectoryScale); - ps->setTrajectoryFrequency(trajectoryFrequency); + // printf("Setting trajectorySpeed = %f\n",trajectorySpeed); + ps->setTrajectorySpeed(trajectorySpeed); + ps->setTrajectoryScale(trajectoryScale); + ps->setTrajectoryFrequency(trajectoryFrequency); - ps->initParticleSystem(); + ps->initParticleSystem(); - return ps; + return ps; } void ParticleSystemTypeProjectile::saveGame(XmlNode *rootNode) { - ParticleSystemType::saveGame(rootNode); - - std::map mapTagReplacements; - XmlNode *particleSystemTypeProjectileNode = rootNode->addChild("ParticleSystemTypeProjectile"); - -// string trajectory; - particleSystemTypeProjectileNode->addAttribute("trajectory",trajectory, mapTagReplacements); -// float trajectorySpeed; - particleSystemTypeProjectileNode->addAttribute("trajectorySpeed",floatToStr(trajectorySpeed,6), mapTagReplacements); -// float trajectoryScale; - particleSystemTypeProjectileNode->addAttribute("trajectoryScale",floatToStr(trajectoryScale,6), mapTagReplacements); -// float trajectoryFrequency; - particleSystemTypeProjectileNode->addAttribute("trajectoryFrequency",floatToStr(trajectoryFrequency,6), mapTagReplacements); + ParticleSystemType::saveGame(rootNode); + + std::map mapTagReplacements; + XmlNode *particleSystemTypeProjectileNode = + rootNode->addChild("ParticleSystemTypeProjectile"); + + // string trajectory; + particleSystemTypeProjectileNode->addAttribute("trajectory", trajectory, + mapTagReplacements); + // float trajectorySpeed; + particleSystemTypeProjectileNode->addAttribute( + "trajectorySpeed", floatToStr(trajectorySpeed, 6), mapTagReplacements); + // float trajectoryScale; + particleSystemTypeProjectileNode->addAttribute( + "trajectoryScale", floatToStr(trajectoryScale, 6), mapTagReplacements); + // float trajectoryFrequency; + particleSystemTypeProjectileNode->addAttribute( + "trajectoryFrequency", floatToStr(trajectoryFrequency, 6), + mapTagReplacements); } // =========================================================== @@ -542,86 +634,111 @@ void ParticleSystemTypeProjectile::saveGame(XmlNode *rootNode) { // =========================================================== ParticleSystemTypeSplash::ParticleSystemTypeSplash() { - emissionRateFade = 0.0f; - verticalSpreadA = 0.0f; - verticalSpreadB = 0.0f; - horizontalSpreadA = 0.0f; - horizontalSpreadB = 0.0f; + emissionRateFade = 0.0f; + verticalSpreadA = 0.0f; + verticalSpreadB = 0.0f; + horizontalSpreadA = 0.0f; + horizontalSpreadB = 0.0f; } -void ParticleSystemTypeSplash::load(const XmlNode* particleFileNode, const string &dir, const string &path, - RendererInterface *renderer, std::map > > &loadedFileList, - string parentLoader, string techtreePath) { - - try{ - XmlTree xmlTree; - - std::map mapExtraTagReplacementValues; - mapExtraTagReplacementValues["$COMMONDATAPATH"] = techtreePath + "/commondata/"; - xmlTree.load(path, Properties::getTagReplacementValues(&mapExtraTagReplacementValues)); - loadedFileList[path].push_back(make_pair(parentLoader,parentLoader)); - - const XmlNode *particleSystemNode= xmlTree.getRootNode(); - - if(particleFileNode){ - // immediate children in the particleFileNode will override the particleSystemNode - particleFileNode->setSuper(particleSystemNode); - particleSystemNode= particleFileNode; - } - - ParticleSystemType::load(particleSystemNode, dir, renderer, loadedFileList, parentLoader, techtreePath); - - //emission rate fade - const XmlNode *emissionRateFadeNode= particleSystemNode->getChild("emission-rate-fade"); - emissionRateFade= emissionRateFadeNode->getAttribute("value")->getFloatValue(); - - //spread values - const XmlNode *verticalSpreadNode= particleSystemNode->getChild("vertical-spread"); - verticalSpreadA= verticalSpreadNode->getAttribute("a")->getFloatValue(0.0f, 1.0f); - verticalSpreadB= verticalSpreadNode->getAttribute("b")->getFloatValue(-1.0f, 1.0f); - - const XmlNode *horizontalSpreadNode= particleSystemNode->getChild("horizontal-spread"); - horizontalSpreadA= horizontalSpreadNode->getAttribute("a")->getFloatValue(0.0f, 1.0f); - horizontalSpreadB= horizontalSpreadNode->getAttribute("b")->getFloatValue(-1.0f, 1.0f); - } - catch(const exception &e){ - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,e.what()); - throw megaglest_runtime_error("Error loading ParticleSystem: "+ path + "\n" +e.what()); - } +void ParticleSystemTypeSplash::load( + const XmlNode *particleFileNode, const string &dir, const string &path, + RendererInterface *renderer, + std::map>> &loadedFileList, + string parentLoader, string techtreePath) { + + try { + XmlTree xmlTree; + + std::map mapExtraTagReplacementValues; + mapExtraTagReplacementValues["$COMMONDATAPATH"] = + techtreePath + "/commondata/"; + xmlTree.load(path, Properties::getTagReplacementValues( + &mapExtraTagReplacementValues)); + loadedFileList[path].push_back(make_pair(parentLoader, parentLoader)); + + const XmlNode *particleSystemNode = xmlTree.getRootNode(); + + if (particleFileNode) { + // immediate children in the particleFileNode will override the + // particleSystemNode + particleFileNode->setSuper(particleSystemNode); + particleSystemNode = particleFileNode; + } + + ParticleSystemType::load(particleSystemNode, dir, renderer, loadedFileList, + parentLoader, techtreePath); + + // emission rate fade + const XmlNode *emissionRateFadeNode = + particleSystemNode->getChild("emission-rate-fade"); + emissionRateFade = + emissionRateFadeNode->getAttribute("value")->getFloatValue(); + + // spread values + const XmlNode *verticalSpreadNode = + particleSystemNode->getChild("vertical-spread"); + verticalSpreadA = + verticalSpreadNode->getAttribute("a")->getFloatValue(0.0f, 1.0f); + verticalSpreadB = + verticalSpreadNode->getAttribute("b")->getFloatValue(-1.0f, 1.0f); + + const XmlNode *horizontalSpreadNode = + particleSystemNode->getChild("horizontal-spread"); + horizontalSpreadA = + horizontalSpreadNode->getAttribute("a")->getFloatValue(0.0f, 1.0f); + horizontalSpreadB = + horizontalSpreadNode->getAttribute("b")->getFloatValue(-1.0f, 1.0f); + } catch (const exception &e) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", __FILE__, + __FUNCTION__, __LINE__, e.what()); + throw megaglest_runtime_error("Error loading ParticleSystem: " + path + + "\n" + e.what()); + } } SplashParticleSystem *ParticleSystemTypeSplash::create(ParticleOwner *owner) { - SplashParticleSystem *ps= new SplashParticleSystem(); - ps->setParticleOwner(owner); - ParticleSystemType::setValues(ps); + SplashParticleSystem *ps = new SplashParticleSystem(); + ps->setParticleOwner(owner); + ParticleSystemType::setValues(ps); - ps->setEmissionRateFade(emissionRateFade); - ps->setVerticalSpreadA(verticalSpreadA); - ps->setVerticalSpreadB(verticalSpreadB); - ps->setHorizontalSpreadA(horizontalSpreadA); - ps->setHorizontalSpreadB(horizontalSpreadB); + ps->setEmissionRateFade(emissionRateFade); + ps->setVerticalSpreadA(verticalSpreadA); + ps->setVerticalSpreadB(verticalSpreadB); + ps->setHorizontalSpreadA(horizontalSpreadA); + ps->setHorizontalSpreadB(horizontalSpreadB); - ps->initParticleSystem(); + ps->initParticleSystem(); - return ps; + return ps; } void ParticleSystemTypeSplash::saveGame(XmlNode *rootNode) { - ParticleSystemType::saveGame(rootNode); - - std::map mapTagReplacements; - XmlNode *particleSystemTypeSplashNode = rootNode->addChild("ParticleSystemTypeSplash"); - -// float emissionRateFade; - particleSystemTypeSplashNode->addAttribute("emissionRateFade",floatToStr(emissionRateFade,6), mapTagReplacements); -// float verticalSpreadA; - particleSystemTypeSplashNode->addAttribute("verticalSpreadA",floatToStr(verticalSpreadA,6), mapTagReplacements); -// float verticalSpreadB; - particleSystemTypeSplashNode->addAttribute("verticalSpreadB",floatToStr(verticalSpreadB,6), mapTagReplacements); -// float horizontalSpreadA; - particleSystemTypeSplashNode->addAttribute("horizontalSpreadA",floatToStr(horizontalSpreadA,6), mapTagReplacements); -// float horizontalSpreadB; - particleSystemTypeSplashNode->addAttribute("horizontalSpreadB",floatToStr(horizontalSpreadB,6), mapTagReplacements); + ParticleSystemType::saveGame(rootNode); + + std::map mapTagReplacements; + XmlNode *particleSystemTypeSplashNode = + rootNode->addChild("ParticleSystemTypeSplash"); + + // float emissionRateFade; + particleSystemTypeSplashNode->addAttribute( + "emissionRateFade", floatToStr(emissionRateFade, 6), mapTagReplacements); + // float verticalSpreadA; + particleSystemTypeSplashNode->addAttribute( + "verticalSpreadA", floatToStr(verticalSpreadA, 6), mapTagReplacements); + // float verticalSpreadB; + particleSystemTypeSplashNode->addAttribute( + "verticalSpreadB", floatToStr(verticalSpreadB, 6), mapTagReplacements); + // float horizontalSpreadA; + particleSystemTypeSplashNode->addAttribute("horizontalSpreadA", + floatToStr(horizontalSpreadA, 6), + mapTagReplacements); + // float horizontalSpreadB; + particleSystemTypeSplashNode->addAttribute("horizontalSpreadB", + floatToStr(horizontalSpreadB, 6), + mapTagReplacements); } -}}//end mamespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/graphics/particle_type.h b/source/glest_game/graphics/particle_type.h index 0291cbbf7..55f1f8990 100644 --- a/source/glest_game/graphics/particle_type.h +++ b/source/glest_game/graphics/particle_type.h @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,156 +13,159 @@ #define _GLEST_GAME_PARTICLETYPE_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include -#include -#include "particle.h" #include "factory.h" +#include "graphics_interface.h" +#include "leak_dumper.h" +#include "particle.h" #include "texture.h" #include "vec.h" #include "xml_parser.h" -#include "graphics_interface.h" -#include "leak_dumper.h" +#include +#include using std::string; using namespace Shared::Graphics; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { -using Shared::Graphics::ParticleSystem; -using Shared::Graphics::UnitParticleSystem; using Shared::Graphics::AttackParticleSystem; +using Shared::Graphics::Model; +using Shared::Graphics::ParticleSystem; using Shared::Graphics::ProjectileParticleSystem; using Shared::Graphics::SplashParticleSystem; using Shared::Graphics::Texture2D; +using Shared::Graphics::UnitParticleSystem; using Shared::Graphics::Vec3f; using Shared::Graphics::Vec4f; -using Shared::Graphics::Model; using Shared::Util::MultiFactory; using Shared::Xml::XmlNode; class UnitParticleSystemType; // =========================================================== -// class ParticleSystemType +// class ParticleSystemType // /// A type of particle system // =========================================================== class ParticleSystemType : public ParticleSystemTypeInterface { protected: - string type; - Texture2D *texture; - Model *model; - float modelCycle; - string primitive; - Vec3f offset; - Vec4f color; - Vec4f colorNoEnergy; - float size; - float sizeNoEnergy; - float speed; - float speedUpRelative; - float speedUpConstant; - float gravity; - float emissionRate; - int energyMax; - int energyVar; - string mode; - bool teamcolorNoEnergy; - bool teamcolorEnergy; - int alternations; - int particleSystemStartDelay; - typedef std::list Children; - Children children; - - bool minmaxEnabled; - int minHp; - int maxHp; - bool minmaxIsPercent; - - void copyAll(const ParticleSystemType &src); -public: + string type; + Texture2D *texture; + Model *model; + float modelCycle; + string primitive; + Vec3f offset; + Vec4f color; + Vec4f colorNoEnergy; + float size; + float sizeNoEnergy; + float speed; + float speedUpRelative; + float speedUpConstant; + float gravity; + float emissionRate; + int energyMax; + int energyVar; + string mode; + bool teamcolorNoEnergy; + bool teamcolorEnergy; + int alternations; + int particleSystemStartDelay; + typedef std::list Children; + Children children; + + bool minmaxEnabled; + int minHp; + int maxHp; + bool minmaxIsPercent; + + void copyAll(const ParticleSystemType &src); - ParticleSystemType(); - virtual ~ParticleSystemType(); +public: + ParticleSystemType(); + virtual ~ParticleSystemType(); - ParticleSystemType & operator=(const ParticleSystemType &src); - ParticleSystemType(const ParticleSystemType &src); + ParticleSystemType &operator=(const ParticleSystemType &src); + ParticleSystemType(const ParticleSystemType &src); - void load(const XmlNode *particleSystemNode, const string &dir, - RendererInterface *renderer, std::map > > &loadedFileList, - string parentLoader, string techtreePath); - void setValues(AttackParticleSystem *ats); - bool hasTexture() const { return(texture != NULL); } - bool hasModel() const { return(model != NULL); } + void load(const XmlNode *particleSystemNode, const string &dir, + RendererInterface *renderer, + std::map>> &loadedFileList, + string parentLoader, string techtreePath); + void setValues(AttackParticleSystem *ats); + bool hasTexture() const { return (texture != NULL); } + bool hasModel() const { return (model != NULL); } - bool getMinmaxEnabled() const { return minmaxEnabled;} - int getMinHp() const { return minHp;} - int getMaxHp() const { return maxHp;} - bool getMinmaxIsPercent() const { return minmaxIsPercent; } + bool getMinmaxEnabled() const { return minmaxEnabled; } + int getMinHp() const { return minHp; } + int getMaxHp() const { return maxHp; } + bool getMinmaxIsPercent() const { return minmaxIsPercent; } - void setMinmaxEnabled(bool value) { minmaxEnabled=value;} - void setMinHp(int value) { minHp=value;} - void setMaxHp(int value) { maxHp=value;} - void setMinmaxIsPercent(bool value) { minmaxIsPercent=value; } + void setMinmaxEnabled(bool value) { minmaxEnabled = value; } + void setMinHp(int value) { minHp = value; } + void setMaxHp(int value) { maxHp = value; } + void setMinmaxIsPercent(bool value) { minmaxIsPercent = value; } - string getType() const { return type; }; + string getType() const { return type; }; - virtual void saveGame(XmlNode *rootNode); - virtual void loadGame(const XmlNode *rootNode); + virtual void saveGame(XmlNode *rootNode); + virtual void loadGame(const XmlNode *rootNode); protected: - }; // =========================================================== // class ParticleSystemTypeProjectile // =========================================================== -class ParticleSystemTypeProjectile: public ParticleSystemType{ +class ParticleSystemTypeProjectile : public ParticleSystemType { private: - string trajectory; - float trajectorySpeed; - float trajectoryScale; - float trajectoryFrequency; + string trajectory; + float trajectorySpeed; + float trajectoryScale; + float trajectoryFrequency; public: - ParticleSystemTypeProjectile(); - void load(const XmlNode *particleFileNode, const string &dir, const string &path, - RendererInterface *renderer, std::map > > &loadedFileList, - string parentLoader, string techtreePath); - ProjectileParticleSystem *create(ParticleOwner *owner); - - virtual void saveGame(XmlNode *rootNode); + ParticleSystemTypeProjectile(); + void load(const XmlNode *particleFileNode, const string &dir, + const string &path, RendererInterface *renderer, + std::map>> &loadedFileList, + string parentLoader, string techtreePath); + ProjectileParticleSystem *create(ParticleOwner *owner); + + virtual void saveGame(XmlNode *rootNode); }; // =========================================================== // class ParticleSystemTypeSplash // =========================================================== -class ParticleSystemTypeSplash: public ParticleSystemType { +class ParticleSystemTypeSplash : public ParticleSystemType { public: + ParticleSystemTypeSplash(); + void load(const XmlNode *particleFileNode, const string &dir, + const string &path, RendererInterface *renderer, + std::map>> &loadedFileList, + string parentLoader, string techtreePath); + SplashParticleSystem *create(ParticleOwner *owner); - ParticleSystemTypeSplash(); - void load(const XmlNode *particleFileNode, const string &dir, const string &path, - RendererInterface *renderer, std::map > > &loadedFileList, - string parentLoader, string techtreePath); - SplashParticleSystem *create(ParticleOwner *owner); - - virtual void saveGame(XmlNode *rootNode); + virtual void saveGame(XmlNode *rootNode); private: - float emissionRateFade; - float verticalSpreadA; - float verticalSpreadB; - float horizontalSpreadA; - float horizontalSpreadB; + float emissionRateFade; + float verticalSpreadA; + float verticalSpreadB; + float horizontalSpreadA; + float horizontalSpreadB; }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/graphics/renderer.cpp b/source/glest_game/graphics/renderer.cpp index 4b399d7e9..943291677 100644 --- a/source/glest_game/graphics/renderer.cpp +++ b/source/glest_game/graphics/renderer.cpp @@ -11,43 +11,41 @@ #define NOMINMAX #include "renderer.h" -#include "texture_gl.h" -#include "main_menu.h" -#include "config.h" +#include "cache_manager.h" #include "components.h" -#include "time_flow.h" -#include "graphics_interface.h" -#include "object.h" +#include "config.h" #include "core_data.h" -#include "game.h" -#include "metrics.h" -#include "opengl.h" #include "faction.h" #include "factory_repository.h" -#include -#include "cache_manager.h" +#include "game.h" +#include "graphics_interface.h" +#include "leak_dumper.h" +#include "main_menu.h" +#include "metrics.h" #include "network_manager.h" +#include "object.h" +#include "opengl.h" +#include "texture_gl.h" +#include "time_flow.h" #include +#include #include -#include "leak_dumper.h" using namespace Shared::Graphics; using namespace Shared::Graphics::Gl; using namespace Shared::Util; using namespace Shared::Graphics; -namespace Glest { namespace Game{ +namespace Glest { +namespace Game { uint32 Renderer::SurfaceData::nextUniqueId = 1; bool Renderer::renderText3DEnabled = true; -//const float SKIP_INTERPOLATION_DISTANCE = 20.0f; +// const float SKIP_INTERPOLATION_DISTANCE = 20.0f; const string DEFAULT_CHAR_FOR_WIDTH_CALC = "V"; -enum PROJECTION_TO_INFINITY { - pti_D_IS_ZERO, - pti_N_OVER_D_IS_OUTSIDE -}; +enum PROJECTION_TO_INFINITY { pti_D_IS_ZERO, pti_N_OVER_D_IS_OUTSIDE }; // ===================================================== // class MeshCallbackTeamColor @@ -56,58 +54,58 @@ enum PROJECTION_TO_INFINITY { bool MeshCallbackTeamColor::noTeamColors = false; void MeshCallbackTeamColor::execute(const Mesh *mesh) { - //team color - if( mesh->getCustomTexture() && teamTexture != NULL && - MeshCallbackTeamColor::noTeamColors == false) { - //texture 0 - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); + // team color + if (mesh->getCustomTexture() && teamTexture != NULL && + MeshCallbackTeamColor::noTeamColors == false) { + // texture 0 + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); - //set color to interpolation - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_INTERPOLATE); + // set color to interpolation + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_INTERPOLATE); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_TEXTURE); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_TEXTURE); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_TEXTURE1); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_TEXTURE1); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB, GL_TEXTURE); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_ALPHA); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB, GL_TEXTURE); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_ALPHA); - //set alpha to 1 - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_TEXTURE); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA); + // set alpha to 1 + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_TEXTURE); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA); - //texture 1 - glActiveTexture(GL_TEXTURE1); - glMultiTexCoord2f(GL_TEXTURE1, 0.f, 0.f); - glEnable(GL_TEXTURE_2D); + // texture 1 + glActiveTexture(GL_TEXTURE1); + glMultiTexCoord2f(GL_TEXTURE1, 0.f, 0.f); + glEnable(GL_TEXTURE_2D); - glBindTexture(GL_TEXTURE_2D, static_cast(teamTexture)->getHandle()); - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); + glBindTexture(GL_TEXTURE_2D, + static_cast(teamTexture)->getHandle()); + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE); + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PRIMARY_COLOR); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PRIMARY_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_PREVIOUS); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_PREVIOUS); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR); - //set alpha to 1 - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_PRIMARY_COLOR); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA); + // set alpha to 1 + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_PRIMARY_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA); - glActiveTexture(GL_TEXTURE0); - } - else { - glActiveTexture(GL_TEXTURE1); - glDisable(GL_TEXTURE_2D); - glActiveTexture(GL_TEXTURE0); - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - } + glActiveTexture(GL_TEXTURE0); + } else { + glActiveTexture(GL_TEXTURE1); + glDisable(GL_TEXTURE_2D); + glActiveTexture(GL_TEXTURE0); + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + } } // =========================================================== @@ -116,733 +114,874 @@ void MeshCallbackTeamColor::execute(const Mesh *mesh) { // ===================== PUBLIC ======================== -const int Renderer::maxProgressBar= 100; -const Vec4f Renderer::progressBarBack1= Vec4f(0.7f, 0.7f, 0.7f, 0.7f); -const Vec4f Renderer::progressBarBack2= Vec4f(0.7f, 0.7f, 0.7f, 1.f); -const Vec4f Renderer::progressBarFront1= Vec4f(0.f, 0.5f, 0.f, 1.f); -const Vec4f Renderer::progressBarFront2= Vec4f(0.f, 0.1f, 0.f, 1.f); +const int Renderer::maxProgressBar = 100; +const Vec4f Renderer::progressBarBack1 = Vec4f(0.7f, 0.7f, 0.7f, 0.7f); +const Vec4f Renderer::progressBarBack2 = Vec4f(0.7f, 0.7f, 0.7f, 1.f); +const Vec4f Renderer::progressBarFront1 = Vec4f(0.f, 0.5f, 0.f, 1.f); +const Vec4f Renderer::progressBarFront2 = Vec4f(0.f, 0.1f, 0.f, 1.f); -const float Renderer::sunDist= 10e6; -const float Renderer::moonDist= 10e6; -const float Renderer::lightAmbFactor= 0.4f; +const float Renderer::sunDist = 10e6; +const float Renderer::moonDist = 10e6; +const float Renderer::lightAmbFactor = 0.4f; -const int Renderer::maxMouse2dAnim= 100; +const int Renderer::maxMouse2dAnim = 100; -const GLenum Renderer::baseTexUnit= GL_TEXTURE0; -const GLenum Renderer::fowTexUnit= GL_TEXTURE1; -const GLenum Renderer::shadowTexUnit= GL_TEXTURE2; +const GLenum Renderer::baseTexUnit = GL_TEXTURE0; +const GLenum Renderer::fowTexUnit = GL_TEXTURE1; +const GLenum Renderer::shadowTexUnit = GL_TEXTURE2; -const float Renderer::selectionCircleRadius= 0.7f; -const float Renderer::magicCircleRadius= 1.f; +const float Renderer::selectionCircleRadius = 0.7f; +const float Renderer::magicCircleRadius = 1.f; -//perspective values -const float Renderer::perspFov= 60.f; -const float Renderer::perspNearPlane= 1.f; -//const float Renderer::perspFarPlane= 50.f; -float Renderer::perspFarPlane= 1000000.f; +// perspective values +const float Renderer::perspFov = 60.f; +const float Renderer::perspNearPlane = 1.f; +// const float Renderer::perspFarPlane= 50.f; +float Renderer::perspFarPlane = 1000000.f; -const float Renderer::ambFactor= 0.7f; -const Vec4f Renderer::fowColor= Vec4f(0.0f, 0.0f, 0.0f, 1.0f); -const Vec4f Renderer::defSpecularColor= Vec4f(0.8f, 0.8f, 0.8f, 1.f); -const Vec4f Renderer::defDiffuseColor= Vec4f(1.f, 1.f, 1.f, 1.f); -const Vec4f Renderer::defAmbientColor= Vec4f(1.f * ambFactor, 1.f * ambFactor, 1.f * ambFactor, 1.f); -const Vec4f Renderer::defColor= Vec4f(1.f, 1.f, 1.f, 1.f); +const float Renderer::ambFactor = 0.7f; +const Vec4f Renderer::fowColor = Vec4f(0.0f, 0.0f, 0.0f, 1.0f); +const Vec4f Renderer::defSpecularColor = Vec4f(0.8f, 0.8f, 0.8f, 1.f); +const Vec4f Renderer::defDiffuseColor = Vec4f(1.f, 1.f, 1.f, 1.f); +const Vec4f Renderer::defAmbientColor = + Vec4f(1.f * ambFactor, 1.f * ambFactor, 1.f * ambFactor, 1.f); +const Vec4f Renderer::defColor = Vec4f(1.f, 1.f, 1.f, 1.f); -//const float Renderer::maxLightDist= 100.f; -const float Renderer::maxLightDist= 100.f; +// const float Renderer::maxLightDist= 100.f; +const float Renderer::maxLightDist = 100.f; bool Renderer::rendererEnded = true; const int MIN_FPS_NORMAL_RENDERING = 15; const int MIN_FPS_NORMAL_RENDERING_TOP_THRESHOLD = 25; -const int OBJECT_SELECT_OFFSET=100000000; +const int OBJECT_SELECT_OFFSET = 100000000; bool VisibleQuadContainerCache::enableFrustumCalcs = true; // ==================== constructor and destructor ==================== -Renderer::Renderer() : BaseRenderer(), saveScreenShotThreadAccessor(new Mutex(CODE_AT_LINE)) { - //this->masterserverMode = masterserverMode; - //printf("this->masterserverMode = %d\n",this->masterserverMode); - //assert(0==1); - - Renderer::rendererEnded = false; - shadowIntensity = 0; - shadowFrameSkip = 0; - triangleCount = 0; - smoothedRenderFps = 0; - shadowTextureSize = 0; - shadows = sDisabled; - shadowMapFrame = 0; - textures3D = false; - photoMode = false; - focusArrows = false; - pointCount = 0; - maxLights = 0; - waterAnim = 0; - - this->allowRenderUnitTitles = false; - this->menu = NULL; - this->game = NULL; - this->gameCamera = NULL; - showDebugUI = false; - showDebugUILevel = debugui_fps; - modelRenderer = NULL; - textRenderer = NULL; - textRenderer3D = NULL; - particleRenderer = NULL; - saveScreenShotThread = NULL; - mapSurfaceData.clear(); - visibleFrameUnitList.clear(); - visibleFrameUnitListCameraKey = ""; - - quadCache = VisibleQuadContainerCache(); - quadCache.clearFrustumData(); - - lastRenderFps=MIN_FPS_NORMAL_RENDERING; - shadowsOffDueToMinRender=false; - shadowMapHandle=0; - shadowMapHandleValid=false; - - //list3d=0; - //list3dValid=false; - //list2d=0; - //list2dValid=false; - //list3dMenu=0; - //list3dMenuValid=false; - //customlist3dMenu=NULL; - //this->mm3d = NULL; - this->custom_mm3d = NULL; - - this->program = NULL; - - //resources - for(int i=0; i < rsCount; ++i) { - modelManager[i] = NULL; - textureManager[i] = NULL; - particleManager[i] = NULL; - fontManager[i] = NULL; - } - - Config &config= Config::getInstance(); - - Renderer::perspFarPlane = config.getFloat("PerspectiveFarPlane",floatToStr(Renderer::perspFarPlane).c_str()); - this->no2DMouseRendering = config.getBool("No2DMouseRendering","false"); - this->maxConsoleLines= config.getInt("ConsoleMaxLines"); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] Renderer::perspFarPlane [%f] this->no2DMouseRendering [%d] this->maxConsoleLines [%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,Renderer::perspFarPlane,this->no2DMouseRendering,this->maxConsoleLines); - - GraphicsInterface &gi= GraphicsInterface::getInstance(); - FactoryRepository &fr= FactoryRepository::getInstance(); - gi.setFactory(fr.getGraphicsFactory(config.getString("FactoryGraphics"))); - GraphicsFactory *graphicsFactory= GraphicsInterface::getInstance().getFactory(); - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - modelRenderer= graphicsFactory->newModelRenderer(); - textRenderer= graphicsFactory->newTextRenderer2D(); - textRenderer3D = graphicsFactory->newTextRenderer3D(); - particleRenderer= graphicsFactory->newParticleRenderer(); - } - - //resources - for(int i=0; i< rsCount; ++i) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - modelManager[i]= graphicsFactory->newModelManager(); - textureManager[i]= graphicsFactory->newTextureManager(); - modelManager[i]->setTextureManager(textureManager[i]); - fontManager[i]= graphicsFactory->newFontManager(); - } - particleManager[i]= graphicsFactory->newParticleManager(); - } - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); - saveScreenShotThread = new SimpleTaskThread(this,0,25); - saveScreenShotThread->setUniqueID(mutexOwnerId); - saveScreenShotThread->start(); - } +Renderer::Renderer() + : BaseRenderer(), saveScreenShotThreadAccessor(new Mutex(CODE_AT_LINE)) { + // this->masterserverMode = masterserverMode; + // printf("this->masterserverMode = %d\n",this->masterserverMode); + // assert(0==1); + + Renderer::rendererEnded = false; + shadowIntensity = 0; + shadowFrameSkip = 0; + triangleCount = 0; + smoothedRenderFps = 0; + shadowTextureSize = 0; + shadows = sDisabled; + shadowMapFrame = 0; + textures3D = false; + photoMode = false; + focusArrows = false; + pointCount = 0; + maxLights = 0; + waterAnim = 0; + + this->allowRenderUnitTitles = false; + this->menu = NULL; + this->game = NULL; + this->gameCamera = NULL; + showDebugUI = false; + showDebugUILevel = debugui_fps; + modelRenderer = NULL; + textRenderer = NULL; + textRenderer3D = NULL; + particleRenderer = NULL; + saveScreenShotThread = NULL; + mapSurfaceData.clear(); + visibleFrameUnitList.clear(); + visibleFrameUnitListCameraKey = ""; + + quadCache = VisibleQuadContainerCache(); + quadCache.clearFrustumData(); + + lastRenderFps = MIN_FPS_NORMAL_RENDERING; + shadowsOffDueToMinRender = false; + shadowMapHandle = 0; + shadowMapHandleValid = false; + + // list3d=0; + // list3dValid=false; + // list2d=0; + // list2dValid=false; + // list3dMenu=0; + // list3dMenuValid=false; + // customlist3dMenu=NULL; + // this->mm3d = NULL; + this->custom_mm3d = NULL; + + this->program = NULL; + + // resources + for (int i = 0; i < rsCount; ++i) { + modelManager[i] = NULL; + textureManager[i] = NULL; + particleManager[i] = NULL; + fontManager[i] = NULL; + } + + Config &config = Config::getInstance(); + + Renderer::perspFarPlane = config.getFloat( + "PerspectiveFarPlane", floatToStr(Renderer::perspFarPlane).c_str()); + this->no2DMouseRendering = config.getBool("No2DMouseRendering", "false"); + this->maxConsoleLines = config.getInt("ConsoleMaxLines"); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] Renderer::perspFarPlane [%f] " + "this->no2DMouseRendering [%d] this->maxConsoleLines [%d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, Renderer::perspFarPlane, this->no2DMouseRendering, + this->maxConsoleLines); + + GraphicsInterface &gi = GraphicsInterface::getInstance(); + FactoryRepository &fr = FactoryRepository::getInstance(); + gi.setFactory(fr.getGraphicsFactory(config.getString("FactoryGraphics"))); + GraphicsFactory *graphicsFactory = + GraphicsInterface::getInstance().getFactory(); + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + modelRenderer = graphicsFactory->newModelRenderer(); + textRenderer = graphicsFactory->newTextRenderer2D(); + textRenderer3D = graphicsFactory->newTextRenderer3D(); + particleRenderer = graphicsFactory->newParticleRenderer(); + } + + // resources + for (int i = 0; i < rsCount; ++i) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + modelManager[i] = graphicsFactory->newModelManager(); + textureManager[i] = graphicsFactory->newTextureManager(); + modelManager[i]->setTextureManager(textureManager[i]); + fontManager[i] = graphicsFactory->newFontManager(); + } + particleManager[i] = graphicsFactory->newParticleManager(); + } + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + static string mutexOwnerId = + string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + + intToStr(__LINE__); + saveScreenShotThread = new SimpleTaskThread(this, 0, 25); + saveScreenShotThread->setUniqueID(mutexOwnerId); + saveScreenShotThread->start(); + } } void Renderer::cleanupScreenshotThread() { - if(saveScreenShotThread) { - saveScreenShotThread->signalQuit(); -// for(time_t elapsed = time(NULL); -// getSaveScreenQueueSize() > 0 && difftime((long int)time(NULL),elapsed) <= 7;) { -// sleep(0); -// } -// if(saveScreenShotThread->canShutdown(true) == true && -// saveScreenShotThread->shutdownAndWait() == true) { -// //printf("IN MenuStateCustomGame cleanup - C\n"); -// delete saveScreenShotThread; -// } -// saveScreenShotThread = NULL; - if(saveScreenShotThread->shutdownAndWait() == true) { - delete saveScreenShotThread; - } - saveScreenShotThread = NULL; - - - if(getSaveScreenQueueSize() > 0) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] FORCING MEMORY CLEANUP and NOT SAVING screenshots, saveScreenQueue.size() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,saveScreenQueue.size()); - - static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(saveScreenShotThreadAccessor,mutexOwnerId); - for(std::list >::iterator iter = saveScreenQueue.begin(); - iter != saveScreenQueue.end(); ++iter) { - delete iter->second; - } - saveScreenQueue.clear(); - } - } + if (saveScreenShotThread) { + saveScreenShotThread->signalQuit(); + // for(time_t elapsed = time(NULL); + // getSaveScreenQueueSize() > 0 && difftime((long + // int)time(NULL),elapsed) <= 7;) { sleep(0); + // } + // if(saveScreenShotThread->canShutdown(true) == true && + // saveScreenShotThread->shutdownAndWait() == true) + //{ + // //printf("IN MenuStateCustomGame cleanup - C\n"); + // delete saveScreenShotThread; + // } + // saveScreenShotThread = NULL; + if (saveScreenShotThread->shutdownAndWait() == true) { + delete saveScreenShotThread; + } + saveScreenShotThread = NULL; + + if (getSaveScreenQueueSize() > 0) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line %d] FORCING MEMORY CLEANUP and NOT SAVING " + "screenshots, saveScreenQueue.size() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, saveScreenQueue.size()); + + static string mutexOwnerId = + string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + + intToStr(__LINE__); + MutexSafeWrapper safeMutex(saveScreenShotThreadAccessor, mutexOwnerId); + for (std::list>::iterator iter = + saveScreenQueue.begin(); + iter != saveScreenQueue.end(); ++iter) { + delete iter->second; + } + saveScreenQueue.clear(); + } + } } Renderer::~Renderer() { - try{ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - delete modelRenderer; - modelRenderer = NULL; - delete textRenderer; - textRenderer = NULL; - delete textRenderer3D; - textRenderer3D = NULL; - delete particleRenderer; - particleRenderer = NULL; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //resources - for(int i=0; imenu = NULL; - this->game = NULL; - this->gameCamera = NULL; - - delete saveScreenShotThreadAccessor; - saveScreenShotThreadAccessor = NULL; - } - catch(const exception &e) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d]\nError [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,szBuf); - - throw megaglest_runtime_error(szBuf); - } -} - -void Renderer::simpleTask(BaseThread *callingThread,void *userdata) { - // This code reads pixmaps from a queue and saves them to disk - Pixmap2D *savePixMapBuffer=NULL; - string path=""; - static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(saveScreenShotThreadAccessor,mutexOwnerId); - if(saveScreenQueue.empty() == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] saveScreenQueue.size() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,saveScreenQueue.size()); - - savePixMapBuffer = saveScreenQueue.front().second; - path = saveScreenQueue.front().first; - - saveScreenQueue.pop_front(); - } - safeMutex.ReleaseLock(); - - if(savePixMapBuffer != NULL) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] about to save [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,path.c_str()); - - savePixMapBuffer->save(path); - delete savePixMapBuffer; - } -} + try { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + delete modelRenderer; + modelRenderer = NULL; + delete textRenderer; + textRenderer = NULL; + delete textRenderer3D; + textRenderer3D = NULL; + delete particleRenderer; + particleRenderer = NULL; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // resources + for (int i = 0; i < rsCount; ++i) { + delete modelManager[i]; + modelManager[i] = NULL; + delete textureManager[i]; + textureManager[i] = NULL; + delete particleManager[i]; + particleManager[i] = NULL; + delete fontManager[i]; + fontManager[i] = NULL; + } -bool Renderer::isEnded() { - return Renderer::rendererEnded; -} + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // Wait for the queue to become empty or timeout the thread at 7 seconds + cleanupScreenshotThread(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + mapSurfaceData.clear(); + quadCache = VisibleQuadContainerCache(); + quadCache.clearFrustumData(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + this->menu = NULL; + this->game = NULL; + this->gameCamera = NULL; + + delete saveScreenShotThreadAccessor; + saveScreenShotThreadAccessor = NULL; + } catch (const exception &e) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d]\nError [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, e.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, szBuf); + + throw megaglest_runtime_error(szBuf); + } +} + +void Renderer::simpleTask(BaseThread *callingThread, void *userdata) { + // This code reads pixmaps from a queue and saves them to disk + Pixmap2D *savePixMapBuffer = NULL; + string path = ""; + static string mutexOwnerId = + string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + + intToStr(__LINE__); + MutexSafeWrapper safeMutex(saveScreenShotThreadAccessor, mutexOwnerId); + if (saveScreenQueue.empty() == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line %d] saveScreenQueue.size() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, saveScreenQueue.size()); + + savePixMapBuffer = saveScreenQueue.front().second; + path = saveScreenQueue.front().first; + + saveScreenQueue.pop_front(); + } + safeMutex.ReleaseLock(); + + if (savePixMapBuffer != NULL) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d] about to save [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, path.c_str()); + + savePixMapBuffer->save(path); + delete savePixMapBuffer; + } +} + +bool Renderer::isEnded() { return Renderer::rendererEnded; } Renderer &Renderer::getInstance() { - static Renderer renderer; - return renderer; + static Renderer renderer; + return renderer; } void Renderer::reinitAll() { - //resources - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - for(int i=0; iinit(); - textureManager[i]->init(true); - //particleManager[i]->init(); - //fontManager[i]->init(); - } + // resources + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + for (int i = 0; i < rsCount; ++i) { + // modelManager[i]->init(); + textureManager[i]->init(true); + // particleManager[i]->init(); + // fontManager[i]->init(); + } } // ==================== init ==================== void Renderer::init() { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - Config &config= Config::getInstance(); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + Config &config = Config::getInstance(); - loadConfig(); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + loadConfig(); - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - if(config.getBool("CheckGlCaps")){ + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (config.getBool("CheckGlCaps")) { - checkGlCaps(); - } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - if(glActiveTexture == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Error: glActiveTexture == NULL\nglActiveTexture is only supported if the GL version is 1.3 or greater,\nor if the ARB_multitexture extension is supported!"); - throw megaglest_runtime_error(szBuf); - } + checkGlCaps(); + } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (glActiveTexture == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "Error: glActiveTexture == NULL\nglActiveTexture is only " + "supported if the GL version is 1.3 or greater,\nor if the " + "ARB_multitexture extension is supported!"); + throw megaglest_runtime_error(szBuf); + } - if(config.getBool("FirstTime")){ - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - config.setBool("FirstTime", false); - autoConfig(); + if (config.getBool("FirstTime")) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + config.setBool("FirstTime", false); + autoConfig(); - config.save(); - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - modelManager[rsGlobal]->init(); + config.save(); + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + modelManager[rsGlobal]->init(); - textureManager[rsGlobal]->init(); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + textureManager[rsGlobal]->init(); - fontManager[rsGlobal]->init(); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + fontManager[rsGlobal]->init(); - init2dList(); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + init2dList(); - glHint(GL_FOG_HINT, GL_FASTEST); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //glHint(GL_GENERATE_MIPMAP_HINT, GL_FASTEST); - glHint(GL_LINE_SMOOTH_HINT, GL_FASTEST); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST); - //glHint(GL_POINT_SMOOTH_HINT, GL_FASTEST); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - //glHint(GL_POLYGON_SMOOTH_HINT, GL_FASTEST); - glHint(GL_TEXTURE_COMPRESSION_HINT, GL_FASTEST); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + glHint(GL_FOG_HINT, GL_FASTEST); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + // glHint(GL_GENERATE_MIPMAP_HINT, GL_FASTEST); + glHint(GL_LINE_SMOOTH_HINT, GL_FASTEST); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + // glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST); + // glHint(GL_POINT_SMOOTH_HINT, GL_FASTEST); + // glHint(GL_POLYGON_SMOOTH_HINT, GL_FASTEST); + glHint(GL_TEXTURE_COMPRESSION_HINT, GL_FASTEST); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); } void Renderer::initGame(const Game *game, GameCamera *gameCamera) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - this->gameCamera = gameCamera; - VisibleQuadContainerCache::enableFrustumCalcs = Config::getInstance().getBool("EnableFrustrumCalcs","true"); - quadCache = VisibleQuadContainerCache(); - quadCache.clearFrustumData(); - - SurfaceData::nextUniqueId = 1; - mapSurfaceData.clear(); - this->game= game; - worldToScreenPosCache.clear(); - - //vars - shadowMapFrame= 0; - waterAnim= 0; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - //check gl caps - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - checkGlOptionalCaps(); - - //shadows - if(shadows == sProjected || shadows == sShadowMapping) { - static_cast(modelRenderer)->setSecondaryTexCoordUnit(2); - Config &config= Config::getInstance(); - - glGenTextures(1, &shadowMapHandle); - shadowMapHandleValid=true; - - shadowIntensity= config.getFloat("ShadowIntensity","1.0"); - if(game!=NULL){ - shadowIntensity=shadowIntensity*game->getWorld()->getTileset()->getShadowIntense(); - if(shadowIntensity > 1.0f){ - shadowIntensity=1.0f; - } - } - - glBindTexture(GL_TEXTURE_2D, shadowMapHandle); - - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - - if(shadows == sShadowMapping) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //shadow mapping - glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_LUMINANCE); - //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB, GL_COMPARE_R_TO_TEXTURE_ARB); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB, GL_NONE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC_ARB, GL_LEQUAL); - //glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FAIL_VALUE_ARB, 1.0f-shadowAlpha); - - glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, - shadowTextureSize, shadowTextureSize, - 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + this->gameCamera = gameCamera; + VisibleQuadContainerCache::enableFrustumCalcs = + Config::getInstance().getBool("EnableFrustrumCalcs", "true"); + quadCache = VisibleQuadContainerCache(); + quadCache.clearFrustumData(); + + SurfaceData::nextUniqueId = 1; + mapSurfaceData.clear(); + this->game = game; + worldToScreenPosCache.clear(); + + // vars + shadowMapFrame = 0; + waterAnim = 0; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + // check gl caps + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + checkGlOptionalCaps(); + + // shadows + if (shadows == sProjected || shadows == sShadowMapping) { + static_cast(modelRenderer)->setSecondaryTexCoordUnit(2); + Config &config = Config::getInstance(); + + glGenTextures(1, &shadowMapHandle); + shadowMapHandleValid = true; + + shadowIntensity = config.getFloat("ShadowIntensity", "1.0"); + if (game != NULL) { + shadowIntensity = + shadowIntensity * game->getWorld()->getTileset()->getShadowIntense(); + if (shadowIntensity > 1.0f) { + shadowIntensity = 1.0f; + } + } - //projected - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, - shadowTextureSize, shadowTextureSize, - 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, NULL); - } + glBindTexture(GL_TEXTURE_2D, shadowMapHandle); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + + if (shadows == sShadowMapping) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // shadow mapping + glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_LUMINANCE); + // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB, + // GL_COMPARE_R_TO_TEXTURE_ARB); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB, GL_NONE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC_ARB, GL_LEQUAL); + // glTexParameterf(GL_TEXTURE_2D, + // GL_TEXTURE_COMPARE_FAIL_VALUE_ARB, 1.0f-shadowAlpha); + + glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, shadowTextureSize, + shadowTextureSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, + NULL); + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // projected + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, shadowTextureSize, + shadowTextureSize, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, NULL); + } - shadowMapFrame= -1; - } + shadowMapFrame = -1; + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - IF_DEBUG_EDITION( getDebugRenderer().init(); ) + IF_DEBUG_EDITION(getDebugRenderer().init();) - //texture init - modelManager[rsGame]->init(); - textureManager[rsGame]->init(); - fontManager[rsGame]->init(); + // texture init + modelManager[rsGame]->init(); + textureManager[rsGame]->init(); + fontManager[rsGame]->init(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - init3dList(); + init3dList(); } void Renderer::manageDeferredParticleSystems() { -// if(deferredParticleSystems.empty() == false) { -// printf("deferredParticleSystems.size() = %d\n",(int)deferredParticleSystems.size()); -// } - - for(unsigned int i = 0; i < deferredParticleSystems.size(); ++i) { - std::pair &deferredParticleSystem = deferredParticleSystems[i]; - ParticleSystem *ps = deferredParticleSystem.first; - ResourceScope rs = deferredParticleSystem.second; - if(ps->getTextureFileLoadDeferred() != "" && ps->getTexture() == NULL) { - CoreData::TextureSystemType textureSystemId = - static_cast( - ps->getTextureFileLoadDeferredSystemId()); - - //printf("Load DEFERRED particle i = %d textureSystemId = %d\n",i,textureSystemId); - - if(textureSystemId != CoreData::tsyst_NONE) { - Texture2D *texture= CoreData::getInstance().getTextureBySystemId(textureSystemId); - //printf("Loading texture from system [%d] [%p]\n",textureSystemId,texture); - ps->setTexture(texture); - - //printf("#2 Load DEFERRED particle i = %d textureSystemId = %d, texture = %p\n",i,textureSystemId,texture); - } - else { - Texture2D *texture= newTexture2D(rs); - if(texture) { - texture->setFormat(ps->getTextureFileLoadDeferredFormat()); - texture->getPixmap()->init(ps->getTextureFileLoadDeferredComponents()); - } - if(texture) { - string textureFile = ps->getTextureFileLoadDeferred(); - if(fileExists(textureFile) == false) { - textureFile = Config::findValidLocalFileFromPath(textureFile); - } - texture->load(textureFile); - ps->setTexture(texture); - } - //printf("#3 Load DEFERRED particle i = %d textureSystemId = %d, texture = %p\n",i,textureSystemId,texture); - } - } - if(dynamic_cast(ps) != NULL) { - GameParticleSystem *gps = dynamic_cast(ps); - if(gps != NULL && gps->getModelFileLoadDeferred() != "" && gps->getModel() == NULL) { - std::map > > loadedFileList; - Model *model= newModel(rsGame, gps->getModelFileLoadDeferred(), false, &loadedFileList, NULL); - if(model) - gps->setModel(model); - } - } - manageParticleSystem(ps, rs); - //printf("Managing ps [%p]\n",ps); - } - deferredParticleSystems.clear(); - //printf("After deferredParticleSystems.size() = %d\n",deferredParticleSystems.size()); + // if(deferredParticleSystems.empty() == false) { + // printf("deferredParticleSystems.size() = + //%d\n",(int)deferredParticleSystems.size()); + // } + + for (unsigned int i = 0; i < deferredParticleSystems.size(); ++i) { + std::pair &deferredParticleSystem = + deferredParticleSystems[i]; + ParticleSystem *ps = deferredParticleSystem.first; + ResourceScope rs = deferredParticleSystem.second; + if (ps->getTextureFileLoadDeferred() != "" && ps->getTexture() == NULL) { + CoreData::TextureSystemType textureSystemId = + static_cast( + ps->getTextureFileLoadDeferredSystemId()); + + // printf("Load DEFERRED particle i = %d textureSystemId = + // %d\n",i,textureSystemId); + + if (textureSystemId != CoreData::tsyst_NONE) { + Texture2D *texture = + CoreData::getInstance().getTextureBySystemId(textureSystemId); + // printf("Loading texture from system [%d] + // [%p]\n",textureSystemId,texture); + ps->setTexture(texture); + + // printf("#2 Load DEFERRED particle i = %d textureSystemId = %d, + // texture = %p\n",i,textureSystemId,texture); + } else { + Texture2D *texture = newTexture2D(rs); + if (texture) { + texture->setFormat(ps->getTextureFileLoadDeferredFormat()); + texture->getPixmap()->init( + ps->getTextureFileLoadDeferredComponents()); + } + if (texture) { + string textureFile = ps->getTextureFileLoadDeferred(); + if (fileExists(textureFile) == false) { + textureFile = Config::findValidLocalFileFromPath(textureFile); + } + texture->load(textureFile); + ps->setTexture(texture); + } + // printf("#3 Load DEFERRED particle i = %d textureSystemId = %d, + // texture = %p\n",i,textureSystemId,texture); + } + } + if (dynamic_cast(ps) != NULL) { + GameParticleSystem *gps = dynamic_cast(ps); + if (gps != NULL && gps->getModelFileLoadDeferred() != "" && + gps->getModel() == NULL) { + std::map>> loadedFileList; + Model *model = newModel(rsGame, gps->getModelFileLoadDeferred(), false, + &loadedFileList, NULL); + if (model) + gps->setModel(model); + } + } + manageParticleSystem(ps, rs); + // printf("Managing ps [%p]\n",ps); + } + deferredParticleSystems.clear(); + // printf("After deferredParticleSystems.size() = + // %d\n",deferredParticleSystems.size()); } void Renderer::initMenu(const MainMenu *mm) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - this->menu = mm; + this->menu = mm; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - modelManager[rsMenu]->init(); - textureManager[rsMenu]->init(); - fontManager[rsMenu]->init(); - //modelRenderer->setCustomTexture(CoreData::getInstance().getCustomTexture()); + modelManager[rsMenu]->init(); + textureManager[rsMenu]->init(); + fontManager[rsMenu]->init(); + // modelRenderer->setCustomTexture(CoreData::getInstance().getCustomTexture()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - //init3dListMenu(mm); + // init3dListMenu(mm); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); } void Renderer::reset3d() { - assertGl(); - glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR); - //glCallList(list3d); - render3dSetup(); + assertGl(); + glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR); + // glCallList(list3d); + render3dSetup(); - pointCount= 0; - triangleCount= 0; - assertGl(); + pointCount = 0; + triangleCount = 0; + assertGl(); } void Renderer::reset2d() { - assertGl(); - glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR); - //glCallList(list2d); - render2dMenuSetup(); - assertGl(); + assertGl(); + glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR); + // glCallList(list2d); + render2dMenuSetup(); + assertGl(); } void Renderer::reset3dMenu() { - assertGl(); - glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR); + assertGl(); + glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR); - //printf("In [%s::%s Line: %d] this->custom_mm3d [%p] this->mm3d [%p]\n",__FILE__,__FUNCTION__,__LINE__,this->custom_mm3d,this->mm3d); + // printf("In [%s::%s Line: %d] this->custom_mm3d [%p] this->mm3d + // [%p]\n",__FILE__,__FUNCTION__,__LINE__,this->custom_mm3d,this->mm3d); - if(this->custom_mm3d != NULL) { - render3dMenuSetup(this->custom_mm3d); - //glCallList(*this->customlist3dMenu); - } - else { - render3dMenuSetup(this->menu); - //render3dMenuSetup(this->mm3d); - //glCallList(list3dMenu); - } + if (this->custom_mm3d != NULL) { + render3dMenuSetup(this->custom_mm3d); + // glCallList(*this->customlist3dMenu); + } else { + render3dMenuSetup(this->menu); + // render3dMenuSetup(this->mm3d); + // glCallList(list3dMenu); + } - assertGl(); + assertGl(); } // ==================== end ==================== void Renderer::end() { - quadCache = VisibleQuadContainerCache(); - quadCache.clearFrustumData(); - - if(Renderer::rendererEnded == true) { - return; - } - std::map &crcFactionPreviewTextureCache = CacheManager::getCachedItem< std::map >(GameConstants::factionPreviewTextureCacheLookupKey); - crcFactionPreviewTextureCache.clear(); - - // Wait for the queue to become empty or timeout the thread at 7 seconds - cleanupScreenshotThread(); - - mapSurfaceData.clear(); - - //delete resources - if(modelManager[rsGlobal]) { - modelManager[rsGlobal]->end(); - } - if(textureManager[rsGlobal]) { - textureManager[rsGlobal]->end(); - } - if(fontManager[rsGlobal]) { - fontManager[rsGlobal]->end(); - } - if(particleManager[rsGlobal]) { - particleManager[rsGlobal]->end(); - } - - //delete 2d list - //if(list2dValid == true) { - // glDeleteLists(list2d, 1); - // list2dValid=false; - //} - - Renderer::rendererEnded = true; + quadCache = VisibleQuadContainerCache(); + quadCache.clearFrustumData(); + + if (Renderer::rendererEnded == true) { + return; + } + std::map &crcFactionPreviewTextureCache = + CacheManager::getCachedItem>( + GameConstants::factionPreviewTextureCacheLookupKey); + crcFactionPreviewTextureCache.clear(); + + // Wait for the queue to become empty or timeout the thread at 7 seconds + cleanupScreenshotThread(); + + mapSurfaceData.clear(); + + // delete resources + if (modelManager[rsGlobal]) { + modelManager[rsGlobal]->end(); + } + if (textureManager[rsGlobal]) { + textureManager[rsGlobal]->end(); + } + if (fontManager[rsGlobal]) { + fontManager[rsGlobal]->end(); + } + if (particleManager[rsGlobal]) { + particleManager[rsGlobal]->end(); + } + + // delete 2d list + // if(list2dValid == true) { + // glDeleteLists(list2d, 1); + // list2dValid=false; + // } + + Renderer::rendererEnded = true; } void Renderer::endScenario() { - this->game= NULL; - this->gameCamera = NULL; - quadCache = VisibleQuadContainerCache(); - quadCache.clearFrustumData(); + this->game = NULL; + this->gameCamera = NULL; + quadCache = VisibleQuadContainerCache(); + quadCache.clearFrustumData(); - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - //delete resources - //modelManager[rsGame]->end(); - //textureManager[rsGame]->end(); - //fontManager[rsGame]->end(); - //particleManager[rsGame]->end(); + // delete resources + // modelManager[rsGame]->end(); + // textureManager[rsGame]->end(); + // fontManager[rsGame]->end(); + // particleManager[rsGame]->end(); - if(shadowMapHandleValid == true && - (shadows == sProjected || shadows == sShadowMapping)) { - glDeleteTextures(1, &shadowMapHandle); - shadowMapHandleValid=false; - } + if (shadowMapHandleValid == true && + (shadows == sProjected || shadows == sShadowMapping)) { + glDeleteTextures(1, &shadowMapHandle); + shadowMapHandleValid = false; + } - //if(list3dValid == true) { - // glDeleteLists(list3d, 1); - // list3dValid=false; - //} + // if(list3dValid == true) { + // glDeleteLists(list3d, 1); + // list3dValid=false; + // } - worldToScreenPosCache.clear(); - ReleaseSurfaceVBOs(); - mapSurfaceData.clear(); + worldToScreenPosCache.clear(); + ReleaseSurfaceVBOs(); + mapSurfaceData.clear(); } void Renderer::endGame(bool isFinalEnd) { - this->game= NULL; - this->gameCamera = NULL; - Config &config= Config::getInstance(); - - try { - quadCache = VisibleQuadContainerCache(); - quadCache.clearFrustumData(); - } - catch(const exception &e) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d]\nError [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,szBuf); - - abort(); - } - - if(isFinalEnd) { - //delete resources - if(modelManager[rsGame] != NULL) { - modelManager[rsGame]->end(); - } - if(textureManager[rsGame] != NULL) { - textureManager[rsGame]->end(); - } - if(fontManager[rsGame] != NULL) { - fontManager[rsGame]->end(); - } - if(particleManager[rsGame] != NULL) { - particleManager[rsGame]->end(); - } - } - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - if(shadowMapHandleValid == true && - (shadows == sProjected || shadows == sShadowMapping)) { - glDeleteTextures(1, &shadowMapHandle); - shadowMapHandleValid=false; - } - shadowIntensity= config.getFloat("ShadowIntensity","1.0"); - - //if(list3dValid == true) { - // glDeleteLists(list3d, 1); - // list3dValid=false; - //} - - worldToScreenPosCache.clear(); - ReleaseSurfaceVBOs(); - mapSurfaceData.clear(); + this->game = NULL; + this->gameCamera = NULL; + Config &config = Config::getInstance(); + + try { + quadCache = VisibleQuadContainerCache(); + quadCache.clearFrustumData(); + } catch (const exception &e) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d]\nError [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, e.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, szBuf); + + abort(); + } + + if (isFinalEnd) { + // delete resources + if (modelManager[rsGame] != NULL) { + modelManager[rsGame]->end(); + } + if (textureManager[rsGame] != NULL) { + textureManager[rsGame]->end(); + } + if (fontManager[rsGame] != NULL) { + fontManager[rsGame]->end(); + } + if (particleManager[rsGame] != NULL) { + particleManager[rsGame]->end(); + } + } + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + if (shadowMapHandleValid == true && + (shadows == sProjected || shadows == sShadowMapping)) { + glDeleteTextures(1, &shadowMapHandle); + shadowMapHandleValid = false; + } + shadowIntensity = config.getFloat("ShadowIntensity", "1.0"); + + // if(list3dValid == true) { + // glDeleteLists(list3d, 1); + // list3dValid=false; + // } + + worldToScreenPosCache.clear(); + ReleaseSurfaceVBOs(); + mapSurfaceData.clear(); } void Renderer::endMenu() { - this->menu = NULL; - - //delete resources - if(modelManager[rsMenu]) { - modelManager[rsMenu]->end(); - } - if(textureManager[rsMenu]) { - textureManager[rsMenu]->end(); - } - if(fontManager[rsMenu]) { - fontManager[rsMenu]->end(); - } - if(particleManager[rsMenu]) { - particleManager[rsMenu]->end(); - } - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - //if(this->customlist3dMenu != NULL) { - // glDeleteLists(*this->customlist3dMenu,1); - //} - //else { - // glDeleteLists(list3dMenu, 1); - //} -} - -//void Renderer::reloadResources() { + this->menu = NULL; + + // delete resources + if (modelManager[rsMenu]) { + modelManager[rsMenu]->end(); + } + if (textureManager[rsMenu]) { + textureManager[rsMenu]->end(); + } + if (fontManager[rsMenu]) { + fontManager[rsMenu]->end(); + } + if (particleManager[rsMenu]) { + particleManager[rsMenu]->end(); + } + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + // if(this->customlist3dMenu != NULL) { + // glDeleteLists(*this->customlist3dMenu,1); + // } + // else { + // glDeleteLists(list3dMenu, 1); + // } +} + +// void Renderer::reloadResources() { // if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { // return; // } @@ -858,247 +997,282 @@ void Renderer::endMenu() { // textureManager[i]->init(); // fontManager[i]->init(); // } -//} +// } // ==================== engine interface ==================== void Renderer::initTexture(ResourceScope rs, Texture *texture) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - textureManager[rs]->initTexture(texture); -} - -void Renderer::endTexture(ResourceScope rs, Texture *texture, bool mustExistInList) { - string textureFilename = texture->getPath(); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] free texture from manager [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,textureFilename.c_str()); - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - textureManager[rs]->endTexture(texture,mustExistInList); - - if(rs == rsGlobal) { - std::map &crcFactionPreviewTextureCache = CacheManager::getCachedItem< std::map >(GameConstants::factionPreviewTextureCacheLookupKey); - if(crcFactionPreviewTextureCache.find(textureFilename) != crcFactionPreviewTextureCache.end()) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] textureFilename [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,textureFilename.c_str()); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] free texture from cache [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,textureFilename.c_str()); - - crcFactionPreviewTextureCache.erase(textureFilename); - } - } + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + textureManager[rs]->initTexture(texture); +} + +void Renderer::endTexture(ResourceScope rs, Texture *texture, + bool mustExistInList) { + string textureFilename = texture->getPath(); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] free texture from manager [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, textureFilename.c_str()); + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + textureManager[rs]->endTexture(texture, mustExistInList); + + if (rs == rsGlobal) { + std::map &crcFactionPreviewTextureCache = + CacheManager::getCachedItem>( + GameConstants::factionPreviewTextureCacheLookupKey); + if (crcFactionPreviewTextureCache.find(textureFilename) != + crcFactionPreviewTextureCache.end()) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] textureFilename [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, + textureFilename.c_str()); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] free texture from cache [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, textureFilename.c_str()); + + crcFactionPreviewTextureCache.erase(textureFilename); + } + } } void Renderer::endLastTexture(ResourceScope rs, bool mustExistInList) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - textureManager[rs]->endLastTexture(mustExistInList); + textureManager[rs]->endLastTexture(mustExistInList); } -Model *Renderer::newModel(ResourceScope rs,const string &path,bool deletePixMapAfterLoad,std::map > > *loadedFileList, string *sourceLoader){ - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return NULL; - } +Model *Renderer::newModel( + ResourceScope rs, const string &path, bool deletePixMapAfterLoad, + std::map>> *loadedFileList, + string *sourceLoader) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return NULL; + } - return modelManager[rs]->newModel(path,deletePixMapAfterLoad,loadedFileList,sourceLoader); + return modelManager[rs]->newModel(path, deletePixMapAfterLoad, loadedFileList, + sourceLoader); } -void Renderer::endModel(ResourceScope rs, Model *model,bool mustExistInList) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } +void Renderer::endModel(ResourceScope rs, Model *model, bool mustExistInList) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - modelManager[rs]->endModel(model,mustExistInList); + modelManager[rs]->endModel(model, mustExistInList); } void Renderer::endLastModel(ResourceScope rs, bool mustExistInList) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - modelManager[rs]->endLastModel(mustExistInList); + modelManager[rs]->endLastModel(mustExistInList); } -Texture2D *Renderer::newTexture2D(ResourceScope rs){ - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return NULL; - } +Texture2D *Renderer::newTexture2D(ResourceScope rs) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return NULL; + } - return textureManager[rs]->newTexture2D(); + return textureManager[rs]->newTexture2D(); } -Texture3D *Renderer::newTexture3D(ResourceScope rs){ - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return NULL; - } +Texture3D *Renderer::newTexture3D(ResourceScope rs) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return NULL; + } - return textureManager[rs]->newTexture3D(); + return textureManager[rs]->newTexture3D(); } -Font2D *Renderer::newFont(ResourceScope rs){ - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return NULL; - } +Font2D *Renderer::newFont(ResourceScope rs) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return NULL; + } - return fontManager[rs]->newFont2D(); + return fontManager[rs]->newFont2D(); } -Font3D *Renderer::newFont3D(ResourceScope rs){ - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return NULL; - } +Font3D *Renderer::newFont3D(ResourceScope rs) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return NULL; + } - return fontManager[rs]->newFont3D(); + return fontManager[rs]->newFont3D(); } -void Renderer::endFont(::Shared::Graphics::Font *font, ResourceScope rs, bool mustExistInList) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } +void Renderer::endFont(::Shared::Graphics::Font *font, ResourceScope rs, + bool mustExistInList) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - fontManager[rs]->endFont(font,mustExistInList); + fontManager[rs]->endFont(font, mustExistInList); } -//void Renderer::resetFontManager(ResourceScope rs) { +// void Renderer::resetFontManager(ResourceScope rs) { // if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { // return; // } // fontManager[rs]->end(); // fontManager[rsGlobal]->init(); -//} +// } -void Renderer::addToDeferredParticleSystemList(std::pair deferredParticleSystem) { - deferredParticleSystems.push_back(deferredParticleSystem); +void Renderer::addToDeferredParticleSystemList( + std::pair deferredParticleSystem) { + deferredParticleSystems.push_back(deferredParticleSystem); } -void Renderer::manageParticleSystem(ParticleSystem *particleSystem, ResourceScope rs){ - particleManager[rs]->manage(particleSystem); +void Renderer::manageParticleSystem(ParticleSystem *particleSystem, + ResourceScope rs) { + particleManager[rs]->manage(particleSystem); } -bool Renderer::validateParticleSystemStillExists(ParticleSystem * particleSystem,ResourceScope rs) const { - return particleManager[rs]->validateParticleSystemStillExists(particleSystem); +bool Renderer::validateParticleSystemStillExists(ParticleSystem *particleSystem, + ResourceScope rs) const { + return particleManager[rs]->validateParticleSystemStillExists(particleSystem); } -void Renderer::removeParticleSystemsForParticleOwner(ParticleOwner * particleOwner,ResourceScope rs) { - particleManager[rs]->removeParticleSystemsForParticleOwner(particleOwner); +void Renderer::removeParticleSystemsForParticleOwner( + ParticleOwner *particleOwner, ResourceScope rs) { + particleManager[rs]->removeParticleSystemsForParticleOwner(particleOwner); } -void Renderer::cleanupParticleSystems(vector &particleSystems, ResourceScope rs) { - particleManager[rs]->cleanupParticleSystems(particleSystems); +void Renderer::cleanupParticleSystems(vector &particleSystems, + ResourceScope rs) { + particleManager[rs]->cleanupParticleSystems(particleSystems); } -void Renderer::cleanupUnitParticleSystems(vector &particleSystems, ResourceScope rs) { - particleManager[rs]->cleanupUnitParticleSystems(particleSystems); +void Renderer::cleanupUnitParticleSystems( + vector &particleSystems, ResourceScope rs) { + particleManager[rs]->cleanupUnitParticleSystems(particleSystems); } void Renderer::updateParticleManager(ResourceScope rs, int renderFps) { - particleManager[rs]->update(renderFps); + particleManager[rs]->update(renderFps); } -void Renderer::renderParticleManager(ResourceScope rs){ - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } +void Renderer::renderParticleManager(ResourceScope rs) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - glPushAttrib(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); - glDepthFunc(GL_LESS); - particleRenderer->renderManager(particleManager[rs], modelRenderer); - glPopAttrib(); + glPushAttrib(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); + glDepthFunc(GL_LESS); + particleRenderer->renderManager(particleManager[rs], modelRenderer); + glPopAttrib(); } void Renderer::swapBuffers() { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - //glFlush(); // should not be required - http://www.opengl.org/wiki/Common_Mistakes - //glFlush(); + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + // glFlush(); // should not be required - + // http://www.opengl.org/wiki/Common_Mistakes glFlush(); - GraphicsInterface::getInstance().getCurrentContext()->swapBuffers(); + GraphicsInterface::getInstance().getCurrentContext()->swapBuffers(); } // ==================== lighting ==================== -//places all the opengl lights +// places all the opengl lights void Renderer::setupLighting() { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - int lightCount= 0; - const World *world= game->getWorld(); - const GameCamera *gameCamera= game->getGameCamera(); - const TimeFlow *timeFlow= world->getTimeFlow(); - float time= timeFlow->getTime(); - - assertGl(); - - //sun/moon light - Vec3f lightColor= timeFlow->computeLightColor(); - Vec3f fogColor= world->getTileset()->getFogColor(); - Vec4f lightPos= timeFlow->isDay()? computeSunPos(time): computeMoonPos(time); - nearestLightPos= lightPos; - - glLightfv(GL_LIGHT0, GL_POSITION, lightPos.ptr()); - glLightfv(GL_LIGHT0, GL_AMBIENT, Vec4f(lightColor*lightAmbFactor, 1.f).ptr()); - glLightfv(GL_LIGHT0, GL_DIFFUSE, Vec4f(lightColor, 1.f).ptr()); - glLightfv(GL_LIGHT0, GL_SPECULAR, Vec4f(0.0f, 0.0f, 0.f, 1.f).ptr()); - - glFogfv(GL_FOG_COLOR, Vec4f(fogColor*lightColor, 1.f).ptr()); - - lightCount++; - - //disable all secondary lights - for(int i= 1; i < maxLights; ++i) { - glDisable(GL_LIGHT0 + i); - } - - //unit lights (not projectiles) - - if(timeFlow->isTotalNight()) { - VisibleQuadContainerCache &qCache = getQuadCache(); - if(qCache.visibleQuadUnitList.empty() == false) { - //bool modelRenderStarted = false; - for(int visibleUnitIndex = 0; - visibleUnitIndex < (int)qCache.visibleQuadUnitList.size() && lightCount < maxLights; - ++visibleUnitIndex) { - Unit *unit = qCache.visibleQuadUnitList[visibleUnitIndex]; - - if(world->toRenderUnit(unit) && - unit->getCurrMidHeightVector().dist(gameCamera->getPos()) < maxLightDist && - unit->getType()->getLight() && unit->isOperative()) { - //printf("$$$ Show light for faction: %s # %d / %d for Unit [%d - %s]\n",world->getFaction(i)->getType()->getName().c_str(),lightCount,maxLights,unit->getId(),unit->getFullName().c_str()); - - Vec4f pos= Vec4f(unit->getCurrMidHeightVector()); - pos.y+=4.f; - - GLenum lightEnum= GL_LIGHT0 + lightCount; - - glEnable(lightEnum); - glLightfv(lightEnum, GL_POSITION, pos.ptr()); - glLightfv(lightEnum, GL_AMBIENT, Vec4f(unit->getType()->getLightColor()).ptr()); - glLightfv(lightEnum, GL_DIFFUSE, Vec4f(unit->getType()->getLightColor()).ptr()); - glLightfv(lightEnum, GL_SPECULAR, Vec4f(unit->getType()->getLightColor()*0.3f).ptr()); - glLightf(lightEnum, GL_QUADRATIC_ATTENUATION, 0.05f); - - ++lightCount; - - const GameCamera *gameCamera= game->getGameCamera(); - - if(Vec3f(pos).dist(gameCamera->getPos())getPos())){ - nearestLightPos= pos; - } - } - } - } - } + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + int lightCount = 0; + const World *world = game->getWorld(); + const GameCamera *gameCamera = game->getGameCamera(); + const TimeFlow *timeFlow = world->getTimeFlow(); + float time = timeFlow->getTime(); + + assertGl(); + + // sun/moon light + Vec3f lightColor = timeFlow->computeLightColor(); + Vec3f fogColor = world->getTileset()->getFogColor(); + Vec4f lightPos = + timeFlow->isDay() ? computeSunPos(time) : computeMoonPos(time); + nearestLightPos = lightPos; + + glLightfv(GL_LIGHT0, GL_POSITION, lightPos.ptr()); + glLightfv(GL_LIGHT0, GL_AMBIENT, + Vec4f(lightColor * lightAmbFactor, 1.f).ptr()); + glLightfv(GL_LIGHT0, GL_DIFFUSE, Vec4f(lightColor, 1.f).ptr()); + glLightfv(GL_LIGHT0, GL_SPECULAR, Vec4f(0.0f, 0.0f, 0.f, 1.f).ptr()); + + glFogfv(GL_FOG_COLOR, Vec4f(fogColor * lightColor, 1.f).ptr()); + + lightCount++; + + // disable all secondary lights + for (int i = 1; i < maxLights; ++i) { + glDisable(GL_LIGHT0 + i); + } + + // unit lights (not projectiles) + + if (timeFlow->isTotalNight()) { + VisibleQuadContainerCache &qCache = getQuadCache(); + if (qCache.visibleQuadUnitList.empty() == false) { + // bool modelRenderStarted = false; + for (int visibleUnitIndex = 0; + visibleUnitIndex < (int)qCache.visibleQuadUnitList.size() && + lightCount < maxLights; + ++visibleUnitIndex) { + Unit *unit = qCache.visibleQuadUnitList[visibleUnitIndex]; + + if (world->toRenderUnit(unit) && + unit->getCurrMidHeightVector().dist(gameCamera->getPos()) < + maxLightDist && + unit->getType()->getLight() && unit->isOperative()) { + // printf("$$$ Show light for faction: %s # %d / %d for Unit [%d - + // %s]\n",world->getFaction(i)->getType()->getName().c_str(),lightCount,maxLights,unit->getId(),unit->getFullName().c_str()); + + Vec4f pos = Vec4f(unit->getCurrMidHeightVector()); + pos.y += 4.f; + + GLenum lightEnum = GL_LIGHT0 + lightCount; + + glEnable(lightEnum); + glLightfv(lightEnum, GL_POSITION, pos.ptr()); + glLightfv(lightEnum, GL_AMBIENT, + Vec4f(unit->getType()->getLightColor()).ptr()); + glLightfv(lightEnum, GL_DIFFUSE, + Vec4f(unit->getType()->getLightColor()).ptr()); + glLightfv(lightEnum, GL_SPECULAR, + Vec4f(unit->getType()->getLightColor() * 0.3f).ptr()); + glLightf(lightEnum, GL_QUADRATIC_ATTENUATION, 0.05f); + + ++lightCount; + + const GameCamera *gameCamera = game->getGameCamera(); + + if (Vec3f(pos).dist(gameCamera->getPos()) < + Vec3f(nearestLightPos).dist(gameCamera->getPos())) { + nearestLightPos = pos; + } + } + } + } + } - assertGl(); + assertGl(); } -//void Renderer::setupLightingForRotatedModel() { +// void Renderer::setupLightingForRotatedModel() { // if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { // return; // } @@ -1110,7205 +1284,7767 @@ void Renderer::setupLighting() { // // assertGl(); // -// //sun/moon light +// //sun/moon light // Vec3f lightColor= timeFlow->computeLightColor(); // Vec3f fogColor= world->getTileset()->getFogColor(); -// Vec4f lightPos= timeFlow->isDay()? computeSunPos(time): computeMoonPos(time); +// Vec4f lightPos= timeFlow->isDay()? computeSunPos(time): +// computeMoonPos(time); // //nearestLightPos= lightPos; // // glLightfv(GL_LIGHT0, GL_POSITION, lightPos.ptr()); -// glLightfv(GL_LIGHT0, GL_AMBIENT, Vec4f(lightColor*lightAmbFactor, 1.f).ptr()); -// glLightfv(GL_LIGHT0, GL_DIFFUSE, Vec4f(lightColor, 1.f).ptr()); -// glLightfv(GL_LIGHT0, GL_SPECULAR, Vec4f(0.0f, 0.0f, 0.f, 1.f).ptr()); +// glLightfv(GL_LIGHT0, GL_AMBIENT, +// Vec4f(lightColor*lightAmbFactor, 1.f).ptr()); glLightfv(GL_LIGHT0, +// GL_DIFFUSE, +// Vec4f(lightColor, 1.f).ptr()); glLightfv(GL_LIGHT0, GL_SPECULAR, +// Vec4f(0.0f, 0.0f, 0.f, 1.f).ptr()); // // glFogfv(GL_FOG_COLOR, Vec4f(fogColor*lightColor, 1.f).ptr()); // // assertGl(); -//} +// } void Renderer::loadGameCameraMatrix() { - const GameCamera *gameCamera= game->getGameCamera(); + const GameCamera *gameCamera = game->getGameCamera(); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - if(gameCamera != NULL) { - glRotatef(gameCamera->getVAng(), -1, 0, 0); - glRotatef(gameCamera->getHAng(), 0, 1, 0); - glTranslatef(-(gameCamera->getPos().x + gameCamera->getShakeOffset().x), - -gameCamera->getPos().y, - -(gameCamera->getPos().z + gameCamera->getShakeOffset().y)); - } + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + if (gameCamera != NULL) { + glRotatef(gameCamera->getVAng(), -1, 0, 0); + glRotatef(gameCamera->getHAng(), 0, 1, 0); + glTranslatef(-(gameCamera->getPos().x + gameCamera->getShakeOffset().x), + -gameCamera->getPos().y, + -(gameCamera->getPos().z + gameCamera->getShakeOffset().y)); + } } void Renderer::loadCameraMatrix(const Camera *camera) { - const Vec3f &position= camera->getConstPosition(); - Quaternion orientation= camera->getOrientation().conjugate(); - - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - glMultMatrixf(orientation.toMatrix4().ptr()); - glTranslatef(-position.x, -position.y, -position.z); -} - -static Vec2i _unprojectMap(const Vec2i& pt,const GLdouble* model,const GLdouble* projection,const GLint* viewport,const char* label=NULL) { - Vec3d a,b; - /* note viewport[3] is height of window in pixels */ - GLint realy = viewport[3] - (GLint) pt.y; - gluUnProject(pt.x,realy,0,model,projection,viewport,&a.x,&a.y,&a.z); - gluUnProject(pt.x,realy,1,model,projection,viewport,&b.x,&b.y,&b.z); - - // junk values if you were looking parallel to the XZ plane; this shouldn't happen as the camera can't do this? - const Vec3f - start(a.x,a.y,a.z), - stop(b.x,b.y,b.z), - plane(0,0,0), - norm(0,1,0), - u = stop-start, - w = start-plane; - const float d = norm.x*u.x + norm.y*u.y + norm.z*u.z; - if(std::fabs(d) < 0.00001) - throw pti_D_IS_ZERO; - - const float nd = -(norm.x*w.x + norm.y*w.y + norm.z*w.z) / d; - if(nd < 0.0 || nd >= 1.0) - throw pti_N_OVER_D_IS_OUTSIDE; - - const Vec3f i = start + u*nd; - //const Vec2i pos(i.x,i.z); - - Vec2i pos; - if(strcmp(label,"tl") == 0) { - pos = Vec2i(std::floor(i.x),std::floor(i.z)); - } - else if(strcmp(label,"tr") == 0) { - pos = Vec2i(std::ceil(i.x),std::floor(i.z)); - } - else if(strcmp(label,"bl") == 0) { - pos = Vec2i(std::floor(i.x),std::ceil(i.z)); - } - else if(strcmp(label,"br") == 0) { - pos = Vec2i(std::ceil(i.x),std::ceil(i.z)); - } - - if(false) { // print debug info - if(label) printf("%s ",label); - printf("%d,%d -> %f,%f,%f -> %f,%f,%f -> %f,%f,%f -> %d,%d\n", - pt.x,pt.y, - start.x,start.y,start.z, - stop.x,stop.y,stop.z, - i.x,i.y,i.z, - pos.x,pos.y); - } - return pos; - + const Vec3f &position = camera->getConstPosition(); + Quaternion orientation = camera->getOrientation().conjugate(); + + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glMultMatrixf(orientation.toMatrix4().ptr()); + glTranslatef(-position.x, -position.y, -position.z); +} + +static Vec2i _unprojectMap(const Vec2i &pt, const GLdouble *model, + const GLdouble *projection, const GLint *viewport, + const char *label = NULL) { + Vec3d a, b; + /* note viewport[3] is height of window in pixels */ + GLint realy = viewport[3] - (GLint)pt.y; + gluUnProject(pt.x, realy, 0, model, projection, viewport, &a.x, &a.y, &a.z); + gluUnProject(pt.x, realy, 1, model, projection, viewport, &b.x, &b.y, &b.z); + + // junk values if you were looking parallel to the XZ plane; this shouldn't + // happen as the camera can't do this? + const Vec3f start(a.x, a.y, a.z), stop(b.x, b.y, b.z), plane(0, 0, 0), + norm(0, 1, 0), u = stop - start, w = start - plane; + const float d = norm.x * u.x + norm.y * u.y + norm.z * u.z; + if (std::fabs(d) < 0.00001) + throw pti_D_IS_ZERO; + + const float nd = -(norm.x * w.x + norm.y * w.y + norm.z * w.z) / d; + if (nd < 0.0 || nd >= 1.0) + throw pti_N_OVER_D_IS_OUTSIDE; + + const Vec3f i = start + u * nd; + // const Vec2i pos(i.x,i.z); + + Vec2i pos; + if (strcmp(label, "tl") == 0) { + pos = Vec2i(std::floor(i.x), std::floor(i.z)); + } else if (strcmp(label, "tr") == 0) { + pos = Vec2i(std::ceil(i.x), std::floor(i.z)); + } else if (strcmp(label, "bl") == 0) { + pos = Vec2i(std::floor(i.x), std::ceil(i.z)); + } else if (strcmp(label, "br") == 0) { + pos = Vec2i(std::ceil(i.x), std::ceil(i.z)); + } + + if (false) { // print debug info + if (label) + printf("%s ", label); + printf("%d,%d -> %f,%f,%f -> %f,%f,%f -> %f,%f,%f -> %d,%d\n", pt.x, pt.y, + start.x, start.y, start.z, stop.x, stop.y, stop.z, i.x, i.y, i.z, + pos.x, pos.y); + } + return pos; } bool Renderer::ExtractFrustum(VisibleQuadContainerCache &quadCacheItem) { - bool frustumChanged = false; - vector proj(16,0); - vector modl(16,0); - - /* Get the current PROJECTION matrix from OpenGL */ - glGetFloatv( GL_PROJECTION_MATRIX, &proj[0] ); - - /* Get the current MODELVIEW matrix from OpenGL */ - glGetFloatv( GL_MODELVIEW_MATRIX, &modl[0] ); - -// for(unsigned int i = 0; i < proj.size(); ++i) { -// //printf("\ni = %d proj [%f][%f] modl [%f][%f]\n",i,proj[i],quadCacheItem.proj[i],modl[i],quadCacheItem.modl[i]); -// if(proj[i] != quadCacheItem.proj[i]) { -// frustumChanged = true; -// break; -// } -// if(modl[i] != quadCacheItem.modl[i]) { -// frustumChanged = true; -// break; -// } -// } - - // Check the frustum cache - const bool useFrustumCache = Config::getInstance().getBool("EnableFrustrumCache","false"); - pair,vector > lookupKey; - if(useFrustumCache == true) { - lookupKey = make_pair(proj,modl); - map,vector >, vector > >::iterator iterFind = quadCacheItem.frustumDataCache.find(lookupKey); - if(iterFind != quadCacheItem.frustumDataCache.end()) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\nCalc Frustum found in cache\n"); - - quadCacheItem.frustumData = iterFind->second; - frustumChanged = (quadCacheItem.proj != proj || quadCacheItem.modl != modl); - if(frustumChanged == true) { - quadCacheItem.proj = proj; - quadCacheItem.modl = modl; - } - - return frustumChanged; - } - } - - if(quadCacheItem.proj != proj || quadCacheItem.modl != modl) { - //if(frustumChanged == true) { - frustumChanged = true; - vector > &frustum = quadCacheItem.frustumData; - //assert(frustum.size() == 6); - //assert(frustum[0].size() == 4); - - quadCacheItem.proj = proj; - quadCacheItem.modl = modl; - - float clip[16]; - float t=0; - - /* Combine the two matrices (multiply projection by modelview) */ - clip[ 0] = modl[ 0] * proj[ 0] + modl[ 1] * proj[ 4] + modl[ 2] * proj[ 8] + modl[ 3] * proj[12]; - clip[ 1] = modl[ 0] * proj[ 1] + modl[ 1] * proj[ 5] + modl[ 2] * proj[ 9] + modl[ 3] * proj[13]; - clip[ 2] = modl[ 0] * proj[ 2] + modl[ 1] * proj[ 6] + modl[ 2] * proj[10] + modl[ 3] * proj[14]; - clip[ 3] = modl[ 0] * proj[ 3] + modl[ 1] * proj[ 7] + modl[ 2] * proj[11] + modl[ 3] * proj[15]; - - clip[ 4] = modl[ 4] * proj[ 0] + modl[ 5] * proj[ 4] + modl[ 6] * proj[ 8] + modl[ 7] * proj[12]; - clip[ 5] = modl[ 4] * proj[ 1] + modl[ 5] * proj[ 5] + modl[ 6] * proj[ 9] + modl[ 7] * proj[13]; - clip[ 6] = modl[ 4] * proj[ 2] + modl[ 5] * proj[ 6] + modl[ 6] * proj[10] + modl[ 7] * proj[14]; - clip[ 7] = modl[ 4] * proj[ 3] + modl[ 5] * proj[ 7] + modl[ 6] * proj[11] + modl[ 7] * proj[15]; - - clip[ 8] = modl[ 8] * proj[ 0] + modl[ 9] * proj[ 4] + modl[10] * proj[ 8] + modl[11] * proj[12]; - clip[ 9] = modl[ 8] * proj[ 1] + modl[ 9] * proj[ 5] + modl[10] * proj[ 9] + modl[11] * proj[13]; - clip[10] = modl[ 8] * proj[ 2] + modl[ 9] * proj[ 6] + modl[10] * proj[10] + modl[11] * proj[14]; - clip[11] = modl[ 8] * proj[ 3] + modl[ 9] * proj[ 7] + modl[10] * proj[11] + modl[11] * proj[15]; - - clip[12] = modl[12] * proj[ 0] + modl[13] * proj[ 4] + modl[14] * proj[ 8] + modl[15] * proj[12]; - clip[13] = modl[12] * proj[ 1] + modl[13] * proj[ 5] + modl[14] * proj[ 9] + modl[15] * proj[13]; - clip[14] = modl[12] * proj[ 2] + modl[13] * proj[ 6] + modl[14] * proj[10] + modl[15] * proj[14]; - clip[15] = modl[12] * proj[ 3] + modl[13] * proj[ 7] + modl[14] * proj[11] + modl[15] * proj[15]; - - /* Extract the numbers for the RIGHT plane */ - frustum[0][0] = clip[ 3] - clip[ 0]; - frustum[0][1] = clip[ 7] - clip[ 4]; - frustum[0][2] = clip[11] - clip[ 8]; - frustum[0][3] = clip[15] - clip[12]; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\nCalc Frustum #%da: [%f][%f][%f][%f]\n",0,frustum[0][0],frustum[0][1],frustum[0][2],frustum[0][3]); - - /* Normalize the result */ - t = std::sqrt( frustum[0][0] * frustum[0][0] + frustum[0][1] * frustum[0][1] + frustum[0][2] * frustum[0][2] ); - if(t != 0.0) { - frustum[0][0] /= t; - frustum[0][1] /= t; - frustum[0][2] /= t; - frustum[0][3] /= t; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\nCalc Frustum #%db: [%f][%f][%f][%f] t = %f\n",0,frustum[0][0],frustum[0][1],frustum[0][2],frustum[0][3],t); - } - - /* Extract the numbers for the LEFT plane */ - frustum[1][0] = clip[ 3] + clip[ 0]; - frustum[1][1] = clip[ 7] + clip[ 4]; - frustum[1][2] = clip[11] + clip[ 8]; - frustum[1][3] = clip[15] + clip[12]; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\nCalc Frustum #%da: [%f][%f][%f][%f]\n",1,frustum[1][0],frustum[1][1],frustum[1][2],frustum[1][3]); - - /* Normalize the result */ - t = std::sqrt( frustum[1][0] * frustum[1][0] + frustum[1][1] * frustum[1][1] + frustum[1][2] * frustum[1][2] ); - if(t != 0.0) { - frustum[1][0] /= t; - frustum[1][1] /= t; - frustum[1][2] /= t; - frustum[1][3] /= t; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\nCalc Frustum #%db: [%f][%f][%f][%f] t = %f\n",1,frustum[1][0],frustum[1][1],frustum[1][2],frustum[1][3],t); - } - - /* Extract the BOTTOM plane */ - frustum[2][0] = clip[ 3] + clip[ 1]; - frustum[2][1] = clip[ 7] + clip[ 5]; - frustum[2][2] = clip[11] + clip[ 9]; - frustum[2][3] = clip[15] + clip[13]; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\nCalc Frustum #%da: [%f][%f][%f][%f]\n",2,frustum[2][0],frustum[2][1],frustum[2][2],frustum[2][3]); - - /* Normalize the result */ - - t = std::sqrt( frustum[2][0] * frustum[2][0] + frustum[2][1] * frustum[2][1] + frustum[2][2] * frustum[2][2] ); - if(t != 0.0) { - frustum[2][0] /= t; - frustum[2][1] /= t; - frustum[2][2] /= t; - frustum[2][3] /= t; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\nCalc Frustum #%db: [%f][%f][%f][%f] t = %f\n",2,frustum[2][0],frustum[2][1],frustum[2][2],frustum[2][3],t); - } - - /* Extract the TOP plane */ - frustum[3][0] = clip[ 3] - clip[ 1]; - frustum[3][1] = clip[ 7] - clip[ 5]; - frustum[3][2] = clip[11] - clip[ 9]; - frustum[3][3] = clip[15] - clip[13]; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\nCalc Frustum #%da: [%f][%f][%f][%f]\n",3,frustum[3][0],frustum[3][1],frustum[3][2],frustum[3][3]); - - /* Normalize the result */ - - t = std::sqrt( frustum[3][0] * frustum[3][0] + frustum[3][1] * frustum[3][1] + frustum[3][2] * frustum[3][2] ); - if(t != 0.0) { - frustum[3][0] /= t; - frustum[3][1] /= t; - frustum[3][2] /= t; - frustum[3][3] /= t; + bool frustumChanged = false; + vector proj(16, 0); + vector modl(16, 0); + + /* Get the current PROJECTION matrix from OpenGL */ + glGetFloatv(GL_PROJECTION_MATRIX, &proj[0]); + + /* Get the current MODELVIEW matrix from OpenGL */ + glGetFloatv(GL_MODELVIEW_MATRIX, &modl[0]); + + // for(unsigned int i = 0; i < proj.size(); ++i) { + // //printf("\ni = %d proj [%f][%f] modl + //[%f][%f]\n",i,proj[i],quadCacheItem.proj[i],modl[i],quadCacheItem.modl[i]); + // if(proj[i] != quadCacheItem.proj[i]) { + // frustumChanged = true; + // break; + // } + // if(modl[i] != quadCacheItem.modl[i]) { + // frustumChanged = true; + // break; + // } + // } + + // Check the frustum cache + const bool useFrustumCache = + Config::getInstance().getBool("EnableFrustrumCache", "false"); + pair, vector> lookupKey; + if (useFrustumCache == true) { + lookupKey = make_pair(proj, modl); + map, vector>, vector>>::iterator + iterFind = quadCacheItem.frustumDataCache.find(lookupKey); + if (iterFind != quadCacheItem.frustumDataCache.end()) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\nCalc Frustum found in cache\n"); + + quadCacheItem.frustumData = iterFind->second; + frustumChanged = + (quadCacheItem.proj != proj || quadCacheItem.modl != modl); + if (frustumChanged == true) { + quadCacheItem.proj = proj; + quadCacheItem.modl = modl; + } + + return frustumChanged; + } + } + + if (quadCacheItem.proj != proj || quadCacheItem.modl != modl) { + // if(frustumChanged == true) { + frustumChanged = true; + vector> &frustum = quadCacheItem.frustumData; + // assert(frustum.size() == 6); + // assert(frustum[0].size() == 4); + + quadCacheItem.proj = proj; + quadCacheItem.modl = modl; + + float clip[16]; + float t = 0; + + /* Combine the two matrices (multiply projection by modelview) */ + clip[0] = modl[0] * proj[0] + modl[1] * proj[4] + modl[2] * proj[8] + + modl[3] * proj[12]; + clip[1] = modl[0] * proj[1] + modl[1] * proj[5] + modl[2] * proj[9] + + modl[3] * proj[13]; + clip[2] = modl[0] * proj[2] + modl[1] * proj[6] + modl[2] * proj[10] + + modl[3] * proj[14]; + clip[3] = modl[0] * proj[3] + modl[1] * proj[7] + modl[2] * proj[11] + + modl[3] * proj[15]; + + clip[4] = modl[4] * proj[0] + modl[5] * proj[4] + modl[6] * proj[8] + + modl[7] * proj[12]; + clip[5] = modl[4] * proj[1] + modl[5] * proj[5] + modl[6] * proj[9] + + modl[7] * proj[13]; + clip[6] = modl[4] * proj[2] + modl[5] * proj[6] + modl[6] * proj[10] + + modl[7] * proj[14]; + clip[7] = modl[4] * proj[3] + modl[5] * proj[7] + modl[6] * proj[11] + + modl[7] * proj[15]; + + clip[8] = modl[8] * proj[0] + modl[9] * proj[4] + modl[10] * proj[8] + + modl[11] * proj[12]; + clip[9] = modl[8] * proj[1] + modl[9] * proj[5] + modl[10] * proj[9] + + modl[11] * proj[13]; + clip[10] = modl[8] * proj[2] + modl[9] * proj[6] + modl[10] * proj[10] + + modl[11] * proj[14]; + clip[11] = modl[8] * proj[3] + modl[9] * proj[7] + modl[10] * proj[11] + + modl[11] * proj[15]; + + clip[12] = modl[12] * proj[0] + modl[13] * proj[4] + modl[14] * proj[8] + + modl[15] * proj[12]; + clip[13] = modl[12] * proj[1] + modl[13] * proj[5] + modl[14] * proj[9] + + modl[15] * proj[13]; + clip[14] = modl[12] * proj[2] + modl[13] * proj[6] + modl[14] * proj[10] + + modl[15] * proj[14]; + clip[15] = modl[12] * proj[3] + modl[13] * proj[7] + modl[14] * proj[11] + + modl[15] * proj[15]; + + /* Extract the numbers for the RIGHT plane */ + frustum[0][0] = clip[3] - clip[0]; + frustum[0][1] = clip[7] - clip[4]; + frustum[0][2] = clip[11] - clip[8]; + frustum[0][3] = clip[15] - clip[12]; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\nCalc Frustum #%da: [%f][%f][%f][%f]\n", 0, frustum[0][0], + frustum[0][1], frustum[0][2], frustum[0][3]); + + /* Normalize the result */ + t = std::sqrt(frustum[0][0] * frustum[0][0] + + frustum[0][1] * frustum[0][1] + + frustum[0][2] * frustum[0][2]); + if (t != 0.0) { + frustum[0][0] /= t; + frustum[0][1] /= t; + frustum[0][2] /= t; + frustum[0][3] /= t; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\nCalc Frustum #%db: [%f][%f][%f][%f] t = %f\n", 0, + frustum[0][0], frustum[0][1], frustum[0][2], frustum[0][3], t); + } + + /* Extract the numbers for the LEFT plane */ + frustum[1][0] = clip[3] + clip[0]; + frustum[1][1] = clip[7] + clip[4]; + frustum[1][2] = clip[11] + clip[8]; + frustum[1][3] = clip[15] + clip[12]; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\nCalc Frustum #%da: [%f][%f][%f][%f]\n", 1, frustum[1][0], + frustum[1][1], frustum[1][2], frustum[1][3]); + + /* Normalize the result */ + t = std::sqrt(frustum[1][0] * frustum[1][0] + + frustum[1][1] * frustum[1][1] + + frustum[1][2] * frustum[1][2]); + if (t != 0.0) { + frustum[1][0] /= t; + frustum[1][1] /= t; + frustum[1][2] /= t; + frustum[1][3] /= t; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\nCalc Frustum #%db: [%f][%f][%f][%f] t = %f\n", 1, + frustum[1][0], frustum[1][1], frustum[1][2], frustum[1][3], t); + } + + /* Extract the BOTTOM plane */ + frustum[2][0] = clip[3] + clip[1]; + frustum[2][1] = clip[7] + clip[5]; + frustum[2][2] = clip[11] + clip[9]; + frustum[2][3] = clip[15] + clip[13]; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\nCalc Frustum #%da: [%f][%f][%f][%f]\n", 2, frustum[2][0], + frustum[2][1], frustum[2][2], frustum[2][3]); + + /* Normalize the result */ + + t = std::sqrt(frustum[2][0] * frustum[2][0] + + frustum[2][1] * frustum[2][1] + + frustum[2][2] * frustum[2][2]); + if (t != 0.0) { + frustum[2][0] /= t; + frustum[2][1] /= t; + frustum[2][2] /= t; + frustum[2][3] /= t; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\nCalc Frustum #%db: [%f][%f][%f][%f] t = %f\n", 2, + frustum[2][0], frustum[2][1], frustum[2][2], frustum[2][3], t); + } + + /* Extract the TOP plane */ + frustum[3][0] = clip[3] - clip[1]; + frustum[3][1] = clip[7] - clip[5]; + frustum[3][2] = clip[11] - clip[9]; + frustum[3][3] = clip[15] - clip[13]; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\nCalc Frustum #%da: [%f][%f][%f][%f]\n", 3, frustum[3][0], + frustum[3][1], frustum[3][2], frustum[3][3]); + + /* Normalize the result */ + + t = std::sqrt(frustum[3][0] * frustum[3][0] + + frustum[3][1] * frustum[3][1] + + frustum[3][2] * frustum[3][2]); + if (t != 0.0) { + frustum[3][0] /= t; + frustum[3][1] /= t; + frustum[3][2] /= t; + frustum[3][3] /= t; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\nCalc Frustum #%db: [%f][%f][%f][%f] t = %f\n", 3, + frustum[3][0], frustum[3][1], frustum[3][2], frustum[3][3], t); + } + + /* Extract the FAR plane */ + frustum[4][0] = clip[3] - clip[2]; + frustum[4][1] = clip[7] - clip[6]; + frustum[4][2] = clip[11] - clip[10]; + frustum[4][3] = clip[15] - clip[14]; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\nCalc Frustum #%db: [%f][%f][%f][%f] t = %f\n",3,frustum[3][0],frustum[3][1],frustum[3][2],frustum[3][3],t); - } - - /* Extract the FAR plane */ - frustum[4][0] = clip[ 3] - clip[ 2]; - frustum[4][1] = clip[ 7] - clip[ 6]; - frustum[4][2] = clip[11] - clip[10]; - frustum[4][3] = clip[15] - clip[14]; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\nCalc Frustum #%da: [%f][%f][%f][%f]\n", 4, frustum[4][0], + frustum[4][1], frustum[4][2], frustum[4][3]); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\nCalc Frustum #%da: [%f][%f][%f][%f]\n",4,frustum[4][0],frustum[4][1],frustum[4][2],frustum[4][3]); - - /* Normalize the result */ + /* Normalize the result */ - t = std::sqrt( frustum[4][0] * frustum[4][0] + frustum[4][1] * frustum[4][1] + frustum[4][2] * frustum[4][2] ); + t = std::sqrt(frustum[4][0] * frustum[4][0] + + frustum[4][1] * frustum[4][1] + + frustum[4][2] * frustum[4][2]); - if(t != 0.0) { - frustum[4][0] /= t; - frustum[4][1] /= t; - frustum[4][2] /= t; - frustum[4][3] /= t; + if (t != 0.0) { + frustum[4][0] /= t; + frustum[4][1] /= t; + frustum[4][2] /= t; + frustum[4][3] /= t; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\nCalc Frustum #%db: [%f][%f][%f][%f] t = %f\n",4,frustum[4][0],frustum[4][1],frustum[4][2],frustum[4][3],t); - } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\nCalc Frustum #%db: [%f][%f][%f][%f] t = %f\n", 4, + frustum[4][0], frustum[4][1], frustum[4][2], frustum[4][3], t); + } - /* Extract the NEAR plane */ - frustum[5][0] = clip[ 3] + clip[ 2]; - frustum[5][1] = clip[ 7] + clip[ 6]; - frustum[5][2] = clip[11] + clip[10]; - frustum[5][3] = clip[15] + clip[14]; + /* Extract the NEAR plane */ + frustum[5][0] = clip[3] + clip[2]; + frustum[5][1] = clip[7] + clip[6]; + frustum[5][2] = clip[11] + clip[10]; + frustum[5][3] = clip[15] + clip[14]; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\nCalc Frustum #%da: [%f][%f][%f][%f]\n",5,frustum[5][0],frustum[5][1],frustum[5][2],frustum[5][3]); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\nCalc Frustum #%da: [%f][%f][%f][%f]\n", 5, frustum[5][0], + frustum[5][1], frustum[5][2], frustum[5][3]); - /* Normalize the result */ + /* Normalize the result */ - t = std::sqrt( frustum[5][0] * frustum[5][0] + frustum[5][1] * frustum[5][1] + frustum[5][2] * frustum[5][2] ); + t = std::sqrt(frustum[5][0] * frustum[5][0] + + frustum[5][1] * frustum[5][1] + + frustum[5][2] * frustum[5][2]); - if(t != 0.0) { - frustum[5][0] /= t; - frustum[5][1] /= t; - frustum[5][2] /= t; - frustum[5][3] /= t; + if (t != 0.0) { + frustum[5][0] /= t; + frustum[5][1] /= t; + frustum[5][2] /= t; + frustum[5][3] /= t; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\nCalc Frustum #%db: [%f][%f][%f][%f] t = %f\n",5,frustum[5][0],frustum[5][1],frustum[5][2],frustum[5][3],t); - } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\nCalc Frustum #%db: [%f][%f][%f][%f] t = %f\n", 5, + frustum[5][0], frustum[5][1], frustum[5][2], frustum[5][3], t); + } - if(useFrustumCache == true) { - quadCacheItem.frustumDataCache[lookupKey] = frustum; - } - } - return frustumChanged; + if (useFrustumCache == true) { + quadCacheItem.frustumDataCache[lookupKey] = frustum; + } + } + return frustumChanged; } -//bool Renderer::PointInFrustum(vector > &frustum, float x, float y, float z ) { -// unsigned int p=0; +// bool Renderer::PointInFrustum(vector > &frustum, float x, float +// y, float z ) { +// unsigned int p=0; // -// for( p = 0; p < frustum.size(); p++ ) { -// if( frustum[p][0] * x + frustum[p][1] * y + frustum[p][2] * z + frustum[p][3] <= 0 ) { -// return false; -// } -// } -// return true; -//} +// for( p = 0; p < frustum.size(); p++ ) { +// if( frustum[p][0] * x + frustum[p][1] * y + frustum[p][2] * z + +// frustum[p][3] <= 0 ) { +// return false; +// } +// } +// return true; +// } // -//bool Renderer::SphereInFrustum(vector > &frustum, float x, float y, float z, float radius) { +// bool Renderer::SphereInFrustum(vector > &frustum, float x, +// float y, float z, float radius) { // // Go through all the sides of the frustum // for(int i = 0; i < (int)frustum.size(); i++ ) { -// // If the center of the sphere is farther away from the plane than the radius -// if(frustum[i][0] * x + frustum[i][1] * y + frustum[i][2] * z + frustum[i][3] <= -radius ) { -// // The distance was greater than the radius so the sphere is outside of the frustum -// return false; +// // If the center of the sphere is farther away from the plane +//than +// the radius if(frustum[i][0] * x + frustum[i][1] * y + frustum[i][2] +// * z + frustum[i][3] <= -radius ) { +// // The distance was greater than the radius so the sphere +//is outside of the frustum return false; // } // } // // // The sphere was inside of the frustum! // return true; -//} - -bool Renderer::CubeInFrustum(vector > &frustum, float x, float y, float z, float size ) { - unsigned int p=0; - - for( p = 0; p < frustum.size(); p++ ) { - if( frustum[p][0] * (x - size) + frustum[p][1] * (y - size) + frustum[p][2] * (z - size) + frustum[p][3] > 0 ) - continue; - if( frustum[p][0] * (x + size) + frustum[p][1] * (y - size) + frustum[p][2] * (z - size) + frustum[p][3] > 0 ) - continue; - if( frustum[p][0] * (x - size) + frustum[p][1] * (y + size) + frustum[p][2] * (z - size) + frustum[p][3] > 0 ) - continue; - if( frustum[p][0] * (x + size) + frustum[p][1] * (y + size) + frustum[p][2] * (z - size) + frustum[p][3] > 0 ) - continue; - if( frustum[p][0] * (x - size) + frustum[p][1] * (y - size) + frustum[p][2] * (z + size) + frustum[p][3] > 0 ) - continue; - if( frustum[p][0] * (x + size) + frustum[p][1] * (y - size) + frustum[p][2] * (z + size) + frustum[p][3] > 0 ) - continue; - if( frustum[p][0] * (x - size) + frustum[p][1] * (y + size) + frustum[p][2] * (z + size) + frustum[p][3] > 0 ) - continue; - if( frustum[p][0] * (x + size) + frustum[p][1] * (y + size) + frustum[p][2] * (z + size) + frustum[p][3] > 0 ) - continue; - return false; - } - return true; +// } + +bool Renderer::CubeInFrustum(vector> &frustum, float x, float y, + float z, float size) { + unsigned int p = 0; + + for (p = 0; p < frustum.size(); p++) { + if (frustum[p][0] * (x - size) + frustum[p][1] * (y - size) + + frustum[p][2] * (z - size) + frustum[p][3] > + 0) + continue; + if (frustum[p][0] * (x + size) + frustum[p][1] * (y - size) + + frustum[p][2] * (z - size) + frustum[p][3] > + 0) + continue; + if (frustum[p][0] * (x - size) + frustum[p][1] * (y + size) + + frustum[p][2] * (z - size) + frustum[p][3] > + 0) + continue; + if (frustum[p][0] * (x + size) + frustum[p][1] * (y + size) + + frustum[p][2] * (z - size) + frustum[p][3] > + 0) + continue; + if (frustum[p][0] * (x - size) + frustum[p][1] * (y - size) + + frustum[p][2] * (z + size) + frustum[p][3] > + 0) + continue; + if (frustum[p][0] * (x + size) + frustum[p][1] * (y - size) + + frustum[p][2] * (z + size) + frustum[p][3] > + 0) + continue; + if (frustum[p][0] * (x - size) + frustum[p][1] * (y + size) + + frustum[p][2] * (z + size) + frustum[p][3] > + 0) + continue; + if (frustum[p][0] * (x + size) + frustum[p][1] * (y + size) + + frustum[p][2] * (z + size) + frustum[p][3] > + 0) + continue; + return false; + } + return true; } void Renderer::computeVisibleQuad() { - visibleQuad = this->gameCamera->computeVisibleQuad(); - - bool frustumChanged = false; - if(VisibleQuadContainerCache::enableFrustumCalcs == true) { - frustumChanged = ExtractFrustum(quadCache); - } - - if(frustumChanged && SystemFlags::VERBOSE_MODE_ENABLED) { - printf("\nCamera: %d,%d %d,%d %d,%d %d,%d\n", - visibleQuad.p[0].x,visibleQuad.p[0].y, - visibleQuad.p[1].x,visibleQuad.p[1].y, - visibleQuad.p[2].x,visibleQuad.p[2].y, - visibleQuad.p[3].x,visibleQuad.p[3].y); - - for(unsigned int i = 0; i < quadCache.frustumData.size(); ++i) { - printf("\nFrustum #%u [" MG_SIZE_T_SPECIFIER "]: ",i,quadCache.frustumData.size()); - vector &frustumDataInner = quadCache.frustumData[i]; - for(unsigned int j = 0; j < frustumDataInner.size(); ++j) { - printf("[%f]",quadCache.frustumData[i][j]); - } - } - - printf("\nEND\n"); - } - - const bool newVisibleQuadCalc = false; - if(newVisibleQuadCalc) { - const bool debug = false; - try { - if(debug) { - visibleQuad = gameCamera->computeVisibleQuad(); - printf("Camera: %d,%d %d,%d %d,%d %d,%d\n", - visibleQuad.p[0].x,visibleQuad.p[0].y, - visibleQuad.p[1].x,visibleQuad.p[1].y, - visibleQuad.p[2].x,visibleQuad.p[2].y, - visibleQuad.p[3].x,visibleQuad.p[3].y); - } - - - // compute the four corners using OpenGL - GLdouble model[16], projection[16]; - GLint viewport[4]; - glGetDoublev(GL_MODELVIEW_MATRIX,model); - glGetDoublev(GL_PROJECTION_MATRIX,projection); - glGetIntegerv(GL_VIEWPORT,viewport); - Vec2i - tl = _unprojectMap(Vec2i(0,0),model,projection,viewport,"tl"), - tr = _unprojectMap(Vec2i(viewport[2],0),model,projection,viewport,"tr"), - br = _unprojectMap(Vec2i(viewport[2],viewport[3]),model,projection,viewport,"br"), - bl = _unprojectMap(Vec2i(0,viewport[3]),model,projection,viewport,"bl"); - - - // orientate it for map iterator - //bool swapRequiredX = false; - bool swapRequiredY = false; - int const cellBuffer = 4; - if((tl.x > tr.x) || (bl.x > br.x)) { - if(debug) printf("Swap X???\n"); - - //std::swap(tl,bl); - //std::swap(tr,br); - if(tl.x > tr.x) { - if(debug) printf("Swap X1???\n"); - - tr.x += cellBuffer; - tl.x -= cellBuffer; - - std::swap(tl.x,tr.x); - //swapRequiredX = true; - } - else { - tl.x += cellBuffer; - tr.x -= cellBuffer; - } - if(bl.x > br.x) { - if(debug) printf("Swap X2???\n"); - - bl.x += cellBuffer; - br.x -= cellBuffer; - - std::swap(bl.x,br.x); - //swapRequiredX = true; - } - else { - br.x += cellBuffer; - bl.x -= cellBuffer; - } - } - - if((tl.y > bl.y) || (tr.y > br.y)) { - visibleQuad = this->gameCamera->computeVisibleQuad(); - - if(debug) printf("Swap Y???\n"); - - if(tl.y > bl.y) { - if(debug) printf("Swap Y1???\n"); - - tl.y += cellBuffer; - bl.y -= cellBuffer; - - std::swap(tl.y,bl.y); - swapRequiredY = true; - } - else { - bl.y += cellBuffer; - tl.y -= cellBuffer; - } - if(tr.y > br.y) { - if(debug) printf("Swap Y2???\n"); - - tr.y += cellBuffer; - br.y -= cellBuffer; - - std::swap(tr.y,br.y); - swapRequiredY = true; - } - else { - br.y += cellBuffer; - tr.y -= cellBuffer; - } - - - //std::swap(tl,tr); - //std::swap(bl,br); - } - if(swapRequiredY == false) { - tl.y -= cellBuffer; - tr.y -= cellBuffer; - bl.y += cellBuffer; - br.y += cellBuffer; - } - - // set it as the frustum - visibleQuad = Quad2i(tl,bl,tr,br); // strange order - if(debug) { - printf("Will: %d,%d %d,%d %d,%d %d,%d\n", - visibleQuad.p[0].x,visibleQuad.p[0].y, - visibleQuad.p[1].x,visibleQuad.p[1].y, - visibleQuad.p[2].x,visibleQuad.p[2].y, - visibleQuad.p[3].x,visibleQuad.p[3].y); - } - } - catch(PROJECTION_TO_INFINITY &e) { - if(debug) printf("hmm staring at the horizon %d\n",(int)e); - // use historic code solution - visibleQuad = this->gameCamera->computeVisibleQuad(); - } - } -} + visibleQuad = this->gameCamera->computeVisibleQuad(); + + bool frustumChanged = false; + if (VisibleQuadContainerCache::enableFrustumCalcs == true) { + frustumChanged = ExtractFrustum(quadCache); + } + + if (frustumChanged && SystemFlags::VERBOSE_MODE_ENABLED) { + printf("\nCamera: %d,%d %d,%d %d,%d %d,%d\n", visibleQuad.p[0].x, + visibleQuad.p[0].y, visibleQuad.p[1].x, visibleQuad.p[1].y, + visibleQuad.p[2].x, visibleQuad.p[2].y, visibleQuad.p[3].x, + visibleQuad.p[3].y); + + for (unsigned int i = 0; i < quadCache.frustumData.size(); ++i) { + printf("\nFrustum #%u [" MG_SIZE_T_SPECIFIER "]: ", i, + quadCache.frustumData.size()); + vector &frustumDataInner = quadCache.frustumData[i]; + for (unsigned int j = 0; j < frustumDataInner.size(); ++j) { + printf("[%f]", quadCache.frustumData[i][j]); + } + } -// ======================================= -// basic rendering -// ======================================= + printf("\nEND\n"); + } + + const bool newVisibleQuadCalc = false; + if (newVisibleQuadCalc) { + const bool debug = false; + try { + if (debug) { + visibleQuad = gameCamera->computeVisibleQuad(); + printf("Camera: %d,%d %d,%d %d,%d %d,%d\n", visibleQuad.p[0].x, + visibleQuad.p[0].y, visibleQuad.p[1].x, visibleQuad.p[1].y, + visibleQuad.p[2].x, visibleQuad.p[2].y, visibleQuad.p[3].x, + visibleQuad.p[3].y); + } + + // compute the four corners using OpenGL + GLdouble model[16], projection[16]; + GLint viewport[4]; + glGetDoublev(GL_MODELVIEW_MATRIX, model); + glGetDoublev(GL_PROJECTION_MATRIX, projection); + glGetIntegerv(GL_VIEWPORT, viewport); + Vec2i tl = _unprojectMap(Vec2i(0, 0), model, projection, viewport, "tl"), + tr = _unprojectMap(Vec2i(viewport[2], 0), model, projection, + viewport, "tr"), + br = _unprojectMap(Vec2i(viewport[2], viewport[3]), model, + projection, viewport, "br"), + bl = _unprojectMap(Vec2i(0, viewport[3]), model, projection, + viewport, "bl"); + + // orientate it for map iterator + // bool swapRequiredX = false; + bool swapRequiredY = false; + int const cellBuffer = 4; + if ((tl.x > tr.x) || (bl.x > br.x)) { + if (debug) + printf("Swap X???\n"); + + // std::swap(tl,bl); + // std::swap(tr,br); + if (tl.x > tr.x) { + if (debug) + printf("Swap X1???\n"); + + tr.x += cellBuffer; + tl.x -= cellBuffer; + + std::swap(tl.x, tr.x); + // swapRequiredX = true; + } else { + tl.x += cellBuffer; + tr.x -= cellBuffer; + } + if (bl.x > br.x) { + if (debug) + printf("Swap X2???\n"); + + bl.x += cellBuffer; + br.x -= cellBuffer; + + std::swap(bl.x, br.x); + // swapRequiredX = true; + } else { + br.x += cellBuffer; + bl.x -= cellBuffer; + } + } -void Renderer::renderMouse2d(int x, int y, int anim, float fade) { - if(no2DMouseRendering == true) { - return; - } - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } -// float blue=0.0f; -// float green=0.4f; - if(game != NULL && game->getGui() != NULL) { - const Gui *gui=game->getGui(); - const Display *display=gui->getDisplay(); - int downPos= display->getDownSelectedPos(); - if(downPos != Display::invalidPos){ - // in state of doing something - const Texture2D *texture= display->getDownImage(downPos); - renderTextureQuad(x+18,y-50,32,32,texture,0.8f); - } -// else { -// // Display current commandtype -// const Unit *unit=NULL; -// if(gui->getSelection()->isEmpty()){ -// blue=0.0f; -// green=0.1f; -// } -// else{ -// unit=gui->getSelection()->getFrontUnit(); -// if(unit->getCurrCommand()!=NULL && unit->getCurrCommand()->getCommandType()->getImage()!=NULL){ -// const Texture2D *texture = unit->getCurrCommand()->getCommandType()->getImage(); -// renderTextureQuad(x+18,y-50,32,32,texture,0.2f); -// } -// } -// } + if ((tl.y > bl.y) || (tr.y > br.y)) { + visibleQuad = this->gameCamera->computeVisibleQuad(); - if(game->isMarkCellMode() == true) { - const Texture2D *texture= game->getMarkCellTexture(); - renderTextureQuad(x,y,texture->getTextureWidth(),texture->getTextureHeight(),texture,0.8f); - } - if(game->isUnMarkCellMode() == true) { - const Texture2D *texture= game->getUnMarkCellTexture(); - renderTextureQuad(x,y,texture->getTextureWidth(),texture->getTextureHeight(),texture,0.8f); - } - } - - float fadeFactor = fade + 1.f; - - anim= anim * 2 - maxMouse2dAnim; - - float color2= (abs(anim*(int)fadeFactor)/static_cast(maxMouse2dAnim))/2.f+0.4f; - float color1= (abs(anim*(int)fadeFactor)/static_cast(maxMouse2dAnim))/2.f+0.8f; - - glPushAttrib(GL_CURRENT_BIT | GL_COLOR_BUFFER_BIT | GL_LINE_BIT); - glEnable(GL_BLEND); - - //inside - glColor4f(0.4f*fadeFactor, 0.2f*fadeFactor, 0.2f*fadeFactor, 0.5f*fadeFactor); - glBegin(GL_TRIANGLES); - glVertex2i(x, y); - glVertex2i(x+20, y-10); - glVertex2i(x+10, y-20); - glEnd(); - - //border - glLineWidth(2); - glBegin(GL_LINE_LOOP); - glColor4f(1.f, 0.2f, 0, color1); - glVertex2i(x, y); - glColor4f(1.f, 0.4f, 0, color2); - glVertex2i(x+20, y-10); - glColor4f(1.f, 0.4f, 0, color2); - glVertex2i(x+10, y-20); - glEnd(); - glPopAttrib(); - - -/* - if(no2DMouseRendering == true) { - return; - } - float color1 = 0.0, color2 = 0.0; - - float fadeFactor = fade + 1.f; - - anim= anim * 2 - maxMouse2dAnim; - - color2= (abs(anim*(int)fadeFactor)/static_cast(maxMouse2dAnim))/2.f+0.4f; - color1= (abs(anim*(int)fadeFactor)/static_cast(maxMouse2dAnim))/2.f+0.8f; - - glPushAttrib(GL_CURRENT_BIT | GL_COLOR_BUFFER_BIT | GL_LINE_BIT); - glEnable(GL_BLEND); + if (debug) + printf("Swap Y???\n"); - //inside - Vec2i vertices[3]; - vertices[0] = Vec2i(x, y); - vertices[1] = Vec2i(x+20, y-10); - vertices[2] = Vec2i(x+10, y-20); + if (tl.y > bl.y) { + if (debug) + printf("Swap Y1???\n"); - glColor4f(0.4f*fadeFactor, 0.2f*fadeFactor, 0.2f*fadeFactor, 0.5f*fadeFactor); - glEnableClientState(GL_VERTEX_ARRAY); - glVertexPointer(2, GL_INT, 0, &vertices[0]); - glDrawArrays(GL_TRIANGLES, 0, 3); - glDisableClientState(GL_VERTEX_ARRAY); + tl.y += cellBuffer; + bl.y -= cellBuffer; - //border - vertices[0] = Vec2i(x, y); - vertices[1] = Vec2i(x+20, y-10); - vertices[2] = Vec2i(x+10, y-20); - - Vec4f colors[4]; - colors[0] = Vec4f(1.f, 0.2f, 0, color1); - colors[1] = Vec4f(1.f, 0.4f, 0, color2); - colors[2] = Vec4f(1.f, 0.4f, 0, color2); - - glLineWidth(2); - glEnableClientState(GL_VERTEX_ARRAY); - glVertexPointer(2, GL_INT, 0, &vertices[0]); - glEnableClientState(GL_COLOR_ARRAY); - glColorPointer(4, GL_FLOAT, 0, &colors[0]); - glDrawArrays(GL_LINE_LOOP, 0, 3); - glDisableClientState(GL_COLOR_ARRAY); - glDisableClientState(GL_VERTEX_ARRAY); + std::swap(tl.y, bl.y); + swapRequiredY = true; + } else { + bl.y += cellBuffer; + tl.y -= cellBuffer; + } + if (tr.y > br.y) { + if (debug) + printf("Swap Y2???\n"); + + tr.y += cellBuffer; + br.y -= cellBuffer; + + std::swap(tr.y, br.y); + swapRequiredY = true; + } else { + br.y += cellBuffer; + tr.y -= cellBuffer; + } - glPopAttrib(); -*/ + // std::swap(tl,tr); + // std::swap(bl,br); + } + if (swapRequiredY == false) { + tl.y -= cellBuffer; + tr.y -= cellBuffer; + bl.y += cellBuffer; + br.y += cellBuffer; + } + + // set it as the frustum + visibleQuad = Quad2i(tl, bl, tr, br); // strange order + if (debug) { + printf("Will: %d,%d %d,%d %d,%d %d,%d\n", visibleQuad.p[0].x, + visibleQuad.p[0].y, visibleQuad.p[1].x, visibleQuad.p[1].y, + visibleQuad.p[2].x, visibleQuad.p[2].y, visibleQuad.p[3].x, + visibleQuad.p[3].y); + } + } catch (PROJECTION_TO_INFINITY &e) { + if (debug) + printf("hmm staring at the horizon %d\n", (int)e); + // use historic code solution + visibleQuad = this->gameCamera->computeVisibleQuad(); + } + } } -void Renderer::renderMouse3d() { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - Config &config= Config::getInstance(); - if(config.getBool("RecordMode","false") == true) { - return; - } - - if(game == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s] Line: %d game == NULL",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - throw megaglest_runtime_error(szBuf); - } - else if(game->getGui() == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s] Line: %d game->getGui() == NULL",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - throw megaglest_runtime_error(szBuf); - } - else if(game->getGui()->getMouse3d() == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s] Line: %d game->getGui()->getMouse3d() == NULL",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - throw megaglest_runtime_error(szBuf); - } - - const Gui *gui= game->getGui(); - const Mouse3d *mouse3d= gui->getMouse3d(); - const Map *map= game->getWorld()->getMap(); - if(map == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s] Line: %d map == NULL",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - throw megaglest_runtime_error(szBuf); - } - - assertGl(); +// ======================================= +// basic rendering +// ======================================= - if((mouse3d->isEnabled() || gui->isPlacingBuilding()) && gui->isValidPosObjWorld()) { - const Vec2i &pos= gui->getPosObjWorld(); +void Renderer::renderMouse2d(int x, int y, int anim, float fade) { + if (no2DMouseRendering == true) { + return; + } + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + // float blue=0.0f; + // float green=0.4f; + if (game != NULL && game->getGui() != NULL) { + const Gui *gui = game->getGui(); + const Display *display = gui->getDisplay(); + int downPos = display->getDownSelectedPos(); + if (downPos != Display::invalidPos) { + // in state of doing something + const Texture2D *texture = display->getDownImage(downPos); + renderTextureQuad(x + 18, y - 50, 32, 32, texture, 0.8f); + } + // else { + // // Display current commandtype + // const Unit *unit=NULL; + // if(gui->getSelection()->isEmpty()){ + // blue=0.0f; + // green=0.1f; + // } + // else{ + // unit=gui->getSelection()->getFrontUnit(); + // if(unit->getCurrCommand()!=NULL && + // unit->getCurrCommand()->getCommandType()->getImage()!=NULL){ + // const Texture2D *texture = + // unit->getCurrCommand()->getCommandType()->getImage(); + // renderTextureQuad(x+18,y-50,32,32,texture,0.2f); + // } + // } + // } + + if (game->isMarkCellMode() == true) { + const Texture2D *texture = game->getMarkCellTexture(); + renderTextureQuad(x, y, texture->getTextureWidth(), + texture->getTextureHeight(), texture, 0.8f); + } + if (game->isUnMarkCellMode() == true) { + const Texture2D *texture = game->getUnMarkCellTexture(); + renderTextureQuad(x, y, texture->getTextureWidth(), + texture->getTextureHeight(), texture, 0.8f); + } + } + + float fadeFactor = fade + 1.f; + + anim = anim * 2 - maxMouse2dAnim; + + float color2 = + (abs(anim * (int)fadeFactor) / static_cast(maxMouse2dAnim)) / 2.f + + 0.4f; + float color1 = + (abs(anim * (int)fadeFactor) / static_cast(maxMouse2dAnim)) / 2.f + + 0.8f; + + glPushAttrib(GL_CURRENT_BIT | GL_COLOR_BUFFER_BIT | GL_LINE_BIT); + glEnable(GL_BLEND); + + // inside + glColor4f(0.4f * fadeFactor, 0.2f * fadeFactor, 0.2f * fadeFactor, + 0.5f * fadeFactor); + glBegin(GL_TRIANGLES); + glVertex2i(x, y); + glVertex2i(x + 20, y - 10); + glVertex2i(x + 10, y - 20); + glEnd(); + + // border + glLineWidth(2); + glBegin(GL_LINE_LOOP); + glColor4f(1.f, 0.2f, 0, color1); + glVertex2i(x, y); + glColor4f(1.f, 0.4f, 0, color2); + glVertex2i(x + 20, y - 10); + glColor4f(1.f, 0.4f, 0, color2); + glVertex2i(x + 10, y - 20); + glEnd(); + glPopAttrib(); + + /* + if(no2DMouseRendering == true) { + return; + } + float color1 = 0.0, color2 = 0.0; + + float fadeFactor = fade + 1.f; + + anim= anim * 2 - maxMouse2dAnim; + + color2= + (abs(anim*(int)fadeFactor)/static_cast(maxMouse2dAnim))/2.f+0.4f; + color1= + (abs(anim*(int)fadeFactor)/static_cast(maxMouse2dAnim))/2.f+0.8f; + + glPushAttrib(GL_CURRENT_BIT | GL_COLOR_BUFFER_BIT | GL_LINE_BIT); + glEnable(GL_BLEND); + + //inside + Vec2i vertices[3]; + vertices[0] = Vec2i(x, y); + vertices[1] = Vec2i(x+20, y-10); + vertices[2] = Vec2i(x+10, y-20); + + glColor4f(0.4f*fadeFactor, 0.2f*fadeFactor, 0.2f*fadeFactor, + 0.5f*fadeFactor); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(2, + GL_INT, 0, &vertices[0]); glDrawArrays(GL_TRIANGLES, 0, 3); + glDisableClientState(GL_VERTEX_ARRAY); + + //border + vertices[0] = Vec2i(x, y); + vertices[1] = Vec2i(x+20, y-10); + vertices[2] = Vec2i(x+10, y-20); + + Vec4f colors[4]; + colors[0] = Vec4f(1.f, 0.2f, 0, color1); + colors[1] = Vec4f(1.f, 0.4f, 0, color2); + colors[2] = Vec4f(1.f, 0.4f, 0, color2); + + glLineWidth(2); + glEnableClientState(GL_VERTEX_ARRAY); + glVertexPointer(2, GL_INT, 0, &vertices[0]); + glEnableClientState(GL_COLOR_ARRAY); + glColorPointer(4, GL_FLOAT, 0, &colors[0]); + glDrawArrays(GL_LINE_LOOP, 0, 3); + glDisableClientState(GL_COLOR_ARRAY); + glDisableClientState(GL_VERTEX_ARRAY); + + glPopAttrib(); + */ +} - glMatrixMode(GL_MODELVIEW); +void Renderer::renderMouse3d() { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + Config &config = Config::getInstance(); + if (config.getBool("RecordMode", "false") == true) { + return; + } + + if (game == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s] Line: %d game == NULL", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + throw megaglest_runtime_error(szBuf); + } else if (game->getGui() == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s] Line: %d game->getGui() == NULL", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + throw megaglest_runtime_error(szBuf); + } else if (game->getGui()->getMouse3d() == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s] Line: %d game->getGui()->getMouse3d() == NULL", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + throw megaglest_runtime_error(szBuf); + } + + const Gui *gui = game->getGui(); + const Mouse3d *mouse3d = gui->getMouse3d(); + const Map *map = game->getWorld()->getMap(); + if (map == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s] Line: %d map == NULL", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + throw megaglest_runtime_error(szBuf); + } + + assertGl(); + + if ((mouse3d->isEnabled() || gui->isPlacingBuilding()) && + gui->isValidPosObjWorld()) { + const Vec2i &pos = gui->getPosObjWorld(); + + glMatrixMode(GL_MODELVIEW); + + glPushAttrib(GL_CURRENT_BIT | GL_LIGHTING_BIT | GL_ENABLE_BIT | + GL_DEPTH_BUFFER_BIT); + glEnable(GL_BLEND); + glDisable(GL_STENCIL_TEST); + glDepthFunc(GL_LESS); + glEnable(GL_COLOR_MATERIAL); + glDepthMask(GL_FALSE); + + if (gui->isPlacingBuilding()) { + + modelRenderer->begin(true, true, false, false); + + const UnitType *building = gui->getBuilding(); + const Gui *gui = game->getGui(); + renderGhostModel(building, pos, gui->getSelectedFacing()); + + modelRenderer->end(); + + glDisable(GL_COLOR_MATERIAL); + glPopAttrib(); + } else { + glPushMatrix(); + Vec3f pos3f = Vec3f(pos.x, map->getCell(pos)->getHeight(), pos.y); + Vec4f color; + GLUquadricObj *cilQuadric; + // standard mouse + glDisable(GL_TEXTURE_2D); + glDisable(GL_CULL_FACE); + color = Vec4f(1.f, 0.f, 0.f, 1.f - mouse3d->getFade()); + glColor4fv(color.ptr()); + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, color.ptr()); + + glTranslatef(pos3f.x, pos3f.y + 2.f, pos3f.z); + glRotatef(90.f, 1.f, 0.f, 0.f); + glRotatef(static_cast(mouse3d->getRot()), 0.f, 0.f, 1.f); + + cilQuadric = gluNewQuadric(); + gluQuadricDrawStyle(cilQuadric, GLU_FILL); + gluCylinder(cilQuadric, 0.5f, 0.f, 2.f, 4, 1); + gluCylinder(cilQuadric, 0.5f, 0.f, 0.f, 4, 1); + glTranslatef(0.f, 0.f, 1.f); + gluCylinder(cilQuadric, 0.7f, 0.f, 1.f, 4, 1); + gluCylinder(cilQuadric, 0.7f, 0.f, 0.f, 4, 1); + gluDeleteQuadric(cilQuadric); + + glPopAttrib(); + glPopMatrix(); + } + } +} - glPushAttrib(GL_CURRENT_BIT | GL_LIGHTING_BIT | GL_ENABLE_BIT | GL_DEPTH_BUFFER_BIT); - glEnable(GL_BLEND); - glDisable(GL_STENCIL_TEST); - glDepthFunc(GL_LESS); - glEnable(GL_COLOR_MATERIAL); - glDepthMask(GL_FALSE); +void Renderer::renderBackground(const Texture2D *texture) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + const Metrics &metrics = Metrics::getInstance(); + + assertGl(); + + glPushAttrib(GL_ENABLE_BIT); + + glDisable(GL_LIGHTING); + glEnable(GL_TEXTURE_2D); + + renderQuad(0, 0, metrics.getVirtualW(), metrics.getVirtualH(), texture); + + glPopAttrib(); + + assertGl(); +} + +void Renderer::renderTextureQuad(int x, int y, int w, int h, + const Texture2D *texture, float alpha, + const Vec3f *color) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + assertGl(); + + glPushAttrib(GL_ENABLE_BIT); + + glDisable(GL_LIGHTING); + glEnable(GL_TEXTURE_2D); + glEnable(GL_BLEND); + + if (color != NULL) { + Vec4f newColor(*color); + newColor.w = alpha; + glColor4fv(newColor.ptr()); + } else { + glColor4f(1.f, 1.f, 1.f, alpha); + } + renderQuad(x, y, w, h, texture); + + glPopAttrib(); + + assertGl(); +} + +void Renderer::renderConsoleLine3D(int lineIndex, int xPosition, int yPosition, + int lineHeight, Font3D *font, + string stringToHightlight, + const ConsoleLineInfo *lineInfo) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + Vec4f fontColor; + Lang &lang = Lang::getInstance(); + // const Metrics &metrics= Metrics::getInstance(); + FontMetrics *fontMetrics = font->getMetrics(); + + if (game != NULL) { + fontColor = game->getGui()->getDisplay()->getColor(); + } else { + // white shadowed is default ( in the menu for example ) + // fontColor=Vec4f(1.f, 1.f, 1.f, 0.0f); + fontColor = + Vec4f(lineInfo->color.x, lineInfo->color.y, lineInfo->color.z, 0.0f); + } + + Vec4f defaultFontColor = fontColor; + + if (lineInfo->PlayerIndex >= 0) { + std::map &crcPlayerTextureCache = + CacheManager::getCachedItem>( + GameConstants::playerTextureCacheLookupKey); + Vec3f playerColor = + crcPlayerTextureCache[lineInfo->PlayerIndex]->getPixmap()->getPixel3f( + 0, 0); + fontColor.x = playerColor.x; + fontColor.y = playerColor.y; + fontColor.z = playerColor.z; + + GameNetworkInterface *gameNetInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + if (gameNetInterface != NULL && + gameNetInterface->getGameSettings() != NULL) { + const GameSettings *gameSettings = gameNetInterface->getGameSettings(); + string playerName = gameSettings->getNetworkPlayerNameByPlayerIndex( + lineInfo->PlayerIndex); + if (playerName != lineInfo->originalPlayerName && + lineInfo->originalPlayerName != "") { + playerName = lineInfo->originalPlayerName; + } + if (playerName == GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME) { + playerName = lang.getString("SystemUser"); + } + // printf("playerName [%s], line [%s]\n",playerName.c_str(),line.c_str()); + + // string headerLine = "*" + playerName + ":"; + // string headerLine = playerName + ": "; + string headerLine = playerName; + if (lineInfo->teamMode == true) { + headerLine += " (" + lang.getString("Team") + ")"; + } + headerLine += ": "; + + if (fontMetrics == NULL) { + throw megaglest_runtime_error("fontMetrics == NULL"); + } + + renderTextShadow3D(headerLine, font, fontColor, xPosition, + lineIndex * lineHeight + yPosition); + + fontColor = defaultFontColor; + // xPosition += (8 * (playerName.length() + 2)); + // Proper font spacing after username portion of chat text rendering + + // xPosition += + // (metrics.toVirtualX(fontMetrics->getTextWidth(headerLine))); + xPosition += fontMetrics->getTextWidth(headerLine); + } + } else if (lineInfo->originalPlayerName != "") { + string playerName = lineInfo->originalPlayerName; + // string headerLine = playerName + ": "; + string headerLine = playerName; + if (lineInfo->teamMode == true) { + headerLine += " (" + lang.getString("Team") + ")"; + } + headerLine += ": "; - if(gui->isPlacingBuilding()) { + if (fontMetrics == NULL) { + throw megaglest_runtime_error("fontMetrics == NULL"); + } - modelRenderer->begin(true, true, false, false); + renderTextShadow3D(headerLine, font, fontColor, xPosition, + lineIndex * lineHeight + yPosition); + + fontColor = defaultFontColor; + // xPosition += (8 * (playerName.length() + 2)); + // Proper font spacing after username portion of chat text rendering + // xPosition += (metrics.toVirtualX(fontMetrics->getTextWidth(headerLine))); + xPosition += fontMetrics->getTextWidth(headerLine); + } else { + fontColor = defaultFontColor; + } + + if (stringToHightlight != "" && + lineInfo->text.find(stringToHightlight) != string::npos) { + fontColor = Vec4f(1.f, 0.5f, 0.5f, 0.0f); + } + renderTextShadow3D(lineInfo->text, font, fontColor, xPosition, + (lineIndex * lineHeight) + yPosition); +} + +void Renderer::renderConsoleLine(int lineIndex, int xPosition, int yPosition, + int lineHeight, Font2D *font, + string stringToHightlight, + const ConsoleLineInfo *lineInfo) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + Vec4f fontColor; + Lang &lang = Lang::getInstance(); + + const Metrics &metrics = Metrics::getInstance(); + FontMetrics *fontMetrics = font->getMetrics(); + + if (game != NULL) { + fontColor = game->getGui()->getDisplay()->getColor(); + } else { + // white shadowed is default ( in the menu for example ) + // fontColor=Vec4f(1.f, 1.f, 1.f, 0.0f); + fontColor = + Vec4f(lineInfo->color.x, lineInfo->color.y, lineInfo->color.z, 0.0f); + } + + Vec4f defaultFontColor = fontColor; + + if (lineInfo->PlayerIndex >= 0) { + std::map &crcPlayerTextureCache = + CacheManager::getCachedItem>( + GameConstants::playerTextureCacheLookupKey); + Vec3f playerColor = + crcPlayerTextureCache[lineInfo->PlayerIndex]->getPixmap()->getPixel3f( + 0, 0); + fontColor.x = playerColor.x; + fontColor.y = playerColor.y; + fontColor.z = playerColor.z; + + GameNetworkInterface *gameNetInterface = + NetworkManager::getInstance().getGameNetworkInterface(); + if (gameNetInterface != NULL && + gameNetInterface->getGameSettings() != NULL) { + const GameSettings *gameSettings = gameNetInterface->getGameSettings(); + string playerName = gameSettings->getNetworkPlayerNameByPlayerIndex( + lineInfo->PlayerIndex); + if (playerName != lineInfo->originalPlayerName && + lineInfo->originalPlayerName != "") { + playerName = lineInfo->originalPlayerName; + } + // printf("playerName [%s], line [%s]\n",playerName.c_str(),line.c_str()); + + // string headerLine = "*" + playerName + ":"; + // string headerLine = playerName + ": "; + string headerLine = playerName; + if (lineInfo->teamMode == true) { + headerLine += " (" + lang.getString("Team") + ")"; + } + headerLine += ": "; + + if (fontMetrics == NULL) { + throw megaglest_runtime_error("fontMetrics == NULL"); + } + + renderTextShadow(headerLine, font, fontColor, xPosition, + lineIndex * lineHeight + yPosition); + + fontColor = defaultFontColor; + // xPosition += (8 * (playerName.length() + 2)); + // Proper font spacing after username portion of chat text rendering + xPosition += (metrics.toVirtualX(fontMetrics->getTextWidth(headerLine))); + } + } else if (lineInfo->originalPlayerName != "") { + string playerName = lineInfo->originalPlayerName; + // string headerLine = playerName + ": "; + string headerLine = playerName; + if (lineInfo->teamMode == true) { + headerLine += " (" + lang.getString("Team") + ")"; + } + headerLine += ": "; - const UnitType *building= gui->getBuilding(); - const Gui *gui= game->getGui(); - renderGhostModel(building, pos, gui->getSelectedFacing()); + if (fontMetrics == NULL) { + throw megaglest_runtime_error("fontMetrics == NULL"); + } - modelRenderer->end(); + renderTextShadow(headerLine, font, fontColor, xPosition, + lineIndex * lineHeight + yPosition); + + fontColor = defaultFontColor; + // xPosition += (8 * (playerName.length() + 2)); + // Proper font spacing after username portion of chat text rendering + xPosition += (metrics.toVirtualX(fontMetrics->getTextWidth(headerLine))); + } else { + fontColor = defaultFontColor; + } + + if (stringToHightlight != "" && + lineInfo->text.find(stringToHightlight) != string::npos) { + fontColor = Vec4f(1.f, 0.5f, 0.5f, 0.0f); + } + renderTextShadow(lineInfo->text, font, fontColor, xPosition, + (lineIndex * lineHeight) + yPosition); +} + +void Renderer::renderConsole(const Console *console, ConsoleMode mode, + int overrideMaxConsoleLines) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + if (console == NULL) { + throw megaglest_runtime_error("console == NULL"); + } + + glPushAttrib(GL_ENABLE_BIT); + glEnable(GL_BLEND); + + if (mode == consoleFull) { + int x = console->getXPos() - 5; + int y = console->getYPos() - 5; + int h = console->getLineHeight() * console->getStoredLineCount(); + + if (h > 0) { + int w = 1000; + // background + glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT); + glEnable(GL_BLEND); + + glColor4f(0.0f, 0.0f, 0.0f, 0.8f); + + glBegin(GL_TRIANGLE_STRIP); + glVertex2i(x, y); + glVertex2i(x, y + h); + glVertex2i(x + w, y); + glVertex2i(x + w, y + h); + glEnd(); + glPopAttrib(); + } + for (int i = 0; i < console->getStoredLineCount(); ++i) { + const ConsoleLineInfo &lineInfo = console->getStoredLineItem(i); + if (renderText3DEnabled == true) { + renderConsoleLine3D(i, console->getXPos(), console->getYPos(), + console->getLineHeight(), console->getFont3D(), + console->getStringToHighlight(), &lineInfo); + } else { + renderConsoleLine(i, console->getXPos(), console->getYPos(), + console->getLineHeight(), console->getFont(), + console->getStringToHighlight(), &lineInfo); + } + } + } else if (mode == consoleStoredOnly) { + int allowedMaxLines = + (overrideMaxConsoleLines >= 0 ? overrideMaxConsoleLines + : maxConsoleLines); + for (int i = 0; i < console->getStoredLineCount() && i < allowedMaxLines; + ++i) { + const ConsoleLineInfo &lineInfo = console->getStoredLineItem(i); + if (renderText3DEnabled == true) { + renderConsoleLine3D(i, console->getXPos(), console->getYPos(), + console->getLineHeight(), console->getFont3D(), + console->getStringToHighlight(), &lineInfo); + } else { + renderConsoleLine(i, console->getXPos(), console->getYPos(), + console->getLineHeight(), console->getFont(), + console->getStringToHighlight(), &lineInfo); + } + } + } else if (mode == consoleStoredAndNormal) { + int allowedMaxLines = + (overrideMaxConsoleLines >= 0 ? overrideMaxConsoleLines + : maxConsoleLines); + float starttimestamp = -1; + int consoleIndex = 0; + for (int i = 0; i < console->getLineCount() && i < allowedMaxLines; ++i) { + const ConsoleLineInfo &lineInfo = console->getLineItem(i); + if (starttimestamp > lineInfo.timeStamp || starttimestamp == -1) + starttimestamp = lineInfo.timeStamp; + if (renderText3DEnabled == true) { + renderConsoleLine3D(i, console->getXPos(), console->getYPos(), + console->getLineHeight(), console->getFont3D(), + console->getStringToHighlight(), &lineInfo); + } else { + renderConsoleLine(i, console->getXPos(), console->getYPos(), + console->getLineHeight(), console->getFont(), + console->getStringToHighlight(), &lineInfo); + } + consoleIndex++; + } + for (int i = 0; + i < console->getStoredLineCount() && consoleIndex < allowedMaxLines; + ++i) { + const ConsoleLineInfo &lineInfo = console->getStoredLineItem(i); + if (lineInfo.timeStamp < starttimestamp || starttimestamp == -1) { + if (renderText3DEnabled == true) { + renderConsoleLine3D(consoleIndex, console->getXPos(), + console->getYPos(), console->getLineHeight(), + console->getFont3D(), + console->getStringToHighlight(), &lineInfo); + } else { + renderConsoleLine(consoleIndex, console->getXPos(), + console->getYPos(), console->getLineHeight(), + console->getFont(), console->getStringToHighlight(), + &lineInfo); + } + consoleIndex++; + } + } + } else if (mode == consoleNormal) { + for (int i = 0; i < console->getLineCount(); ++i) { + const ConsoleLineInfo &lineInfo = console->getLineItem(i); + if (renderText3DEnabled == true) { + renderConsoleLine3D(i, console->getXPos(), console->getYPos(), + console->getLineHeight(), console->getFont3D(), + console->getStringToHighlight(), &lineInfo); + } else { + renderConsoleLine(i, console->getXPos(), console->getYPos(), + console->getLineHeight(), console->getFont(), + console->getStringToHighlight(), &lineInfo); + } + } + } + glPopAttrib(); +} - glDisable(GL_COLOR_MATERIAL); - glPopAttrib(); - } - else { - glPushMatrix(); - Vec3f pos3f= Vec3f(pos.x, map->getCell(pos)->getHeight(), pos.y); - Vec4f color; - GLUquadricObj *cilQuadric; - //standard mouse - glDisable(GL_TEXTURE_2D); - glDisable(GL_CULL_FACE); - color= Vec4f(1.f, 0.f, 0.f, 1.f-mouse3d->getFade()); - glColor4fv(color.ptr()); - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, color.ptr()); +void Renderer::renderChatManager(const ChatManager *chatManager) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + Vec4f fontColor; + Lang &lang = Lang::getInstance(); + + if (chatManager->getEditEnabled()) { + Vec4f color = Vec4f(0.0f, 0.0f, 0.0f, 0.6f); + string text = ""; + + if (chatManager->isInCustomInputMode() == true) { + text += lang.getString("CellHint"); + } else if (chatManager->getInMenu()) { + text += lang.getString("Chat"); + } else if (chatManager->getTeamMode()) { + text += lang.getString("Team"); + } else { + text += lang.getString("All"); + } + text += ": " + chatManager->getText() + "_"; - glTranslatef(pos3f.x, pos3f.y+2.f, pos3f.z); - glRotatef(90.f, 1.f, 0.f, 0.f); - glRotatef(static_cast(mouse3d->getRot()), 0.f, 0.f, 1.f); + if (game != NULL) { + fontColor = game->getGui()->getDisplay()->getColor(); + } else { + // white shadowed is default ( in the menu for example ) + fontColor = Vec4f(1.f, 1.f, 1.f, 0.0f); + } - cilQuadric= gluNewQuadric(); - gluQuadricDrawStyle(cilQuadric, GLU_FILL); - gluCylinder(cilQuadric, 0.5f, 0.f, 2.f, 4, 1); - gluCylinder(cilQuadric, 0.5f, 0.f, 0.f, 4, 1); - glTranslatef(0.f, 0.f, 1.f); - gluCylinder(cilQuadric, 0.7f, 0.f, 1.f, 4, 1); - gluCylinder(cilQuadric, 0.7f, 0.f, 0.f, 4, 1); - gluDeleteQuadric(cilQuadric); + // render Background + int x = chatManager->getXPos(); + int y = chatManager->getYPos() - 6; + int h = 22; + int w = 830; - glPopAttrib(); - glPopMatrix(); - } - } + glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT); + glEnable(GL_BLEND); -} + glColor4f(color.x, color.y, color.z, color.w); -void Renderer::renderBackground(const Texture2D *texture) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } + glBegin(GL_TRIANGLE_STRIP); + glVertex2i(x, y); + glVertex2i(x, y + h); + glVertex2i(x + w, y); + glVertex2i(x + w, y + h); + glEnd(); + glPopAttrib(); - const Metrics &metrics= Metrics::getInstance(); + if (renderText3DEnabled == true) { + renderTextShadow3D(text, chatManager->getFont3D(), fontColor, + chatManager->getXPos(), chatManager->getYPos()); + } else { + renderTextShadow(text, chatManager->getFont(), fontColor, + chatManager->getXPos(), chatManager->getYPos()); + } + } else { + if (chatManager->getInMenu()) { + string text = + "\t\t\t\t\t>> " + lang.getString("PressEnterToChat") + " <<"; + fontColor = Vec4f(0.5f, 0.5f, 0.5f, 0.5f); + + if (renderText3DEnabled == true) { + renderTextShadow3D(text, chatManager->getFont3D(), fontColor, + chatManager->getXPos(), chatManager->getYPos()); + } else { + renderTextShadow(text, chatManager->getFont(), fontColor, + chatManager->getXPos(), chatManager->getYPos()); + } + } + } +} - assertGl(); +void Renderer::renderPerformanceStats() { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - glPushAttrib(GL_ENABLE_BIT); + const Metrics &metrics = Metrics::getInstance(); + const Vec4f fontColor = game->getGui()->getDisplay()->getColor(); - glDisable(GL_LIGHTING); - glEnable(GL_TEXTURE_2D); + char szBuf[200] = ""; + snprintf(szBuf, 200, "Frame: %d", game->getWorld()->getFrameCount() / 20); + string str = string(szBuf) + string("\n"); - renderQuad(0, 0, metrics.getVirtualW(), metrics.getVirtualH(), texture); + static time_t lastGamePerfCheck = time(NULL); + static string gamePerfStats = ""; + if (difftime((long int)time(NULL), lastGamePerfCheck) > 3) { + lastGamePerfCheck = time(NULL); + gamePerfStats = game->getGamePerformanceCounts(true); + } - glPopAttrib(); + if (gamePerfStats != "") { + str += gamePerfStats + "\n"; + } - assertGl(); + if (renderText3DEnabled == true) { + renderTextShadow3D(str, CoreData::getInstance().getDisplayFontSmall3D(), + fontColor, 10, metrics.getVirtualH() - 180, false); + } else { + renderTextShadow(str, CoreData::getInstance().getDisplayFontSmall(), + fontColor, 10, metrics.getVirtualH() - 180, false); + } } -void Renderer::renderTextureQuad(int x, int y, int w, int h, const Texture2D *texture, float alpha,const Vec3f *color) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - assertGl(); - - glPushAttrib(GL_ENABLE_BIT); - - glDisable(GL_LIGHTING); - glEnable(GL_TEXTURE_2D); - glEnable(GL_BLEND); - - if(color != NULL) { - Vec4f newColor(*color); - newColor.w = alpha; - glColor4fv(newColor.ptr()); - } - else { - glColor4f(1.f, 1.f, 1.f, alpha); - } - renderQuad(x, y, w, h, texture); +void Renderer::renderClock() { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + Config &config = Config::getInstance(); + if (config.getBool("InGameClock", "true") == false && + config.getBool("InGameLocalClock", "true") == false && + config.getBool("InGameFrameCounter", "false") == false) { + return; + } + + string str = ""; + const Metrics &metrics = Metrics::getInstance(); + const World *world = game->getWorld(); + const Vec4f fontColor = game->getGui()->getDisplay()->getColor(); + + if (config.getBool("InGameClock", "true") == true) { + Lang &lang = Lang::getInstance(); + char szBuf[501] = ""; + + // int hours = world->getTimeFlow()->getTime(); + // int minutes = (world->getTimeFlow()->getTime() - hours) * 100 * 0.6; // + // scale 100 to 60 snprintf(szBuf,200,"%s + // %.2d:%.2d",lang.getString("GameTime","",true).c_str(),hours,minutes); + // string header2 = lang.getString("GameDurationTime","",true) + ": " + + // getTimeString(stats.getFramesToCalculatePlaytime()); + snprintf( + szBuf, 500, "%s %s", + lang.getString("GameDurationTime", "", true).c_str(), + getTimeDuationString(world->getFrameCount(), GameConstants::updateFps) + .c_str()); + if (str != "") { + str += " "; + } + str += szBuf; + } + + if (config.getBool("InGameLocalClock", "true") == true) { + // time_t nowTime = time(NULL); + // struct tm *loctime = localtime(&nowTime); + struct tm loctime = threadsafe_localtime(systemtime_now()); + char szBuf2[100] = ""; + strftime(szBuf2, 100, "%H:%M", &loctime); + + Lang &lang = Lang::getInstance(); + char szBuf[200] = ""; + snprintf(szBuf, 200, "%s %s", lang.getString("LocalTime", "", true).c_str(), + szBuf2); + if (str != "") { + str += " "; + } + str += szBuf; + } + + if (config.getBool("InGameFrameCounter", "false") == true) { + char szBuf[200] = ""; + snprintf(szBuf, 200, "Frame: %d", game->getWorld()->getFrameCount() / 20); + if (str != "") { + str += " "; + } + str += szBuf; + } - glPopAttrib(); + // string str = szBuf; - assertGl(); + if (renderText3DEnabled == true) { + renderTextShadow3D(str, CoreData::getInstance().getDisplayFontSmall3D(), + fontColor, 10, metrics.getVirtualH() - 160, false); + } else { + renderTextShadow(str, CoreData::getInstance().getDisplayFontSmall(), + fontColor, 10, metrics.getVirtualH() - 160, false); + } } -void Renderer::renderConsoleLine3D(int lineIndex, int xPosition, int yPosition, int lineHeight, - Font3D* font, string stringToHightlight, const ConsoleLineInfo *lineInfo) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - Vec4f fontColor; - Lang &lang= Lang::getInstance(); - //const Metrics &metrics= Metrics::getInstance(); - FontMetrics *fontMetrics= font->getMetrics(); - - if(game != NULL) { - fontColor = game->getGui()->getDisplay()->getColor(); - } - else { - // white shadowed is default ( in the menu for example ) - //fontColor=Vec4f(1.f, 1.f, 1.f, 0.0f); - fontColor=Vec4f(lineInfo->color.x,lineInfo->color.y,lineInfo->color.z, 0.0f); - } - - Vec4f defaultFontColor = fontColor; - - if(lineInfo->PlayerIndex >= 0) { - std::map &crcPlayerTextureCache = CacheManager::getCachedItem< std::map >(GameConstants::playerTextureCacheLookupKey); - Vec3f playerColor = crcPlayerTextureCache[lineInfo->PlayerIndex]->getPixmap()->getPixel3f(0, 0); - fontColor.x = playerColor.x; - fontColor.y = playerColor.y; - fontColor.z = playerColor.z; - - GameNetworkInterface *gameNetInterface = NetworkManager::getInstance().getGameNetworkInterface(); - if(gameNetInterface != NULL && gameNetInterface->getGameSettings() != NULL) { - const GameSettings *gameSettings = gameNetInterface->getGameSettings(); - string playerName = gameSettings->getNetworkPlayerNameByPlayerIndex(lineInfo->PlayerIndex); - if(playerName != lineInfo->originalPlayerName && lineInfo->originalPlayerName != "") { - playerName = lineInfo->originalPlayerName; - } - if(playerName == GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME) { - playerName = lang.getString("SystemUser"); - } - //printf("playerName [%s], line [%s]\n",playerName.c_str(),line.c_str()); - - //string headerLine = "*" + playerName + ":"; - //string headerLine = playerName + ": "; - string headerLine = playerName; - if(lineInfo->teamMode == true) { - headerLine += " (" + lang.getString("Team") + ")"; - } - headerLine += ": "; - - if(fontMetrics == NULL) { - throw megaglest_runtime_error("fontMetrics == NULL"); - } - - renderTextShadow3D( - headerLine, - font, - fontColor, - xPosition, lineIndex * lineHeight + yPosition); - - fontColor = defaultFontColor; - //xPosition += (8 * (playerName.length() + 2)); - // Proper font spacing after username portion of chat text rendering - - //xPosition += (metrics.toVirtualX(fontMetrics->getTextWidth(headerLine))); - xPosition += fontMetrics->getTextWidth(headerLine); - } - } - else if(lineInfo->originalPlayerName != "") { - string playerName = lineInfo->originalPlayerName; - //string headerLine = playerName + ": "; - string headerLine = playerName; - if(lineInfo->teamMode == true) { - headerLine += " (" + lang.getString("Team") + ")"; - } - headerLine += ": "; - - if(fontMetrics == NULL) { - throw megaglest_runtime_error("fontMetrics == NULL"); +void Renderer::renderResourceStatus() { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + const World *world = game->getWorld(); + Config &config = Config::getInstance(); + + if (world->getThisFactionIndex() < 0 || + world->getThisFactionIndex() >= world->getFactionCount()) { + return; + } + + const Faction *thisFaction = world->getFaction(world->getThisFactionIndex()); + if (thisFaction->getPersonalityType() == fpt_Observer) { + // render resources of selected units faction + const Gui *gui = game->getGui(); + if (gui != NULL) { + const Selection *selection = gui->getSelection(); + if (selection != NULL && selection->getCount() > 0 && + selection->getFrontUnit() != NULL) { + const Unit *selectedUnit = selection->getFrontUnit(); + thisFaction = selectedUnit->getFaction(); + } + } + } + assertGl(); + glPushAttrib(GL_ENABLE_BIT); + + int rowsRendered = 0; + int resourceCountRendered = 0; + bool twoRessourceLines = false; + + bool sharedTeamUnits = + game != NULL && game->getGui() != NULL && + game->isFlagType1BitEnabled(ft1_allow_shared_team_units) == true; + bool sharedTeamResources = + game != NULL && game->getGui() != NULL && + game->isFlagType1BitEnabled(ft1_allow_shared_team_resources) == true; + + bool renderSharedTeamResources = false; + bool renderSharedTeamUnits = false; + bool renderLocalFactionResources = false; + + if (config.getBool("TwoLineTeamResourceRendering", "false") == true) { + if (sharedTeamResources == true || sharedTeamUnits == true) { + twoRessourceLines = true; + } + if (sharedTeamResources == true) { + renderSharedTeamResources = true; + renderSharedTeamUnits = true; + } else if (sharedTeamUnits == true) { + renderSharedTeamUnits = true; + renderLocalFactionResources = true; + } else { + renderLocalFactionResources = true; + } + } else { + if (sharedTeamResources == true) + renderSharedTeamResources = true; + else if (sharedTeamUnits == true) + renderSharedTeamUnits = true; + else + renderLocalFactionResources = true; + } + + if (renderSharedTeamResources == true) { + resourceCountRendered = 0; + for (int techTreeResourceTypeIndex = 0; + techTreeResourceTypeIndex < + world->getTechTree()->getResourceTypeCount(); + ++techTreeResourceTypeIndex) { + + const ResourceType *rt = + world->getTechTree()->getResourceType(techTreeResourceTypeIndex); + + if (rt->getDisplayInHud() == false) { + continue; + } + + bool showResource = + world->showResourceTypeForTeam(rt, thisFaction->getTeam()); + if (showResource == true) { + rowsRendered = renderResource(thisFaction, false, twoRessourceLines, rt, + 0, resourceCountRendered); + } + } + if (resourceCountRendered > 0) { + rowsRendered++; + } + } + + if (renderLocalFactionResources == true) { + resourceCountRendered = 0; + + const Faction *factionForResourceView = thisFaction; + bool localFactionResourcesOnly = true; + + for (int techTreeResourceTypeIndex = 0; + techTreeResourceTypeIndex < + world->getTechTree()->getResourceTypeCount(); + ++techTreeResourceTypeIndex) { + const ResourceType *rt = + world->getTechTree()->getResourceType(techTreeResourceTypeIndex); + if (rt->getDisplayInHud() == false) { + continue; + } + + // if any unit produces the resource + bool showResource; + if (twoRessourceLines) + showResource = world->showResourceTypeForTeam( + rt, factionForResourceView->getTeam()); + else + showResource = + world->showResourceTypeForFaction(rt, factionForResourceView); + if (showResource == true) { + renderResource(factionForResourceView, localFactionResourcesOnly, + twoRessourceLines, rt, rowsRendered, + resourceCountRendered); + } + } + if (resourceCountRendered > 0) { + rowsRendered++; + } + } + + if (renderSharedTeamUnits == true) { + resourceCountRendered = 0; + + const Faction *factionForResourceView = thisFaction; + bool localFactionResourcesOnly = true; + + const Gui *gui = game->getGui(); + if (gui != NULL) { + const Selection *selection = gui->getSelection(); + if (selection != NULL && selection->getCount() > 0 && + selection->getFrontUnit() != NULL) { + const Unit *selectedUnit = selection->getFrontUnit(); + if (selectedUnit != NULL && + selectedUnit->getFaction()->isAlly(thisFaction) == true) { + factionForResourceView = selectedUnit->getFaction(); } + } + } - renderTextShadow3D( - headerLine, - font, - fontColor, - xPosition, lineIndex * lineHeight + yPosition); - - fontColor = defaultFontColor; - //xPosition += (8 * (playerName.length() + 2)); - // Proper font spacing after username portion of chat text rendering - //xPosition += (metrics.toVirtualX(fontMetrics->getTextWidth(headerLine))); - xPosition += fontMetrics->getTextWidth(headerLine); - } - else { - fontColor = defaultFontColor; - } - - if(stringToHightlight!="" && lineInfo->text.find(stringToHightlight)!=string::npos){ - fontColor=Vec4f(1.f, 0.5f, 0.5f, 0.0f); - } - renderTextShadow3D( - lineInfo->text, - font, - fontColor, - xPosition, (lineIndex * lineHeight) + yPosition); -} - -void Renderer::renderConsoleLine(int lineIndex, int xPosition, int yPosition, int lineHeight, - Font2D* font, string stringToHightlight, const ConsoleLineInfo *lineInfo) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - Vec4f fontColor; - Lang &lang= Lang::getInstance(); - - const Metrics &metrics= Metrics::getInstance(); - FontMetrics *fontMetrics= font->getMetrics(); - - if(game != NULL) { - fontColor = game->getGui()->getDisplay()->getColor(); - } - else { - // white shadowed is default ( in the menu for example ) - //fontColor=Vec4f(1.f, 1.f, 1.f, 0.0f); - fontColor=Vec4f(lineInfo->color.x,lineInfo->color.y,lineInfo->color.z, 0.0f); - } - - Vec4f defaultFontColor = fontColor; - - if(lineInfo->PlayerIndex >= 0) { - std::map &crcPlayerTextureCache = CacheManager::getCachedItem< std::map >(GameConstants::playerTextureCacheLookupKey); - Vec3f playerColor = crcPlayerTextureCache[lineInfo->PlayerIndex]->getPixmap()->getPixel3f(0, 0); - fontColor.x = playerColor.x; - fontColor.y = playerColor.y; - fontColor.z = playerColor.z; - - GameNetworkInterface *gameNetInterface = NetworkManager::getInstance().getGameNetworkInterface(); - if(gameNetInterface != NULL && gameNetInterface->getGameSettings() != NULL) { - const GameSettings *gameSettings = gameNetInterface->getGameSettings(); - string playerName = gameSettings->getNetworkPlayerNameByPlayerIndex(lineInfo->PlayerIndex); - if(playerName != lineInfo->originalPlayerName && lineInfo->originalPlayerName != "") { - playerName = lineInfo->originalPlayerName; - } - //printf("playerName [%s], line [%s]\n",playerName.c_str(),line.c_str()); - - //string headerLine = "*" + playerName + ":"; - //string headerLine = playerName + ": "; - string headerLine = playerName; - if(lineInfo->teamMode == true) { - headerLine += " (" + lang.getString("Team") + ")"; - } - headerLine += ": "; - - if(fontMetrics == NULL) { - throw megaglest_runtime_error("fontMetrics == NULL"); - } - - renderTextShadow( - headerLine, - font, - fontColor, - xPosition, lineIndex * lineHeight + yPosition); - - fontColor = defaultFontColor; - //xPosition += (8 * (playerName.length() + 2)); - // Proper font spacing after username portion of chat text rendering - xPosition += (metrics.toVirtualX(fontMetrics->getTextWidth(headerLine))); - } - } - else if(lineInfo->originalPlayerName != "") { - string playerName = lineInfo->originalPlayerName; - //string headerLine = playerName + ": "; - string headerLine = playerName; - if(lineInfo->teamMode == true) { - headerLine += " (" + lang.getString("Team") + ")"; - } - headerLine += ": "; - - if(fontMetrics == NULL) { - throw megaglest_runtime_error("fontMetrics == NULL"); + for (int techTreeResourceTypeIndex = 0; + techTreeResourceTypeIndex < + world->getTechTree()->getResourceTypeCount(); + ++techTreeResourceTypeIndex) { + const ResourceType *rt = + world->getTechTree()->getResourceType(techTreeResourceTypeIndex); + if (rt->getDisplayInHud() == false) { + continue; + } + + // if any unit produces the resource + bool showResource; + if (twoRessourceLines) + showResource = world->showResourceTypeForTeam( + rt, factionForResourceView->getTeam()); + else + showResource = + world->showResourceTypeForFaction(rt, factionForResourceView); + + if (showResource == true) { + renderResource(factionForResourceView, localFactionResourcesOnly, + twoRessourceLines, rt, rowsRendered, + resourceCountRendered); + } + } + // if(resourceCountRendered > 0) { + // rowsRendered++; + // } + } + + glPopAttrib(); + + assertGl(); +} + +int Renderer::renderResource(const Faction *factionForResourceView, + bool localFactionResourcesOnly, + bool twoResourceLines, const ResourceType *rt, + int startRow, int &resourceCountRendered) { + + const Metrics &metrics = Metrics::getInstance(); + const int MAX_RESOURCES_PER_ROW = 6; + + int resourceRowHeigth = 30; + int resourceYStart = metrics.getVirtualH() - 30; + if (twoResourceLines) { + // we need to save some space + resourceYStart = metrics.getVirtualH() - 22; + resourceRowHeigth = 16; + } + + // draw resource status + if (localFactionResourcesOnly == true) { + Vec4f resourceFontColor = Vec4f( + factionForResourceView->getTexture()->getPixmapConst()->getPixel3f(0, + 0)); + int resourceCol = 0; + int resourceRow = startRow; + + int x = resourceCol * 100 + 190; + int y = resourceYStart - (resourceRowHeigth * resourceRow); + int h = 16; + int w = 8; + glColor3f(resourceFontColor.x, resourceFontColor.y, resourceFontColor.z); + glBegin(GL_TRIANGLE_STRIP); + glVertex2i(x, y + h); + glVertex2i(x, y); + glVertex2i(x + w, y + h / 2); + glEnd(); + } + + const Resource *r = + factionForResourceView->getResource(rt, localFactionResourcesOnly); + string str = intToStr(r->getAmount()); + + glEnable(GL_TEXTURE_2D); + + const Vec4f fontColor = game->getGui()->getDisplay()->getColor(); + Vec4f resourceFontColor = fontColor; + + bool isNegativeConsumableDisplayCycle = false; + if (rt->getClass() == rcConsumable) { + // Show in yellow/orange/red font if negative + if (r->getBalance() * 5 + r->getAmount() < 0) { + if (time(NULL) % 2 == 0) { + + isNegativeConsumableDisplayCycle = true; + if (r->getBalance() * 1 + r->getAmount() < 0) { + glColor3f(RED.x, RED.y, RED.z); + resourceFontColor = RED; + } else if (r->getBalance() * 3 + r->getAmount() < 0) { + glColor3f(ORANGE.x, ORANGE.y, ORANGE.z); + resourceFontColor = ORANGE; + } else if (r->getBalance() * 5 + r->getAmount() < 0) { + glColor3f(YELLOW.x, YELLOW.y, YELLOW.z); + resourceFontColor = YELLOW; } + } + } + } + + if (isNegativeConsumableDisplayCycle == false) { + glColor3f(1.f, 1.f, 1.f); + } + + int resourceRow = + startRow + (resourceCountRendered > 0 + ? resourceCountRendered / MAX_RESOURCES_PER_ROW + : 0); + int resourceCol = resourceCountRendered % MAX_RESOURCES_PER_ROW; + + renderQuad(resourceCol * 100 + 200, + resourceYStart - (resourceRowHeigth * resourceRow), 16, 16, + rt->getImage()); + + if (rt->getClass() != rcStatic) { + str += "/" + intToStr(factionForResourceView->getStoreAmount( + rt, localFactionResourcesOnly)); + } + if (rt->getClass() == rcConsumable) { + str += "("; + if (r->getBalance() > 0) { + str += "+"; + } + str += intToStr(r->getBalance()) + ")"; + } - renderTextShadow( - headerLine, - font, - fontColor, - xPosition, lineIndex * lineHeight + yPosition); - - fontColor = defaultFontColor; - //xPosition += (8 * (playerName.length() + 2)); - // Proper font spacing after username portion of chat text rendering - xPosition += (metrics.toVirtualX(fontMetrics->getTextWidth(headerLine))); - } - else { - fontColor = defaultFontColor; - } - - if(stringToHightlight!="" && lineInfo->text.find(stringToHightlight)!=string::npos){ - fontColor=Vec4f(1.f, 0.5f, 0.5f, 0.0f); - } - renderTextShadow( - lineInfo->text, - font, - fontColor, - xPosition, (lineIndex * lineHeight) + yPosition); -} - -void Renderer::renderConsole(const Console *console, ConsoleMode mode , int overrideMaxConsoleLines){ - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - if(console == NULL) { - throw megaglest_runtime_error("console == NULL"); - } - - glPushAttrib(GL_ENABLE_BIT); - glEnable(GL_BLEND); - - if(mode==consoleFull) { - int x= console->getXPos()-5; - int y= console->getYPos()-5; - int h= console->getLineHeight()*console->getStoredLineCount(); - - if(h > 0) { - int w= 1000; - //background - glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT); - glEnable(GL_BLEND); - - glColor4f(0.0f, 0.0f, 0.0f, 0.8f) ; - - glBegin(GL_TRIANGLE_STRIP); - glVertex2i(x, y); - glVertex2i(x, y+h); - glVertex2i(x+w, y); - glVertex2i(x+w, y+h); - glEnd(); - glPopAttrib(); - } - for(int i = 0; i < console->getStoredLineCount(); ++i) { - const ConsoleLineInfo &lineInfo = console->getStoredLineItem(i); - if(renderText3DEnabled == true) { - renderConsoleLine3D(i, console->getXPos(), console->getYPos(), - console->getLineHeight(), console->getFont3D(), - console->getStringToHighlight(), &lineInfo); - } - else { - renderConsoleLine(i, console->getXPos(), console->getYPos(), - console->getLineHeight(), console->getFont(), - console->getStringToHighlight(), &lineInfo); - } - } - } - else if(mode==consoleStoredOnly) { - int allowedMaxLines = (overrideMaxConsoleLines >= 0 ? overrideMaxConsoleLines : maxConsoleLines); - for(int i = 0; i < console->getStoredLineCount() && i < allowedMaxLines; ++i) { - const ConsoleLineInfo &lineInfo = console->getStoredLineItem(i); - if(renderText3DEnabled == true) { - renderConsoleLine3D(i, console->getXPos(), console->getYPos(), - console->getLineHeight(), console->getFont3D(), console->getStringToHighlight(), &lineInfo); - } - else { - renderConsoleLine(i, console->getXPos(), console->getYPos(), - console->getLineHeight(), console->getFont(), console->getStringToHighlight(), &lineInfo); - } - } - } - else if(mode==consoleStoredAndNormal) { - int allowedMaxLines = (overrideMaxConsoleLines >= 0 ? overrideMaxConsoleLines : maxConsoleLines); - float starttimestamp=-1; - int consoleIndex=0; - for(int i = 0; i < console->getLineCount() && i < allowedMaxLines; ++i) { - const ConsoleLineInfo &lineInfo = console->getLineItem(i); - if(starttimestamp>lineInfo.timeStamp || starttimestamp==-1) starttimestamp=lineInfo.timeStamp; - if(renderText3DEnabled == true) { - renderConsoleLine3D(i, console->getXPos(), console->getYPos(), - console->getLineHeight(), console->getFont3D(), console->getStringToHighlight(), &lineInfo); - } - else { - renderConsoleLine(i, console->getXPos(), console->getYPos(), - console->getLineHeight(), console->getFont(), console->getStringToHighlight(), &lineInfo); - } - consoleIndex++; - } - for(int i = 0; i < console->getStoredLineCount() && consoleIndex < allowedMaxLines; ++i) { - const ConsoleLineInfo &lineInfo = console->getStoredLineItem(i); - if( lineInfo.timeStampgetXPos(), console->getYPos(), - console->getLineHeight(), console->getFont3D(), console->getStringToHighlight(), &lineInfo); - } - else { - renderConsoleLine(consoleIndex, console->getXPos(), console->getYPos(), - console->getLineHeight(), console->getFont(), console->getStringToHighlight(), &lineInfo); - } - consoleIndex++; - } - } - } - else if(mode==consoleNormal) { - for(int i = 0; i < console->getLineCount(); ++i) { - const ConsoleLineInfo &lineInfo = console->getLineItem(i); - if(renderText3DEnabled == true) { - renderConsoleLine3D(i, console->getXPos(), console->getYPos(), - console->getLineHeight(), console->getFont3D(), console->getStringToHighlight(), &lineInfo); - } - else { - renderConsoleLine(i, console->getXPos(), console->getYPos(), - console->getLineHeight(), console->getFont(), console->getStringToHighlight(), &lineInfo); - } - } - } - glPopAttrib(); -} + glDisable(GL_TEXTURE_2D); -void Renderer::renderChatManager(const ChatManager *chatManager) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - Vec4f fontColor; - Lang &lang= Lang::getInstance(); - - if(chatManager->getEditEnabled()) { - Vec4f color=Vec4f(0.0f,0.0f,0.0f,0.6f); - string text=""; - - if(chatManager->isInCustomInputMode() == true) { - text += lang.getString("CellHint"); - } - else if(chatManager->getInMenu()) { - text += lang.getString("Chat"); - } - else if(chatManager->getTeamMode()) { - text += lang.getString("Team"); - } - else { - text += lang.getString("All"); - } - text += ": " + chatManager->getText() + "_"; - - if(game != NULL) { - fontColor = game->getGui()->getDisplay()->getColor(); - } - else { - // white shadowed is default ( in the menu for example ) - fontColor=Vec4f(1.f, 1.f, 1.f, 0.0f); - } - - // render Background - int x=chatManager->getXPos(); - int y=chatManager->getYPos()-6; - int h=22; - int w=830; - - glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT); - glEnable(GL_BLEND); - - glColor4f(color.x, color.y, color.z, color.w) ; - - glBegin(GL_TRIANGLE_STRIP); - glVertex2i(x, y); - glVertex2i(x, y+h); - glVertex2i(x+w, y); - glVertex2i(x+w, y+h); - glEnd(); - glPopAttrib(); - - if(renderText3DEnabled == true) { - renderTextShadow3D( - text, - chatManager->getFont3D(), - fontColor, - chatManager->getXPos(), chatManager->getYPos()); - } - else { - renderTextShadow( - text, - chatManager->getFont(), - fontColor, - chatManager->getXPos(), chatManager->getYPos()); - } - } - else - { - if (chatManager->getInMenu()) { - string text = "\t\t\t\t\t>> "+lang.getString("PressEnterToChat")+" <<"; - fontColor = Vec4f(0.5f, 0.5f, 0.5f, 0.5f); - - if(renderText3DEnabled == true) { - renderTextShadow3D(text, chatManager->getFont3D(), fontColor, - chatManager->getXPos(), chatManager->getYPos()); - } - else { - renderTextShadow(text, chatManager->getFont(), fontColor, - chatManager->getXPos(), chatManager->getYPos()); - } - } - } + if (renderText3DEnabled == true) { + renderTextShadow3D(str, CoreData::getInstance().getDisplayFontSmall3D(), + resourceFontColor, resourceCol * 100 + 220, + resourceYStart - (resourceRowHeigth * resourceRow), + false); + } else { + renderTextShadow(str, CoreData::getInstance().getDisplayFontSmall(), + resourceFontColor, resourceCol * 100 + 220, + resourceYStart - (resourceRowHeigth * resourceRow), false); + } + ++resourceCountRendered; + + return resourceRow; } +void Renderer::renderSelectionQuad() { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } -void Renderer::renderPerformanceStats() { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - const Metrics &metrics = Metrics::getInstance(); - const Vec4f fontColor = game->getGui()->getDisplay()->getColor(); - - char szBuf[200]=""; - snprintf(szBuf,200,"Frame: %d",game->getWorld()->getFrameCount() / 20); - string str = string(szBuf) + string("\n"); - - static time_t lastGamePerfCheck = time(NULL); - static string gamePerfStats = ""; - if(difftime((long int)time(NULL),lastGamePerfCheck) > 3) { - lastGamePerfCheck = time(NULL); - gamePerfStats = game->getGamePerformanceCounts(true); - } - - if(gamePerfStats != "") { - str += gamePerfStats + "\n"; - } - - if(renderText3DEnabled == true) { - renderTextShadow3D( - str, CoreData::getInstance().getDisplayFontSmall3D(), - fontColor, - 10, metrics.getVirtualH()-180, false); - } - else { - renderTextShadow( - str, CoreData::getInstance().getDisplayFontSmall(), - fontColor, - 10, metrics.getVirtualH()-180, false); - } -} + Config &config = Config::getInstance(); + if (config.getBool("RecordMode", "false") == true) { + return; + } -void Renderer::renderClock() { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - Config &config= Config::getInstance(); - if(config.getBool("InGameClock","true") == false && - config.getBool("InGameLocalClock","true") == false && - config.getBool("InGameFrameCounter","false") == false) { - return; - } - - string str = ""; - const Metrics &metrics = Metrics::getInstance(); - const World *world = game->getWorld(); - const Vec4f fontColor = game->getGui()->getDisplay()->getColor(); - - if(config.getBool("InGameClock","true") == true) { - Lang &lang= Lang::getInstance(); - char szBuf[501]=""; - - //int hours = world->getTimeFlow()->getTime(); - //int minutes = (world->getTimeFlow()->getTime() - hours) * 100 * 0.6; // scale 100 to 60 - //snprintf(szBuf,200,"%s %.2d:%.2d",lang.getString("GameTime","",true).c_str(),hours,minutes); - // string header2 = lang.getString("GameDurationTime","",true) + ": " + getTimeString(stats.getFramesToCalculatePlaytime()); - snprintf(szBuf,500,"%s %s",lang.getString("GameDurationTime","",true).c_str(),getTimeDuationString(world->getFrameCount(),GameConstants::updateFps).c_str()); - if(str != "") { - str += " "; - } - str += szBuf; - } - - if(config.getBool("InGameLocalClock","true") == true) { - //time_t nowTime = time(NULL); - //struct tm *loctime = localtime(&nowTime); - struct tm loctime = threadsafe_localtime(systemtime_now()); - char szBuf2[100]=""; - strftime(szBuf2,100,"%H:%M",&loctime); - - Lang &lang= Lang::getInstance(); - char szBuf[200]=""; - snprintf(szBuf,200,"%s %s",lang.getString("LocalTime","",true).c_str(),szBuf2); - if(str != "") { - str += " "; - } - str += szBuf; - } - - if(config.getBool("InGameFrameCounter","false") == true) { - char szBuf[200]=""; - snprintf(szBuf,200,"Frame: %d",game->getWorld()->getFrameCount() / 20); - if(str != "") { - str += " "; - } - str += szBuf; - } - - //string str = szBuf; - - if(renderText3DEnabled == true) { - renderTextShadow3D( - str, CoreData::getInstance().getDisplayFontSmall3D(), - fontColor, - 10, metrics.getVirtualH()-160, false); - } - else { - renderTextShadow( - str, CoreData::getInstance().getDisplayFontSmall(), - fontColor, - 10, metrics.getVirtualH()-160, false); - } -} + const Gui *gui = game->getGui(); + const SelectionQuad *sq = gui->getSelectionQuad(); -void Renderer::renderResourceStatus() { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - const World *world = game->getWorld(); - Config &config= Config::getInstance(); - - if(world->getThisFactionIndex() < 0 || - world->getThisFactionIndex() >= world->getFactionCount()) { - return; - } - - const Faction *thisFaction = world->getFaction(world->getThisFactionIndex()); - if(thisFaction->getPersonalityType() == fpt_Observer){ - // render resources of selected units faction - const Gui *gui = game->getGui(); - if(gui != NULL) { - const Selection *selection = gui->getSelection(); - if(selection != NULL && selection->getCount() > 0 && selection->getFrontUnit() != NULL) { - const Unit *selectedUnit = selection->getFrontUnit(); - thisFaction=selectedUnit->getFaction(); - } - } - } - assertGl(); - glPushAttrib(GL_ENABLE_BIT); - - int rowsRendered = 0; - int resourceCountRendered = 0; - bool twoRessourceLines=false; - - bool sharedTeamUnits = game != NULL && game->getGui() != NULL - && game->isFlagType1BitEnabled(ft1_allow_shared_team_units) - == true; - bool sharedTeamResources = game != NULL && game->getGui() != NULL - && game->isFlagType1BitEnabled( - ft1_allow_shared_team_resources) == true; - - bool renderSharedTeamResources=false; - bool renderSharedTeamUnits=false; - bool renderLocalFactionResources=false; - - if(config.getBool("TwoLineTeamResourceRendering","false") == true) { - if( sharedTeamResources == true || sharedTeamUnits == true){ - twoRessourceLines=true; - } - if(sharedTeamResources == true){ - renderSharedTeamResources=true; - renderSharedTeamUnits=true; - } - else if(sharedTeamUnits == true){ - renderSharedTeamUnits=true; - renderLocalFactionResources=true; - } - else{ - renderLocalFactionResources=true; - } - } - else { - if(sharedTeamResources == true) - renderSharedTeamResources=true; - else if(sharedTeamUnits == true) - renderSharedTeamUnits=true; - else - renderLocalFactionResources=true; - } - - if(renderSharedTeamResources == true) { - resourceCountRendered = 0; - for(int techTreeResourceTypeIndex = 0; - techTreeResourceTypeIndex < world->getTechTree()->getResourceTypeCount(); - ++techTreeResourceTypeIndex) { - - const ResourceType *rt = world->getTechTree()->getResourceType(techTreeResourceTypeIndex); - - if ( rt->getDisplayInHud() == false ) { - continue; - } - - bool showResource = world->showResourceTypeForTeam(rt, thisFaction->getTeam()); - if(showResource == true) { - rowsRendered = renderResource(thisFaction, - false, twoRessourceLines, rt, 0, - resourceCountRendered); - } - } - if(resourceCountRendered > 0) { - rowsRendered++; - } - } - - if(renderLocalFactionResources == true){ - resourceCountRendered = 0; - - const Faction *factionForResourceView = thisFaction; - bool localFactionResourcesOnly = true; - - for(int techTreeResourceTypeIndex = 0; - techTreeResourceTypeIndex < world->getTechTree()->getResourceTypeCount(); - ++techTreeResourceTypeIndex) { - const ResourceType *rt = world->getTechTree()->getResourceType(techTreeResourceTypeIndex); - if ( rt->getDisplayInHud() == false ) { - continue; - } - - //if any unit produces the resource - bool showResource; - if (twoRessourceLines) - showResource = world->showResourceTypeForTeam(rt, - factionForResourceView->getTeam()); - else - showResource = world->showResourceTypeForFaction(rt, - factionForResourceView); - if(showResource == true) { - renderResource(factionForResourceView, localFactionResourcesOnly, - twoRessourceLines, rt, rowsRendered, resourceCountRendered); - } - } - if(resourceCountRendered > 0) { - rowsRendered++; - } - } - - if(renderSharedTeamUnits == true){ - resourceCountRendered = 0; - - const Faction *factionForResourceView = thisFaction; - bool localFactionResourcesOnly = true; - - const Gui *gui = game->getGui(); - if(gui != NULL) { - const Selection *selection = gui->getSelection(); - if(selection != NULL && selection->getCount() > 0 && selection->getFrontUnit() != NULL) { - const Unit *selectedUnit = selection->getFrontUnit(); - if(selectedUnit != NULL && selectedUnit->getFaction()->isAlly(thisFaction) == true) { - factionForResourceView = selectedUnit->getFaction(); - } - } - } - - for(int techTreeResourceTypeIndex = 0; - techTreeResourceTypeIndex < world->getTechTree()->getResourceTypeCount(); - ++techTreeResourceTypeIndex) { - const ResourceType *rt = world->getTechTree()->getResourceType(techTreeResourceTypeIndex); - if ( rt->getDisplayInHud() == false ) { - continue; - } - - //if any unit produces the resource - bool showResource; - if (twoRessourceLines) - showResource = world->showResourceTypeForTeam(rt, - factionForResourceView->getTeam()); - else - showResource = world->showResourceTypeForFaction(rt, - factionForResourceView); - - if(showResource == true) { - renderResource(factionForResourceView, localFactionResourcesOnly, - twoRessourceLines, rt, rowsRendered, resourceCountRendered); - } - } - //if(resourceCountRendered > 0) { - // rowsRendered++; - //} - } - - glPopAttrib(); + Vec2i down = sq->getPosDown(); + Vec2i up = sq->getPosUp(); - assertGl(); -} + if (gui->isSelecting()) { + glPushAttrib(GL_CURRENT_BIT | GL_LINE_BIT); -int Renderer::renderResource(const Faction *factionForResourceView,bool localFactionResourcesOnly, - bool twoResourceLines, const ResourceType *rt, int startRow, int &resourceCountRendered) { - - const Metrics &metrics = Metrics::getInstance(); - const int MAX_RESOURCES_PER_ROW = 6; - - int resourceRowHeigth=30; - int resourceYStart=metrics.getVirtualH()-30; - if(twoResourceLines){ - // we need to save some space - resourceYStart=metrics.getVirtualH()-22; - resourceRowHeigth=16; - } - - //draw resource status - if(localFactionResourcesOnly == true) { - Vec4f resourceFontColor = Vec4f(factionForResourceView->getTexture()->getPixmapConst()->getPixel3f(0,0)); - int resourceCol = 0; - int resourceRow = startRow; - - int x=resourceCol * 100 + 190; - int y=resourceYStart - (resourceRowHeigth * resourceRow); - int h=16; - int w=8; - glColor3f(resourceFontColor.x,resourceFontColor.y,resourceFontColor.z); - glBegin(GL_TRIANGLE_STRIP); - glVertex2i(x, y+h); - glVertex2i(x, y); - glVertex2i(x+w, y+h/2); - glEnd(); - } - - const Resource *r = factionForResourceView->getResource(rt,localFactionResourcesOnly); - string str = intToStr(r->getAmount()); - - glEnable(GL_TEXTURE_2D); - - const Vec4f fontColor = game->getGui()->getDisplay()->getColor(); - Vec4f resourceFontColor = fontColor; - - bool isNegativeConsumableDisplayCycle = false; - if(rt->getClass() == rcConsumable) { - // Show in yellow/orange/red font if negative - if(r->getBalance() * 5 + r->getAmount() < 0) { - if(time(NULL) % 2 == 0) { - - isNegativeConsumableDisplayCycle = true; - if(r->getBalance() * 1 + r->getAmount() < 0) { - glColor3f(RED.x,RED.y,RED.z); - resourceFontColor = RED; - } - else if(r->getBalance() * 3 + r->getAmount() < 0) { - glColor3f(ORANGE.x,ORANGE.y,ORANGE.z); - resourceFontColor = ORANGE; - } - else if(r->getBalance() * 5 + r->getAmount() < 0) { - glColor3f(YELLOW.x,YELLOW.y,YELLOW.z); - resourceFontColor = YELLOW; - } - } - } - } - - if(isNegativeConsumableDisplayCycle == false) { - glColor3f(1.f, 1.f, 1.f); - } - - int resourceRow = startRow + (resourceCountRendered > 0 ? resourceCountRendered / MAX_RESOURCES_PER_ROW : 0); - int resourceCol = resourceCountRendered % MAX_RESOURCES_PER_ROW; - - renderQuad(resourceCol * 100 + 200, resourceYStart - (resourceRowHeigth * resourceRow), 16, 16, rt->getImage()); - - if(rt->getClass() != rcStatic) { - str+= "/" + intToStr(factionForResourceView->getStoreAmount(rt,localFactionResourcesOnly)); - } - if(rt->getClass() == rcConsumable) { - str+= "("; - if(r->getBalance() > 0) { - str+= "+"; - } - str+= intToStr(r->getBalance()) + ")"; - } - - glDisable(GL_TEXTURE_2D); - - if(renderText3DEnabled == true) { - renderTextShadow3D( - str, CoreData::getInstance().getDisplayFontSmall3D(), - resourceFontColor, - resourceCol * 100 + 220, resourceYStart - (resourceRowHeigth * resourceRow), false); - } - else { - renderTextShadow( - str, CoreData::getInstance().getDisplayFontSmall(), - resourceFontColor, - resourceCol * 100 + 220, resourceYStart - (resourceRowHeigth * resourceRow), false); - } - ++resourceCountRendered; - - return resourceRow; -} + Vec2i vertices[4]; + vertices[0] = Vec2i(down.x, down.y); + vertices[1] = Vec2i(up.x, down.y); + vertices[2] = Vec2i(up.x, up.y); + vertices[3] = Vec2i(down.x, up.y); -void Renderer::renderSelectionQuad() { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - Config &config= Config::getInstance(); - if(config.getBool("RecordMode","false") == true) { - return; - } - - const Gui *gui= game->getGui(); - const SelectionQuad *sq= gui->getSelectionQuad(); - - Vec2i down= sq->getPosDown(); - Vec2i up= sq->getPosUp(); - - if(gui->isSelecting()) { - glPushAttrib(GL_CURRENT_BIT | GL_LINE_BIT); - - Vec2i vertices[4]; - vertices[0] = Vec2i(down.x, down.y); - vertices[1] = Vec2i(up.x, down.y); - vertices[2] = Vec2i(up.x, up.y); - vertices[3] = Vec2i(down.x, up.y); - - glColor3f(0,1,0); - glEnableClientState(GL_VERTEX_ARRAY); - glVertexPointer(2, GL_INT, 0, &vertices[0]); - glDrawArrays(GL_LINE_LOOP, 0, 4); - glDisableClientState(GL_VERTEX_ARRAY); - -/* - glColor3f(0,1,0); - glBegin(GL_LINE_LOOP); - glVertex2i(down.x, down.y); - glVertex2i(up.x, down.y); - glVertex2i(up.x, up.y); - glVertex2i(down.x, up.y); - glEnd(); -*/ - glPopAttrib(); - } + glColor3f(0, 1, 0); + glEnableClientState(GL_VERTEX_ARRAY); + glVertexPointer(2, GL_INT, 0, &vertices[0]); + glDrawArrays(GL_LINE_LOOP, 0, 4); + glDisableClientState(GL_VERTEX_ARRAY); + + /* + glColor3f(0,1,0); + glBegin(GL_LINE_LOOP); + glVertex2i(down.x, down.y); + glVertex2i(up.x, down.y); + glVertex2i(up.x, up.y); + glVertex2i(down.x, up.y); + glEnd(); + */ + glPopAttrib(); + } } Vec2i computeCenteredPos(const string &text, Font2D *font, int x, int y) { - if(font == NULL) { - //abort(); - throw megaglest_runtime_error("font == NULL (1) text = " + text); - } - const Metrics &metrics= Metrics::getInstance(); - FontMetrics *fontMetrics= font->getMetrics(); + if (font == NULL) { + // abort(); + throw megaglest_runtime_error("font == NULL (1) text = " + text); + } + const Metrics &metrics = Metrics::getInstance(); + FontMetrics *fontMetrics = font->getMetrics(); - if(fontMetrics == NULL) { - throw megaglest_runtime_error("fontMetrics == NULL (1) text = " + text); - } + if (fontMetrics == NULL) { + throw megaglest_runtime_error("fontMetrics == NULL (1) text = " + text); + } - int virtualX = (fontMetrics->getTextWidth(text) > 0 ? static_cast(fontMetrics->getTextWidth(text)/2.f) : 5); - int virtualY = (fontMetrics->getHeight(text) > 0 ? static_cast(fontMetrics->getHeight(text)/2.f) : 5); + int virtualX = (fontMetrics->getTextWidth(text) > 0 + ? static_cast(fontMetrics->getTextWidth(text) / 2.f) + : 5); + int virtualY = (fontMetrics->getHeight(text) > 0 + ? static_cast(fontMetrics->getHeight(text) / 2.f) + : 5); - Vec2i textPos( - x-metrics.toVirtualX(virtualX), - y-metrics.toVirtualY(virtualY)); + Vec2i textPos(x - metrics.toVirtualX(virtualX), + y - metrics.toVirtualY(virtualY)); - //printf("text [%s] x = %d y = %d virtualX = %d virtualY = %d fontMetrics->getHeight() = %f\n",text.c_str(),x,y,virtualX,virtualY,fontMetrics->getHeight()); + // printf("text [%s] x = %d y = %d virtualX = %d virtualY = %d + // fontMetrics->getHeight() = + // %f\n",text.c_str(),x,y,virtualX,virtualY,fontMetrics->getHeight()); - return textPos; + return textPos; } Vec2i computeCenteredPos(const string &text, Font3D *font, int x, int y) { - if(font == NULL) { - throw megaglest_runtime_error("font == NULL (2) text = " + text); - } - const Metrics &metrics= Metrics::getInstance(); - FontMetrics *fontMetrics= font->getMetrics(); + if (font == NULL) { + throw megaglest_runtime_error("font == NULL (2) text = " + text); + } + const Metrics &metrics = Metrics::getInstance(); + FontMetrics *fontMetrics = font->getMetrics(); - if(fontMetrics == NULL) { - throw megaglest_runtime_error("fontMetrics == NULL (2) text = " + text); - } + if (fontMetrics == NULL) { + throw megaglest_runtime_error("fontMetrics == NULL (2) text = " + text); + } - int virtualX = (fontMetrics->getTextWidth(text) > 0 ? static_cast(fontMetrics->getTextWidth(text) / 2.f) : 5); - int virtualY = (fontMetrics->getHeight(text) > 0 ? static_cast(fontMetrics->getHeight(text) / 2.f) : 5); + int virtualX = (fontMetrics->getTextWidth(text) > 0 + ? static_cast(fontMetrics->getTextWidth(text) / 2.f) + : 5); + int virtualY = (fontMetrics->getHeight(text) > 0 + ? static_cast(fontMetrics->getHeight(text) / 2.f) + : 5); - Vec2i textPos( - x-metrics.toVirtualX(virtualX), - y-metrics.toVirtualY(virtualY)); + Vec2i textPos(x - metrics.toVirtualX(virtualX), + y - metrics.toVirtualY(virtualY)); - return textPos; + return textPos; } void Renderer::renderTextSurroundingBox(int x, int y, int w, int h, - int maxEditWidth, int maxEditRenderWidth) { - //glColor4fv(color.ptr()); - //glBegin(GL_QUADS); // Start drawing a quad primitive - - //printf("A w = %d maxEditWidth = %d maxEditRenderWidth = %d\n",w,maxEditWidth,maxEditRenderWidth); - if(maxEditWidth >= 0 || maxEditRenderWidth >= 0) { - //printf("B w = %d maxEditWidth = %d maxEditRenderWidth = %d\n",w,maxEditWidth,maxEditRenderWidth); - if(maxEditRenderWidth >= 0) { - w = maxEditRenderWidth; - } - else { - w = maxEditWidth; - } - } - //printf("HI!!!\n"); - glPointSize(20.0f); - - int margin = 4; - //glBegin(GL_POINTS); // Start drawing a point primitive - glBegin(GL_LINE_LOOP); // Start drawing a line primitive - - glVertex3f(x, y+h, 0.0f); // The bottom left corner - glVertex3f(x, y-margin, 0.0f); // The top left corner - glVertex3f(x+w, y-margin, 0.0f); // The top right corner - glVertex3f(x+w, y+h, 0.0f); // The bottom right corner - glEnd(); + int maxEditWidth, + int maxEditRenderWidth) { + // glColor4fv(color.ptr()); + // glBegin(GL_QUADS); // Start drawing a quad primitive + + // printf("A w = %d maxEditWidth = %d maxEditRenderWidth = + // %d\n",w,maxEditWidth,maxEditRenderWidth); + if (maxEditWidth >= 0 || maxEditRenderWidth >= 0) { + // printf("B w = %d maxEditWidth = %d maxEditRenderWidth = + // %d\n",w,maxEditWidth,maxEditRenderWidth); + if (maxEditRenderWidth >= 0) { + w = maxEditRenderWidth; + } else { + w = maxEditWidth; + } + } + // printf("HI!!!\n"); + glPointSize(20.0f); + + int margin = 4; + // glBegin(GL_POINTS); // Start drawing a point primitive + glBegin(GL_LINE_LOOP); // Start drawing a line primitive + + glVertex3f(x, y + h, 0.0f); // The bottom left corner + glVertex3f(x, y - margin, 0.0f); // The top left corner + glVertex3f(x + w, y - margin, 0.0f); // The top right corner + glVertex3f(x + w, y + h, 0.0f); // The bottom right corner + glEnd(); } // // renderTextBoundingBox3D // -void Renderer::renderTextBoundingBox3D(const string &text, Font3D *font, float alpha, int x, int y, int w, int h, bool centeredW, bool centeredH, - bool editModeEnabled, int maxEditWidth, int maxEditRenderWidth) { - renderTextBoundingBox3D(text, font, Vec4f(1.f, 1.f, 1.f, alpha), x, y, w, h, centeredW, centeredH, editModeEnabled, maxEditRenderWidth, maxEditRenderWidth); -} +void Renderer::renderTextBoundingBox3D(const string &text, Font3D *font, + float alpha, int x, int y, int w, int h, + bool centeredW, bool centeredH, + bool editModeEnabled, int maxEditWidth, + int maxEditRenderWidth) { + renderTextBoundingBox3D(text, font, Vec4f(1.f, 1.f, 1.f, alpha), x, y, w, h, + centeredW, centeredH, editModeEnabled, + maxEditRenderWidth, maxEditRenderWidth); +} + +void Renderer::renderTextBoundingBox3D(const string &text, Font3D *font, + const Vec3f &color, int x, int y, int w, + int h, bool centeredW, bool centeredH, + bool editModeEnabled, int maxEditWidth, + int maxEditRenderWidth) { + renderTextBoundingBox3D(text, font, Vec4f(color.x, color.y, color.z, 1.f), x, + y, w, h, centeredW, centeredH, editModeEnabled, + maxEditRenderWidth, maxEditRenderWidth); +} + +void Renderer::renderTextBoundingBox3D(const string &text, Font3D *font, + const Vec4f &color, int x, int y, int w, + int h, bool centeredW, bool centeredH, + bool editModeEnabled, int maxEditWidth, + int maxEditRenderWidth) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT); + glEnable(GL_BLEND); + glColor4fv(color.ptr()); + + Vec2f pos = Vec2f(x, y); + // Vec2i pos= centered? computeCenteredPos(text, font, x, y): Vec2i(x, y); + + if (centeredW == true || centeredH == true) { + getCentered3DPos(text, font, pos, w, h, centeredW, centeredH); + } + + if (editModeEnabled) { + if (maxEditWidth >= 0 || maxEditRenderWidth >= 0) { + int useWidth = maxEditWidth; + string temp = ""; + for (int i = 0; i < useWidth; ++i) { + temp += DEFAULT_CHAR_FOR_WIDTH_CALC; + } + float lineWidth = (font->getTextHandler()->Advance(temp.c_str()) * + ::Shared::Graphics::Font::scaleFontValue); + useWidth = (int)lineWidth; + + maxEditWidth = useWidth; + } + + renderTextSurroundingBox(pos.x, pos.y, w, h, maxEditWidth, + maxEditRenderWidth); + } + glColor4fv(color.ptr()); + TextRendererSafeWrapper safeTextRender(textRenderer3D, font); + textRenderer3D->render(text, pos.x, pos.y); + safeTextRender.end(); -void Renderer::renderTextBoundingBox3D(const string &text, Font3D *font, const Vec3f &color, int x, int y, int w, int h, bool centeredW, bool centeredH, - bool editModeEnabled, int maxEditWidth, int maxEditRenderWidth) { - renderTextBoundingBox3D(text, font, Vec4f(color.x, color.y, color.z, 1.f), x, y, w, h, centeredW, centeredH, editModeEnabled, maxEditRenderWidth, - maxEditRenderWidth); + glDisable(GL_BLEND); + glPopAttrib(); } -void Renderer::renderTextBoundingBox3D(const string &text, Font3D *font, const Vec4f &color, int x, int y, int w, int h, bool centeredW, bool centeredH, - bool editModeEnabled, int maxEditWidth, int maxEditRenderWidth) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } +// +// renderText3D +// - glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT); - glEnable(GL_BLEND); - glColor4fv(color.ptr()); +void Renderer::renderText3D(const string &text, Font3D *font, float alpha, + int x, int y, bool centered) { + renderText3D(text, font, Vec4f(1.f, 1.f, 1.f, alpha), x, y, centered); +} - Vec2f pos= Vec2f(x, y); - //Vec2i pos= centered? computeCenteredPos(text, font, x, y): Vec2i(x, y); +void Renderer::renderText3D(const string &text, Font3D *font, + const Vec3f &color, int x, int y, bool centered) { + renderText3D(text, font, Vec4f(color.x, color.y, color.z, 1.f), x, y, + centered); +} - if(centeredW == true || centeredH == true) { - getCentered3DPos(text, font, pos, w, h,centeredW,centeredH); - } +void Renderer::renderText3D(const string &text, Font3D *font, + const Vec4f &color, int x, int y, bool centered) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - if(editModeEnabled) { - if(maxEditWidth >= 0 || maxEditRenderWidth >= 0) { - int useWidth = maxEditWidth; - string temp = ""; - for(int i = 0; i < useWidth; ++i) { - temp += DEFAULT_CHAR_FOR_WIDTH_CALC; - } - float lineWidth = (font->getTextHandler()->Advance(temp.c_str()) * ::Shared::Graphics::Font::scaleFontValue); - useWidth = (int)lineWidth; + glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT); + glEnable(GL_BLEND); + glColor4fv(color.ptr()); - maxEditWidth = useWidth; - } + Vec2i pos = Vec2i(x, y); + // Vec2i pos= centered? computeCenteredPos(text, font, x, y): Vec2i(x, y); - renderTextSurroundingBox(pos.x, pos.y, w, h,maxEditWidth,maxEditRenderWidth); - } - glColor4fv(color.ptr()); - TextRendererSafeWrapper safeTextRender(textRenderer3D,font); - textRenderer3D->render(text, pos.x, pos.y); - safeTextRender.end(); + TextRendererSafeWrapper safeTextRender(textRenderer3D, font); + textRenderer3D->render(text, pos.x, pos.y, centered); + safeTextRender.end(); - glDisable(GL_BLEND); - glPopAttrib(); + glDisable(GL_BLEND); + glPopAttrib(); } - // -// renderText3D +// renderText // - -void Renderer::renderText3D(const string &text, Font3D *font, float alpha, int x, int y, bool centered) { - renderText3D(text,font,Vec4f(1.f, 1.f, 1.f, alpha),x,y,centered); +void Renderer::renderText(const string &text, Font2D *font, float alpha, int x, + int y, bool centered) { + renderText(text, font, Vec4f(1.f, 1.f, 1.f, alpha), x, y, centered); } -void Renderer::renderText3D(const string &text, Font3D *font, const Vec3f &color, int x, int y, bool centered) { - renderText3D(text,font,Vec4f(color.x, color.y, color.z, 1.f),x,y,centered); +void Renderer::renderText(const string &text, Font2D *font, const Vec3f &color, + int x, int y, bool centered) { + renderText(text, font, Vec4f(color.x, color.y, color.z, 1.f), x, y, centered); } -void Renderer::renderText3D(const string &text, Font3D *font, const Vec4f &color, int x, int y, bool centered) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } +void Renderer::renderText(const string &text, Font2D *font, const Vec4f &color, + int x, int y, bool centered) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT); - glEnable(GL_BLEND); - glColor4fv(color.ptr()); + glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT); + glEnable(GL_BLEND); + glColor4fv(color.ptr()); - Vec2i pos= Vec2i(x, y); - //Vec2i pos= centered? computeCenteredPos(text, font, x, y): Vec2i(x, y); + Vec2i pos = centered ? computeCenteredPos(text, font, x, y) : Vec2i(x, y); - TextRendererSafeWrapper safeTextRender(textRenderer3D,font); - textRenderer3D->render(text, pos.x, pos.y, centered); - safeTextRender.end(); + TextRendererSafeWrapper safeTextRender(textRenderer, font); + textRenderer->render(text, pos.x, pos.y); + safeTextRender.end(); - glDisable(GL_BLEND); - glPopAttrib(); + glPopAttrib(); } -// -// renderText -// -void Renderer::renderText(const string &text, Font2D *font, float alpha, int x, int y, bool centered) { - renderText(text,font,Vec4f(1.f, 1.f, 1.f, alpha),x,y,centered); -} - -void Renderer::renderText(const string &text, Font2D *font, const Vec3f &color, int x, int y, bool centered){ - renderText(text,font,Vec4f(color.x, color.y, color.z, 1.f),x,y,centered); -} - -void Renderer::renderText(const string &text, Font2D *font, const Vec4f &color, int x, int y, bool centered){ - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT); - glEnable(GL_BLEND); - glColor4fv(color.ptr()); - - Vec2i pos= centered? computeCenteredPos(text, font, x, y): Vec2i(x, y); - - TextRendererSafeWrapper safeTextRender(textRenderer,font); - textRenderer->render(text, pos.x, pos.y); - safeTextRender.end(); - - glPopAttrib(); -} - -Vec2f Renderer::getCentered3DPos(const string &text, Font3D *font, Vec2f &pos, int w, int h,bool centeredW, bool centeredH) { - if(centeredW == true) { - if(font == NULL) { - //abort(); - throw megaglest_runtime_error("font == NULL (5) text = " + text); - } - else if(font->getTextHandler() == NULL) { - char szBuf[8096] = ""; - snprintf(szBuf, 8096, "font->getTextHandler() == NULL(5) text = [%s] FontPtr = [%p]\n", text.c_str(),font); - throw megaglest_runtime_error(szBuf); - } - - float lineWidth = (font->getTextHandler()->Advance(text.c_str()) * ::Shared::Graphics::Font::scaleFontValue); - if(lineWidth < w) { - pos.x += ((w / 2.f) - (lineWidth / 2.f)); - } - } - - if(centeredH) { - if(font == NULL) { - throw megaglest_runtime_error("font == NULL (6) text = " + text); - } - else if(font->getTextHandler() == NULL) { - throw megaglest_runtime_error("font->getTextHandler() == NULL (6) text = " + text); - } - - //const Metrics &metrics= Metrics::getInstance(); - //float lineHeight = (font->getTextHandler()->LineHeight(text.c_str()) * Font::scaleFontValue); - float lineHeight = (font->getTextHandler()->LineHeight(text.c_str()) * ::Shared::Graphics::Font::scaleFontValue); - //lineHeight=metrics.toVirtualY(lineHeight); - //lineHeight= lineHeight / (2.f + 0.2f * FontMetrics::DEFAULT_Y_OFFSET_FACTOR); - //pos.y += (h / 2.f) - (lineHeight / 2.f); - //pos.y += (h / 2.f) - (lineHeight); - //pos.y += (lineHeight / 2.f); // y starts at the middle of the render position, so only move up 1/2 the font height - - if(lineHeight < h) { - //printf("line %d, lineHeight [%f] h [%d] text [%s]\n",__LINE__,lineHeight,h,text.c_str()); - - //if(Font::forceFTGLFonts == true) { - // First go to top of bounding box - pos.y += (h - lineHeight); - pos.y -= ((h - lineHeight) / ::Shared::Graphics::Font::scaleFontValueCenterHFactor); -// } -// else { -// pos.y += (float)(((float)h) / 2.0); -// float heightGap = (float)(((float)h - lineHeight) / 2.0); -// pos.y -= heightGap; -// -// //printf("h = %d lineHeight = %f heightGap = %f\n",h,lineHeight,heightGap); -// -// // Now calculate till we get text to middle -// //pos.y -= (realHeight / 2); -// //pos.y += (lineHeight / 2); -// } - } - else if(lineHeight > h) { - //printf("line %d, lineHeight [%f] h [%d] text [%s]\n",__LINE__,lineHeight,h,text.c_str()); +Vec2f Renderer::getCentered3DPos(const string &text, Font3D *font, Vec2f &pos, + int w, int h, bool centeredW, bool centeredH) { + if (centeredW == true) { + if (font == NULL) { + // abort(); + throw megaglest_runtime_error("font == NULL (5) text = " + text); + } else if (font->getTextHandler() == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "font->getTextHandler() == NULL(5) text = [%s] FontPtr = [%p]\n", + text.c_str(), font); + throw megaglest_runtime_error(szBuf); + } + + float lineWidth = (font->getTextHandler()->Advance(text.c_str()) * + ::Shared::Graphics::Font::scaleFontValue); + if (lineWidth < w) { + pos.x += ((w / 2.f) - (lineWidth / 2.f)); + } + } + + if (centeredH) { + if (font == NULL) { + throw megaglest_runtime_error("font == NULL (6) text = " + text); + } else if (font->getTextHandler() == NULL) { + throw megaglest_runtime_error( + "font->getTextHandler() == NULL (6) text = " + text); + } - pos.y += (std::ceil(lineHeight - h)); - } - } - return pos; + // const Metrics &metrics= Metrics::getInstance(); + // float lineHeight = (font->getTextHandler()->LineHeight(text.c_str()) * + // Font::scaleFontValue); + float lineHeight = (font->getTextHandler()->LineHeight(text.c_str()) * + ::Shared::Graphics::Font::scaleFontValue); + // lineHeight=metrics.toVirtualY(lineHeight); + // lineHeight= lineHeight / (2.f + 0.2f * + // FontMetrics::DEFAULT_Y_OFFSET_FACTOR); pos.y += (h / 2.f) - (lineHeight + // / 2.f); pos.y += (h / 2.f) - (lineHeight); pos.y += (lineHeight / 2.f); + // // y starts at the middle of the render position, so only move up 1/2 the + // font height + + if (lineHeight < h) { + // printf("line %d, lineHeight [%f] h [%d] text + // [%s]\n",__LINE__,lineHeight,h,text.c_str()); + + // if(Font::forceFTGLFonts == true) { + // First go to top of bounding box + pos.y += (h - lineHeight); + pos.y -= ((h - lineHeight) / + ::Shared::Graphics::Font::scaleFontValueCenterHFactor); + // } + // else { + // pos.y += (float)(((float)h) / 2.0); + // float heightGap = (float)(((float)h - + // lineHeight) / 2.0); pos.y -= heightGap; + // + // //printf("h = %d lineHeight = %f + // heightGap = %f\n",h,lineHeight,heightGap); + // + // // Now calculate till we get text to middle + // //pos.y -= (realHeight / 2); + // //pos.y += (lineHeight / 2); + // } + } else if (lineHeight > h) { + // printf("line %d, lineHeight [%f] h [%d] text + // [%s]\n",__LINE__,lineHeight,h,text.c_str()); + + pos.y += (std::ceil(lineHeight - h)); + } + } + return pos; } -void Renderer::renderTextShadow3D(const string &text, Font3D *font,const Vec4f &color, int x, int y, bool centered) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } +void Renderer::renderTextShadow3D(const string &text, Font3D *font, + const Vec4f &color, int x, int y, + bool centered) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - if(font == NULL) { - throw megaglest_runtime_error("font == NULL (3) text = " + text); - } + if (font == NULL) { + throw megaglest_runtime_error("font == NULL (3) text = " + text); + } - glPushAttrib(GL_CURRENT_BIT); + glPushAttrib(GL_CURRENT_BIT); - Vec2i pos= centered? computeCenteredPos(text, font, x, y): Vec2i(x, y); + Vec2i pos = centered ? computeCenteredPos(text, font, x, y) : Vec2i(x, y); - TextRendererSafeWrapper safeTextRender(textRenderer3D,font); - if(color.w < 0.5) { - glColor3f(0.0f, 0.0f, 0.0f); + TextRendererSafeWrapper safeTextRender(textRenderer3D, font); + if (color.w < 0.5) { + glColor3f(0.0f, 0.0f, 0.0f); - textRenderer3D->render(text, pos.x-1.0f, pos.y-1.0f); - } - glColor3f(color.x,color.y,color.z); + textRenderer3D->render(text, pos.x - 1.0f, pos.y - 1.0f); + } + glColor3f(color.x, color.y, color.z); - textRenderer3D->render(text, pos.x, pos.y); - //textRenderer3D->end(); - safeTextRender.end(); + textRenderer3D->render(text, pos.x, pos.y); + // textRenderer3D->end(); + safeTextRender.end(); - glPopAttrib(); + glPopAttrib(); } -void Renderer::renderTextShadow(const string &text, Font2D *font,const Vec4f &color, int x, int y, bool centered){ - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } +void Renderer::renderTextShadow(const string &text, Font2D *font, + const Vec4f &color, int x, int y, + bool centered) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - if(font == NULL) { - throw megaglest_runtime_error("font == NULL (4) text = " + text); - } + if (font == NULL) { + throw megaglest_runtime_error("font == NULL (4) text = " + text); + } - glPushAttrib(GL_CURRENT_BIT); + glPushAttrib(GL_CURRENT_BIT); - Vec2i pos= centered? computeCenteredPos(text, font, x, y): Vec2i(x, y); + Vec2i pos = centered ? computeCenteredPos(text, font, x, y) : Vec2i(x, y); - TextRendererSafeWrapper safeTextRender(textRenderer,font); - if(color.w < 0.5) { - glColor3f(0.0f, 0.0f, 0.0f); + TextRendererSafeWrapper safeTextRender(textRenderer, font); + if (color.w < 0.5) { + glColor3f(0.0f, 0.0f, 0.0f); - textRenderer->render(text, pos.x-1.0f, pos.y-1.0f); - } - glColor3f(color.x,color.y,color.z); + textRenderer->render(text, pos.x - 1.0f, pos.y - 1.0f); + } + glColor3f(color.x, color.y, color.z); - textRenderer->render(text, pos.x, pos.y); - //textRenderer->end(); - safeTextRender.end(); + textRenderer->render(text, pos.x, pos.y); + // textRenderer->end(); + safeTextRender.end(); - glPopAttrib(); + glPopAttrib(); } // ============= COMPONENTS ============================= void Renderer::renderLabel(GraphicLabel *label) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - if( label->getVisible()==false){ - return; - } - - if(label->getEditable() && label->getMaxEditRenderWidth()>0) - { - int x= label->getX(); - int y= label->getY(); - int h= label->getH(); - int w= label->getMaxEditRenderWidth(); - if(h>0){ - //background - glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT); - glEnable(GL_BLEND); - - glColor4f(0.2f, 0.2f, 0.2f, 0.6f*label->getFade()) ; - - glBegin(GL_TRIANGLE_STRIP); - glVertex2i(x, y); - glVertex2i(x, y+h); - glVertex2i(x+w, y); - glVertex2i(x+w, y+h); - glEnd(); - glPopAttrib(); - } - } - - if(label->getRenderBackground()) - { - int x= label->getX(); - int y= label->getY(); - int h= label->getH(); - int w= label->getW(); - if(label->getMaxEditRenderWidth()>0){ - w= label->getMaxEditRenderWidth(); - } - Vec4f color=label->getBackgroundColor(); - if(h>0){ - //background - glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT); - glEnable(GL_BLEND); - - glColor4f(color.x, color.y, color.z, color.w*label->getFade()) ; - - glBegin(GL_TRIANGLE_STRIP); - glVertex2i(x, y); - glVertex2i(x, y+h); - glVertex2i(x+w, y); - glVertex2i(x+w, y+h); - glEnd(); - glPopAttrib(); - } - } - - if(label->getTexture()!=NULL ) - { - int x= label->getX(); - int y= label->getY(); - int h= label->getH(); - int w= label->getW(); - if(h>0){ - //background - glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT); - glEnable(GL_BLEND); - glEnable(GL_TEXTURE_2D); - glBindTexture(GL_TEXTURE_2D, static_cast( label->getTexture())->getHandle()); - glColor4f(1.0f, 1.0f, 1.0f, 1.0f*label->getFade()) ; - glBegin(GL_TRIANGLE_STRIP); - glTexCoord2f(0.f, 0.f); - glVertex2f(x, y); - - glTexCoord2f(0.f, 1.f); - glVertex2f(x, y+h); - - glTexCoord2f(1.f, 0.f); - glVertex2f(x+w, y); - - glTexCoord2f(1.f, 1.f); - glVertex2f(x+w, y+h); - glEnd(); - glDisable(GL_TEXTURE_2D); - glPopAttrib(); - } - } - Vec3f labelColor=label->getTextColor(); - Vec4f colorWithAlpha = Vec4f(labelColor.x,labelColor.y,labelColor.z,GraphicComponent::getFade()); - renderLabel(label,&colorWithAlpha); -} - -void Renderer::renderLabel(GraphicLabel *label,const Vec3f *color) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - if(color != NULL) { - Vec4f colorWithAlpha = Vec4f(*color); - colorWithAlpha.w = GraphicComponent::getFade(); - renderLabel(label,&colorWithAlpha); - } - else { - Vec4f *colorWithAlpha = NULL; - renderLabel(label,colorWithAlpha); - } -} - -void Renderer::renderLabel(GraphicLabel *label,const Vec4f *color) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - if(label->getVisible() == false) { - return; - } - try { - glPushAttrib(GL_ENABLE_BIT); - glEnable(GL_BLEND); - - vector lines; - string renderTextString = (label->getTextNativeTranslation() != "" ? label->getTextNativeTranslation() : label->getText()); - if(label->getWordWrap() == true) { - Tokenize(renderTextString,lines,"\n"); - } - else { - lines.push_back(renderTextString); - } - - for(unsigned int i = 0; i < lines.size(); ++i) { - Vec2i textPos; - int x= label->getX(); - int y= label->getY() - (i * label->getH()); - int h= label->getH(); - int w= label->getW(); - //if(label->getInstanceName() == "modDescrLabel") printf("~~~ lines.size() [%u] i = %d lines[i] [%s] y = %d\n",lines.size(),i,lines[i].c_str(),y); - - if(label->getCentered()) { - textPos= Vec2i(x+w/2, y+h/2); - } - else { - textPos= Vec2i(x, y+h/4); - } - - string renderTextStr = lines[i]; - if(label->getIsPassword() == true) { - if(renderTextStr != "") { - renderTextStr = "*****"; - } - } - - if(color != NULL) { - if(renderText3DEnabled == true) { - //renderText3D(lines[i], label->getFont3D(), (*color), textPos.x, textPos.y, label->getCentered()); - //printf("Text Render3D [%s] font3d [%p]\n",lines[i].c_str(),label->getFont3D()); - //printf("Label render C\n"); - - renderTextBoundingBox3D(renderTextStr, label->getFont3D(), (*color), - x, y, w, h, label->getCenteredW(),label->getCenteredH(), - label->getEditModeEnabled(),label->getMaxEditWidth(), - label->getMaxEditRenderWidth()); - } - else { - //printf("Label render D\n"); - renderText(renderTextStr, label->getFont(), (*color), textPos.x, textPos.y, label->getCentered()); - } - } - else { - if(renderText3DEnabled == true) { - //renderText3D(lines[i], label->getFont3D(), GraphicComponent::getFade(), textPos.x, textPos.y, label->getCentered()); - //printf("Text Render3D [%s] font3d [%p]\n",lines[i].c_str(),label->getFont3D()); - //printf("Label render E\n"); - renderTextBoundingBox3D(renderTextStr, label->getFont3D(), - GraphicComponent::getFade(), x, y, w, h, - label->getCenteredW(),label->getCenteredH(), - label->getEditModeEnabled(),label->getMaxEditWidth(), - label->getMaxEditRenderWidth()); - } - else { - //printf("Label render F\n"); - renderText(renderTextStr, label->getFont(), GraphicComponent::getFade(), textPos.x, textPos.y, label->getCentered()); - } - } - } - glPopAttrib(); - } - catch(const exception &e) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d]\nError [%s] For Control [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what(),label->getInstanceName().c_str()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,szBuf); - - throw megaglest_runtime_error(szBuf); - } - -} - -void Renderer::renderButton(GraphicButton *button, const Vec4f *fontColorOverride, bool *lightedOverride) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - if(button->getVisible() == false) { - return; - } - - try { - - //char szBuf[8096]=""; - //snprintf(szBuf,8096,"In [%s::%s Line: %d]\n For Control container [%s] name [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,button->getContainerName().c_str(), button->getInstanceName().c_str()); - //printf(szBuf); - - int x= button->getX(); - int y= button->getY(); - int h= button->getH(); - int w= button->getW(); - - const Vec3f disabledTextColor= Vec3f(0.25f,0.25f,0.25f); - - glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT); - - //background - CoreData &coreData= CoreData::getInstance(); - Texture2D *backTexture = NULL; - - if(button->getUseCustomTexture() == true) { - backTexture = dynamic_cast(button->getCustomTexture()); - } - else { - backTexture = w > 3 * h / 2 ? coreData.getButtonBigTexture(): coreData.getButtonSmallTexture(); - } - - glEnable(GL_TEXTURE_2D); - glEnable(GL_BLEND); - - if(backTexture != NULL) { - glBindTexture(GL_TEXTURE_2D, static_cast(backTexture)->getHandle()); - } - else { - glBindTexture(GL_TEXTURE_2D, 0); - } - - //button - Vec4f fontColor(GraphicComponent::getCustomTextColor()); - - if(fontColorOverride != NULL) { - fontColor= *fontColorOverride; - } - else { - // white shadowed is default ( in the menu for example ) - fontColor.w = GraphicComponent::getFade(); - } - - //Vec4f color= Vec4f(1.f, 1.f, 1.f, GraphicComponent::getFade()); - Vec4f color= fontColor; - glColor4fv(color.ptr()); - - glBegin(GL_TRIANGLE_STRIP); - glTexCoord2f(0.f, 0.f); - glVertex2f(x, y); - - glTexCoord2f(0.f, 1.f); - glVertex2f(x, y+h); - - glTexCoord2f(1.f, 0.f); - glVertex2f(x+w, y); - - glTexCoord2f(1.f, 1.f); - glVertex2f(x+w, y+h); - - glEnd(); - - glDisable(GL_TEXTURE_2D); - - //lighting - float anim= GraphicComponent::getAnim(); - if(anim>0.5f) anim= 1.f-anim; - - bool renderLighted = (button->getLighted() && button->getEditable()); - if(lightedOverride != NULL) { - renderLighted = *lightedOverride; - } - if(renderLighted) { - const int lightSize= 0; - const Vec4f color1= Vec4f(color.x, color.y, color.z, 0.1f+anim*0.5f); - const Vec4f color2= Vec4f(color.x, color.y, color.z, 0.3f+anim); - - glBegin(GL_TRIANGLE_FAN); + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + if (label->getVisible() == false) { + return; + } + + if (label->getEditable() && label->getMaxEditRenderWidth() > 0) { + int x = label->getX(); + int y = label->getY(); + int h = label->getH(); + int w = label->getMaxEditRenderWidth(); + if (h > 0) { + // background + glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT); + glEnable(GL_BLEND); + + glColor4f(0.2f, 0.2f, 0.2f, 0.6f * label->getFade()); + + glBegin(GL_TRIANGLE_STRIP); + glVertex2i(x, y); + glVertex2i(x, y + h); + glVertex2i(x + w, y); + glVertex2i(x + w, y + h); + glEnd(); + glPopAttrib(); + } + } + + if (label->getRenderBackground()) { + int x = label->getX(); + int y = label->getY(); + int h = label->getH(); + int w = label->getW(); + if (label->getMaxEditRenderWidth() > 0) { + w = label->getMaxEditRenderWidth(); + } + Vec4f color = label->getBackgroundColor(); + if (h > 0) { + // background + glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT); + glEnable(GL_BLEND); + + glColor4f(color.x, color.y, color.z, color.w * label->getFade()); + + glBegin(GL_TRIANGLE_STRIP); + glVertex2i(x, y); + glVertex2i(x, y + h); + glVertex2i(x + w, y); + glVertex2i(x + w, y + h); + glEnd(); + glPopAttrib(); + } + } + + if (label->getTexture() != NULL) { + int x = label->getX(); + int y = label->getY(); + int h = label->getH(); + int w = label->getW(); + if (h > 0) { + // background + glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT); + glEnable(GL_BLEND); + glEnable(GL_TEXTURE_2D); + glBindTexture( + GL_TEXTURE_2D, + static_cast(label->getTexture())->getHandle()); + glColor4f(1.0f, 1.0f, 1.0f, 1.0f * label->getFade()); + glBegin(GL_TRIANGLE_STRIP); + glTexCoord2f(0.f, 0.f); + glVertex2f(x, y); + + glTexCoord2f(0.f, 1.f); + glVertex2f(x, y + h); + + glTexCoord2f(1.f, 0.f); + glVertex2f(x + w, y); + + glTexCoord2f(1.f, 1.f); + glVertex2f(x + w, y + h); + glEnd(); + glDisable(GL_TEXTURE_2D); + glPopAttrib(); + } + } + Vec3f labelColor = label->getTextColor(); + Vec4f colorWithAlpha = Vec4f(labelColor.x, labelColor.y, labelColor.z, + GraphicComponent::getFade()); + renderLabel(label, &colorWithAlpha); +} + +void Renderer::renderLabel(GraphicLabel *label, const Vec3f *color) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + if (color != NULL) { + Vec4f colorWithAlpha = Vec4f(*color); + colorWithAlpha.w = GraphicComponent::getFade(); + renderLabel(label, &colorWithAlpha); + } else { + Vec4f *colorWithAlpha = NULL; + renderLabel(label, colorWithAlpha); + } +} + +void Renderer::renderLabel(GraphicLabel *label, const Vec4f *color) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + if (label->getVisible() == false) { + return; + } + try { + glPushAttrib(GL_ENABLE_BIT); + glEnable(GL_BLEND); - glColor4fv(color2.ptr()); - glVertex2f(x+w/2, y+h/2); + vector lines; + string renderTextString = (label->getTextNativeTranslation() != "" + ? label->getTextNativeTranslation() + : label->getText()); + if (label->getWordWrap() == true) { + Tokenize(renderTextString, lines, "\n"); + } else { + lines.push_back(renderTextString); + } - glColor4fv(color1.ptr()); - glVertex2f(x-lightSize, y-lightSize); + for (unsigned int i = 0; i < lines.size(); ++i) { + Vec2i textPos; + int x = label->getX(); + int y = label->getY() - (i * label->getH()); + int h = label->getH(); + int w = label->getW(); + // if(label->getInstanceName() == "modDescrLabel") printf("~~~ + // lines.size() [%u] i = %d lines[i] [%s] y = + // %d\n",lines.size(),i,lines[i].c_str(),y); + + if (label->getCentered()) { + textPos = Vec2i(x + w / 2, y + h / 2); + } else { + textPos = Vec2i(x, y + h / 4); + } + + string renderTextStr = lines[i]; + if (label->getIsPassword() == true) { + if (renderTextStr != "") { + renderTextStr = "*****"; + } + } + + if (color != NULL) { + if (renderText3DEnabled == true) { + // renderText3D(lines[i], label->getFont3D(), (*color), textPos.x, + // textPos.y, label->getCentered()); printf("Text Render3D [%s] font3d + // [%p]\n",lines[i].c_str(),label->getFont3D()); printf("Label render + // C\n"); + + renderTextBoundingBox3D( + renderTextStr, label->getFont3D(), (*color), x, y, w, h, + label->getCenteredW(), label->getCenteredH(), + label->getEditModeEnabled(), label->getMaxEditWidth(), + label->getMaxEditRenderWidth()); + } else { + // printf("Label render D\n"); + renderText(renderTextStr, label->getFont(), (*color), textPos.x, + textPos.y, label->getCentered()); + } + } else { + if (renderText3DEnabled == true) { + // renderText3D(lines[i], label->getFont3D(), + // GraphicComponent::getFade(), textPos.x, textPos.y, + // label->getCentered()); printf("Text Render3D [%s] font3d + // [%p]\n",lines[i].c_str(),label->getFont3D()); printf("Label render + // E\n"); + renderTextBoundingBox3D( + renderTextStr, label->getFont3D(), GraphicComponent::getFade(), x, + y, w, h, label->getCenteredW(), label->getCenteredH(), + label->getEditModeEnabled(), label->getMaxEditWidth(), + label->getMaxEditRenderWidth()); + } else { + // printf("Label render F\n"); + renderText(renderTextStr, label->getFont(), + GraphicComponent::getFade(), textPos.x, textPos.y, + label->getCentered()); + } + } + } + glPopAttrib(); + } catch (const exception &e) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d]\nError [%s] For Control [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, e.what(), label->getInstanceName().c_str()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, szBuf); + + throw megaglest_runtime_error(szBuf); + } +} + +void Renderer::renderButton(GraphicButton *button, + const Vec4f *fontColorOverride, + bool *lightedOverride) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + if (button->getVisible() == false) { + return; + } + + try { + + // char szBuf[8096]=""; + // snprintf(szBuf,8096,"In [%s::%s Line: %d]\n For Control container [%s] + // name + // [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,button->getContainerName().c_str(), + // button->getInstanceName().c_str()); printf(szBuf); + + int x = button->getX(); + int y = button->getY(); + int h = button->getH(); + int w = button->getW(); + + const Vec3f disabledTextColor = Vec3f(0.25f, 0.25f, 0.25f); + + glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT); + + // background + CoreData &coreData = CoreData::getInstance(); + Texture2D *backTexture = NULL; + + if (button->getUseCustomTexture() == true) { + backTexture = dynamic_cast(button->getCustomTexture()); + } else { + backTexture = w > 3 * h / 2 ? coreData.getButtonBigTexture() + : coreData.getButtonSmallTexture(); + } - glColor4fv(color1.ptr()); - glVertex2f(x+w+lightSize, y-lightSize); - - glColor4fv(color1.ptr()); - glVertex2f(x+w+lightSize, y+h+lightSize); - - glColor4fv(color1.ptr()); - glVertex2f(x+w+lightSize, y+h+lightSize); - - glColor4fv(color1.ptr()); - glVertex2f(x-lightSize, y+h+lightSize); - - glColor4fv(color1.ptr()); - glVertex2f(x-lightSize, y-lightSize); - - glEnd(); - } - - //Vec2i textPos= Vec2i(x + w / 2, y + h / 2); - - if(button->getEditable()) { - if(renderText3DEnabled == true) { - //renderText3D(button->getText(), button->getFont3D(), color,x + (w / 2), y + (h / 2), true); - renderTextBoundingBox3D(button->getText(), button->getFont3D(), - color, x, y, w, h, true, true,false,-1,-1); - } - else { - renderText(button->getText(), button->getFont(), color,x + (w / 2), y + (h / 2), true); - } - } - else { - if(renderText3DEnabled == true) { - //renderText3D(button->getText(), button->getFont3D(),disabledTextColor, - // x + (w / 2), y + (h / 2), true); - renderTextBoundingBox3D(button->getText(), button->getFont3D(),disabledTextColor, - x, y, w, h, true, true,false,-1,-1); - } - else { - renderText(button->getText(), button->getFont(),disabledTextColor, - x + (w / 2), y + (h / 2), true); - } - } + glEnable(GL_TEXTURE_2D); + glEnable(GL_BLEND); - glPopAttrib(); - } - catch(const exception &e) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d]\nError [%s] For Control container [%s] name [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what(),button->getContainerName().c_str(), button->getInstanceName().c_str()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,szBuf); + if (backTexture != NULL) { + glBindTexture(GL_TEXTURE_2D, + static_cast(backTexture)->getHandle()); + } else { + glBindTexture(GL_TEXTURE_2D, 0); + } - throw megaglest_runtime_error(szBuf); - } -} + // button + Vec4f fontColor(GraphicComponent::getCustomTextColor()); -void Renderer::renderCheckBox(const GraphicCheckBox *box) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } + if (fontColorOverride != NULL) { + fontColor = *fontColorOverride; + } else { + // white shadowed is default ( in the menu for example ) + fontColor.w = GraphicComponent::getFade(); + } - if(box->getVisible() == false) { - return; - } + // Vec4f color= Vec4f(1.f, 1.f, 1.f, GraphicComponent::getFade()); + Vec4f color = fontColor; + glColor4fv(color.ptr()); - int x= box->getX(); - int y= box->getY(); - int h= box->getH(); - int w= box->getW(); + glBegin(GL_TRIANGLE_STRIP); + glTexCoord2f(0.f, 0.f); + glVertex2f(x, y); - //const Vec3f disabledTextColor= Vec3f(0.25f,0.25f,0.25f); + glTexCoord2f(0.f, 1.f); + glVertex2f(x, y + h); - glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT); + glTexCoord2f(1.f, 0.f); + glVertex2f(x + w, y); - //background - CoreData &coreData= CoreData::getInstance(); - Texture2D *backTexture= box->getValue()? coreData.getCheckedCheckBoxTexture(): coreData.getCheckBoxTexture(); + glTexCoord2f(1.f, 1.f); + glVertex2f(x + w, y + h); - glEnable(GL_TEXTURE_2D); - glEnable(GL_BLEND); + glEnd(); - glBindTexture(GL_TEXTURE_2D, static_cast(backTexture)->getHandle()); + glDisable(GL_TEXTURE_2D); - //box - Vec4f fontColor; - //if(game!=NULL){ - // fontColor=game->getGui()->getDisplay()->getColor(); - // fontColor.w = GraphicComponent::getFade(); - //} - //else { - // white shadowed is default ( in the menu for example ) - fontColor=Vec4f(1.f, 1.f, 1.f, GraphicComponent::getFade()); - //} + // lighting + float anim = GraphicComponent::getAnim(); + if (anim > 0.5f) + anim = 1.f - anim; - //Vec4f color= Vec4f(1.f, 1.f, 1.f, GraphicComponent::getFade()); - Vec4f color= fontColor; - glColor4fv(color.ptr()); + bool renderLighted = (button->getLighted() && button->getEditable()); + if (lightedOverride != NULL) { + renderLighted = *lightedOverride; + } + if (renderLighted) { + const int lightSize = 0; + const Vec4f color1 = Vec4f(color.x, color.y, color.z, 0.1f + anim * 0.5f); + const Vec4f color2 = Vec4f(color.x, color.y, color.z, 0.3f + anim); - glBegin(GL_TRIANGLE_STRIP); - glTexCoord2f(0.f, 0.f); - glVertex2f(x, y); + glBegin(GL_TRIANGLE_FAN); - glTexCoord2f(0.f, 1.f); - glVertex2f(x, y+h); + glColor4fv(color2.ptr()); + glVertex2f(x + w / 2, y + h / 2); - glTexCoord2f(1.f, 0.f); - glVertex2f(x+w, y); + glColor4fv(color1.ptr()); + glVertex2f(x - lightSize, y - lightSize); - glTexCoord2f(1.f, 1.f); - glVertex2f(x+w, y+h); + glColor4fv(color1.ptr()); + glVertex2f(x + w + lightSize, y - lightSize); - glEnd(); + glColor4fv(color1.ptr()); + glVertex2f(x + w + lightSize, y + h + lightSize); - glDisable(GL_TEXTURE_2D); + glColor4fv(color1.ptr()); + glVertex2f(x + w + lightSize, y + h + lightSize); - //lighting - float anim= GraphicComponent::getAnim(); - if(anim > 0.5f) { - anim = 1.f - anim; - } + glColor4fv(color1.ptr()); + glVertex2f(x - lightSize, y + h + lightSize); - if(box->getLighted() && box->getEditable()) { - const int lightSize= 0; - const Vec4f color1= Vec4f(color.x, color.y, color.z, 0.1f+anim*0.5f); - const Vec4f color2= Vec4f(color.x, color.y, color.z, 0.3f+anim); + glColor4fv(color1.ptr()); + glVertex2f(x - lightSize, y - lightSize); - glBegin(GL_TRIANGLE_FAN); + glEnd(); + } - glColor4fv(color2.ptr()); - glVertex2f(x+w/2, y+h/2); + // Vec2i textPos= Vec2i(x + w / 2, y + h / 2); + + if (button->getEditable()) { + if (renderText3DEnabled == true) { + // renderText3D(button->getText(), button->getFont3D(), color,x + (w / + // 2), y + (h / 2), true); + renderTextBoundingBox3D(button->getText(), button->getFont3D(), color, + x, y, w, h, true, true, false, -1, -1); + } else { + renderText(button->getText(), button->getFont(), color, x + (w / 2), + y + (h / 2), true); + } + } else { + if (renderText3DEnabled == true) { + // renderText3D(button->getText(), + // button->getFont3D(),disabledTextColor, + // x + (w / 2), y + (h / 2), true); + renderTextBoundingBox3D(button->getText(), button->getFont3D(), + disabledTextColor, x, y, w, h, true, true, + false, -1, -1); + } else { + renderText(button->getText(), button->getFont(), disabledTextColor, + x + (w / 2), y + (h / 2), true); + } + } - glColor4fv(color1.ptr()); - glVertex2f(x-lightSize, y-lightSize); + glPopAttrib(); + } catch (const exception &e) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d]\nError [%s] For Control container [%s] name " + "[%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, e.what(), button->getContainerName().c_str(), + button->getInstanceName().c_str()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, szBuf); + + throw megaglest_runtime_error(szBuf); + } +} - glColor4fv(color1.ptr()); - glVertex2f(x+w+lightSize, y-lightSize); +void Renderer::renderCheckBox(const GraphicCheckBox *box) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - glColor4fv(color1.ptr()); - glVertex2f(x+w+lightSize, y+h+lightSize); + if (box->getVisible() == false) { + return; + } - glColor4fv(color1.ptr()); - glVertex2f(x+w+lightSize, y+h+lightSize); + int x = box->getX(); + int y = box->getY(); + int h = box->getH(); + int w = box->getW(); - glColor4fv(color1.ptr()); - glVertex2f(x-lightSize, y+h+lightSize); + // const Vec3f disabledTextColor= Vec3f(0.25f,0.25f,0.25f); - glColor4fv(color1.ptr()); - glVertex2f(x-lightSize, y-lightSize); + glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT); - glEnd(); - } + // background + CoreData &coreData = CoreData::getInstance(); + Texture2D *backTexture = box->getValue() + ? coreData.getCheckedCheckBoxTexture() + : coreData.getCheckBoxTexture(); - glPopAttrib(); -} + glEnable(GL_TEXTURE_2D); + glEnable(GL_BLEND); + glBindTexture(GL_TEXTURE_2D, + static_cast(backTexture)->getHandle()); -void Renderer::renderLine(const GraphicLine *line) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } + // box + Vec4f fontColor; + // if(game!=NULL){ + // fontColor=game->getGui()->getDisplay()->getColor(); + // fontColor.w = GraphicComponent::getFade(); + // } + // else { + // white shadowed is default ( in the menu for example ) + fontColor = Vec4f(1.f, 1.f, 1.f, GraphicComponent::getFade()); + //} - if(line->getVisible() == false) { - return; - } + // Vec4f color= Vec4f(1.f, 1.f, 1.f, GraphicComponent::getFade()); + Vec4f color = fontColor; + glColor4fv(color.ptr()); - int x= line->getX(); - int y= line->getY(); - int h= line->getH(); - int w= line->getW(); + glBegin(GL_TRIANGLE_STRIP); + glTexCoord2f(0.f, 0.f); + glVertex2f(x, y); - //const Vec3f disabledTextColor= Vec3f(0.25f,0.25f,0.25f); + glTexCoord2f(0.f, 1.f); + glVertex2f(x, y + h); - glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT); + glTexCoord2f(1.f, 0.f); + glVertex2f(x + w, y); - //background - CoreData &coreData= CoreData::getInstance(); - Texture2D *backTexture= line->getHorizontal()? coreData.getHorizontalLineTexture(): coreData.getVerticalLineTexture(); + glTexCoord2f(1.f, 1.f); + glVertex2f(x + w, y + h); - glEnable(GL_TEXTURE_2D); - glEnable(GL_BLEND); + glEnd(); - glBindTexture(GL_TEXTURE_2D, static_cast(backTexture)->getHandle()); + glDisable(GL_TEXTURE_2D); - glBegin(GL_TRIANGLE_STRIP); - glTexCoord2f(0.f, 0.f); - glVertex2f(x, y); + // lighting + float anim = GraphicComponent::getAnim(); + if (anim > 0.5f) { + anim = 1.f - anim; + } - glTexCoord2f(0.f, 1.f); - glVertex2f(x, y+h); + if (box->getLighted() && box->getEditable()) { + const int lightSize = 0; + const Vec4f color1 = Vec4f(color.x, color.y, color.z, 0.1f + anim * 0.5f); + const Vec4f color2 = Vec4f(color.x, color.y, color.z, 0.3f + anim); - glTexCoord2f(1.f, 0.f); - glVertex2f(x+w, y); + glBegin(GL_TRIANGLE_FAN); - glTexCoord2f(1.f, 1.f); - glVertex2f(x+w, y+h); + glColor4fv(color2.ptr()); + glVertex2f(x + w / 2, y + h / 2); - glEnd(); + glColor4fv(color1.ptr()); + glVertex2f(x - lightSize, y - lightSize); - glDisable(GL_TEXTURE_2D); - glPopAttrib(); -} + glColor4fv(color1.ptr()); + glVertex2f(x + w + lightSize, y - lightSize); -void Renderer::renderScrollBar(const GraphicScrollBar *sb) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } + glColor4fv(color1.ptr()); + glVertex2f(x + w + lightSize, y + h + lightSize); - if(sb->getVisible() == false) { - return; - } + glColor4fv(color1.ptr()); + glVertex2f(x + w + lightSize, y + h + lightSize); - int x= sb->getX(); - int y= sb->getY(); - int h= sb->getH(); - int w= sb->getW(); + glColor4fv(color1.ptr()); + glVertex2f(x - lightSize, y + h + lightSize); - // calc real length - if(sb->getElementCount()getVisibleSize()){ - int realLength=sb->getElementCount()*sb->getLength()/ sb->getVisibleSize(); - if (sb->getHorizontal()) { - x=x-(w-realLength); - } - else { - y=y+(h-realLength); - h=realLength; - }; - } + glColor4fv(color1.ptr()); + glVertex2f(x - lightSize, y - lightSize); - glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT); - ///////////////////// - //background - //////////////////// - CoreData &coreData= CoreData::getInstance(); - Texture2D *backTexture= coreData.getHorizontalLineTexture(); + glEnd(); + } - glEnable(GL_TEXTURE_2D); - glEnable(GL_BLEND); + glPopAttrib(); +} - Vec4f fontColor; - fontColor=Vec4f(1.f, 1.f, 1.f, GraphicComponent::getFade()); - Vec4f color= fontColor; - glColor4fv(color.ptr()); +void Renderer::renderLine(const GraphicLine *line) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - glBindTexture(GL_TEXTURE_2D, static_cast(backTexture)->getHandle()); + if (line->getVisible() == false) { + return; + } - glBegin(GL_TRIANGLE_STRIP); - glTexCoord2f(0.f, 0.f); - glVertex2f(x, y); + int x = line->getX(); + int y = line->getY(); + int h = line->getH(); + int w = line->getW(); - glTexCoord2f(0.f, 1.f); - glVertex2f(x, y+h); + // const Vec3f disabledTextColor= Vec3f(0.25f,0.25f,0.25f); - glTexCoord2f(1.f, 0.f); - glVertex2f(x+w, y); + glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT); - glTexCoord2f(1.f, 1.f); - glVertex2f(x+w, y+h); + // background + CoreData &coreData = CoreData::getInstance(); + Texture2D *backTexture = line->getHorizontal() + ? coreData.getHorizontalLineTexture() + : coreData.getVerticalLineTexture(); - glEnd(); + glEnable(GL_TEXTURE_2D); + glEnable(GL_BLEND); - //////////////////// - // selectBlock - //////////////////// + glBindTexture(GL_TEXTURE_2D, + static_cast(backTexture)->getHandle()); - if (sb->getElementCount() >= sb->getVisibleSize()) { - if (sb->getHorizontal()) { - x = x + sb->getVisibleCompPosStart(); - w = sb->getVisibleCompPosEnd() - sb->getVisibleCompPosStart(); - } else { - y = y + sb->getVisibleCompPosStart(); - h = sb->getVisibleCompPosEnd() - sb->getVisibleCompPosStart(); - } - } + glBegin(GL_TRIANGLE_STRIP); + glTexCoord2f(0.f, 0.f); + glVertex2f(x, y); - Texture2D *selectTexture= coreData.getButtonBigTexture(); - assert(selectTexture != NULL); + glTexCoord2f(0.f, 1.f); + glVertex2f(x, y + h); - glBindTexture(GL_TEXTURE_2D, static_cast(selectTexture)->getHandle()); + glTexCoord2f(1.f, 0.f); + glVertex2f(x + w, y); + glTexCoord2f(1.f, 1.f); + glVertex2f(x + w, y + h); - glBegin(GL_TRIANGLE_STRIP); - glTexCoord2f(0.f, 0.f); - glVertex2f(x, y); + glEnd(); - glTexCoord2f(0.f, 1.f); - glVertex2f(x, y+h); + glDisable(GL_TEXTURE_2D); + glPopAttrib(); +} - glTexCoord2f(1.f, 0.f); - glVertex2f(x+w, y); +void Renderer::renderScrollBar(const GraphicScrollBar *sb) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + if (sb->getVisible() == false) { + return; + } + + int x = sb->getX(); + int y = sb->getY(); + int h = sb->getH(); + int w = sb->getW(); + + // calc real length + if (sb->getElementCount() < sb->getVisibleSize()) { + int realLength = + sb->getElementCount() * sb->getLength() / sb->getVisibleSize(); + if (sb->getHorizontal()) { + x = x - (w - realLength); + } else { + y = y + (h - realLength); + h = realLength; + }; + } + + glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT); + ///////////////////// + // background + //////////////////// + CoreData &coreData = CoreData::getInstance(); + Texture2D *backTexture = coreData.getHorizontalLineTexture(); + + glEnable(GL_TEXTURE_2D); + glEnable(GL_BLEND); + + Vec4f fontColor; + fontColor = Vec4f(1.f, 1.f, 1.f, GraphicComponent::getFade()); + Vec4f color = fontColor; + glColor4fv(color.ptr()); + + glBindTexture(GL_TEXTURE_2D, + static_cast(backTexture)->getHandle()); + + glBegin(GL_TRIANGLE_STRIP); + glTexCoord2f(0.f, 0.f); + glVertex2f(x, y); + + glTexCoord2f(0.f, 1.f); + glVertex2f(x, y + h); + + glTexCoord2f(1.f, 0.f); + glVertex2f(x + w, y); + + glTexCoord2f(1.f, 1.f); + glVertex2f(x + w, y + h); + + glEnd(); + + //////////////////// + // selectBlock + //////////////////// + + if (sb->getElementCount() >= sb->getVisibleSize()) { + if (sb->getHorizontal()) { + x = x + sb->getVisibleCompPosStart(); + w = sb->getVisibleCompPosEnd() - sb->getVisibleCompPosStart(); + } else { + y = y + sb->getVisibleCompPosStart(); + h = sb->getVisibleCompPosEnd() - sb->getVisibleCompPosStart(); + } + } - glTexCoord2f(1.f, 1.f); - glVertex2f(x+w, y+h); + Texture2D *selectTexture = coreData.getButtonBigTexture(); + assert(selectTexture != NULL); - glEnd(); + glBindTexture(GL_TEXTURE_2D, + static_cast(selectTexture)->getHandle()); - glDisable(GL_TEXTURE_2D); + glBegin(GL_TRIANGLE_STRIP); + glTexCoord2f(0.f, 0.f); + glVertex2f(x, y); - //lighting - float anim= GraphicComponent::getAnim(); - if(anim>0.5f) anim= 1.f-anim; + glTexCoord2f(0.f, 1.f); + glVertex2f(x, y + h); - if(sb->getLighted() && sb->getEditable()){ - const int lightSize= 0; - const Vec4f color1= Vec4f(color.x, color.y, color.z, 0.1f+anim*0.5f); - const Vec4f color2= Vec4f(color.x, color.y, color.z, 0.3f+anim); + glTexCoord2f(1.f, 0.f); + glVertex2f(x + w, y); - glBegin(GL_TRIANGLE_FAN); + glTexCoord2f(1.f, 1.f); + glVertex2f(x + w, y + h); - glColor4fv(color2.ptr()); - glVertex2f(x+w/2, y+h/2); + glEnd(); - glColor4fv(color1.ptr()); - glVertex2f(x-lightSize, y-lightSize); + glDisable(GL_TEXTURE_2D); - glColor4fv(color1.ptr()); - glVertex2f(x+w+lightSize, y-lightSize); + // lighting + float anim = GraphicComponent::getAnim(); + if (anim > 0.5f) + anim = 1.f - anim; - glColor4fv(color1.ptr()); - glVertex2f(x+w+lightSize, y+h+lightSize); + if (sb->getLighted() && sb->getEditable()) { + const int lightSize = 0; + const Vec4f color1 = Vec4f(color.x, color.y, color.z, 0.1f + anim * 0.5f); + const Vec4f color2 = Vec4f(color.x, color.y, color.z, 0.3f + anim); - glColor4fv(color1.ptr()); - glVertex2f(x+w+lightSize, y+h+lightSize); + glBegin(GL_TRIANGLE_FAN); - glColor4fv(color1.ptr()); - glVertex2f(x-lightSize, y+h+lightSize); + glColor4fv(color2.ptr()); + glVertex2f(x + w / 2, y + h / 2); - glColor4fv(color1.ptr()); - glVertex2f(x-lightSize, y-lightSize); + glColor4fv(color1.ptr()); + glVertex2f(x - lightSize, y - lightSize); - glEnd(); - } + glColor4fv(color1.ptr()); + glVertex2f(x + w + lightSize, y - lightSize); - glPopAttrib(); -} + glColor4fv(color1.ptr()); + glVertex2f(x + w + lightSize, y + h + lightSize); -void Renderer::renderListBox(GraphicListBox *listBox) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } + glColor4fv(color1.ptr()); + glVertex2f(x + w + lightSize, y + h + lightSize); - if(listBox->getVisible() == false) { - return; - } - //if(listBox->getLeftControlled()==true) - { - int x= listBox->getX(); - int y= listBox->getY(); - int h= listBox->getH(); - int w= listBox->getW(); - if(h>0){ - //background - glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT); - glEnable(GL_BLEND); + glColor4fv(color1.ptr()); + glVertex2f(x - lightSize, y + h + lightSize); - glColor4f(0.0f, 0.0f, 0.0f, 0.6f*listBox->getFade()) ; + glColor4fv(color1.ptr()); + glVertex2f(x - lightSize, y - lightSize); - glBegin(GL_TRIANGLE_STRIP); - glVertex2i(x, y); - glVertex2i(x, y+h); - glVertex2i(x+w, y); - glVertex2i(x+w, y+h); - glEnd(); - glPopAttrib(); - } - } - renderButton(listBox->getButton1()); - renderButton(listBox->getButton2()); + glEnd(); + } - glPushAttrib(GL_ENABLE_BIT); - glEnable(GL_BLEND); + glPopAttrib(); +} - GraphicLabel label("ListBox_render_label","label",false); - //label.setInstanceName("ListBox_render_label"); - if(listBox->getLeftControlled()==true){ - label.init(listBox->getX()+listBox->getButton1()->getW()+listBox->getButton2()->getW()+2, listBox->getY(), listBox->getW(), listBox->getH(), false,listBox->getTextColor()); - } - else { - label.init(listBox->getX(), listBox->getY(), listBox->getW(), listBox->getH(), true,listBox->getTextColor()); - } - label.setText(listBox->getText()); - label.setTextNativeTranslation(listBox->getTextNativeTranslation()); - label.setFont(listBox->getFont()); - label.setFont3D(listBox->getFont3D()); - renderLabel(&label); +void Renderer::renderListBox(GraphicListBox *listBox) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + if (listBox->getVisible() == false) { + return; + } + // if(listBox->getLeftControlled()==true) + { + int x = listBox->getX(); + int y = listBox->getY(); + int h = listBox->getH(); + int w = listBox->getW(); + if (h > 0) { + // background + glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT); + glEnable(GL_BLEND); + + glColor4f(0.0f, 0.0f, 0.0f, 0.6f * listBox->getFade()); + + glBegin(GL_TRIANGLE_STRIP); + glVertex2i(x, y); + glVertex2i(x, y + h); + glVertex2i(x + w, y); + glVertex2i(x + w, y + h); + glEnd(); + glPopAttrib(); + } + } + renderButton(listBox->getButton1()); + renderButton(listBox->getButton2()); + glPushAttrib(GL_ENABLE_BIT); + glEnable(GL_BLEND); - //lighting + GraphicLabel label("ListBox_render_label", "label", false); + // label.setInstanceName("ListBox_render_label"); + if (listBox->getLeftControlled() == true) { + label.init(listBox->getX() + listBox->getButton1()->getW() + + listBox->getButton2()->getW() + 2, + listBox->getY(), listBox->getW(), listBox->getH(), false, + listBox->getTextColor()); + } else { + label.init(listBox->getX(), listBox->getY(), listBox->getW(), + listBox->getH(), true, listBox->getTextColor()); + } + label.setText(listBox->getText()); + label.setTextNativeTranslation(listBox->getTextNativeTranslation()); + label.setFont(listBox->getFont()); + label.setFont3D(listBox->getFont3D()); + renderLabel(&label); - bool renderLighted= (listBox->getLighted()); + // lighting + bool renderLighted = (listBox->getLighted()); - if(renderLighted) { - float anim= GraphicComponent::getAnim(); - if(anim>0.5f) anim= 1.f-anim; + if (renderLighted) { + float anim = GraphicComponent::getAnim(); + if (anim > 0.5f) + anim = 1.f - anim; - Vec3f color=listBox->getTextColor(); - int x= listBox->getX()+listBox->getButton1()->getW(); - int y= listBox->getY(); - int h= listBox->getH(); - int w= listBox->getW()-listBox->getButton1()->getW()-listBox->getButton2()->getW(); + Vec3f color = listBox->getTextColor(); + int x = listBox->getX() + listBox->getButton1()->getW(); + int y = listBox->getY(); + int h = listBox->getH(); + int w = listBox->getW() - listBox->getButton1()->getW() - + listBox->getButton2()->getW(); - const int lightSize= 0; - const Vec4f color1= Vec4f(color.x, color.y, color.z, 0.1f+anim*0.5f); - const Vec4f color2= Vec4f(color.x, color.y, color.z, 0.3f+anim); + const int lightSize = 0; + const Vec4f color1 = Vec4f(color.x, color.y, color.z, 0.1f + anim * 0.5f); + const Vec4f color2 = Vec4f(color.x, color.y, color.z, 0.3f + anim); - glBegin(GL_TRIANGLE_FAN); + glBegin(GL_TRIANGLE_FAN); - glColor4fv(color2.ptr()); - glVertex2f(x+w/2, y+h/2); + glColor4fv(color2.ptr()); + glVertex2f(x + w / 2, y + h / 2); - glColor4fv(color1.ptr()); - glVertex2f(x-lightSize, y-lightSize); + glColor4fv(color1.ptr()); + glVertex2f(x - lightSize, y - lightSize); - glColor4fv(color1.ptr()); - glVertex2f(x+w+lightSize, y-lightSize); + glColor4fv(color1.ptr()); + glVertex2f(x + w + lightSize, y - lightSize); - glColor4fv(color1.ptr()); - glVertex2f(x+w+lightSize, y+h+lightSize); + glColor4fv(color1.ptr()); + glVertex2f(x + w + lightSize, y + h + lightSize); - glColor4fv(color1.ptr()); - glVertex2f(x+w+lightSize, y+h+lightSize); + glColor4fv(color1.ptr()); + glVertex2f(x + w + lightSize, y + h + lightSize); - glColor4fv(color1.ptr()); - glVertex2f(x-lightSize, y+h+lightSize); + glColor4fv(color1.ptr()); + glVertex2f(x - lightSize, y + h + lightSize); - glColor4fv(color1.ptr()); - glVertex2f(x-lightSize, y-lightSize); + glColor4fv(color1.ptr()); + glVertex2f(x - lightSize, y - lightSize); - glEnd(); - } + glEnd(); + } - glPopAttrib(); + glPopAttrib(); } void Renderer::renderComboBox(GraphicComboBox *comboBox) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + if (comboBox->getVisible() == false) { + return; + } + + int x = comboBox->getX(); + int y = comboBox->getY(); + int h = comboBox->getH(); + int w = comboBox->getW(); + if (h > 0) { + // background + glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT); + glEnable(GL_BLEND); + + glColor4f(0.0f, 0.0f, 0.0f, 0.6f * comboBox->getFade()); + + glBegin(GL_TRIANGLE_STRIP); + glVertex2i(x, y); + glVertex2i(x, y + h); + glVertex2i(x + w, y); + glVertex2i(x + w, y + h); + glEnd(); + glPopAttrib(); + } + + renderButton(comboBox->getButton()); + + if (comboBox->isDropDownShowing()) { + renderScrollBar(comboBox->getScrollbar()); + + if (comboBox->getPopupButtons()->size() != 0) { + for (int i = comboBox->getScrollbar()->getVisibleStart(); + i <= comboBox->getScrollbar()->getVisibleEnd(); ++i) { + renderButton((*comboBox->getPopupButtons())[i]); + } + } + } - if(comboBox->getVisible() == false) { - return; - } + glPushAttrib(GL_ENABLE_BIT); + glEnable(GL_BLEND); - int x= comboBox->getX(); - int y= comboBox->getY(); - int h= comboBox->getH(); - int w= comboBox->getW(); - if(h>0){ - //background - glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT); - glEnable(GL_BLEND); + GraphicLabel label("ComboBox_render_label", "label", false); + // label.setInstanceName("ComboBox_render_label"); - glColor4f(0.0f, 0.0f, 0.0f, 0.6f*comboBox->getFade()) ; + label.init(comboBox->getX(), comboBox->getY(), comboBox->getW(), + comboBox->getH(), true, comboBox->getTextColor()); + label.setText(comboBox->getText()); + label.setTextNativeTranslation(comboBox->getTextNativeTranslation()); + label.setFont(comboBox->getFont()); + label.setFont3D(comboBox->getFont3D()); + renderLabel(&label); - glBegin(GL_TRIANGLE_STRIP); - glVertex2i(x, y); - glVertex2i(x, y+h); - glVertex2i(x+w, y); - glVertex2i(x+w, y+h); - glEnd(); - glPopAttrib(); - } + // lighting - renderButton(comboBox->getButton()); + bool renderLighted = (comboBox->getLighted()); - if( comboBox->isDropDownShowing()){ - renderScrollBar(comboBox->getScrollbar()); + if (renderLighted) { + float anim = GraphicComponent::getAnim(); + if (anim > 0.5f) + anim = 1.f - anim; - if(comboBox->getPopupButtons()->size() != 0) { - for(int i = comboBox->getScrollbar()->getVisibleStart(); - i <= comboBox->getScrollbar()->getVisibleEnd(); ++i) { - renderButton((* comboBox->getPopupButtons())[i]); - } - } - } + Vec3f color = comboBox->getTextColor(); + int x = comboBox->getX() + comboBox->getButton()->getW(); + int y = comboBox->getY(); + int h = comboBox->getH(); + int w = comboBox->getW() - comboBox->getButton()->getW(); - glPushAttrib(GL_ENABLE_BIT); - glEnable(GL_BLEND); + const int lightSize = 0; + const Vec4f color1 = Vec4f(color.x, color.y, color.z, 0.1f + anim * 0.5f); + const Vec4f color2 = Vec4f(color.x, color.y, color.z, 0.3f + anim); - GraphicLabel label("ComboBox_render_label","label",false); - //label.setInstanceName("ComboBox_render_label"); + glBegin(GL_TRIANGLE_FAN); - label.init(comboBox->getX(), comboBox->getY(), comboBox->getW(), comboBox->getH(), true,comboBox->getTextColor()); - label.setText(comboBox->getText()); - label.setTextNativeTranslation(comboBox->getTextNativeTranslation()); - label.setFont(comboBox->getFont()); - label.setFont3D(comboBox->getFont3D()); - renderLabel(&label); + glColor4fv(color2.ptr()); + glVertex2f(x + w / 2, y + h / 2); + glColor4fv(color1.ptr()); + glVertex2f(x - lightSize, y - lightSize); - //lighting + glColor4fv(color1.ptr()); + glVertex2f(x + w + lightSize, y - lightSize); - bool renderLighted= (comboBox->getLighted()); + glColor4fv(color1.ptr()); + glVertex2f(x + w + lightSize, y + h + lightSize); + glColor4fv(color1.ptr()); + glVertex2f(x + w + lightSize, y + h + lightSize); - if(renderLighted) { - float anim= GraphicComponent::getAnim(); - if(anim>0.5f) anim= 1.f-anim; + glColor4fv(color1.ptr()); + glVertex2f(x - lightSize, y + h + lightSize); - Vec3f color=comboBox->getTextColor(); - int x= comboBox->getX()+comboBox->getButton()->getW(); - int y= comboBox->getY(); - int h= comboBox->getH(); - int w= comboBox->getW()-comboBox->getButton()->getW(); + glColor4fv(color1.ptr()); + glVertex2f(x - lightSize, y - lightSize); - const int lightSize= 0; - const Vec4f color1= Vec4f(color.x, color.y, color.z, 0.1f+anim*0.5f); - const Vec4f color2= Vec4f(color.x, color.y, color.z, 0.3f+anim); + glEnd(); + } - glBegin(GL_TRIANGLE_FAN); + glPopAttrib(); +} - glColor4fv(color2.ptr()); - glVertex2f(x+w/2, y+h/2); +void Renderer::renderMessageBox(GraphicMessageBox *messageBox) { + const int headerHeight = 25; + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + try { + if (messageBox->getVisible() == false) { + return; + } - glColor4fv(color1.ptr()); - glVertex2f(x-lightSize, y-lightSize); + if ((renderText3DEnabled == false && messageBox->getFont() == NULL) || + (renderText3DEnabled == true && messageBox->getFont3D() == NULL)) { + messageBox->setFont(CoreData::getInstance().getMenuFontNormal()); + messageBox->setFont3D(CoreData::getInstance().getMenuFontNormal3D()); + } - glColor4fv(color1.ptr()); - glVertex2f(x+w+lightSize, y-lightSize); + string wrappedText = messageBox->getText(); + if (messageBox->getAutoWordWrap() == true) { + if (renderText3DEnabled == false) { + wrappedText = messageBox->getFont()->getMetrics()->wordWrapText( + wrappedText, messageBox->getW() * 0.90); + } else { + wrappedText = messageBox->getFont3D()->getMetrics()->wordWrapText( + wrappedText, messageBox->getW() * 0.90); + } + } - glColor4fv(color1.ptr()); - glVertex2f(x+w+lightSize, y+h+lightSize); + // background + glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT); + glEnable(GL_BLEND); - glColor4fv(color1.ptr()); - glVertex2f(x+w+lightSize, y+h+lightSize); + glColor4f(0.0f, 0.0f, 0.0f, 0.8f); + glBegin(GL_TRIANGLE_STRIP); + glVertex2i(messageBox->getX(), + messageBox->getY() + messageBox->getH() - headerHeight); + glVertex2i(messageBox->getX(), messageBox->getY()); + glVertex2i(messageBox->getX() + messageBox->getW(), + messageBox->getY() + messageBox->getH() - headerHeight); + glVertex2i(messageBox->getX() + messageBox->getW(), messageBox->getY()); + glEnd(); - glColor4fv(color1.ptr()); - glVertex2f(x-lightSize, y+h+lightSize); + glColor4f(0.0f, 0.0f, 0.0f, 0.8f); + glBegin(GL_TRIANGLE_STRIP); + glVertex2i(messageBox->getX(), messageBox->getY() + messageBox->getH()); + glVertex2i(messageBox->getX(), + messageBox->getY() + messageBox->getH() - headerHeight); + glVertex2i(messageBox->getX() + messageBox->getW(), + messageBox->getY() + messageBox->getH()); + glVertex2i(messageBox->getX() + messageBox->getW(), + messageBox->getY() + messageBox->getH() - headerHeight); + glEnd(); - glColor4fv(color1.ptr()); - glVertex2f(x-lightSize, y-lightSize); + glBegin(GL_LINE_LOOP); + glColor4f(0.5f, 0.5f, 0.5f, 0.25f); + glVertex2i(messageBox->getX(), messageBox->getY()); - glEnd(); - } + glColor4f(0.0f, 0.0f, 0.0f, 0.25f); + glVertex2i(messageBox->getX() + messageBox->getW(), messageBox->getY()); - glPopAttrib(); -} + glColor4f(0.5f, 0.5f, 0.5f, 0.25f); + glVertex2i(messageBox->getX() + messageBox->getW(), + messageBox->getY() + messageBox->getH()); -void Renderer::renderMessageBox(GraphicMessageBox *messageBox) { - const int headerHeight=25; - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - try { - if(messageBox->getVisible() == false) { - return; - } - - if((renderText3DEnabled == false && messageBox->getFont() == NULL) || - (renderText3DEnabled == true && messageBox->getFont3D() == NULL)) { - messageBox->setFont(CoreData::getInstance().getMenuFontNormal()); - messageBox->setFont3D(CoreData::getInstance().getMenuFontNormal3D()); - } - - string wrappedText = messageBox->getText(); - if(messageBox->getAutoWordWrap() == true) { - if(renderText3DEnabled == false) { - wrappedText = messageBox->getFont()->getMetrics()->wordWrapText(wrappedText,messageBox->getW() * 0.90); - } - else { - wrappedText = messageBox->getFont3D()->getMetrics()->wordWrapText(wrappedText,messageBox->getW() * 0.90); - } - } - - //background - glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT); - glEnable(GL_BLEND); - - glColor4f(0.0f, 0.0f, 0.0f, 0.8f) ; - glBegin(GL_TRIANGLE_STRIP); - glVertex2i(messageBox->getX(), messageBox->getY()+messageBox->getH()-headerHeight); - glVertex2i(messageBox->getX(), messageBox->getY()); - glVertex2i(messageBox->getX() + messageBox->getW(), messageBox->getY() + messageBox->getH()-headerHeight); - glVertex2i(messageBox->getX() + messageBox->getW(), messageBox->getY()); - glEnd(); - - glColor4f(0.0f, 0.0f, 0.0f, 0.8f) ; - glBegin(GL_TRIANGLE_STRIP); - glVertex2i(messageBox->getX(), messageBox->getY()+messageBox->getH()); - glVertex2i(messageBox->getX(), messageBox->getY()+messageBox->getH()-headerHeight); - glVertex2i(messageBox->getX() + messageBox->getW(), messageBox->getY() + messageBox->getH()); - glVertex2i(messageBox->getX() + messageBox->getW(), messageBox->getY()+messageBox->getH()-headerHeight); - glEnd(); - - glBegin(GL_LINE_LOOP); - glColor4f(0.5f, 0.5f, 0.5f, 0.25f) ; - glVertex2i(messageBox->getX(), messageBox->getY()); - - glColor4f(0.0f, 0.0f, 0.0f, 0.25f) ; - glVertex2i(messageBox->getX()+ messageBox->getW(), messageBox->getY()); - - glColor4f(0.5f, 0.5f, 0.5f, 0.25f) ; - glVertex2i(messageBox->getX()+ messageBox->getW(), messageBox->getY() + messageBox->getH()); - - glColor4f(0.25f, 0.25f, 0.25f, 0.25f) ; - glVertex2i(messageBox->getX(), messageBox->getY() + messageBox->getH()); - glEnd(); - - glBegin(GL_LINE_STRIP); - glColor4f(1.0f, 1.0f, 1.0f, 0.25f) ; - glVertex2i(messageBox->getX(), messageBox->getY() + messageBox->getH()-headerHeight); - - glColor4f(0.5f, 0.5f, 0.5f, 0.25f) ; - glVertex2i(messageBox->getX()+ messageBox->getW(), messageBox->getY() + messageBox->getH()-headerHeight); - glEnd(); - - glPopAttrib(); - - - //buttons - for(int i=0; igetButtonCount();i++){ - - if((renderText3DEnabled == false && messageBox->getButton(i)->getFont() == NULL) || - (renderText3DEnabled == true && messageBox->getButton(i)->getFont3D() == NULL)) { - messageBox->getButton(i)->setFont(CoreData::getInstance().getMenuFontNormal()); - messageBox->getButton(i)->setFont3D(CoreData::getInstance().getMenuFontNormal3D()); - } - - renderButton(messageBox->getButton(i)); - } - - Vec4f fontColor; - //if(game!=NULL){ - // fontColor=game->getGui()->getDisplay()->getColor(); - //} - //else { - // white shadowed is default ( in the menu for example ) - fontColor=Vec4f(1.f, 1.f, 1.f, 1.0f); - //} - - if(renderText3DEnabled == true) { - //text - renderTextShadow3D( - wrappedText, messageBox->getFont3D(), fontColor, - messageBox->getX()+15, messageBox->getY()+messageBox->getH()-headerHeight*2, - false ); - - renderTextShadow3D( - messageBox->getHeader(), messageBox->getFont3D(),fontColor, - messageBox->getX()+15, messageBox->getY()+messageBox->getH()-headerHeight+8, - false ); - - } - else { - //text - renderTextShadow( - wrappedText, messageBox->getFont(), fontColor, - messageBox->getX()+15, messageBox->getY()+messageBox->getH()-headerHeight*2, - false ); - - renderTextShadow( - messageBox->getHeader(), messageBox->getFont(),fontColor, - messageBox->getX()+15, messageBox->getY()+messageBox->getH()-headerHeight+8, - false ); - } - } - catch(const exception &e) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d]\nError [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,szBuf); - - throw megaglest_runtime_error(szBuf); - } + glColor4f(0.25f, 0.25f, 0.25f, 0.25f); + glVertex2i(messageBox->getX(), messageBox->getY() + messageBox->getH()); + glEnd(); + + glBegin(GL_LINE_STRIP); + glColor4f(1.0f, 1.0f, 1.0f, 0.25f); + glVertex2i(messageBox->getX(), + messageBox->getY() + messageBox->getH() - headerHeight); + + glColor4f(0.5f, 0.5f, 0.5f, 0.25f); + glVertex2i(messageBox->getX() + messageBox->getW(), + messageBox->getY() + messageBox->getH() - headerHeight); + glEnd(); + + glPopAttrib(); + + // buttons + for (int i = 0; i < messageBox->getButtonCount(); i++) { + + if ((renderText3DEnabled == false && + messageBox->getButton(i)->getFont() == NULL) || + (renderText3DEnabled == true && + messageBox->getButton(i)->getFont3D() == NULL)) { + messageBox->getButton(i)->setFont( + CoreData::getInstance().getMenuFontNormal()); + messageBox->getButton(i)->setFont3D( + CoreData::getInstance().getMenuFontNormal3D()); + } + + renderButton(messageBox->getButton(i)); + } + + Vec4f fontColor; + // if(game!=NULL){ + // fontColor=game->getGui()->getDisplay()->getColor(); + // } + // else { + // white shadowed is default ( in the menu for example ) + fontColor = Vec4f(1.f, 1.f, 1.f, 1.0f); + //} + + if (renderText3DEnabled == true) { + // text + renderTextShadow3D( + wrappedText, messageBox->getFont3D(), fontColor, + messageBox->getX() + 15, + messageBox->getY() + messageBox->getH() - headerHeight * 2, false); + + renderTextShadow3D( + messageBox->getHeader(), messageBox->getFont3D(), fontColor, + messageBox->getX() + 15, + messageBox->getY() + messageBox->getH() - headerHeight + 8, false); + + } else { + // text + renderTextShadow( + wrappedText, messageBox->getFont(), fontColor, + messageBox->getX() + 15, + messageBox->getY() + messageBox->getH() - headerHeight * 2, false); + + renderTextShadow( + messageBox->getHeader(), messageBox->getFont(), fontColor, + messageBox->getX() + 15, + messageBox->getY() + messageBox->getH() - headerHeight + 8, false); + } + } catch (const exception &e) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d]\nError [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, e.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, szBuf); + + throw megaglest_runtime_error(szBuf); + } } // ==================== complex rendering ==================== -//VisibleQuadContainerVBOCache * Renderer::GetSurfaceVBOs(SurfaceData *cellData) { -// std::map::iterator iterFind = mapSurfaceVBOCache.find(cellData->uniqueId); -// if(iterFind == mapSurfaceVBOCache.end()) { -// Vec2f *texCoords = &cellData->texCoords[0]; -// Vec2f *texCoordsSurface = &cellData->texCoordsSurface[0]; -// Vec3f *vertices = &cellData->vertices[0]; -// Vec3f *normals = &cellData->normals[0]; +// VisibleQuadContainerVBOCache * Renderer::GetSurfaceVBOs(SurfaceData +// *cellData) { std::map::iterator +// iterFind = mapSurfaceVBOCache.find(cellData->uniqueId); if(iterFind == +// mapSurfaceVBOCache.end()) { Vec2f *texCoords = +//&cellData->texCoords[0]; Vec2f *texCoordsSurface = +//&cellData->texCoordsSurface[0]; Vec3f *vertices = +//&cellData->vertices[0]; Vec3f *normals = +//&cellData->normals[0]; // // VisibleQuadContainerVBOCache vboCache; // // // Generate And Bind The Vertex Buffer -// glGenBuffersARB( 1, (GLuint*)&vboCache.m_nVBOVertices ); // Get A Valid Name -// glBindBufferARB( GL_ARRAY_BUFFER_ARB, vboCache.m_nVBOVertices ); // Bind The Buffer +// glGenBuffersARB( 1, (GLuint*)&vboCache.m_nVBOVertices ); +//// Get A Valid Name glBindBufferARB( GL_ARRAY_BUFFER_ARB, +// vboCache.m_nVBOVertices ); // Bind The Buffer // // Load The Data -// glBufferDataARB( GL_ARRAY_BUFFER_ARB, sizeof(Vec3f) * cellData->bufferCount, vertices, GL_STATIC_DRAW_ARB ); +// glBufferDataARB( GL_ARRAY_BUFFER_ARB, sizeof(Vec3f) * +// cellData->bufferCount, vertices, GL_STATIC_DRAW_ARB ); // glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0); // // assertGl(); // // Generate And Bind The Texture Coordinate Buffer -// glGenBuffersARB( 1, (GLuint*)&vboCache.m_nVBOFowTexCoords ); // Get A Valid Name -// glBindBufferARB( GL_ARRAY_BUFFER_ARB, vboCache.m_nVBOFowTexCoords ); // Bind The Buffer +// glGenBuffersARB( 1, (GLuint*)&vboCache.m_nVBOFowTexCoords ); +//// Get A Valid Name glBindBufferARB( GL_ARRAY_BUFFER_ARB, +// vboCache.m_nVBOFowTexCoords ); // Bind The Buffer // // Load The Data -// glBufferDataARB( GL_ARRAY_BUFFER_ARB, sizeof(Vec2f) * cellData->bufferCount, texCoords, GL_STATIC_DRAW_ARB ); +// glBufferDataARB( GL_ARRAY_BUFFER_ARB, sizeof(Vec2f) * +// cellData->bufferCount, texCoords, GL_STATIC_DRAW_ARB ); // glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0); // // assertGl(); // // Generate And Bind The Texture Coordinate Buffer -// glGenBuffersARB( 1, (GLuint*)&vboCache.m_nVBOSurfaceTexCoords ); // Get A Valid Name -// glBindBufferARB( GL_ARRAY_BUFFER_ARB, vboCache.m_nVBOSurfaceTexCoords ); // Bind The Buffer +// glGenBuffersARB( 1, (GLuint*)&vboCache.m_nVBOSurfaceTexCoords ); +//// Get A Valid Name glBindBufferARB( GL_ARRAY_BUFFER_ARB, +// vboCache.m_nVBOSurfaceTexCoords ); // Bind The Buffer // // Load The Data -// glBufferDataARB( GL_ARRAY_BUFFER_ARB, sizeof(Vec2f) * cellData->bufferCount, texCoordsSurface, GL_STATIC_DRAW_ARB ); +// glBufferDataARB( GL_ARRAY_BUFFER_ARB, sizeof(Vec2f) * +// cellData->bufferCount, texCoordsSurface, GL_STATIC_DRAW_ARB ); // glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0); // // assertGl(); // // Generate And Bind The Normal Buffer -// glGenBuffersARB( 1, (GLuint*)&vboCache.m_nVBONormals ); // Get A Valid Name -// glBindBufferARB( GL_ARRAY_BUFFER_ARB, vboCache.m_nVBONormals ); // Bind The Buffer +// glGenBuffersARB( 1, (GLuint*)&vboCache.m_nVBONormals ); +//// Get A Valid Name glBindBufferARB( GL_ARRAY_BUFFER_ARB, +// vboCache.m_nVBONormals ); // Bind The Buffer // // Load The Data -// glBufferDataARB( GL_ARRAY_BUFFER_ARB, sizeof(Vec3f) * cellData->bufferCount, normals, GL_STATIC_DRAW_ARB ); +// glBufferDataARB( GL_ARRAY_BUFFER_ARB, sizeof(Vec3f) * +// cellData->bufferCount, normals, GL_STATIC_DRAW_ARB ); // glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0); // // vboCache.hasBuiltVBOs = true; // // mapSurfaceVBOCache[cellData->uniqueId] = vboCache; // -// // don't need the data in computer RAM anymore its in the GPU now -// cellData->texCoords.clear(); -// cellData->texCoordsSurface.clear(); -// cellData->vertices.clear(); +// // don't need the data in computer RAM anymore its in the GPU +// now cellData->texCoords.clear(); +// cellData->texCoordsSurface.clear(); cellData->vertices.clear(); // cellData->normals.clear(); // } // // return &mapSurfaceVBOCache[cellData->uniqueId]; -//} +// } void Renderer::ReleaseSurfaceVBOs() { - for(std::map::iterator iterFind = mapSurfaceVBOCache.begin(); - iterFind != mapSurfaceVBOCache.end(); ++iterFind) { - - VisibleQuadContainerVBOCache &item = iterFind->second; - if(item.hasBuiltVBOs == true) { - glDeleteBuffersARB( 1, (GLuint*)&item.m_nVBOVertices ); // Get A Valid Name - glDeleteBuffersARB( 1, (GLuint*)&item.m_nVBOFowTexCoords ); // Get A Valid Name - glDeleteBuffersARB( 1, (GLuint*)&item.m_nVBOSurfaceTexCoords ); // Get A Valid Name - glDeleteBuffersARB( 1, (GLuint*)&item.m_nVBONormals ); // Get A Valid Name - //glDeleteBuffersARB( 1, &item.m_nVBOIndexes ); // Get A Valid Name - } - } + for (std::map::iterator iterFind = + mapSurfaceVBOCache.begin(); + iterFind != mapSurfaceVBOCache.end(); ++iterFind) { + + VisibleQuadContainerVBOCache &item = iterFind->second; + if (item.hasBuiltVBOs == true) { + glDeleteBuffersARB(1, (GLuint *)&item.m_nVBOVertices); // Get A Valid Name + glDeleteBuffersARB( + 1, (GLuint *)&item.m_nVBOFowTexCoords); // Get A Valid Name + glDeleteBuffersARB( + 1, (GLuint *)&item.m_nVBOSurfaceTexCoords); // Get A Valid Name + glDeleteBuffersARB(1, (GLuint *)&item.m_nVBONormals); // Get A Valid Name + // glDeleteBuffersARB( 1, &item.m_nVBOIndexes ); + // // Get A Valid Name + } + } - mapSurfaceVBOCache.clear(); + mapSurfaceVBOCache.clear(); } Renderer::MapRenderer::Layer::~Layer() { - if(vbo_vertices) glDeleteBuffersARB(1,&vbo_vertices); - if(vbo_normals) glDeleteBuffersARB(1,&vbo_normals); - if(vbo_fowTexCoords) glDeleteBuffersARB(1,&vbo_fowTexCoords); - if(vbo_surfTexCoords) glDeleteBuffersARB(1,&vbo_surfTexCoords); - if(vbo_indices) glDeleteBuffersARB(1,&vbo_indices); - -} - -template void _loadVBO(GLuint &vbo,std::vector buf,int target=GL_ARRAY_BUFFER_ARB) { - assert(buf.size()); - if(true /* vbo enabled? */) { - glGenBuffersARB(1,&vbo); - assert(vbo); - glBindBufferARB(target,vbo); - glBufferDataARB(target,sizeof(T)*buf.size(),&buf[0],GL_STATIC_DRAW_ARB); - glBindBufferARB(target,0); - assertGl(); - buf.clear(); - } + if (vbo_vertices) + glDeleteBuffersARB(1, &vbo_vertices); + if (vbo_normals) + glDeleteBuffersARB(1, &vbo_normals); + if (vbo_fowTexCoords) + glDeleteBuffersARB(1, &vbo_fowTexCoords); + if (vbo_surfTexCoords) + glDeleteBuffersARB(1, &vbo_surfTexCoords); + if (vbo_indices) + glDeleteBuffersARB(1, &vbo_indices); +} + +template +void _loadVBO(GLuint &vbo, std::vector buf, + int target = GL_ARRAY_BUFFER_ARB) { + assert(buf.size()); + if (true /* vbo enabled? */) { + glGenBuffersARB(1, &vbo); + assert(vbo); + glBindBufferARB(target, vbo); + glBufferDataARB(target, sizeof(T) * buf.size(), &buf[0], + GL_STATIC_DRAW_ARB); + glBindBufferARB(target, 0); + assertGl(); + buf.clear(); + } } void Renderer::MapRenderer::Layer::load_vbos(bool vboEnabled) { - indexCount = (int)indices.size(); - if(vboEnabled) { - _loadVBO(vbo_vertices,vertices); - _loadVBO(vbo_normals,normals); - _loadVBO(vbo_fowTexCoords,fowTexCoords); - _loadVBO(vbo_surfTexCoords,surfTexCoords); - - _loadVBO(vbo_indices,indices,GL_ELEMENT_ARRAY_BUFFER_ARB); - } - else { - vbo_vertices = 0; - vbo_normals = 0; - vbo_fowTexCoords = 0; - vbo_surfTexCoords = 0; - vbo_indices = 0; - } -} - -void Renderer::MapRenderer::loadVisibleLayers(float coordStep,VisibleQuadContainerCache &qCache) { - int totalCellCount = 0; - // we create a layer for each visible texture in the map - for(int visibleIndex = 0; - visibleIndex < (int)qCache.visibleScaledCellList.size(); ++visibleIndex) { - Vec2i &pos = qCache.visibleScaledCellList[visibleIndex]; - - totalCellCount++; - - SurfaceCell *tc00= map->getSurfaceCell(pos.x, pos.y); - SurfaceCell *tc10= map->getSurfaceCell(pos.x+1, pos.y); - SurfaceCell *tc01= map->getSurfaceCell(pos.x, pos.y+1); - SurfaceCell *tc11= map->getSurfaceCell(pos.x+1, pos.y+1); - - const Vec2f &surfCoord= tc00->getSurfTexCoord(); - - SurfaceCell *tc[4] = { - tc00, - tc10, - tc01, - tc11 - }; - int textureHandle = static_cast(tc[0]->getSurfaceTexture())->getHandle(); - string texturePath = static_cast(tc[0]->getSurfaceTexture())->getPath(); - //int32 textureCRC = CalculatePixelsCRC(static_cast(tc[0]->getSurfaceTexture())); - Layer* layer = NULL; - for(Layers::iterator it= layers.begin(); it!= layers.end(); ++it) { - if((*it)->textureHandle == textureHandle) { - //if((*it)->texturePath == texturePath) { - //if((*it)->textureCRC == textureCRC) { - layer = *it; - break; - } - } - if(!layer) { - layer = new Layer(textureHandle); - layer->texturePath = texturePath; - //layer->textureCRC = textureCRC; - layers.push_back(layer); - - //printf("Ading new unique texture [%s]\n",texturePath.c_str()); - } - // we'll be super-lazy and re-emit all four corners just because its easier - int index[4]; - int loopIndexes[4] = { 2,0,3,1 }; - for(int i=0; i < 4; i++) { - index[i] = (int)layer->vertices.size(); - SurfaceCell *corner = tc[loopIndexes[i]]; - - layer->vertices.push_back(corner->getVertex()); - layer->normals.push_back(corner->getNormal()); - layer->fowTexCoords.push_back(corner->getFowTexCoord()); - } - - layer->surfTexCoords.push_back(Vec2f(surfCoord.x, surfCoord.y + coordStep)); - layer->surfTexCoords.push_back(Vec2f(surfCoord.x, surfCoord.y)); - layer->surfTexCoords.push_back(Vec2f(surfCoord.x+coordStep, surfCoord.y+coordStep)); - layer->surfTexCoords.push_back(Vec2f(surfCoord.x+coordStep, surfCoord.y)); - - // and make two triangles (no strip, we may be disjoint) - layer->indices.push_back(index[0]); - layer->indices.push_back(index[1]); - layer->indices.push_back(index[2]); - layer->indices.push_back(index[1]); - layer->indices.push_back(index[3]); - layer->indices.push_back(index[2]); - - } - // turn them into vbos (actually this method will just calc the index count) - for(Layers::iterator layer= layers.begin(); layer!= layers.end(); ++layer){ - (*layer)->load_vbos(false); - } - - //printf("Total # of layers for this map = %d totalCellCount = %d overall render reduction ratio = %d times\n",layers.size(),totalCellCount,(totalCellCount / layers.size())); + indexCount = (int)indices.size(); + if (vboEnabled) { + _loadVBO(vbo_vertices, vertices); + _loadVBO(vbo_normals, normals); + _loadVBO(vbo_fowTexCoords, fowTexCoords); + _loadVBO(vbo_surfTexCoords, surfTexCoords); + + _loadVBO(vbo_indices, indices, GL_ELEMENT_ARRAY_BUFFER_ARB); + } else { + vbo_vertices = 0; + vbo_normals = 0; + vbo_fowTexCoords = 0; + vbo_surfTexCoords = 0; + vbo_indices = 0; + } +} + +void Renderer::MapRenderer::loadVisibleLayers( + float coordStep, VisibleQuadContainerCache &qCache) { + int totalCellCount = 0; + // we create a layer for each visible texture in the map + for (int visibleIndex = 0; + visibleIndex < (int)qCache.visibleScaledCellList.size(); + ++visibleIndex) { + Vec2i &pos = qCache.visibleScaledCellList[visibleIndex]; + + totalCellCount++; + + SurfaceCell *tc00 = map->getSurfaceCell(pos.x, pos.y); + SurfaceCell *tc10 = map->getSurfaceCell(pos.x + 1, pos.y); + SurfaceCell *tc01 = map->getSurfaceCell(pos.x, pos.y + 1); + SurfaceCell *tc11 = map->getSurfaceCell(pos.x + 1, pos.y + 1); + + const Vec2f &surfCoord = tc00->getSurfTexCoord(); + + SurfaceCell *tc[4] = {tc00, tc10, tc01, tc11}; + int textureHandle = + static_cast(tc[0]->getSurfaceTexture()) + ->getHandle(); + string texturePath = + static_cast(tc[0]->getSurfaceTexture())->getPath(); + // int32 textureCRC = CalculatePixelsCRC(static_cast(tc[0]->getSurfaceTexture())); + Layer *layer = NULL; + for (Layers::iterator it = layers.begin(); it != layers.end(); ++it) { + if ((*it)->textureHandle == textureHandle) { + // if((*it)->texturePath == texturePath) { + // if((*it)->textureCRC == textureCRC) { + layer = *it; + break; + } + } + if (!layer) { + layer = new Layer(textureHandle); + layer->texturePath = texturePath; + // layer->textureCRC = textureCRC; + layers.push_back(layer); + + // printf("Ading new unique texture [%s]\n",texturePath.c_str()); + } + // we'll be super-lazy and re-emit all four corners just because its easier + int index[4]; + int loopIndexes[4] = {2, 0, 3, 1}; + for (int i = 0; i < 4; i++) { + index[i] = (int)layer->vertices.size(); + SurfaceCell *corner = tc[loopIndexes[i]]; + + layer->vertices.push_back(corner->getVertex()); + layer->normals.push_back(corner->getNormal()); + layer->fowTexCoords.push_back(corner->getFowTexCoord()); + } + + layer->surfTexCoords.push_back(Vec2f(surfCoord.x, surfCoord.y + coordStep)); + layer->surfTexCoords.push_back(Vec2f(surfCoord.x, surfCoord.y)); + layer->surfTexCoords.push_back( + Vec2f(surfCoord.x + coordStep, surfCoord.y + coordStep)); + layer->surfTexCoords.push_back(Vec2f(surfCoord.x + coordStep, surfCoord.y)); + + // and make two triangles (no strip, we may be disjoint) + layer->indices.push_back(index[0]); + layer->indices.push_back(index[1]); + layer->indices.push_back(index[2]); + layer->indices.push_back(index[1]); + layer->indices.push_back(index[3]); + layer->indices.push_back(index[2]); + } + // turn them into vbos (actually this method will just calc the index count) + for (Layers::iterator layer = layers.begin(); layer != layers.end(); + ++layer) { + (*layer)->load_vbos(false); + } + + // printf("Total # of layers for this map = %d totalCellCount = %d overall + // render reduction ratio = %d + // times\n",layers.size(),totalCellCount,(totalCellCount / layers.size())); } void Renderer::MapRenderer::load(float coordStep) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - int totalCellCount = 0; - // we create a layer for each texture in the map - for(int y=0; ygetSurfaceH()-1; y++) { - for(int x=0; xgetSurfaceW()-1; x++) { - totalCellCount++; - - SurfaceCell *tc[4] = { - map->getSurfaceCell(x,y), - map->getSurfaceCell(x+1,y), - map->getSurfaceCell(x,y+1), - map->getSurfaceCell(x+1,y+1) - }; - int textureHandle = static_cast(tc[0]->getSurfaceTexture())->getHandle(); - string texturePath = static_cast(tc[0]->getSurfaceTexture())->getPath(); - //int32 textureCRC = CalculatePixelsCRC(static_cast(tc[0]->getSurfaceTexture())); - Layer* layer = NULL; - for(Layers::iterator it= layers.begin(); it!= layers.end(); ++it) { - if((*it)->textureHandle == textureHandle) { - //if((*it)->texturePath == texturePath) { - //if((*it)->textureCRC == textureCRC) { - layer = *it; - break; - } - } - if(!layer) { - layer = new Layer(textureHandle); - layer->texturePath = texturePath; - //layer->textureCRC = textureCRC; - layers.push_back(layer); - - //printf("Ading new unique texture [%s]\n",texturePath.c_str()); - } - // we'll be super-lazy and re-emit all four corners just because its easier - int index[4]; - int loopIndexes[4] = { 2,0,3,1 }; - for(int i=0; i < 4; i++) { - index[i] = (int)layer->vertices.size(); - SurfaceCell *corner = tc[loopIndexes[i]]; - layer->vertices.push_back(corner->getVertex()); - layer->normals.push_back(corner->getNormal()); - } - - // the texture coords are all on the current texture obviously - layer->fowTexCoords.push_back(tc[loopIndexes[0]]->getFowTexCoord()); - layer->fowTexCoords.push_back(tc[loopIndexes[1]]->getFowTexCoord()); - layer->fowTexCoords.push_back(tc[loopIndexes[2]]->getFowTexCoord()); - layer->fowTexCoords.push_back(tc[loopIndexes[3]]->getFowTexCoord()); - - layer->surfTexCoords.push_back(tc[0]->getSurfTexCoord()+Vec2f(0,coordStep)); - layer->surfTexCoords.push_back(tc[0]->getSurfTexCoord()+Vec2f(0,0)); - layer->surfTexCoords.push_back(tc[0]->getSurfTexCoord()+Vec2f(coordStep,coordStep)); - layer->surfTexCoords.push_back(tc[0]->getSurfTexCoord()+Vec2f(coordStep,0)); - - layer->cellToIndicesMap[Vec2i(x,y)] = (int)layer->indices.size(); - - // and make two triangles (no strip, we may be disjoint) - layer->indices.push_back(index[0]); - layer->indices.push_back(index[1]); - layer->indices.push_back(index[2]); - layer->indices.push_back(index[1]); - layer->indices.push_back(index[3]); - layer->indices.push_back(index[2]); - } - } - // turn them into vbos - for(Layers::iterator layer= layers.begin(); layer!= layers.end(); ++layer){ - (*layer)->load_vbos(true); - } - - //printf("Total # of layers for this map = %d totalCellCount = %d overall render reduction ratio = %d times\n",layers.size(),totalCellCount,(totalCellCount / layers.size())); -} - -template void* _bindVBO(GLuint vbo,std::vector &buf,int target=GL_ARRAY_BUFFER_ARB) { - void* result = NULL; - if(vbo) { - glBindBuffer(target,vbo); - } - else { - result = &buf[0]; - } - return result; + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + int totalCellCount = 0; + // we create a layer for each texture in the map + for (int y = 0; y < map->getSurfaceH() - 1; y++) { + for (int x = 0; x < map->getSurfaceW() - 1; x++) { + totalCellCount++; + + SurfaceCell *tc[4] = { + map->getSurfaceCell(x, y), map->getSurfaceCell(x + 1, y), + map->getSurfaceCell(x, y + 1), map->getSurfaceCell(x + 1, y + 1)}; + int textureHandle = + static_cast(tc[0]->getSurfaceTexture()) + ->getHandle(); + string texturePath = + static_cast(tc[0]->getSurfaceTexture()) + ->getPath(); + // int32 textureCRC = CalculatePixelsCRC(static_cast(tc[0]->getSurfaceTexture())); + Layer *layer = NULL; + for (Layers::iterator it = layers.begin(); it != layers.end(); ++it) { + if ((*it)->textureHandle == textureHandle) { + // if((*it)->texturePath == texturePath) { + // if((*it)->textureCRC == textureCRC) { + layer = *it; + break; + } + } + if (!layer) { + layer = new Layer(textureHandle); + layer->texturePath = texturePath; + // layer->textureCRC = textureCRC; + layers.push_back(layer); + + // printf("Ading new unique texture [%s]\n",texturePath.c_str()); + } + // we'll be super-lazy and re-emit all four corners just because its + // easier + int index[4]; + int loopIndexes[4] = {2, 0, 3, 1}; + for (int i = 0; i < 4; i++) { + index[i] = (int)layer->vertices.size(); + SurfaceCell *corner = tc[loopIndexes[i]]; + layer->vertices.push_back(corner->getVertex()); + layer->normals.push_back(corner->getNormal()); + } + + // the texture coords are all on the current texture obviously + layer->fowTexCoords.push_back(tc[loopIndexes[0]]->getFowTexCoord()); + layer->fowTexCoords.push_back(tc[loopIndexes[1]]->getFowTexCoord()); + layer->fowTexCoords.push_back(tc[loopIndexes[2]]->getFowTexCoord()); + layer->fowTexCoords.push_back(tc[loopIndexes[3]]->getFowTexCoord()); + + layer->surfTexCoords.push_back(tc[0]->getSurfTexCoord() + + Vec2f(0, coordStep)); + layer->surfTexCoords.push_back(tc[0]->getSurfTexCoord() + Vec2f(0, 0)); + layer->surfTexCoords.push_back(tc[0]->getSurfTexCoord() + + Vec2f(coordStep, coordStep)); + layer->surfTexCoords.push_back(tc[0]->getSurfTexCoord() + + Vec2f(coordStep, 0)); + + layer->cellToIndicesMap[Vec2i(x, y)] = (int)layer->indices.size(); + + // and make two triangles (no strip, we may be disjoint) + layer->indices.push_back(index[0]); + layer->indices.push_back(index[1]); + layer->indices.push_back(index[2]); + layer->indices.push_back(index[1]); + layer->indices.push_back(index[3]); + layer->indices.push_back(index[2]); + } + } + // turn them into vbos + for (Layers::iterator layer = layers.begin(); layer != layers.end(); + ++layer) { + (*layer)->load_vbos(true); + } + + // printf("Total # of layers for this map = %d totalCellCount = %d overall + // render reduction ratio = %d + // times\n",layers.size(),totalCellCount,(totalCellCount / layers.size())); +} + +template +void *_bindVBO(GLuint vbo, std::vector &buf, + int target = GL_ARRAY_BUFFER_ARB) { + void *result = NULL; + if (vbo) { + glBindBuffer(target, vbo); + } else { + result = &buf[0]; + } + return result; } void Renderer::MapRenderer::Layer::renderVisibleLayer() { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - //glBindTexture(GL_TEXTURE_2D, static_cast(fowTex)->getHandle()); - glClientActiveTexture(Renderer::fowTexUnit); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - glTexCoordPointer(2, GL_FLOAT, 0,&fowTexCoords[0]); + // glBindTexture(GL_TEXTURE_2D, static_cast(fowTex)->getHandle()); + glClientActiveTexture(Renderer::fowTexUnit); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + glTexCoordPointer(2, GL_FLOAT, 0, &fowTexCoords[0]); - glBindTexture(GL_TEXTURE_2D, textureHandle); - glClientActiveTexture(Renderer::baseTexUnit); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - glTexCoordPointer(2, GL_FLOAT, 0, &surfTexCoords[0]); + glBindTexture(GL_TEXTURE_2D, textureHandle); + glClientActiveTexture(Renderer::baseTexUnit); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + glTexCoordPointer(2, GL_FLOAT, 0, &surfTexCoords[0]); - glVertexPointer(3, GL_FLOAT, 0, &vertices[0]); - glNormalPointer(GL_FLOAT, 0, &normals[0]); + glVertexPointer(3, GL_FLOAT, 0, &vertices[0]); + glNormalPointer(GL_FLOAT, 0, &normals[0]); - //glDrawArrays(GL_TRIANGLE_STRIP, 0, vertices.size()); - //unsigned short faceIndices[4] = {0, 1, 2, 3}; - //glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_SHORT, &faceIndices[0]); - glDrawElements(GL_TRIANGLES,indexCount,GL_UNSIGNED_INT,&indices[0]); + // glDrawArrays(GL_TRIANGLE_STRIP, 0, vertices.size()); + // unsigned short faceIndices[4] = {0, 1, 2, 3}; + // glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_SHORT, &faceIndices[0]); + glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, &indices[0]); - glClientActiveTexture(Renderer::fowTexUnit); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - glClientActiveTexture(Renderer::baseTexUnit); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); + glClientActiveTexture(Renderer::fowTexUnit); + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + glClientActiveTexture(Renderer::baseTexUnit); + glDisableClientState(GL_TEXTURE_COORD_ARRAY); } void Renderer::MapRenderer::Layer::render(VisibleQuadContainerCache &qCache) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + // const bool renderOnlyVisibleQuad = true; + // + // if(renderOnlyVisibleQuad == true) { + vector> rowsToRender; + + if (rowsToRenderCache.find(qCache.lastVisibleQuad) != + rowsToRenderCache.end()) { + rowsToRender = rowsToRenderCache[qCache.lastVisibleQuad]; + } else { + int startIndex = -1; + int lastValidIndex = -1; + + for (int visibleIndex = 0; + visibleIndex < (int)qCache.visibleScaledCellList.size(); + ++visibleIndex) { + Vec2i &pos = qCache.visibleScaledCellList[visibleIndex]; + + if (cellToIndicesMap.find(pos) != cellToIndicesMap.end()) { + // printf("Layer Render, visibleindex = %d pos [%s] + // cellToIndicesMap[pos] = %d lastValidIndex = + // %d\n",visibleIndex,pos.getString().c_str(),cellToIndicesMap[pos],lastValidIndex); + + if (startIndex < 0 || cellToIndicesMap[pos] == lastValidIndex + 6) { + lastValidIndex = cellToIndicesMap[pos]; + if (startIndex < 0) { + startIndex = lastValidIndex; + } + } else if (startIndex >= 0) { + rowsToRender.push_back(make_pair(startIndex, lastValidIndex)); + + lastValidIndex = cellToIndicesMap[pos]; + startIndex = lastValidIndex; + } + } + } + if (startIndex >= 0) { + rowsToRender.push_back(make_pair(startIndex, lastValidIndex)); + } -// const bool renderOnlyVisibleQuad = true; -// -// if(renderOnlyVisibleQuad == true) { - vector > rowsToRender; - - if(rowsToRenderCache.find(qCache.lastVisibleQuad) != rowsToRenderCache.end()) { - rowsToRender = rowsToRenderCache[qCache.lastVisibleQuad]; - } - else { - int startIndex = -1; - int lastValidIndex = -1; - - for(int visibleIndex = 0; - visibleIndex < (int)qCache.visibleScaledCellList.size(); ++visibleIndex) { - Vec2i &pos = qCache.visibleScaledCellList[visibleIndex]; - - if(cellToIndicesMap.find(pos) != cellToIndicesMap.end()) { - //printf("Layer Render, visibleindex = %d pos [%s] cellToIndicesMap[pos] = %d lastValidIndex = %d\n",visibleIndex,pos.getString().c_str(),cellToIndicesMap[pos],lastValidIndex); - - if(startIndex < 0 || cellToIndicesMap[pos] == lastValidIndex + 6) { - lastValidIndex = cellToIndicesMap[pos]; - if(startIndex < 0) { - startIndex = lastValidIndex; - } - } - else if(startIndex >= 0) { - rowsToRender.push_back(make_pair(startIndex,lastValidIndex)); - - lastValidIndex = cellToIndicesMap[pos]; - startIndex = lastValidIndex; - } - } - } - if(startIndex >= 0) { - rowsToRender.push_back(make_pair(startIndex,lastValidIndex)); - } - - rowsToRenderCache[qCache.lastVisibleQuad] = rowsToRender; - } - - if(rowsToRender.empty() == false) { - //printf("Layer has %d rows in visible quad, visible quad has %d cells\n",rowsToRender.size(),qCache.visibleScaledCellList.size()); - - glVertexPointer(3,GL_FLOAT,0,_bindVBO(vbo_vertices,vertices)); - glNormalPointer(GL_FLOAT,0,_bindVBO(vbo_normals,normals)); - - glClientActiveTexture(Renderer::fowTexUnit); - glTexCoordPointer(2,GL_FLOAT,0,_bindVBO(vbo_fowTexCoords,fowTexCoords)); - - glClientActiveTexture(Renderer::baseTexUnit); - glBindTexture(GL_TEXTURE_2D,textureHandle); - glTexCoordPointer(2,GL_FLOAT,0,_bindVBO(vbo_surfTexCoords,surfTexCoords)); - - for(unsigned int i = 0; i < rowsToRender.size(); ++i) { - //glDrawElements(GL_TRIANGLES,indexCount,GL_UNSIGNED_INT,_bindVBO(vbo_indices,indices,GL_ELEMENT_ARRAY_BUFFER_ARB)); - glDrawRangeElements(GL_TRIANGLES,rowsToRender[i].first,rowsToRender[i].second,indexCount,GL_UNSIGNED_INT,_bindVBO(vbo_indices,indices,GL_ELEMENT_ARRAY_BUFFER_ARB)); - } - } -// } -// else { -// glVertexPointer(3,GL_FLOAT,0,_bindVBO(vbo_vertices,vertices)); -// glNormalPointer(GL_FLOAT,0,_bindVBO(vbo_normals,normals)); -// -// glClientActiveTexture(Renderer::fowTexUnit); -// glTexCoordPointer(2,GL_FLOAT,0,_bindVBO(vbo_fowTexCoords,fowTexCoords)); -// -// glClientActiveTexture(Renderer::baseTexUnit); -// glBindTexture(GL_TEXTURE_2D,textureHandle); -// glTexCoordPointer(2,GL_FLOAT,0,_bindVBO(vbo_surfTexCoords,surfTexCoords)); -// -// glDrawElements(GL_TRIANGLES,indexCount,GL_UNSIGNED_INT,_bindVBO(vbo_indices,indices,GL_ELEMENT_ARRAY_BUFFER_ARB)); -// } -} + rowsToRenderCache[qCache.lastVisibleQuad] = rowsToRender; + } -void Renderer::MapRenderer::renderVisibleLayers(const Map* map,float coordStep,VisibleQuadContainerCache &qCache) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - if(map != this->map) { - //printf("New Map loading\n"); - destroy(); // clear any previous map data - this->map = map; - loadVisibleLayers(coordStep,qCache); - } - else if(lastVisibleQuad != qCache.lastVisibleQuad) { - //printf("New Visible Quad loading\n"); - destroy(); // clear any previous map data - this->map = map; - loadVisibleLayers(coordStep,qCache); - } - - lastVisibleQuad = qCache.lastVisibleQuad; - //printf("About to render %d layers\n",layers.size()); - - glClientActiveTexture(fowTexUnit); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - glClientActiveTexture(baseTexUnit); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - glEnableClientState(GL_VERTEX_ARRAY); - glEnableClientState(GL_NORMAL_ARRAY); - for(Layers::iterator layer= layers.begin(); layer!= layers.end(); ++layer) - (*layer)->renderVisibleLayer(); - glDisableClientState(GL_VERTEX_ARRAY); - glBindBuffer(GL_ARRAY_BUFFER_ARB,0); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB,0); - glDisableClientState(GL_NORMAL_ARRAY); - glClientActiveTexture(fowTexUnit); - glBindTexture(GL_TEXTURE_2D,0); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - glClientActiveTexture(baseTexUnit); - glBindTexture(GL_TEXTURE_2D,0); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - assertGl(); -} + if (rowsToRender.empty() == false) { + // printf("Layer has %d rows in visible quad, visible quad has %d + // cells\n",rowsToRender.size(),qCache.visibleScaledCellList.size()); -void Renderer::MapRenderer::render(const Map* map,float coordStep,VisibleQuadContainerCache &qCache) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - if(map != this->map) { - destroy(); // clear any previous map data - this->map = map; - load(coordStep); - } - - //printf("About to render %d layers\n",layers.size()); - - glClientActiveTexture(fowTexUnit); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - glClientActiveTexture(baseTexUnit); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - glEnableClientState(GL_VERTEX_ARRAY); - glEnableClientState(GL_NORMAL_ARRAY); - for(Layers::iterator layer= layers.begin(); layer!= layers.end(); ++layer) - (*layer)->render(qCache); - glDisableClientState(GL_VERTEX_ARRAY); - glBindBuffer(GL_ARRAY_BUFFER_ARB,0); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB,0); - glDisableClientState(GL_NORMAL_ARRAY); - glClientActiveTexture(fowTexUnit); - glBindTexture(GL_TEXTURE_2D,0); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - glClientActiveTexture(baseTexUnit); - glBindTexture(GL_TEXTURE_2D,0); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - assertGl(); + glVertexPointer(3, GL_FLOAT, 0, _bindVBO(vbo_vertices, vertices)); + glNormalPointer(GL_FLOAT, 0, _bindVBO(vbo_normals, normals)); + + glClientActiveTexture(Renderer::fowTexUnit); + glTexCoordPointer(2, GL_FLOAT, 0, _bindVBO(vbo_fowTexCoords, fowTexCoords)); + + glClientActiveTexture(Renderer::baseTexUnit); + glBindTexture(GL_TEXTURE_2D, textureHandle); + glTexCoordPointer(2, GL_FLOAT, 0, + _bindVBO(vbo_surfTexCoords, surfTexCoords)); + + for (unsigned int i = 0; i < rowsToRender.size(); ++i) { + // glDrawElements(GL_TRIANGLES,indexCount,GL_UNSIGNED_INT,_bindVBO(vbo_indices,indices,GL_ELEMENT_ARRAY_BUFFER_ARB)); + glDrawRangeElements( + GL_TRIANGLES, rowsToRender[i].first, rowsToRender[i].second, + indexCount, GL_UNSIGNED_INT, + _bindVBO(vbo_indices, indices, GL_ELEMENT_ARRAY_BUFFER_ARB)); + } + } + // } + // else { + // glVertexPointer(3,GL_FLOAT,0,_bindVBO(vbo_vertices,vertices)); + // glNormalPointer(GL_FLOAT,0,_bindVBO(vbo_normals,normals)); + // + // glClientActiveTexture(Renderer::fowTexUnit); + // glTexCoordPointer(2,GL_FLOAT,0,_bindVBO(vbo_fowTexCoords,fowTexCoords)); + // + // glClientActiveTexture(Renderer::baseTexUnit); + // glBindTexture(GL_TEXTURE_2D,textureHandle); + // glTexCoordPointer(2,GL_FLOAT,0,_bindVBO(vbo_surfTexCoords,surfTexCoords)); + // + // glDrawElements(GL_TRIANGLES,indexCount,GL_UNSIGNED_INT,_bindVBO(vbo_indices,indices,GL_ELEMENT_ARRAY_BUFFER_ARB)); + // } +} + +void Renderer::MapRenderer::renderVisibleLayers( + const Map *map, float coordStep, VisibleQuadContainerCache &qCache) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + if (map != this->map) { + // printf("New Map loading\n"); + destroy(); // clear any previous map data + this->map = map; + loadVisibleLayers(coordStep, qCache); + } else if (lastVisibleQuad != qCache.lastVisibleQuad) { + // printf("New Visible Quad loading\n"); + destroy(); // clear any previous map data + this->map = map; + loadVisibleLayers(coordStep, qCache); + } + + lastVisibleQuad = qCache.lastVisibleQuad; + // printf("About to render %d layers\n",layers.size()); + + glClientActiveTexture(fowTexUnit); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + glClientActiveTexture(baseTexUnit); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + glEnableClientState(GL_VERTEX_ARRAY); + glEnableClientState(GL_NORMAL_ARRAY); + for (Layers::iterator layer = layers.begin(); layer != layers.end(); ++layer) + (*layer)->renderVisibleLayer(); + glDisableClientState(GL_VERTEX_ARRAY); + glBindBuffer(GL_ARRAY_BUFFER_ARB, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); + glDisableClientState(GL_NORMAL_ARRAY); + glClientActiveTexture(fowTexUnit); + glBindTexture(GL_TEXTURE_2D, 0); + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + glClientActiveTexture(baseTexUnit); + glBindTexture(GL_TEXTURE_2D, 0); + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + assertGl(); +} + +void Renderer::MapRenderer::render(const Map *map, float coordStep, + VisibleQuadContainerCache &qCache) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + if (map != this->map) { + destroy(); // clear any previous map data + this->map = map; + load(coordStep); + } + + // printf("About to render %d layers\n",layers.size()); + + glClientActiveTexture(fowTexUnit); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + glClientActiveTexture(baseTexUnit); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + glEnableClientState(GL_VERTEX_ARRAY); + glEnableClientState(GL_NORMAL_ARRAY); + for (Layers::iterator layer = layers.begin(); layer != layers.end(); ++layer) + (*layer)->render(qCache); + glDisableClientState(GL_VERTEX_ARRAY); + glBindBuffer(GL_ARRAY_BUFFER_ARB, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); + glDisableClientState(GL_NORMAL_ARRAY); + glClientActiveTexture(fowTexUnit); + glBindTexture(GL_TEXTURE_2D, 0); + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + glClientActiveTexture(baseTexUnit); + glBindTexture(GL_TEXTURE_2D, 0); + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + assertGl(); } void Renderer::MapRenderer::destroy() { - while(layers.empty() == false) { - delete layers.back(); - layers.pop_back(); - } - map = NULL; + while (layers.empty() == false) { + delete layers.back(); + layers.pop_back(); + } + map = NULL; } void Renderer::renderSurface(const int renderFps) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - IF_DEBUG_EDITION( - if (getDebugRenderer().willRenderSurface()) { - getDebugRenderer().renderSurface(visibleQuad / Map::cellScale); - } else { - ) + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + IF_DEBUG_EDITION( + if (getDebugRenderer().willRenderSurface()) { + getDebugRenderer().renderSurface(visibleQuad / Map::cellScale); + } else { + ) assertGl(); - const World *world= game->getWorld(); - const Map *map= world->getMap(); - float coordStep= world->getTileset()->getSurfaceAtlas()->getCoordStep(); - - const Texture2D *fowTex= world->getMinimap()->getFowTexture(); - if(fowTex == NULL) { - return; - } - - glPushAttrib(GL_LIGHTING_BIT | GL_ENABLE_BIT | GL_FOG_BIT | GL_TEXTURE_BIT); - - glEnable(GL_BLEND); - glEnable(GL_COLOR_MATERIAL); - glDisable(GL_ALPHA_TEST); - glEnable(GL_CULL_FACE); - - //fog of war tex unit - glActiveTexture(fowTexUnit); - glEnable(GL_TEXTURE_2D); - glBindTexture(GL_TEXTURE_2D, static_cast(fowTex)->getHandle()); - - glTexSubImage2D( - GL_TEXTURE_2D, 0, 0, 0, - fowTex->getPixmapConst()->getW(), fowTex->getPixmapConst()->getH(), - GL_ALPHA, GL_UNSIGNED_BYTE, fowTex->getPixmapConst()->getPixels()); - - if(shadowsOffDueToMinRender == false) { - //shadow texture - if(shadows == sProjected || shadows == sShadowMapping) { - glActiveTexture(shadowTexUnit); - glEnable(GL_TEXTURE_2D); - - glBindTexture(GL_TEXTURE_2D, shadowMapHandle); - - static_cast(modelRenderer)->setDuplicateTexCoords(true); - enableProjectiveTexturing(); - } - } - - const Rect2i mapBounds(0, 0, map->getSurfaceW()-1, map->getSurfaceH()-1); - - glActiveTexture(baseTexUnit); - - VisibleQuadContainerCache &qCache = getQuadCache(); - - bool useVBORendering = getVBOSupported(); - if(useVBORendering == true) { - VisibleQuadContainerCache &qCache = getQuadCache(); - //mapRenderer.render(map,coordStep,qCache); - mapRenderer.renderVisibleLayers(map,coordStep,qCache); - } - else if(qCache.visibleScaledCellList.empty() == false) { - - int lastTex=-1; - //int currTex=-1; - - //Quad2i snapshotOfvisibleQuad = visibleQuad; - - //bool useVertexArrayRendering = getVBOSupported(); - //bool useVertexArrayRendering = false; - //if(useVertexArrayRendering == false) { - //printf("\LEGACY qCache.visibleScaledCellList.size() = %d \n",qCache.visibleScaledCellList.size()); - - Vec2f texCoords[4]; - Vec2f texCoordsSurface[4]; - Vec3f vertices[4]; - Vec3f normals[4]; - glEnableClientState(GL_VERTEX_ARRAY); - glEnableClientState(GL_NORMAL_ARRAY); - - std::map uniqueVisibleTextures; - for(int visibleIndex = 0; - visibleIndex < (int)qCache.visibleScaledCellList.size(); ++visibleIndex) { - Vec2i &pos = qCache.visibleScaledCellList[visibleIndex]; - SurfaceCell *tc00= map->getSurfaceCell(pos.x, pos.y); - int cellTex= static_cast(tc00->getSurfaceTexture())->getHandle(); - - uniqueVisibleTextures[cellTex]++; - } - - //printf("Current renders = %d possible = %d\n",qCache.visibleScaledCellList.size(),uniqueVisibleTextures.size()); - - for(int visibleIndex = 0; - visibleIndex < (int)qCache.visibleScaledCellList.size(); ++visibleIndex) { - Vec2i &pos = qCache.visibleScaledCellList[visibleIndex]; - - SurfaceCell *tc00= map->getSurfaceCell(pos.x, pos.y); - SurfaceCell *tc10= map->getSurfaceCell(pos.x+1, pos.y); - SurfaceCell *tc01= map->getSurfaceCell(pos.x, pos.y+1); - SurfaceCell *tc11= map->getSurfaceCell(pos.x+1, pos.y+1); - - if(tc00 == NULL) { - throw megaglest_runtime_error("tc00 == NULL"); - } - if(tc10 == NULL) { - throw megaglest_runtime_error("tc10 == NULL"); - } - if(tc01 == NULL) { - throw megaglest_runtime_error("tc01 == NULL"); - } - if(tc11 == NULL) { - throw megaglest_runtime_error("tc11 == NULL"); - } - - triangleCount+= 2; - pointCount+= 4; - - //set texture - if(tc00->getSurfaceTexture() == NULL) { - throw megaglest_runtime_error("tc00->getSurfaceTexture() == NULL"); - } - int currTex= static_cast(tc00->getSurfaceTexture())->getHandle(); - if(currTex != lastTex) { - lastTex = currTex; - //glBindTexture(GL_TEXTURE_2D, lastTex); - } - - const Vec2f &surfCoord= tc00->getSurfTexCoord(); - - texCoords[0] = tc01->getFowTexCoord(); - texCoordsSurface[0] = Vec2f(surfCoord.x, surfCoord.y + coordStep); - vertices[0] = tc01->getVertex(); - normals[0] = tc01->getNormal();; - - texCoords[1] = tc00->getFowTexCoord(); - texCoordsSurface[1] = Vec2f(surfCoord.x, surfCoord.y); - vertices[1] = tc00->getVertex(); - normals[1] = tc00->getNormal(); - - texCoords[2] = tc11->getFowTexCoord(); - texCoordsSurface[2] = Vec2f(surfCoord.x+coordStep, surfCoord.y+coordStep); - vertices[2] = tc11->getVertex(); - normals[2] = tc11->getNormal(); - - texCoords[3] = tc10->getFowTexCoord(); - texCoordsSurface[3] = Vec2f(surfCoord.x+coordStep, surfCoord.y); - vertices[3] = tc10->getVertex(); - normals[3] = tc10->getNormal(); - - //glBindTexture(GL_TEXTURE_2D, static_cast(fowTex)->getHandle()); - glClientActiveTexture(fowTexUnit); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - glTexCoordPointer(2, GL_FLOAT, 0,&texCoords[0]); - - glBindTexture(GL_TEXTURE_2D, lastTex); - glClientActiveTexture(baseTexUnit); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - glTexCoordPointer(2, GL_FLOAT, 0, &texCoordsSurface[0]); - - glVertexPointer(3, GL_FLOAT, 0, &vertices[0]); - glNormalPointer(GL_FLOAT, 0, &normals[0]); - - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - //unsigned short faceIndices[4] = {0, 1, 2, 3}; - //glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_SHORT, &faceIndices[0]); - - glClientActiveTexture(fowTexUnit); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - glClientActiveTexture(baseTexUnit); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - -/* - glBegin(GL_TRIANGLE_STRIP); - - //draw quad using immediate mode - glMultiTexCoord2fv(fowTexUnit, tc01->getFowTexCoord().ptr()); - glMultiTexCoord2f(baseTexUnit, surfCoord.x, surfCoord.y + coordStep); - glNormal3fv(tc01->getNormal().ptr()); - glVertex3fv(tc01->getVertex().ptr()); - - glMultiTexCoord2fv(fowTexUnit, tc00->getFowTexCoord().ptr()); - glMultiTexCoord2f(baseTexUnit, surfCoord.x, surfCoord.y); - glNormal3fv(tc00->getNormal().ptr()); - glVertex3fv(tc00->getVertex().ptr()); - - glMultiTexCoord2fv(fowTexUnit, tc11->getFowTexCoord().ptr()); - glMultiTexCoord2f(baseTexUnit, surfCoord.x+coordStep, surfCoord.y+coordStep); - glNormal3fv(tc11->getNormal().ptr()); - glVertex3fv(tc11->getVertex().ptr()); - - glMultiTexCoord2fv(fowTexUnit, tc10->getFowTexCoord().ptr()); - glMultiTexCoord2f(baseTexUnit, surfCoord.x + coordStep, surfCoord.y); - glNormal3fv(tc10->getNormal().ptr()); - glVertex3fv(tc10->getVertex().ptr()); - - glEnd(); -*/ - } - - glDisableClientState(GL_NORMAL_ARRAY); - glDisableClientState(GL_VERTEX_ARRAY); + const World *world = game->getWorld(); + const Map *map = world->getMap(); + float coordStep = + world->getTileset()->getSurfaceAtlas()->getCoordStep(); -// } -// else { -// const bool useVBOs = false; -// const bool useSurfaceCache = false; -// -// std::vector surfaceData; -// bool recalcSurface = false; -// -// if(useSurfaceCache == true) { -// std::map > >::iterator iterFind = mapSurfaceData.find(snapshotOfvisibleQuad.getString()); -// if(iterFind == mapSurfaceData.end()) { -// recalcSurface = true; -// //printf("#1 Calculating surface for Rendering using VA's [%s]\n",snapshotOfvisibleQuad.getString().c_str()); -// } -///* -// else if(iterFind->second.first.getMillis() >= 250) { -// recalcSurface = true; -// mapSurfaceData.erase(snapshotOfvisibleQuad.getString()); -// //printf("#2 RE-Calculating surface for Rendering using VA's [%s]\n",snapshotOfvisibleQuad.getString().c_str()); -// } -//*/ -// } -// else { -// recalcSurface = true; -// } -// -// if(recalcSurface == true) { -// //printf("Calculating surface for Rendering using VA's [%s]\n",snapshotOfvisibleQuad.getString().c_str()); -// -// std::vector *surface = &surfaceData; -// if(useSurfaceCache == true) { -// std::pair > &surfaceCacheEntity = mapSurfaceData[snapshotOfvisibleQuad.getString()]; -// surface = &surfaceCacheEntity.second; -// //surface.reserve(qCache.visibleScaledCellList.size()); -// } -// surface->reserve(qCache.visibleScaledCellList.size()); -// -// int lastSurfaceDataIndex = -1; -// for(int visibleIndex = 0; -// visibleIndex < (int)qCache.visibleScaledCellList.size(); ++visibleIndex) { -// Vec2i &pos = qCache.visibleScaledCellList[visibleIndex]; -// -// SurfaceCell *tc00= map->getSurfaceCell(pos.x, pos.y); -// SurfaceCell *tc10= map->getSurfaceCell(pos.x+1, pos.y); -// SurfaceCell *tc01= map->getSurfaceCell(pos.x, pos.y+1); -// SurfaceCell *tc11= map->getSurfaceCell(pos.x+1, pos.y+1); -// -// if(tc00 == NULL) { -// throw megaglest_runtime_error("tc00 == NULL"); -// } -// if(tc10 == NULL) { -// throw megaglest_runtime_error("tc10 == NULL"); -// } -// if(tc01 == NULL) { -// throw megaglest_runtime_error("tc01 == NULL"); -// } -// if(tc11 == NULL) { -// throw megaglest_runtime_error("tc11 == NULL"); -// } -// -// triangleCount+= 2; -// pointCount+= 4; -// -// //set texture -// if(tc00->getSurfaceTexture() == NULL) { -// throw megaglest_runtime_error("tc00->getSurfaceTexture() == NULL"); -// } -// -// int surfaceDataIndex = -1; -// currTex= static_cast(tc00->getSurfaceTexture())->getHandle(); -// if(currTex != lastTex) { -// lastTex = currTex; -// } -// else { -// surfaceDataIndex = lastSurfaceDataIndex; -// } -// -// if(surfaceDataIndex < 0) { -// SurfaceData newData; -// newData.uniqueId = SurfaceData::nextUniqueId; -// SurfaceData::nextUniqueId++; -// newData.bufferCount=0; -// newData.textureHandle = currTex; -// surface->push_back(newData); -// -// surfaceDataIndex = (int)surface->size() - 1; -// } -// -// lastSurfaceDataIndex = surfaceDataIndex; -// -// SurfaceData *cellData = &(*surface)[surfaceDataIndex]; -// -// const Vec2f &surfCoord= tc00->getSurfTexCoord(); -// -// cellData->texCoords.push_back(tc01->getFowTexCoord()); -// cellData->texCoordsSurface.push_back(Vec2f(surfCoord.x, surfCoord.y + coordStep)); -// cellData->vertices.push_back(tc01->getVertex()); -// cellData->normals.push_back(tc01->getNormal()); -// cellData->bufferCount++; -// -// cellData->texCoords.push_back(tc00->getFowTexCoord()); -// cellData->texCoordsSurface.push_back(Vec2f(surfCoord.x, surfCoord.y)); -// cellData->vertices.push_back(tc00->getVertex()); -// cellData->normals.push_back(tc00->getNormal()); -// cellData->bufferCount++; -// -// cellData->texCoords.push_back(tc11->getFowTexCoord()); -// cellData->texCoordsSurface.push_back(Vec2f(surfCoord.x+coordStep, surfCoord.y+coordStep)); -// cellData->vertices.push_back(tc11->getVertex()); -// cellData->normals.push_back(tc11->getNormal()); -// cellData->bufferCount++; -// -// cellData->texCoords.push_back(tc10->getFowTexCoord()); -// cellData->texCoordsSurface.push_back(Vec2f(surfCoord.x+coordStep, surfCoord.y)); -// cellData->vertices.push_back(tc10->getVertex()); -// cellData->normals.push_back(tc10->getNormal()); -// cellData->bufferCount++; -// } -// } -// -// std::vector *surface = &surfaceData; -// if(useSurfaceCache == true) { -// std::pair > &surfaceCacheEntity = mapSurfaceData[snapshotOfvisibleQuad.getString()]; -// surface = &surfaceCacheEntity.second; -// } -// -// glEnableClientState(GL_VERTEX_ARRAY); -// glEnableClientState(GL_NORMAL_ARRAY); -// -// for(int i = 0; i < (int)surface->size(); ++i) { -// SurfaceData &data = (*surface)[i]; -// -// if(useVBOs == true) { -// VisibleQuadContainerVBOCache *vboCache = GetSurfaceVBOs(&data); -// -// //glBindTexture(GL_TEXTURE_2D, static_cast(fowTex)->getHandle()); -// glClientActiveTexture(fowTexUnit); -// glEnableClientState(GL_TEXTURE_COORD_ARRAY); -// -// glBindBufferARB( GL_ARRAY_BUFFER_ARB, vboCache->m_nVBOFowTexCoords); -// glTexCoordPointer(2, GL_FLOAT, 0,(char *) NULL); -// -// glBindTexture(GL_TEXTURE_2D, data.textureHandle); -// glClientActiveTexture(baseTexUnit); -// glEnableClientState(GL_TEXTURE_COORD_ARRAY); -// -// glBindBufferARB( GL_ARRAY_BUFFER_ARB, vboCache->m_nVBOSurfaceTexCoords); -// glTexCoordPointer(2, GL_FLOAT, 0, (char *) NULL); -// -// glBindBufferARB( GL_ARRAY_BUFFER_ARB, vboCache->m_nVBOVertices); -// glVertexPointer(3, GL_FLOAT, 0, (char *) NULL); -// -// glBindBufferARB( GL_ARRAY_BUFFER_ARB, vboCache->m_nVBONormals); -// glNormalPointer(GL_FLOAT, 0, (char *) NULL); -// -// glDrawArrays(GL_TRIANGLE_STRIP, 0, data.bufferCount); -// -// glBindBufferARB( GL_ARRAY_BUFFER_ARB, 0 ); -// -// glClientActiveTexture(fowTexUnit); -// glDisableClientState(GL_TEXTURE_COORD_ARRAY); -// glClientActiveTexture(baseTexUnit); -// glDisableClientState(GL_TEXTURE_COORD_ARRAY); -// -// } -// else { -// Vec2f *texCoords = &data.texCoords[0]; -// Vec2f *texCoordsSurface = &data.texCoordsSurface[0]; -// Vec3f *vertices = &data.vertices[0]; -// Vec3f *normals = &data.normals[0]; -// -// //glBindTexture(GL_TEXTURE_2D, static_cast(fowTex)->getHandle()); -// glClientActiveTexture(fowTexUnit); -// glEnableClientState(GL_TEXTURE_COORD_ARRAY); -// glTexCoordPointer(2, GL_FLOAT, 0,texCoords); -// -// glBindTexture(GL_TEXTURE_2D, data.textureHandle); -// glClientActiveTexture(baseTexUnit); -// glEnableClientState(GL_TEXTURE_COORD_ARRAY); -// glTexCoordPointer(2, GL_FLOAT, 0, texCoordsSurface); -// -// glVertexPointer(3, GL_FLOAT, 0, vertices); -// glNormalPointer(GL_FLOAT, 0, normals); -// -// glDrawArrays(GL_TRIANGLE_STRIP, 0, data.bufferCount); -// -// glClientActiveTexture(fowTexUnit); -// glDisableClientState(GL_TEXTURE_COORD_ARRAY); -// glClientActiveTexture(baseTexUnit); -// glDisableClientState(GL_TEXTURE_COORD_ARRAY); -// } -// } -// -// glDisableClientState(GL_NORMAL_ARRAY); -// glDisableClientState(GL_VERTEX_ARRAY); -// -// //printf("Surface Render before [%d] after [%d]\n",qCache.visibleScaledCellList.size(),surface.size()); -// } - } + const Texture2D *fowTex = world->getMinimap()->getFowTexture(); + if (fowTex == NULL) { + return; + } - //Restore - static_cast(modelRenderer)->setDuplicateTexCoords(false); + glPushAttrib(GL_LIGHTING_BIT | GL_ENABLE_BIT | GL_FOG_BIT | + GL_TEXTURE_BIT); + + glEnable(GL_BLEND); + glEnable(GL_COLOR_MATERIAL); + glDisable(GL_ALPHA_TEST); + glEnable(GL_CULL_FACE); + + // fog of war tex unit + glActiveTexture(fowTexUnit); + glEnable(GL_TEXTURE_2D); + glBindTexture(GL_TEXTURE_2D, + static_cast(fowTex)->getHandle()); + + glTexSubImage2D( + GL_TEXTURE_2D, 0, 0, 0, fowTex->getPixmapConst()->getW(), + fowTex->getPixmapConst()->getH(), GL_ALPHA, GL_UNSIGNED_BYTE, + fowTex->getPixmapConst()->getPixels()); + + if (shadowsOffDueToMinRender == false) { + // shadow texture + if (shadows == sProjected || shadows == sShadowMapping) { + glActiveTexture(shadowTexUnit); + glEnable(GL_TEXTURE_2D); + + glBindTexture(GL_TEXTURE_2D, shadowMapHandle); + + static_cast(modelRenderer) + ->setDuplicateTexCoords(true); + enableProjectiveTexturing(); + } + } - glDisable(GL_TEXTURE_2D); + const Rect2i mapBounds(0, 0, map->getSurfaceW() - 1, + map->getSurfaceH() - 1); + + glActiveTexture(baseTexUnit); + + VisibleQuadContainerCache &qCache = getQuadCache(); + + bool useVBORendering = getVBOSupported(); + if (useVBORendering == true) { + VisibleQuadContainerCache &qCache = getQuadCache(); + // mapRenderer.render(map,coordStep,qCache); + mapRenderer.renderVisibleLayers(map, coordStep, qCache); + } else if (qCache.visibleScaledCellList.empty() == false) { + + int lastTex = -1; + // int currTex=-1; + + // Quad2i snapshotOfvisibleQuad = visibleQuad; + + // bool useVertexArrayRendering = getVBOSupported(); + // bool useVertexArrayRendering = false; + // if(useVertexArrayRendering == false) { + // printf("\LEGACY qCache.visibleScaledCellList.size() = %d + // \n",qCache.visibleScaledCellList.size()); + + Vec2f texCoords[4]; + Vec2f texCoordsSurface[4]; + Vec3f vertices[4]; + Vec3f normals[4]; + glEnableClientState(GL_VERTEX_ARRAY); + glEnableClientState(GL_NORMAL_ARRAY); + + std::map uniqueVisibleTextures; + for (int visibleIndex = 0; + visibleIndex < (int)qCache.visibleScaledCellList.size(); + ++visibleIndex) { + Vec2i &pos = qCache.visibleScaledCellList[visibleIndex]; + SurfaceCell *tc00 = map->getSurfaceCell(pos.x, pos.y); + int cellTex = + static_cast(tc00->getSurfaceTexture()) + ->getHandle(); + + uniqueVisibleTextures[cellTex]++; + } + + // printf("Current renders = %d possible = + // %d\n",qCache.visibleScaledCellList.size(),uniqueVisibleTextures.size()); + + for (int visibleIndex = 0; + visibleIndex < (int)qCache.visibleScaledCellList.size(); + ++visibleIndex) { + Vec2i &pos = qCache.visibleScaledCellList[visibleIndex]; + + SurfaceCell *tc00 = map->getSurfaceCell(pos.x, pos.y); + SurfaceCell *tc10 = map->getSurfaceCell(pos.x + 1, pos.y); + SurfaceCell *tc01 = map->getSurfaceCell(pos.x, pos.y + 1); + SurfaceCell *tc11 = map->getSurfaceCell(pos.x + 1, pos.y + 1); + + if (tc00 == NULL) { + throw megaglest_runtime_error("tc00 == NULL"); + } + if (tc10 == NULL) { + throw megaglest_runtime_error("tc10 == NULL"); + } + if (tc01 == NULL) { + throw megaglest_runtime_error("tc01 == NULL"); + } + if (tc11 == NULL) { + throw megaglest_runtime_error("tc11 == NULL"); + } - glPopAttrib(); + triangleCount += 2; + pointCount += 4; - //assert - GLenum glresult = glGetError(); //remove when first mtex problem solved - if(glresult) { - assertGl(); - } - assertGl(); + // set texture + if (tc00->getSurfaceTexture() == NULL) { + throw megaglest_runtime_error( + "tc00->getSurfaceTexture() == NULL"); + } + int currTex = + static_cast(tc00->getSurfaceTexture()) + ->getHandle(); + if (currTex != lastTex) { + lastTex = currTex; + // glBindTexture(GL_TEXTURE_2D, lastTex); + } - IF_DEBUG_EDITION( - } // end else, if not renderering debug textures instead of regular terrain - getDebugRenderer().renderEffects(visibleQuad / Map::cellScale); - ) -} + const Vec2f &surfCoord = tc00->getSurfTexCoord(); + + texCoords[0] = tc01->getFowTexCoord(); + texCoordsSurface[0] = Vec2f(surfCoord.x, surfCoord.y + coordStep); + vertices[0] = tc01->getVertex(); + normals[0] = tc01->getNormal(); + ; + + texCoords[1] = tc00->getFowTexCoord(); + texCoordsSurface[1] = Vec2f(surfCoord.x, surfCoord.y); + vertices[1] = tc00->getVertex(); + normals[1] = tc00->getNormal(); + + texCoords[2] = tc11->getFowTexCoord(); + texCoordsSurface[2] = + Vec2f(surfCoord.x + coordStep, surfCoord.y + coordStep); + vertices[2] = tc11->getVertex(); + normals[2] = tc11->getNormal(); + + texCoords[3] = tc10->getFowTexCoord(); + texCoordsSurface[3] = Vec2f(surfCoord.x + coordStep, surfCoord.y); + vertices[3] = tc10->getVertex(); + normals[3] = tc10->getNormal(); + + // glBindTexture(GL_TEXTURE_2D, static_cast(fowTex)->getHandle()); + glClientActiveTexture(fowTexUnit); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + glTexCoordPointer(2, GL_FLOAT, 0, &texCoords[0]); + + glBindTexture(GL_TEXTURE_2D, lastTex); + glClientActiveTexture(baseTexUnit); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + glTexCoordPointer(2, GL_FLOAT, 0, &texCoordsSurface[0]); + + glVertexPointer(3, GL_FLOAT, 0, &vertices[0]); + glNormalPointer(GL_FLOAT, 0, &normals[0]); + + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + // unsigned short faceIndices[4] = {0, 1, 2, 3}; + // glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_SHORT, + // &faceIndices[0]); + + glClientActiveTexture(fowTexUnit); + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + glClientActiveTexture(baseTexUnit); + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + + /* + glBegin(GL_TRIANGLE_STRIP); + + //draw quad using immediate mode + glMultiTexCoord2fv(fowTexUnit, + tc01->getFowTexCoord().ptr()); glMultiTexCoord2f(baseTexUnit, + surfCoord.x, surfCoord.y + coordStep); + glNormal3fv(tc01->getNormal().ptr()); + glVertex3fv(tc01->getVertex().ptr()); + + glMultiTexCoord2fv(fowTexUnit, + tc00->getFowTexCoord().ptr()); glMultiTexCoord2f(baseTexUnit, + surfCoord.x, surfCoord.y); glNormal3fv(tc00->getNormal().ptr()); + glVertex3fv(tc00->getVertex().ptr()); + + glMultiTexCoord2fv(fowTexUnit, + tc11->getFowTexCoord().ptr()); glMultiTexCoord2f(baseTexUnit, + surfCoord.x+coordStep, surfCoord.y+coordStep); + glNormal3fv(tc11->getNormal().ptr()); + glVertex3fv(tc11->getVertex().ptr()); + + glMultiTexCoord2fv(fowTexUnit, + tc10->getFowTexCoord().ptr()); glMultiTexCoord2f(baseTexUnit, + surfCoord.x + coordStep, surfCoord.y); + glNormal3fv(tc10->getNormal().ptr()); + glVertex3fv(tc10->getVertex().ptr()); + + glEnd(); + */ + } + + glDisableClientState(GL_NORMAL_ARRAY); + glDisableClientState(GL_VERTEX_ARRAY); + + // } + // else { + // const bool useVBOs = false; + // const bool useSurfaceCache = false; + // + // std::vector surfaceData; + // bool recalcSurface = false; + // + // if(useSurfaceCache == true) { + // std::map > >::iterator iterFind = + // mapSurfaceData.find(snapshotOfvisibleQuad.getString()); + // if(iterFind + //== mapSurfaceData.end()) { recalcSurface = + //true; + // //printf("#1 Calculating surface for + //Rendering using VA's + // [%s]\n",snapshotOfvisibleQuad.getString().c_str()); + // } + ///* + // else if(iterFind->second.first.getMillis() >= + //250) { recalcSurface = true; + // mapSurfaceData.erase(snapshotOfvisibleQuad.getString()); + // //printf("#2 RE-Calculating surface + //for Rendering using VA's + //[%s]\n",snapshotOfvisibleQuad.getString().c_str()); + // } + //*/ + // } + // else { + // recalcSurface = true; + // } + // + // if(recalcSurface == true) { + // //printf("Calculating surface for Rendering + //using VA's [%s]\n",snapshotOfvisibleQuad.getString().c_str()); + // + // std::vector *surface = + //&surfaceData; if(useSurfaceCache == true) { + //std::pair > &surfaceCacheEntity = + // mapSurfaceData[snapshotOfvisibleQuad.getString()]; + // surface = &surfaceCacheEntity.second; + // //surface.reserve(qCache.visibleScaledCellList.size()); + // } + // surface->reserve(qCache.visibleScaledCellList.size()); + // + // int lastSurfaceDataIndex = -1; + // for(int visibleIndex = 0; + // visibleIndex < + //(int)qCache.visibleScaledCellList.size(); ++visibleIndex) { + //Vec2i &pos = qCache.visibleScaledCellList[visibleIndex]; + // + // SurfaceCell *tc00= + //map->getSurfaceCell(pos.x, + // pos.y); SurfaceCell *tc10= + // map->getSurfaceCell(pos.x+1, pos.y); SurfaceCell *tc01= + //map->getSurfaceCell(pos.x, + // pos.y+1); SurfaceCell *tc11= + // map->getSurfaceCell(pos.x+1, pos.y+1); + // + // if(tc00 == NULL) { + // throw megaglest_runtime_error("tc00 + //== NULL"); + // } + // if(tc10 == NULL) { + // throw megaglest_runtime_error("tc10 + //== NULL"); + // } + // if(tc01 == NULL) { + // throw megaglest_runtime_error("tc01 + //== NULL"); + // } + // if(tc11 == NULL) { + // throw megaglest_runtime_error("tc11 + //== NULL"); + // } + // + // triangleCount+= 2; + // pointCount+= 4; + // + // //set texture + // if(tc00->getSurfaceTexture() == + //NULL) { throw + //megaglest_runtime_error("tc00->getSurfaceTexture() == NULL"); + // } + // + // int surfaceDataIndex = -1; + // currTex= static_cast(tc00->getSurfaceTexture())->getHandle(); + // if(currTex != + // lastTex) { lastTex = + // currTex; + // } + // else { + // surfaceDataIndex = + // lastSurfaceDataIndex; + // } + // + // if(surfaceDataIndex < 0) { + // SurfaceData newData; + // newData.uniqueId = + // SurfaceData::nextUniqueId; + // SurfaceData::nextUniqueId++; newData.bufferCount=0; + // newData.textureHandle = + // currTex; + // surface->push_back(newData); + // + // surfaceDataIndex = (int)surface->size() + //- 1; + // } + // + // lastSurfaceDataIndex = + // surfaceDataIndex; + // + // SurfaceData *cellData = + //&(*surface)[surfaceDataIndex]; + // + // const Vec2f &surfCoord= + // tc00->getSurfTexCoord(); + // + // cellData->texCoords.push_back(tc01->getFowTexCoord()); + // cellData->texCoordsSurface.push_back(Vec2f(surfCoord.x, + // surfCoord.y + coordStep)); + // cellData->vertices.push_back(tc01->getVertex()); + // cellData->normals.push_back(tc01->getNormal()); + // cellData->bufferCount++; + // + // cellData->texCoords.push_back(tc00->getFowTexCoord()); + // cellData->texCoordsSurface.push_back(Vec2f(surfCoord.x, + // surfCoord.y)); + // cellData->vertices.push_back(tc00->getVertex()); + // cellData->normals.push_back(tc00->getNormal()); + // cellData->bufferCount++; + // + // cellData->texCoords.push_back(tc11->getFowTexCoord()); + // cellData->texCoordsSurface.push_back(Vec2f(surfCoord.x+coordStep, + // surfCoord.y+coordStep)); + // cellData->vertices.push_back(tc11->getVertex()); + // cellData->normals.push_back(tc11->getNormal()); + // cellData->bufferCount++; + // + // cellData->texCoords.push_back(tc10->getFowTexCoord()); + // cellData->texCoordsSurface.push_back(Vec2f(surfCoord.x+coordStep, + // surfCoord.y)); + // cellData->vertices.push_back(tc10->getVertex()); + // cellData->normals.push_back(tc10->getNormal()); + // cellData->bufferCount++; + // } + // } + // + // std::vector *surface = &surfaceData; + // if(useSurfaceCache == true) { + // std::pair > + //&surfaceCacheEntity = + // mapSurfaceData[snapshotOfvisibleQuad.getString()]; + // surface = &surfaceCacheEntity.second; + // } + // + // glEnableClientState(GL_VERTEX_ARRAY); + // glEnableClientState(GL_NORMAL_ARRAY); + // + // for(int i = 0; i < (int)surface->size(); ++i) { + // SurfaceData &data = (*surface)[i]; + // + // if(useVBOs == true) { + // VisibleQuadContainerVBOCache *vboCache + //= GetSurfaceVBOs(&data); + // + // //glBindTexture(GL_TEXTURE_2D, + //static_cast(fowTex)->getHandle()); + // glClientActiveTexture(fowTexUnit); + // glEnableClientState(GL_TEXTURE_COORD_ARRAY); + // + // glBindBufferARB( + //GL_ARRAY_BUFFER_ARB, vboCache->m_nVBOFowTexCoords); + // glTexCoordPointer(2, GL_FLOAT, 0,(char *) NULL); + // + // glBindTexture(GL_TEXTURE_2D, + // data.textureHandle); + // glClientActiveTexture(baseTexUnit); + // glEnableClientState(GL_TEXTURE_COORD_ARRAY); + // + // glBindBufferARB( + //GL_ARRAY_BUFFER_ARB, vboCache->m_nVBOSurfaceTexCoords); + // glTexCoordPointer(2, GL_FLOAT, 0, (char *) NULL); + // + // glBindBufferARB( + //GL_ARRAY_BUFFER_ARB, vboCache->m_nVBOVertices); + // glVertexPointer(3, GL_FLOAT, 0, (char *) NULL); + // + // glBindBufferARB( + //GL_ARRAY_BUFFER_ARB, vboCache->m_nVBONormals); + // glNormalPointer(GL_FLOAT, 0, (char *) NULL); + // + // glDrawArrays(GL_TRIANGLE_STRIP, + //0, data.bufferCount); + // + // glBindBufferARB( GL_ARRAY_BUFFER_ARB, + //0 + //); + // + // glClientActiveTexture(fowTexUnit); + // glDisableClientState(GL_TEXTURE_COORD_ARRAY); + // glClientActiveTexture(baseTexUnit); + // glDisableClientState(GL_TEXTURE_COORD_ARRAY); + // + // } + // else { + // Vec2f *texCoords = + //&data.texCoords[0]; Vec2f *texCoordsSurface + //= + //&data.texCoordsSurface[0]; Vec3f *vertices + //= + //&data.vertices[0]; Vec3f *normals + //= &data.normals[0]; + // + // //glBindTexture(GL_TEXTURE_2D, + //static_cast(fowTex)->getHandle()); + // glClientActiveTexture(fowTexUnit); + // glEnableClientState(GL_TEXTURE_COORD_ARRAY); + // glTexCoordPointer(2, GL_FLOAT, + // 0,texCoords); + // + // glBindTexture(GL_TEXTURE_2D, + // data.textureHandle); + // glClientActiveTexture(baseTexUnit); + // glEnableClientState(GL_TEXTURE_COORD_ARRAY); + // glTexCoordPointer(2, GL_FLOAT, + //0, texCoordsSurface); + // + // glVertexPointer(3, GL_FLOAT, 0, + // vertices); glNormalPointer(GL_FLOAT, 0, + // normals); + // + // glDrawArrays(GL_TRIANGLE_STRIP, + //0, data.bufferCount); + // + // glClientActiveTexture(fowTexUnit); + // glDisableClientState(GL_TEXTURE_COORD_ARRAY); + // glClientActiveTexture(baseTexUnit); + // glDisableClientState(GL_TEXTURE_COORD_ARRAY); + // } + // } + // + // glDisableClientState(GL_NORMAL_ARRAY); + // glDisableClientState(GL_VERTEX_ARRAY); + // + // //printf("Surface Render before [%d] after + //[%d]\n",qCache.visibleScaledCellList.size(),surface.size()); + // } + } -void Renderer::renderObjects(const int renderFps) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } + // Restore + static_cast(modelRenderer) + ->setDuplicateTexCoords(false); - const World *world= game->getWorld(); - //const Map *map= world->getMap(); + glDisable(GL_TEXTURE_2D); - Config &config= Config::getInstance(); - int tilesetObjectsToAnimate=config.getInt("AnimatedTilesetObjects","-1"); + glPopAttrib(); - assertGl(); + // assert + GLenum glresult = glGetError(); // remove when first mtex problem solved + if (glresult) { + assertGl(); + } + assertGl(); - const Texture2D *fowTex = world->getMinimap()->getFowTexture(); - const Pixmap2D *fowTexPixmap = fowTex->getPixmapConst(); - Vec3f baseFogColor = world->getTileset()->getFogColor() * world->getTimeFlow()->computeLightColor(); + IF_DEBUG_EDITION( + } // end else, if not renderering debug textures instead of regular + // terrain + getDebugRenderer() + .renderEffects(visibleQuad / Map::cellScale);) +} - bool modelRenderStarted = false; +void Renderer::renderObjects(const int renderFps) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - VisibleQuadContainerCache &qCache = getQuadCache(); + const World *world = game->getWorld(); + // const Map *map= world->getMap(); - // for(int visibleIndex = 0; - // visibleIndex < qCache.visibleObjectList.size(); ++visibleIndex) { - // render from last to first object so animated objects which are on bottom of screen are - // rendered first which looks better for limited number of animated tileset objects - for(int visibleIndex = (int)qCache.visibleObjectList.size()-1; - visibleIndex >= 0 ; --visibleIndex) { - Object *o = qCache.visibleObjectList[visibleIndex]; + Config &config = Config::getInstance(); + int tilesetObjectsToAnimate = config.getInt("AnimatedTilesetObjects", "-1"); - Model *objModel= o->getModelPtr(); - //objModel->updateInterpolationData(o->getAnimProgress(), true); - const Vec3f v= o->getConstPos(); + assertGl(); - if(modelRenderStarted == false) { - modelRenderStarted = true; + const Texture2D *fowTex = world->getMinimap()->getFowTexture(); + const Pixmap2D *fowTexPixmap = fowTex->getPixmapConst(); + Vec3f baseFogColor = world->getTileset()->getFogColor() * + world->getTimeFlow()->computeLightColor(); - glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_FOG_BIT | GL_LIGHTING_BIT | GL_TEXTURE_BIT); + bool modelRenderStarted = false; - if(shadowsOffDueToMinRender == false && - shadows == sShadowMapping) { - glActiveTexture(shadowTexUnit); - glEnable(GL_TEXTURE_2D); + VisibleQuadContainerCache &qCache = getQuadCache(); - glBindTexture(GL_TEXTURE_2D, shadowMapHandle); + // for(int visibleIndex = 0; + // visibleIndex < qCache.visibleObjectList.size(); + //++visibleIndex) + //{ + // render from last to first object so animated objects which are on bottom of + // screen are rendered first which looks better for limited number of animated + // tileset objects + for (int visibleIndex = (int)qCache.visibleObjectList.size() - 1; + visibleIndex >= 0; --visibleIndex) { + Object *o = qCache.visibleObjectList[visibleIndex]; - static_cast(modelRenderer)->setDuplicateTexCoords(true); - enableProjectiveTexturing(); - } + Model *objModel = o->getModelPtr(); + // objModel->updateInterpolationData(o->getAnimProgress(), true); + const Vec3f v = o->getConstPos(); - glActiveTexture(baseTexUnit); - glEnable(GL_COLOR_MATERIAL); - glAlphaFunc(GL_GREATER, 0.5f); + if (modelRenderStarted == false) { + modelRenderStarted = true; - modelRenderer->begin(true, true, false, false); - } - //ambient and diffuse color is taken from cell color + glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_FOG_BIT | + GL_LIGHTING_BIT | GL_TEXTURE_BIT); - float fowFactor= fowTexPixmap->getPixelf(o->getMapPos().x / Map::cellScale, o->getMapPos().y / Map::cellScale); - Vec4f color= Vec4f(Vec3f(fowFactor), 1.f); - glColor4fv(color.ptr()); - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, (color * ambFactor).ptr()); - glFogfv(GL_FOG_COLOR, (baseFogColor * fowFactor).ptr()); + if (shadowsOffDueToMinRender == false && shadows == sShadowMapping) { + glActiveTexture(shadowTexUnit); + glEnable(GL_TEXTURE_2D); - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - glTranslatef(v.x, v.y, v.z); - glRotatef(o->getRotation(), 0.f, 1.f, 0.f); + glBindTexture(GL_TEXTURE_2D, shadowMapHandle); - //We use OpenGL Lights so no manual action is needed here. In fact this call did bad things on lighting big rocks for example - // if(o->getRotation() != 0.0) { - // setupLightingForRotatedModel(); - // } + static_cast(modelRenderer) + ->setDuplicateTexCoords(true); + enableProjectiveTexturing(); + } - //objModel->updateInterpolationData(0.f, true); - //if(this->gameCamera->getPos().dist(o->getPos()) <= SKIP_INTERPOLATION_DISTANCE) { + glActiveTexture(baseTexUnit); + glEnable(GL_COLOR_MATERIAL); + glAlphaFunc(GL_GREATER, 0.5f); + modelRenderer->begin(true, true, false, false); + } + // ambient and diffuse color is taken from cell color - if (tilesetObjectsToAnimate == -1) { - objModel->updateInterpolationData(o->getAnimProgress(), true); - } else if (tilesetObjectsToAnimate > 0 && o->isAnimated()) { - tilesetObjectsToAnimate--; - objModel->updateInterpolationData(o->getAnimProgress(), true); - } else { - objModel->updateInterpolationData(0, true); - } + float fowFactor = fowTexPixmap->getPixelf( + o->getMapPos().x / Map::cellScale, o->getMapPos().y / Map::cellScale); + Vec4f color = Vec4f(Vec3f(fowFactor), 1.f); + glColor4fv(color.ptr()); + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, (color * ambFactor).ptr()); + glFogfv(GL_FOG_COLOR, (baseFogColor * fowFactor).ptr()); -// objModel->updateInterpolationData(o->getAnimProgress(), true); - //} - modelRenderer->render(objModel); + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glTranslatef(v.x, v.y, v.z); + glRotatef(o->getRotation(), 0.f, 1.f, 0.f); + + // We use OpenGL Lights so no manual action is needed here. In fact this + // call did bad things on lighting big rocks for example + // if(o->getRotation() + //!= 0.0) { setupLightingForRotatedModel(); + // } + + // objModel->updateInterpolationData(0.f, true); + // if(this->gameCamera->getPos().dist(o->getPos()) <= + // SKIP_INTERPOLATION_DISTANCE) { + + if (tilesetObjectsToAnimate == -1) { + objModel->updateInterpolationData(o->getAnimProgress(), true); + } else if (tilesetObjectsToAnimate > 0 && o->isAnimated()) { + tilesetObjectsToAnimate--; + objModel->updateInterpolationData(o->getAnimProgress(), true); + } else { + objModel->updateInterpolationData(0, true); + } - triangleCount+= objModel->getTriangleCount(); - pointCount+= objModel->getVertexCount(); + // objModel->updateInterpolationData(o->getAnimProgress(), true); + //} + modelRenderer->render(objModel); - glPopMatrix(); - } + triangleCount += objModel->getTriangleCount(); + pointCount += objModel->getVertexCount(); - if(modelRenderStarted == true) { - modelRenderer->end(); - glPopAttrib(); - } + glPopMatrix(); + } - //restore - static_cast(modelRenderer)->setDuplicateTexCoords(true); + if (modelRenderStarted == true) { + modelRenderer->end(); + glPopAttrib(); + } - assertGl(); + // restore + static_cast(modelRenderer)->setDuplicateTexCoords(true); + + assertGl(); } void Renderer::renderWater() { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - const World *world= game->getWorld(); - const Map *map= world->getMap(); - - const Texture2D *fowTex= world->getMinimap()->getFowTexture(); - if(fowTex == NULL) { - return; - } - - float waterAnim= world->getWaterEffects()->getAmin(); - - //assert - assertGl(); + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - glPushAttrib(GL_TEXTURE_BIT | GL_ENABLE_BIT | GL_CURRENT_BIT); + const World *world = game->getWorld(); + const Map *map = world->getMap(); - //water texture nit - glDisable(GL_TEXTURE_2D); - - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - - if(textures3D) { - Texture3D *waterTex= world->getTileset()->getWaterTex(); - if(waterTex == NULL) { - throw megaglest_runtime_error("waterTex == NULL"); - } - glEnable(GL_TEXTURE_3D); - glBindTexture(GL_TEXTURE_3D, static_cast(waterTex)->getHandle()); - } - else{ - glEnable(GL_COLOR_MATERIAL); - glColor4f(0.5f, 0.5f, 1.0f, 0.5f); - glBindTexture(GL_TEXTURE_3D, 0); - } - - assertGl(); - - //fog of War texture Unit - //const Texture2D *fowTex= world->getMinimap()->getFowTexture(); - glActiveTexture(fowTexUnit); - glEnable(GL_TEXTURE_2D); - glBindTexture(GL_TEXTURE_2D, static_cast(fowTex)->getHandle()); - glActiveTexture(baseTexUnit); + const Texture2D *fowTex = world->getMinimap()->getFowTexture(); + if (fowTex == NULL) { + return; + } - assertGl(); - - int thisTeamIndex= world->getThisTeamIndex(); - bool cellExplored = world->showWorldForPlayer(world->getThisFactionIndex()); - bool closed= false; + float waterAnim = world->getWaterEffects()->getAmin(); - Rect2i boundingRect= visibleQuad.computeBoundingRect(); - Rect2i scaledRect= boundingRect/Map::cellScale; - scaledRect.clamp(0, 0, map->getSurfaceW()-1, map->getSurfaceH()-1); + // assert + assertGl(); - float waterLevel= world->getMap()->getWaterLevel(); - for(int j=scaledRect.p[0].y; jgetSurfaceCell(i, j); - SurfaceCell *tc1= map->getSurfaceCell(i, j+1); - if(tc0 == NULL) { - throw megaglest_runtime_error("tc0 == NULL"); - } - if(tc1 == NULL) { - throw megaglest_runtime_error("tc1 == NULL"); - } - - if(cellExplored == false) { - cellExplored = (tc0->isExplored(thisTeamIndex) || tc1->isExplored(thisTeamIndex)); - } + // water texture nit + glDisable(GL_TEXTURE_2D); - if(cellExplored == true && tc0->getNearSubmerged()) { - glNormal3f(0.f, 1.f, 0.f); - closed= false; - - triangleCount+= 2; - pointCount+= 2; - - //vertex 1 - glMaterialfv( - GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, - computeWaterColor(waterLevel, tc1->getHeight()).ptr()); - glMultiTexCoord2fv(GL_TEXTURE1, tc1->getFowTexCoord().ptr()); - glTexCoord3f(i, 1.f, waterAnim); - glVertex3f( - static_cast(i)*Map::mapScale, - waterLevel, - static_cast(j+1)*Map::mapScale); - - //vertex 2 - glMaterialfv( - GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, - computeWaterColor(waterLevel, tc0->getHeight()).ptr()); - glMultiTexCoord2fv(GL_TEXTURE1, tc0->getFowTexCoord().ptr()); - glTexCoord3f(i, 0.f, waterAnim); - glVertex3f( - static_cast(i)*Map::mapScale, - waterLevel, - static_cast(j)*Map::mapScale); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - } - else{ - if(closed == false) { - pointCount+= 2; - - //vertex 1 - glMaterialfv( - GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, - computeWaterColor(waterLevel, tc1->getHeight()).ptr()); - glMultiTexCoord2fv(GL_TEXTURE1, tc1->getFowTexCoord().ptr()); - glTexCoord3f(i, 1.f, waterAnim); - glVertex3f( - static_cast(i)*Map::mapScale, - waterLevel, - static_cast(j+1)*Map::mapScale); - - //vertex 2 - glMaterialfv( - GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, - computeWaterColor(waterLevel, tc0->getHeight()).ptr()); - glMultiTexCoord2fv(GL_TEXTURE1, tc0->getFowTexCoord().ptr()); - glTexCoord3f(i, 0.f, waterAnim); - glVertex3f( - static_cast(i)*Map::mapScale, - waterLevel, - static_cast(j)*Map::mapScale); - - glEnd(); - glBegin(GL_TRIANGLE_STRIP); - closed= true; - } - } + if (textures3D) { + Texture3D *waterTex = world->getTileset()->getWaterTex(); + if (waterTex == NULL) { + throw megaglest_runtime_error("waterTex == NULL"); + } + glEnable(GL_TEXTURE_3D); + glBindTexture(GL_TEXTURE_3D, + static_cast(waterTex)->getHandle()); + } else { + glEnable(GL_COLOR_MATERIAL); + glColor4f(0.5f, 0.5f, 1.0f, 0.5f); + glBindTexture(GL_TEXTURE_3D, 0); + } + + assertGl(); + + // fog of War texture Unit + // const Texture2D *fowTex= world->getMinimap()->getFowTexture(); + glActiveTexture(fowTexUnit); + glEnable(GL_TEXTURE_2D); + glBindTexture(GL_TEXTURE_2D, + static_cast(fowTex)->getHandle()); + glActiveTexture(baseTexUnit); + + assertGl(); + + int thisTeamIndex = world->getThisTeamIndex(); + bool cellExplored = world->showWorldForPlayer(world->getThisFactionIndex()); + bool closed = false; + + Rect2i boundingRect = visibleQuad.computeBoundingRect(); + Rect2i scaledRect = boundingRect / Map::cellScale; + scaledRect.clamp(0, 0, map->getSurfaceW() - 1, map->getSurfaceH() - 1); + + float waterLevel = world->getMap()->getWaterLevel(); + for (int j = scaledRect.p[0].y; j < scaledRect.p[1].y; ++j) { + glBegin(GL_TRIANGLE_STRIP); + + for (int i = scaledRect.p[0].x; i <= scaledRect.p[1].x; ++i) { + SurfaceCell *tc0 = map->getSurfaceCell(i, j); + SurfaceCell *tc1 = map->getSurfaceCell(i, j + 1); + if (tc0 == NULL) { + throw megaglest_runtime_error("tc0 == NULL"); + } + if (tc1 == NULL) { + throw megaglest_runtime_error("tc1 == NULL"); + } + + if (cellExplored == false) { + cellExplored = + (tc0->isExplored(thisTeamIndex) || tc1->isExplored(thisTeamIndex)); + } + + if (cellExplored == true && tc0->getNearSubmerged()) { + glNormal3f(0.f, 1.f, 0.f); + closed = false; + + triangleCount += 2; + pointCount += 2; + + // vertex 1 + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, + computeWaterColor(waterLevel, tc1->getHeight()).ptr()); + glMultiTexCoord2fv(GL_TEXTURE1, tc1->getFowTexCoord().ptr()); + glTexCoord3f(i, 1.f, waterAnim); + glVertex3f(static_cast(i) * Map::mapScale, waterLevel, + static_cast(j + 1) * Map::mapScale); + + // vertex 2 + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, + computeWaterColor(waterLevel, tc0->getHeight()).ptr()); + glMultiTexCoord2fv(GL_TEXTURE1, tc0->getFowTexCoord().ptr()); + glTexCoord3f(i, 0.f, waterAnim); + glVertex3f(static_cast(i) * Map::mapScale, waterLevel, + static_cast(j) * Map::mapScale); + + } else { + if (closed == false) { + pointCount += 2; + + // vertex 1 + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, + computeWaterColor(waterLevel, tc1->getHeight()).ptr()); + glMultiTexCoord2fv(GL_TEXTURE1, tc1->getFowTexCoord().ptr()); + glTexCoord3f(i, 1.f, waterAnim); + glVertex3f(static_cast(i) * Map::mapScale, waterLevel, + static_cast(j + 1) * Map::mapScale); + + // vertex 2 + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, + computeWaterColor(waterLevel, tc0->getHeight()).ptr()); + glMultiTexCoord2fv(GL_TEXTURE1, tc0->getFowTexCoord().ptr()); + glTexCoord3f(i, 0.f, waterAnim); + glVertex3f(static_cast(i) * Map::mapScale, waterLevel, + static_cast(j) * Map::mapScale); + + glEnd(); + glBegin(GL_TRIANGLE_STRIP); + closed = true; } - glEnd(); + } } + glEnd(); + } - //restore - glPopAttrib(); - - assertGl(); -} + // restore + glPopAttrib(); -void Renderer::renderTeamColorCircle(){ - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - VisibleQuadContainerCache &qCache = getQuadCache(); - if(qCache.visibleQuadUnitList.empty() == false) { - - glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT); - glDisable(GL_LIGHTING); - glDisable(GL_TEXTURE_2D); - glDepthFunc(GL_ALWAYS); - glDisable(GL_STENCIL_TEST); - glDisable(GL_CULL_FACE); - glEnable(GL_BLEND); - glLineWidth(2.f); - - for(int visibleUnitIndex = 0; - visibleUnitIndex < (int)qCache.visibleQuadUnitList.size(); ++visibleUnitIndex) { - Unit *unit = qCache.visibleQuadUnitList[visibleUnitIndex]; - Vec3f currVec= unit->getCurrVectorFlat(); - Vec3f color=unit->getFaction()->getTexture()->getPixmapConst()->getPixel3f(0,0); - glColor4f(color.x, color.y, color.z, 0.7f); - renderSelectionCircle(currVec, unit->getType()->getSize(), 0.8f, 0.05f); - } - glPopAttrib(); - } -} - -void Renderer::renderSpecialHighlightUnits(std::map unitHighlightList) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true || unitHighlightList.empty() == true) { - return; - } - - VisibleQuadContainerCache &qCache = getQuadCache(); - if(qCache.visibleQuadUnitList.empty() == false) { - - glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT); - glDisable(GL_LIGHTING); - glDisable(GL_TEXTURE_2D); - glDepthFunc(GL_ALWAYS); - glDisable(GL_STENCIL_TEST); - glDisable(GL_CULL_FACE); - glEnable(GL_BLEND); - glLineWidth(2.f); - - for(int visibleUnitIndex = 0; - visibleUnitIndex < (int)qCache.visibleQuadUnitList.size(); ++visibleUnitIndex) { - Unit *unit = qCache.visibleQuadUnitList[visibleUnitIndex]; - - std::map::iterator iterFindSpecialUnit = unitHighlightList.find(unit->getId()); - if(iterFindSpecialUnit != unitHighlightList.end()) { - Vec3f color=unit->getFaction()->getTexture()->getPixmapConst()->getPixel3f(0,0); - float radius = 1.0f; - float thickness = 0.1f; - float alpha = 0.65f; - - HighlightSpecialUnitInfo &specialInfo = iterFindSpecialUnit->second; - if(specialInfo.color.x >= 0) { - color.x = specialInfo.color.x; - color.y = specialInfo.color.y; - color.z = specialInfo.color.z; - } - if(specialInfo.color.w >= 0) { - alpha = specialInfo.color.w; - } - if(specialInfo.radius > 0) { - radius = specialInfo.radius; - } - if(specialInfo.thickness > 0) { - thickness = specialInfo.thickness; - } - - glColor4f(color.x, color.y, color.z, alpha); - - Vec3f currVec= unit->getCurrVectorFlat(); - renderSelectionCircle(currVec, unit->getType()->getSize(), radius, thickness); - } - } - glPopAttrib(); - } -} - -void Renderer::renderTeamColorPlane(){ - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - VisibleQuadContainerCache &qCache = getQuadCache(); - if(qCache.visibleQuadUnitList.empty() == false){ - glPushAttrib(GL_ENABLE_BIT); - glDisable(GL_LIGHTING); - glEnable(GL_TEXTURE_2D); - glEnable(GL_BLEND); - glEnable(GL_COLOR_MATERIAL); - const Texture2D *texture=CoreData::getInstance().getTeamColorTexture(); - for(int visibleUnitIndex = 0; - visibleUnitIndex < (int)qCache.visibleQuadUnitList.size(); ++visibleUnitIndex){ - Unit *unit = qCache.visibleQuadUnitList[visibleUnitIndex]; - if( unit->isAlive()){ - Vec3f currVec= unit->getCurrVectorFlat(); - renderTeamColorEffect(currVec,visibleUnitIndex,unit->getType()->getSize(), - unit->getFaction()->getTexture()->getPixmapConst()->getPixel3f(0,0),texture); - } - } - glDisable(GL_COLOR_MATERIAL); - glPopAttrib(); - } -} - -void Renderer::renderGhostModel(const UnitType *building, const Vec2i pos,CardinalDir facing, Vec4f *forceColor) { - //const UnitType *building= gui->getBuilding(); - //const Vec2i &pos= gui->getPosObjWorld(); - - //const Gui *gui= game->getGui(); - //const Mouse3d *mouse3d= gui->getMouse3d(); - const Map *map= game->getWorld()->getMap(); - if(map == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s] Line: %d map == NULL",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - throw megaglest_runtime_error(szBuf); - } - - glPushMatrix(); - Vec3f pos3f= Vec3f(pos.x, map->getCell(pos)->getHeight(), pos.y); - - //selection building placement - float offset= building->getSize()/2.f-0.5f; - glTranslatef(pos3f.x+offset, pos3f.y, pos3f.z+offset); - - //choose color - Vec4f color; - if(forceColor != NULL) { - color = *forceColor; - } - else { - if(map->isFreeCells(pos, building->getSize(), fLand)) { - color= Vec4f(1.f, 1.f, 1.f, 0.5f); - } - else { -// Uint64 tc=game->getTickCount(); -// float red=0.49f+((tc%4*1.0f)/2); - color= Vec4f(1.0f, 0.f, 0.f, 0.5f); - } - } - - glColor4fv(color.ptr()); - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, color.ptr()); - Model *buildingModel= building->getFirstStOfClass(scStop)->getAnimation(); - - if(facing != CardinalDir::NORTH) { - float rotateAmount = facing * 90.f; - if(rotateAmount > 0) { - glRotatef(rotateAmount, 0.f, 1.f, 0.f); - } - } - - buildingModel->updateInterpolationData(0.f, false); - modelRenderer->render(buildingModel); - - glPopMatrix(); + assertGl(); } -void Renderer::renderUnits(bool airUnits, const int renderFps) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - //Unit *unit=NULL; - //const World *world= game->getWorld(); - MeshCallbackTeamColor meshCallbackTeamColor; - - //assert - assertGl(); +void Renderer::renderTeamColorCircle() { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - if(visibleFrameUnitList.empty() == false) { - visibleFrameUnitList.clear(); - //visibleFrameUnitListCameraKey = ""; - //if(visibleFrameUnitListCameraKey != game->getGameCamera()->getCameraMovementKey()) { - // worldToScreenPosCache.clear(); - //} - } - - VisibleQuadContainerCache &qCache = getQuadCache(); - if(qCache.visibleQuadUnitList.empty() == false) { - bool modelRenderStarted = false; - for(int visibleUnitIndex = 0; - visibleUnitIndex < (int)qCache.visibleQuadUnitList.size(); ++visibleUnitIndex) { - Unit *unit = qCache.visibleQuadUnitList[visibleUnitIndex]; - - if(( airUnits==false && unit->getType()->getField()==fAir) || ( airUnits==true && unit->getType()->getField()!=fAir)){ - continue; - } - meshCallbackTeamColor.setTeamTexture(unit->getFaction()->getTexture()); - - if(modelRenderStarted == false) { - modelRenderStarted = true; - - glPushAttrib(GL_ENABLE_BIT | GL_FOG_BIT | GL_LIGHTING_BIT | GL_TEXTURE_BIT); - glEnable(GL_COLOR_MATERIAL); - - if(!shadowsOffDueToMinRender) { - if(shadows == sShadowMapping) { - glActiveTexture(shadowTexUnit); - glEnable(GL_TEXTURE_2D); - - glBindTexture(GL_TEXTURE_2D, shadowMapHandle); - - static_cast(modelRenderer)->setDuplicateTexCoords(true); - enableProjectiveTexturing(); - } - } - glActiveTexture(baseTexUnit); - - modelRenderer->begin(true, true, true, false, &meshCallbackTeamColor); - } - - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - - //translate - Vec3f currVec= unit->getCurrVectorFlat(); - glTranslatef(currVec.x, currVec.y, currVec.z); - - //rotate - float zrot=unit->getRotationZ(); - float xrot=unit->getRotationX(); - if(zrot!=.0f){ - glRotatef(zrot, 0.f, 0.f, 1.f); - } - if(xrot!=.0f){ - glRotatef(xrot, 1.f, 0.f, 0.f); - } - glRotatef(unit->getRotation(), 0.f, 1.f, 0.f); - - //dead alpha - const SkillType *st= unit->getCurrSkill(); - if(st->getClass() == scDie && static_cast(st)->getFade()) { - float alpha= 1.0f - unit->getAnimProgressAsFloat(); - glDisable(GL_COLOR_MATERIAL); - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, Vec4f(1.0f, 1.0f, 1.0f, alpha).ptr()); - } - else { - glEnable(GL_COLOR_MATERIAL); - // we cut off a tiny bit here to avoid problems with fully transparent texture parts cutting units in background rendered later. - glAlphaFunc(GL_GREATER, 0.02f); - } - - //render - Model *model= unit->getCurrentModelPtr(); - //printf("Rendering model [%d - %s]\n[%s]\nCamera [%s]\nDistance: %f\n",unit->getId(),unit->getType()->getName().c_str(),unit->getCurrVector().getString().c_str(),this->gameCamera->getPos().getString().c_str(),this->gameCamera->getPos().dist(unit->getCurrVector())); - - //if(this->gameCamera->getPos().dist(unit->getCurrVector()) <= SKIP_INTERPOLATION_DISTANCE) { - model->updateInterpolationData(unit->getAnimProgressAsFloat(), unit->isAlive() && !unit->isAnimProgressBound()); - //} - - modelRenderer->render(model); - triangleCount+= model->getTriangleCount(); - pointCount+= model->getVertexCount(); - - glPopMatrix(); - unit->setVisible(true); - - if( showDebugUI == true && - (showDebugUILevel & debugui_unit_titles) == debugui_unit_titles) { - - unit->setScreenPos(computeScreenPosition(currVec)); - visibleFrameUnitList.push_back(unit); - visibleFrameUnitListCameraKey = game->getGameCamera()->getCameraMovementKey(); - } - } - - if(modelRenderStarted == true) { - modelRenderer->end(); - glPopAttrib(); - } - } - - //restore - static_cast(modelRenderer)->setDuplicateTexCoords(true); - - // reset alpha - glAlphaFunc(GL_GREATER, 0.0f); - //assert - assertGl(); + VisibleQuadContainerCache &qCache = getQuadCache(); + if (qCache.visibleQuadUnitList.empty() == false) { + glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT); + glDisable(GL_LIGHTING); + glDisable(GL_TEXTURE_2D); + glDepthFunc(GL_ALWAYS); + glDisable(GL_STENCIL_TEST); + glDisable(GL_CULL_FACE); + glEnable(GL_BLEND); + glLineWidth(2.f); + + for (int visibleUnitIndex = 0; + visibleUnitIndex < (int)qCache.visibleQuadUnitList.size(); + ++visibleUnitIndex) { + Unit *unit = qCache.visibleQuadUnitList[visibleUnitIndex]; + Vec3f currVec = unit->getCurrVectorFlat(); + Vec3f color = + unit->getFaction()->getTexture()->getPixmapConst()->getPixel3f(0, 0); + glColor4f(color.x, color.y, color.z, 0.7f); + renderSelectionCircle(currVec, unit->getType()->getSize(), 0.8f, 0.05f); + } + glPopAttrib(); + } } -void Renderer::renderUnitsToBuild(const int renderFps) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - //assert - assertGl(); - - VisibleQuadContainerCache &qCache = getQuadCache(); - if(qCache.visibleQuadUnitBuildList.empty() == false) { - - glMatrixMode(GL_MODELVIEW); - glPushAttrib(GL_CURRENT_BIT | GL_LIGHTING_BIT | GL_ENABLE_BIT | GL_DEPTH_BUFFER_BIT); - glEnable(GL_BLEND); - glDisable(GL_STENCIL_TEST); - glDepthFunc(GL_LESS); - glEnable(GL_COLOR_MATERIAL); - glDepthMask(GL_FALSE); - - modelRenderer->begin(true, true, false, false); - - for(int visibleUnitIndex = 0; - visibleUnitIndex < (int)qCache.visibleQuadUnitBuildList.size(); ++visibleUnitIndex) { - const UnitBuildInfo &buildUnit = qCache.visibleQuadUnitBuildList[visibleUnitIndex]; - //Vec4f modelColor= Vec4f(0.f, 1.f, 0.f, 0.5f); - const Vec3f teamColor = buildUnit.unit->getFaction()->getTexture()->getPixmapConst()->getPixel3f(0,0); - Vec4f modelColor= Vec4f(teamColor.x,teamColor.y,teamColor.z,0.4f); - renderGhostModel(buildUnit.buildUnit, buildUnit.pos, buildUnit.facing, &modelColor); - - //printf("Rendering to build unit index = %d\n",visibleUnitIndex); - } - - modelRenderer->end(); +void Renderer::renderSpecialHighlightUnits( + std::map unitHighlightList) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true || + unitHighlightList.empty() == true) { + return; + } - glDisable(GL_COLOR_MATERIAL); - glPopAttrib(); - } + VisibleQuadContainerCache &qCache = getQuadCache(); + if (qCache.visibleQuadUnitList.empty() == false) { - //assert - assertGl(); + glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT); + glDisable(GL_LIGHTING); + glDisable(GL_TEXTURE_2D); + glDepthFunc(GL_ALWAYS); + glDisable(GL_STENCIL_TEST); + glDisable(GL_CULL_FACE); + glEnable(GL_BLEND); + glLineWidth(2.f); + + for (int visibleUnitIndex = 0; + visibleUnitIndex < (int)qCache.visibleQuadUnitList.size(); + ++visibleUnitIndex) { + Unit *unit = qCache.visibleQuadUnitList[visibleUnitIndex]; + + std::map::iterator iterFindSpecialUnit = + unitHighlightList.find(unit->getId()); + if (iterFindSpecialUnit != unitHighlightList.end()) { + Vec3f color = + unit->getFaction()->getTexture()->getPixmapConst()->getPixel3f(0, + 0); + float radius = 1.0f; + float thickness = 0.1f; + float alpha = 0.65f; + + HighlightSpecialUnitInfo &specialInfo = iterFindSpecialUnit->second; + if (specialInfo.color.x >= 0) { + color.x = specialInfo.color.x; + color.y = specialInfo.color.y; + color.z = specialInfo.color.z; + } + if (specialInfo.color.w >= 0) { + alpha = specialInfo.color.w; + } + if (specialInfo.radius > 0) { + radius = specialInfo.radius; + } + if (specialInfo.thickness > 0) { + thickness = specialInfo.thickness; + } -} + glColor4f(color.x, color.y, color.z, alpha); -void Renderer::renderTeamColorEffect(Vec3f &v, int heigth, int size, Vec3f color, const Texture2D *texture) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - //GLUquadricObj *disc; - float halfSize=size; - //halfSize=halfSize; - float heigthoffset=0.5+heigth%25*0.004; - glPushMatrix(); - glBindTexture(GL_TEXTURE_2D, static_cast(texture)->getHandle()); - glColor4f(color.x, color.y, color.z, 1.0f); - glBegin(GL_TRIANGLE_STRIP); - glTexCoord2i(0, 1); - glVertex3f(v.x-halfSize,v.y+heigthoffset,v.z+halfSize); - glTexCoord2i(0, 0); - glVertex3f(v.x-halfSize,v.y+heigthoffset, v.z-halfSize); - glTexCoord2i(1, 1); - - glVertex3f(v.x+halfSize,v.y+heigthoffset, v.z+halfSize); - glTexCoord2i(1, 0); - glVertex3f(v.x+halfSize,v.y+heigthoffset, v.z-halfSize); - glEnd(); - glPopMatrix(); - -} - -void Renderer::renderMorphEffects(){ - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - VisibleQuadContainerCache &qCache = getQuadCache(); - if(qCache.visibleQuadUnitList.empty() == false) { - bool initialized=false; - int frameCycle=0; - for(int visibleUnitIndex = 0; - visibleUnitIndex < (int)qCache.visibleQuadUnitList.size(); ++visibleUnitIndex) { - Unit *unit = qCache.visibleQuadUnitList[visibleUnitIndex]; - if(unit->getCurrSkill() != NULL && unit->getCurrSkill()->getClass() == scMorph) { - Command *command= unit->getCurrCommand(); - if(command != NULL && command->getCommandType()->commandTypeClass == ccMorph){ - const MorphCommandType *mct= static_cast(command->getCommandType()); - const UnitType* mType=mct->getMorphUnit(); - - if(mType->getSize()>unit->getType()->getSize() || - mType->getField()!=unit->getType()->getField()){ - if(!initialized){ - const World *world= game->getWorld(); - frameCycle=world->getFrameCount() % 40; - - glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT); - glDisable(GL_LIGHTING); - glDisable(GL_TEXTURE_2D); - glDepthFunc(GL_ALWAYS); - glDisable(GL_STENCIL_TEST); - glDisable(GL_CULL_FACE); - glEnable(GL_BLEND); - glLineWidth(2.f); - initialized=true; - } - - Vec3f currVec= unit->getCurrVectorFlat(); - currVec=Vec3f(currVec.x,currVec.y+0.3f,currVec.z); - if(mType->getField() == fAir && unit->getType()->getField()== fLand) { - currVec=Vec3f(currVec.x,currVec.y+game->getWorld()->getTileset()->getAirHeight(),currVec.z); - } - if(mType->getField() == fLand && unit->getType()->getField()== fAir) { - currVec=Vec3f(currVec.x,currVec.y-game->getWorld()->getTileset()->getAirHeight(),currVec.z); - } - - float color=frameCycle*0.4f/40; - glColor4f(color,color, 0.4f, 0.4f); - renderSelectionCircle(currVec, mType->getSize(), frameCycle*0.85f/40, 0.2f); - } - } - } - } - if(initialized) { - glPopAttrib(); - } - } + Vec3f currVec = unit->getCurrVectorFlat(); + renderSelectionCircle(currVec, unit->getType()->getSize(), radius, + thickness); + } + } + glPopAttrib(); + } } +void Renderer::renderTeamColorPlane() { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + VisibleQuadContainerCache &qCache = getQuadCache(); + if (qCache.visibleQuadUnitList.empty() == false) { + glPushAttrib(GL_ENABLE_BIT); + glDisable(GL_LIGHTING); + glEnable(GL_TEXTURE_2D); + glEnable(GL_BLEND); + glEnable(GL_COLOR_MATERIAL); + const Texture2D *texture = CoreData::getInstance().getTeamColorTexture(); + for (int visibleUnitIndex = 0; + visibleUnitIndex < (int)qCache.visibleQuadUnitList.size(); + ++visibleUnitIndex) { + Unit *unit = qCache.visibleQuadUnitList[visibleUnitIndex]; + if (unit->isAlive()) { + Vec3f currVec = unit->getCurrVectorFlat(); + renderTeamColorEffect( + currVec, visibleUnitIndex, unit->getType()->getSize(), + unit->getFaction()->getTexture()->getPixmapConst()->getPixel3f(0, + 0), + texture); + } + } + glDisable(GL_COLOR_MATERIAL); + glPopAttrib(); + } +} + +void Renderer::renderGhostModel(const UnitType *building, const Vec2i pos, + CardinalDir facing, Vec4f *forceColor) { + // const UnitType *building= gui->getBuilding(); + // const Vec2i &pos= gui->getPosObjWorld(); + + // const Gui *gui= game->getGui(); + // const Mouse3d *mouse3d= gui->getMouse3d(); + const Map *map = game->getWorld()->getMap(); + if (map == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s] Line: %d map == NULL", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + throw megaglest_runtime_error(szBuf); + } + + glPushMatrix(); + Vec3f pos3f = Vec3f(pos.x, map->getCell(pos)->getHeight(), pos.y); + + // selection building placement + float offset = building->getSize() / 2.f - 0.5f; + glTranslatef(pos3f.x + offset, pos3f.y, pos3f.z + offset); + + // choose color + Vec4f color; + if (forceColor != NULL) { + color = *forceColor; + } else { + if (map->isFreeCells(pos, building->getSize(), fLand)) { + color = Vec4f(1.f, 1.f, 1.f, 0.5f); + } else { + // Uint64 tc=game->getTickCount(); + // float red=0.49f+((tc%4*1.0f)/2); + color = Vec4f(1.0f, 0.f, 0.f, 0.5f); + } + } -void Renderer::renderSelectionEffects(int healthbarMode) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - Config &config= Config::getInstance(); - if(config.getBool("RecordMode","false") == true) { - return; - } - - const World *world= game->getWorld(); - const Map *map= world->getMap(); - const Selection *selection= game->getGui()->getSelection(); - const Object *selectedResourceObject= game->getGui()->getSelectedResourceObject(); - - glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT); - glDisable(GL_LIGHTING); - glDisable(GL_TEXTURE_2D); - glDepthFunc(GL_ALWAYS); - glDisable(GL_STENCIL_TEST); - glDisable(GL_CULL_FACE); - glEnable(GL_BLEND); - glLineWidth(2.f); - - //units - for(int i=0; igetCount(); ++i){ - - const Unit *unit= selection->getUnit(i); - if(unit != NULL) { - //translate - Vec3f currVec= unit->getCurrVectorFlat(); - currVec.y+= 0.3f; - - //selection circle - int finalHealthbarMode = hbvUndefined; - if(healthbarMode == hbvUndefined) { - finalHealthbarMode = unit->getFaction()->getType()->getHealthbarVisible(); - } - else { - finalHealthbarMode = healthbarMode; - } - bool healthbarsVisible =((finalHealthbarMode & hbvAlways) || - (finalHealthbarMode & hbvSelected) || - (finalHealthbarMode & hbvIfNeeded)); - float selectionCircleThickness = 0.2f; - float hpRatio = unit->getHpRatio(); - if(healthbarsVisible) { - selectionCircleThickness = 0.05f; - hpRatio = 1.0f; - } - - if(world->getThisFactionIndex() == unit->getFactionIndex()) { - if( showDebugUI == true && - ((showDebugUILevel & debugui_unit_titles) == debugui_unit_titles) && - unit->getCommandSize() > 0 && - dynamic_cast(unit->getCurrCommand()->getCommandType()) != NULL) { - glColor4f(hpRatio, hpRatio, hpRatio, 0.3f); - } - else { - glColor4f(0, hpRatio, 0, 0.3f); - } - } - else if ( world->getThisTeamIndex() == unit->getTeam()) { - glColor4f(hpRatio, hpRatio, 0, 0.3f); - } - else { - glColor4f(hpRatio, 0, 0, 0.3f); - } - renderSelectionCircle(currVec, unit->getType()->getSize(), selectionCircleRadius,selectionCircleThickness); - - if( showDebugUI == true && - (showDebugUILevel & debugui_unit_titles) == debugui_unit_titles) { - - const UnitPathInterface *path= unit->getPath(); - const UnitPathBasic *pathfinder = (path == NULL ? NULL : dynamic_cast(path)); - if(pathfinder != NULL) { - vector pathList = pathfinder->getQueue(); - - Vec2i lastPosValue; - for(int i = 0; i < (int)pathList.size(); ++i) { - Vec2i curPosValue = pathList[i]; - if(i == 0) { - lastPosValue = curPosValue; - } - Vec3f currVec2 = unit->getVectorFlat(lastPosValue,curPosValue); - currVec2.y+= 0.3f; - renderSelectionCircle(currVec2, 1, selectionCircleRadius); - } - } - } - - //magic circle - if(!healthbarsVisible && world->getThisFactionIndex() == unit->getFactionIndex() && unit->getType()->getMaxEp() > 0) { - glColor4f(unit->getEpRatio()/2.f, unit->getEpRatio(), unit->getEpRatio(), 0.5f); - renderSelectionCircle(currVec, unit->getType()->getSize(), magicCircleRadius); - } - - // Render Attack-boost circles - if(showDebugUI == true) { - //const std::pair > ¤tAttackBoostUnits = unit->getCurrentAttackBoostUnits(); - const UnitAttackBoostEffectOriginator &effect = unit->getAttackBoostOriginatorEffect(); - - if(effect.skillType->isAttackBoostEnabled() == true) { - glColor4f(MAGENTA.x,MAGENTA.y,MAGENTA.z,MAGENTA.w); - renderSelectionCircle(currVec, 1, effect.skillType->getAttackBoost()->radius, .25f/effect.skillType->getAttackBoost()->radius); - - for(unsigned int i = 0; i < effect.currentAttackBoostUnits.size(); ++i) { - // Remove attack boost upgrades from unit - int findUnitId = effect.currentAttackBoostUnits[i]; - Unit *affectedUnit = game->getWorld()->findUnitById(findUnitId); - if(affectedUnit != NULL) { - Vec3f currVecBoost = affectedUnit->getCurrVectorFlat(); - currVecBoost.y += 0.3f; - - renderSelectionCircle(currVecBoost, affectedUnit->getType()->getSize(), 1.f); - } - } - } - } - - //meeting point arrow - if(unit->getType()->getMeetingPoint()) { - Vec2i pos= unit->getMeetingPos(); - map->clampPos(pos); - - Vec3f arrowTarget= Vec3f(pos.x, map->getCell(pos)->getHeight(), pos.y); - renderArrow(unit->getCurrVectorFlat(), arrowTarget, Vec3f(0.f, 0.f, 1.f), 0.3f); - } - } - } - - if(selectedResourceObject != NULL && selectedResourceObject->getResource() != NULL && selection->getCount() < 1) { - Resource *r= selectedResourceObject->getResource(); - int defaultValue= r->getType()->getDefResPerPatch(); - float colorValue=static_cast(r->getAmount())/static_cast(defaultValue); - glColor4f(0.1f, 0.1f , colorValue, 0.4f); - renderSelectionCircle(selectedResourceObject->getPos(),2, selectionCircleRadius); - } - //target arrow - if(selection->getCount() == 1) { - const Unit *unit= selection->getUnit(0); - if(unit != NULL) { - //comand arrow - if(focusArrows && unit->anyCommand()) { - const CommandType *ct= unit->getCurrCommand()->getCommandType(); - if(ct->getClicks() != cOne){ - - //arrow color - Vec3f arrowColor; - switch(ct->getClass()) { - case ccMove: - arrowColor= Vec3f(0.f, 1.f, 0.f); - break; - case ccAttack: - case ccAttackStopped: - arrowColor= Vec3f(1.f, 0.f, 0.f); - break; - default: - arrowColor= Vec3f(1.f, 1.f, 0.f); - break; - } - - //arrow target - Vec3f arrowTarget; - Command *c= unit->getCurrCommand(); - if(c->getUnit() != NULL) { - arrowTarget= c->getUnit()->getCurrVectorFlat(); - } - else { - Vec2i pos= c->getPos(); - map->clampPos(pos); - - arrowTarget= Vec3f(pos.x, map->getCell(pos)->getHeight(), pos.y); - } - - renderArrow(unit->getCurrVectorFlat(), arrowTarget, arrowColor, 0.3f); - } - } - } - } - - //render selection hightlights - if(game->getGui()->getHighlightedUnit() != NULL) { - const Unit *unit=game->getGui()->getHighlightedUnit() ; - - if(unit->isHighlighted()) { - float highlight= unit->getHightlight(); - if(game->getWorld()->getThisFactionIndex() == unit->getFactionIndex()) { - glColor4f(0.f, 1.f, 0.f, highlight); - } - else{ - glColor4f(1.f, 0.f, 0.f, highlight); - } - - Vec3f v= unit->getCurrVectorFlat(); - v.y+= 0.3f; - renderSelectionCircle(v, unit->getType()->getSize(), 0.5f+0.4f*highlight ); - } - } -// old inefficient way to render highlights -// for(int i=0; i < world->getFactionCount(); ++i) { -// for(int j=0; j < world->getFaction(i)->getUnitCount(); ++j) { -// const Unit *unit= world->getFaction(i)->getUnit(j); -// -// if(unit->isHighlighted()) { -// float highlight= unit->getHightlight(); -// if(game->getWorld()->getThisFactionIndex() == unit->getFactionIndex()) { -// glColor4f(0.f, 1.f, 0.f, highlight); -// } -// else{ -// glColor4f(1.f, 0.f, 0.f, highlight); -// } -// -// Vec3f v= unit->getCurrVectorFlat(); -// v.y+= 0.3f; -// renderSelectionCircle(v, unit->getType()->getSize(), 0.5f+0.4f*highlight ); -// } -// } -// } - //render resource selection highlight - if(game->getGui()->getHighlightedResourceObject() != NULL) { - const Object* object=game->getGui()->getHighlightedResourceObject(); - if(object->isHighlighted()) { - float highlight= object->getHightlight(); - glColor4f(0.1f, 0.1f , 1.0f, highlight); - Vec3f v= object->getPos(); - v.y+= 0.3f; - renderSelectionCircle(v, 2, 0.4f+0.4f*highlight ); - } - } - - glPopAttrib(); -} - -void Renderer::renderHealthBars(int healthbarMode){ - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - Config &config= Config::getInstance(); - if(config.getBool("RecordMode","false") == true) { - return; - } - - if(config.getBool("PhotoMode")) { - return; - } - - glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT); - glDisable(GL_LIGHTING); - glDisable(GL_TEXTURE_2D); - glDepthFunc(GL_ALWAYS); - glDisable(GL_STENCIL_TEST); - glDisable(GL_CULL_FACE); - glEnable(GL_BLEND); - glLineWidth(2.f); - - VisibleQuadContainerCache &qCache = getQuadCache(); - if(qCache.visibleQuadUnitList.empty() == false) { - for(int visibleUnitIndex = 0; - visibleUnitIndex < (int)qCache.visibleQuadUnitList.size(); ++visibleUnitIndex) { - Unit *unit = qCache.visibleQuadUnitList[visibleUnitIndex]; - if(isHealthBarVisible(unit,healthbarMode)) { - float healthbarheight; - float healthbarthickness; - const Texture2D *healthbarTexture; - const Texture2D *healthbarBackgroundTexture; - bool healthbarLineBorder; - - //get settings of the faction - healthbarheight=unit->getFaction()->getType()->getHealthbarHeight(); - healthbarthickness=unit->getFaction()->getType()->getHealthbarThickness(); - healthbarLineBorder=unit->getFaction()->getType()->isHealthbarLineBorder(); - CoreData &coreData= CoreData::getInstance(); - //First try faction texture then use core Texture - if(unit->getFaction()->getType()->isHealthbarBorderTextureEnabled()) { - healthbarTexture=unit->getFaction()->getType()->getHealthbarTexture(); - if(healthbarTexture==NULL) { - healthbarTexture=coreData.getHealthbarTexture(); - } - } else { - healthbarTexture=NULL; - } - if(unit->getFaction()->getType()->isHealthbarBackgroundTextureEnabled()) { - healthbarBackgroundTexture=unit->getFaction()->getType()->getHealthbarBackgroundTexture(); - if(healthbarBackgroundTexture==NULL) { - healthbarBackgroundTexture=coreData.getHealthbarBackgroundTexture(); - } - } else { - healthbarBackgroundTexture=NULL; - } - - //replace them by the ones from the unit if existent - if(unit->getType()->getHealthbarVisible()!=hbvOff && unit->getType()->getHealthbarVisible()!=hbvUndefined) { - if(unit->getType()->getHealthbarHeight()!=-100.0f) { - healthbarheight=unit->getType()->getHealthbarHeight(); - } - if(unit->getType()->getHealthbarThickness()!=-1.0f) { - healthbarthickness=unit->getType()->getHealthbarThickness(); - } - } - - Vec3f currVec= unit->getCurrVectorFlat(); - if(healthbarheight==-100.0f) { - currVec.y+=unit->getType()->getHeight(); - } else { - currVec.y+=healthbarheight; - } - renderHealthBar(currVec,unit,healthbarthickness,healthbarLineBorder,healthbarTexture,healthbarBackgroundTexture); - } - } - } - glPopAttrib(); -} - -bool Renderer::isHealthBarVisible(const Unit *unit,int healthbarMode){ - int healthbarVisible=hbvUndefined; - //check options (hotkey) - if(healthbarMode==hbvUndefined) { - healthbarVisible=unit->getFaction()->getType()->getHealthbarVisible(); - } else { - healthbarVisible=healthbarMode; - } - - //replace them by the ones from the unit if existent - if(unit->getType()->getHealthbarVisible()!=hbvOff && unit->getType()->getHealthbarVisible()!=hbvUndefined) { - if(healthbarMode==hbvUndefined) { //don't override the visible setting when hotkey is not hbvUndefined - healthbarVisible=unit->getType()->getHealthbarVisible(); - } - } - - bool settingsWantToRenderThem=!(healthbarVisible==hbvUndefined || (healthbarVisible&hbvOff)) - && ((healthbarVisible&hbvAlways) - || ((healthbarVisible&hbvIfNeeded) && unit->getHp()getType()->getMaxHp()+unit->getTotalUpgrade()->getMaxHp()) - || ((healthbarVisible&hbvIfNeeded) && unit->getType()->getMaxEp() > 0 && unit->getEp()getType()->getMaxEp()+unit->getTotalUpgrade()->getMaxEp()) - || ((healthbarVisible&hbvIfNeeded) && unit->getProductionPercent() > 0) - || ((healthbarVisible&hbvSelected) && game->getGui()->isSelected(unit))); - - if(unit->isAlive() && (settingsWantToRenderThem)) { - return true; - } - return false; -} - -void Renderer::renderWaterEffects(){ - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - const World *world= game->getWorld(); - const WaterEffects *we= world->getWaterEffects(); - const Map *map= world->getMap(); - CoreData &coreData= CoreData::getInstance(); - float height= map->getWaterLevel()+0.001f; - - assertGl(); - - glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT | GL_DEPTH_BUFFER_BIT); - glEnable(GL_BLEND); - glDisable(GL_ALPHA_TEST); - glDepthMask(GL_FALSE); - glDepthFunc(GL_LEQUAL); - glEnable(GL_COLOR_MATERIAL); - - //glNormal3f(0.f, 1.f, 0.f); - - //splashes - glBindTexture(GL_TEXTURE_2D, static_cast(coreData.getWaterSplashTexture())->getHandle()); - - //!!! - Vec2f texCoords[4]; - Vec3f vertices[4]; - Vec3f normals[4]; - - glEnableClientState(GL_VERTEX_ARRAY); - glEnableClientState(GL_NORMAL_ARRAY); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - - for(int i=0; igetWaterSplashCount(); ++i){ - const WaterSplash *ws= we->getWaterSplash(i); - - //render only if enabled - if(ws->getEnabled()){ - - //render only if visible - Vec2i intPos= Vec2i(static_cast(ws->getPos().x), static_cast(ws->getPos().y)); - const Vec2i &mapPos = Map::toSurfCoords(intPos); - - bool visible = map->getSurfaceCell(mapPos)->isVisible(world->getThisTeamIndex()); - if(visible == false && world->showWorldForPlayer(world->getThisFactionIndex()) == true) { - visible = true; - } - - if(visible == true) { - float scale= ws->getAnim()*ws->getSize(); - texCoords[0] = Vec2f(0.f, 1.f); - vertices[0] = Vec3f(ws->getPos().x-scale, height, ws->getPos().y+scale); - normals[0] = Vec3f(0.f, 1.f, 0.f); - - texCoords[1] = Vec2f(0.f, 0.f); - vertices[1] = Vec3f(ws->getPos().x-scale, height, ws->getPos().y-scale); - normals[1] = Vec3f(0.f, 1.f, 0.f); - - texCoords[2] = Vec2f(1.f, 1.f); - vertices[2] = Vec3f(ws->getPos().x+scale, height, ws->getPos().y+scale); - normals[2] = Vec3f(0.f, 1.f, 0.f); - - texCoords[3] = Vec2f(1.f, 0.f); - vertices[3] = Vec3f(ws->getPos().x+scale, height, ws->getPos().y-scale); - normals[3] = Vec3f(0.f, 1.f, 0.f); - - glColor4f(1.f, 1.f, 1.f, 1.f - ws->getAnim()); - glTexCoordPointer(2, GL_FLOAT, 0,&texCoords[0]); - glVertexPointer(3, GL_FLOAT, 0, &vertices[0]); - glNormalPointer(GL_FLOAT, 0, &normals[0]); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - - -/* - glBegin(GL_TRIANGLE_STRIP); - glTexCoord2f(0.f, 1.f); - glVertex3f(ws->getPos().x-scale, height, ws->getPos().y+scale); - glTexCoord2f(0.f, 0.f); - glVertex3f(ws->getPos().x-scale, height, ws->getPos().y-scale); - glTexCoord2f(1.f, 1.f); - glVertex3f(ws->getPos().x+scale, height, ws->getPos().y+scale); - glTexCoord2f(1.f, 0.f); - glVertex3f(ws->getPos().x+scale, height, ws->getPos().y-scale); - glEnd(); -*/ - } - } - } - - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - glDisableClientState(GL_NORMAL_ARRAY); - glDisableClientState(GL_VERTEX_ARRAY); - - glPopAttrib(); + glColor4fv(color.ptr()); + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, color.ptr()); + Model *buildingModel = building->getFirstStOfClass(scStop)->getAnimation(); - assertGl(); -} + if (facing != CardinalDir::NORTH) { + float rotateAmount = facing * 90.f; + if (rotateAmount > 0) { + glRotatef(rotateAmount, 0.f, 1.f, 0.f); + } + } -void Renderer::renderHud(){ - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } + buildingModel->updateInterpolationData(0.f, false); + modelRenderer->render(buildingModel); - Texture2D *hudTexture=game->getGui()->getHudTexture(); - if(hudTexture!=NULL){ - const Metrics &metrics= Metrics::getInstance(); - renderTextureQuad(0, 0, metrics.getVirtualW(), metrics.getVirtualH(),hudTexture,1.0f); - } + glPopMatrix(); } -void Renderer::renderMinimap(){ - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - const World *world= game->getWorld(); - const Minimap *minimap= world->getMinimap(); +void Renderer::renderUnits(bool airUnits, const int renderFps) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + // Unit *unit=NULL; + // const World *world= game->getWorld(); + MeshCallbackTeamColor meshCallbackTeamColor; + + // assert + assertGl(); + + if (visibleFrameUnitList.empty() == false) { + visibleFrameUnitList.clear(); + // visibleFrameUnitListCameraKey = ""; + // if(visibleFrameUnitListCameraKey != + // game->getGameCamera()->getCameraMovementKey()) { + // worldToScreenPosCache.clear(); + // } + } + + VisibleQuadContainerCache &qCache = getQuadCache(); + if (qCache.visibleQuadUnitList.empty() == false) { + bool modelRenderStarted = false; + for (int visibleUnitIndex = 0; + visibleUnitIndex < (int)qCache.visibleQuadUnitList.size(); + ++visibleUnitIndex) { + Unit *unit = qCache.visibleQuadUnitList[visibleUnitIndex]; + + if ((airUnits == false && unit->getType()->getField() == fAir) || + (airUnits == true && unit->getType()->getField() != fAir)) { + continue; + } + meshCallbackTeamColor.setTeamTexture(unit->getFaction()->getTexture()); + + if (modelRenderStarted == false) { + modelRenderStarted = true; + + glPushAttrib(GL_ENABLE_BIT | GL_FOG_BIT | GL_LIGHTING_BIT | + GL_TEXTURE_BIT); + glEnable(GL_COLOR_MATERIAL); + + if (!shadowsOffDueToMinRender) { + if (shadows == sShadowMapping) { + glActiveTexture(shadowTexUnit); + glEnable(GL_TEXTURE_2D); + + glBindTexture(GL_TEXTURE_2D, shadowMapHandle); + + static_cast(modelRenderer) + ->setDuplicateTexCoords(true); + enableProjectiveTexturing(); + } + } + glActiveTexture(baseTexUnit); + + modelRenderer->begin(true, true, true, false, &meshCallbackTeamColor); + } + + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + + // translate + Vec3f currVec = unit->getCurrVectorFlat(); + glTranslatef(currVec.x, currVec.y, currVec.z); + + // rotate + float zrot = unit->getRotationZ(); + float xrot = unit->getRotationX(); + if (zrot != .0f) { + glRotatef(zrot, 0.f, 0.f, 1.f); + } + if (xrot != .0f) { + glRotatef(xrot, 1.f, 0.f, 0.f); + } + glRotatef(unit->getRotation(), 0.f, 1.f, 0.f); + + // dead alpha + const SkillType *st = unit->getCurrSkill(); + if (st->getClass() == scDie && + static_cast(st)->getFade()) { + float alpha = 1.0f - unit->getAnimProgressAsFloat(); + glDisable(GL_COLOR_MATERIAL); + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, + Vec4f(1.0f, 1.0f, 1.0f, alpha).ptr()); + } else { + glEnable(GL_COLOR_MATERIAL); + // we cut off a tiny bit here to avoid problems with fully transparent + // texture parts cutting units in background rendered later. + glAlphaFunc(GL_GREATER, 0.02f); + } + + // render + Model *model = unit->getCurrentModelPtr(); + // printf("Rendering model [%d - %s]\n[%s]\nCamera [%s]\nDistance: + // %f\n",unit->getId(),unit->getType()->getName().c_str(),unit->getCurrVector().getString().c_str(),this->gameCamera->getPos().getString().c_str(),this->gameCamera->getPos().dist(unit->getCurrVector())); + + // if(this->gameCamera->getPos().dist(unit->getCurrVector()) <= + // SKIP_INTERPOLATION_DISTANCE) { + model->updateInterpolationData(unit->getAnimProgressAsFloat(), + unit->isAlive() && + !unit->isAnimProgressBound()); + //} + + modelRenderer->render(model); + triangleCount += model->getTriangleCount(); + pointCount += model->getVertexCount(); + + glPopMatrix(); + unit->setVisible(true); + + if (showDebugUI == true && + (showDebugUILevel & debugui_unit_titles) == debugui_unit_titles) { + + unit->setScreenPos(computeScreenPosition(currVec)); + visibleFrameUnitList.push_back(unit); + visibleFrameUnitListCameraKey = + game->getGameCamera()->getCameraMovementKey(); + } + } - if(minimap == NULL || minimap->getTexture() == NULL) { - return; - } + if (modelRenderStarted == true) { + modelRenderer->end(); + glPopAttrib(); + } + } - const GameCamera *gameCamera= game->getGameCamera(); - const Pixmap2D *pixmap= minimap->getTexture()->getPixmapConst(); - const Metrics &metrics= Metrics::getInstance(); - const WaterEffects *attackEffects= world->getAttackEffects(); + // restore + static_cast(modelRenderer)->setDuplicateTexCoords(true); - int mx= metrics.getMinimapX(); - int my= metrics.getMinimapY(); - int mw= metrics.getMinimapW(); - int mh= metrics.getMinimapH(); + // reset alpha + glAlphaFunc(GL_GREATER, 0.0f); + // assert + assertGl(); +} - Vec2f zoom= Vec2f( - static_cast(mw)/ pixmap->getW(), - static_cast(mh)/ pixmap->getH()); +void Renderer::renderUnitsToBuild(const int renderFps) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - assertGl(); + // assert + assertGl(); - // render minimap border - Vec4f col= game->getGui()->getDisplay()->getColor(); - glColor4f(col.x*0.5f,col.y*0.5f,col.z*0.5f,1.0 ); - - int borderWidth=2; - glBegin(GL_QUADS); - glVertex2i(mx-borderWidth, my-borderWidth); - glVertex2i(mx-borderWidth, my); - glVertex2i(mx+mw+borderWidth, my); - glVertex2i(mx+mw+borderWidth, my-borderWidth); - glEnd(); - - glBegin(GL_QUADS); - glVertex2i(mx-borderWidth, my+mh+borderWidth); - glVertex2i(mx-borderWidth, my+mh); - glVertex2i(mx+mw+borderWidth, my+mh); - glVertex2i(mx+mw+borderWidth, my+mh+borderWidth); - glEnd(); - - glBegin(GL_QUADS); - glVertex2i(mx-borderWidth, my); - glVertex2i(mx-borderWidth, my+mh); - glVertex2i(mx, my+mh); - glVertex2i(mx, my); - glEnd(); - - glBegin(GL_QUADS); - glVertex2i(mx+mw, my); - glVertex2i(mx+mw, my+mh); - glVertex2i(mx+mw+borderWidth, my+mh); - glVertex2i(mx+mw+borderWidth, my); - glEnd(); + VisibleQuadContainerCache &qCache = getQuadCache(); + if (qCache.visibleQuadUnitBuildList.empty() == false) { - assertGl(); + glMatrixMode(GL_MODELVIEW); + glPushAttrib(GL_CURRENT_BIT | GL_LIGHTING_BIT | GL_ENABLE_BIT | + GL_DEPTH_BUFFER_BIT); + glEnable(GL_BLEND); + glDisable(GL_STENCIL_TEST); + glDepthFunc(GL_LESS); + glEnable(GL_COLOR_MATERIAL); + glDepthMask(GL_FALSE); + + modelRenderer->begin(true, true, false, false); + + for (int visibleUnitIndex = 0; + visibleUnitIndex < (int)qCache.visibleQuadUnitBuildList.size(); + ++visibleUnitIndex) { + const UnitBuildInfo &buildUnit = + qCache.visibleQuadUnitBuildList[visibleUnitIndex]; + // Vec4f modelColor= Vec4f(0.f, 1.f, 0.f, 0.5f); + const Vec3f teamColor = buildUnit.unit->getFaction() + ->getTexture() + ->getPixmapConst() + ->getPixel3f(0, 0); + Vec4f modelColor = Vec4f(teamColor.x, teamColor.y, teamColor.z, 0.4f); + renderGhostModel(buildUnit.buildUnit, buildUnit.pos, buildUnit.facing, + &modelColor); + + // printf("Rendering to build unit index = %d\n",visibleUnitIndex); + } - glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT | GL_LINE_BIT | GL_TEXTURE_BIT); + modelRenderer->end(); - //draw map - glEnable(GL_TEXTURE_2D); - glEnable(GL_BLEND); + glDisable(GL_COLOR_MATERIAL); + glPopAttrib(); + } + + // assert + assertGl(); +} + +void Renderer::renderTeamColorEffect(Vec3f &v, int heigth, int size, + Vec3f color, const Texture2D *texture) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + // GLUquadricObj *disc; + float halfSize = size; + // halfSize=halfSize; + float heigthoffset = 0.5 + heigth % 25 * 0.004; + glPushMatrix(); + glBindTexture(GL_TEXTURE_2D, + static_cast(texture)->getHandle()); + glColor4f(color.x, color.y, color.z, 1.0f); + glBegin(GL_TRIANGLE_STRIP); + glTexCoord2i(0, 1); + glVertex3f(v.x - halfSize, v.y + heigthoffset, v.z + halfSize); + glTexCoord2i(0, 0); + glVertex3f(v.x - halfSize, v.y + heigthoffset, v.z - halfSize); + glTexCoord2i(1, 1); + + glVertex3f(v.x + halfSize, v.y + heigthoffset, v.z + halfSize); + glTexCoord2i(1, 0); + glVertex3f(v.x + halfSize, v.y + heigthoffset, v.z - halfSize); + glEnd(); + glPopMatrix(); +} + +void Renderer::renderMorphEffects() { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + VisibleQuadContainerCache &qCache = getQuadCache(); + if (qCache.visibleQuadUnitList.empty() == false) { + bool initialized = false; + int frameCycle = 0; + for (int visibleUnitIndex = 0; + visibleUnitIndex < (int)qCache.visibleQuadUnitList.size(); + ++visibleUnitIndex) { + Unit *unit = qCache.visibleQuadUnitList[visibleUnitIndex]; + if (unit->getCurrSkill() != NULL && + unit->getCurrSkill()->getClass() == scMorph) { + Command *command = unit->getCurrCommand(); + if (command != NULL && + command->getCommandType()->commandTypeClass == ccMorph) { + const MorphCommandType *mct = + static_cast(command->getCommandType()); + const UnitType *mType = mct->getMorphUnit(); + + if (mType->getSize() > unit->getType()->getSize() || + mType->getField() != unit->getType()->getField()) { + if (!initialized) { + const World *world = game->getWorld(); + frameCycle = world->getFrameCount() % 40; + + glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT | + GL_DEPTH_BUFFER_BIT); + glDisable(GL_LIGHTING); + glDisable(GL_TEXTURE_2D); + glDepthFunc(GL_ALWAYS); + glDisable(GL_STENCIL_TEST); + glDisable(GL_CULL_FACE); + glEnable(GL_BLEND); + glLineWidth(2.f); + initialized = true; + } - glActiveTexture(fowTexUnit); - glEnable(GL_TEXTURE_2D); - glBindTexture(GL_TEXTURE_2D, static_cast(minimap->getFowTexture())->getHandle()); - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); + Vec3f currVec = unit->getCurrVectorFlat(); + currVec = Vec3f(currVec.x, currVec.y + 0.3f, currVec.z); + if (mType->getField() == fAir && + unit->getType()->getField() == fLand) { + currVec = Vec3f( + currVec.x, + currVec.y + game->getWorld()->getTileset()->getAirHeight(), + currVec.z); + } + if (mType->getField() == fLand && + unit->getType()->getField() == fAir) { + currVec = Vec3f( + currVec.x, + currVec.y - game->getWorld()->getTileset()->getAirHeight(), + currVec.z); + } - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_INTERPOLATE); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PREVIOUS); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_PRIMARY_COLOR); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB, GL_TEXTURE); + float color = frameCycle * 0.4f / 40; + glColor4f(color, color, 0.4f, 0.4f); + renderSelectionCircle(currVec, mType->getSize(), + frameCycle * 0.85f / 40, 0.2f); + } + } + } + } + if (initialized) { + glPopAttrib(); + } + } +} - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_ADD); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_PRIMARY_COLOR); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA, GL_TEXTURE); +void Renderer::renderSelectionEffects(int healthbarMode) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + Config &config = Config::getInstance(); + if (config.getBool("RecordMode", "false") == true) { + return; + } + + const World *world = game->getWorld(); + const Map *map = world->getMap(); + const Selection *selection = game->getGui()->getSelection(); + const Object *selectedResourceObject = + game->getGui()->getSelectedResourceObject(); + + glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT); + glDisable(GL_LIGHTING); + glDisable(GL_TEXTURE_2D); + glDepthFunc(GL_ALWAYS); + glDisable(GL_STENCIL_TEST); + glDisable(GL_CULL_FACE); + glEnable(GL_BLEND); + glLineWidth(2.f); + + // units + for (int i = 0; i < selection->getCount(); ++i) { + + const Unit *unit = selection->getUnit(i); + if (unit != NULL) { + // translate + Vec3f currVec = unit->getCurrVectorFlat(); + currVec.y += 0.3f; + + // selection circle + int finalHealthbarMode = hbvUndefined; + if (healthbarMode == hbvUndefined) { + finalHealthbarMode = + unit->getFaction()->getType()->getHealthbarVisible(); + } else { + finalHealthbarMode = healthbarMode; + } + bool healthbarsVisible = ((finalHealthbarMode & hbvAlways) || + (finalHealthbarMode & hbvSelected) || + (finalHealthbarMode & hbvIfNeeded)); + float selectionCircleThickness = 0.2f; + float hpRatio = unit->getHpRatio(); + if (healthbarsVisible) { + selectionCircleThickness = 0.05f; + hpRatio = 1.0f; + } + + if (world->getThisFactionIndex() == unit->getFactionIndex()) { + if (showDebugUI == true && + ((showDebugUILevel & debugui_unit_titles) == debugui_unit_titles) && + unit->getCommandSize() > 0 && + dynamic_cast( + unit->getCurrCommand()->getCommandType()) != NULL) { + glColor4f(hpRatio, hpRatio, hpRatio, 0.3f); + } else { + glColor4f(0, hpRatio, 0, 0.3f); + } + } else if (world->getThisTeamIndex() == unit->getTeam()) { + glColor4f(hpRatio, hpRatio, 0, 0.3f); + } else { + glColor4f(hpRatio, 0, 0, 0.3f); + } + renderSelectionCircle(currVec, unit->getType()->getSize(), + selectionCircleRadius, selectionCircleThickness); + + if (showDebugUI == true && + (showDebugUILevel & debugui_unit_titles) == debugui_unit_titles) { + + const UnitPathInterface *path = unit->getPath(); + const UnitPathBasic *pathfinder = + (path == NULL ? NULL : dynamic_cast(path)); + if (pathfinder != NULL) { + vector pathList = pathfinder->getQueue(); + + Vec2i lastPosValue; + for (int i = 0; i < (int)pathList.size(); ++i) { + Vec2i curPosValue = pathList[i]; + if (i == 0) { + lastPosValue = curPosValue; + } + Vec3f currVec2 = unit->getVectorFlat(lastPosValue, curPosValue); + currVec2.y += 0.3f; + renderSelectionCircle(currVec2, 1, selectionCircleRadius); + } + } + } + + // magic circle + if (!healthbarsVisible && + world->getThisFactionIndex() == unit->getFactionIndex() && + unit->getType()->getMaxEp() > 0) { + glColor4f(unit->getEpRatio() / 2.f, unit->getEpRatio(), + unit->getEpRatio(), 0.5f); + renderSelectionCircle(currVec, unit->getType()->getSize(), + magicCircleRadius); + } + + // Render Attack-boost circles + if (showDebugUI == true) { + // const std::pair > + // ¤tAttackBoostUnits = unit->getCurrentAttackBoostUnits(); + const UnitAttackBoostEffectOriginator &effect = + unit->getAttackBoostOriginatorEffect(); + + if (effect.skillType->isAttackBoostEnabled() == true) { + glColor4f(MAGENTA.x, MAGENTA.y, MAGENTA.z, MAGENTA.w); + renderSelectionCircle( + currVec, 1, effect.skillType->getAttackBoost()->radius, + .25f / effect.skillType->getAttackBoost()->radius); + + for (unsigned int i = 0; i < effect.currentAttackBoostUnits.size(); + ++i) { + // Remove attack boost upgrades from unit + int findUnitId = effect.currentAttackBoostUnits[i]; + Unit *affectedUnit = game->getWorld()->findUnitById(findUnitId); + if (affectedUnit != NULL) { + Vec3f currVecBoost = affectedUnit->getCurrVectorFlat(); + currVecBoost.y += 0.3f; + + renderSelectionCircle(currVecBoost, + affectedUnit->getType()->getSize(), 1.f); + } + } + } + } - glActiveTexture(baseTexUnit); - glBindTexture(GL_TEXTURE_2D, static_cast(minimap->getTexture())->getHandle()); + // meeting point arrow + if (unit->getType()->getMeetingPoint()) { + Vec2i pos = unit->getMeetingPos(); + map->clampPos(pos); - glColor4f(0.5f, 0.5f, 0.5f, 0.2f); + Vec3f arrowTarget = Vec3f(pos.x, map->getCell(pos)->getHeight(), pos.y); + renderArrow(unit->getCurrVectorFlat(), arrowTarget, + Vec3f(0.f, 0.f, 1.f), 0.3f); + } + } + } + + if (selectedResourceObject != NULL && + selectedResourceObject->getResource() != NULL && + selection->getCount() < 1) { + Resource *r = selectedResourceObject->getResource(); + int defaultValue = r->getType()->getDefResPerPatch(); + float colorValue = + static_cast(r->getAmount()) / static_cast(defaultValue); + glColor4f(0.1f, 0.1f, colorValue, 0.4f); + renderSelectionCircle(selectedResourceObject->getPos(), 2, + selectionCircleRadius); + } + // target arrow + if (selection->getCount() == 1) { + const Unit *unit = selection->getUnit(0); + if (unit != NULL) { + // comand arrow + if (focusArrows && unit->anyCommand()) { + const CommandType *ct = unit->getCurrCommand()->getCommandType(); + if (ct->getClicks() != cOne) { + + // arrow color + Vec3f arrowColor; + switch (ct->getClass()) { + case ccMove: + arrowColor = Vec3f(0.f, 1.f, 0.f); + break; + case ccAttack: + case ccAttackStopped: + arrowColor = Vec3f(1.f, 0.f, 0.f); + break; + default: + arrowColor = Vec3f(1.f, 1.f, 0.f); + break; + } + + // arrow target + Vec3f arrowTarget; + Command *c = unit->getCurrCommand(); + if (c->getUnit() != NULL) { + arrowTarget = c->getUnit()->getCurrVectorFlat(); + } else { + Vec2i pos = c->getPos(); + map->clampPos(pos); + + arrowTarget = Vec3f(pos.x, map->getCell(pos)->getHeight(), pos.y); + } + + renderArrow(unit->getCurrVectorFlat(), arrowTarget, arrowColor, 0.3f); + } + } + } + } + + // render selection hightlights + if (game->getGui()->getHighlightedUnit() != NULL) { + const Unit *unit = game->getGui()->getHighlightedUnit(); + + if (unit->isHighlighted()) { + float highlight = unit->getHightlight(); + if (game->getWorld()->getThisFactionIndex() == unit->getFactionIndex()) { + glColor4f(0.f, 1.f, 0.f, highlight); + } else { + glColor4f(1.f, 0.f, 0.f, highlight); + } + + Vec3f v = unit->getCurrVectorFlat(); + v.y += 0.3f; + renderSelectionCircle(v, unit->getType()->getSize(), + 0.5f + 0.4f * highlight); + } + } + // old inefficient way to render highlights + // for(int i=0; i < world->getFactionCount(); ++i) { + // for(int j=0; j < world->getFaction(i)->getUnitCount(); ++j) { + // const Unit *unit= world->getFaction(i)->getUnit(j); + // + // if(unit->isHighlighted()) { + // float highlight= unit->getHightlight(); + // if(game->getWorld()->getThisFactionIndex() == + // unit->getFactionIndex()) { glColor4f(0.f, 1.f, 0.f, + // highlight); + // } + // else{ + // glColor4f(1.f, 0.f, 0.f, highlight); + // } + // + // Vec3f v= unit->getCurrVectorFlat(); + // v.y+= 0.3f; + // renderSelectionCircle(v, + //unit->getType()->getSize(), 0.5f+0.4f*highlight ); + // } + // } + // } + // render resource selection highlight + if (game->getGui()->getHighlightedResourceObject() != NULL) { + const Object *object = game->getGui()->getHighlightedResourceObject(); + if (object->isHighlighted()) { + float highlight = object->getHightlight(); + glColor4f(0.1f, 0.1f, 1.0f, highlight); + Vec3f v = object->getPos(); + v.y += 0.3f; + renderSelectionCircle(v, 2, 0.4f + 0.4f * highlight); + } + } + + glPopAttrib(); +} + +void Renderer::renderHealthBars(int healthbarMode) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + Config &config = Config::getInstance(); + if (config.getBool("RecordMode", "false") == true) { + return; + } + + if (config.getBool("PhotoMode")) { + return; + } + + glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT); + glDisable(GL_LIGHTING); + glDisable(GL_TEXTURE_2D); + glDepthFunc(GL_ALWAYS); + glDisable(GL_STENCIL_TEST); + glDisable(GL_CULL_FACE); + glEnable(GL_BLEND); + glLineWidth(2.f); + + VisibleQuadContainerCache &qCache = getQuadCache(); + if (qCache.visibleQuadUnitList.empty() == false) { + for (int visibleUnitIndex = 0; + visibleUnitIndex < (int)qCache.visibleQuadUnitList.size(); + ++visibleUnitIndex) { + Unit *unit = qCache.visibleQuadUnitList[visibleUnitIndex]; + if (isHealthBarVisible(unit, healthbarMode)) { + float healthbarheight; + float healthbarthickness; + const Texture2D *healthbarTexture; + const Texture2D *healthbarBackgroundTexture; + bool healthbarLineBorder; + + // get settings of the faction + healthbarheight = unit->getFaction()->getType()->getHealthbarHeight(); + healthbarthickness = + unit->getFaction()->getType()->getHealthbarThickness(); + healthbarLineBorder = + unit->getFaction()->getType()->isHealthbarLineBorder(); + CoreData &coreData = CoreData::getInstance(); + // First try faction texture then use core Texture + if (unit->getFaction()->getType()->isHealthbarBorderTextureEnabled()) { + healthbarTexture = + unit->getFaction()->getType()->getHealthbarTexture(); + if (healthbarTexture == NULL) { + healthbarTexture = coreData.getHealthbarTexture(); + } + } else { + healthbarTexture = NULL; + } + if (unit->getFaction() + ->getType() + ->isHealthbarBackgroundTextureEnabled()) { + healthbarBackgroundTexture = + unit->getFaction()->getType()->getHealthbarBackgroundTexture(); + if (healthbarBackgroundTexture == NULL) { + healthbarBackgroundTexture = + coreData.getHealthbarBackgroundTexture(); + } + } else { + healthbarBackgroundTexture = NULL; + } - glBegin(GL_TRIANGLE_STRIP); - glTexCoord2f(0.0f, 1.0f); - glMultiTexCoord2f(fowTexUnit, 0.0f, 1.0f); - glVertex2i(mx, my); + // replace them by the ones from the unit if existent + if (unit->getType()->getHealthbarVisible() != hbvOff && + unit->getType()->getHealthbarVisible() != hbvUndefined) { + if (unit->getType()->getHealthbarHeight() != -100.0f) { + healthbarheight = unit->getType()->getHealthbarHeight(); + } + if (unit->getType()->getHealthbarThickness() != -1.0f) { + healthbarthickness = unit->getType()->getHealthbarThickness(); + } + } - glTexCoord2f(0.0f, 0.0f); - glMultiTexCoord2f(fowTexUnit, 0.0f, 0.0f); - glVertex2i(mx, my+mh); + Vec3f currVec = unit->getCurrVectorFlat(); + if (healthbarheight == -100.0f) { + currVec.y += unit->getType()->getHeight(); + } else { + currVec.y += healthbarheight; + } + renderHealthBar(currVec, unit, healthbarthickness, healthbarLineBorder, + healthbarTexture, healthbarBackgroundTexture); + } + } + } + glPopAttrib(); +} + +bool Renderer::isHealthBarVisible(const Unit *unit, int healthbarMode) { + int healthbarVisible = hbvUndefined; + // check options (hotkey) + if (healthbarMode == hbvUndefined) { + healthbarVisible = unit->getFaction()->getType()->getHealthbarVisible(); + } else { + healthbarVisible = healthbarMode; + } + + // replace them by the ones from the unit if existent + if (unit->getType()->getHealthbarVisible() != hbvOff && + unit->getType()->getHealthbarVisible() != hbvUndefined) { + if (healthbarMode == hbvUndefined) { // don't override the visible setting + // when hotkey is not hbvUndefined + healthbarVisible = unit->getType()->getHealthbarVisible(); + } + } + + bool settingsWantToRenderThem = + !(healthbarVisible == hbvUndefined || (healthbarVisible & hbvOff)) && + ((healthbarVisible & hbvAlways) || + ((healthbarVisible & hbvIfNeeded) && + unit->getHp() < unit->getType()->getMaxHp() + + unit->getTotalUpgrade()->getMaxHp()) || + ((healthbarVisible & hbvIfNeeded) && unit->getType()->getMaxEp() > 0 && + unit->getEp() < unit->getType()->getMaxEp() + + unit->getTotalUpgrade()->getMaxEp()) || + ((healthbarVisible & hbvIfNeeded) && unit->getProductionPercent() > 0) || + ((healthbarVisible & hbvSelected) && game->getGui()->isSelected(unit))); + + if (unit->isAlive() && (settingsWantToRenderThem)) { + return true; + } + return false; +} + +void Renderer::renderWaterEffects() { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + const World *world = game->getWorld(); + const WaterEffects *we = world->getWaterEffects(); + const Map *map = world->getMap(); + CoreData &coreData = CoreData::getInstance(); + float height = map->getWaterLevel() + 0.001f; + + assertGl(); + + glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT | GL_DEPTH_BUFFER_BIT); + glEnable(GL_BLEND); + glDisable(GL_ALPHA_TEST); + glDepthMask(GL_FALSE); + glDepthFunc(GL_LEQUAL); + glEnable(GL_COLOR_MATERIAL); + + // glNormal3f(0.f, 1.f, 0.f); + + // splashes + glBindTexture(GL_TEXTURE_2D, + static_cast(coreData.getWaterSplashTexture()) + ->getHandle()); + + //!!! + Vec2f texCoords[4]; + Vec3f vertices[4]; + Vec3f normals[4]; + + glEnableClientState(GL_VERTEX_ARRAY); + glEnableClientState(GL_NORMAL_ARRAY); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + + for (int i = 0; i < we->getWaterSplashCount(); ++i) { + const WaterSplash *ws = we->getWaterSplash(i); + + // render only if enabled + if (ws->getEnabled()) { + + // render only if visible + Vec2i intPos = Vec2i(static_cast(ws->getPos().x), + static_cast(ws->getPos().y)); + const Vec2i &mapPos = Map::toSurfCoords(intPos); + + bool visible = + map->getSurfaceCell(mapPos)->isVisible(world->getThisTeamIndex()); + if (visible == false && + world->showWorldForPlayer(world->getThisFactionIndex()) == true) { + visible = true; + } + + if (visible == true) { + float scale = ws->getAnim() * ws->getSize(); + texCoords[0] = Vec2f(0.f, 1.f); + vertices[0] = + Vec3f(ws->getPos().x - scale, height, ws->getPos().y + scale); + normals[0] = Vec3f(0.f, 1.f, 0.f); + + texCoords[1] = Vec2f(0.f, 0.f); + vertices[1] = + Vec3f(ws->getPos().x - scale, height, ws->getPos().y - scale); + normals[1] = Vec3f(0.f, 1.f, 0.f); + + texCoords[2] = Vec2f(1.f, 1.f); + vertices[2] = + Vec3f(ws->getPos().x + scale, height, ws->getPos().y + scale); + normals[2] = Vec3f(0.f, 1.f, 0.f); + + texCoords[3] = Vec2f(1.f, 0.f); + vertices[3] = + Vec3f(ws->getPos().x + scale, height, ws->getPos().y - scale); + normals[3] = Vec3f(0.f, 1.f, 0.f); + + glColor4f(1.f, 1.f, 1.f, 1.f - ws->getAnim()); + glTexCoordPointer(2, GL_FLOAT, 0, &texCoords[0]); + glVertexPointer(3, GL_FLOAT, 0, &vertices[0]); + glNormalPointer(GL_FLOAT, 0, &normals[0]); + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + + /* + glBegin(GL_TRIANGLE_STRIP); + glTexCoord2f(0.f, 1.f); + glVertex3f(ws->getPos().x-scale, + height, ws->getPos().y+scale); glTexCoord2f(0.f, 0.f); + glVertex3f(ws->getPos().x-scale, + height, ws->getPos().y-scale); glTexCoord2f(1.f, 1.f); + glVertex3f(ws->getPos().x+scale, + height, ws->getPos().y+scale); glTexCoord2f(1.f, 0.f); + glVertex3f(ws->getPos().x+scale, + height, ws->getPos().y-scale); glEnd(); + */ + } + } + } + + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + glDisableClientState(GL_NORMAL_ARRAY); + glDisableClientState(GL_VERTEX_ARRAY); + + glPopAttrib(); + + assertGl(); +} + +void Renderer::renderHud() { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + Texture2D *hudTexture = game->getGui()->getHudTexture(); + if (hudTexture != NULL) { + const Metrics &metrics = Metrics::getInstance(); + renderTextureQuad(0, 0, metrics.getVirtualW(), metrics.getVirtualH(), + hudTexture, 1.0f); + } +} + +void Renderer::renderMinimap() { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + const World *world = game->getWorld(); + const Minimap *minimap = world->getMinimap(); + + if (minimap == NULL || minimap->getTexture() == NULL) { + return; + } + + const GameCamera *gameCamera = game->getGameCamera(); + const Pixmap2D *pixmap = minimap->getTexture()->getPixmapConst(); + const Metrics &metrics = Metrics::getInstance(); + const WaterEffects *attackEffects = world->getAttackEffects(); + + int mx = metrics.getMinimapX(); + int my = metrics.getMinimapY(); + int mw = metrics.getMinimapW(); + int mh = metrics.getMinimapH(); + + Vec2f zoom = Vec2f(static_cast(mw) / pixmap->getW(), + static_cast(mh) / pixmap->getH()); + + assertGl(); + + // render minimap border + Vec4f col = game->getGui()->getDisplay()->getColor(); + glColor4f(col.x * 0.5f, col.y * 0.5f, col.z * 0.5f, 1.0); + + int borderWidth = 2; + glBegin(GL_QUADS); + glVertex2i(mx - borderWidth, my - borderWidth); + glVertex2i(mx - borderWidth, my); + glVertex2i(mx + mw + borderWidth, my); + glVertex2i(mx + mw + borderWidth, my - borderWidth); + glEnd(); + + glBegin(GL_QUADS); + glVertex2i(mx - borderWidth, my + mh + borderWidth); + glVertex2i(mx - borderWidth, my + mh); + glVertex2i(mx + mw + borderWidth, my + mh); + glVertex2i(mx + mw + borderWidth, my + mh + borderWidth); + glEnd(); + + glBegin(GL_QUADS); + glVertex2i(mx - borderWidth, my); + glVertex2i(mx - borderWidth, my + mh); + glVertex2i(mx, my + mh); + glVertex2i(mx, my); + glEnd(); + + glBegin(GL_QUADS); + glVertex2i(mx + mw, my); + glVertex2i(mx + mw, my + mh); + glVertex2i(mx + mw + borderWidth, my + mh); + glVertex2i(mx + mw + borderWidth, my); + glEnd(); + + assertGl(); + + glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT | GL_LINE_BIT | GL_TEXTURE_BIT); + + // draw map + glEnable(GL_TEXTURE_2D); + glEnable(GL_BLEND); + + glActiveTexture(fowTexUnit); + glEnable(GL_TEXTURE_2D); + glBindTexture( + GL_TEXTURE_2D, + static_cast(minimap->getFowTexture())->getHandle()); + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); + + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_INTERPOLATE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PREVIOUS); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_PRIMARY_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB, GL_TEXTURE); + + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_ADD); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_PRIMARY_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA, GL_TEXTURE); + + glActiveTexture(baseTexUnit); + glBindTexture( + GL_TEXTURE_2D, + static_cast(minimap->getTexture())->getHandle()); + + glColor4f(0.5f, 0.5f, 0.5f, 0.2f); + + glBegin(GL_TRIANGLE_STRIP); + glTexCoord2f(0.0f, 1.0f); + glMultiTexCoord2f(fowTexUnit, 0.0f, 1.0f); + glVertex2i(mx, my); + + glTexCoord2f(0.0f, 0.0f); + glMultiTexCoord2f(fowTexUnit, 0.0f, 0.0f); + glVertex2i(mx, my + mh); + + glTexCoord2f(1.0f, 1.0f); + glMultiTexCoord2f(fowTexUnit, 1.0f, 1.0f); + glVertex2i(mx + mw, my); + + glTexCoord2f(1.0f, 0.0f); + glMultiTexCoord2f(fowTexUnit, 1.0f, 0.0f); + glVertex2i(mx + mw, my + mh); + glEnd(); + + glDisable(GL_BLEND); + + glActiveTexture(fowTexUnit); + glDisable(GL_TEXTURE_2D); + glActiveTexture(baseTexUnit); + glDisable(GL_TEXTURE_2D); + + glEnable(GL_BLEND); + + const int itemCount = attackEffects->getWaterSplashCount() * 12; + if (itemCount > 0) { + vector vertices; + vertices.resize(itemCount); + vector colors; + colors.resize(itemCount); + + // draw attack alarm + int vertexIndex = 0; + for (int i = 0; i < attackEffects->getWaterSplashCount(); ++i) { + const WaterSplash *ws = attackEffects->getWaterSplash(i); + float scale = (1 / ws->getAnim() * ws->getSize()) * 5; + // glColor4f(1.f, 1.f, 0.f, 1.f-ws->getAnim()); + float alpha = (1.f - ws->getAnim()) * 0.01f; + Vec2f pos = ws->getPos() / Map::cellScale; + float attackX = mx + pos.x * zoom.x; + float attackY = my + mh - pos.y * zoom.y; + if (ws->getEnabled()) { + // glBegin(GL_QUADS); + // glVertex2f(attackX-scale, + // attackY-scale); glVertex2f(attackX-scale, + // attackY+scale); glVertex2f(attackX+scale, attackY+scale); + // glVertex2f(attackX+scale, attackY-scale); glEnd(); + + colors[vertexIndex] = Vec4f(1.f, 1.f, 0.f, alpha); + vertices[vertexIndex] = Vec2f(attackX - scale, attackY - scale); + vertexIndex++; + colors[vertexIndex] = Vec4f(1.f, 1.f, 0.f, alpha); + vertices[vertexIndex] = Vec2f(attackX - scale, attackY + scale); + vertexIndex++; + colors[vertexIndex] = Vec4f(1.f, 1.f, 0.f, 0.8f); + vertices[vertexIndex] = Vec2f(attackX, attackY); + vertexIndex++; + + colors[vertexIndex] = Vec4f(1.f, 1.f, 0.f, alpha); + vertices[vertexIndex] = Vec2f(attackX + scale, attackY + scale); + vertexIndex++; + colors[vertexIndex] = Vec4f(1.f, 1.f, 0.f, alpha); + vertices[vertexIndex] = Vec2f(attackX - scale, attackY + scale); + vertexIndex++; + colors[vertexIndex] = Vec4f(1.f, 1.f, 0.f, 0.8f); + vertices[vertexIndex] = Vec2f(attackX, attackY); + vertexIndex++; + + colors[vertexIndex] = Vec4f(1.f, 1.f, 0.f, alpha); + vertices[vertexIndex] = Vec2f(attackX + scale, attackY + scale); + vertexIndex++; + colors[vertexIndex] = Vec4f(1.f, 1.f, 0.f, alpha); + vertices[vertexIndex] = Vec2f(attackX + scale, attackY - scale); + vertexIndex++; + colors[vertexIndex] = Vec4f(1.f, 1.f, 0.f, 0.8f); + vertices[vertexIndex] = Vec2f(attackX, attackY); + vertexIndex++; + + colors[vertexIndex] = Vec4f(1.f, 1.f, 0.f, alpha); + vertices[vertexIndex] = Vec2f(attackX + scale, attackY - scale); + vertexIndex++; + colors[vertexIndex] = Vec4f(1.f, 1.f, 0.f, alpha); + vertices[vertexIndex] = Vec2f(attackX - scale, attackY - scale); + vertexIndex++; + colors[vertexIndex] = Vec4f(1.f, 1.f, 0.f, 0.8f); + vertices[vertexIndex] = Vec2f(attackX, attackY); + vertexIndex++; + + /* + glBegin(GL_TRIANGLES); + glColor4f(1.f, 1.f, 0.f, alpha); + glVertex2f(attackX-scale, + attackY-scale); glVertex2f(attackX-scale, attackY+scale); + glColor4f(1.f, 1.f, 0.f, 0.8f); + glVertex2f(attackX, attackY); + glEnd(); + glBegin(GL_TRIANGLES); + glColor4f(1.f, 1.f, 0.f, alpha); + glVertex2f(attackX-scale, + attackY+scale); glVertex2f(attackX+scale, attackY+scale); + glColor4f(1.f, 1.f, 0.f, 0.8f); + glVertex2f(attackX, attackY); + glEnd(); + glBegin(GL_TRIANGLES); + glColor4f(1.f, 1.f, 0.f, alpha); + glVertex2f(attackX+scale, + attackY+scale); glVertex2f(attackX+scale, attackY-scale); + glColor4f(1.f, 1.f, 0.f, 0.8f); + glVertex2f(attackX, attackY); + glEnd(); + glBegin(GL_TRIANGLES); + glColor4f(1.f, 1.f, 0.f, alpha); + glVertex2f(attackX+scale, + attackY-scale); glVertex2f(attackX-scale, attackY-scale); + glColor4f(1.f, 1.f, 0.f, 0.8f); + glVertex2f(attackX, attackY); + glEnd(); + */ + } + } - glTexCoord2f(1.0f, 1.0f); - glMultiTexCoord2f(fowTexUnit, 1.0f, 1.0f); - glVertex2i(mx+mw, my); + if (vertexIndex > 0) { + glEnableClientState(GL_COLOR_ARRAY); + glEnableClientState(GL_VERTEX_ARRAY); + glColorPointer(4, GL_FLOAT, 0, &colors[0]); + glVertexPointer(2, GL_FLOAT, 0, &vertices[0]); + glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexIndex); + glDisableClientState(GL_COLOR_ARRAY); + glDisableClientState(GL_VERTEX_ARRAY); + } + } + + glDisable(GL_BLEND); + + // draw units + VisibleQuadContainerCache &qCache = getQuadCache(); + std::vector visibleUnitList = qCache.visibleUnitList; + + const bool showAllUnitsInMinimap = + Config::getInstance().getBool("DebugGameSynchUI", "false"); + if (showAllUnitsInMinimap == true) { + visibleUnitList.clear(); + + const World *world = game->getWorld(); + for (unsigned int i = 0; i < (unsigned int)world->getFactionCount(); ++i) { + const Faction *faction = world->getFaction(i); + for (unsigned int j = 0; j < (unsigned int)faction->getUnitCount(); ++j) { + Unit *unit = faction->getUnit(j); + visibleUnitList.push_back(unit); + } + } + } + + if (visibleUnitList.empty() == false) { + uint32 unitIdx = 0; + vector unit_vertices; + unit_vertices.resize(visibleUnitList.size() * 4); + vector unit_colors; + unit_colors.resize(visibleUnitList.size() * 4); + + for (int visibleIndex = 0; visibleIndex < (int)visibleUnitList.size(); + ++visibleIndex) { + Unit *unit = visibleUnitList[visibleIndex]; + if (unit->isAlive() == false) { + continue; + } + + Vec2i pos = unit->getPos() / Map::cellScale; + int size = unit->getType()->getSize(); + Vec3f color = + unit->getFaction()->getTexture()->getPixmapConst()->getPixel3f(0, 0); + + unit_colors[unitIdx] = color; + unit_vertices[unitIdx] = + Vec2f(mx + pos.x * zoom.x, my + mh - (pos.y * zoom.y)); + unitIdx++; + + unit_colors[unitIdx] = color; + unit_vertices[unitIdx] = + Vec2f(mx + (pos.x + 1) * zoom.x + size, my + mh - (pos.y * zoom.y)); + unitIdx++; + + unit_colors[unitIdx] = color; + unit_vertices[unitIdx] = Vec2f(mx + (pos.x + 1) * zoom.x + size, + my + mh - ((pos.y + size) * zoom.y)); + unitIdx++; + + unit_colors[unitIdx] = color; + unit_vertices[unitIdx] = + Vec2f(mx + pos.x * zoom.x, my + mh - ((pos.y + size) * zoom.y)); + unitIdx++; + } - glTexCoord2f(1.0f, 0.0f); - glMultiTexCoord2f(fowTexUnit, 1.0f, 0.0f); - glVertex2i(mx+mw, my+mh); - glEnd(); + if (unitIdx > 0) { + glEnableClientState(GL_COLOR_ARRAY); + glEnableClientState(GL_VERTEX_ARRAY); + glColorPointer(3, GL_FLOAT, 0, &unit_colors[0]); + glVertexPointer(2, GL_FLOAT, 0, &unit_vertices[0]); + glDrawArrays(GL_QUADS, 0, unitIdx); + glDisableClientState(GL_COLOR_ARRAY); + glDisableClientState(GL_VERTEX_ARRAY); + } + } - glDisable(GL_BLEND); + renderMarkedCellsOnMinimap(); - glActiveTexture(fowTexUnit); - glDisable(GL_TEXTURE_2D); - glActiveTexture(baseTexUnit); - glDisable(GL_TEXTURE_2D); - - glEnable(GL_BLEND); - - const int itemCount = attackEffects->getWaterSplashCount() * 12; - if(itemCount > 0) { - vector vertices; - vertices.resize(itemCount); - vector colors; - colors.resize(itemCount); - - // draw attack alarm - int vertexIndex = 0; - for(int i = 0; i < attackEffects->getWaterSplashCount(); ++i) { - const WaterSplash *ws = attackEffects->getWaterSplash(i); - float scale= (1/ws->getAnim()*ws->getSize())*5; - //glColor4f(1.f, 1.f, 0.f, 1.f-ws->getAnim()); - float alpha=(1.f-ws->getAnim())*0.01f; - Vec2f pos= ws->getPos()/Map::cellScale; - float attackX=mx +pos.x*zoom.x; - float attackY=my +mh -pos.y*zoom.y; - if(ws->getEnabled()){ - // glBegin(GL_QUADS); - // glVertex2f(attackX-scale, attackY-scale); - // glVertex2f(attackX-scale, attackY+scale); - // glVertex2f(attackX+scale, attackY+scale); - // glVertex2f(attackX+scale, attackY-scale); - // glEnd(); - - colors[vertexIndex] = Vec4f(1.f, 1.f, 0.f, alpha); - vertices[vertexIndex] = Vec2f(attackX-scale, attackY-scale); - vertexIndex++; - colors[vertexIndex] = Vec4f(1.f, 1.f, 0.f, alpha); - vertices[vertexIndex] = Vec2f(attackX-scale, attackY+scale); - vertexIndex++; - colors[vertexIndex] = Vec4f(1.f, 1.f, 0.f, 0.8f); - vertices[vertexIndex] = Vec2f(attackX, attackY); - vertexIndex++; - - colors[vertexIndex] = Vec4f(1.f, 1.f, 0.f, alpha); - vertices[vertexIndex] = Vec2f(attackX+scale, attackY+scale); - vertexIndex++; - colors[vertexIndex] = Vec4f(1.f, 1.f, 0.f, alpha); - vertices[vertexIndex] = Vec2f(attackX-scale, attackY+scale); - vertexIndex++; - colors[vertexIndex] = Vec4f(1.f, 1.f, 0.f, 0.8f); - vertices[vertexIndex] = Vec2f(attackX, attackY); - vertexIndex++; - - colors[vertexIndex] = Vec4f(1.f, 1.f, 0.f, alpha); - vertices[vertexIndex] = Vec2f(attackX+scale, attackY+scale); - vertexIndex++; - colors[vertexIndex] = Vec4f(1.f, 1.f, 0.f, alpha); - vertices[vertexIndex] = Vec2f(attackX+scale, attackY-scale); - vertexIndex++; - colors[vertexIndex] = Vec4f(1.f, 1.f, 0.f, 0.8f); - vertices[vertexIndex] = Vec2f(attackX, attackY); - vertexIndex++; - - colors[vertexIndex] = Vec4f(1.f, 1.f, 0.f, alpha); - vertices[vertexIndex] = Vec2f(attackX+scale, attackY-scale); - vertexIndex++; - colors[vertexIndex] = Vec4f(1.f, 1.f, 0.f, alpha); - vertices[vertexIndex] = Vec2f(attackX-scale, attackY-scale); - vertexIndex++; - colors[vertexIndex] = Vec4f(1.f, 1.f, 0.f, 0.8f); - vertices[vertexIndex] = Vec2f(attackX, attackY); - vertexIndex++; - - /* - glBegin(GL_TRIANGLES); - glColor4f(1.f, 1.f, 0.f, alpha); - glVertex2f(attackX-scale, attackY-scale); - glVertex2f(attackX-scale, attackY+scale); - glColor4f(1.f, 1.f, 0.f, 0.8f); - glVertex2f(attackX, attackY); - glEnd(); - glBegin(GL_TRIANGLES); - glColor4f(1.f, 1.f, 0.f, alpha); - glVertex2f(attackX-scale, attackY+scale); - glVertex2f(attackX+scale, attackY+scale); - glColor4f(1.f, 1.f, 0.f, 0.8f); - glVertex2f(attackX, attackY); - glEnd(); - glBegin(GL_TRIANGLES); - glColor4f(1.f, 1.f, 0.f, alpha); - glVertex2f(attackX+scale, attackY+scale); - glVertex2f(attackX+scale, attackY-scale); - glColor4f(1.f, 1.f, 0.f, 0.8f); - glVertex2f(attackX, attackY); - glEnd(); - glBegin(GL_TRIANGLES); - glColor4f(1.f, 1.f, 0.f, alpha); - glVertex2f(attackX+scale, attackY-scale); - glVertex2f(attackX-scale, attackY-scale); - glColor4f(1.f, 1.f, 0.f, 0.8f); - glVertex2f(attackX, attackY); - glEnd(); - */ - - } - } - - if(vertexIndex > 0) { - glEnableClientState(GL_COLOR_ARRAY); - glEnableClientState(GL_VERTEX_ARRAY); - glColorPointer(4,GL_FLOAT, 0, &colors[0]); - glVertexPointer(2, GL_FLOAT, 0, &vertices[0]); - glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexIndex); - glDisableClientState(GL_COLOR_ARRAY); - glDisableClientState(GL_VERTEX_ARRAY); - } - } + // draw camera + float wRatio = + static_cast(metrics.getMinimapW()) / world->getMap()->getW(); + float hRatio = + static_cast(metrics.getMinimapH()) / world->getMap()->getH(); - glDisable(GL_BLEND); + int x = static_cast(gameCamera->getPos().x * wRatio); + int y = static_cast(gameCamera->getPos().z * hRatio); - //draw units - VisibleQuadContainerCache &qCache = getQuadCache(); - std::vector visibleUnitList = qCache.visibleUnitList; - - const bool showAllUnitsInMinimap = Config::getInstance().getBool("DebugGameSynchUI","false"); - if(showAllUnitsInMinimap == true) { - visibleUnitList.clear(); - - const World *world= game->getWorld(); - for(unsigned int i = 0; i < (unsigned int)world->getFactionCount(); ++i) { - const Faction *faction = world->getFaction(i); - for(unsigned int j = 0; j < (unsigned int)faction->getUnitCount(); ++j) { - Unit *unit = faction->getUnit(j); - visibleUnitList.push_back(unit); - } - } - } - - if(visibleUnitList.empty() == false) { - uint32 unitIdx=0; - vector unit_vertices; - unit_vertices.resize(visibleUnitList.size()*4); - vector unit_colors; - unit_colors.resize(visibleUnitList.size()*4); - - for(int visibleIndex = 0; - visibleIndex < (int)visibleUnitList.size(); ++visibleIndex) { - Unit *unit = visibleUnitList[visibleIndex]; - if (unit->isAlive() == false) { - continue; - } - - Vec2i pos= unit->getPos() / Map::cellScale; - int size= unit->getType()->getSize(); - Vec3f color= unit->getFaction()->getTexture()->getPixmapConst()->getPixel3f(0, 0); - - unit_colors[unitIdx] = color; - unit_vertices[unitIdx] = Vec2f(mx + pos.x*zoom.x, my + mh - (pos.y*zoom.y)); - unitIdx++; - - unit_colors[unitIdx] = color; - unit_vertices[unitIdx] = Vec2f(mx + (pos.x+1)*zoom.x+size, my + mh - (pos.y*zoom.y)); - unitIdx++; - - unit_colors[unitIdx] = color; - unit_vertices[unitIdx] = Vec2f(mx + (pos.x+1)*zoom.x+size, my + mh - ((pos.y+size)*zoom.y)); - unitIdx++; - - unit_colors[unitIdx] = color; - unit_vertices[unitIdx] = Vec2f(mx + pos.x*zoom.x, my + mh - ((pos.y+size)*zoom.y)); - unitIdx++; - } - - if(unitIdx > 0) { - glEnableClientState(GL_COLOR_ARRAY); - glEnableClientState(GL_VERTEX_ARRAY); - glColorPointer(3,GL_FLOAT, 0, &unit_colors[0]); - glVertexPointer(2, GL_FLOAT, 0, &unit_vertices[0]); - glDrawArrays(GL_QUADS, 0, unitIdx); - glDisableClientState(GL_COLOR_ARRAY); - glDisableClientState(GL_VERTEX_ARRAY); - } - - } - - renderMarkedCellsOnMinimap(); - - //draw camera - float wRatio= static_cast(metrics.getMinimapW()) / world->getMap()->getW(); - float hRatio= static_cast(metrics.getMinimapH()) / world->getMap()->getH(); - - int x= static_cast(gameCamera->getPos().x * wRatio); - int y= static_cast(gameCamera->getPos().z * hRatio); - - float ang= degToRad(gameCamera->getHAng()); + float ang = degToRad(gameCamera->getHAng()); - glEnable(GL_BLEND); + glEnable(GL_BLEND); - int x1; - int y1; - x1 = mx + x + static_cast(20*std::sin(ang-pi/5)); - y1 = my + mh - (y-static_cast(20*std::cos(ang-pi/5))); + int x1; + int y1; + x1 = mx + x + static_cast(20 * std::sin(ang - pi / 5)); + y1 = my + mh - (y - static_cast(20 * std::cos(ang - pi / 5))); - int x2; - int y2; - x2 = mx + x + static_cast(20*std::sin(ang+pi/5)); - y2 = my + mh - (y-static_cast(20*std::cos(ang+pi/5))); + int x2; + int y2; + x2 = mx + x + static_cast(20 * std::sin(ang + pi / 5)); + y2 = my + mh - (y - static_cast(20 * std::cos(ang + pi / 5))); - glColor4f(1.f, 1.f, 1.f, 1.f); - glBegin(GL_TRIANGLES); + glColor4f(1.f, 1.f, 1.f, 1.f); + glBegin(GL_TRIANGLES); - glVertex2i(mx+x, my+mh-y); - glColor4f(1.f, 1.f, 1.f, 0.0f); - glVertex2i(x1,y1); - glColor4f(1.f, 1.f, 1.f, 0.0f); - glVertex2i(x2,y2); + glVertex2i(mx + x, my + mh - y); + glColor4f(1.f, 1.f, 1.f, 0.0f); + glVertex2i(x1, y1); + glColor4f(1.f, 1.f, 1.f, 0.0f); + glVertex2i(x2, y2); - glEnd(); + glEnd(); - glPopAttrib(); + glPopAttrib(); - assertGl(); + assertGl(); } void Renderer::renderHighlightedCellsOnMinimap() { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - // Draw marked cells - const std::vector *highlightedCells = game->getHighlightedCells(); - if(highlightedCells->empty() == false) { - //const Map *map= game->getWorld()->getMap(); - const World *world= game->getWorld(); - const Minimap *minimap= world->getMinimap(); - int pointersize=10; - if(minimap == NULL || minimap->getTexture() == NULL) { - return; - } - - //const GameCamera *gameCamera= game->getGameCamera(); - const Pixmap2D *pixmap= minimap->getTexture()->getPixmapConst(); - const Metrics &metrics= Metrics::getInstance(); - - - //int mx= metrics.getMinimapX(); - int my= metrics.getMinimapY(); - int mw= metrics.getMinimapW(); - int mh= metrics.getMinimapH(); - - Vec2f zoom= Vec2f( - static_cast(mw)/ pixmap->getW()/2, - static_cast(mh)/ pixmap->getH()/2); - - for(int i = 0;i < (int)highlightedCells->size(); i++) { - const MarkedCell *mc=&highlightedCells->at(i); - if(mc->getFaction() == NULL || (mc->getFaction()->getTeam() == game->getWorld()->getThisFaction()->getTeam())) { - const Texture2D *texture= game->getHighlightCellTexture(); - Vec3f color(MarkedCell::static_system_marker_color); - if(mc->getFaction() != NULL) { - color= mc->getFaction()->getTexture()->getPixmapConst()->getPixel3f(0, 0); - } - int lighting=(mc->getAliveCount()%15); - Vec3f myColor=Vec3f(color.x/2+.5f/lighting,color.y/2+.5f/lighting,color.z/2+.5f/lighting); - - Vec2i pos=mc->getTargetPos(); - if(texture != NULL) { - //float alpha = 0.49f+0.5f/(mc->getAliveCount()%15); - float alpha=1.0f; - renderTextureQuad((int)(pos.x*zoom.x)+pointersize, my + mh-(int)(pos.y*zoom.y), pointersize, pointersize, texture, alpha,&myColor); - } - } - } - } -} - -void Renderer::renderMarkedCellsOnMinimap() { - // Draw marked cells - std::map markedCells = game->getMapMarkedCellList(); - if(markedCells.empty() == false) { - //const Map *map= game->getWorld()->getMap(); - const World *world= game->getWorld(); - const Minimap *minimap= world->getMinimap(); - - if(minimap == NULL || minimap->getTexture() == NULL) { - return; - } - - //const GameCamera *gameCamera= game->getGameCamera(); - const Pixmap2D *pixmap= minimap->getTexture()->getPixmapConst(); - const Metrics &metrics= Metrics::getInstance(); - //const WaterEffects *attackEffects= world->getAttackEffects(); - - int mx= metrics.getMinimapX(); - int my= metrics.getMinimapY(); - int mw= metrics.getMinimapW(); - int mh= metrics.getMinimapH(); - - Vec2f zoom= Vec2f( - static_cast(mw)/ pixmap->getW(), - static_cast(mh)/ pixmap->getH()); - - uint32 unitIdx=0; - vector unit_vertices; - unit_vertices.resize(markedCells.size()*4); - vector unit_colors; - unit_colors.resize(markedCells.size()*4); - - for(std::map::iterator iterMap =markedCells.begin(); - iterMap != markedCells.end(); ++iterMap) { - MarkedCell &bm = iterMap->second; - if(bm.getPlayerIndex() < 0 || - (bm.getFaction() != NULL && - bm.getFaction()->getTeam() == game->getWorld()->getThisFaction()->getTeam())) { - Vec2i pos= bm.getTargetPos() / Map::cellScale; - float size= 0.5f; - - Vec3f color(MarkedCell::static_system_marker_color); - if(bm.getFaction() != NULL) { - color= bm.getFaction()->getTexture()->getPixmapConst()->getPixel3f(0, 0); - } - float alpha = 0.65f; - - unit_colors[unitIdx] = Vec4f(color.x,color.y,color.z,alpha); - unit_vertices[unitIdx] = Vec2f(mx + pos.x*zoom.x, my + mh - (pos.y*zoom.y)); - unitIdx++; - - unit_colors[unitIdx] = Vec4f(color.x,color.y,color.z,alpha); - unit_vertices[unitIdx] = Vec2f(mx + (pos.x+1)*zoom.x+size, my + mh - (pos.y*zoom.y)); - unitIdx++; - - unit_colors[unitIdx] = Vec4f(color.x,color.y,color.z,alpha); - unit_vertices[unitIdx] = Vec2f(mx + (pos.x+1)*zoom.x+size, my + mh - ((pos.y+size)*zoom.y)); - unitIdx++; - - unit_colors[unitIdx] = Vec4f(color.x,color.y,color.z,alpha); - unit_vertices[unitIdx] = Vec2f(mx + pos.x*zoom.x, my + mh - ((pos.y+size)*zoom.y)); - unitIdx++; - } - } - - if(unitIdx > 0) { - glEnable(GL_BLEND); - - glEnableClientState(GL_COLOR_ARRAY); - glEnableClientState(GL_VERTEX_ARRAY); - glColorPointer(4,GL_FLOAT, 0, &unit_colors[0]); - glVertexPointer(2, GL_FLOAT, 0, &unit_vertices[0]); - glDrawArrays(GL_QUADS, 0, unitIdx); - //glDrawArrays(GL_TRIANGLE_STRIP, 0, unitIdx); - glDisableClientState(GL_COLOR_ARRAY); - glDisableClientState(GL_VERTEX_ARRAY); - - glDisable(GL_BLEND); - } - } -} -void Renderer::renderVisibleMarkedCells(bool renderTextHint,int x, int y) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - // Draw marked cells - std::map markedCells = game->getMapMarkedCellList(); - if(markedCells.empty() == false) { - const Texture2D *texture= game->getMarkCellTexture(); - const int yOffset = -40; - - for(std::map::iterator iterMap =markedCells.begin(); - iterMap != markedCells.end(); ++iterMap) { - MarkedCell &bm = iterMap->second; - if(bm.getPlayerIndex() < 0 || - (bm.getFaction() != NULL && - bm.getFaction()->getTeam() == game->getWorld()->getThisFaction()->getTeam())) { - const Map *map= game->getWorld()->getMap(); - std::pair bmVisible = posInCellQuadCache( - map->toSurfCoords(bm.getTargetPos())); - if(bmVisible.first == true) { - if(renderTextHint == true) { - if(bm.getNote() != "") { - bool validPosObjWorld= x > bmVisible.second.x && - y > bmVisible.second.y + yOffset && - x < bmVisible.second.x + texture->getTextureWidth() && - y < bmVisible.second.y + yOffset + texture->getTextureHeight(); - - if(validPosObjWorld) { - //printf("Checking for hint text render mouse [%d,%d] marker pos [%d,%d] validPosObjWorld = %d, hint [%s]\n",x,y,bm.getTargetPos().x,bm.getTargetPos().y,validPosObjWorld,bm.getNote().c_str()); - - //Lang &lang= Lang::getInstance(); - Vec4f fontColor = Vec4f(1.0f, 1.0f, 1.0f, 0.25f); - - if(renderText3DEnabled == true) { - renderTextShadow3D(bm.getNote(), CoreData::getInstance().getConsoleFont3D(), fontColor, - bmVisible.second.x, bmVisible.second.y); - } - else { - renderTextShadow(bm.getNote(), CoreData::getInstance().getConsoleFont(), fontColor, - bmVisible.second.x, bmVisible.second.y); - } - } - } - } - else { - - -/* - //texture 0 - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); - - //set color to interpolation - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_INTERPOLATE); - - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_TEXTURE); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR); - - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_TEXTURE1); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR); - - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB, GL_TEXTURE); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_ALPHA); - - //set alpha to 1 - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_TEXTURE); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA); - - //texture 1 - glActiveTexture(GL_TEXTURE1); - glMultiTexCoord2f(GL_TEXTURE1, 0.f, 0.f); - glEnable(GL_TEXTURE_2D); - - glBindTexture(GL_TEXTURE_2D, static_cast(bm.getFaction()->getTexture())->getHandle()); - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); - - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE); - - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PRIMARY_COLOR); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR); - - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_PREVIOUS); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR); - - //set alpha to 1 - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_PRIMARY_COLOR); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA); - - glActiveTexture(GL_TEXTURE0); -*/ - - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - - Vec3f color(MarkedCell::static_system_marker_color); - if(bm.getFaction() != NULL) { - color = bm.getFaction()->getTexture()->getPixmapConst()->getPixel3f(0,0); - } - - renderTextureQuad( - bmVisible.second.x,bmVisible.second.y + yOffset, - texture->getTextureWidth(),texture->getTextureHeight(),texture,0.8f,&color); - -/* - glActiveTexture(GL_TEXTURE1); - glDisable(GL_TEXTURE_2D); - glActiveTexture(GL_TEXTURE0); - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); -*/ - } - } - } - } - } -} + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + // Draw marked cells + const std::vector *highlightedCells = game->getHighlightedCells(); + if (highlightedCells->empty() == false) { + // const Map *map= game->getWorld()->getMap(); + const World *world = game->getWorld(); + const Minimap *minimap = world->getMinimap(); + int pointersize = 10; + if (minimap == NULL || minimap->getTexture() == NULL) { + return; + } -void Renderer::renderDisplay() { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - CoreData &coreData= CoreData::getInstance(); - const Metrics &metrics= Metrics::getInstance(); - const Display *display= game->getGui()->getDisplay(); - - glPushAttrib(GL_ENABLE_BIT); - - if(renderText3DEnabled == true) { - //infoString - renderTextShadow3D( - display->getInfoText().c_str(), - coreData.getDisplayFont3D(), - display->getColor(), - metrics.getDisplayX(), - metrics.getDisplayY()+Display::infoStringY); - - //title - renderTextShadow3D( - display->getTitle().c_str(), - coreData.getDisplayFont3D(), - display->getColor(), - metrics.getDisplayX()+40, - metrics.getDisplayY() + metrics.getDisplayH() - 20); - - glColor3f(0.0f, 0.0f, 0.0f); - - //text - renderTextShadow3D( - display->getText().c_str(), - coreData.getDisplayFont3D(), - display->getColor(), - metrics.getDisplayX() -1, - metrics.getDisplayY() + metrics.getDisplayH() - 56); - - //progress Bar - if(display->getProgressBar() != -1) { - renderProgressBar3D( - display->getProgressBar(), - metrics.getDisplayX(), - metrics.getDisplayY() + metrics.getDisplayH()-50, - coreData.getDisplayFontSmall3D(), 175); - } - } - else { - //infoString - renderTextShadow( - display->getInfoText().c_str(), - coreData.getDisplayFont(), - display->getColor(), - metrics.getDisplayX(), - metrics.getDisplayY()+Display::infoStringY); - - //title - renderTextShadow( - display->getTitle().c_str(), - coreData.getDisplayFont(), - display->getColor(), - metrics.getDisplayX()+40, - metrics.getDisplayY() + metrics.getDisplayH() - 20); - - glColor3f(0.0f, 0.0f, 0.0f); - - //text - renderTextShadow( - display->getText().c_str(), - coreData.getDisplayFont(), - display->getColor(), - metrics.getDisplayX() -1, - metrics.getDisplayY() + metrics.getDisplayH() - 56); - - //progress Bar - if(display->getProgressBar()!=-1){ - renderProgressBar( - display->getProgressBar(), - metrics.getDisplayX(), - metrics.getDisplayY() + metrics.getDisplayH()-50, - coreData.getDisplayFontSmall()); - } - } - - //up images - glEnable(GL_TEXTURE_2D); - - glColor3f(1.f, 1.f, 1.f); - for(int i=0; igetUpImage(i)!=NULL){ - renderQuad( - metrics.getDisplayX()+display->computeUpX(i), - metrics.getDisplayY()+display->computeUpY(i), - display->getUpImageSize(), display->getUpImageSize(), display->getUpImage(i)); - } - } - - //down images - for(int i=0; igetDownImage(i)!=NULL){ - Vec3f c=display->getDownImageColor(i); - glColor3f(c.x,c.y,c.z ); - - int x= metrics.getDisplayX()+display->computeDownX(i); - int y= metrics.getDisplayY()+display->computeDownY(i); - int size= Display::imageSize; - - if(display->getDownSelectedPos()==i){ - x-= 3; - y-= 3; - size+= 6; - } - - renderQuad(x, y, size, size, display->getDownImage(i)); - } - } - - //selection - int downPos= display->getDownSelectedPos(); - if(downPos!=Display::invalidPos){ - const Texture2D *texture= display->getDownImage(downPos); - if(texture!=NULL){ - int x= metrics.getDisplayX()+display->computeDownX(downPos)-3; - int y= metrics.getDisplayY()+display->computeDownY(downPos)-3; - int size= Display::imageSize+6; - renderQuad(x, y, size, size, display->getDownImage(downPos)); - } - } - - glPopAttrib(); + // const GameCamera *gameCamera= game->getGameCamera(); + const Pixmap2D *pixmap = minimap->getTexture()->getPixmapConst(); + const Metrics &metrics = Metrics::getInstance(); + + // int mx= metrics.getMinimapX(); + int my = metrics.getMinimapY(); + int mw = metrics.getMinimapW(); + int mh = metrics.getMinimapH(); + + Vec2f zoom = Vec2f(static_cast(mw) / pixmap->getW() / 2, + static_cast(mh) / pixmap->getH() / 2); + + for (int i = 0; i < (int)highlightedCells->size(); i++) { + const MarkedCell *mc = &highlightedCells->at(i); + if (mc->getFaction() == NULL || + (mc->getFaction()->getTeam() == + game->getWorld()->getThisFaction()->getTeam())) { + const Texture2D *texture = game->getHighlightCellTexture(); + Vec3f color(MarkedCell::static_system_marker_color); + if (mc->getFaction() != NULL) { + color = mc->getFaction()->getTexture()->getPixmapConst()->getPixel3f( + 0, 0); + } + int lighting = (mc->getAliveCount() % 15); + Vec3f myColor = + Vec3f(color.x / 2 + .5f / lighting, color.y / 2 + .5f / lighting, + color.z / 2 + .5f / lighting); + + Vec2i pos = mc->getTargetPos(); + if (texture != NULL) { + // float alpha = 0.49f+0.5f/(mc->getAliveCount()%15); + float alpha = 1.0f; + renderTextureQuad((int)(pos.x * zoom.x) + pointersize, + my + mh - (int)(pos.y * zoom.y), pointersize, + pointersize, texture, alpha, &myColor); + } + } + } + } } -void Renderer::renderMenuBackground(const MenuBackground *menuBackground) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - assertGl(); - - const Vec3f &cameraPosition= menuBackground->getCamera()->getConstPosition(); - - glPushAttrib(GL_LIGHTING_BIT | GL_ENABLE_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT); - - //clear - Vec4f fogColor= Vec4f(0.4f, 0.4f, 0.4f, 1.f) * menuBackground->getFade(); - glClearColor(fogColor.x, fogColor.y, fogColor.z, 1.f); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - glFogfv(GL_FOG_COLOR, fogColor.ptr()); - - //light - Vec4f lightPos= Vec4f(10.f, 10.f, 10.f, 1.f)* menuBackground->getFade(); - Vec4f diffLight= Vec4f(0.9f, 0.9f, 0.9f, 1.f)* menuBackground->getFade(); - Vec4f ambLight= Vec4f(0.3f, 0.3f, 0.3f, 1.f)* menuBackground->getFade(); - Vec4f specLight= Vec4f(0.1f, 0.1f, 0.1f, 1.f)* menuBackground->getFade(); - - glEnable(GL_LIGHT0); - glLightfv(GL_LIGHT0, GL_POSITION, lightPos.ptr()); - glLightfv(GL_LIGHT0, GL_DIFFUSE, diffLight.ptr()); - glLightfv(GL_LIGHT0, GL_AMBIENT, ambLight.ptr()); - glLightfv(GL_LIGHT0, GL_SPECULAR, specLight.ptr()); - - //main model - glEnable(GL_ALPHA_TEST); - glAlphaFunc(GL_GREATER, 0.5f); - modelRenderer->begin(true, true, true, false); - menuBackground->getMainModelPtr()->updateInterpolationData(menuBackground->getAnim(), true); - modelRenderer->render(menuBackground->getMainModelPtr()); - modelRenderer->end(); - glDisable(GL_ALPHA_TEST); - - //characters - float dist= menuBackground->getAboutPosition().dist(cameraPosition); - float minDist= 3.f; - if(dist < minDist) { - - glAlphaFunc(GL_GREATER, 0.0f); - float alpha= clamp((minDist-dist) / minDist, 0.f, 1.f); - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, Vec4f(1.0f, 1.0f, 1.0f, alpha).ptr()); - - std::vector &characterMenuScreenPositionListCache = - CacheManager::getCachedItem< std::vector >(GameConstants::characterMenuScreenPositionListCacheLookupKey); - characterMenuScreenPositionListCache.clear(); - - modelRenderer->begin(true, true, false, false); - - for(int i=0; i < MenuBackground::characterCount; ++i) { - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - glLoadIdentity(); - - Vec3f worldPos(i*2.f-4.f, -1.4f, -7.5f); - glTranslatef(worldPos.x,worldPos.y,worldPos.z); - - // - // Get the screen coordinates for each character model - START - //std::vector projection(16); - //std::vector modelview(16); - //std::vector screen_coords(3); - - //glGetDoublev(GL_PROJECTION_MATRIX, projection.data()); - //glGetDoublev(GL_MODELVIEW_MATRIX, modelview.data()); - - const Metrics &metrics= Metrics::getInstance(); - GLint viewport[]= {0, 0, metrics.getVirtualW(), metrics.getVirtualH()}; - - //get matrices - GLdouble projection[16]; - glGetDoublev(GL_PROJECTION_MATRIX, projection); - - GLdouble modelview[16]; - glGetDoublev(GL_MODELVIEW_MATRIX, modelview); - - //get the screen coordinates - GLdouble screen_coords[3]; - - gluProject(worldPos.x, worldPos.y, worldPos.z, - modelview, projection, viewport, - &screen_coords[0], &screen_coords[1], &screen_coords[2]); - characterMenuScreenPositionListCache.push_back(Vec3f(screen_coords[0],screen_coords[1],screen_coords[2])); - // Get the screen coordinates for each character model - END - // - - menuBackground->getCharacterModelPtr(i)->updateInterpolationData(menuBackground->getAnim(), true); - modelRenderer->render(menuBackground->getCharacterModelPtr(i)); - - glPopMatrix(); - } - modelRenderer->end(); - } - - //water - if(menuBackground->getWater()) { - - //water surface - const int waterTesselation= 10; - const int waterSize= 250; - const int waterQuadSize= 2*waterSize/waterTesselation; - const float waterHeight= menuBackground->getWaterHeight(); - - glEnable(GL_BLEND); - - glNormal3f(0.f, 1.f, 0.f); - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, Vec4f(1.f, 1.f, 1.f, 1.f).ptr()); - GLuint waterHandle= static_cast(menuBackground->getWaterTexture())->getHandle(); - glBindTexture(GL_TEXTURE_2D, waterHandle); - for(int i=1; i < waterTesselation; ++i) { - glBegin(GL_TRIANGLE_STRIP); - for(int j=1; j < waterTesselation; ++j) { - glTexCoord2i(1, 2 % j); - glVertex3f(-waterSize+i*waterQuadSize, waterHeight, -waterSize+j*waterQuadSize); - glTexCoord2i(0, 2 % j); - glVertex3f(-waterSize+(i+1)*waterQuadSize, waterHeight, -waterSize+j*waterQuadSize); - } - glEnd(); - } - glDisable(GL_BLEND); - - //raindrops - if(menuBackground->getRain()) { - const float maxRaindropAlpha= 0.5f; - - glEnable(GL_BLEND); - glDisable(GL_LIGHTING); - glDisable(GL_ALPHA_TEST); - glDepthMask(GL_FALSE); - - //splashes - CoreData &coreData= CoreData::getInstance(); - glBindTexture(GL_TEXTURE_2D, static_cast(coreData.getWaterSplashTexture())->getHandle()); - for(int i=0; i< MenuBackground::raindropCount; ++i) { - - Vec2f pos= menuBackground->getRaindropPos(i); - float scale= menuBackground->getRaindropState(i); - float alpha= maxRaindropAlpha-scale*maxRaindropAlpha; - - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - - glColor4f(1.f, 1.f, 1.f, alpha); - glTranslatef(pos.x, waterHeight+0.01f, pos.y); - - glBegin(GL_TRIANGLE_STRIP); - glTexCoord2f(0.f, 1.f); - glVertex3f(-scale, 0, scale); - glTexCoord2f(0.f, 0.f); - glVertex3f(-scale, 0, -scale); - glTexCoord2f(1.f, 1.f); - glVertex3f(scale, 0, scale); - glTexCoord2f(1.f, 0.f); - glVertex3f(scale, 0, -scale); - glEnd(); - - glPopMatrix(); - } - } - } - - glPopAttrib(); +void Renderer::renderMarkedCellsOnMinimap() { + // Draw marked cells + std::map markedCells = game->getMapMarkedCellList(); + if (markedCells.empty() == false) { + // const Map *map= game->getWorld()->getMap(); + const World *world = game->getWorld(); + const Minimap *minimap = world->getMinimap(); + + if (minimap == NULL || minimap->getTexture() == NULL) { + return; + } - assertGl(); -} + // const GameCamera *gameCamera= game->getGameCamera(); + const Pixmap2D *pixmap = minimap->getTexture()->getPixmapConst(); + const Metrics &metrics = Metrics::getInstance(); + // const WaterEffects *attackEffects= world->getAttackEffects(); + + int mx = metrics.getMinimapX(); + int my = metrics.getMinimapY(); + int mw = metrics.getMinimapW(); + int mh = metrics.getMinimapH(); + + Vec2f zoom = Vec2f(static_cast(mw) / pixmap->getW(), + static_cast(mh) / pixmap->getH()); + + uint32 unitIdx = 0; + vector unit_vertices; + unit_vertices.resize(markedCells.size() * 4); + vector unit_colors; + unit_colors.resize(markedCells.size() * 4); + + for (std::map::iterator iterMap = markedCells.begin(); + iterMap != markedCells.end(); ++iterMap) { + MarkedCell &bm = iterMap->second; + if (bm.getPlayerIndex() < 0 || + (bm.getFaction() != NULL && + bm.getFaction()->getTeam() == + game->getWorld()->getThisFaction()->getTeam())) { + Vec2i pos = bm.getTargetPos() / Map::cellScale; + float size = 0.5f; + + Vec3f color(MarkedCell::static_system_marker_color); + if (bm.getFaction() != NULL) { + color = + bm.getFaction()->getTexture()->getPixmapConst()->getPixel3f(0, 0); + } + float alpha = 0.65f; + + unit_colors[unitIdx] = Vec4f(color.x, color.y, color.z, alpha); + unit_vertices[unitIdx] = + Vec2f(mx + pos.x * zoom.x, my + mh - (pos.y * zoom.y)); + unitIdx++; + + unit_colors[unitIdx] = Vec4f(color.x, color.y, color.z, alpha); + unit_vertices[unitIdx] = + Vec2f(mx + (pos.x + 1) * zoom.x + size, my + mh - (pos.y * zoom.y)); + unitIdx++; + + unit_colors[unitIdx] = Vec4f(color.x, color.y, color.z, alpha); + unit_vertices[unitIdx] = Vec2f(mx + (pos.x + 1) * zoom.x + size, + my + mh - ((pos.y + size) * zoom.y)); + unitIdx++; + + unit_colors[unitIdx] = Vec4f(color.x, color.y, color.z, alpha); + unit_vertices[unitIdx] = + Vec2f(mx + pos.x * zoom.x, my + mh - ((pos.y + size) * zoom.y)); + unitIdx++; + } + } -void Renderer::renderMenuBackground(Camera *camera, float fade, Model *mainModel, vector characterModels,const Vec3f characterPosition, float anim) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } + if (unitIdx > 0) { + glEnable(GL_BLEND); - assertGl(); + glEnableClientState(GL_COLOR_ARRAY); + glEnableClientState(GL_VERTEX_ARRAY); + glColorPointer(4, GL_FLOAT, 0, &unit_colors[0]); + glVertexPointer(2, GL_FLOAT, 0, &unit_vertices[0]); + glDrawArrays(GL_QUADS, 0, unitIdx); + // glDrawArrays(GL_TRIANGLE_STRIP, 0, unitIdx); + glDisableClientState(GL_COLOR_ARRAY); + glDisableClientState(GL_VERTEX_ARRAY); - const Vec3f &cameraPosition= camera->getConstPosition(); - - glPushAttrib(GL_LIGHTING_BIT | GL_ENABLE_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT); - - //clear - //Vec4f fogColor= Vec4f(0.4f, 0.4f, 0.4f, 1.f) * fade; - // Show black bacground - Vec4f fogColor= Vec4f(0.f, 0.f, 0.f, 1.f); - glClearColor(fogColor.x, fogColor.y, fogColor.z, 1.f); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - glFogfv(GL_FOG_COLOR, fogColor.ptr()); - - //light - Vec4f lightPos= Vec4f(10.f, 10.f, 10.f, 1.f) * fade; - Vec4f diffLight= Vec4f(0.9f, 0.9f, 0.9f, 1.f) * fade; - Vec4f ambLight= Vec4f(0.3f, 0.3f, 0.3f, 1.f) * fade; - Vec4f specLight= Vec4f(0.1f, 0.1f, 0.1f, 1.f) * fade; - - glEnable(GL_LIGHT0); - glLightfv(GL_LIGHT0, GL_POSITION, lightPos.ptr()); - glLightfv(GL_LIGHT0, GL_DIFFUSE, diffLight.ptr()); - glLightfv(GL_LIGHT0, GL_AMBIENT, ambLight.ptr()); - glLightfv(GL_LIGHT0, GL_SPECULAR, specLight.ptr()); - - //main model - if(mainModel) { - glEnable(GL_ALPHA_TEST); - glAlphaFunc(GL_GREATER, 0.5f); - modelRenderer->begin(true, true, true, false); - mainModel->updateInterpolationData(anim, true); - modelRenderer->render(mainModel); - modelRenderer->end(); - glDisable(GL_ALPHA_TEST); - } - - //characters - if(characterModels.empty() == false) { - float dist= characterPosition.dist(cameraPosition); - float minDist= 3.f; - if(dist < minDist) { - glAlphaFunc(GL_GREATER, 0.0f); - float alpha= clamp((minDist-dist) / minDist, 0.f, 1.f); - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, Vec4f(1.0f, 1.0f, 1.0f, alpha).ptr()); - modelRenderer->begin(true, true, false, false); - - for(unsigned int i = 0; i < characterModels.size(); ++i) { - if(characterModels[i]) { - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - glLoadIdentity(); - glTranslatef(i*2.f-4.f, -1.4f, -7.5f); - characterModels[i]->updateInterpolationData(anim, true); - modelRenderer->render(characterModels[i]); - glPopMatrix(); - } - } - modelRenderer->end(); - } - } - - - glPopAttrib(); + glDisable(GL_BLEND); + } + } +} +void Renderer::renderVisibleMarkedCells(bool renderTextHint, int x, int y) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + // Draw marked cells + std::map markedCells = game->getMapMarkedCellList(); + if (markedCells.empty() == false) { + const Texture2D *texture = game->getMarkCellTexture(); + const int yOffset = -40; + + for (std::map::iterator iterMap = markedCells.begin(); + iterMap != markedCells.end(); ++iterMap) { + MarkedCell &bm = iterMap->second; + if (bm.getPlayerIndex() < 0 || + (bm.getFaction() != NULL && + bm.getFaction()->getTeam() == + game->getWorld()->getThisFaction()->getTeam())) { + const Map *map = game->getWorld()->getMap(); + std::pair bmVisible = + posInCellQuadCache(map->toSurfCoords(bm.getTargetPos())); + if (bmVisible.first == true) { + if (renderTextHint == true) { + if (bm.getNote() != "") { + bool validPosObjWorld = + x > bmVisible.second.x && y > bmVisible.second.y + yOffset && + x < bmVisible.second.x + texture->getTextureWidth() && + y < bmVisible.second.y + yOffset + + texture->getTextureHeight(); + + if (validPosObjWorld) { + // printf("Checking for hint text render mouse [%d,%d] marker + // pos [%d,%d] validPosObjWorld = %d, hint + // [%s]\n",x,y,bm.getTargetPos().x,bm.getTargetPos().y,validPosObjWorld,bm.getNote().c_str()); + + // Lang &lang= Lang::getInstance(); + Vec4f fontColor = Vec4f(1.0f, 1.0f, 1.0f, 0.25f); + + if (renderText3DEnabled == true) { + renderTextShadow3D( + bm.getNote(), CoreData::getInstance().getConsoleFont3D(), + fontColor, bmVisible.second.x, bmVisible.second.y); + } else { + renderTextShadow( + bm.getNote(), CoreData::getInstance().getConsoleFont(), + fontColor, bmVisible.second.x, bmVisible.second.y); + } + } + } + } else { + + /* + //texture 0 + glTexEnvi(GL_TEXTURE_ENV, + GL_TEXTURE_ENV_MODE, GL_COMBINE); + + //set color to + interpolation glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, + GL_INTERPOLATE); + + glTexEnvi(GL_TEXTURE_ENV, + GL_SOURCE0_RGB, GL_TEXTURE); glTexEnvi(GL_TEXTURE_ENV, + GL_OPERAND0_RGB, GL_SRC_COLOR); + + glTexEnvi(GL_TEXTURE_ENV, + GL_SOURCE1_RGB, GL_TEXTURE1); glTexEnvi(GL_TEXTURE_ENV, + GL_OPERAND1_RGB, GL_SRC_COLOR); + + glTexEnvi(GL_TEXTURE_ENV, + GL_SOURCE2_RGB, GL_TEXTURE); glTexEnvi(GL_TEXTURE_ENV, + GL_OPERAND2_RGB, GL_SRC_ALPHA); + + //set alpha to 1 + glTexEnvi(GL_TEXTURE_ENV, + GL_COMBINE_ALPHA, GL_REPLACE); glTexEnvi(GL_TEXTURE_ENV, + GL_SOURCE0_ALPHA, GL_TEXTURE); glTexEnvi(GL_TEXTURE_ENV, + GL_OPERAND0_ALPHA, GL_SRC_ALPHA); + + //texture 1 + glActiveTexture(GL_TEXTURE1); + glMultiTexCoord2f(GL_TEXTURE1, + 0.f, 0.f); glEnable(GL_TEXTURE_2D); + + glBindTexture(GL_TEXTURE_2D, + static_cast(bm.getFaction()->getTexture())->getHandle()); + glTexEnvi(GL_TEXTURE_ENV, + GL_TEXTURE_ENV_MODE, GL_COMBINE); + + glTexEnvi(GL_TEXTURE_ENV, + GL_COMBINE_RGB, GL_MODULATE); + + glTexEnvi(GL_TEXTURE_ENV, + GL_SOURCE0_RGB, GL_PRIMARY_COLOR); glTexEnvi(GL_TEXTURE_ENV, + GL_OPERAND0_RGB, GL_SRC_COLOR); + + glTexEnvi(GL_TEXTURE_ENV, + GL_SOURCE1_RGB, GL_PREVIOUS); glTexEnvi(GL_TEXTURE_ENV, + GL_OPERAND1_RGB, GL_SRC_COLOR); + + //set alpha to 1 + glTexEnvi(GL_TEXTURE_ENV, + GL_COMBINE_ALPHA, GL_REPLACE); glTexEnvi(GL_TEXTURE_ENV, + GL_SOURCE0_ALPHA, GL_PRIMARY_COLOR); glTexEnvi(GL_TEXTURE_ENV, + GL_OPERAND0_ALPHA, GL_SRC_ALPHA); + + glActiveTexture(GL_TEXTURE0); + */ + + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + Vec3f color(MarkedCell::static_system_marker_color); + if (bm.getFaction() != NULL) { + color = + bm.getFaction()->getTexture()->getPixmapConst()->getPixel3f( + 0, 0); + } - assertGl(); + renderTextureQuad(bmVisible.second.x, bmVisible.second.y + yOffset, + texture->getTextureWidth(), + texture->getTextureHeight(), texture, 0.8f, + &color); + + /* + glActiveTexture(GL_TEXTURE1); + glDisable(GL_TEXTURE_2D); + glActiveTexture(GL_TEXTURE0); + glTexEnvi(GL_TEXTURE_ENV, + GL_TEXTURE_ENV_MODE, GL_MODULATE); + */ + } + } + } + } + } } -// ==================== computing ==================== - -bool Renderer::ccomputePosition(const Vec2i &screenPos, Vec2i &worldPos, bool exactCoords) { - assertGl(); - const Map* map= game->getWorld()->getMap(); - const Metrics &metrics= Metrics::getInstance(); - float depth= 0.0f; - GLdouble modelviewMatrix[16]; - GLdouble projectionMatrix[16]; - GLint viewport[4]= {0, 0, metrics.getScreenW(), metrics.getScreenH()}; - GLdouble worldX; - GLdouble worldY; - GLdouble worldZ; - GLint screenX= (screenPos.x * metrics.getScreenW() / metrics.getVirtualW()); - GLint screenY= (screenPos.y * metrics.getScreenH() / metrics.getVirtualH()); - - //get the depth in the cursor pixel - glReadPixels(screenX, screenY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth); - - //load matrices - loadProjectionMatrix(); - loadGameCameraMatrix(); - - //get matrices - glGetDoublev(GL_MODELVIEW_MATRIX, modelviewMatrix); - glGetDoublev(GL_PROJECTION_MATRIX, projectionMatrix); - - //get the world coordinates - gluUnProject( - screenX, screenY, depth, - modelviewMatrix, projectionMatrix, viewport, - &worldX, &worldY, &worldZ); - - //conver coords to int - if(exactCoords == true) { - worldPos= Vec2i(static_cast(worldX), static_cast(worldZ)); - } - else { - worldPos= Vec2i(static_cast(worldX+0.5f), static_cast(worldZ+0.5f)); - } - - //clamp coords to map size - return map->isInside(worldPos); -} +void Renderer::renderDisplay() { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + CoreData &coreData = CoreData::getInstance(); + const Metrics &metrics = Metrics::getInstance(); + const Display *display = game->getGui()->getDisplay(); + + glPushAttrib(GL_ENABLE_BIT); + + if (renderText3DEnabled == true) { + // infoString + renderTextShadow3D(display->getInfoText().c_str(), + coreData.getDisplayFont3D(), display->getColor(), + metrics.getDisplayX(), + metrics.getDisplayY() + Display::infoStringY); + + // title + renderTextShadow3D(display->getTitle().c_str(), coreData.getDisplayFont3D(), + display->getColor(), metrics.getDisplayX() + 40, + metrics.getDisplayY() + metrics.getDisplayH() - 20); + + glColor3f(0.0f, 0.0f, 0.0f); + + // text + renderTextShadow3D(display->getText().c_str(), coreData.getDisplayFont3D(), + display->getColor(), metrics.getDisplayX() - 1, + metrics.getDisplayY() + metrics.getDisplayH() - 56); + + // progress Bar + if (display->getProgressBar() != -1) { + renderProgressBar3D(display->getProgressBar(), metrics.getDisplayX(), + metrics.getDisplayY() + metrics.getDisplayH() - 50, + coreData.getDisplayFontSmall3D(), 175); + } + } else { + // infoString + renderTextShadow(display->getInfoText().c_str(), coreData.getDisplayFont(), + display->getColor(), metrics.getDisplayX(), + metrics.getDisplayY() + Display::infoStringY); + + // title + renderTextShadow(display->getTitle().c_str(), coreData.getDisplayFont(), + display->getColor(), metrics.getDisplayX() + 40, + metrics.getDisplayY() + metrics.getDisplayH() - 20); + + glColor3f(0.0f, 0.0f, 0.0f); + + // text + renderTextShadow(display->getText().c_str(), coreData.getDisplayFont(), + display->getColor(), metrics.getDisplayX() - 1, + metrics.getDisplayY() + metrics.getDisplayH() - 56); + + // progress Bar + if (display->getProgressBar() != -1) { + renderProgressBar(display->getProgressBar(), metrics.getDisplayX(), + metrics.getDisplayY() + metrics.getDisplayH() - 50, + coreData.getDisplayFontSmall()); + } + } + + // up images + glEnable(GL_TEXTURE_2D); + + glColor3f(1.f, 1.f, 1.f); + for (int i = 0; i < Display::upCellCount; ++i) { + if (display->getUpImage(i) != NULL) { + renderQuad(metrics.getDisplayX() + display->computeUpX(i), + metrics.getDisplayY() + display->computeUpY(i), + display->getUpImageSize(), display->getUpImageSize(), + display->getUpImage(i)); + } + } -// This method takes world co-ordinates and translates them to screen co-ords -Vec3f Renderer::computeScreenPosition(const Vec3f &worldPos) { - if(worldToScreenPosCache.find(worldPos) != worldToScreenPosCache.end()) { - return worldToScreenPosCache[worldPos]; - } - assertGl(); + // down images + for (int i = 0; i < Display::downCellCount; ++i) { + if (display->getDownImage(i) != NULL) { + Vec3f c = display->getDownImageColor(i); + glColor3f(c.x, c.y, c.z); - const Metrics &metrics= Metrics::getInstance(); - GLint viewport[]= {0, 0, metrics.getVirtualW(), metrics.getVirtualH()}; - GLdouble worldX = worldPos.x; - GLdouble worldY = worldPos.y; - GLdouble worldZ = worldPos.z; - - //load matrices - loadProjectionMatrix(); - loadGameCameraMatrix(); - - //get matrices - GLdouble modelviewMatrix[16]; - glGetDoublev(GL_MODELVIEW_MATRIX, modelviewMatrix); - GLdouble projectionMatrix[16]; - glGetDoublev(GL_PROJECTION_MATRIX, projectionMatrix); - - //get the screen coordinates - GLdouble screenX; - GLdouble screenY; - GLdouble screenZ; - gluProject(worldX, worldY, worldZ, - modelviewMatrix, projectionMatrix, viewport, - &screenX, &screenY, &screenZ); - - Vec3f screenPos(screenX,screenY,screenZ); - worldToScreenPosCache[worldPos]=screenPos; - - return screenPos; -} - -void Renderer::computeSelected( Selection::UnitContainer &units, const Object *&obj, - const bool withObjectSelection, - const Vec2i &posDown, const Vec2i &posUp) { - const string selectionType=toLower(Config::getInstance().getString("SelectionType",Config::colorPicking)); - - if(selectionType==Config::colorPicking) { - selectUsingColorPicking(units,obj, withObjectSelection,posDown, posUp); - } - /// Frustum approach --> Currently not accurate enough - else if(selectionType==Config::frustumPicking) { - selectUsingFrustumSelection(units,obj, withObjectSelection,posDown, posUp); - } - else { - selectUsingSelectionBuffer(units,obj, withObjectSelection,posDown, posUp); - } -} + int x = metrics.getDisplayX() + display->computeDownX(i); + int y = metrics.getDisplayY() + display->computeDownY(i); + int size = Display::imageSize; -void Renderer::selectUsingFrustumSelection(Selection::UnitContainer &units, - const Object *&obj, const bool withObjectSelection, - const Vec2i &posDown, const Vec2i &posUp) { - glMatrixMode(GL_PROJECTION); - glPushMatrix(); - glLoadIdentity(); - - const Metrics &metrics= Metrics::getInstance(); - GLint view[]= {0, 0, metrics.getVirtualW(), metrics.getVirtualH()}; - - //compute center and dimensions of selection rectangle - int x = (posDown.x+posUp.x) / 2; - int y = (posDown.y+posUp.y) / 2; - int w = abs(posDown.x-posUp.x); - int h = abs(posDown.y-posUp.y); - if(w < 2) { - w = 2; - } - if(h < 2) { - h = 2; - } - - gluPickMatrix(x, y, w, h, view); - gluPerspective(perspFov, metrics.getAspectRatio(), perspNearPlane, perspFarPlane); - loadGameCameraMatrix(); - - VisibleQuadContainerCache quadSelectionCacheItem; - ExtractFrustum(quadSelectionCacheItem); - - //pop matrices - glMatrixMode(GL_PROJECTION); - glPopMatrix(); - - VisibleQuadContainerCache &qCache = getQuadCache(); - if(qCache.visibleQuadUnitList.empty() == false) { - for(int visibleUnitIndex = 0; - visibleUnitIndex < (int)qCache.visibleQuadUnitList.size(); ++visibleUnitIndex) { - Unit *unit = qCache.visibleQuadUnitList[visibleUnitIndex]; - if(unit != NULL && unit->isAlive()) { - Vec3f unitPos = unit->getCurrMidHeightVector(); - bool insideQuad = CubeInFrustum(quadSelectionCacheItem.frustumData, - unitPos.x, unitPos.y, unitPos.z, unit->getType()->getRenderSize()); - if(insideQuad == true) { - units.push_back(unit); - } - } - } - } - - if(withObjectSelection == true) { - if(qCache.visibleObjectList.empty() == false) { - for(int visibleIndex = 0; - visibleIndex < (int)qCache.visibleObjectList.size(); ++visibleIndex) { - Object *object = qCache.visibleObjectList[visibleIndex]; - if(object != NULL) { - bool insideQuad = CubeInFrustum(quadSelectionCacheItem.frustumData, - object->getPos().x, object->getPos().y, object->getPos().z, 1); - if(insideQuad == true) { - obj = object; - //if(withObjectSelection == true) { - break; - //} - } - } - } - } - } -} + if (display->getDownSelectedPos() == i) { + x -= 3; + y -= 3; + size += 6; + } -void Renderer::selectUsingSelectionBuffer(Selection::UnitContainer &units, - const Object *&obj, const bool withObjectSelection, - const Vec2i &posDown, const Vec2i &posUp) { - //compute center and dimensions of selection rectangle - int x = (posDown.x+posUp.x) / 2; - int y = (posDown.y+posUp.y) / 2; - int w = abs(posDown.x-posUp.x); - int h = abs(posDown.y-posUp.y); - if(w < 2) { - w = 2; - } - if(h < 2) { - h = 2; - } - - //declarations - GLuint selectBuffer[Gui::maxSelBuff]; - - //setup matrices - glSelectBuffer(Gui::maxSelBuff, selectBuffer); - //glMatrixMode(GL_PROJECTION); - //glPushMatrix(); - - GLint renderModeResult = glRenderMode(GL_SELECT); - if(renderModeResult < 0) { - const char *errorString= reinterpret_cast(gluErrorString(renderModeResult)); - char szBuf[8096]=""; - snprintf(szBuf,8096,"OpenGL error #%d [0x%X] : [%s] at file: [%s], line: %d",renderModeResult,renderModeResult,errorString,extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - - printf("%s\n",szBuf); - } - - - glPushMatrix(); - glMatrixMode(GL_PROJECTION); - - glLoadIdentity(); - - const Metrics &metrics= Metrics::getInstance(); - GLint view[]= {0, 0, metrics.getVirtualW(), metrics.getVirtualH()}; - //GLint view[4]; - //glGetIntegerv(GL_VIEWPORT, view); - - gluPickMatrix(x, y, w, h, view); - gluPerspective(perspFov, metrics.getAspectRatio(), perspNearPlane, perspFarPlane); - //gluPerspective(perspFov, metrics.getAspectRatio(), 0.0001, 1000.0); - //gluPerspective(perspFov, (float)view[2]/(float)view[3], perspNearPlane, perspFarPlane); - loadGameCameraMatrix(); - - //render units to find which ones should be selected - renderUnitsFast(); - if(withObjectSelection == true) { - renderObjectsFast(false,true); - } - - //pop matrices - glPopMatrix(); - - // Added this to ensure all the selection calls are done now - // (see http://www.unknownroad.com/rtfm/graphics/glselection.html section: [0x4]) - //glFlush(); - - //select units by checking the selected buffer - int selCount= glRenderMode(GL_RENDER); - if(selCount > 0) { - VisibleQuadContainerCache &qCache = getQuadCache(); - for(int i = 1; i <= selCount; ++i) { - int index = selectBuffer[i*4-1]; - if(index >= OBJECT_SELECT_OFFSET) { - Object *object = qCache.visibleObjectList[index - OBJECT_SELECT_OFFSET]; - if(object != NULL) { - obj = object; - if(withObjectSelection == true) { - break; - } - } - } - else { - Unit *unit = qCache.visibleQuadUnitList[index]; - if(unit != NULL && unit->isAlive()) { - units.push_back(unit); - } - } - } - } - else if(selCount < 0) { - const char *errorString= reinterpret_cast(gluErrorString(selCount)); - char szBuf[8096]=""; - snprintf(szBuf,8096,"OpenGL error #%d [0x%X] : [%s] at file: [%s], line: %d",selCount,selCount,errorString,extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - - printf("%s\n",szBuf); - } -} + renderQuad(x, y, size, size, display->getDownImage(i)); + } + } + + // selection + int downPos = display->getDownSelectedPos(); + if (downPos != Display::invalidPos) { + const Texture2D *texture = display->getDownImage(downPos); + if (texture != NULL) { + int x = metrics.getDisplayX() + display->computeDownX(downPos) - 3; + int y = metrics.getDisplayY() + display->computeDownY(downPos) - 3; + int size = Display::imageSize + 6; + renderQuad(x, y, size, size, display->getDownImage(downPos)); + } + } -void Renderer::selectUsingColorPicking(Selection::UnitContainer &units, - const Object *&obj, const bool withObjectSelection, - const Vec2i &posDown, const Vec2i &posUp) { - int x1 = posDown.x; - int y1 = posDown.y; - int x2 = posUp.x; - int y2 = posUp.y; - - int x = min(x1,x2); - int y = min(y1,y2); - int w = max(x1,x2) - min(x1,x2); - int h = max(y1,y2) - min(y1,y2); - if(w < 2) { - w = 2; - } - if(h < 2) { - h = 2; - } - - const Metrics &metrics= Metrics::getInstance(); - x= (x * metrics.getScreenW() / metrics.getVirtualW()); - y= (y * metrics.getScreenH() / metrics.getVirtualH()); - - w= (w * metrics.getScreenW() / metrics.getVirtualW()); - h= (h * metrics.getScreenH() / metrics.getVirtualH()); - - PixelBufferWrapper::begin(); - - - glPushMatrix(); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - //GLint view[]= {0, 0, metrics.getVirtualW(), metrics.getVirtualH()}; - //gluPickMatrix(x, y, w, h, view); - gluPerspective(perspFov, metrics.getAspectRatio(), perspNearPlane, perspFarPlane); - loadGameCameraMatrix(); - - //render units to find which ones should be selected - //printf("In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - vector rendererUnits = renderUnitsFast(false, true); - //printf("In [%s::%s] Line: %d rendererUnits = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,rendererUnits.size()); - - - // Added this to ensure all the selection calls are done now - // (see http://www.unknownroad.com/rtfm/graphics/glselection.html section: [0x4]) - //glFlush(); - - //GraphicsInterface::getInstance().getCurrentContext()->swapBuffers(); - - PixelBufferWrapper::end(); - - vector unitsVector; - bool unitFound=false; - - if(rendererUnits.empty() == false) { - copy(rendererUnits.begin(), rendererUnits.end(), std::inserter(unitsVector, unitsVector.begin())); - } - - if(unitsVector.empty() == false) { - vector pickedList = BaseColorPickEntity::getPickedList(x,y,w,h, unitsVector); - //printf("In [%s::%s] Line: %d pickedList = %d models rendered = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,pickedList.size(),rendererModels.size()); - - if(pickedList.empty() == false) { - units.reserve(pickedList.size()); - for(unsigned int i = 0; i < pickedList.size(); ++i) { - int index = pickedList[i]; - //printf("In [%s::%s] Line: %d searching for selected object i = %d index = %d units = %d objects = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,index,rendererUnits.size(),rendererObjects.size()); - - if(rendererUnits.empty() == false && index < (int)rendererUnits.size()) { - Unit *unit = rendererUnits[index]; - if(unit != NULL && unit->isAlive()) { - unitFound=true; - units.push_back(unit); - } - } - } - } - } - - if(withObjectSelection == true && unitFound==false) { - vector rendererObjects; - vector objectsVector; - rendererObjects = renderObjectsFast(false,true,true); - if(rendererObjects.empty() == false) { - copy(rendererObjects.begin(), rendererObjects.end(), std::inserter(objectsVector, objectsVector.begin())); - } - - if(objectsVector.empty() == false) { - vector pickedList = BaseColorPickEntity::getPickedList(x,y,w,h, objectsVector); - //printf("In [%s::%s] Line: %d pickedList = %d models rendered = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,pickedList.size(),rendererModels.size()); - - if(pickedList.empty() == false) { - for(unsigned int i = 0; i < pickedList.size(); ++i) { - int index = pickedList[i]; - //printf("In [%s::%s] Line: %d searching for selected object i = %d index = %d units = %d objects = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,index,rendererUnits.size(),rendererObjects.size()); - - if(rendererObjects.empty() == false && index < (int)rendererObjects.size()) { - Object *object = rendererObjects[index]; - //printf("In [%s::%s] Line: %d searching for selected object i = %d index = %d [%p]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,index,object); - - if(object != NULL) { - obj = object; - break; - } - } - } - } - } - } - //pop matrices - glPopMatrix(); + glPopAttrib(); } -// ==================== shadows ==================== - -void Renderer::renderShadowsToTexture(const int renderFps){ - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - if(shadowsOffDueToMinRender == false && - (shadows == sProjected || shadows == sShadowMapping)) { - - shadowMapFrame= (shadowMapFrame + 1) % (shadowFrameSkip + 1); - - if(shadowMapFrame == 0){ - assertGl(); - - glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT | GL_COLOR_BUFFER_BIT | GL_VIEWPORT_BIT | GL_POLYGON_BIT); - - if(shadows == sShadowMapping) { - glClear(GL_DEPTH_BUFFER_BIT); - } - else { - float color= 1.0f-shadowIntensity; - glColor3f(color, color, color); - glClearColor(1.f, 1.f, 1.f, 1.f); - glDisable(GL_DEPTH_TEST); - glClear(GL_COLOR_BUFFER_BIT); - } - - //assertGl(); - - //clear color buffer - // - //set viewport, we leave one texel always in white to avoid problems - glViewport(1, 1, shadowTextureSize-2, shadowTextureSize-2); - - //assertGl(); - - if(nearestLightPos.w == 0.f) { - //directional light - - //light pos - assert(game != NULL); - assert(game->getWorld() != NULL); - const TimeFlow *tf= game->getWorld()->getTimeFlow(); - assert(tf != NULL); - float ang= tf->isDay()? computeSunAngle(tf->getTime()): computeMoonAngle(tf->getTime()); - ang= radToDeg(ang); - - //push and set projection - glMatrixMode(GL_PROJECTION); - glPushMatrix(); - glLoadIdentity(); - - //assertGl(); - - if(game->getGameCamera()->getState()==GameCamera::sGame){ - //glOrtho(-35, 5, -15, 15, -1000, 1000); - //glOrtho(-30, 30, -20, 20, -1000, 1000); - glOrtho(-30, 5, -20, 20, -1000, 1000); - } - else{ - glOrtho(-30, 30, -20, 20, -1000, 1000); - } - - //assertGl(); - - //push and set modelview - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - glLoadIdentity(); - - glRotatef(15, 0, 1, 0); - - glRotatef(ang, 1, 0, 0); - glRotatef(90, 0, 1, 0); - const Vec3f &pos= game->getGameCamera()->getPos(); - - glTranslatef(static_cast(-pos.x), 0, static_cast(-pos.z)); - - //assertGl(); - } - else { - //non directional light +void Renderer::renderMenuBackground(const MenuBackground *menuBackground) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + assertGl(); + + const Vec3f &cameraPosition = menuBackground->getCamera()->getConstPosition(); + + glPushAttrib(GL_LIGHTING_BIT | GL_ENABLE_BIT | GL_CURRENT_BIT | + GL_DEPTH_BUFFER_BIT); + + // clear + Vec4f fogColor = Vec4f(0.4f, 0.4f, 0.4f, 1.f) * menuBackground->getFade(); + glClearColor(fogColor.x, fogColor.y, fogColor.z, 1.f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glFogfv(GL_FOG_COLOR, fogColor.ptr()); + + // light + Vec4f lightPos = Vec4f(10.f, 10.f, 10.f, 1.f) * menuBackground->getFade(); + Vec4f diffLight = Vec4f(0.9f, 0.9f, 0.9f, 1.f) * menuBackground->getFade(); + Vec4f ambLight = Vec4f(0.3f, 0.3f, 0.3f, 1.f) * menuBackground->getFade(); + Vec4f specLight = Vec4f(0.1f, 0.1f, 0.1f, 1.f) * menuBackground->getFade(); + + glEnable(GL_LIGHT0); + glLightfv(GL_LIGHT0, GL_POSITION, lightPos.ptr()); + glLightfv(GL_LIGHT0, GL_DIFFUSE, diffLight.ptr()); + glLightfv(GL_LIGHT0, GL_AMBIENT, ambLight.ptr()); + glLightfv(GL_LIGHT0, GL_SPECULAR, specLight.ptr()); + + // main model + glEnable(GL_ALPHA_TEST); + glAlphaFunc(GL_GREATER, 0.5f); + modelRenderer->begin(true, true, true, false); + menuBackground->getMainModelPtr()->updateInterpolationData( + menuBackground->getAnim(), true); + modelRenderer->render(menuBackground->getMainModelPtr()); + modelRenderer->end(); + glDisable(GL_ALPHA_TEST); + + // characters + float dist = menuBackground->getAboutPosition().dist(cameraPosition); + float minDist = 3.f; + if (dist < minDist) { + + glAlphaFunc(GL_GREATER, 0.0f); + float alpha = clamp((minDist - dist) / minDist, 0.f, 1.f); + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, + Vec4f(1.0f, 1.0f, 1.0f, alpha).ptr()); + + std::vector &characterMenuScreenPositionListCache = + CacheManager::getCachedItem>( + GameConstants::characterMenuScreenPositionListCacheLookupKey); + characterMenuScreenPositionListCache.clear(); + + modelRenderer->begin(true, true, false, false); + + for (int i = 0; i < MenuBackground::characterCount; ++i) { + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glLoadIdentity(); + + Vec3f worldPos(i * 2.f - 4.f, -1.4f, -7.5f); + glTranslatef(worldPos.x, worldPos.y, worldPos.z); + + // + // Get the screen coordinates for each character model - START + // std::vector projection(16); + // std::vector modelview(16); + // std::vector screen_coords(3); + + // glGetDoublev(GL_PROJECTION_MATRIX, projection.data()); + // glGetDoublev(GL_MODELVIEW_MATRIX, modelview.data()); + + const Metrics &metrics = Metrics::getInstance(); + GLint viewport[] = {0, 0, metrics.getVirtualW(), metrics.getVirtualH()}; + + // get matrices + GLdouble projection[16]; + glGetDoublev(GL_PROJECTION_MATRIX, projection); + + GLdouble modelview[16]; + glGetDoublev(GL_MODELVIEW_MATRIX, modelview); + + // get the screen coordinates + GLdouble screen_coords[3]; + + gluProject(worldPos.x, worldPos.y, worldPos.z, modelview, projection, + viewport, &screen_coords[0], &screen_coords[1], + &screen_coords[2]); + characterMenuScreenPositionListCache.push_back( + Vec3f(screen_coords[0], screen_coords[1], screen_coords[2])); + // Get the screen coordinates for each character model - END + // + + menuBackground->getCharacterModelPtr(i)->updateInterpolationData( + menuBackground->getAnim(), true); + modelRenderer->render(menuBackground->getCharacterModelPtr(i)); + + glPopMatrix(); + } + modelRenderer->end(); + } - //push projection - glMatrixMode(GL_PROJECTION); - glPushMatrix(); - glLoadIdentity(); + // water + if (menuBackground->getWater()) { - //assertGl(); + // water surface + const int waterTesselation = 10; + const int waterSize = 250; + const int waterQuadSize = 2 * waterSize / waterTesselation; + const float waterHeight = menuBackground->getWaterHeight(); - gluPerspective(perspFov, 1.f, perspNearPlane, perspFarPlane); - //const Metrics &metrics= Metrics::getInstance(); - //gluPerspective(perspFov, metrics.getAspectRatio(), perspNearPlane, perspFarPlane); + glEnable(GL_BLEND); + glNormal3f(0.f, 1.f, 0.f); + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, + Vec4f(1.f, 1.f, 1.f, 1.f).ptr()); + GLuint waterHandle = + static_cast(menuBackground->getWaterTexture()) + ->getHandle(); + glBindTexture(GL_TEXTURE_2D, waterHandle); + for (int i = 1; i < waterTesselation; ++i) { + glBegin(GL_TRIANGLE_STRIP); + for (int j = 1; j < waterTesselation; ++j) { + glTexCoord2i(1, 2 % j); + glVertex3f(-waterSize + i * waterQuadSize, waterHeight, + -waterSize + j * waterQuadSize); + glTexCoord2i(0, 2 % j); + glVertex3f(-waterSize + (i + 1) * waterQuadSize, waterHeight, + -waterSize + j * waterQuadSize); + } + glEnd(); + } + glDisable(GL_BLEND); - assertGl(); + // raindrops + if (menuBackground->getRain()) { + const float maxRaindropAlpha = 0.5f; - //push modelview - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - glLoadIdentity(); - glRotatef(-90, -1, 0, 0); - glTranslatef(-nearestLightPos.x, -nearestLightPos.y-2, -nearestLightPos.z); + glEnable(GL_BLEND); + glDisable(GL_LIGHTING); + glDisable(GL_ALPHA_TEST); + glDepthMask(GL_FALSE); - //assertGl(); - } + // splashes + CoreData &coreData = CoreData::getInstance(); + glBindTexture(GL_TEXTURE_2D, + static_cast(coreData.getWaterSplashTexture()) + ->getHandle()); + for (int i = 0; i < MenuBackground::raindropCount; ++i) { - if(shadows == sShadowMapping) { - glEnable(GL_POLYGON_OFFSET_FILL); - glPolygonOffset(1.0f, 16.0f); + Vec2f pos = menuBackground->getRaindropPos(i); + float scale = menuBackground->getRaindropState(i); + float alpha = maxRaindropAlpha - scale * maxRaindropAlpha; - //assertGl(); - } + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); - //render 3d - renderUnitsFast(true); - renderObjectsFast(true,false); + glColor4f(1.f, 1.f, 1.f, alpha); + glTranslatef(pos.x, waterHeight + 0.01f, pos.y); - //assertGl(); + glBegin(GL_TRIANGLE_STRIP); + glTexCoord2f(0.f, 1.f); + glVertex3f(-scale, 0, scale); + glTexCoord2f(0.f, 0.f); + glVertex3f(-scale, 0, -scale); + glTexCoord2f(1.f, 1.f); + glVertex3f(scale, 0, scale); + glTexCoord2f(1.f, 0.f); + glVertex3f(scale, 0, -scale); + glEnd(); - //read color buffer - glBindTexture(GL_TEXTURE_2D, shadowMapHandle); - assertGl(); - glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, shadowTextureSize, shadowTextureSize); - GLenum error = glGetError(); - // This error can happen when a Linux user switches from an X session - // back to a running game, and 'seems' to be safe to ignore it - if(error != GL_INVALID_OPERATION) { - assertGlWithErrorNumber(error); - } + glPopMatrix(); + } + } + } + + glPopAttrib(); + + assertGl(); +} + +void Renderer::renderMenuBackground(Camera *camera, float fade, + Model *mainModel, + vector characterModels, + const Vec3f characterPosition, float anim) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + assertGl(); + + const Vec3f &cameraPosition = camera->getConstPosition(); + + glPushAttrib(GL_LIGHTING_BIT | GL_ENABLE_BIT | GL_CURRENT_BIT | + GL_DEPTH_BUFFER_BIT); + + // clear + // Vec4f fogColor= Vec4f(0.4f, 0.4f, 0.4f, 1.f) * fade; + // Show black bacground + Vec4f fogColor = Vec4f(0.f, 0.f, 0.f, 1.f); + glClearColor(fogColor.x, fogColor.y, fogColor.z, 1.f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glFogfv(GL_FOG_COLOR, fogColor.ptr()); + + // light + Vec4f lightPos = Vec4f(10.f, 10.f, 10.f, 1.f) * fade; + Vec4f diffLight = Vec4f(0.9f, 0.9f, 0.9f, 1.f) * fade; + Vec4f ambLight = Vec4f(0.3f, 0.3f, 0.3f, 1.f) * fade; + Vec4f specLight = Vec4f(0.1f, 0.1f, 0.1f, 1.f) * fade; + + glEnable(GL_LIGHT0); + glLightfv(GL_LIGHT0, GL_POSITION, lightPos.ptr()); + glLightfv(GL_LIGHT0, GL_DIFFUSE, diffLight.ptr()); + glLightfv(GL_LIGHT0, GL_AMBIENT, ambLight.ptr()); + glLightfv(GL_LIGHT0, GL_SPECULAR, specLight.ptr()); + + // main model + if (mainModel) { + glEnable(GL_ALPHA_TEST); + glAlphaFunc(GL_GREATER, 0.5f); + modelRenderer->begin(true, true, true, false); + mainModel->updateInterpolationData(anim, true); + modelRenderer->render(mainModel); + modelRenderer->end(); + glDisable(GL_ALPHA_TEST); + } + + // characters + if (characterModels.empty() == false) { + float dist = characterPosition.dist(cameraPosition); + float minDist = 3.f; + if (dist < minDist) { + glAlphaFunc(GL_GREATER, 0.0f); + float alpha = clamp((minDist - dist) / minDist, 0.f, 1.f); + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, + Vec4f(1.0f, 1.0f, 1.0f, alpha).ptr()); + modelRenderer->begin(true, true, false, false); + + for (unsigned int i = 0; i < characterModels.size(); ++i) { + if (characterModels[i]) { + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glLoadIdentity(); + glTranslatef(i * 2.f - 4.f, -1.4f, -7.5f); + characterModels[i]->updateInterpolationData(anim, true); + modelRenderer->render(characterModels[i]); + glPopMatrix(); + } + } + modelRenderer->end(); + } + } - //get elemental matrices - static Matrix4f matrix1; - static bool matrix1Populate = true; - if(matrix1Populate == true) { - matrix1Populate = false; - matrix1[0]= 0.5f; matrix1[4]= 0.f; matrix1[8]= 0.f; matrix1[12]= 0.5f; - matrix1[1]= 0.f; matrix1[5]= 0.5f; matrix1[9]= 0.f; matrix1[13]= 0.5f; - matrix1[2]= 0.f; matrix1[6]= 0.f; matrix1[10]= 0.5f; matrix1[14]= 0.5f; - matrix1[3]= 0.f; matrix1[7]= 0.f; matrix1[11]= 0.f; matrix1[15]= 1.f; - } - Matrix4f matrix2; - glGetFloatv(GL_PROJECTION_MATRIX, matrix2.ptr()); + glPopAttrib(); - //assertGl(); + assertGl(); +} - Matrix4f matrix3; - glGetFloatv(GL_MODELVIEW_MATRIX, matrix3.ptr()); +// ==================== computing ==================== - //pop both matrices - glPopMatrix(); - glMatrixMode(GL_PROJECTION); - glPopMatrix(); +bool Renderer::ccomputePosition(const Vec2i &screenPos, Vec2i &worldPos, + bool exactCoords) { + assertGl(); + const Map *map = game->getWorld()->getMap(); + const Metrics &metrics = Metrics::getInstance(); + float depth = 0.0f; + GLdouble modelviewMatrix[16]; + GLdouble projectionMatrix[16]; + GLint viewport[4] = {0, 0, metrics.getScreenW(), metrics.getScreenH()}; + GLdouble worldX; + GLdouble worldY; + GLdouble worldZ; + GLint screenX = (screenPos.x * metrics.getScreenW() / metrics.getVirtualW()); + GLint screenY = (screenPos.y * metrics.getScreenH() / metrics.getVirtualH()); + + // get the depth in the cursor pixel + glReadPixels(screenX, screenY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth); + + // load matrices + loadProjectionMatrix(); + loadGameCameraMatrix(); + + // get matrices + glGetDoublev(GL_MODELVIEW_MATRIX, modelviewMatrix); + glGetDoublev(GL_PROJECTION_MATRIX, projectionMatrix); + + // get the world coordinates + gluUnProject(screenX, screenY, depth, modelviewMatrix, projectionMatrix, + viewport, &worldX, &worldY, &worldZ); + + // conver coords to int + if (exactCoords == true) { + worldPos = Vec2i(static_cast(worldX), static_cast(worldZ)); + } else { + worldPos = + Vec2i(static_cast(worldX + 0.5f), static_cast(worldZ + 0.5f)); + } + + // clamp coords to map size + return map->isInside(worldPos); +} - glMatrixMode(GL_PROJECTION); - glPushMatrix(); +// This method takes world co-ordinates and translates them to screen co-ords +Vec3f Renderer::computeScreenPosition(const Vec3f &worldPos) { + if (worldToScreenPosCache.find(worldPos) != worldToScreenPosCache.end()) { + return worldToScreenPosCache[worldPos]; + } + assertGl(); + + const Metrics &metrics = Metrics::getInstance(); + GLint viewport[] = {0, 0, metrics.getVirtualW(), metrics.getVirtualH()}; + GLdouble worldX = worldPos.x; + GLdouble worldY = worldPos.y; + GLdouble worldZ = worldPos.z; + + // load matrices + loadProjectionMatrix(); + loadGameCameraMatrix(); + + // get matrices + GLdouble modelviewMatrix[16]; + glGetDoublev(GL_MODELVIEW_MATRIX, modelviewMatrix); + GLdouble projectionMatrix[16]; + glGetDoublev(GL_PROJECTION_MATRIX, projectionMatrix); + + // get the screen coordinates + GLdouble screenX; + GLdouble screenY; + GLdouble screenZ; + gluProject(worldX, worldY, worldZ, modelviewMatrix, projectionMatrix, + viewport, &screenX, &screenY, &screenZ); + + Vec3f screenPos(screenX, screenY, screenZ); + worldToScreenPosCache[worldPos] = screenPos; + + return screenPos; +} + +void Renderer::computeSelected(Selection::UnitContainer &units, + const Object *&obj, + const bool withObjectSelection, + const Vec2i &posDown, const Vec2i &posUp) { + const string selectionType = toLower( + Config::getInstance().getString("SelectionType", Config::colorPicking)); + + if (selectionType == Config::colorPicking) { + selectUsingColorPicking(units, obj, withObjectSelection, posDown, posUp); + } + /// Frustum approach --> Currently not accurate enough + else if (selectionType == Config::frustumPicking) { + selectUsingFrustumSelection(units, obj, withObjectSelection, posDown, + posUp); + } else { + selectUsingSelectionBuffer(units, obj, withObjectSelection, posDown, posUp); + } +} - //assertGl(); +void Renderer::selectUsingFrustumSelection(Selection::UnitContainer &units, + const Object *&obj, + const bool withObjectSelection, + const Vec2i &posDown, + const Vec2i &posUp) { + glMatrixMode(GL_PROJECTION); + glPushMatrix(); + glLoadIdentity(); + + const Metrics &metrics = Metrics::getInstance(); + GLint view[] = {0, 0, metrics.getVirtualW(), metrics.getVirtualH()}; + + // compute center and dimensions of selection rectangle + int x = (posDown.x + posUp.x) / 2; + int y = (posDown.y + posUp.y) / 2; + int w = abs(posDown.x - posUp.x); + int h = abs(posDown.y - posUp.y); + if (w < 2) { + w = 2; + } + if (h < 2) { + h = 2; + } + + gluPickMatrix(x, y, w, h, view); + gluPerspective(perspFov, metrics.getAspectRatio(), perspNearPlane, + perspFarPlane); + loadGameCameraMatrix(); + + VisibleQuadContainerCache quadSelectionCacheItem; + ExtractFrustum(quadSelectionCacheItem); + + // pop matrices + glMatrixMode(GL_PROJECTION); + glPopMatrix(); + + VisibleQuadContainerCache &qCache = getQuadCache(); + if (qCache.visibleQuadUnitList.empty() == false) { + for (int visibleUnitIndex = 0; + visibleUnitIndex < (int)qCache.visibleQuadUnitList.size(); + ++visibleUnitIndex) { + Unit *unit = qCache.visibleQuadUnitList[visibleUnitIndex]; + if (unit != NULL && unit->isAlive()) { + Vec3f unitPos = unit->getCurrMidHeightVector(); + bool insideQuad = CubeInFrustum(quadSelectionCacheItem.frustumData, + unitPos.x, unitPos.y, unitPos.z, + unit->getType()->getRenderSize()); + if (insideQuad == true) { + units.push_back(unit); + } + } + } + } + + if (withObjectSelection == true) { + if (qCache.visibleObjectList.empty() == false) { + for (int visibleIndex = 0; + visibleIndex < (int)qCache.visibleObjectList.size(); + ++visibleIndex) { + Object *object = qCache.visibleObjectList[visibleIndex]; + if (object != NULL) { + bool insideQuad = CubeInFrustum( + quadSelectionCacheItem.frustumData, object->getPos().x, + object->getPos().y, object->getPos().z, 1); + if (insideQuad == true) { + obj = object; + // if(withObjectSelection == true) { + break; + //} + } + } + } + } + } +} - //compute texture matrix - glLoadMatrixf(matrix1.ptr()); - glMultMatrixf(matrix2.ptr()); - glMultMatrixf(matrix3.ptr()); - glGetFloatv(GL_TRANSPOSE_PROJECTION_MATRIX_ARB, shadowMapMatrix.ptr()); +void Renderer::selectUsingSelectionBuffer(Selection::UnitContainer &units, + const Object *&obj, + const bool withObjectSelection, + const Vec2i &posDown, + const Vec2i &posUp) { + // compute center and dimensions of selection rectangle + int x = (posDown.x + posUp.x) / 2; + int y = (posDown.y + posUp.y) / 2; + int w = abs(posDown.x - posUp.x); + int h = abs(posDown.y - posUp.y); + if (w < 2) { + w = 2; + } + if (h < 2) { + h = 2; + } + + // declarations + GLuint selectBuffer[Gui::maxSelBuff]; + + // setup matrices + glSelectBuffer(Gui::maxSelBuff, selectBuffer); + // glMatrixMode(GL_PROJECTION); + // glPushMatrix(); + + GLint renderModeResult = glRenderMode(GL_SELECT); + if (renderModeResult < 0) { + const char *errorString = + reinterpret_cast(gluErrorString(renderModeResult)); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "OpenGL error #%d [0x%X] : [%s] at file: [%s], line: %d", + renderModeResult, renderModeResult, errorString, + extractFileFromDirectoryPath(__FILE__).c_str(), __LINE__); + + printf("%s\n", szBuf); + } + + glPushMatrix(); + glMatrixMode(GL_PROJECTION); + + glLoadIdentity(); + + const Metrics &metrics = Metrics::getInstance(); + GLint view[] = {0, 0, metrics.getVirtualW(), metrics.getVirtualH()}; + // GLint view[4]; + // glGetIntegerv(GL_VIEWPORT, view); + + gluPickMatrix(x, y, w, h, view); + gluPerspective(perspFov, metrics.getAspectRatio(), perspNearPlane, + perspFarPlane); + // gluPerspective(perspFov, metrics.getAspectRatio(), 0.0001, 1000.0); + // gluPerspective(perspFov, (float)view[2]/(float)view[3], perspNearPlane, + // perspFarPlane); + loadGameCameraMatrix(); + + // render units to find which ones should be selected + renderUnitsFast(); + if (withObjectSelection == true) { + renderObjectsFast(false, true); + } + + // pop matrices + glPopMatrix(); + + // Added this to ensure all the selection calls are done now + // (see http://www.unknownroad.com/rtfm/graphics/glselection.html section: + // [0x4]) + // glFlush(); + + // select units by checking the selected buffer + int selCount = glRenderMode(GL_RENDER); + if (selCount > 0) { + VisibleQuadContainerCache &qCache = getQuadCache(); + for (int i = 1; i <= selCount; ++i) { + int index = selectBuffer[i * 4 - 1]; + if (index >= OBJECT_SELECT_OFFSET) { + Object *object = qCache.visibleObjectList[index - OBJECT_SELECT_OFFSET]; + if (object != NULL) { + obj = object; + if (withObjectSelection == true) { + break; + } + } + } else { + Unit *unit = qCache.visibleQuadUnitList[index]; + if (unit != NULL && unit->isAlive()) { + units.push_back(unit); + } + } + } + } else if (selCount < 0) { + const char *errorString = + reinterpret_cast(gluErrorString(selCount)); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "OpenGL error #%d [0x%X] : [%s] at file: [%s], line: %d", selCount, + selCount, errorString, + extractFileFromDirectoryPath(__FILE__).c_str(), __LINE__); - //assertGl(); + printf("%s\n", szBuf); + } +} - //if(shadows == sShadowMapping) { - // glDisable(GL_POLYGON_OFFSET_FILL); - // glPolygonOffset(0.0f, 0.0f); - //} +void Renderer::selectUsingColorPicking(Selection::UnitContainer &units, + const Object *&obj, + const bool withObjectSelection, + const Vec2i &posDown, + const Vec2i &posUp) { + int x1 = posDown.x; + int y1 = posDown.y; + int x2 = posUp.x; + int y2 = posUp.y; + + int x = min(x1, x2); + int y = min(y1, y2); + int w = max(x1, x2) - min(x1, x2); + int h = max(y1, y2) - min(y1, y2); + if (w < 2) { + w = 2; + } + if (h < 2) { + h = 2; + } + + const Metrics &metrics = Metrics::getInstance(); + x = (x * metrics.getScreenW() / metrics.getVirtualW()); + y = (y * metrics.getScreenH() / metrics.getVirtualH()); + + w = (w * metrics.getScreenW() / metrics.getVirtualW()); + h = (h * metrics.getScreenH() / metrics.getVirtualH()); + + PixelBufferWrapper::begin(); + + glPushMatrix(); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + // GLint view[]= {0, 0, metrics.getVirtualW(), metrics.getVirtualH()}; + // gluPickMatrix(x, y, w, h, view); + gluPerspective(perspFov, metrics.getAspectRatio(), perspNearPlane, + perspFarPlane); + loadGameCameraMatrix(); + + // render units to find which ones should be selected + // printf("In [%s::%s] Line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + vector rendererUnits = renderUnitsFast(false, true); + // printf("In [%s::%s] Line: %d rendererUnits = + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,rendererUnits.size()); + + // Added this to ensure all the selection calls are done now + // (see http://www.unknownroad.com/rtfm/graphics/glselection.html section: + // [0x4]) + // glFlush(); + + // GraphicsInterface::getInstance().getCurrentContext()->swapBuffers(); + + PixelBufferWrapper::end(); + + vector unitsVector; + bool unitFound = false; + + if (rendererUnits.empty() == false) { + copy(rendererUnits.begin(), rendererUnits.end(), + std::inserter(unitsVector, unitsVector.begin())); + } + + if (unitsVector.empty() == false) { + vector pickedList = + BaseColorPickEntity::getPickedList(x, y, w, h, unitsVector); + // printf("In [%s::%s] Line: %d pickedList = %d models rendered = + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,pickedList.size(),rendererModels.size()); + + if (pickedList.empty() == false) { + units.reserve(pickedList.size()); + for (unsigned int i = 0; i < pickedList.size(); ++i) { + int index = pickedList[i]; + // printf("In [%s::%s] Line: %d searching for selected object i = %d + // index = %d units = %d objects = + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,index,rendererUnits.size(),rendererObjects.size()); + + if (rendererUnits.empty() == false && + index < (int)rendererUnits.size()) { + Unit *unit = rendererUnits[index]; + if (unit != NULL && unit->isAlive()) { + unitFound = true; + units.push_back(unit); + } + } + } + } + } + + if (withObjectSelection == true && unitFound == false) { + vector rendererObjects; + vector objectsVector; + rendererObjects = renderObjectsFast(false, true, true); + if (rendererObjects.empty() == false) { + copy(rendererObjects.begin(), rendererObjects.end(), + std::inserter(objectsVector, objectsVector.begin())); + } - //pop - glPopMatrix(); + if (objectsVector.empty() == false) { + vector pickedList = + BaseColorPickEntity::getPickedList(x, y, w, h, objectsVector); + // printf("In [%s::%s] Line: %d pickedList = %d models rendered = + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,pickedList.size(),rendererModels.size()); + + if (pickedList.empty() == false) { + for (unsigned int i = 0; i < pickedList.size(); ++i) { + int index = pickedList[i]; + // printf("In [%s::%s] Line: %d searching for selected object i = %d + // index = %d units = %d objects = + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,index,rendererUnits.size(),rendererObjects.size()); + + if (rendererObjects.empty() == false && + index < (int)rendererObjects.size()) { + Object *object = rendererObjects[index]; + // printf("In [%s::%s] Line: %d searching for selected object i = %d + // index = %d + // [%p]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,index,object); + + if (object != NULL) { + obj = object; + break; + } + } + } + } + } + } + // pop matrices + glPopMatrix(); +} - //assertGl(); +// ==================== shadows ==================== - glPopAttrib(); +void Renderer::renderShadowsToTexture(const int renderFps) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + if (shadowsOffDueToMinRender == false && + (shadows == sProjected || shadows == sShadowMapping)) { + + shadowMapFrame = (shadowMapFrame + 1) % (shadowFrameSkip + 1); + + if (shadowMapFrame == 0) { + assertGl(); + + glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT | GL_COLOR_BUFFER_BIT | + GL_VIEWPORT_BIT | GL_POLYGON_BIT); + + if (shadows == sShadowMapping) { + glClear(GL_DEPTH_BUFFER_BIT); + } else { + float color = 1.0f - shadowIntensity; + glColor3f(color, color, color); + glClearColor(1.f, 1.f, 1.f, 1.f); + glDisable(GL_DEPTH_TEST); + glClear(GL_COLOR_BUFFER_BIT); + } + + // assertGl(); + + // clear color buffer + // + // set viewport, we leave one texel always in white to avoid problems + glViewport(1, 1, shadowTextureSize - 2, shadowTextureSize - 2); + + // assertGl(); + + if (nearestLightPos.w == 0.f) { + // directional light + + // light pos + assert(game != NULL); + assert(game->getWorld() != NULL); + const TimeFlow *tf = game->getWorld()->getTimeFlow(); + assert(tf != NULL); + float ang = tf->isDay() ? computeSunAngle(tf->getTime()) + : computeMoonAngle(tf->getTime()); + ang = radToDeg(ang); + + // push and set projection + glMatrixMode(GL_PROJECTION); + glPushMatrix(); + glLoadIdentity(); + + // assertGl(); + + if (game->getGameCamera()->getState() == GameCamera::sGame) { + // glOrtho(-35, 5, -15, 15, -1000, 1000); + // glOrtho(-30, 30, -20, 20, -1000, 1000); + glOrtho(-30, 5, -20, 20, -1000, 1000); + } else { + glOrtho(-30, 30, -20, 20, -1000, 1000); + } - assertGl(); - } - } + // assertGl(); + + // push and set modelview + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glLoadIdentity(); + + glRotatef(15, 0, 1, 0); + + glRotatef(ang, 1, 0, 0); + glRotatef(90, 0, 1, 0); + const Vec3f &pos = game->getGameCamera()->getPos(); + + glTranslatef(static_cast(-pos.x), 0, static_cast(-pos.z)); + + // assertGl(); + } else { + // non directional light + + // push projection + glMatrixMode(GL_PROJECTION); + glPushMatrix(); + glLoadIdentity(); + + // assertGl(); + + gluPerspective(perspFov, 1.f, perspNearPlane, perspFarPlane); + // const Metrics &metrics= Metrics::getInstance(); + // gluPerspective(perspFov, metrics.getAspectRatio(), perspNearPlane, + // perspFarPlane); + + assertGl(); + + // push modelview + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glLoadIdentity(); + glRotatef(-90, -1, 0, 0); + glTranslatef(-nearestLightPos.x, -nearestLightPos.y - 2, + -nearestLightPos.z); + + // assertGl(); + } + + if (shadows == sShadowMapping) { + glEnable(GL_POLYGON_OFFSET_FILL); + glPolygonOffset(1.0f, 16.0f); + + // assertGl(); + } + + // render 3d + renderUnitsFast(true); + renderObjectsFast(true, false); + + // assertGl(); + + // read color buffer + glBindTexture(GL_TEXTURE_2D, shadowMapHandle); + assertGl(); + glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, shadowTextureSize, + shadowTextureSize); + GLenum error = glGetError(); + // This error can happen when a Linux user switches from an X session + // back to a running game, and 'seems' to be safe to ignore it + if (error != GL_INVALID_OPERATION) { + assertGlWithErrorNumber(error); + } + + // get elemental matrices + static Matrix4f matrix1; + static bool matrix1Populate = true; + if (matrix1Populate == true) { + matrix1Populate = false; + matrix1[0] = 0.5f; + matrix1[4] = 0.f; + matrix1[8] = 0.f; + matrix1[12] = 0.5f; + matrix1[1] = 0.f; + matrix1[5] = 0.5f; + matrix1[9] = 0.f; + matrix1[13] = 0.5f; + matrix1[2] = 0.f; + matrix1[6] = 0.f; + matrix1[10] = 0.5f; + matrix1[14] = 0.5f; + matrix1[3] = 0.f; + matrix1[7] = 0.f; + matrix1[11] = 0.f; + matrix1[15] = 1.f; + } + Matrix4f matrix2; + glGetFloatv(GL_PROJECTION_MATRIX, matrix2.ptr()); + + // assertGl(); + + Matrix4f matrix3; + glGetFloatv(GL_MODELVIEW_MATRIX, matrix3.ptr()); + + // pop both matrices + glPopMatrix(); + glMatrixMode(GL_PROJECTION); + glPopMatrix(); + + glMatrixMode(GL_PROJECTION); + glPushMatrix(); + + // assertGl(); + + // compute texture matrix + glLoadMatrixf(matrix1.ptr()); + glMultMatrixf(matrix2.ptr()); + glMultMatrixf(matrix3.ptr()); + glGetFloatv(GL_TRANSPOSE_PROJECTION_MATRIX_ARB, shadowMapMatrix.ptr()); + + // assertGl(); + + // if(shadows == sShadowMapping) { + // glDisable(GL_POLYGON_OFFSET_FILL); + // glPolygonOffset(0.0f, 0.0f); + // } + + // pop + glPopMatrix(); + + // assertGl(); + + glPopAttrib(); + + assertGl(); + } + } } - // ==================== gl wrap ==================== -string Renderer::getGlInfo(){ - string infoStr=""; - Lang &lang= Lang::getInstance(); - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - infoStr+= lang.getString("OpenGlInfo")+":\n"; - infoStr+= " "+lang.getString("OpenGlVersion")+": "; - infoStr+= string((getGlVersion() != NULL ? getGlVersion() : "?"))+"\n"; - infoStr+= " "+lang.getString("OpenGlRenderer")+": "; - infoStr+= string((getGlVersion() != NULL ? getGlVersion() : "?"))+"\n"; - infoStr+= " "+lang.getString("OpenGlVendor")+": "; - infoStr+= string((getGlVendor() != NULL ? getGlVendor() : "?"))+"\n"; - infoStr+= " "+lang.getString("OpenGlMaxLights")+": "; - infoStr+= intToStr(getGlMaxLights())+"\n"; - infoStr+= " "+lang.getString("OpenGlMaxTextureSize")+": "; - infoStr+= intToStr(getGlMaxTextureSize())+"\n"; - infoStr+= " "+lang.getString("OpenGlMaxTextureUnits")+": "; - infoStr+= intToStr(getGlMaxTextureUnits())+"\n"; - infoStr+= " "+lang.getString("OpenGlModelviewStack")+": "; - infoStr+= intToStr(getGlModelviewMatrixStackDepth())+"\n"; - infoStr+= " "+lang.getString("OpenGlProjectionStack")+": "; - infoStr+= intToStr(getGlProjectionMatrixStackDepth())+"\n"; - } - return infoStr; -} - -string Renderer::getGlMoreInfo(){ - string infoStr=""; - Lang &lang= Lang::getInstance(); - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - //gl extensions - infoStr+= lang.getString("OpenGlExtensions")+":\n "; - - string extensions= getGlExtensions(); - int charCount= 0; - for(int i = 0; i < (int)extensions.size(); ++i) { - infoStr+= extensions[i]; - if(charCount>120 && extensions[i]==' '){ - infoStr+= "\n "; - charCount= 0; - } - ++charCount; - } - - //platform extensions - infoStr+= "\n\n"; - infoStr+= lang.getString("OpenGlPlatformExtensions")+":\n "; - - charCount= 0; - string platformExtensions= getGlPlatformExtensions(); - for(int i = 0; i < (int)platformExtensions.size(); ++i) { - infoStr+= platformExtensions[i]; - if(charCount>120 && platformExtensions[i]==' '){ - infoStr+= "\n "; - charCount= 0; - } - ++charCount; - } - } - - return infoStr; +string Renderer::getGlInfo() { + string infoStr = ""; + Lang &lang = Lang::getInstance(); + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + infoStr += lang.getString("OpenGlInfo") + ":\n"; + infoStr += " " + lang.getString("OpenGlVersion") + ": "; + infoStr += string((getGlVersion() != NULL ? getGlVersion() : "?")) + "\n"; + infoStr += " " + lang.getString("OpenGlRenderer") + ": "; + infoStr += string((getGlVersion() != NULL ? getGlVersion() : "?")) + "\n"; + infoStr += " " + lang.getString("OpenGlVendor") + ": "; + infoStr += string((getGlVendor() != NULL ? getGlVendor() : "?")) + "\n"; + infoStr += " " + lang.getString("OpenGlMaxLights") + ": "; + infoStr += intToStr(getGlMaxLights()) + "\n"; + infoStr += " " + lang.getString("OpenGlMaxTextureSize") + ": "; + infoStr += intToStr(getGlMaxTextureSize()) + "\n"; + infoStr += " " + lang.getString("OpenGlMaxTextureUnits") + ": "; + infoStr += intToStr(getGlMaxTextureUnits()) + "\n"; + infoStr += " " + lang.getString("OpenGlModelviewStack") + ": "; + infoStr += intToStr(getGlModelviewMatrixStackDepth()) + "\n"; + infoStr += " " + lang.getString("OpenGlProjectionStack") + ": "; + infoStr += intToStr(getGlProjectionMatrixStackDepth()) + "\n"; + } + return infoStr; +} + +string Renderer::getGlMoreInfo() { + string infoStr = ""; + Lang &lang = Lang::getInstance(); + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + // gl extensions + infoStr += lang.getString("OpenGlExtensions") + ":\n "; + + string extensions = getGlExtensions(); + int charCount = 0; + for (int i = 0; i < (int)extensions.size(); ++i) { + infoStr += extensions[i]; + if (charCount > 120 && extensions[i] == ' ') { + infoStr += "\n "; + charCount = 0; + } + ++charCount; + } + + // platform extensions + infoStr += "\n\n"; + infoStr += lang.getString("OpenGlPlatformExtensions") + ":\n "; + + charCount = 0; + string platformExtensions = getGlPlatformExtensions(); + for (int i = 0; i < (int)platformExtensions.size(); ++i) { + infoStr += platformExtensions[i]; + if (charCount > 120 && platformExtensions[i] == ' ') { + infoStr += "\n "; + charCount = 0; + } + ++charCount; + } + } + + return infoStr; } void Renderer::autoConfig() { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - Config &config= Config::getInstance(); - - bool nvidiaCard= toLower(getGlVendor()).find("nvidia")!=string::npos; - bool atiCard= toLower(getGlVendor()).find("ati")!=string::npos; - //bool shadowExtensions = isGlExtensionSupported("GL_ARB_shadow") && isGlExtensionSupported("GL_ARB_shadow_ambient"); - bool shadowExtensions = isGlExtensionSupported("GL_ARB_shadow"); - - //3D textures - config.setBool("Textures3D", isGlExtensionSupported("GL_EXT_texture3D")); - - //shadows - string shadows=""; - if(getGlMaxTextureUnits()>=3){ - if(nvidiaCard && shadowExtensions){ - shadows= shadowsToStr(sShadowMapping); - } - else{ - shadows= shadowsToStr(sProjected); - } - } - else{ - shadows=shadowsToStr(sDisabled); - } - config.setString("Shadows", shadows); - - //lights - config.setInt("MaxLights", atiCard? 1: 4); - - //filter - config.setString("Filter", "Bilinear"); - } + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + Config &config = Config::getInstance(); + + bool nvidiaCard = toLower(getGlVendor()).find("nvidia") != string::npos; + bool atiCard = toLower(getGlVendor()).find("ati") != string::npos; + // bool shadowExtensions = isGlExtensionSupported("GL_ARB_shadow") && + // isGlExtensionSupported("GL_ARB_shadow_ambient"); + bool shadowExtensions = isGlExtensionSupported("GL_ARB_shadow"); + + // 3D textures + config.setBool("Textures3D", isGlExtensionSupported("GL_EXT_texture3D")); + + // shadows + string shadows = ""; + if (getGlMaxTextureUnits() >= 3) { + if (nvidiaCard && shadowExtensions) { + shadows = shadowsToStr(sShadowMapping); + } else { + shadows = shadowsToStr(sProjected); + } + } else { + shadows = shadowsToStr(sDisabled); + } + config.setString("Shadows", shadows); + + // lights + config.setInt("MaxLights", atiCard ? 1 : 4); + + // filter + config.setString("Filter", "Bilinear"); + } } void Renderer::clearBuffers() { - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } -void Renderer::clearZBuffer() { - glClear(GL_DEPTH_BUFFER_BIT); -} +void Renderer::clearZBuffer() { glClear(GL_DEPTH_BUFFER_BIT); } void Renderer::loadConfig() { - Config &config= Config::getInstance(); - - //cache most used config params - maxLights= config.getInt("MaxLights"); - photoMode= config.getBool("PhotoMode"); - focusArrows= config.getBool("FocusArrows"); - textures3D= config.getBool("Textures3D"); - float gammaValue=config.getFloat("GammaValue","0.0"); - if(this->program == NULL) { - throw megaglest_runtime_error("this->program == NULL"); - } - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - //if(this->program != NULL) { - if(gammaValue != 0.0) { - this->program->getWindow()->setGamma(gammaValue); - } - //} - } - //load shadows - shadows= strToShadows(config.getString("Shadows")); - if(shadows==sProjected || shadows==sShadowMapping){ - shadowTextureSize= config.getInt("ShadowTextureSize"); - shadowFrameSkip= config.getInt("ShadowFrameSkip"); - shadowIntensity= config.getFloat("ShadowIntensity","1.0"); - } - - //load filter settings - Texture2D::Filter textureFilter= strToTextureFilter(config.getString("Filter")); - int maxAnisotropy= config.getInt("FilterMaxAnisotropy"); - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - for(int i=0; isetFilter(textureFilter); - textureManager[i]->setMaxAnisotropy(maxAnisotropy); - } - } -} - -//Texture2D *Renderer::saveScreenToTexture(int x, int y, int width, int height) { -// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + Config &config = Config::getInstance(); + + // cache most used config params + maxLights = config.getInt("MaxLights"); + photoMode = config.getBool("PhotoMode"); + focusArrows = config.getBool("FocusArrows"); + textures3D = config.getBool("Textures3D"); + float gammaValue = config.getFloat("GammaValue", "0.0"); + if (this->program == NULL) { + throw megaglest_runtime_error("this->program == NULL"); + } + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + // if(this->program != NULL) { + if (gammaValue != 0.0) { + this->program->getWindow()->setGamma(gammaValue); + } + //} + } + // load shadows + shadows = strToShadows(config.getString("Shadows")); + if (shadows == sProjected || shadows == sShadowMapping) { + shadowTextureSize = config.getInt("ShadowTextureSize"); + shadowFrameSkip = config.getInt("ShadowFrameSkip"); + shadowIntensity = config.getFloat("ShadowIntensity", "1.0"); + } + + // load filter settings + Texture2D::Filter textureFilter = + strToTextureFilter(config.getString("Filter")); + int maxAnisotropy = config.getInt("FilterMaxAnisotropy"); + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + for (int i = 0; i < rsCount; ++i) { + textureManager[i]->setFilter(textureFilter); + textureManager[i]->setMaxAnisotropy(maxAnisotropy); + } + } +} + +// Texture2D *Renderer::saveScreenToTexture(int x, int y, int width, int height) +// { if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) +// SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: +//%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); // // Config &config= Config::getInstance(); -// Texture2D::Filter textureFilter = strToTextureFilter(config.getString("Filter")); -// int maxAnisotropy = config.getInt("FilterMaxAnisotropy"); +// Texture2D::Filter textureFilter = +// strToTextureFilter(config.getString("Filter")); int maxAnisotropy +//= config.getInt("FilterMaxAnisotropy"); // -// Texture2D *texture = GraphicsInterface::getInstance().getFactory()->newTexture2D(); +// Texture2D *texture = +// GraphicsInterface::getInstance().getFactory()->newTexture2D(); // texture->setForceCompressionDisabled(true); // texture->setMipmap(false); // Pixmap2D *pixmapScreenShot = texture->getPixmap(); // pixmapScreenShot->init(width, height, 3); // texture->init(textureFilter,maxAnisotropy); // -// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) +// SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: +//%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); // //glFinish(); // -// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) +// SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: +//%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); // glReadPixels(x, y, pixmapScreenShot->getW(), pixmapScreenShot->getH(), -// GL_RGB, GL_UNSIGNED_BYTE, pixmapScreenShot->getPixels()); +// GL_RGB, GL_UNSIGNED_BYTE, +// pixmapScreenShot->getPixels()); // -// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) +// SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: +//%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); // // return texture; -//} - -void Renderer::saveScreen(const string &path,int w, int h) { - const Metrics &sm= Metrics::getInstance(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - Pixmap2D *pixmapScreenShot = new Pixmap2D(sm.getScreenW(),sm.getScreenH(), 3); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //glFinish(); - - glPixelStorei(GL_PACK_ALIGNMENT, 1); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - glReadPixels(0, 0, pixmapScreenShot->getW(), pixmapScreenShot->getH(), - GL_RGB, GL_UNSIGNED_BYTE, pixmapScreenShot->getPixels()); - - if(w==0 || h==0){ - h=sm.getScreenH(); - w=sm.getScreenW(); - } - else{ - pixmapScreenShot->Scale(GL_RGB,w,h); - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - - // Signal the threads queue to add a screenshot save request - MutexSafeWrapper safeMutex(saveScreenShotThreadAccessor,string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + intToStr(__LINE__)); - saveScreenQueue.push_back(make_pair(path,pixmapScreenShot)); - safeMutex.ReleaseLock(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +// } + +void Renderer::saveScreen(const string &path, int w, int h) { + const Metrics &sm = Metrics::getInstance(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + Pixmap2D *pixmapScreenShot = + new Pixmap2D(sm.getScreenW(), sm.getScreenH(), 3); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + // glFinish(); + + glPixelStorei(GL_PACK_ALIGNMENT, 1); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + glReadPixels(0, 0, pixmapScreenShot->getW(), pixmapScreenShot->getH(), GL_RGB, + GL_UNSIGNED_BYTE, pixmapScreenShot->getPixels()); + + if (w == 0 || h == 0) { + h = sm.getScreenH(); + w = sm.getScreenW(); + } else { + pixmapScreenShot->Scale(GL_RGB, w, h); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + + // Signal the threads queue to add a screenshot save request + MutexSafeWrapper safeMutex( + saveScreenShotThreadAccessor, + string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + + intToStr(__LINE__)); + saveScreenQueue.push_back(make_pair(path, pixmapScreenShot)); + safeMutex.ReleaseLock(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); } unsigned int Renderer::getSaveScreenQueueSize() { - MutexSafeWrapper safeMutex(saveScreenShotThreadAccessor,string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + intToStr(__LINE__)); - int queueSize = (int)saveScreenQueue.size(); - safeMutex.ReleaseLock(); + MutexSafeWrapper safeMutex( + saveScreenShotThreadAccessor, + string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + + intToStr(__LINE__)); + int queueSize = (int)saveScreenQueue.size(); + safeMutex.ReleaseLock(); - return queueSize; + return queueSize; } // ==================== PRIVATE ==================== float Renderer::computeSunAngle(float time) { - float dayTime= TimeFlow::dusk-TimeFlow::dawn; - float fTime= (time-TimeFlow::dawn)/dayTime; - return clamp(fTime*pi, pi/8.f, 7.f*pi/8.f); + float dayTime = TimeFlow::dusk - TimeFlow::dawn; + float fTime = (time - TimeFlow::dawn) / dayTime; + return clamp(fTime * pi, pi / 8.f, 7.f * pi / 8.f); } float Renderer::computeMoonAngle(float time) { - float nightTime= 24-(TimeFlow::dusk-TimeFlow::dawn); + float nightTime = 24 - (TimeFlow::dusk - TimeFlow::dawn); - if(time Renderer::renderUnitsFast(bool renderingShadows, bool colorPickingSelection) { - vector unitsList; - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return unitsList; - } - - assert(game != NULL); - //const World *world= game->getWorld(); - //assert(world != NULL); - - VisibleQuadContainerCache &qCache = getQuadCache(); - if(qCache.visibleQuadUnitList.empty() == false) { - if(colorPickingSelection == true) { - unitsList.reserve(qCache.visibleQuadUnitList.size()); - } - - bool modelRenderStarted = false; - bool renderOnlyBuildings=true; - for(int k=0; k<2 ;k++) { - if(k==0){ - //glDisable(GL_DEPTH_TEST); - renderOnlyBuildings=true; - } - else { - if(colorPickingSelection == true){ - // clear depth buffer to get units behind buildings rendered in front of them - glClear(GL_DEPTH_BUFFER_BIT); - } - //glEnable(GL_DEPTH_TEST); - renderOnlyBuildings=false; - } - for(int visibleUnitIndex = 0; - visibleUnitIndex < (int)qCache.visibleQuadUnitList.size(); ++visibleUnitIndex) { - Unit *unit = qCache.visibleQuadUnitList[visibleUnitIndex]; - - if(renderingShadows==false && unit->isAlive()==false){ - // no need to render dead units for selection - continue; - } - - if(renderOnlyBuildings==true && unit->getType()->hasSkillClass(scMove)){ - continue; - } - - if(renderOnlyBuildings==false && !unit->getType()->hasSkillClass(scMove)){ - continue; - } - - if(modelRenderStarted == false) { - modelRenderStarted = true; - - if(colorPickingSelection == false) { - //glPushAttrib(GL_ENABLE_BIT| GL_TEXTURE_BIT); - glDisable(GL_LIGHTING); - if (renderingShadows == false) { - glPushAttrib(GL_ENABLE_BIT); - glDisable(GL_TEXTURE_2D); - } - else { - glPushAttrib(GL_ENABLE_BIT| GL_TEXTURE_BIT); - glEnable(GL_TEXTURE_2D); - glAlphaFunc(GL_GREATER, 0.4f); - - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); - - //set color to the texture alpha - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_REPLACE); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PRIMARY_COLOR); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR); - - //set alpha to the texture alpha - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_TEXTURE); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA); - } - } - - modelRenderer->begin(false, renderingShadows, false, colorPickingSelection); - - if(colorPickingSelection == false) { - glInitNames(); - } - } - - if(colorPickingSelection == false) { - glPushName(visibleUnitIndex); - } - - //assertGl(); - - glMatrixMode(GL_MODELVIEW); - //debuxar modelo - glPushMatrix(); - - //translate - Vec3f currVec= unit->getCurrVectorFlat(); - glTranslatef(currVec.x, currVec.y, currVec.z); - - //rotate - glRotatef(unit->getRotation(), 0.f, 1.f, 0.f); - - //render - Model *model= unit->getCurrentModelPtr(); - //if(this->gameCamera->getPos().dist(unit->getCurrVector()) <= SKIP_INTERPOLATION_DISTANCE) { - - // ***MV don't think this is needed below 2013/01/11 - model->updateInterpolationVertices(unit->getAnimProgressAsFloat(), unit->isAlive() && !unit->isAnimProgressBound()); - - //} - - if(colorPickingSelection == true) { - unit->setUniquePickingColor(); - unitsList.push_back(unit); - } - - modelRenderer->render(model,renderingShadows?rmShadows:rmSelection); - - glPopMatrix(); - - if(colorPickingSelection == false) { - glPopName(); - } - } - } - - if(modelRenderStarted == true) { - modelRenderer->end(); - if(colorPickingSelection == false) { - glPopAttrib(); - } - } - } - //glDisable(GL_DEPTH_TEST); - return unitsList; -} - -//render objects for selection purposes -vector Renderer::renderObjectsFast(bool renderingShadows, bool resourceOnly, - bool colorPickingSelection) { - vector objectList; - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return objectList; - } - - VisibleQuadContainerCache &qCache = getQuadCache(); - if(qCache.visibleObjectList.empty() == false) { - if(colorPickingSelection == true) { - objectList.reserve(qCache.visibleObjectList.size()); - } - - bool modelRenderStarted = false; - for(int visibleIndex = 0; - visibleIndex < (int)qCache.visibleObjectList.size(); ++visibleIndex) { - Object *o = qCache.visibleObjectList[visibleIndex]; - - if(modelRenderStarted == false) { - modelRenderStarted = true; - - if(colorPickingSelection == false) { - glDisable(GL_LIGHTING); - - if (renderingShadows == false){ - glPushAttrib(GL_ENABLE_BIT); - glDisable(GL_TEXTURE_2D); - } - else { - glPushAttrib(GL_ENABLE_BIT| GL_TEXTURE_BIT); - glAlphaFunc(GL_GREATER, 0.5f); - - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); - - //set color to the texture alpha - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_REPLACE); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PRIMARY_COLOR); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR); +// render units for selection purposes +vector Renderer::renderUnitsFast(bool renderingShadows, + bool colorPickingSelection) { + vector unitsList; + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return unitsList; + } + + assert(game != NULL); + // const World *world= game->getWorld(); + // assert(world != NULL); + + VisibleQuadContainerCache &qCache = getQuadCache(); + if (qCache.visibleQuadUnitList.empty() == false) { + if (colorPickingSelection == true) { + unitsList.reserve(qCache.visibleQuadUnitList.size()); + } - //set alpha to the texture alpha - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_TEXTURE); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA); - } - } + bool modelRenderStarted = false; + bool renderOnlyBuildings = true; + for (int k = 0; k < 2; k++) { + if (k == 0) { + // glDisable(GL_DEPTH_TEST); + renderOnlyBuildings = true; + } else { + if (colorPickingSelection == true) { + // clear depth buffer to get units behind buildings rendered in front + // of them + glClear(GL_DEPTH_BUFFER_BIT); + } + // glEnable(GL_DEPTH_TEST); + renderOnlyBuildings = false; + } + for (int visibleUnitIndex = 0; + visibleUnitIndex < (int)qCache.visibleQuadUnitList.size(); + ++visibleUnitIndex) { + Unit *unit = qCache.visibleQuadUnitList[visibleUnitIndex]; + + if (renderingShadows == false && unit->isAlive() == false) { + // no need to render dead units for selection + continue; + } - modelRenderer->begin(false, renderingShadows, false, colorPickingSelection); + if (renderOnlyBuildings == true && + unit->getType()->hasSkillClass(scMove)) { + continue; + } - if(colorPickingSelection == false) { - glInitNames(); - } - } + if (renderOnlyBuildings == false && + !unit->getType()->hasSkillClass(scMove)) { + continue; + } - if(resourceOnly == false || o->getResource()!= NULL) { - Model *objModel= o->getModelPtr(); - //if(this->gameCamera->getPos().dist(o->getPos()) <= SKIP_INTERPOLATION_DISTANCE) { + if (modelRenderStarted == false) { + modelRenderStarted = true; + + if (colorPickingSelection == false) { + // glPushAttrib(GL_ENABLE_BIT| GL_TEXTURE_BIT); + glDisable(GL_LIGHTING); + if (renderingShadows == false) { + glPushAttrib(GL_ENABLE_BIT); + glDisable(GL_TEXTURE_2D); + } else { + glPushAttrib(GL_ENABLE_BIT | GL_TEXTURE_BIT); + glEnable(GL_TEXTURE_2D); + glAlphaFunc(GL_GREATER, 0.4f); + + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); + + // set color to the texture alpha + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_REPLACE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PRIMARY_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR); + + // set alpha to the texture alpha + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_TEXTURE); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA); + } + } - // ***MV don't think this is needed below 2013/01/11 - //objModel->updateInterpolationData(o->getAnimProgress(), true); + modelRenderer->begin(false, renderingShadows, false, + colorPickingSelection); - //} - const Vec3f v= o->getConstPos(); + if (colorPickingSelection == false) { + glInitNames(); + } + } - if(colorPickingSelection == false) { - glPushName(OBJECT_SELECT_OFFSET+visibleIndex); - } + if (colorPickingSelection == false) { + glPushName(visibleUnitIndex); + } - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - glTranslatef(v.x, v.y, v.z); - glRotatef(o->getRotation(), 0.f, 1.f, 0.f); - - if(colorPickingSelection == true) { - o->setUniquePickingColor(); - objectList.push_back(o); - } + // assertGl(); - modelRenderer->render(objModel,resourceOnly?rmSelection:rmNormal); - - glPopMatrix(); - - if(colorPickingSelection == false) { - glPopName(); - } - } - } - - if(modelRenderStarted == true) { - modelRenderer->end(); - - if(colorPickingSelection == false) { - glPopAttrib(); - } - } - } + glMatrixMode(GL_MODELVIEW); + // debuxar modelo + glPushMatrix(); - return objectList; -} + // translate + Vec3f currVec = unit->getCurrVectorFlat(); + glTranslatef(currVec.x, currVec.y, currVec.z); -// ==================== gl caps ==================== + // rotate + glRotatef(unit->getRotation(), 0.f, 1.f, 0.f); -void Renderer::checkGlCaps() { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } + // render + Model *model = unit->getCurrentModelPtr(); + // if(this->gameCamera->getPos().dist(unit->getCurrVector()) <= + // SKIP_INTERPOLATION_DISTANCE) { - if(glActiveTexture == NULL) { - string message; + // ***MV don't think this is needed below 2013/01/11 + model->updateInterpolationVertices(unit->getAnimProgressAsFloat(), + unit->isAlive() && + !unit->isAnimProgressBound()); - message += "Your system supports OpenGL version ["; - message += getGlVersion() + string("]\n"); - message += "MegaGlest needs a version that supports\n"; - message += "glActiveTexture (OpenGL 1.3) or the ARB_multitexture extension."; + //} - throw megaglest_runtime_error(message.c_str(),true); - } + if (colorPickingSelection == true) { + unit->setUniquePickingColor(); + unitsList.push_back(unit); + } - //opengl 2.1 - if(glewIsSupported("GL_VERSION_2_1") == false) { - string message; + modelRenderer->render(model, + renderingShadows ? rmShadows : rmSelection); - message += "Your system supports OpenGL version ["; - message += getGlVersion() + string("]\n"); - message += "MegaGlest needs at least version 2.1 to work\n"; - message += "You may solve this problem by installing your latest video card drivers"; + glPopMatrix(); - throw megaglest_runtime_error(message.c_str(),true); - } + if (colorPickingSelection == false) { + glPopName(); + } + } + } - //opengl 1.4 or extension - //if(!isGlVersionSupported(1, 4, 0)){ - if(glewIsSupported("GL_VERSION_1_4") == false) { - checkExtension("GL_ARB_texture_env_crossbar", "MegaGlest"); - } -} + if (modelRenderStarted == true) { + modelRenderer->end(); + if (colorPickingSelection == false) { + glPopAttrib(); + } + } + } + // glDisable(GL_DEPTH_TEST); + return unitsList; +} + +// render objects for selection purposes +vector Renderer::renderObjectsFast(bool renderingShadows, + bool resourceOnly, + bool colorPickingSelection) { + vector objectList; + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return objectList; + } + + VisibleQuadContainerCache &qCache = getQuadCache(); + if (qCache.visibleObjectList.empty() == false) { + if (colorPickingSelection == true) { + objectList.reserve(qCache.visibleObjectList.size()); + } -void Renderer::checkGlOptionalCaps() { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } + bool modelRenderStarted = false; + for (int visibleIndex = 0; + visibleIndex < (int)qCache.visibleObjectList.size(); ++visibleIndex) { + Object *o = qCache.visibleObjectList[visibleIndex]; + + if (modelRenderStarted == false) { + modelRenderStarted = true; + + if (colorPickingSelection == false) { + glDisable(GL_LIGHTING); + + if (renderingShadows == false) { + glPushAttrib(GL_ENABLE_BIT); + glDisable(GL_TEXTURE_2D); + } else { + glPushAttrib(GL_ENABLE_BIT | GL_TEXTURE_BIT); + glAlphaFunc(GL_GREATER, 0.5f); + + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); + + // set color to the texture alpha + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_REPLACE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PRIMARY_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR); + + // set alpha to the texture alpha + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_TEXTURE); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA); + } + } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //shadows - if(shadows == sProjected || shadows == sShadowMapping) { - if(getGlMaxTextureUnits() < 3) { - throw megaglest_runtime_error("Your system doesn't support 3 texture units, required for shadows"); - } - } + modelRenderer->begin(false, renderingShadows, false, + colorPickingSelection); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //shadow mapping - if(shadows == sShadowMapping) { - checkExtension("GL_ARB_shadow", "Shadow Mapping"); - //checkExtension("GL_ARB_shadow_ambient", "Shadow Mapping"); - //checkExtension("GL_ARB_depth_texture", "Shadow Mapping"); - } + if (colorPickingSelection == false) { + glInitNames(); + } + } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); -} + if (resourceOnly == false || o->getResource() != NULL) { + Model *objModel = o->getModelPtr(); + // if(this->gameCamera->getPos().dist(o->getPos()) <= + // SKIP_INTERPOLATION_DISTANCE) { -void Renderer::checkExtension(const string &extension, const string &msg) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } + // ***MV don't think this is needed below 2013/01/11 + // objModel->updateInterpolationData(o->getAnimProgress(), true); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(!isGlExtensionSupported(extension.c_str())) { - string str= "OpenGL extension not supported: " + extension + ", required for " + msg; - throw megaglest_runtime_error(str); - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); -} + //} + const Vec3f v = o->getConstPos(); -// ==================== init 3d lists ==================== + if (colorPickingSelection == false) { + glPushName(OBJECT_SELECT_OFFSET + visibleIndex); + } -void Renderer::init3dList() { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glTranslatef(v.x, v.y, v.z); + glRotatef(o->getRotation(), 0.f, 1.f, 0.f); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (colorPickingSelection == true) { + o->setUniquePickingColor(); + objectList.push_back(o); + } - render3dSetup(); + modelRenderer->render(objModel, resourceOnly ? rmSelection : rmNormal); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + glPopMatrix(); - //const Metrics &metrics= Metrics::getInstance(); + if (colorPickingSelection == false) { + glPopName(); + } + } + } - //assertGl(); + if (modelRenderStarted == true) { + modelRenderer->end(); - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (colorPickingSelection == false) { + glPopAttrib(); + } + } + } - //list3d= glGenLists(1); - //assertGl(); - //list3dValid=true; + return objectList; +} - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +// ==================== gl caps ==================== - //glNewList(list3d, GL_COMPILE_AND_EXECUTE); - //need to execute, because if not gluPerspective takes no effect and gluLoadMatrix is wrong - //render3dSetup(); - //glEndList(); +void Renderer::checkGlCaps() { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (glActiveTexture == NULL) { + string message; - //assert - //assertGl(); -} + message += "Your system supports OpenGL version ["; + message += getGlVersion() + string("]\n"); + message += "MegaGlest needs a version that supports\n"; + message += + "glActiveTexture (OpenGL 1.3) or the ARB_multitexture extension."; -void Renderer::render3dSetup() { - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - const Metrics &metrics= Metrics::getInstance(); - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + throw megaglest_runtime_error(message.c_str(), true); + } - //misc - glViewport(0, 0, metrics.getScreenW(), metrics.getScreenH()); - glClearColor(fowColor.x, fowColor.y, fowColor.z, fowColor.w); - glFrontFace(GL_CW); - glEnable(GL_CULL_FACE); - loadProjectionMatrix(); + // opengl 2.1 + if (glewIsSupported("GL_VERSION_2_1") == false) { + string message; - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + message += "Your system supports OpenGL version ["; + message += getGlVersion() + string("]\n"); + message += "MegaGlest needs at least version 2.1 to work\n"; + message += "You may solve this problem by installing your latest video " + "card drivers"; - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + throw megaglest_runtime_error(message.c_str(), true); + } - //texture state - glActiveTexture(shadowTexUnit); - glDisable(GL_TEXTURE_2D); - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + // opengl 1.4 or extension + // if(!isGlVersionSupported(1, 4, 0)){ + if (glewIsSupported("GL_VERSION_1_4") == false) { + checkExtension("GL_ARB_texture_env_crossbar", "MegaGlest"); + } +} - glActiveTexture(fowTexUnit); - glDisable(GL_TEXTURE_2D); - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); +void Renderer::checkGlOptionalCaps() { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + // shadows + if (shadows == sProjected || shadows == sShadowMapping) { + if (getGlMaxTextureUnits() < 3) { + throw megaglest_runtime_error( + "Your system doesn't support 3 texture units, required for shadows"); + } + } - glActiveTexture(baseTexUnit); - glEnable(GL_TEXTURE_2D); - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + // shadow mapping + if (shadows == sShadowMapping) { + checkExtension("GL_ARB_shadow", "Shadow Mapping"); + // checkExtension("GL_ARB_shadow_ambient", "Shadow Mapping"); + // checkExtension("GL_ARB_depth_texture", "Shadow Mapping"); + } - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); +} - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void Renderer::checkExtension(const string &extension, const string &msg) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + if (!isGlExtensionSupported(extension.c_str())) { + string str = "OpenGL extension not supported: " + extension + + ", required for " + msg; + throw megaglest_runtime_error(str); + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); +} - //material state - glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, defSpecularColor.ptr()); - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, defAmbientColor.ptr()); - glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, defDiffuseColor.ptr()); - glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE); - glColor4fv(defColor.ptr()); +// ==================== init 3d lists ==================== - //blend state - glDisable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); +void Renderer::init3dList() { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - //alpha test state - glEnable(GL_ALPHA_TEST); - glAlphaFunc(GL_GREATER, 0.f); + render3dSetup(); - //depth test state - glEnable(GL_DEPTH_TEST); - glDepthMask(GL_TRUE); - glDepthFunc(GL_LESS); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // const Metrics &metrics= Metrics::getInstance(); - //lighting state - glEnable(GL_LIGHTING); - glEnable(GL_LIGHT0); + // assertGl(); - //matrix mode - glMatrixMode(GL_MODELVIEW); + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //stencil test - glDisable(GL_STENCIL_TEST); + // list3d= glGenLists(1); + // assertGl(); + // list3dValid=true; - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //fog - const Tileset *tileset= NULL; - if(game != NULL && game->getWorld() != NULL) { - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - tileset = game->getWorld()->getTileset(); - } + // glNewList(list3d, GL_COMPILE_AND_EXECUTE); + // need to execute, because if not gluPerspective takes no effect and + // gluLoadMatrix is wrong render3dSetup(); glEndList(); - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(tileset != NULL && tileset->getFog()) { - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // assert + // assertGl(); +} - glEnable(GL_FOG); - if(tileset->getFogMode()==fmExp) { - glFogi(GL_FOG_MODE, GL_EXP); - } - else { - glFogi(GL_FOG_MODE, GL_EXP2); - } +void Renderer::render3dSetup() { + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + const Metrics &metrics = Metrics::getInstance(); + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + // misc + glViewport(0, 0, metrics.getScreenW(), metrics.getScreenH()); + glClearColor(fowColor.x, fowColor.y, fowColor.z, fowColor.w); + glFrontFace(GL_CW); + glEnable(GL_CULL_FACE); + loadProjectionMatrix(); + + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + // texture state + glActiveTexture(shadowTexUnit); + glDisable(GL_TEXTURE_2D); + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + + glActiveTexture(fowTexUnit); + glDisable(GL_TEXTURE_2D); + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + + glActiveTexture(baseTexUnit); + glEnable(GL_TEXTURE_2D); + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + // material state + glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, defSpecularColor.ptr()); + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, defAmbientColor.ptr()); + glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, defDiffuseColor.ptr()); + glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE); + glColor4fv(defColor.ptr()); + + // blend state + glDisable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + // alpha test state + glEnable(GL_ALPHA_TEST); + glAlphaFunc(GL_GREATER, 0.f); + + // depth test state + glEnable(GL_DEPTH_TEST); + glDepthMask(GL_TRUE); + glDepthFunc(GL_LESS); + + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + // lighting state + glEnable(GL_LIGHTING); + glEnable(GL_LIGHT0); + + // matrix mode + glMatrixMode(GL_MODELVIEW); + + // stencil test + glDisable(GL_STENCIL_TEST); + + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + // fog + const Tileset *tileset = NULL; + if (game != NULL && game->getWorld() != NULL) { + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + tileset = game->getWorld()->getTileset(); + } + + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + if (tileset != NULL && tileset->getFog()) { + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + glEnable(GL_FOG); + if (tileset->getFogMode() == fmExp) { + glFogi(GL_FOG_MODE, GL_EXP); + } else { + glFogi(GL_FOG_MODE, GL_EXP2); + } - glFogf(GL_FOG_DENSITY, tileset->getFogDensity()); - glFogfv(GL_FOG_COLOR, tileset->getFogColor().ptr()); - } + glFogf(GL_FOG_DENSITY, tileset->getFogDensity()); + glFogfv(GL_FOG_COLOR, tileset->getFogColor().ptr()); + } - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); } void Renderer::init2dList() { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - -// //this list sets the state for the 2d rendering -// list2d= glGenLists(1); -// assertGl(); -// list2dValid=true; -// -// glNewList(list2d, GL_COMPILE); -// render2dMenuSetup(); -// glEndList(); -// -// assertGl(); + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + // //this list sets the state for the 2d rendering + // list2d= glGenLists(1); + // assertGl(); + // list2dValid=true; + // + // glNewList(list2d, GL_COMPILE); + // render2dMenuSetup(); + // glEndList(); + // + // assertGl(); } void Renderer::render2dMenuSetup() { - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - const Metrics &metrics= Metrics::getInstance(); - //projection - glViewport(0, 0, metrics.getScreenW(), metrics.getScreenH()); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glOrtho(0, metrics.getVirtualW(), 0, metrics.getVirtualH(), 0, 1); - - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //modelview - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //disable everything - glDisable(GL_BLEND); - glDisable(GL_LIGHTING); - glDisable(GL_ALPHA_TEST); - glDisable(GL_DEPTH_TEST); - glDisable(GL_STENCIL_TEST); - glDisable(GL_FOG); - glDisable(GL_CULL_FACE); - glFrontFace(GL_CCW); - - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(glActiveTexture != NULL) { - glActiveTexture(baseTexUnit); - } - else { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s] Line: %d\nglActiveTexture == NULL\nglActiveTexture is only supported if the GL version is 1.3 or greater,\nor if the ARB_multitexture extension is supported!",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - throw megaglest_runtime_error(szBuf); - } + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + const Metrics &metrics = Metrics::getInstance(); + // projection + glViewport(0, 0, metrics.getScreenW(), metrics.getScreenH()); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(0, metrics.getVirtualW(), 0, metrics.getVirtualH(), 0, 1); + + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + // modelview + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + // disable everything + glDisable(GL_BLEND); + glDisable(GL_LIGHTING); + glDisable(GL_ALPHA_TEST); + glDisable(GL_DEPTH_TEST); + glDisable(GL_STENCIL_TEST); + glDisable(GL_FOG); + glDisable(GL_CULL_FACE); + glFrontFace(GL_CCW); + + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + if (glActiveTexture != NULL) { + glActiveTexture(baseTexUnit); + } else { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s] Line: %d\nglActiveTexture == NULL\nglActiveTexture " + "is only supported if the GL version is 1.3 or greater,\nor if " + "the ARB_multitexture extension is supported!", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + throw megaglest_runtime_error(szBuf); + } - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - glDisable(GL_TEXTURE_2D); + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + glDisable(GL_TEXTURE_2D); - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //blend func - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + // blend func + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - //color - glColor4f(1.f, 1.f, 1.f, 1.f); + // color + glColor4f(1.f, 1.f, 1.f, 1.f); - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); } -//void Renderer::init3dListMenu(const MainMenu *mm) { +// void Renderer::init3dListMenu(const MainMenu *mm) { // if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { // return; // } // // //this->mm3d = mm; -// //printf("In [%s::%s Line: %d] this->custom_mm3d [%p] this->mm3d [%p]\n",__FILE__,__FUNCTION__,__LINE__,this->custom_mm3d,this->mm3d); +// //printf("In [%s::%s Line: %d] this->custom_mm3d [%p] this->mm3d +//[%p]\n",__FILE__,__FUNCTION__,__LINE__,this->custom_mm3d,this->mm3d); // ///* // assertGl(); // -// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) +// SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: +// %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); // // const Metrics &metrics= Metrics::getInstance(); // //const MenuBackground *mb= mm->getConstMenuBackground(); @@ -8317,7 +9053,9 @@ void Renderer::render2dMenuSetup() { // mb = mm->getConstMenuBackground(); // } // -// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) +// SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: +//%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); // // if(this->customlist3dMenu != NULL) { // *this->customlist3dMenu = glGenLists(1); @@ -8329,7 +9067,9 @@ void Renderer::render2dMenuSetup() { // list3dMenuValid=true; // } // -// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) +// SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: +//%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); // // if(this->customlist3dMenu != NULL) { // glNewList(*this->customlist3dMenu, GL_COMPILE); @@ -8338,7 +9078,9 @@ void Renderer::render2dMenuSetup() { // glNewList(list3dMenu, GL_COMPILE); // } // -// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) +// SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: +//%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); // //misc // glViewport(0, 0, metrics.getScreenW(), metrics.getScreenH()); // glClearColor(0.4f, 0.4f, 0.4f, 1.f); @@ -8346,17 +9088,18 @@ void Renderer::render2dMenuSetup() { // glEnable(GL_CULL_FACE); // glMatrixMode(GL_PROJECTION); // glLoadIdentity(); -// gluPerspective(perspFov, metrics.getAspectRatio(), perspNearPlane, 1000000); +// gluPerspective(perspFov, metrics.getAspectRatio(), +//perspNearPlane, 1000000); // // //texture state // glEnable(GL_TEXTURE_2D); // glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); // // //material state -// glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, defSpecularColor.ptr()); -// glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, defAmbientColor.ptr()); -// glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, defDiffuseColor.ptr()); -// glColor4fv(defColor.ptr()); +// glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, +// defSpecularColor.ptr()); glMaterialfv(GL_FRONT_AND_BACK, +// GL_AMBIENT, defAmbientColor.ptr()); glMaterialfv(GL_FRONT_AND_BACK, +// GL_DIFFUSE, defDiffuseColor.ptr()); glColor4fv(defColor.ptr()); // glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE); // // //blend state @@ -8381,22 +9124,30 @@ void Renderer::render2dMenuSetup() { // //stencil test // glDisable(GL_STENCIL_TEST); // -// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) +// SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: +//%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); // // //fog // if(mb != NULL && mb->getFog()){ -// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) +// SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: +//%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); // // glEnable(GL_FOG); // glFogi(GL_FOG_MODE, GL_EXP2); // glFogf(GL_FOG_DENSITY, mb->getFogDensity()); // } // -// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) +// SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: +//%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); // // glEndList(); // -// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) +// SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: +//%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); // // //assert // assertGl(); @@ -8404,477 +9155,531 @@ void Renderer::render2dMenuSetup() { //} void Renderer::render3dMenuSetup(const MainMenu *mm) { - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - const Metrics &metrics= Metrics::getInstance(); - const MenuBackground *mb = NULL; - if(mm != NULL) { - mb = mm->getConstMenuBackground(); - } - - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //misc - glViewport(0, 0, metrics.getScreenW(), metrics.getScreenH()); - glClearColor(0.4f, 0.4f, 0.4f, 1.f); - glFrontFace(GL_CW); - glEnable(GL_CULL_FACE); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - gluPerspective(perspFov, metrics.getAspectRatio(), perspNearPlane, 1000000); - - //texture state - glEnable(GL_TEXTURE_2D); - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - - //material state - glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, defSpecularColor.ptr()); - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, defAmbientColor.ptr()); - glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, defDiffuseColor.ptr()); - glColor4fv(defColor.ptr()); - glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE); - - //blend state - glDisable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - - //alpha test state - glEnable(GL_ALPHA_TEST); - glAlphaFunc(GL_GREATER, 0.f); - - //depth test state - glEnable(GL_DEPTH_TEST); - glDepthMask(GL_TRUE); - glDepthFunc(GL_LESS); - - //lighting state - glEnable(GL_LIGHTING); - - //matrix mode - glMatrixMode(GL_MODELVIEW); - - //stencil test - glDisable(GL_STENCIL_TEST); - - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //fog - if(mb != NULL && mb->getFog()) { - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - glEnable(GL_FOG); - glFogi(GL_FOG_MODE, GL_EXP2); - glFogf(GL_FOG_DENSITY, mb->getFogDensity()); - } - - //assert - assertGl(); - - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + const Metrics &metrics = Metrics::getInstance(); + const MenuBackground *mb = NULL; + if (mm != NULL) { + mb = mm->getConstMenuBackground(); + } + + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // misc + glViewport(0, 0, metrics.getScreenW(), metrics.getScreenH()); + glClearColor(0.4f, 0.4f, 0.4f, 1.f); + glFrontFace(GL_CW); + glEnable(GL_CULL_FACE); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + gluPerspective(perspFov, metrics.getAspectRatio(), perspNearPlane, 1000000); + + // texture state + glEnable(GL_TEXTURE_2D); + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + + // material state + glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, defSpecularColor.ptr()); + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, defAmbientColor.ptr()); + glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, defDiffuseColor.ptr()); + glColor4fv(defColor.ptr()); + glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE); + + // blend state + glDisable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + // alpha test state + glEnable(GL_ALPHA_TEST); + glAlphaFunc(GL_GREATER, 0.f); + + // depth test state + glEnable(GL_DEPTH_TEST); + glDepthMask(GL_TRUE); + glDepthFunc(GL_LESS); + + // lighting state + glEnable(GL_LIGHTING); + + // matrix mode + glMatrixMode(GL_MODELVIEW); + + // stencil test + glDisable(GL_STENCIL_TEST); + + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + // fog + if (mb != NULL && mb->getFog()) { + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + glEnable(GL_FOG); + glFogi(GL_FOG_MODE, GL_EXP2); + glFogf(GL_FOG_DENSITY, mb->getFogDensity()); + } + + // assert + assertGl(); + + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); } // ==================== misc ==================== void Renderer::loadProjectionMatrix() { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - GLdouble clipping; - const Metrics &metrics= Metrics::getInstance(); + GLdouble clipping; + const Metrics &metrics = Metrics::getInstance(); - assertGl(); + assertGl(); - clipping= photoMode ? perspFarPlane*100 : perspFarPlane; + clipping = photoMode ? perspFarPlane * 100 : perspFarPlane; - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - gluPerspective(perspFov, metrics.getAspectRatio(), perspNearPlane, clipping); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + gluPerspective(perspFov, metrics.getAspectRatio(), perspNearPlane, clipping); - assertGl(); + assertGl(); } void Renderer::enableProjectiveTexturing() { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - glTexGenfv(GL_S, GL_EYE_PLANE, &shadowMapMatrix[0]); - glTexGenfv(GL_T, GL_EYE_PLANE, &shadowMapMatrix[4]); - glTexGenfv(GL_R, GL_EYE_PLANE, &shadowMapMatrix[8]); - glTexGenfv(GL_Q, GL_EYE_PLANE, &shadowMapMatrix[12]); - glEnable(GL_TEXTURE_GEN_S); - glEnable(GL_TEXTURE_GEN_T); - glEnable(GL_TEXTURE_GEN_R); - glEnable(GL_TEXTURE_GEN_Q); + glTexGenfv(GL_S, GL_EYE_PLANE, &shadowMapMatrix[0]); + glTexGenfv(GL_T, GL_EYE_PLANE, &shadowMapMatrix[4]); + glTexGenfv(GL_R, GL_EYE_PLANE, &shadowMapMatrix[8]); + glTexGenfv(GL_Q, GL_EYE_PLANE, &shadowMapMatrix[12]); + glEnable(GL_TEXTURE_GEN_S); + glEnable(GL_TEXTURE_GEN_T); + glEnable(GL_TEXTURE_GEN_R); + glEnable(GL_TEXTURE_GEN_Q); } // ==================== private aux drawing ==================== -void Renderer::renderHealthBar(Vec3f v, Unit *unit, float height, bool lineBorder, const Texture2D *texture, const Texture2D *backgroundTexture) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - int numberOfBars=1; - int barCount=0; - float hp=unit->getHpRatio(); - float ep=-1.f; - if(unit->getType()->getTotalMaxEp(unit->getTotalUpgrade()) !=0 ) { - ep=unit->getEpRatio(); - numberOfBars++; - } - int productionPercent=unit->getProductionPercent(); - if(productionPercent!=-1) { - numberOfBars++; - } - int size=unit->getType()->getSize(); - - - Vec3f rightVector; - Vec3f upVector; - Vec3f rightVectorTexture; - Vec3f upVectorTexture; - v.y+=1; - float modelview[16]; - float width=(float)size/6+0.25f; - float red; - float green; - float brightness=0.8f; - - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); +void Renderer::renderHealthBar(Vec3f v, Unit *unit, float height, + bool lineBorder, const Texture2D *texture, + const Texture2D *backgroundTexture) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + int numberOfBars = 1; + int barCount = 0; + float hp = unit->getHpRatio(); + float ep = -1.f; + if (unit->getType()->getTotalMaxEp(unit->getTotalUpgrade()) != 0) { + ep = unit->getEpRatio(); + numberOfBars++; + } + int productionPercent = unit->getProductionPercent(); + if (productionPercent != -1) { + numberOfBars++; + } + int size = unit->getType()->getSize(); + + Vec3f rightVector; + Vec3f upVector; + Vec3f rightVectorTexture; + Vec3f upVectorTexture; + v.y += 1; + float modelview[16]; + float width = (float)size / 6 + 0.25f; + float red; + float green; + float brightness = 0.8f; + + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + + // get the current modelview state + glGetFloatv(GL_MODELVIEW_MATRIX, modelview); + rightVector = Vec3f(modelview[0], modelview[4], modelview[8]); + upVector = Vec3f(modelview[1], modelview[5], modelview[9]); + rightVectorTexture = rightVector * 2; + upVectorTexture = upVector * 4; + + // from green to yellow to red + + if (hp >= 0.75f) { + green = 1; + red = 1 - ((2 * hp - 1) - 0.5f); + } else { + red = 1; + green = 0.5f + (2 * hp - 1); + } + + if (red > 1.0f) + red = 1.0f; + if (green > 1.0f) + green = 1.0f; + float yOffset = (float)numberOfBars / 2.f; + + if (backgroundTexture != NULL) { + // backgroundTexture + glEnable(GL_TEXTURE_2D); + glBindTexture( + GL_TEXTURE_2D, + static_cast(backgroundTexture)->getHandle()); + glColor4f(1.f, 1.f, 1.f, 1.f); + // glColor4f(red+0.1f,green+0.1f,0.1f,0.5f); + glBegin(GL_QUADS); + glTexCoord2i(0, 1); + glVertex3fv( + (v - (rightVectorTexture * width - upVectorTexture * height * yOffset)) + .ptr()); + glTexCoord2i(0, 0); + glVertex3fv( + (v - (rightVectorTexture * width + upVectorTexture * height * yOffset)) + .ptr()); + glTexCoord2i(1, 0); + glVertex3fv( + (v + (rightVectorTexture * width - upVectorTexture * height * yOffset)) + .ptr()); + glTexCoord2i(1, 1); + glVertex3fv( + (v + (rightVectorTexture * width + upVectorTexture * height * yOffset)) + .ptr()); + glEnd(); + glDisable(GL_TEXTURE_2D); + } + + // healthbar + glColor4f(red * brightness, green * brightness, 0.0f, 0.4f); + // hpbar + barCount++; + internalRenderHp(numberOfBars, barCount, hp, v, width, height, rightVector, + upVector); + + if (ep > -1.0f) { + // epbar + barCount++; + // glColor4f(brightness,0,brightness,0.5f); + glColor4f(.15f * brightness, 0.3f * brightness, 0.8f * brightness, 0.7f); + internalRenderHp(numberOfBars, barCount, ep, v, width, height, rightVector, + upVector); + } + if (productionPercent != -1) { + barCount++; + glColor4f(brightness, 0, brightness, 0.6f); + // glColor4f(0.0f*brightness,0.4f*brightness,0.2f*brightness,0.8f); + internalRenderHp(numberOfBars, barCount, (float)productionPercent / 100, v, + width, height, rightVector, upVector); + } + + // glBegin(GL_QUADS); + // if(ep < -2.0f) { + // //hpbar + // glVertex3fv((v - (rightVector*width - + // upVector*height)).ptr()); glVertex3fv((v - (rightVector*width + // + + // upVector*height)).ptr()); glVertex3fv((v + (rightVector*hp*width + // - + // upVector*height)).ptr()); glVertex3fv((v + (rightVector*hp*width + // + upVector*height)).ptr()); + // + // } else { + // //hpbar + // glVertex3fv((v - (rightVector*width - + // upVector*height)).ptr()); glVertex3fv((v - (rightVector*width + // + + // upVector*height*0.0f)).ptr()); glVertex3fv((v + + // (rightVector*hp*width - upVector*height*0.0f)).ptr()); + // glVertex3fv((v + (rightVector*hp*width + upVector*height)).ptr()); + // //epbar + // glColor4f(brightness,0,brightness,0.4f); + // glVertex3fv((v - (rightVector*width + + // upVector*height*0.0f)).ptr()); glVertex3fv((v - (rightVector*width + // + + // upVector*height)).ptr()); glVertex3fv((v + (rightVector*ep*width + // - + // upVector*height)).ptr()); glVertex3fv((v + (rightVector*ep*width + // - upVector*height*0.0f)).ptr()); + // } + // glEnd(); + + if (lineBorder) { + // border + glColor4f(red * brightness, green * brightness, 0.1f * brightness, 0.5f); + glBegin(GL_LINE_LOOP); + glVertex3fv( + (v - (rightVector * width - upVector * height * yOffset)).ptr()); + glVertex3fv( + (v - (rightVector * width + upVector * height * yOffset)).ptr()); + glVertex3fv( + (v + (rightVector * width - upVector * height * yOffset)).ptr()); + glVertex3fv( + (v + (rightVector * width + upVector * height * yOffset)).ptr()); + glEnd(); + } - // get the current modelview state - glGetFloatv(GL_MODELVIEW_MATRIX , modelview); - rightVector= Vec3f(modelview[0], modelview[4], modelview[8]); - upVector= Vec3f(modelview[1], modelview[5], modelview[9]); - rightVectorTexture=rightVector*2; - upVectorTexture=upVector*4; - - //from green to yellow to red - - if(hp >= 0.75f) { - green=1; - red=1-((2*hp-1)-0.5f); - } else { - red=1; - green=0.5f+(2*hp-1); - } - - if(red>1.0f) red=1.0f; - if(green>1.0f) green=1.0f; - float yOffset=(float)numberOfBars/2.f; - - if(backgroundTexture!=NULL) { - //backgroundTexture - glEnable(GL_TEXTURE_2D); - glBindTexture(GL_TEXTURE_2D, static_cast(backgroundTexture)->getHandle()); - glColor4f(1.f,1.f,1.f,1.f); - //glColor4f(red+0.1f,green+0.1f,0.1f,0.5f); - glBegin(GL_QUADS); - glTexCoord2i(0,1); - glVertex3fv((v - (rightVectorTexture*width - upVectorTexture*height*yOffset)).ptr()); - glTexCoord2i(0,0); - glVertex3fv((v - (rightVectorTexture*width + upVectorTexture*height*yOffset)).ptr()); - glTexCoord2i(1,0); - glVertex3fv((v + (rightVectorTexture*width - upVectorTexture*height*yOffset)).ptr()); - glTexCoord2i(1,1); - glVertex3fv((v + (rightVectorTexture*width + upVectorTexture*height*yOffset)).ptr()); - glEnd(); - glDisable(GL_TEXTURE_2D); - } - - //healthbar - glColor4f(red*brightness,green*brightness,0.0f,0.4f); - //hpbar - barCount++; - internalRenderHp(numberOfBars,barCount,hp,v,width,height,rightVector,upVector); - - - if(ep > -1.0f) { - //epbar - barCount++; - //glColor4f(brightness,0,brightness,0.5f); - glColor4f(.15f*brightness,0.3f*brightness,0.8f*brightness,0.7f); - internalRenderHp(numberOfBars,barCount,ep,v,width,height,rightVector,upVector); - } - if(productionPercent!=-1) { - barCount++; - glColor4f(brightness,0,brightness,0.6f); - //glColor4f(0.0f*brightness,0.4f*brightness,0.2f*brightness,0.8f); - internalRenderHp(numberOfBars,barCount,(float)productionPercent/100,v,width,height,rightVector,upVector); - } - - -// glBegin(GL_QUADS); -// if(ep < -2.0f) { -// //hpbar -// glVertex3fv((v - (rightVector*width - upVector*height)).ptr()); -// glVertex3fv((v - (rightVector*width + upVector*height)).ptr()); -// glVertex3fv((v + (rightVector*hp*width - upVector*height)).ptr()); -// glVertex3fv((v + (rightVector*hp*width + upVector*height)).ptr()); -// -// } else { -// //hpbar -// glVertex3fv((v - (rightVector*width - upVector*height)).ptr()); -// glVertex3fv((v - (rightVector*width + upVector*height*0.0f)).ptr()); -// glVertex3fv((v + (rightVector*hp*width - upVector*height*0.0f)).ptr()); -// glVertex3fv((v + (rightVector*hp*width + upVector*height)).ptr()); -// //epbar -// glColor4f(brightness,0,brightness,0.4f); -// glVertex3fv((v - (rightVector*width + upVector*height*0.0f)).ptr()); -// glVertex3fv((v - (rightVector*width + upVector*height)).ptr()); -// glVertex3fv((v + (rightVector*ep*width - upVector*height)).ptr()); -// glVertex3fv((v + (rightVector*ep*width - upVector*height*0.0f)).ptr()); -// } -// glEnd(); - - if(lineBorder) { - //border - glColor4f(red*brightness,green*brightness,0.1f*brightness,0.5f); - glBegin(GL_LINE_LOOP); - glVertex3fv((v - (rightVector*width - upVector*height*yOffset)).ptr()); - glVertex3fv((v - (rightVector*width + upVector*height*yOffset)).ptr()); - glVertex3fv((v + (rightVector*width - upVector*height*yOffset)).ptr()); - glVertex3fv((v + (rightVector*width + upVector*height*yOffset)).ptr()); - glEnd(); - } - - if(texture!=NULL) { - //BorderTexture - glEnable(GL_TEXTURE_2D); - glBindTexture(GL_TEXTURE_2D, static_cast(texture)->getHandle()); - glColor4f(1.f,1.f,1.f,1.f); - //glColor4f(red+0.1f,green+0.1f,0.1f,0.5f); - glBegin(GL_QUADS); - glTexCoord2i(0,1); - glVertex3fv((v - (rightVectorTexture*width - upVectorTexture*height*yOffset)).ptr()); - glTexCoord2i(0,0); - glVertex3fv((v - (rightVectorTexture*width + upVectorTexture*height*yOffset)).ptr()); - glTexCoord2i(1,0); - glVertex3fv((v + (rightVectorTexture*width - upVectorTexture*height*yOffset)).ptr()); - glTexCoord2i(1,1); - glVertex3fv((v + (rightVectorTexture*width + upVectorTexture*height*yOffset)).ptr()); - glEnd(); - glDisable(GL_TEXTURE_2D); - } + if (texture != NULL) { + // BorderTexture + glEnable(GL_TEXTURE_2D); + glBindTexture(GL_TEXTURE_2D, + static_cast(texture)->getHandle()); + glColor4f(1.f, 1.f, 1.f, 1.f); + // glColor4f(red+0.1f,green+0.1f,0.1f,0.5f); + glBegin(GL_QUADS); + glTexCoord2i(0, 1); + glVertex3fv( + (v - (rightVectorTexture * width - upVectorTexture * height * yOffset)) + .ptr()); + glTexCoord2i(0, 0); + glVertex3fv( + (v - (rightVectorTexture * width + upVectorTexture * height * yOffset)) + .ptr()); + glTexCoord2i(1, 0); + glVertex3fv( + (v + (rightVectorTexture * width - upVectorTexture * height * yOffset)) + .ptr()); + glTexCoord2i(1, 1); + glVertex3fv( + (v + (rightVectorTexture * width + upVectorTexture * height * yOffset)) + .ptr()); + glEnd(); + glDisable(GL_TEXTURE_2D); + } - glPopMatrix(); + glPopMatrix(); } void Renderer::internalRenderHp(int numberOfBars, int barNumber, float hp, - Vec3f posVector, float width, float singleHPheight, Vec3f rightVector, Vec3f upVector) { - - float yOffset=(float)numberOfBars*singleHPheight/2; - float offsetTop=yOffset-singleHPheight*(barNumber-1); - float offsetBottom=yOffset-singleHPheight*barNumber; - offsetBottom=offsetBottom*-1; - hp=hp*2-1; - - glBegin(GL_QUADS); - glVertex3fv((posVector - (rightVector*width - upVector*offsetTop)).ptr()); - glVertex3fv((posVector - (rightVector*width + upVector*offsetBottom)).ptr()); - glVertex3fv((posVector + (rightVector*hp*width - upVector*offsetBottom)).ptr()); - glVertex3fv((posVector + (rightVector*hp*width + upVector*offsetTop)).ptr()); - glEnd(); -} - -void Renderer::renderSelectionCircle(Vec3f v, int size, float radius, float thickness) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - GLUquadricObj *disc; - - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - - glTranslatef(v.x, v.y, v.z); - glRotatef(90.f, 1.f, 0.f, 0.f); - disc= gluNewQuadric(); - gluQuadricDrawStyle(disc, GLU_FILL); - gluCylinder(disc, radius*(size-thickness), radius*size, thickness, 30, 1); - gluDeleteQuadric(disc); - - glPopMatrix(); - // glBegin (GL_QUAD_STRIP); - // for (float k = 0; k <= 180; k=k+1) { - // float j=degToRad(k); - // glVertex3f(v.x+std::cos(j)*.9*radius*size, v.y+thickness, v.z+std::sin(j)*.9*radius*size); - // glVertex3f(v.x+std::cos(j)*radius*size, v.y, v.z+std::sin(j)*radius*size); - // } - // glEnd(); + Vec3f posVector, float width, + float singleHPheight, Vec3f rightVector, + Vec3f upVector) { + + float yOffset = (float)numberOfBars * singleHPheight / 2; + float offsetTop = yOffset - singleHPheight * (barNumber - 1); + float offsetBottom = yOffset - singleHPheight * barNumber; + offsetBottom = offsetBottom * -1; + hp = hp * 2 - 1; + + glBegin(GL_QUADS); + glVertex3fv((posVector - (rightVector * width - upVector * offsetTop)).ptr()); + glVertex3fv( + (posVector - (rightVector * width + upVector * offsetBottom)).ptr()); + glVertex3fv( + (posVector + (rightVector * hp * width - upVector * offsetBottom)).ptr()); + glVertex3fv( + (posVector + (rightVector * hp * width + upVector * offsetTop)).ptr()); + glEnd(); +} + +void Renderer::renderSelectionCircle(Vec3f v, int size, float radius, + float thickness) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + GLUquadricObj *disc; + + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + + glTranslatef(v.x, v.y, v.z); + glRotatef(90.f, 1.f, 0.f, 0.f); + disc = gluNewQuadric(); + gluQuadricDrawStyle(disc, GLU_FILL); + gluCylinder(disc, radius * (size - thickness), radius * size, thickness, 30, + 1); + gluDeleteQuadric(disc); + + glPopMatrix(); + // glBegin (GL_QUAD_STRIP); + // for (float k = 0; k <= 180; k=k+1) { + // float j=degToRad(k); + // glVertex3f(v.x+std::cos(j)*.9*radius*size, v.y+thickness, + // v.z+std::sin(j)*.9*radius*size); + // glVertex3f(v.x+std::cos(j)*radius*size, v.y, v.z+std::sin(j)*radius*size); + // } + // glEnd(); } void Renderer::renderArrow(const Vec3f &pos1, const Vec3f &pos2, - const Vec3f &color, float width) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - Config &config= Config::getInstance(); - if(config.getBool("RecordMode","false") == true) { - return; - } - - const int tesselation= 3; - const float arrowEndSize= 0.4f; - const float maxlen= 25; - const float blendDelay= 5.f; - - Vec3f dir= Vec3f(pos2-pos1); - float len= dir.length(); - - if(len>maxlen) { - return; - } - float alphaFactor= clamp((maxlen-len)/blendDelay, 0.f, 1.f); - - dir.normalize(); - Vec3f normal= dir.cross(Vec3f(0, 1, 0)); - - Vec3f pos2Left= pos2 + normal*(width-0.05f) - dir*arrowEndSize*width; - Vec3f pos2Right= pos2 - normal*(width-0.05f) - dir*arrowEndSize*width; - Vec3f pos1Left= pos1 + normal*(width+0.05f); - Vec3f pos1Right= pos1 - normal*(width+0.05f); - - //arrow body - glBegin(GL_TRIANGLE_STRIP); - for(int i=0; i<=tesselation; ++i) { - float t= static_cast(i)/tesselation; - Vec3f a= pos1Left.lerp(t, pos2Left); - Vec3f b= pos1Right.lerp(t, pos2Right); - Vec4f c= Vec4f(color, t*0.25f*alphaFactor); - - glColor4fv(c.ptr()); - - glVertex3fv(a.ptr()); - glVertex3fv(b.ptr()); - - } - - glEnd(); - //arrow end - glBegin(GL_TRIANGLES); - glVertex3fv((pos2Left + normal*(arrowEndSize-0.1f)).ptr()); - glVertex3fv((pos2Right - normal*(arrowEndSize-0.1f)).ptr()); - glVertex3fv((pos2 + dir*(arrowEndSize-0.1f)).ptr()); - glEnd(); -} - -void Renderer::renderProgressBar3D(int size, int x, int y, Font3D *font, int customWidth, - string prefixLabel,bool centeredText,int customHeight) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - // Makiong this smaller than 14 is a bad idea (since the font size is never smaller than that) - int progressbarHeight = (customHeight > 0 ? customHeight : 14); - int currentSize = size; - int maxSize = maxProgressBar; - string renderText = intToStr(static_cast(size)) + "%"; - if(customWidth > 0) { - if(size > 0) { - currentSize = (int)((double)customWidth * ((double)size / 100.0)); - } - maxSize = customWidth; - //if(maxSize <= 0) { - // maxSize = maxProgressBar; - //} + const Vec3f &color, float width) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + Config &config = Config::getInstance(); + if (config.getBool("RecordMode", "false") == true) { + return; + } + + const int tesselation = 3; + const float arrowEndSize = 0.4f; + const float maxlen = 25; + const float blendDelay = 5.f; + + Vec3f dir = Vec3f(pos2 - pos1); + float len = dir.length(); + + if (len > maxlen) { + return; + } + float alphaFactor = clamp((maxlen - len) / blendDelay, 0.f, 1.f); + + dir.normalize(); + Vec3f normal = dir.cross(Vec3f(0, 1, 0)); + + Vec3f pos2Left = pos2 + normal * (width - 0.05f) - dir * arrowEndSize * width; + Vec3f pos2Right = + pos2 - normal * (width - 0.05f) - dir * arrowEndSize * width; + Vec3f pos1Left = pos1 + normal * (width + 0.05f); + Vec3f pos1Right = pos1 - normal * (width + 0.05f); + + // arrow body + glBegin(GL_TRIANGLE_STRIP); + for (int i = 0; i <= tesselation; ++i) { + float t = static_cast(i) / tesselation; + Vec3f a = pos1Left.lerp(t, pos2Left); + Vec3f b = pos1Right.lerp(t, pos2Right); + Vec4f c = Vec4f(color, t * 0.25f * alphaFactor); + + glColor4fv(c.ptr()); + + glVertex3fv(a.ptr()); + glVertex3fv(b.ptr()); + } + + glEnd(); + // arrow end + glBegin(GL_TRIANGLES); + glVertex3fv((pos2Left + normal * (arrowEndSize - 0.1f)).ptr()); + glVertex3fv((pos2Right - normal * (arrowEndSize - 0.1f)).ptr()); + glVertex3fv((pos2 + dir * (arrowEndSize - 0.1f)).ptr()); + glEnd(); +} + +void Renderer::renderProgressBar3D(int size, int x, int y, Font3D *font, + int customWidth, string prefixLabel, + bool centeredText, int customHeight) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + // Makiong this smaller than 14 is a bad idea (since the font size is never + // smaller than that) + int progressbarHeight = (customHeight > 0 ? customHeight : 14); + int currentSize = size; + int maxSize = maxProgressBar; + string renderText = intToStr(static_cast(size)) + "%"; + if (customWidth > 0) { + if (size > 0) { + currentSize = (int)((double)customWidth * ((double)size / 100.0)); } - if(prefixLabel != "") { - renderText = prefixLabel + renderText; - } - - //bar - glBegin(GL_QUADS); - glColor4fv(progressBarFront2.ptr()); - glVertex2i(x, y); - glVertex2i(x, y + progressbarHeight); - glColor4fv(progressBarFront1.ptr()); - glVertex2i(x + currentSize, y + progressbarHeight); - glVertex2i(x + currentSize, y); - glEnd(); - - //transp bar - glEnable(GL_BLEND); - glBegin(GL_QUADS); - glColor4fv(progressBarBack2.ptr()); - glVertex2i(x + currentSize, y); - glVertex2i(x + currentSize, y + progressbarHeight); - glColor4fv(progressBarBack1.ptr()); - glVertex2i(x + maxSize, y + progressbarHeight); - glVertex2i(x + maxSize, y); - glEnd(); - glDisable(GL_BLEND); - - //text - //glColor3fv(defColor.ptr()); - //printf("Render progress bar3d renderText [%s] y = %d, centeredText = %d\n",renderText.c_str(),y, centeredText); - - renderTextBoundingBox3D(renderText, font, defColor, x, y, maxSize, - progressbarHeight, true, true, false,-1,-1); -} - -void Renderer::renderProgressBar(int size, int x, int y, Font2D *font, int customWidth, - string prefixLabel,bool centeredText) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - int currentSize = size; - int maxSize = maxProgressBar; - string renderText = intToStr(static_cast(size)) + "%"; - if(customWidth > 0) { - if(size > 0) { - currentSize = (int)((double)customWidth * ((double)size / 100.0)); - } - maxSize = customWidth; - //if(maxSize <= 0) { - // maxSize = maxProgressBar; - //} + maxSize = customWidth; + // if(maxSize <= 0) { + // maxSize = maxProgressBar; + // } + } + if (prefixLabel != "") { + renderText = prefixLabel + renderText; + } + + // bar + glBegin(GL_QUADS); + glColor4fv(progressBarFront2.ptr()); + glVertex2i(x, y); + glVertex2i(x, y + progressbarHeight); + glColor4fv(progressBarFront1.ptr()); + glVertex2i(x + currentSize, y + progressbarHeight); + glVertex2i(x + currentSize, y); + glEnd(); + + // transp bar + glEnable(GL_BLEND); + glBegin(GL_QUADS); + glColor4fv(progressBarBack2.ptr()); + glVertex2i(x + currentSize, y); + glVertex2i(x + currentSize, y + progressbarHeight); + glColor4fv(progressBarBack1.ptr()); + glVertex2i(x + maxSize, y + progressbarHeight); + glVertex2i(x + maxSize, y); + glEnd(); + glDisable(GL_BLEND); + + // text + // glColor3fv(defColor.ptr()); + // printf("Render progress bar3d renderText [%s] y = %d, centeredText = + // %d\n",renderText.c_str(),y, centeredText); + + renderTextBoundingBox3D(renderText, font, defColor, x, y, maxSize, + progressbarHeight, true, true, false, -1, -1); +} + +void Renderer::renderProgressBar(int size, int x, int y, Font2D *font, + int customWidth, string prefixLabel, + bool centeredText) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + int currentSize = size; + int maxSize = maxProgressBar; + string renderText = intToStr(static_cast(size)) + "%"; + if (customWidth > 0) { + if (size > 0) { + currentSize = (int)((double)customWidth * ((double)size / 100.0)); } - if(prefixLabel != "") { - renderText = prefixLabel + renderText; - } - - //bar - glBegin(GL_QUADS); - glColor4fv(progressBarFront2.ptr()); - glVertex2i(x, y); - glVertex2i(x, y+10); - glColor4fv(progressBarFront1.ptr()); - glVertex2i(x + currentSize, y+10); - glVertex2i(x + currentSize, y); - glEnd(); - - //transp bar - glEnable(GL_BLEND); - glBegin(GL_QUADS); - glColor4fv(progressBarBack2.ptr()); - glVertex2i(x + currentSize, y); - glVertex2i(x + currentSize, y+10); - glColor4fv(progressBarBack1.ptr()); - glVertex2i(x + maxSize, y+10); - glVertex2i(x + maxSize, y); - glEnd(); - glDisable(GL_BLEND); - - //text - glColor3fv(defColor.ptr()); - - //textRenderer->begin(font); - TextRendererSafeWrapper safeTextRender(textRenderer,font); - if(centeredText == true) { - textRenderer->render(renderText.c_str(), x + maxSize / 2, y, centeredText); - } - else { - textRenderer->render(renderText.c_str(), x, y, centeredText); - } - //textRenderer->end(); - safeTextRender.end(); -} - - -//void Renderer::renderTile(const Vec2i &pos) { + maxSize = customWidth; + // if(maxSize <= 0) { + // maxSize = maxProgressBar; + // } + } + if (prefixLabel != "") { + renderText = prefixLabel + renderText; + } + + // bar + glBegin(GL_QUADS); + glColor4fv(progressBarFront2.ptr()); + glVertex2i(x, y); + glVertex2i(x, y + 10); + glColor4fv(progressBarFront1.ptr()); + glVertex2i(x + currentSize, y + 10); + glVertex2i(x + currentSize, y); + glEnd(); + + // transp bar + glEnable(GL_BLEND); + glBegin(GL_QUADS); + glColor4fv(progressBarBack2.ptr()); + glVertex2i(x + currentSize, y); + glVertex2i(x + currentSize, y + 10); + glColor4fv(progressBarBack1.ptr()); + glVertex2i(x + maxSize, y + 10); + glVertex2i(x + maxSize, y); + glEnd(); + glDisable(GL_BLEND); + + // text + glColor3fv(defColor.ptr()); + + // textRenderer->begin(font); + TextRendererSafeWrapper safeTextRender(textRenderer, font); + if (centeredText == true) { + textRenderer->render(renderText.c_str(), x + maxSize / 2, y, centeredText); + } else { + textRenderer->render(renderText.c_str(), x, y, centeredText); + } + // textRenderer->end(); + safeTextRender.end(); +} + +// void Renderer::renderTile(const Vec2i &pos) { // if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { // return; // } @@ -8897,10 +9702,13 @@ void Renderer::renderProgressBar(int size, int x, int y, Font2D *font, int custo // // glDisable(GL_CULL_FACE); // -// float h1 = map->getCell(renderPos.x, renderPos.y)->getHeight(); -// float h2 = map->getCell(renderPos.x, renderPos.y+1)->getHeight(); -// float h3 = map->getCell(renderPos.x+1, renderPos.y)->getHeight(); -// float h4 = map->getCell(renderPos.x+1, renderPos.y+1)->getHeight(); +// float h1 = map->getCell(renderPos.x, +// renderPos.y)->getHeight(); float h2 = +// map->getCell(renderPos.x, +// renderPos.y+1)->getHeight(); float h3 = +// map->getCell(renderPos.x+1, +// renderPos.y)->getHeight(); float h4 = +// map->getCell(renderPos.x+1, renderPos.y+1)->getHeight(); // // glBegin(GL_TRIANGLE_STRIP); // glVertex3f( @@ -8927,478 +9735,530 @@ void Renderer::renderProgressBar(int size, int x, int y, Font2D *font, int custo // } // // glPopMatrix(); -//} - -void Renderer::renderQuad(int x, int y, int w, int h, const Texture2D *texture) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - if(texture == NULL) { - printf("\n**WARNING** detected a null texture to render in renderQuad!\n"); - return; - } - - if(w < 0) { - w = texture->getPixmapConst()->getW(); - } - if(h < 0) { - h = texture->getPixmapConst()->getH(); - } - - glBindTexture(GL_TEXTURE_2D, static_cast(texture)->getHandle()); - glBegin(GL_TRIANGLE_STRIP); - glTexCoord2i(0, 1); - glVertex2i(x, y+h); - glTexCoord2i(0, 0); - glVertex2i(x, y); - glTexCoord2i(1, 1); - glVertex2i(x+w, y+h); - glTexCoord2i(1, 0); - glVertex2i(x+w, y); - glEnd(); -} - -Renderer::Shadows Renderer::strToShadows(const string &s){ - if(s=="Projected"){ - return sProjected; - } - else if(s=="ShadowMapping"){ - return sShadowMapping; - } - return sDisabled; -} - -string Renderer::shadowsToStr(Shadows shadows){ - switch(shadows){ - case sDisabled: - return "Disabled2"; - case sProjected: - return "Projected"; - case sShadowMapping: - return "ShadowMapping"; - default: - assert(false); - return ""; - } -} - -Texture2D::Filter Renderer::strToTextureFilter(const string &s){ - if(s=="Bilinear"){ - return Texture2D::fBilinear; - } - else if(s=="Trilinear"){ - return Texture2D::fTrilinear; - } - - throw megaglest_runtime_error("Error converting from string to FilterType, found: "+s); +// } + +void Renderer::renderQuad(int x, int y, int w, int h, + const Texture2D *texture) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + if (texture == NULL) { + printf("\n**WARNING** detected a null texture to render in renderQuad!\n"); + return; + } + + if (w < 0) { + w = texture->getPixmapConst()->getW(); + } + if (h < 0) { + h = texture->getPixmapConst()->getH(); + } + + glBindTexture(GL_TEXTURE_2D, + static_cast(texture)->getHandle()); + glBegin(GL_TRIANGLE_STRIP); + glTexCoord2i(0, 1); + glVertex2i(x, y + h); + glTexCoord2i(0, 0); + glVertex2i(x, y); + glTexCoord2i(1, 1); + glVertex2i(x + w, y + h); + glTexCoord2i(1, 0); + glVertex2i(x + w, y); + glEnd(); +} + +Renderer::Shadows Renderer::strToShadows(const string &s) { + if (s == "Projected") { + return sProjected; + } else if (s == "ShadowMapping") { + return sShadowMapping; + } + return sDisabled; +} + +string Renderer::shadowsToStr(Shadows shadows) { + switch (shadows) { + case sDisabled: + return "Disabled2"; + case sProjected: + return "Projected"; + case sShadowMapping: + return "ShadowMapping"; + default: + assert(false); + return ""; + } +} + +Texture2D::Filter Renderer::strToTextureFilter(const string &s) { + if (s == "Bilinear") { + return Texture2D::fBilinear; + } else if (s == "Trilinear") { + return Texture2D::fTrilinear; + } + + throw megaglest_runtime_error( + "Error converting from string to FilterType, found: " + s); } void Renderer::setAllowRenderUnitTitles(bool value) { - allowRenderUnitTitles = value; + allowRenderUnitTitles = value; } // This method renders titles for units void Renderer::renderUnitTitles3D(Font3D *font, Vec3f color) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - //std::map unitRenderedList; - - if(visibleFrameUnitList.empty() == false) { - //printf("Render Unit titles ON\n"); - - for(int idx = 0; idx < (int)visibleFrameUnitList.size(); idx++) { - const Unit *unit = visibleFrameUnitList[idx]; - if(unit != NULL) { - if(unit->getVisible() == true) { - if(unit->getCurrentUnitTitle() != "") { - //get the screen coordinates - Vec3f screenPos = unit->getScreenPos(); - renderText3D(unit->getCurrentUnitTitle(), font, color, std::fabs(screenPos.x) + 5, std::fabs(screenPos.y) + 5, false); - //unitRenderedList[unit->getId()] = true; - } - else { - string str = unit->getFullName(unit->showTranslatedTechTree()) + " - " + intToStr(unit->getId()) + " [" + unit->getPosNotThreadSafe().getString() + "]"; - Vec3f screenPos = unit->getScreenPos(); - renderText3D(str, font, color, std::fabs(screenPos.x) + 5, std::fabs(screenPos.y) + 5, false); - } - } - } - } - visibleFrameUnitList.clear(); - } - - /* - if(renderUnitTitleList.empty() == false) { - for(int idx = 0; idx < renderUnitTitleList.size(); idx++) { - std::pair &unitInfo = renderUnitTitleList[idx]; - Unit *unit = unitInfo.first; - - const World *world= game->getWorld(); - Unit *validUnit = world->findUnitById(unit->getId()); - - if(validUnit != NULL && unitRenderedList.find(validUnit->getId()) == unitRenderedList.end()) { - string str = validUnit->getFullName() + " - " + intToStr(validUnit->getId()); - //get the screen coordinates - Vec3f &screenPos = unitInfo.second; - renderText(str, font, color, fabs(screenPos.x) + 5, fabs(screenPos.y) + 5, false); - //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] screenPos.x = %f, screenPos.y = %f, screenPos.z = %f\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,screenPos.x,screenPos.y,screenPos.z); - } - } - renderUnitTitleList.clear(); - } - */ + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + // std::map unitRenderedList; + + if (visibleFrameUnitList.empty() == false) { + // printf("Render Unit titles ON\n"); + + for (int idx = 0; idx < (int)visibleFrameUnitList.size(); idx++) { + const Unit *unit = visibleFrameUnitList[idx]; + if (unit != NULL) { + if (unit->getVisible() == true) { + if (unit->getCurrentUnitTitle() != "") { + // get the screen coordinates + Vec3f screenPos = unit->getScreenPos(); + renderText3D(unit->getCurrentUnitTitle(), font, color, + std::fabs(screenPos.x) + 5, std::fabs(screenPos.y) + 5, + false); + // unitRenderedList[unit->getId()] = true; + } else { + string str = unit->getFullName(unit->showTranslatedTechTree()) + + " - " + intToStr(unit->getId()) + " [" + + unit->getPosNotThreadSafe().getString() + "]"; + Vec3f screenPos = unit->getScreenPos(); + renderText3D(str, font, color, std::fabs(screenPos.x) + 5, + std::fabs(screenPos.y) + 5, false); + } + } + } + } + visibleFrameUnitList.clear(); + } + + /* + if(renderUnitTitleList.empty() == false) { + for(int idx = 0; idx < renderUnitTitleList.size(); idx++) { + std::pair &unitInfo = renderUnitTitleList[idx]; + Unit *unit = unitInfo.first; + + const World *world= game->getWorld(); + Unit *validUnit = world->findUnitById(unit->getId()); + + if(validUnit != NULL && + unitRenderedList.find(validUnit->getId()) == unitRenderedList.end()) { string + str = validUnit->getFullName() + " - " + intToStr(validUnit->getId()); + //get the screen coordinates + Vec3f &screenPos = unitInfo.second; + renderText(str, font, color, fabs(screenPos.x) + 5, + fabs(screenPos.y) + 5, false); + //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In + [%s::%s Line: %d] screenPos.x = %f, screenPos.y = %f, screenPos.z = + %f\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,screenPos.x,screenPos.y,screenPos.z); + } + } + renderUnitTitleList.clear(); + } + */ } // This method renders titles for units void Renderer::renderUnitTitles(Font2D *font, Vec3f color) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - //std::map unitRenderedList; - - if(visibleFrameUnitList.empty() == false) { - //printf("Render Unit titles ON\n"); - - for(int idx = 0; idx < (int)visibleFrameUnitList.size(); idx++) { - const Unit *unit = visibleFrameUnitList[idx]; - if(unit != NULL) { - if(unit->getCurrentUnitTitle() != "") { - //get the screen coordinates - Vec3f screenPos = unit->getScreenPos(); - renderText(unit->getCurrentUnitTitle(), font, color, std::fabs(screenPos.x) + 5, std::fabs(screenPos.y) + 5, false); - - //unitRenderedList[unit->getId()] = true; - } - else { - string str = unit->getFullName(unit->showTranslatedTechTree()) + " - " + intToStr(unit->getId()) + " [" + unit->getPosNotThreadSafe().getString() + "]"; - Vec3f screenPos = unit->getScreenPos(); - renderText(str, font, color, std::fabs(screenPos.x) + 5, std::fabs(screenPos.y) + 5, false); - } - } - } - visibleFrameUnitList.clear(); - } - - /* - if(renderUnitTitleList.empty() == false) { - for(int idx = 0; idx < renderUnitTitleList.size(); idx++) { - std::pair &unitInfo = renderUnitTitleList[idx]; - Unit *unit = unitInfo.first; - - const World *world= game->getWorld(); - Unit *validUnit = world->findUnitById(unit->getId()); - - if(validUnit != NULL && unitRenderedList.find(validUnit->getId()) == unitRenderedList.end()) { - string str = validUnit->getFullName() + " - " + intToStr(validUnit->getId()); - //get the screen coordinates - Vec3f &screenPos = unitInfo.second; - renderText(str, font, color, fabs(screenPos.x) + 5, fabs(screenPos.y) + 5, false); - //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] screenPos.x = %f, screenPos.y = %f, screenPos.z = %f\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,screenPos.x,screenPos.y,screenPos.z); - } - } - renderUnitTitleList.clear(); - } - */ + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + // std::map unitRenderedList; + + if (visibleFrameUnitList.empty() == false) { + // printf("Render Unit titles ON\n"); + + for (int idx = 0; idx < (int)visibleFrameUnitList.size(); idx++) { + const Unit *unit = visibleFrameUnitList[idx]; + if (unit != NULL) { + if (unit->getCurrentUnitTitle() != "") { + // get the screen coordinates + Vec3f screenPos = unit->getScreenPos(); + renderText(unit->getCurrentUnitTitle(), font, color, + std::fabs(screenPos.x) + 5, std::fabs(screenPos.y) + 5, + false); + + // unitRenderedList[unit->getId()] = true; + } else { + string str = unit->getFullName(unit->showTranslatedTechTree()) + + " - " + intToStr(unit->getId()) + " [" + + unit->getPosNotThreadSafe().getString() + "]"; + Vec3f screenPos = unit->getScreenPos(); + renderText(str, font, color, std::fabs(screenPos.x) + 5, + std::fabs(screenPos.y) + 5, false); + } + } + } + visibleFrameUnitList.clear(); + } + + /* + if(renderUnitTitleList.empty() == false) { + for(int idx = 0; idx < renderUnitTitleList.size(); idx++) { + std::pair &unitInfo = renderUnitTitleList[idx]; + Unit *unit = unitInfo.first; + + const World *world= game->getWorld(); + Unit *validUnit = world->findUnitById(unit->getId()); + + if(validUnit != NULL && + unitRenderedList.find(validUnit->getId()) == unitRenderedList.end()) { string + str = validUnit->getFullName() + " - " + intToStr(validUnit->getId()); + //get the screen coordinates + Vec3f &screenPos = unitInfo.second; + renderText(str, font, color, fabs(screenPos.x) + 5, + fabs(screenPos.y) + 5, false); + //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In + [%s::%s Line: %d] screenPos.x = %f, screenPos.y = %f, screenPos.z = + %f\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,screenPos.x,screenPos.y,screenPos.z); + } + } + renderUnitTitleList.clear(); + } + */ } void Renderer::removeObjectFromQuadCache(const Object *o) { - VisibleQuadContainerCache &qCache = getQuadCache(); - for(int visibleIndex = 0; - visibleIndex < (int)qCache.visibleObjectList.size(); ++visibleIndex) { - Object *currentObj = qCache.visibleObjectList[visibleIndex]; - if(currentObj == o) { - qCache.visibleObjectList.erase(qCache.visibleObjectList.begin() + visibleIndex); - break; - } - } + VisibleQuadContainerCache &qCache = getQuadCache(); + for (int visibleIndex = 0; + visibleIndex < (int)qCache.visibleObjectList.size(); ++visibleIndex) { + Object *currentObj = qCache.visibleObjectList[visibleIndex]; + if (currentObj == o) { + qCache.visibleObjectList.erase(qCache.visibleObjectList.begin() + + visibleIndex); + break; + } + } } void Renderer::removeUnitFromQuadCache(const Unit *unit) { - VisibleQuadContainerCache &qCache = getQuadCache(); - for(int visibleIndex = 0; - visibleIndex < (int)qCache.visibleQuadUnitList.size(); ++visibleIndex) { - Unit *currentUnit = qCache.visibleQuadUnitList[visibleIndex]; - if(currentUnit == unit) { - qCache.visibleQuadUnitList.erase(qCache.visibleQuadUnitList.begin() + visibleIndex); - break; - } - } - for(int visibleIndex = 0; - visibleIndex < (int)qCache.visibleUnitList.size(); ++visibleIndex) { - Unit *currentUnit = qCache.visibleUnitList[visibleIndex]; - if(currentUnit == unit) { - qCache.visibleUnitList.erase(qCache.visibleUnitList.begin() + visibleIndex); - break; - } - } -} - -VisibleQuadContainerCache & Renderer::getQuadCache( bool updateOnDirtyFrame, - bool forceNew) { - //forceNew = true; - if(game != NULL && game->getWorld() != NULL) { - const World *world= game->getWorld(); - - if(forceNew == true || - (updateOnDirtyFrame == true && - (world->getFrameCount() != quadCache.cacheFrame || - visibleQuad != quadCache.lastVisibleQuad))) { - - // Dump cached info - //if(forceNew == true || visibleQuad != quadCache.lastVisibleQuad) { - //quadCache.clearCacheData(); - //} - //else { - quadCache.clearVolatileCacheData(); - worldToScreenPosCache.clear(); - //} - - // Unit calculations - for(int i = 0; i < world->getFactionCount(); ++i) { - const Faction *faction = world->getFaction(i); - for(int j = 0; j < faction->getUnitCount(); ++j) { - Unit *unit= faction->getUnit(j); - - bool unitCheckedForRender = false; - if(VisibleQuadContainerCache::enableFrustumCalcs == true) { - //bool insideQuad = PointInFrustum(quadCache.frustumData, unit->getCurrVector().x, unit->getCurrVector().y, unit->getCurrVector().z ); - bool insideQuad = CubeInFrustum(quadCache.frustumData, unit->getCurrMidHeightVector().x, unit->getCurrMidHeightVector().y, unit->getCurrMidHeightVector().z, unit->getType()->getRenderSize()); - bool renderInMap = world->toRenderUnit(unit); - if(insideQuad == false || renderInMap == false) { - unit->setVisible(false); - if(renderInMap == true) { - quadCache.visibleUnitList.push_back(unit); - } - unitCheckedForRender = true; // no more need to check any further; - // Currently don't need this list - //quadCache.inVisibleUnitList.push_back(unit); - } - } - if(unitCheckedForRender == false) { - bool insideQuad = visibleQuad.isInside(unit->getPos()); - bool renderInMap = world->toRenderUnit(unit); - if(insideQuad == true && renderInMap == true) { - quadCache.visibleQuadUnitList.push_back(unit); - } - else { - unit->setVisible(false); - // Currently don't need this list - //quadCache.inVisibleUnitList.push_back(unit); - } - - if(renderInMap == true) { - quadCache.visibleUnitList.push_back(unit); - } - } - - bool unitBuildPending = unit->isBuildCommandPending(); - if(unitBuildPending == true) { - const UnitBuildInfo &pendingUnit = unit->getBuildCommandPendingInfo(); - const Vec2i &pos = pendingUnit.pos; - const Map *map= world->getMap(); - - bool unitBuildCheckedForRender = false; - - //printf("#1 Unit is about to build another unit\n"); - - if(VisibleQuadContainerCache::enableFrustumCalcs == true) { - Vec3f pos3f= Vec3f(pos.x, map->getCell(pos)->getHeight(), pos.y); - //bool insideQuad = PointInFrustum(quadCache.frustumData, unit->getCurrVector().x, unit->getCurrVector().y, unit->getCurrVector().z ); - bool insideQuad = CubeInFrustum(quadCache.frustumData, pos3f.x, pos3f.y, pos3f.z, pendingUnit.buildUnit->getRenderSize()); - bool renderInMap = world->toRenderUnit(pendingUnit); - if(insideQuad == false || renderInMap == false) { - if(renderInMap == true) { - quadCache.visibleQuadUnitBuildList.push_back(pendingUnit); - } - unitBuildCheckedForRender = true; // no more need to check any further; - // Currently don't need this list - //quadCache.inVisibleUnitList.push_back(unit); - } - - //printf("#2 Unit build added? insideQuad = %d, renderInMap = %d\n",insideQuad,renderInMap); - } - - if(unitBuildCheckedForRender == false) { - bool insideQuad = visibleQuad.isInside(pos); - bool renderInMap = world->toRenderUnit(pendingUnit); - if(insideQuad == true && renderInMap == true) { - quadCache.visibleQuadUnitBuildList.push_back(pendingUnit); - } - else { - //unit->setVisible(false); - // Currently don't need this list - //quadCache.inVisibleUnitList.push_back(unit); - } - - //printf("#3 Unit build added? insideQuad = %d, renderInMap = %d\n",insideQuad,renderInMap); - } - - //printf("#4 quadCache.visibleQuadUnitBuildList.size() = %d\n",quadCache.visibleQuadUnitBuildList.size()); - } - } - } - - if(forceNew == true || visibleQuad != quadCache.lastVisibleQuad) { - // Object calculations - const Map *map= world->getMap(); - // clear visibility of old objects - for(int visibleIndex = 0; - visibleIndex < (int)quadCache.visibleObjectList.size(); ++visibleIndex){ - quadCache.visibleObjectList[visibleIndex]->setVisible(false); - } - quadCache.clearNonVolatileCacheData(); - - //int loops1=0; - PosQuadIterator pqi(map,visibleQuad, Map::cellScale); - while(pqi.next()) { - const Vec2i &pos= pqi.getPos(); - if(map->isInside(pos)) { - //loops1++; - const Vec2i &mapPos = Map::toSurfCoords(pos); - - //quadCache.visibleCellList.push_back(mapPos); - - SurfaceCell *sc = map->getSurfaceCell(mapPos); - Object *o = sc->getObject(); - - if(VisibleQuadContainerCache::enableFrustumCalcs == true) { - if(o != NULL) { - //bool insideQuad = PointInFrustum(quadCache.frustumData, o->getPos().x, o->getPos().y, o->getPos().z ); - bool insideQuad = CubeInFrustum(quadCache.frustumData, o->getPos().x, o->getPos().y, o->getPos().z, 1); - if(insideQuad == false) { - o->setVisible(false); - continue; - } - } - } - - bool cellExplored = world->showWorldForPlayer(world->getThisFactionIndex()); - if(cellExplored == false) { - cellExplored = sc->isExplored(world->getThisTeamIndex()); - } - - bool isExplored = (cellExplored == true && o != NULL); - //bool isVisible = (sc->isVisible(world->getThisTeamIndex()) && o != NULL); - bool isVisible = true; - - if(isExplored == true && isVisible == true) { - quadCache.visibleObjectList.push_back(o); - o->setVisible(true); - } - } - } - - //printf("Frame # = %d loops1 = %d\n",world->getFrameCount(),loops1); - - //int loops2=0; - - std::map markedCells = game->getMapMarkedCellList(); - - const Rect2i mapBounds(0, 0, map->getSurfaceW()-1, map->getSurfaceH()-1); - Quad2i scaledQuad = visibleQuad / Map::cellScale; - PosQuadIterator pqis(map,scaledQuad); - while(pqis.next()) { - const Vec2i &pos= pqis.getPos(); - if(mapBounds.isInside(pos)) { - //loops2++; - if(VisibleQuadContainerCache::enableFrustumCalcs == false) { - quadCache.visibleScaledCellList.push_back(pos); - - if(markedCells.empty() == false) { - if(markedCells.find(pos) != markedCells.end()) { - //printf("#1 ******** VISIBLE SCALED CELL FOUND in marked list pos [%s] markedCells.size() = " MG_SIZE_T_SPECIFIER "\n",pos.getString().c_str(),markedCells.size()); - //if(markedCells.empty() == false) { - //SurfaceCell *sc = map->getSurfaceCell(pos); - //quadCache.visibleScaledCellToScreenPosList[pos]=computeScreenPosition(sc->getVertex()); - updateMarkedCellScreenPosQuadCache(pos); - } - else { - //printf("#1 VISIBLE SCALED CELL NOT FOUND in marked list pos [%s] markedCells.size() = " MG_SIZE_T_SPECIFIER "\n",pos.getString().c_str(),markedCells.size()); - } - } - } - else { - //bool insideQuad = false; - - //if( !insideQuad) { - SurfaceCell *sc = map->getSurfaceCell(pos.x, pos.y); - bool insideQuad = CubeInFrustum(quadCache.frustumData, sc->getVertex().x, sc->getVertex().y, sc->getVertex().z, 0); - //} - if( !insideQuad) { - SurfaceCell *sc = map->getSurfaceCell(pos.x+1, pos.y); - insideQuad = CubeInFrustum(quadCache.frustumData, sc->getVertex().x, sc->getVertex().y, sc->getVertex().z, 0); - } - if( !insideQuad) { - SurfaceCell *sc = map->getSurfaceCell(pos.x, pos.y+1); - insideQuad = CubeInFrustum(quadCache.frustumData, sc->getVertex().x, sc->getVertex().y, sc->getVertex().z, 0); - } - if( !insideQuad) { - SurfaceCell *sc = map->getSurfaceCell(pos.x+1, pos.y+1); - insideQuad = CubeInFrustum(quadCache.frustumData, sc->getVertex().x, sc->getVertex().y, sc->getVertex().z, 0); - } - - if(insideQuad == true) { - quadCache.visibleScaledCellList.push_back(pos); - - if(markedCells.empty() == false) { - if(markedCells.find(pos) != markedCells.end()) { - //printf("#2 ******** VISIBLE SCALED CELL FOUND in marked list pos [%s] markedCells.size() = " MG_SIZE_T_SPECIFIER "\n",pos.getString().c_str(),markedCells.size()); - //if(markedCells.empty() == false) { - //quadCache.visibleScaledCellToScreenPosList[pos]=computeScreenPosition(sc->getVertex()); - updateMarkedCellScreenPosQuadCache(pos); - } - else { - //printf("#2 VISIBLE SCALED CELL NOT FOUND in marked list pos [%s] markedCells.size() = " MG_SIZE_T_SPECIFIER "\n",pos.getString().c_str(),markedCells.size()); - } - } - } - } - } - } - //printf("Frame # = %d loops2 = %d\n",world->getFrameCount(),loops2); - } - quadCache.cacheFrame = world->getFrameCount(); - quadCache.lastVisibleQuad = visibleQuad; - } - } - - return quadCache; + VisibleQuadContainerCache &qCache = getQuadCache(); + for (int visibleIndex = 0; + visibleIndex < (int)qCache.visibleQuadUnitList.size(); ++visibleIndex) { + Unit *currentUnit = qCache.visibleQuadUnitList[visibleIndex]; + if (currentUnit == unit) { + qCache.visibleQuadUnitList.erase(qCache.visibleQuadUnitList.begin() + + visibleIndex); + break; + } + } + for (int visibleIndex = 0; visibleIndex < (int)qCache.visibleUnitList.size(); + ++visibleIndex) { + Unit *currentUnit = qCache.visibleUnitList[visibleIndex]; + if (currentUnit == unit) { + qCache.visibleUnitList.erase(qCache.visibleUnitList.begin() + + visibleIndex); + break; + } + } +} + +VisibleQuadContainerCache &Renderer::getQuadCache(bool updateOnDirtyFrame, + bool forceNew) { + // forceNew = true; + if (game != NULL && game->getWorld() != NULL) { + const World *world = game->getWorld(); + + if (forceNew == true || (updateOnDirtyFrame == true && + (world->getFrameCount() != quadCache.cacheFrame || + visibleQuad != quadCache.lastVisibleQuad))) { + + // Dump cached info + // if(forceNew == true || visibleQuad != quadCache.lastVisibleQuad) { + // quadCache.clearCacheData(); + //} + // else { + quadCache.clearVolatileCacheData(); + worldToScreenPosCache.clear(); + //} + + // Unit calculations + for (int i = 0; i < world->getFactionCount(); ++i) { + const Faction *faction = world->getFaction(i); + for (int j = 0; j < faction->getUnitCount(); ++j) { + Unit *unit = faction->getUnit(j); + + bool unitCheckedForRender = false; + if (VisibleQuadContainerCache::enableFrustumCalcs == true) { + // bool insideQuad = PointInFrustum(quadCache.frustumData, + // unit->getCurrVector().x, unit->getCurrVector().y, + // unit->getCurrVector().z ); + bool insideQuad = CubeInFrustum(quadCache.frustumData, + unit->getCurrMidHeightVector().x, + unit->getCurrMidHeightVector().y, + unit->getCurrMidHeightVector().z, + unit->getType()->getRenderSize()); + bool renderInMap = world->toRenderUnit(unit); + if (insideQuad == false || renderInMap == false) { + unit->setVisible(false); + if (renderInMap == true) { + quadCache.visibleUnitList.push_back(unit); + } + unitCheckedForRender = true; // no more need to check any further; + // Currently don't need this list + // quadCache.inVisibleUnitList.push_back(unit); + } + } + if (unitCheckedForRender == false) { + bool insideQuad = visibleQuad.isInside(unit->getPos()); + bool renderInMap = world->toRenderUnit(unit); + if (insideQuad == true && renderInMap == true) { + quadCache.visibleQuadUnitList.push_back(unit); + } else { + unit->setVisible(false); + // Currently don't need this list + // quadCache.inVisibleUnitList.push_back(unit); + } + + if (renderInMap == true) { + quadCache.visibleUnitList.push_back(unit); + } + } + + bool unitBuildPending = unit->isBuildCommandPending(); + if (unitBuildPending == true) { + const UnitBuildInfo &pendingUnit = + unit->getBuildCommandPendingInfo(); + const Vec2i &pos = pendingUnit.pos; + const Map *map = world->getMap(); + + bool unitBuildCheckedForRender = false; + + // printf("#1 Unit is about to build another unit\n"); + + if (VisibleQuadContainerCache::enableFrustumCalcs == true) { + Vec3f pos3f = Vec3f(pos.x, map->getCell(pos)->getHeight(), pos.y); + // bool insideQuad = PointInFrustum(quadCache.frustumData, + // unit->getCurrVector().x, unit->getCurrVector().y, + // unit->getCurrVector().z ); + bool insideQuad = CubeInFrustum( + quadCache.frustumData, pos3f.x, pos3f.y, pos3f.z, + pendingUnit.buildUnit->getRenderSize()); + bool renderInMap = world->toRenderUnit(pendingUnit); + if (insideQuad == false || renderInMap == false) { + if (renderInMap == true) { + quadCache.visibleQuadUnitBuildList.push_back(pendingUnit); + } + unitBuildCheckedForRender = + true; // no more need to check any further; + // Currently don't need this list + // quadCache.inVisibleUnitList.push_back(unit); + } + + // printf("#2 Unit build added? insideQuad = %d, renderInMap = + // %d\n",insideQuad,renderInMap); + } + + if (unitBuildCheckedForRender == false) { + bool insideQuad = visibleQuad.isInside(pos); + bool renderInMap = world->toRenderUnit(pendingUnit); + if (insideQuad == true && renderInMap == true) { + quadCache.visibleQuadUnitBuildList.push_back(pendingUnit); + } else { + // unit->setVisible(false); + // Currently don't need this list + // quadCache.inVisibleUnitList.push_back(unit); + } + + // printf("#3 Unit build added? insideQuad = %d, renderInMap = + // %d\n",insideQuad,renderInMap); + } + + // printf("#4 quadCache.visibleQuadUnitBuildList.size() = + // %d\n",quadCache.visibleQuadUnitBuildList.size()); + } + } + } + + if (forceNew == true || visibleQuad != quadCache.lastVisibleQuad) { + // Object calculations + const Map *map = world->getMap(); + // clear visibility of old objects + for (int visibleIndex = 0; + visibleIndex < (int)quadCache.visibleObjectList.size(); + ++visibleIndex) { + quadCache.visibleObjectList[visibleIndex]->setVisible(false); + } + quadCache.clearNonVolatileCacheData(); + + // int loops1=0; + PosQuadIterator pqi(map, visibleQuad, Map::cellScale); + while (pqi.next()) { + const Vec2i &pos = pqi.getPos(); + if (map->isInside(pos)) { + // loops1++; + const Vec2i &mapPos = Map::toSurfCoords(pos); + + // quadCache.visibleCellList.push_back(mapPos); + + SurfaceCell *sc = map->getSurfaceCell(mapPos); + Object *o = sc->getObject(); + + if (VisibleQuadContainerCache::enableFrustumCalcs == true) { + if (o != NULL) { + // bool insideQuad = PointInFrustum(quadCache.frustumData, + // o->getPos().x, o->getPos().y, o->getPos().z ); + bool insideQuad = + CubeInFrustum(quadCache.frustumData, o->getPos().x, + o->getPos().y, o->getPos().z, 1); + if (insideQuad == false) { + o->setVisible(false); + continue; + } + } + } + + bool cellExplored = + world->showWorldForPlayer(world->getThisFactionIndex()); + if (cellExplored == false) { + cellExplored = sc->isExplored(world->getThisTeamIndex()); + } + + bool isExplored = (cellExplored == true && o != NULL); + // bool isVisible = (sc->isVisible(world->getThisTeamIndex()) && o + // != NULL); + bool isVisible = true; + + if (isExplored == true && isVisible == true) { + quadCache.visibleObjectList.push_back(o); + o->setVisible(true); + } + } + } + + // printf("Frame # = %d loops1 = %d\n",world->getFrameCount(),loops1); + + // int loops2=0; + + std::map markedCells = game->getMapMarkedCellList(); + + const Rect2i mapBounds(0, 0, map->getSurfaceW() - 1, + map->getSurfaceH() - 1); + Quad2i scaledQuad = visibleQuad / Map::cellScale; + PosQuadIterator pqis(map, scaledQuad); + while (pqis.next()) { + const Vec2i &pos = pqis.getPos(); + if (mapBounds.isInside(pos)) { + // loops2++; + if (VisibleQuadContainerCache::enableFrustumCalcs == false) { + quadCache.visibleScaledCellList.push_back(pos); + + if (markedCells.empty() == false) { + if (markedCells.find(pos) != markedCells.end()) { + // printf("#1 ******** VISIBLE SCALED CELL FOUND in marked + // list pos [%s] markedCells.size() = " MG_SIZE_T_SPECIFIER + // "\n",pos.getString().c_str(),markedCells.size()); + // if(markedCells.empty() == false) { + // SurfaceCell *sc = map->getSurfaceCell(pos); + // quadCache.visibleScaledCellToScreenPosList[pos]=computeScreenPosition(sc->getVertex()); + updateMarkedCellScreenPosQuadCache(pos); + } else { + // printf("#1 VISIBLE SCALED CELL NOT FOUND in marked list pos + // [%s] markedCells.size() = " MG_SIZE_T_SPECIFIER + // "\n",pos.getString().c_str(),markedCells.size()); + } + } + } else { + // bool insideQuad = false; + + // if( !insideQuad) { + SurfaceCell *sc = map->getSurfaceCell(pos.x, pos.y); + bool insideQuad = + CubeInFrustum(quadCache.frustumData, sc->getVertex().x, + sc->getVertex().y, sc->getVertex().z, 0); + //} + if (!insideQuad) { + SurfaceCell *sc = map->getSurfaceCell(pos.x + 1, pos.y); + insideQuad = + CubeInFrustum(quadCache.frustumData, sc->getVertex().x, + sc->getVertex().y, sc->getVertex().z, 0); + } + if (!insideQuad) { + SurfaceCell *sc = map->getSurfaceCell(pos.x, pos.y + 1); + insideQuad = + CubeInFrustum(quadCache.frustumData, sc->getVertex().x, + sc->getVertex().y, sc->getVertex().z, 0); + } + if (!insideQuad) { + SurfaceCell *sc = map->getSurfaceCell(pos.x + 1, pos.y + 1); + insideQuad = + CubeInFrustum(quadCache.frustumData, sc->getVertex().x, + sc->getVertex().y, sc->getVertex().z, 0); + } + + if (insideQuad == true) { + quadCache.visibleScaledCellList.push_back(pos); + + if (markedCells.empty() == false) { + if (markedCells.find(pos) != markedCells.end()) { + // printf("#2 ******** VISIBLE SCALED CELL FOUND in marked + // list pos [%s] markedCells.size() = " MG_SIZE_T_SPECIFIER + // "\n",pos.getString().c_str(),markedCells.size()); + // if(markedCells.empty() == false) { + // quadCache.visibleScaledCellToScreenPosList[pos]=computeScreenPosition(sc->getVertex()); + updateMarkedCellScreenPosQuadCache(pos); + } else { + // printf("#2 VISIBLE SCALED CELL NOT FOUND in marked list + // pos [%s] markedCells.size() = " MG_SIZE_T_SPECIFIER + // "\n",pos.getString().c_str(),markedCells.size()); + } + } + } + } + } + } + // printf("Frame # = %d loops2 = %d\n",world->getFrameCount(),loops2); + } + quadCache.cacheFrame = world->getFrameCount(); + quadCache.lastVisibleQuad = visibleQuad; + } + } + + return quadCache; } void Renderer::updateMarkedCellScreenPosQuadCache(Vec2i pos) { - const World *world= game->getWorld(); - const Map *map= world->getMap(); + const World *world = game->getWorld(); + const Map *map = world->getMap(); - SurfaceCell *sc = map->getSurfaceCell(pos); - quadCache.visibleScaledCellToScreenPosList[pos]=computeScreenPosition(sc->getVertex()); + SurfaceCell *sc = map->getSurfaceCell(pos); + quadCache.visibleScaledCellToScreenPosList[pos] = + computeScreenPosition(sc->getVertex()); } void Renderer::forceQuadCacheUpdate() { - quadCache.cacheFrame = -1; + quadCache.cacheFrame = -1; - Vec2i clearPos(-1,-1); - quadCache.lastVisibleQuad.p[0] = clearPos; - quadCache.lastVisibleQuad.p[1] = clearPos; - quadCache.lastVisibleQuad.p[2] = clearPos; - quadCache.lastVisibleQuad.p[3] = clearPos; + Vec2i clearPos(-1, -1); + quadCache.lastVisibleQuad.p[0] = clearPos; + quadCache.lastVisibleQuad.p[1] = clearPos; + quadCache.lastVisibleQuad.p[2] = clearPos; + quadCache.lastVisibleQuad.p[3] = clearPos; } -std::pair Renderer::posInCellQuadCache(Vec2i pos) { - std::pair result = make_pair(false,Vec3f()); - if(std::find( - quadCache.visibleScaledCellList.begin(), - quadCache.visibleScaledCellList.end(), - pos) != quadCache.visibleScaledCellList.end()) { - result.first = true; - result.second = quadCache.visibleScaledCellToScreenPosList[pos]; - } - return result; +std::pair Renderer::posInCellQuadCache(Vec2i pos) { + std::pair result = make_pair(false, Vec3f()); + if (std::find(quadCache.visibleScaledCellList.begin(), + quadCache.visibleScaledCellList.end(), + pos) != quadCache.visibleScaledCellList.end()) { + result.first = true; + result.second = quadCache.visibleScaledCellToScreenPosList[pos]; + } + return result; } -//Vec3f Renderer::getMarkedCellScreenPosQuadCache(Vec2i pos) { +// Vec3f Renderer::getMarkedCellScreenPosQuadCache(Vec2i pos) { // Vec3f result(-1,-1,-1); // if(std::find( // quadCache.visibleScaledCellList.begin(), @@ -9407,710 +10267,768 @@ std::pair Renderer::posInCellQuadCache(Vec2i pos) { // result = quadCache.visibleScaledCellToScreenPosList[pos]; // } // return result; -//} +// } void Renderer::beginRenderToTexture(Texture2D **renderToTexture) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - static bool supportFBOs = Texture2DGl().supports_FBO_RBO(); - - if(supportFBOs == true && renderToTexture != NULL) { - Config &config= Config::getInstance(); - Texture2D::Filter textureFilter = strToTextureFilter(config.getString("Filter")); - int maxAnisotropy = config.getInt("FilterMaxAnisotropy"); - - const Metrics &metrics = Metrics::getInstance(); + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + static bool supportFBOs = Texture2DGl().supports_FBO_RBO(); + + if (supportFBOs == true && renderToTexture != NULL) { + Config &config = Config::getInstance(); + Texture2D::Filter textureFilter = + strToTextureFilter(config.getString("Filter")); + int maxAnisotropy = config.getInt("FilterMaxAnisotropy"); + + const Metrics &metrics = Metrics::getInstance(); + + *renderToTexture = + GraphicsInterface::getInstance().getFactory()->newTexture2D(); + Texture2DGl *texture = static_cast(*renderToTexture); + texture->setMipmap(false); + Pixmap2D *pixmapScreenShot = texture->getPixmap(); + pixmapScreenShot->init(metrics.getScreenW(), metrics.getScreenH(), 4); + texture->setForceCompressionDisabled(true); + texture->init(textureFilter, maxAnisotropy); + texture->setup_FBO_RBO(); - *renderToTexture = GraphicsInterface::getInstance().getFactory()->newTexture2D(); - Texture2DGl *texture = static_cast(*renderToTexture); - texture->setMipmap(false); - Pixmap2D *pixmapScreenShot = texture->getPixmap(); - pixmapScreenShot->init(metrics.getScreenW(), metrics.getScreenH(), 4); - texture->setForceCompressionDisabled(true); - texture->init(textureFilter,maxAnisotropy); - texture->setup_FBO_RBO(); - - assertGl(); + assertGl(); - if(texture->checkFrameBufferStatus() == false) { - //printf("******************** WARNING CANNOT Attach to FBO!\n"); - texture->end(); - delete texture; - *renderToTexture=NULL; - } - } + if (texture->checkFrameBufferStatus() == false) { + // printf("******************** WARNING CANNOT Attach to FBO!\n"); + texture->end(); + delete texture; + *renderToTexture = NULL; + } + } } void Renderer::endRenderToTexture(Texture2D **renderToTexture) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - static bool supportFBOs = Texture2DGl().supports_FBO_RBO(); - - if(supportFBOs == true && renderToTexture != NULL && *renderToTexture != NULL) { - Texture2DGl *texture = static_cast(*renderToTexture); - if(texture != NULL) { - texture->dettachFrameBufferFromTexture(); - } - - assertGl(); - } -} - -void Renderer::renderMapPreview( const MapPreview *map, bool renderAll, - int screenPosX, int screenPosY, - Texture2D **renderToTexture) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - static bool supportFBOs = Texture2DGl().supports_FBO_RBO(); - if(Config::getInstance().getBool("LegacyMapPreviewRendering","false") == true) { - supportFBOs = false; - } - - //static bool supportFBOs = false; - const Metrics &metrics= Metrics::getInstance(); - - float alt = 0; - float showWater = 0; - int renderMapHeight = 64; - int renderMapWidth = 64; - float cellSize = 2; - float playerCrossSize = 2; - float clientW = renderMapWidth * cellSize; - float clientH = renderMapHeight * cellSize;; - float minDimension = std::min(metrics.getVirtualW(), metrics.getVirtualH()); - - // stretch small maps to 128x128 - if(map->getW() < map->getH()) { - cellSize = cellSize * renderMapHeight / map->getH(); - } - else { - cellSize = cellSize * renderMapWidth / map->getW(); - } - - assertGl(); - - if(supportFBOs == true && renderToTexture != NULL) { - Config &config= Config::getInstance(); - Texture2D::Filter textureFilter = strToTextureFilter(config.getString("Filter")); - int maxAnisotropy = config.getInt("FilterMaxAnisotropy"); - - *renderToTexture = GraphicsInterface::getInstance().getFactory()->newTexture2D(); - Texture2DGl *texture = static_cast(*renderToTexture); - texture->setMipmap(false); - Pixmap2D *pixmapScreenShot = texture->getPixmap(); - pixmapScreenShot->init(minDimension, minDimension, 4); - texture->setForceCompressionDisabled(true); - texture->init(textureFilter,maxAnisotropy); - texture->setup_FBO_RBO(); - - assertGl(); - - if(texture->checkFrameBufferStatus() == false) { - //printf("******************** WARNING CANNOT Attach to FBO!\n"); - texture->end(); - delete texture; - *renderToTexture=NULL; - } - } - - if(supportFBOs == true && renderToTexture != NULL && *renderToTexture != NULL) { - cellSize =1; - clientW = minDimension; - clientH = minDimension; - int mapMaxDimensionSize = std::max(map->getW(),map->getH()); - switch(mapMaxDimensionSize) { - case 8: - cellSize = 96; - break; - case 16: - cellSize = 48; - break; - case 32: - cellSize = 24; - break; - case 64: - cellSize = 12; - break; - case 128: - cellSize = 6; - break; - case 256: - cellSize = 3; - break; - case 512: - cellSize = 2; - break; - } - } - - glFrontFace(GL_CW); - glEnable(GL_CULL_FACE); - - glMatrixMode(GL_PROJECTION); - glPushMatrix(); - glLoadIdentity(); - - assertGl(); - - GLint viewport[4]; // Where The original Viewport Values Will Be Stored - - if(supportFBOs == true && renderToTexture != NULL && *renderToTexture != NULL) { - glGetIntegerv(GL_VIEWPORT, viewport); - glOrtho(0, clientW, 0, clientH, 0, 1); - glViewport(0, 0, clientW, clientH); - } - else { - glOrtho(0, metrics.getVirtualW(), 0, metrics.getVirtualH(), 0, 1); - } - - glMatrixMode(GL_MODELVIEW); + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } - glPushMatrix(); - glLoadIdentity(); + static bool supportFBOs = Texture2DGl().supports_FBO_RBO(); - if(supportFBOs == false || renderToTexture == NULL || *renderToTexture == NULL) { - glTranslatef(static_cast(screenPosX),static_cast(screenPosY)-clientH,0.0f); - } - - assertGl(); + if (supportFBOs == true && renderToTexture != NULL && + *renderToTexture != NULL) { + Texture2DGl *texture = static_cast(*renderToTexture); + if (texture != NULL) { + texture->dettachFrameBufferFromTexture(); + } - glPushAttrib(GL_CURRENT_BIT); - glLineWidth(1); - glColor3f(0, 0, 0); - - for (int j = 0; j < map->getH(); j++) { - for (int i = 0; i < map->getW(); i++) { - //surface - alt = map->getHeight(i, j) / 20.f; - showWater = map->getWaterLevel()/ 20.f - alt; - showWater = (showWater > 0)? showWater:0; - Vec3f surfColor; - switch (map->getSurface(i, j)) { - case st_Grass: - surfColor = Vec3f(0.0, 0.8f * alt, 0.f + showWater); - break; - case st_Secondary_Grass: - surfColor = Vec3f(0.4f * alt, 0.6f * alt, 0.f + showWater); - break; - case st_Road: - surfColor = Vec3f(0.6f * alt, 0.3f * alt, 0.f + showWater); - break; - case st_Stone: - surfColor = Vec3f(0.7f * alt, 0.7f * alt, 0.7f * alt + showWater); - break; - case st_Ground: - surfColor = Vec3f(0.7f * alt, 0.5f * alt, 0.3f * alt + showWater); - break; - } - - glColor3fv(surfColor.ptr()); - - glBegin(GL_TRIANGLE_STRIP); - glVertex2f(i * cellSize, clientH - j * cellSize - cellSize); - glVertex2f(i * cellSize, clientH - j * cellSize); - glVertex2f(i * cellSize + cellSize, clientH - j * cellSize - cellSize); - glVertex2f(i * cellSize + cellSize, clientH - j * cellSize); - glEnd(); - - //objects - if(renderAll == true) { - switch (map->getObject(i, j)) { - case 0: - glColor3f(0.f, 0.f, 0.f); - break; - case 1: - glColor3f(1.f, 0.f, 0.f); - break; - case 2: - glColor3f(1.f, 1.f, 1.f); - break; - case 3: - glColor3f(0.5f, 0.5f, 1.f); - break; - case 4: - glColor3f(0.f, 0.f, 1.f); - break; - case 5: - glColor3f(0.5f, 0.5f, 0.5f); - break; - case 6: - glColor3f(1.f, 0.8f, 0.5f); - break; - case 7: - glColor3f(0.f, 1.f, 1.f); - break; - case 8: - glColor3f(0.7f, 0.1f, 0.3f); - break; - case 9: - glColor3f(0.5f, 1.f, 0.1f); - break; - case 10: - glColor3f(1.f, 0.2f, 0.8f); - break;// we don't render unvisible blocking objects - } - - if ( renderAll && (map->getObject(i, j) != 0) && (map->getObject(i, j) != 10) ) { - glPointSize(cellSize / 2.f); - glBegin(GL_POINTS); - glVertex2f(i * cellSize + cellSize / 2.f, clientH - j * cellSize - cellSize / 2.f); - glEnd(); - } - } - - // bool found = false; - - //height lines - // if (!found) { - - //left - if (i > 0 && map->getHeight(i - 1, j) > map->getHeight(i, j)) { - glColor3fv((surfColor*0.5f).ptr()); - glBegin(GL_LINES); - glVertex2f(i * cellSize, clientH - (j + 1) * cellSize); - glVertex2f(i * cellSize, clientH - j * cellSize); - glEnd(); - } - //down - if (j > 0 && map->getHeight(i, j - 1) > map->getHeight(i, j)) { - glColor3fv((surfColor*0.5f).ptr()); - glBegin(GL_LINES); - glVertex2f(i * cellSize, clientH - j * cellSize); - glVertex2f((i + 1) * cellSize, clientH - j * cellSize); - glEnd(); - } - - - //left - if (i > 0 && map->getHeight(i - 1, j) < map->getHeight(i, j)) { - glColor3fv((surfColor*2.f).ptr()); - glBegin(GL_LINES); - glVertex2f(i * cellSize, clientH - (j + 1) * cellSize); - glVertex2f(i * cellSize, clientH - j * cellSize); - glEnd(); - } - if (j > 0 && map->getHeight(i, j - 1) < map->getHeight(i, j)) { - glColor3fv((surfColor*2.f).ptr()); - glBegin(GL_LINES); - glVertex2f(i * cellSize, clientH - j * cellSize); - glVertex2f((i + 1) * cellSize, clientH - j * cellSize); - glEnd(); - } - // } - - //resources - if(renderAll == true) { - switch (map->getResource(i, j)) { - case 1: glColor3f(1.f, 1.f, 0.f); break; - case 2: glColor3f(0.5f, 0.5f, 0.5f); break; - case 3: glColor3f(1.f, 0.f, 0.f); break; - case 4: glColor3f(0.f, 0.f, 1.f); break; - case 5: glColor3f(0.5f, 0.5f, 1.f); break; - } - - if (renderAll && map->getResource(i, j) != 0) { - glBegin(GL_LINES); - glVertex2f(i * cellSize, clientH - j * cellSize - cellSize); - glVertex2f(i * cellSize + cellSize, clientH - j * cellSize); - glVertex2f(i * cellSize, clientH - j * cellSize); - glVertex2f(i * cellSize + cellSize, clientH - j * cellSize - cellSize); - glEnd(); - } - } - } - } - - //start locations - glLineWidth(3); + assertGl(); + } +} + +void Renderer::renderMapPreview(const MapPreview *map, bool renderAll, + int screenPosX, int screenPosY, + Texture2D **renderToTexture) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + static bool supportFBOs = Texture2DGl().supports_FBO_RBO(); + if (Config::getInstance().getBool("LegacyMapPreviewRendering", "false") == + true) { + supportFBOs = false; + } + + // static bool supportFBOs = false; + const Metrics &metrics = Metrics::getInstance(); + + float alt = 0; + float showWater = 0; + int renderMapHeight = 64; + int renderMapWidth = 64; + float cellSize = 2; + float playerCrossSize = 2; + float clientW = renderMapWidth * cellSize; + float clientH = renderMapHeight * cellSize; + ; + float minDimension = std::min(metrics.getVirtualW(), metrics.getVirtualH()); + + // stretch small maps to 128x128 + if (map->getW() < map->getH()) { + cellSize = cellSize * renderMapHeight / map->getH(); + } else { + cellSize = cellSize * renderMapWidth / map->getW(); + } + + assertGl(); + + if (supportFBOs == true && renderToTexture != NULL) { + Config &config = Config::getInstance(); + Texture2D::Filter textureFilter = + strToTextureFilter(config.getString("Filter")); + int maxAnisotropy = config.getInt("FilterMaxAnisotropy"); + + *renderToTexture = + GraphicsInterface::getInstance().getFactory()->newTexture2D(); + Texture2DGl *texture = static_cast(*renderToTexture); + texture->setMipmap(false); + Pixmap2D *pixmapScreenShot = texture->getPixmap(); + pixmapScreenShot->init(minDimension, minDimension, 4); + texture->setForceCompressionDisabled(true); + texture->init(textureFilter, maxAnisotropy); + texture->setup_FBO_RBO(); - assertGl(); + assertGl(); - if(supportFBOs == true && renderToTexture != NULL && *renderToTexture != NULL) { - glLineWidth(14); - playerCrossSize = 24; - } - else { - // force playerCrossSize to be at least of size 4 - if(cellSize < 4) { - playerCrossSize = 4; - } - else { - playerCrossSize = cellSize; - } - } + if (texture->checkFrameBufferStatus() == false) { + // printf("******************** WARNING CANNOT Attach to FBO!\n"); + texture->end(); + delete texture; + *renderToTexture = NULL; + } + } + + if (supportFBOs == true && renderToTexture != NULL && + *renderToTexture != NULL) { + cellSize = 1; + clientW = minDimension; + clientH = minDimension; + int mapMaxDimensionSize = std::max(map->getW(), map->getH()); + switch (mapMaxDimensionSize) { + case 8: + cellSize = 96; + break; + case 16: + cellSize = 48; + break; + case 32: + cellSize = 24; + break; + case 64: + cellSize = 12; + break; + case 128: + cellSize = 6; + break; + case 256: + cellSize = 3; + break; + case 512: + cellSize = 2; + break; + } + } + + glFrontFace(GL_CW); + glEnable(GL_CULL_FACE); + + glMatrixMode(GL_PROJECTION); + glPushMatrix(); + glLoadIdentity(); + + assertGl(); + + GLint viewport[4]; // Where The original Viewport Values Will Be Stored + + if (supportFBOs == true && renderToTexture != NULL && + *renderToTexture != NULL) { + glGetIntegerv(GL_VIEWPORT, viewport); + glOrtho(0, clientW, 0, clientH, 0, 1); + glViewport(0, 0, clientW, clientH); + } else { + glOrtho(0, metrics.getVirtualW(), 0, metrics.getVirtualH(), 0, 1); + } + + glMatrixMode(GL_MODELVIEW); + + glPushMatrix(); + glLoadIdentity(); + + if (supportFBOs == false || renderToTexture == NULL || + *renderToTexture == NULL) { + glTranslatef(static_cast(screenPosX), + static_cast(screenPosY) - clientH, 0.0f); + } + + assertGl(); + + glPushAttrib(GL_CURRENT_BIT); + glLineWidth(1); + glColor3f(0, 0, 0); + + for (int j = 0; j < map->getH(); j++) { + for (int i = 0; i < map->getW(); i++) { + // surface + alt = map->getHeight(i, j) / 20.f; + showWater = map->getWaterLevel() / 20.f - alt; + showWater = (showWater > 0) ? showWater : 0; + Vec3f surfColor; + switch (map->getSurface(i, j)) { + case st_Grass: + surfColor = Vec3f(0.0, 0.8f * alt, 0.f + showWater); + break; + case st_Secondary_Grass: + surfColor = Vec3f(0.4f * alt, 0.6f * alt, 0.f + showWater); + break; + case st_Road: + surfColor = Vec3f(0.6f * alt, 0.3f * alt, 0.f + showWater); + break; + case st_Stone: + surfColor = Vec3f(0.7f * alt, 0.7f * alt, 0.7f * alt + showWater); + break; + case st_Ground: + surfColor = Vec3f(0.7f * alt, 0.5f * alt, 0.3f * alt + showWater); + break; + } + + glColor3fv(surfColor.ptr()); + + glBegin(GL_TRIANGLE_STRIP); + glVertex2f(i * cellSize, clientH - j * cellSize - cellSize); + glVertex2f(i * cellSize, clientH - j * cellSize); + glVertex2f(i * cellSize + cellSize, clientH - j * cellSize - cellSize); + glVertex2f(i * cellSize + cellSize, clientH - j * cellSize); + glEnd(); + + // objects + if (renderAll == true) { + switch (map->getObject(i, j)) { + case 0: + glColor3f(0.f, 0.f, 0.f); + break; + case 1: + glColor3f(1.f, 0.f, 0.f); + break; + case 2: + glColor3f(1.f, 1.f, 1.f); + break; + case 3: + glColor3f(0.5f, 0.5f, 1.f); + break; + case 4: + glColor3f(0.f, 0.f, 1.f); + break; + case 5: + glColor3f(0.5f, 0.5f, 0.5f); + break; + case 6: + glColor3f(1.f, 0.8f, 0.5f); + break; + case 7: + glColor3f(0.f, 1.f, 1.f); + break; + case 8: + glColor3f(0.7f, 0.1f, 0.3f); + break; + case 9: + glColor3f(0.5f, 1.f, 0.1f); + break; + case 10: + glColor3f(1.f, 0.2f, 0.8f); + break; // we don't render unvisible blocking objects + } - assertGl(); + if (renderAll && (map->getObject(i, j) != 0) && + (map->getObject(i, j) != 10)) { + glPointSize(cellSize / 2.f); + glBegin(GL_POINTS); + glVertex2f(i * cellSize + cellSize / 2.f, + clientH - j * cellSize - cellSize / 2.f); + glEnd(); + } + } - Vec2f *vertices = new Vec2f[map->getMaxFactions() * 4]; - Vec3f *colors = new Vec3f[map->getMaxFactions() * 4]; - - for (int i = 0; i < map->getMaxFactions(); i++) { - Vec3f color; - switch (i) { - case 0: - color = Vec3f(1.f, 0.f, 0.f); - break; - case 1: - color = Vec3f(0.f, 0.f, 1.f); - break; - case 2: - color = Vec3f(0.f, 1.f, 0.f); - break; - case 3: - color = Vec3f(1.f, 1.f, 0.f); - break; - case 4: - color = Vec3f(1.f, 1.f, 1.f); - break; - case 5: - color = Vec3f(0.f, 1.f, 0.8f); - break; - case 6: - color = Vec3f(1.f, 0.5f, 0.f); - break; - case 7: - color = Vec3f(1.f, 0.5f, 1.f); - break; - } - - colors[i*4] = color; - colors[(i*4)+1] = color; - colors[(i*4)+2] = color; - colors[(i*4)+3] = color; - - vertices[i*4] = Vec2f((map->getStartLocationX(i) - 1) * cellSize, clientH - (map->getStartLocationY(i) - 1) * cellSize); - vertices[(i*4)+1] = Vec2f((map->getStartLocationX(i) + 1) * cellSize + playerCrossSize, clientH - (map->getStartLocationY(i) + 1) * cellSize - playerCrossSize); - vertices[(i*4)+2] = Vec2f((map->getStartLocationX(i) - 1) * cellSize, clientH - (map->getStartLocationY(i) + 1) * cellSize - playerCrossSize); - vertices[(i*4)+3] = Vec2f((map->getStartLocationX(i) + 1) * cellSize + playerCrossSize, clientH - (map->getStartLocationY(i) - 1) * cellSize); - } - - glEnableClientState(GL_COLOR_ARRAY); - glColorPointer(3, GL_FLOAT, 0, &colors[0]); - glEnableClientState(GL_VERTEX_ARRAY); - glVertexPointer(2, GL_FLOAT, 0, &vertices[0]); - glDrawArrays(GL_LINES, 0, 4 * map->getMaxFactions()); - glDisableClientState(GL_COLOR_ARRAY); - glDisableClientState(GL_VERTEX_ARRAY); + // bool found = false; - assertGl(); + // height lines + // if (!found) { - glLineWidth(1); + // left + if (i > 0 && map->getHeight(i - 1, j) > map->getHeight(i, j)) { + glColor3fv((surfColor * 0.5f).ptr()); + glBegin(GL_LINES); + glVertex2f(i * cellSize, clientH - (j + 1) * cellSize); + glVertex2f(i * cellSize, clientH - j * cellSize); + glEnd(); + } + // down + if (j > 0 && map->getHeight(i, j - 1) > map->getHeight(i, j)) { + glColor3fv((surfColor * 0.5f).ptr()); + glBegin(GL_LINES); + glVertex2f(i * cellSize, clientH - j * cellSize); + glVertex2f((i + 1) * cellSize, clientH - j * cellSize); + glEnd(); + } + + // left + if (i > 0 && map->getHeight(i - 1, j) < map->getHeight(i, j)) { + glColor3fv((surfColor * 2.f).ptr()); + glBegin(GL_LINES); + glVertex2f(i * cellSize, clientH - (j + 1) * cellSize); + glVertex2f(i * cellSize, clientH - j * cellSize); + glEnd(); + } + if (j > 0 && map->getHeight(i, j - 1) < map->getHeight(i, j)) { + glColor3fv((surfColor * 2.f).ptr()); + glBegin(GL_LINES); + glVertex2f(i * cellSize, clientH - j * cellSize); + glVertex2f((i + 1) * cellSize, clientH - j * cellSize); + glEnd(); + } + // } + + // resources + if (renderAll == true) { + switch (map->getResource(i, j)) { + case 1: + glColor3f(1.f, 1.f, 0.f); + break; + case 2: + glColor3f(0.5f, 0.5f, 0.5f); + break; + case 3: + glColor3f(1.f, 0.f, 0.f); + break; + case 4: + glColor3f(0.f, 0.f, 1.f); + break; + case 5: + glColor3f(0.5f, 0.5f, 1.f); + break; + } - glPopMatrix(); - glPopAttrib(); - glMatrixMode(GL_PROJECTION); - glPopMatrix(); + if (renderAll && map->getResource(i, j) != 0) { + glBegin(GL_LINES); + glVertex2f(i * cellSize, clientH - j * cellSize - cellSize); + glVertex2f(i * cellSize + cellSize, clientH - j * cellSize); + glVertex2f(i * cellSize, clientH - j * cellSize); + glVertex2f(i * cellSize + cellSize, + clientH - j * cellSize - cellSize); + glEnd(); + } + } + } + } + + // start locations + glLineWidth(3); + + assertGl(); + + if (supportFBOs == true && renderToTexture != NULL && + *renderToTexture != NULL) { + glLineWidth(14); + playerCrossSize = 24; + } else { + // force playerCrossSize to be at least of size 4 + if (cellSize < 4) { + playerCrossSize = 4; + } else { + playerCrossSize = cellSize; + } + } + + assertGl(); + + Vec2f *vertices = new Vec2f[map->getMaxFactions() * 4]; + Vec3f *colors = new Vec3f[map->getMaxFactions() * 4]; + + for (int i = 0; i < map->getMaxFactions(); i++) { + Vec3f color; + switch (i) { + case 0: + color = Vec3f(1.f, 0.f, 0.f); + break; + case 1: + color = Vec3f(0.f, 0.f, 1.f); + break; + case 2: + color = Vec3f(0.f, 1.f, 0.f); + break; + case 3: + color = Vec3f(1.f, 1.f, 0.f); + break; + case 4: + color = Vec3f(1.f, 1.f, 1.f); + break; + case 5: + color = Vec3f(0.f, 1.f, 0.8f); + break; + case 6: + color = Vec3f(1.f, 0.5f, 0.f); + break; + case 7: + color = Vec3f(1.f, 0.5f, 1.f); + break; + } - if(supportFBOs == true && renderToTexture != NULL && *renderToTexture != NULL) { - Texture2DGl *texture = static_cast(*renderToTexture); - if(texture != NULL) { - texture->dettachFrameBufferFromTexture(); - } + colors[i * 4] = color; + colors[(i * 4) + 1] = color; + colors[(i * 4) + 2] = color; + colors[(i * 4) + 3] = color; + + vertices[i * 4] = + Vec2f((map->getStartLocationX(i) - 1) * cellSize, + clientH - (map->getStartLocationY(i) - 1) * cellSize); + vertices[(i * 4) + 1] = Vec2f( + (map->getStartLocationX(i) + 1) * cellSize + playerCrossSize, + clientH - (map->getStartLocationY(i) + 1) * cellSize - playerCrossSize); + vertices[(i * 4) + 2] = Vec2f( + (map->getStartLocationX(i) - 1) * cellSize, + clientH - (map->getStartLocationY(i) + 1) * cellSize - playerCrossSize); + vertices[(i * 4) + 3] = + Vec2f((map->getStartLocationX(i) + 1) * cellSize + playerCrossSize, + clientH - (map->getStartLocationY(i) - 1) * cellSize); + } + + glEnableClientState(GL_COLOR_ARRAY); + glColorPointer(3, GL_FLOAT, 0, &colors[0]); + glEnableClientState(GL_VERTEX_ARRAY); + glVertexPointer(2, GL_FLOAT, 0, &vertices[0]); + glDrawArrays(GL_LINES, 0, 4 * map->getMaxFactions()); + glDisableClientState(GL_COLOR_ARRAY); + glDisableClientState(GL_VERTEX_ARRAY); + + assertGl(); + + glLineWidth(1); + + glPopMatrix(); + glPopAttrib(); + glMatrixMode(GL_PROJECTION); + glPopMatrix(); + + if (supportFBOs == true && renderToTexture != NULL && + *renderToTexture != NULL) { + Texture2DGl *texture = static_cast(*renderToTexture); + if (texture != NULL) { + texture->dettachFrameBufferFromTexture(); + } - glViewport(viewport[0], viewport[1], viewport[2], viewport[3]); + glViewport(viewport[0], viewport[1], viewport[2], viewport[3]); - assertGl(); - } + assertGl(); + } - delete [] vertices; - delete [] colors; + delete[] vertices; + delete[] colors; - assertGl(); + assertGl(); } // setLastRenderFps and calculate shadowsOffDueToMinRender void Renderer::setLastRenderFps(int value) { - lastRenderFps = value; - smoothedRenderFps=(MIN_FPS_NORMAL_RENDERING*smoothedRenderFps+lastRenderFps)/(MIN_FPS_NORMAL_RENDERING+1.0f); + lastRenderFps = value; + smoothedRenderFps = + (MIN_FPS_NORMAL_RENDERING * smoothedRenderFps + lastRenderFps) / + (MIN_FPS_NORMAL_RENDERING + 1.0f); - if(smoothedRenderFps>=MIN_FPS_NORMAL_RENDERING_TOP_THRESHOLD){ - shadowsOffDueToMinRender=false; - } - if(smoothedRenderFps<=MIN_FPS_NORMAL_RENDERING){ - shadowsOffDueToMinRender=true; - } + if (smoothedRenderFps >= MIN_FPS_NORMAL_RENDERING_TOP_THRESHOLD) { + shadowsOffDueToMinRender = false; + } + if (smoothedRenderFps <= MIN_FPS_NORMAL_RENDERING) { + shadowsOffDueToMinRender = true; + } } std::size_t Renderer::getCurrentPixelByteCount(ResourceScope rs) const { - std::size_t result = 0; - for(int i = (rs == rsCount ? 0 : rs); i < rsCount; ++i) { - if(textureManager[i] != NULL) { - const ::Shared::Graphics::TextureContainer &textures = textureManager[i]->getTextures(); - for(int j = 0; j < (int)textures.size(); ++j) { - const Texture *texture = textures[j]; - result += texture->getPixelByteCount(); - } - if(rs != rsCount) { - break; - } - } - } - - return result; -} - -Texture2D * Renderer::preloadTexture(string logoFilename) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] logoFilename [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,logoFilename.c_str()); - - Texture2D *result = NULL; - if(logoFilename != "") { - // Cache faction preview textures - string data_path = getGameReadWritePath(GameConstants::path_data_CacheLookupKey); - std::map &crcFactionPreviewTextureCache = CacheManager::getCachedItem< std::map >(GameConstants::factionPreviewTextureCacheLookupKey); - - if(crcFactionPreviewTextureCache.find(logoFilename) != crcFactionPreviewTextureCache.end()) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] logoFilename [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,logoFilename.c_str()); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] load texture from cache [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,logoFilename.c_str()); - - result = crcFactionPreviewTextureCache[logoFilename]; - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] logoFilename [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,logoFilename.c_str()); - Renderer &renderer= Renderer::getInstance(); - result = renderer.newTexture2D(rsGlobal); - if(result) { - result->setMipmap(true); - result->load(logoFilename); - //renderer.initTexture(rsGlobal,result); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] add texture to manager and cache [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,logoFilename.c_str()); - - crcFactionPreviewTextureCache[logoFilename] = result; - } - } + std::size_t result = 0; + for (int i = (rs == rsCount ? 0 : rs); i < rsCount; ++i) { + if (textureManager[i] != NULL) { + const ::Shared::Graphics::TextureContainer &textures = + textureManager[i]->getTextures(); + for (int j = 0; j < (int)textures.size(); ++j) { + const Texture *texture = textures[j]; + result += texture->getPixelByteCount(); + } + if (rs != rsCount) { + break; + } + } + } + + return result; +} + +Texture2D *Renderer::preloadTexture(string logoFilename) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] logoFilename [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, logoFilename.c_str()); + + Texture2D *result = NULL; + if (logoFilename != "") { + // Cache faction preview textures + string data_path = + getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + std::map &crcFactionPreviewTextureCache = + CacheManager::getCachedItem>( + GameConstants::factionPreviewTextureCacheLookupKey); + + if (crcFactionPreviewTextureCache.find(logoFilename) != + crcFactionPreviewTextureCache.end()) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] logoFilename [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, logoFilename.c_str()); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] load texture from cache [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, logoFilename.c_str()); + + result = crcFactionPreviewTextureCache[logoFilename]; + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] logoFilename [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, logoFilename.c_str()); + Renderer &renderer = Renderer::getInstance(); + result = renderer.newTexture2D(rsGlobal); + if (result) { + result->setMipmap(true); + result->load(logoFilename); + // renderer.initTexture(rsGlobal,result); + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] add texture to manager and cache [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, logoFilename.c_str()); + + crcFactionPreviewTextureCache[logoFilename] = result; + } + } - return result; + return result; } -Texture2D * Renderer::findTexture(string logoFilename) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] logoFilename [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,logoFilename.c_str()); +Texture2D *Renderer::findTexture(string logoFilename) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] logoFilename [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, logoFilename.c_str()); - Texture2D *result = preloadTexture(logoFilename); - if(result != NULL && result->getInited() == false) { - Renderer &renderer= Renderer::getInstance(); - renderer.initTexture(rsGlobal,result); - } + Texture2D *result = preloadTexture(logoFilename); + if (result != NULL && result->getInited() == false) { + Renderer &renderer = Renderer::getInstance(); + renderer.initTexture(rsGlobal, result); + } - return result; + return result; } void Renderer::cycleShowDebugUILevel() { - //printf("#1 showDebugUILevel = %d, debugui_fps = %d, debugui_unit_titles = %d\n",showDebugUILevel,debugui_fps,debugui_unit_titles); + // printf("#1 showDebugUILevel = %d, debugui_fps = %d, debugui_unit_titles = + // %d\n",showDebugUILevel,debugui_fps,debugui_unit_titles); - //if(showDebugUI == false) { - // showDebugUI = true; - //} - if((showDebugUILevel & debugui_fps) != debugui_fps || - (showDebugUILevel & debugui_unit_titles) != debugui_unit_titles) { - showDebugUILevel |= debugui_fps; - showDebugUILevel |= debugui_unit_titles; - } - else { - showDebugUILevel = debugui_fps; - } + // if(showDebugUI == false) { + // showDebugUI = true; + // } + if ((showDebugUILevel & debugui_fps) != debugui_fps || + (showDebugUILevel & debugui_unit_titles) != debugui_unit_titles) { + showDebugUILevel |= debugui_fps; + showDebugUILevel |= debugui_unit_titles; + } else { + showDebugUILevel = debugui_fps; + } - //printf("#2 showDebugUILevel = %d, debugui_fps = %d, debugui_unit_titles = %d\n",showDebugUILevel,debugui_fps,debugui_unit_titles); + // printf("#2 showDebugUILevel = %d, debugui_fps = %d, debugui_unit_titles = + // %d\n",showDebugUILevel,debugui_fps,debugui_unit_titles); } void Renderer::renderFPSWhenEnabled(int lastFps) { - if(getShowDebugUI() == true) { - CoreData &coreData= CoreData::getInstance(); - if(Renderer::renderText3DEnabled) { - renderText3D( - "FPS: " + intToStr(lastFps), - coreData.getMenuFontNormal3D(), Vec3f(1.f), 10, 10, false); - } - else { - renderText( - "FPS: " + intToStr(lastFps), - coreData.getMenuFontNormal(), Vec3f(1.f), 10, 10, false); - } - } + if (getShowDebugUI() == true) { + CoreData &coreData = CoreData::getInstance(); + if (Renderer::renderText3DEnabled) { + renderText3D("FPS: " + intToStr(lastFps), coreData.getMenuFontNormal3D(), + Vec3f(1.f), 10, 10, false); + } else { + renderText("FPS: " + intToStr(lastFps), coreData.getMenuFontNormal(), + Vec3f(1.f), 10, 10, false); + } + } } void Renderer::renderPopupMenu(PopupMenu *menu) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - if(menu->getVisible() == false || menu->getEnabled() == false) { - return; - } - - //background - glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT); - glEnable(GL_BLEND); - - glColor4f(0.0f, 0.0f, 0.0f, 0.8f) ; - glBegin(GL_TRIANGLE_STRIP); - glVertex2i(menu->getX(), menu->getY() + 9 * menu->getH() / 10); - glVertex2i(menu->getX(), menu->getY()); - glVertex2i(menu->getX() + menu->getW(), menu->getY() + 9 * menu->getH() / 10); - glVertex2i(menu->getX() + menu->getW(), menu->getY()); - glEnd(); - - glColor4f(0.0f, 0.0f, 0.0f, 0.8f) ; - glBegin(GL_TRIANGLE_STRIP); - glVertex2i(menu->getX(), menu->getY() + menu->getH()); - glVertex2i(menu->getX(), menu->getY() + 9 * menu->getH() / 10); - glVertex2i(menu->getX() + menu->getW(), menu->getY() + menu->getH()); - glVertex2i(menu->getX() + menu->getW(), menu->getY() + 9 * menu->getH() / 10); - glEnd(); - - glBegin(GL_LINE_LOOP); - glColor4f(0.5f, 0.5f, 0.5f, 0.25f) ; - glVertex2i(menu->getX(), menu->getY()); - - glColor4f(0.0f, 0.0f, 0.0f, 0.25f) ; - glVertex2i(menu->getX() + menu->getW(), menu->getY()); - - glColor4f(0.5f, 0.5f, 0.5f, 0.25f) ; - glVertex2i(menu->getX() + menu->getW(), menu->getY() + menu->getH()); - - glColor4f(0.25f, 0.25f, 0.25f, 0.25f) ; - glVertex2i(menu->getX(), menu->getY() + menu->getH()); - glEnd(); - - glBegin(GL_LINE_STRIP); - glColor4f(1.0f, 1.0f, 1.0f, 0.25f) ; - glVertex2i(menu->getX(), menu->getY() + 90*menu->getH()/100); - - glColor4f(0.5f, 0.5f, 0.5f, 0.25f) ; - glVertex2i(menu->getX()+ menu->getW(), menu->getY() + 90*menu->getH()/100); - glEnd(); - - glPopAttrib(); - - Vec4f fontColor; - //if(game!=NULL){ - // fontColor=game->getGui()->getDisplay()->getColor(); - //} - //else { - // white shadowed is default ( in the menu for example ) - fontColor=Vec4f(1.f, 1.f, 1.f, 1.0f); - //} - - if(renderText3DEnabled == true) { - //text - renderTextBoundingBox3D( - menu->getHeader(), menu->getFont3D(),fontColor, - menu->getX(), menu->getY()+93*menu->getH()/100,menu->getW(),0, - true,false, false,-1,-1); - - } - else { - //text - int renderX = (menu->getX() + (menu->getW() / 2)); - //int renderY = (menu->getY() + (menu->getH() / 2)); - FontMetrics *fontMetrics= menu->getFont()->getMetrics(); - int renderY = menu->getY() + menu->getH() - fontMetrics->getHeight(menu->getHeader()); - renderTextShadow( - menu->getHeader(), menu->getFont(),fontColor, - renderX, renderY, - true); - - //renderText(button->getText(), button->getFont(), color,x + (w / 2), y + (h / 2), true); - } - - //buttons -// int maxButtonWidth = -1; - std::vector &menuItems = menu->getMenuItems(); -// for(unsigned int i = 0; i < menuItems.size(); ++i) { -// GraphicButton *button = &menuItems[i]; -// int currentButtonWidth = -1; -// if(renderText3DEnabled == true) { -// FontMetrics *fontMetrics= menu->getFont3D()->getMetrics(); -// currentButtonWidth = fontMetrics->getTextWidth(button->getText()); -// } -// else { -// FontMetrics *fontMetrics= menu->getFont()->getMetrics(); -// currentButtonWidth = fontMetrics->getTextWidth(button->getText()); -// } -// -// if(maxButtonWidth < 0 || currentButtonWidth > maxButtonWidth) { -// maxButtonWidth = currentButtonWidth + 5; -// } -// } - - for(unsigned int i = 0; i < menuItems.size(); ++i) { - GraphicButton *button = &menuItems[i]; - - //button->setW(maxButtonWidth); - renderButton(button); - } - + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + if (menu->getVisible() == false || menu->getEnabled() == false) { + return; + } + + // background + glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT); + glEnable(GL_BLEND); + + glColor4f(0.0f, 0.0f, 0.0f, 0.8f); + glBegin(GL_TRIANGLE_STRIP); + glVertex2i(menu->getX(), menu->getY() + 9 * menu->getH() / 10); + glVertex2i(menu->getX(), menu->getY()); + glVertex2i(menu->getX() + menu->getW(), menu->getY() + 9 * menu->getH() / 10); + glVertex2i(menu->getX() + menu->getW(), menu->getY()); + glEnd(); + + glColor4f(0.0f, 0.0f, 0.0f, 0.8f); + glBegin(GL_TRIANGLE_STRIP); + glVertex2i(menu->getX(), menu->getY() + menu->getH()); + glVertex2i(menu->getX(), menu->getY() + 9 * menu->getH() / 10); + glVertex2i(menu->getX() + menu->getW(), menu->getY() + menu->getH()); + glVertex2i(menu->getX() + menu->getW(), menu->getY() + 9 * menu->getH() / 10); + glEnd(); + + glBegin(GL_LINE_LOOP); + glColor4f(0.5f, 0.5f, 0.5f, 0.25f); + glVertex2i(menu->getX(), menu->getY()); + + glColor4f(0.0f, 0.0f, 0.0f, 0.25f); + glVertex2i(menu->getX() + menu->getW(), menu->getY()); + + glColor4f(0.5f, 0.5f, 0.5f, 0.25f); + glVertex2i(menu->getX() + menu->getW(), menu->getY() + menu->getH()); + + glColor4f(0.25f, 0.25f, 0.25f, 0.25f); + glVertex2i(menu->getX(), menu->getY() + menu->getH()); + glEnd(); + + glBegin(GL_LINE_STRIP); + glColor4f(1.0f, 1.0f, 1.0f, 0.25f); + glVertex2i(menu->getX(), menu->getY() + 90 * menu->getH() / 100); + + glColor4f(0.5f, 0.5f, 0.5f, 0.25f); + glVertex2i(menu->getX() + menu->getW(), + menu->getY() + 90 * menu->getH() / 100); + glEnd(); + + glPopAttrib(); + + Vec4f fontColor; + // if(game!=NULL){ + // fontColor=game->getGui()->getDisplay()->getColor(); + // } + // else { + // white shadowed is default ( in the menu for example ) + fontColor = Vec4f(1.f, 1.f, 1.f, 1.0f); + //} + + if (renderText3DEnabled == true) { + // text + renderTextBoundingBox3D(menu->getHeader(), menu->getFont3D(), fontColor, + menu->getX(), + menu->getY() + 93 * menu->getH() / 100, + menu->getW(), 0, true, false, false, -1, -1); + + } else { + // text + int renderX = (menu->getX() + (menu->getW() / 2)); + // int renderY = (menu->getY() + (menu->getH() / 2)); + FontMetrics *fontMetrics = menu->getFont()->getMetrics(); + int renderY = + menu->getY() + menu->getH() - fontMetrics->getHeight(menu->getHeader()); + renderTextShadow(menu->getHeader(), menu->getFont(), fontColor, renderX, + renderY, true); + + // renderText(button->getText(), button->getFont(), color,x + (w / 2), y + + // (h / 2), true); + } + + // buttons + // int maxButtonWidth = -1; + std::vector &menuItems = menu->getMenuItems(); + // for(unsigned int i = 0; i < menuItems.size(); ++i) { + // GraphicButton *button = &menuItems[i]; + // int currentButtonWidth = -1; + // if(renderText3DEnabled == true) { + // FontMetrics *fontMetrics= + // menu->getFont3D()->getMetrics(); currentButtonWidth = + // fontMetrics->getTextWidth(button->getText()); + // } + // else { + // FontMetrics *fontMetrics= menu->getFont()->getMetrics(); + // currentButtonWidth = + // fontMetrics->getTextWidth(button->getText()); + // } + // + // if(maxButtonWidth < 0 || currentButtonWidth > maxButtonWidth) { + // maxButtonWidth = currentButtonWidth + 5; + // } + // } + + for (unsigned int i = 0; i < menuItems.size(); ++i) { + GraphicButton *button = &menuItems[i]; + + // button->setW(maxButtonWidth); + renderButton(button); + } } void Renderer::setupRenderForVideo() { - clearBuffers(); - //3d - reset3dMenu(); - clearZBuffer(); - //2d - reset2d(); - glClearColor(0.f, 0.f, 0.f, 1.f); + clearBuffers(); + // 3d + reset3dMenu(); + clearZBuffer(); + // 2d + reset2d(); + glClearColor(0.f, 0.f, 0.f, 1.f); } void Renderer::renderVideoLoading(int progressPercent) { - //printf("Rendering progress progressPercent = %d\n",progressPercent); - setupRenderForVideo(); - - Lang &lang= Lang::getInstance(); - string textToRender = lang.getString("PleaseWait"); - const Metrics &metrics= Metrics::getInstance(); - - static Chrono cycle(true); - static float anim = 0.0f; - - if(CoreData::getInstance().getMenuFontBig3D() != NULL) { - - int w= metrics.getVirtualW(); - int renderX = (w / 2) - (CoreData::getInstance().getMenuFontBig3D()->getMetrics()->getTextWidth(textToRender) / 2); - int h= metrics.getVirtualH(); - int renderY = (h / 2) + (CoreData::getInstance().getMenuFontBig3D()->getMetrics()->getHeight(textToRender) / 2); - - renderText3D( - textToRender, - CoreData::getInstance().getMenuFontBig3D(), - Vec4f(1.f, 1.f, 0.f,anim), - renderX, renderY, false); - } - else { - renderText( - textToRender, - CoreData::getInstance().getMenuFontBig(), - Vec4f(1.f, 1.f, 0.f,anim), (metrics.getScreenW() / 2), - (metrics.getScreenH() / 2), true); - } - swapBuffers(); - - if(cycle.getCurMillis() % 50 == 0) { - static bool animCycleUp = true; - if(animCycleUp == true) { - anim += 0.1f; - if(anim > 1.f) { - anim= 1.f; - cycle.reset(); - animCycleUp = false; - } - } - else { - anim -= 0.1f; - if(anim < 0.f) { - anim= 0.f; - cycle.reset(); - animCycleUp = true; - } - } - } -} - -}}//end namespace + // printf("Rendering progress progressPercent = %d\n",progressPercent); + setupRenderForVideo(); + + Lang &lang = Lang::getInstance(); + string textToRender = lang.getString("PleaseWait"); + const Metrics &metrics = Metrics::getInstance(); + + static Chrono cycle(true); + static float anim = 0.0f; + + if (CoreData::getInstance().getMenuFontBig3D() != NULL) { + + int w = metrics.getVirtualW(); + int renderX = + (w / 2) - + (CoreData::getInstance().getMenuFontBig3D()->getMetrics()->getTextWidth( + textToRender) / + 2); + int h = metrics.getVirtualH(); + int renderY = + (h / 2) + + (CoreData::getInstance().getMenuFontBig3D()->getMetrics()->getHeight( + textToRender) / + 2); + + renderText3D(textToRender, CoreData::getInstance().getMenuFontBig3D(), + Vec4f(1.f, 1.f, 0.f, anim), renderX, renderY, false); + } else { + renderText(textToRender, CoreData::getInstance().getMenuFontBig(), + Vec4f(1.f, 1.f, 0.f, anim), (metrics.getScreenW() / 2), + (metrics.getScreenH() / 2), true); + } + swapBuffers(); + + if (cycle.getCurMillis() % 50 == 0) { + static bool animCycleUp = true; + if (animCycleUp == true) { + anim += 0.1f; + if (anim > 1.f) { + anim = 1.f; + cycle.reset(); + animCycleUp = false; + } + } else { + anim -= 0.1f; + if (anim < 0.f) { + anim = 0.f; + cycle.reset(); + animCycleUp = true; + } + } + } +} + +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/graphics/renderer.h b/source/glest_game/graphics/renderer.h index 47260bf92..ad651a04d 100644 --- a/source/glest_game/graphics/renderer.h +++ b/source/glest_game/graphics/renderer.h @@ -13,52 +13,49 @@ #define _GLEST_GAME_RENDERER_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include "vec.h" +#include "base_renderer.h" +#include "camera.h" +#include "components.h" +#include "font.h" +#include "font_manager.h" +#include "graphics_factory_gl.h" +#include "graphics_interface.h" #include "math_util.h" +#include "matrix.h" #include "model.h" +#include "model_manager.h" +#include "model_renderer.h" #include "particle.h" #include "pixmap.h" -#include "font.h" -#include "matrix.h" #include "selection.h" -#include "components.h" -#include "texture.h" -#include "model_manager.h" -#include "graphics_factory_gl.h" -#include "font_manager.h" -#include "camera.h" -#include -#include "model_renderer.h" -#include "model.h" -#include "graphics_interface.h" -#include "base_renderer.h" #include "simple_threads.h" +#include "texture.h" +#include "vec.h" #include "video_player.h" +#include #ifdef DEBUG_RENDERING_ENABLED -# define IF_DEBUG_EDITION(x) x -# include "debug_renderer.h" +#define IF_DEBUG_EDITION(x) x +#include "debug_renderer.h" #else -# define IF_DEBUG_EDITION(x) +#define IF_DEBUG_EDITION(x) #endif #include "leak_dumper.h" -enum DebugUILevelType { - debugui_fps = 0x01, - debugui_unit_titles = 0x02 -}; +enum DebugUILevelType { debugui_fps = 0x01, debugui_unit_titles = 0x02 }; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { using namespace ::Shared::Graphics; using namespace ::Shared::PlatformCommon; -//non shared classes +// non shared classes class Config; class Game; class GameCamera; @@ -74,18 +71,18 @@ class Program; // class MeshCallbackTeamColor // ===================================================== -class MeshCallbackTeamColor: public MeshCallback { +class MeshCallbackTeamColor : public MeshCallback { private: - const Texture *teamTexture; + const Texture *teamTexture; public: - MeshCallbackTeamColor() : MeshCallback() { - teamTexture = NULL; - } - void setTeamTexture(const Texture *teamTexture) {this->teamTexture= teamTexture;} - virtual void execute(const Mesh *mesh); + MeshCallbackTeamColor() : MeshCallback() { teamTexture = NULL; } + void setTeamTexture(const Texture *teamTexture) { + this->teamTexture = teamTexture; + } + virtual void execute(const Mesh *mesh); - static bool noTeamColors; + static bool noTeamColors; }; // =========================================================== @@ -96,629 +93,713 @@ class MeshCallbackTeamColor: public MeshCallback { class VisibleQuadContainerCache { protected: - - inline void CopyAll(const VisibleQuadContainerCache &obj) { - cacheFrame = obj.cacheFrame; - visibleObjectList = obj.visibleObjectList; - visibleUnitList = obj.visibleUnitList; - visibleQuadUnitList = obj.visibleQuadUnitList; - visibleQuadUnitBuildList = obj.visibleQuadUnitBuildList; - visibleScaledCellList = obj.visibleScaledCellList; - visibleScaledCellToScreenPosList = obj.visibleScaledCellToScreenPosList; - lastVisibleQuad = obj.lastVisibleQuad; - frustumData = obj.frustumData; - proj = obj.proj; - modl = obj.modl; - frustumDataCache = obj.frustumDataCache; - } + inline void CopyAll(const VisibleQuadContainerCache &obj) { + cacheFrame = obj.cacheFrame; + visibleObjectList = obj.visibleObjectList; + visibleUnitList = obj.visibleUnitList; + visibleQuadUnitList = obj.visibleQuadUnitList; + visibleQuadUnitBuildList = obj.visibleQuadUnitBuildList; + visibleScaledCellList = obj.visibleScaledCellList; + visibleScaledCellToScreenPosList = obj.visibleScaledCellToScreenPosList; + lastVisibleQuad = obj.lastVisibleQuad; + frustumData = obj.frustumData; + proj = obj.proj; + modl = obj.modl; + frustumDataCache = obj.frustumDataCache; + } public: - - inline VisibleQuadContainerCache() { - cacheFrame = 0; - clearFrustumData(); - clearCacheData(); - } - inline VisibleQuadContainerCache(const VisibleQuadContainerCache &obj) { - CopyAll(obj); - } - inline VisibleQuadContainerCache & operator=(const VisibleQuadContainerCache &obj) { - CopyAll(obj); - return *this; - } - - inline void clearCacheData() { - clearVolatileCacheData(); - clearNonVolatileCacheData(); - } - inline void clearVolatileCacheData() { - visibleUnitList.clear(); - visibleQuadUnitList.clear(); - visibleQuadUnitBuildList.clear(); - //inVisibleUnitList.clear(); - - visibleUnitList.reserve(500); - visibleQuadUnitList.reserve(500); - visibleQuadUnitBuildList.reserve(100); - } - inline void clearNonVolatileCacheData() { - visibleObjectList.clear(); - visibleScaledCellList.clear(); - visibleScaledCellToScreenPosList.clear(); - - visibleObjectList.reserve(500); - visibleScaledCellList.reserve(500); - } - inline void clearFrustumData() { - frustumData = vector >(6,vector(4,0)); - proj = vector(16,0); - modl = vector(16,0); - frustumDataCache.clear(); - } - int cacheFrame; - Quad2i lastVisibleQuad; - std::vector visibleObjectList; - std::vector visibleQuadUnitList; - std::vector visibleQuadUnitBuildList; - std::vector visibleUnitList; - std::vector visibleScaledCellList; - std::map visibleScaledCellToScreenPosList; - - static bool enableFrustumCalcs; - vector > frustumData; - vector proj; - vector modl; - map,vector >, vector > > frustumDataCache; - + inline VisibleQuadContainerCache() { + cacheFrame = 0; + clearFrustumData(); + clearCacheData(); + } + inline VisibleQuadContainerCache(const VisibleQuadContainerCache &obj) { + CopyAll(obj); + } + inline VisibleQuadContainerCache & + operator=(const VisibleQuadContainerCache &obj) { + CopyAll(obj); + return *this; + } + + inline void clearCacheData() { + clearVolatileCacheData(); + clearNonVolatileCacheData(); + } + inline void clearVolatileCacheData() { + visibleUnitList.clear(); + visibleQuadUnitList.clear(); + visibleQuadUnitBuildList.clear(); + // inVisibleUnitList.clear(); + + visibleUnitList.reserve(500); + visibleQuadUnitList.reserve(500); + visibleQuadUnitBuildList.reserve(100); + } + inline void clearNonVolatileCacheData() { + visibleObjectList.clear(); + visibleScaledCellList.clear(); + visibleScaledCellToScreenPosList.clear(); + + visibleObjectList.reserve(500); + visibleScaledCellList.reserve(500); + } + inline void clearFrustumData() { + frustumData = vector>(6, vector(4, 0)); + proj = vector(16, 0); + modl = vector(16, 0); + frustumDataCache.clear(); + } + int cacheFrame; + Quad2i lastVisibleQuad; + std::vector visibleObjectList; + std::vector visibleQuadUnitList; + std::vector visibleQuadUnitBuildList; + std::vector visibleUnitList; + std::vector visibleScaledCellList; + std::map visibleScaledCellToScreenPosList; + + static bool enableFrustumCalcs; + vector> frustumData; + vector proj; + vector modl; + map, vector>, vector>> + frustumDataCache; }; class VisibleQuadContainerVBOCache { public: - // Vertex Buffer Object Names - bool hasBuiltVBOs; - uint32 m_nVBOVertices; // Vertex VBO Name - uint32 m_nVBOFowTexCoords; // Texture Coordinate VBO Name for fog of war texture coords - uint32 m_nVBOSurfaceTexCoords; // Texture Coordinate VBO Name for surface texture coords - uint32 m_nVBONormals; // Normal VBO Name - //uint32 m_nVBOIndexes; // Indexes VBO Name + // Vertex Buffer Object Names + bool hasBuiltVBOs; + uint32 m_nVBOVertices; // Vertex VBO Name + uint32 m_nVBOFowTexCoords; // Texture Coordinate VBO Name for fog of war + // texture coords + uint32 m_nVBOSurfaceTexCoords; // Texture Coordinate VBO Name for surface + // texture coords + uint32 m_nVBONormals; // Normal VBO Name + // uint32 m_nVBOIndexes; // + // Indexes VBO + // Name }; enum ConsoleMode { - consoleOff, - consoleNormal, - consoleFull, - consoleStoredOnly, - consoleStoredAndNormal, + consoleOff, + consoleNormal, + consoleFull, + consoleStoredOnly, + consoleStoredAndNormal, - consoleCount + consoleCount }; class Renderer : public RendererInterface, - public BaseRenderer, - // This is for screen saver thread - public SimpleTaskCallbackInterface, - public VideoLoadingCallbackInterface { + public BaseRenderer, + // This is for screen saver thread + public SimpleTaskCallbackInterface, + public VideoLoadingCallbackInterface { public: - //progress bar - static const int maxProgressBar; - static const Vec4f progressBarBack1; - static const Vec4f progressBarBack2; - static const Vec4f progressBarFront1; - static const Vec4f progressBarFront2; - - //sun and moon - static const float sunDist; - static const float moonDist; - static const float lightAmbFactor; - - //mouse - static const int maxMouse2dAnim; - - //texture units - static const GLenum baseTexUnit; - static const GLenum fowTexUnit; - static const GLenum shadowTexUnit; - - //selection - static const float selectionCircleRadius; - static const float magicCircleRadius; - - //perspective values - static const float perspFov; - static const float perspNearPlane; - static float perspFarPlane; - - //default values - static const float ambFactor; - static const Vec4f defSpecularColor; - static const Vec4f defDiffuseColor; - static const Vec4f defAmbientColor; - static const Vec4f defColor; - static const Vec4f fowColor; - - //light - static const float maxLightDist; - - static bool renderText3DEnabled; + // progress bar + static const int maxProgressBar; + static const Vec4f progressBarBack1; + static const Vec4f progressBarBack2; + static const Vec4f progressBarFront1; + static const Vec4f progressBarFront2; + + // sun and moon + static const float sunDist; + static const float moonDist; + static const float lightAmbFactor; + + // mouse + static const int maxMouse2dAnim; + + // texture units + static const GLenum baseTexUnit; + static const GLenum fowTexUnit; + static const GLenum shadowTexUnit; + + // selection + static const float selectionCircleRadius; + static const float magicCircleRadius; + + // perspective values + static const float perspFov; + static const float perspNearPlane; + static float perspFarPlane; + + // default values + static const float ambFactor; + static const Vec4f defSpecularColor; + static const Vec4f defDiffuseColor; + static const Vec4f defAmbientColor; + static const Vec4f defColor; + static const Vec4f fowColor; + + // light + static const float maxLightDist; + + static bool renderText3DEnabled; public: - enum Shadows { - sDisabled, - sProjected, - sShadowMapping, + enum Shadows { + sDisabled, + sProjected, + sShadowMapping, - sCount - }; + sCount + }; private: - - //config - int maxLights; - bool photoMode; - int shadowTextureSize; - int shadowFrameSkip; - float shadowIntensity; - bool focusArrows; - bool textures3D; - Shadows shadows; - int maxConsoleLines; - - //game - const Game *game; - GameCamera *gameCamera; - const MainMenu *menu; - Program *program; - - //misc - int triangleCount; - int pointCount; - Quad2i visibleQuad; - Quad2i visibleQuadFromCamera; - Vec4f nearestLightPos; - VisibleQuadContainerCache quadCache; - VisibleQuadContainerCache quadCacheSelection; - - //renderers - ModelRenderer *modelRenderer; - TextRenderer2D *textRenderer; - TextRenderer3D *textRenderer3D; - ParticleRenderer *particleRenderer; - - //texture managers - ModelManager *modelManager[rsCount]; - TextureManager *textureManager[rsCount]; - FontManager *fontManager[rsCount]; - ParticleManager *particleManager[rsCount]; - - //state lists - //GLuint list3d; - //bool list3dValid; - //GLuint list2d; - //bool list2dValid; - //GLuint list3dMenu; - //bool list3dMenuValid; - //GLuint *customlist3dMenu; - //const MainMenu *mm3d; - const MainMenu *custom_mm3d; - - //shadows - GLuint shadowMapHandle; - bool shadowMapHandleValid; - - Matrix4f shadowMapMatrix; - int shadowMapFrame; - - //water - float waterAnim; - - bool allowRenderUnitTitles; - //std::vector > renderUnitTitleList; - std::vector visibleFrameUnitList; - string visibleFrameUnitListCameraKey; - - bool no2DMouseRendering; - bool showDebugUI; - int showDebugUILevel; - - int lastRenderFps; - float smoothedRenderFps; - bool shadowsOffDueToMinRender; - - std::vector > deferredParticleSystems; - - SimpleTaskThread *saveScreenShotThread; - Mutex *saveScreenShotThreadAccessor; - std::list > saveScreenQueue; - - std::map worldToScreenPosCache; - - //bool masterserverMode; - - std::map mapSurfaceVBOCache; - - class SurfaceData { - public: - inline SurfaceData() { - uniqueId=0; - bufferCount=0; - textureHandle=0; - } - static uint32 nextUniqueId; - uint32 uniqueId; - int bufferCount; - int textureHandle; - vector texCoords; - vector texCoordsSurface; - vector vertices; - vector normals; - }; - - //VisibleQuadContainerVBOCache * GetSurfaceVBOs(SurfaceData *cellData); - void ReleaseSurfaceVBOs(); - std::map > > mapSurfaceData; - static bool rendererEnded; - - class MapRenderer { - public: - inline MapRenderer(): map(NULL) {} - inline ~MapRenderer() { destroy(); } - void render(const Map* map,float coordStep,VisibleQuadContainerCache &qCache); - void renderVisibleLayers(const Map* map,float coordStep,VisibleQuadContainerCache &qCache); - void destroy(); - private: - void load(float coordStep); - void loadVisibleLayers(float coordStep,VisibleQuadContainerCache &qCache); - - const Map* map; - struct Layer { - inline explicit Layer(int th): - vbo_vertices(0), vbo_normals(0), - vbo_fowTexCoords(0), vbo_surfTexCoords(0), - vbo_indices(0), indexCount(0), - textureHandle(th),textureCRC(0) {} - - inline explicit Layer(Layer &obj) { - *this = obj; - } - - inline Layer & operator=(Layer &obj) { - this->vertices = obj.vertices; - this->normals = obj.normals; - this->fowTexCoords = obj.fowTexCoords; - this->surfTexCoords = obj.surfTexCoords; - this->indices = obj.indices; - this->cellToIndicesMap = obj.cellToIndicesMap; - this->rowsToRenderCache = obj.rowsToRenderCache; - this->vbo_vertices = obj.vbo_vertices; - this->vbo_normals = obj.vbo_normals; - this->vbo_fowTexCoords = obj.vbo_fowTexCoords; - this->vbo_surfTexCoords = obj.vbo_surfTexCoords; - this->vbo_indices = obj.vbo_indices; - this->indexCount = obj.indexCount; - this->textureHandle = obj.textureHandle; - this->texturePath = obj.texturePath; - this->textureCRC = obj.textureCRC; - - return *this; - } - - ~Layer(); - void load_vbos(bool vboEnabled); - void render(VisibleQuadContainerCache &qCache); - void renderVisibleLayer(); - - std::vector vertices, normals; - std::vector fowTexCoords, surfTexCoords; - std::vector indices; - std::map cellToIndicesMap; - std::map > > rowsToRenderCache; - - GLuint vbo_vertices, vbo_normals, - vbo_fowTexCoords, vbo_surfTexCoords, - vbo_indices; - int indexCount; - int textureHandle; - string texturePath; - uint32 textureCRC; - }; - typedef std::vector Layers; - Layers layers; - Quad2i lastVisibleQuad; - } mapRenderer; - - bool ExtractFrustum(VisibleQuadContainerCache &quadCacheItem); - //bool PointInFrustum(vector > &frustum, float x, float y, float z ); - //bool SphereInFrustum(vector > &frustum, float x, float y, float z, float radius); - bool CubeInFrustum(vector > &frustum, float x, float y, float z, float size ); + // config + int maxLights; + bool photoMode; + int shadowTextureSize; + int shadowFrameSkip; + float shadowIntensity; + bool focusArrows; + bool textures3D; + Shadows shadows; + int maxConsoleLines; + + // game + const Game *game; + GameCamera *gameCamera; + const MainMenu *menu; + Program *program; + + // misc + int triangleCount; + int pointCount; + Quad2i visibleQuad; + Quad2i visibleQuadFromCamera; + Vec4f nearestLightPos; + VisibleQuadContainerCache quadCache; + VisibleQuadContainerCache quadCacheSelection; + + // renderers + ModelRenderer *modelRenderer; + TextRenderer2D *textRenderer; + TextRenderer3D *textRenderer3D; + ParticleRenderer *particleRenderer; + + // texture managers + ModelManager *modelManager[rsCount]; + TextureManager *textureManager[rsCount]; + FontManager *fontManager[rsCount]; + ParticleManager *particleManager[rsCount]; + + // state lists + // GLuint list3d; + // bool list3dValid; + // GLuint list2d; + // bool list2dValid; + // GLuint list3dMenu; + // bool list3dMenuValid; + // GLuint *customlist3dMenu; + // const MainMenu *mm3d; + const MainMenu *custom_mm3d; + + // shadows + GLuint shadowMapHandle; + bool shadowMapHandleValid; + + Matrix4f shadowMapMatrix; + int shadowMapFrame; + + // water + float waterAnim; + + bool allowRenderUnitTitles; + // std::vector > renderUnitTitleList; + std::vector visibleFrameUnitList; + string visibleFrameUnitListCameraKey; + + bool no2DMouseRendering; + bool showDebugUI; + int showDebugUILevel; + + int lastRenderFps; + float smoothedRenderFps; + bool shadowsOffDueToMinRender; + + std::vector> + deferredParticleSystems; + + SimpleTaskThread *saveScreenShotThread; + Mutex *saveScreenShotThreadAccessor; + std::list> saveScreenQueue; + + std::map worldToScreenPosCache; + + // bool masterserverMode; + + std::map mapSurfaceVBOCache; + + class SurfaceData { + public: + inline SurfaceData() { + uniqueId = 0; + bufferCount = 0; + textureHandle = 0; + } + static uint32 nextUniqueId; + uint32 uniqueId; + int bufferCount; + int textureHandle; + vector texCoords; + vector texCoordsSurface; + vector vertices; + vector normals; + }; + + // VisibleQuadContainerVBOCache * GetSurfaceVBOs(SurfaceData *cellData); + void ReleaseSurfaceVBOs(); + std::map>> mapSurfaceData; + static bool rendererEnded; + + class MapRenderer { + public: + inline MapRenderer() : map(NULL) {} + inline ~MapRenderer() { destroy(); } + void render(const Map *map, float coordStep, + VisibleQuadContainerCache &qCache); + void renderVisibleLayers(const Map *map, float coordStep, + VisibleQuadContainerCache &qCache); + void destroy(); + + private: + void load(float coordStep); + void loadVisibleLayers(float coordStep, VisibleQuadContainerCache &qCache); + + const Map *map; + struct Layer { + inline explicit Layer(int th) + : vbo_vertices(0), vbo_normals(0), vbo_fowTexCoords(0), + vbo_surfTexCoords(0), vbo_indices(0), indexCount(0), + textureHandle(th), textureCRC(0) {} + + inline explicit Layer(Layer &obj) { *this = obj; } + + inline Layer &operator=(Layer &obj) { + this->vertices = obj.vertices; + this->normals = obj.normals; + this->fowTexCoords = obj.fowTexCoords; + this->surfTexCoords = obj.surfTexCoords; + this->indices = obj.indices; + this->cellToIndicesMap = obj.cellToIndicesMap; + this->rowsToRenderCache = obj.rowsToRenderCache; + this->vbo_vertices = obj.vbo_vertices; + this->vbo_normals = obj.vbo_normals; + this->vbo_fowTexCoords = obj.vbo_fowTexCoords; + this->vbo_surfTexCoords = obj.vbo_surfTexCoords; + this->vbo_indices = obj.vbo_indices; + this->indexCount = obj.indexCount; + this->textureHandle = obj.textureHandle; + this->texturePath = obj.texturePath; + this->textureCRC = obj.textureCRC; + + return *this; + } + + ~Layer(); + void load_vbos(bool vboEnabled); + void render(VisibleQuadContainerCache &qCache); + void renderVisibleLayer(); + + std::vector vertices, normals; + std::vector fowTexCoords, surfTexCoords; + std::vector indices; + std::map cellToIndicesMap; + std::map>> rowsToRenderCache; + + GLuint vbo_vertices, vbo_normals, vbo_fowTexCoords, vbo_surfTexCoords, + vbo_indices; + int indexCount; + int textureHandle; + string texturePath; + uint32 textureCRC; + }; + typedef std::vector Layers; + Layers layers; + Quad2i lastVisibleQuad; + } mapRenderer; + + bool ExtractFrustum(VisibleQuadContainerCache &quadCacheItem); + // bool PointInFrustum(vector > &frustum, float x, float y, + // float z ); bool SphereInFrustum(vector > &frustum, float x, + // float y, float z, float radius); + bool CubeInFrustum(vector> &frustum, float x, float y, float z, + float size); private: - Renderer(); - ~Renderer(); + Renderer(); + ~Renderer(); public: - static Renderer &getInstance(); - static bool isEnded(); - //bool isMasterserverMode() const { return masterserverMode; } - - void addToDeferredParticleSystemList(std::pair deferredParticleSystem); - void manageDeferredParticleSystems(); - - void reinitAll(); - - //init - void init(); - void initGame(const Game *game, GameCamera *gameCamera); - void initMenu(const MainMenu *mm); - void reset3d(); - void reset2d(); - void reset3dMenu(); - - //end - void end(); - void endScenario(); - void endMenu(); - void endGame(bool isFinalEnd); - - //get - inline int getTriangleCount() const {return triangleCount;} - inline int getPointCount() const {return pointCount;} - - //misc - //void reloadResources(); - - //engine interface - void initTexture(ResourceScope rs, Texture *texture); - void endTexture(ResourceScope rs, Texture *texture,bool mustExistInList=false); - void endLastTexture(ResourceScope rs, bool mustExistInList=false); - - Model *newModel(ResourceScope rs,const string &path,bool deletePixMapAfterLoad=false,std::map > > *loadedFileList=NULL, string *sourceLoader=NULL); - void endModel(ResourceScope rs, Model *model, bool mustExistInList=false); - void endLastModel(ResourceScope rs, bool mustExistInList=false); - - Texture2D *newTexture2D(ResourceScope rs); - Texture3D *newTexture3D(ResourceScope rs); - Font2D *newFont(ResourceScope rs); - Font3D *newFont3D(ResourceScope rs); - void endFont(::Shared::Graphics::Font *font, ResourceScope rs, bool mustExistInList=false); - //void resetFontManager(ResourceScope rs); - - inline TextRenderer2D *getTextRenderer() const {return textRenderer;} - inline TextRenderer3D *getTextRenderer3D() const {return textRenderer3D;} - - void manageParticleSystem(ParticleSystem *particleSystem, ResourceScope rs); - void cleanupParticleSystems(vector &particleSystems,ResourceScope rs); - void cleanupUnitParticleSystems(vector &particleSystems,ResourceScope rs); - bool validateParticleSystemStillExists(ParticleSystem * particleSystem,ResourceScope rs) const; - void removeParticleSystemsForParticleOwner(ParticleOwner * particleOwner,ResourceScope rs); - void updateParticleManager(ResourceScope rs,int renderFps=-1); - void renderParticleManager(ResourceScope rs); - void swapBuffers(); - - //lights and camera - void setupLighting(); - //void setupLightingForRotatedModel(); - void loadGameCameraMatrix(); - void loadCameraMatrix(const Camera *camera); - void computeVisibleQuad(); - - //basic rendering - void renderMouse2d(int mouseX, int mouseY, int anim, float fade= 0.f); - void renderMouse3d(); - - void renderGhostModel(const UnitType *building, const Vec2i pos,CardinalDir facing,Vec4f *forceColor=NULL); - - void renderBackground(const Texture2D *texture); - void renderTextureQuad(int x, int y, int w, int h, const Texture2D *texture, float alpha=1.f,const Vec3f *color=NULL); - void renderConsole(const Console *console, ConsoleMode mode=consoleNormal, int overrideMaxConsoleLines=-1); - void renderConsoleLine3D(int lineIndex, int xPosition, int yPosition, int lineHeight, Font3D* font, string stringToHightlight, const ConsoleLineInfo *lineInfo); - void renderConsoleLine(int lineIndex, int xPosition, int yPosition, int lineHeight, Font2D* font, string stringToHightlight, const ConsoleLineInfo *lineInfo); - - void renderChatManager(const ChatManager *chatManager); - void renderClock(); - void renderPerformanceStats(); - void renderResourceStatus(); - void renderSelectionQuad(); - void renderText(const string &text, Font2D *font, float alpha, int x, int y, bool centered= false); - void renderText(const string &text, Font2D *font, const Vec3f &color, int x, int y, bool centered= false); - void renderText(const string &text, Font2D *font, const Vec4f &color, int x, int y, bool centered=false); - void renderTextShadow(const string &text, Font2D *font,const Vec4f &color, int x, int y, bool centered= false); - - void renderText3D(const string &text, Font3D *font, float alpha, int x, int y, bool centered); - void renderText3D(const string &text, Font3D *font, const Vec3f &color, int x, int y, bool centered); - void renderText3D(const string &text, Font3D *font, const Vec4f &color, int x, int y, bool centered); - void renderTextShadow3D(const string &text, Font3D *font,const Vec4f &color, int x, int y, bool centered=false); - void renderProgressBar3D(int size, int x, int y, Font3D *font, int customWidth=-1, string prefixLabel="", bool centeredText=true,int customHeight=-1); - - Vec2f getCentered3DPos(const string &text, Font3D *font, Vec2f &pos, int w, int h, bool centeredW, bool centeredH); - void renderTextBoundingBox3D(const string &text, Font3D *font, const Vec4f &color, int x, int y, int w, int h, bool centeredW, bool centeredH, bool editModeEnabled, int maxEditWidth, int maxEditRenderWidth); - void renderTextBoundingBox3D(const string &text, Font3D *font, const Vec3f &color, int x, int y, int w, int h, bool centeredW, bool centeredH, bool editModeEnabled,int maxEditWidth, int maxEditRenderWidth); - void renderTextBoundingBox3D(const string &text, Font3D *font, float alpha, int x, int y, int w, int h, bool centeredW, bool centeredH, bool editModeEnabled,int maxEditWidth, int maxEditRenderWidth); - - void renderTextSurroundingBox(int x, int y, int w, int h,int maxEditWidth, int maxEditRenderWidth); - - void beginRenderToTexture(Texture2D **renderToTexture); - void endRenderToTexture(Texture2D **renderToTexture); - - void renderFPSWhenEnabled(int lastFps); - - //components - void renderLabel(GraphicLabel *label); - void renderLabel(GraphicLabel *label,const Vec3f *color); - void renderLabel(GraphicLabel *label,const Vec4f *color); - void renderButton(GraphicButton *button,const Vec4f *fontColorOverride=NULL,bool *lightedOverride=NULL); - void renderCheckBox(const GraphicCheckBox *box); - void renderLine(const GraphicLine *line); - void renderScrollBar(const GraphicScrollBar *sb); - void renderListBox(GraphicListBox *listBox); - void renderComboBox(GraphicComboBox *comboBox); - void renderMessageBox(GraphicMessageBox *listBox); - void renderPopupMenu(PopupMenu *menu); - - //complex rendering - void renderSurface(const int renderFps); - void renderObjects(const int renderFps); - - void renderWater(); - void renderUnits(bool airUnits, const int renderFps); - void renderUnitsToBuild(const int renderFps); - - void renderSelectionEffects(int healthbarMode); - void renderHealthBars(int healthbarMode); - void renderWaterEffects(); - void renderHud(); - void renderMinimap(); - void renderDisplay(); - void renderMenuBackground(const MenuBackground *menuBackground); - void renderMapPreview(const MapPreview *map, bool renderAll, int screenX, int screenY,Texture2D **renderToTexture=NULL); - void renderMenuBackground(Camera *camera, float fade, Model *mainModel, vector characterModels,const Vec3f characterPosition, float anim); - - //computing - bool ccomputePosition(const Vec2i &screenPos, Vec2i &worldPos,bool exactCoords=false); - void computeSelected(Selection::UnitContainer &units, const Object *&obj, const bool withObjectSelection, const Vec2i &posDown, const Vec2i &posUp); - void selectUsingColorPicking(Selection::UnitContainer &units, const Object *&obj,const bool withObjectSelection,const Vec2i &posDown, const Vec2i &posUp); - void selectUsingSelectionBuffer(Selection::UnitContainer &units,const Object *&obj, const bool withObjectSelection,const Vec2i &posDown, const Vec2i &posUp); - void selectUsingFrustumSelection(Selection::UnitContainer &units,const Object *&obj, const bool withObjectSelection,const Vec2i &posDown, const Vec2i &posUp); - - - //gl wrap - string getGlInfo(); - string getGlMoreInfo(); - void autoConfig(); - - //clear - void clearBuffers(); - void clearZBuffer(); - - //shadows - void renderShadowsToTexture(const int renderFps); - - //misc - void loadConfig(); - void saveScreen(const string &path,int w=0, int h=0); - inline Quad2i getVisibleQuad() const {return visibleQuad;} - inline Quad2i getVisibleQuadFromCamera() const {return visibleQuadFromCamera;} - void renderTeamColorPlane(); - void renderSpecialHighlightUnits(std::map unitHighlightList); - void renderTeamColorCircle(); - void renderMorphEffects(); - - //static - static Shadows strToShadows(const string &s); - static string shadowsToStr(Shadows shadows); - - inline const Game * getGame() { return game; } - - void setAllowRenderUnitTitles(bool value); - inline bool getAllowRenderUnitTitles() { return allowRenderUnitTitles; } - void renderUnitTitles(Font2D *font, Vec3f color); - void renderUnitTitles3D(Font3D *font, Vec3f color); - Vec3f computeScreenPosition(const Vec3f &worldPos); - - void setPhotoMode(bool value) { photoMode = value; } - - inline bool getNo2DMouseRendering() const { return no2DMouseRendering; } - void setNo2DMouseRendering(bool value) { no2DMouseRendering = value; } - - inline bool getShowDebugUI() const { return showDebugUI; } - void setShowDebugUI(bool value) { showDebugUI = value; } - - inline int getShowDebugUILevel() const { return showDebugUILevel; } - void setShowDebugUILevel(int value) { showDebugUILevel=value; } - void cycleShowDebugUILevel(); - - void setLastRenderFps(int value); - inline int getLastRenderFps() const { return lastRenderFps;} - - VisibleQuadContainerCache & getQuadCache(bool updateOnDirtyFrame=true,bool forceNew=false); - std::pair posInCellQuadCache(Vec2i pos); - //Vec3f getMarkedCellScreenPosQuadCache(Vec2i pos); - void updateMarkedCellScreenPosQuadCache(Vec2i pos); - void forceQuadCacheUpdate(); - void renderVisibleMarkedCells(bool renderTextHint=false,int x=-1, int y=-1); - void renderMarkedCellsOnMinimap(); - - void renderHighlightedCellsOnMinimap(); - - void removeObjectFromQuadCache(const Object *o); - void removeUnitFromQuadCache(const Unit *unit); - - std::size_t getCurrentPixelByteCount(ResourceScope rs=rsGame) const; - unsigned int getSaveScreenQueueSize(); - - //Texture2D *saveScreenToTexture(int x, int y, int width, int height); - - void renderProgressBar(int size, int x, int y, Font2D *font,int customWidth=-1, string prefixLabel="", bool centeredText=true); - - static Texture2D * findTexture(string logoFilename); - static Texture2D * preloadTexture(string logoFilename); - inline int getCachedSurfaceDataSize() const { return (int)mapSurfaceData.size(); } - - //void setCustom3dMenuList(GLuint *customlist3dMenu) { this->customlist3dMenu = customlist3dMenu; } - //inline GLuint * getCustom3dMenuList() const { return this->customlist3dMenu; } - void setCustom3dMenu(const MainMenu *mm) { this->custom_mm3d = mm; } - const MainMenu * getCustom3dMenu() { return this->custom_mm3d; } - - //void init3dListMenu(const MainMenu *mm); - - void setProgram(Program *program) { this->program = program; } - - void setupRenderForVideo(); - virtual void renderVideoLoading(int progressPercent); + static Renderer &getInstance(); + static bool isEnded(); + // bool isMasterserverMode() const { return masterserverMode; } + + void addToDeferredParticleSystemList( + std::pair deferredParticleSystem); + void manageDeferredParticleSystems(); + + void reinitAll(); + + // init + void init(); + void initGame(const Game *game, GameCamera *gameCamera); + void initMenu(const MainMenu *mm); + void reset3d(); + void reset2d(); + void reset3dMenu(); + + // end + void end(); + void endScenario(); + void endMenu(); + void endGame(bool isFinalEnd); + + // get + inline int getTriangleCount() const { return triangleCount; } + inline int getPointCount() const { return pointCount; } + + // misc + // void reloadResources(); + + // engine interface + void initTexture(ResourceScope rs, Texture *texture); + void endTexture(ResourceScope rs, Texture *texture, + bool mustExistInList = false); + void endLastTexture(ResourceScope rs, bool mustExistInList = false); + + Model *newModel( + ResourceScope rs, const string &path, bool deletePixMapAfterLoad = false, + std::map>> *loadedFileList = NULL, + string *sourceLoader = NULL); + void endModel(ResourceScope rs, Model *model, bool mustExistInList = false); + void endLastModel(ResourceScope rs, bool mustExistInList = false); + + Texture2D *newTexture2D(ResourceScope rs); + Texture3D *newTexture3D(ResourceScope rs); + Font2D *newFont(ResourceScope rs); + Font3D *newFont3D(ResourceScope rs); + void endFont(::Shared::Graphics::Font *font, ResourceScope rs, + bool mustExistInList = false); + // void resetFontManager(ResourceScope rs); + + inline TextRenderer2D *getTextRenderer() const { return textRenderer; } + inline TextRenderer3D *getTextRenderer3D() const { return textRenderer3D; } + + void manageParticleSystem(ParticleSystem *particleSystem, ResourceScope rs); + void cleanupParticleSystems(vector &particleSystems, + ResourceScope rs); + void cleanupUnitParticleSystems(vector &particleSystems, + ResourceScope rs); + bool validateParticleSystemStillExists(ParticleSystem *particleSystem, + ResourceScope rs) const; + void removeParticleSystemsForParticleOwner(ParticleOwner *particleOwner, + ResourceScope rs); + void updateParticleManager(ResourceScope rs, int renderFps = -1); + void renderParticleManager(ResourceScope rs); + void swapBuffers(); + + // lights and camera + void setupLighting(); + // void setupLightingForRotatedModel(); + void loadGameCameraMatrix(); + void loadCameraMatrix(const Camera *camera); + void computeVisibleQuad(); + + // basic rendering + void renderMouse2d(int mouseX, int mouseY, int anim, float fade = 0.f); + void renderMouse3d(); + + void renderGhostModel(const UnitType *building, const Vec2i pos, + CardinalDir facing, Vec4f *forceColor = NULL); + + void renderBackground(const Texture2D *texture); + void renderTextureQuad(int x, int y, int w, int h, const Texture2D *texture, + float alpha = 1.f, const Vec3f *color = NULL); + void renderConsole(const Console *console, ConsoleMode mode = consoleNormal, + int overrideMaxConsoleLines = -1); + void renderConsoleLine3D(int lineIndex, int xPosition, int yPosition, + int lineHeight, Font3D *font, + string stringToHightlight, + const ConsoleLineInfo *lineInfo); + void renderConsoleLine(int lineIndex, int xPosition, int yPosition, + int lineHeight, Font2D *font, + string stringToHightlight, + const ConsoleLineInfo *lineInfo); + + void renderChatManager(const ChatManager *chatManager); + void renderClock(); + void renderPerformanceStats(); + void renderResourceStatus(); + void renderSelectionQuad(); + void renderText(const string &text, Font2D *font, float alpha, int x, int y, + bool centered = false); + void renderText(const string &text, Font2D *font, const Vec3f &color, int x, + int y, bool centered = false); + void renderText(const string &text, Font2D *font, const Vec4f &color, int x, + int y, bool centered = false); + void renderTextShadow(const string &text, Font2D *font, const Vec4f &color, + int x, int y, bool centered = false); + + void renderText3D(const string &text, Font3D *font, float alpha, int x, int y, + bool centered); + void renderText3D(const string &text, Font3D *font, const Vec3f &color, int x, + int y, bool centered); + void renderText3D(const string &text, Font3D *font, const Vec4f &color, int x, + int y, bool centered); + void renderTextShadow3D(const string &text, Font3D *font, const Vec4f &color, + int x, int y, bool centered = false); + void renderProgressBar3D(int size, int x, int y, Font3D *font, + int customWidth = -1, string prefixLabel = "", + bool centeredText = true, int customHeight = -1); + + Vec2f getCentered3DPos(const string &text, Font3D *font, Vec2f &pos, int w, + int h, bool centeredW, bool centeredH); + void renderTextBoundingBox3D(const string &text, Font3D *font, + const Vec4f &color, int x, int y, int w, int h, + bool centeredW, bool centeredH, + bool editModeEnabled, int maxEditWidth, + int maxEditRenderWidth); + void renderTextBoundingBox3D(const string &text, Font3D *font, + const Vec3f &color, int x, int y, int w, int h, + bool centeredW, bool centeredH, + bool editModeEnabled, int maxEditWidth, + int maxEditRenderWidth); + void renderTextBoundingBox3D(const string &text, Font3D *font, float alpha, + int x, int y, int w, int h, bool centeredW, + bool centeredH, bool editModeEnabled, + int maxEditWidth, int maxEditRenderWidth); + + void renderTextSurroundingBox(int x, int y, int w, int h, int maxEditWidth, + int maxEditRenderWidth); + + void beginRenderToTexture(Texture2D **renderToTexture); + void endRenderToTexture(Texture2D **renderToTexture); + + void renderFPSWhenEnabled(int lastFps); + + // components + void renderLabel(GraphicLabel *label); + void renderLabel(GraphicLabel *label, const Vec3f *color); + void renderLabel(GraphicLabel *label, const Vec4f *color); + void renderButton(GraphicButton *button, + const Vec4f *fontColorOverride = NULL, + bool *lightedOverride = NULL); + void renderCheckBox(const GraphicCheckBox *box); + void renderLine(const GraphicLine *line); + void renderScrollBar(const GraphicScrollBar *sb); + void renderListBox(GraphicListBox *listBox); + void renderComboBox(GraphicComboBox *comboBox); + void renderMessageBox(GraphicMessageBox *listBox); + void renderPopupMenu(PopupMenu *menu); + + // complex rendering + void renderSurface(const int renderFps); + void renderObjects(const int renderFps); + + void renderWater(); + void renderUnits(bool airUnits, const int renderFps); + void renderUnitsToBuild(const int renderFps); + + void renderSelectionEffects(int healthbarMode); + void renderHealthBars(int healthbarMode); + void renderWaterEffects(); + void renderHud(); + void renderMinimap(); + void renderDisplay(); + void renderMenuBackground(const MenuBackground *menuBackground); + void renderMapPreview(const MapPreview *map, bool renderAll, int screenX, + int screenY, Texture2D **renderToTexture = NULL); + void renderMenuBackground(Camera *camera, float fade, Model *mainModel, + vector characterModels, + const Vec3f characterPosition, float anim); + + // computing + bool ccomputePosition(const Vec2i &screenPos, Vec2i &worldPos, + bool exactCoords = false); + void computeSelected(Selection::UnitContainer &units, const Object *&obj, + const bool withObjectSelection, const Vec2i &posDown, + const Vec2i &posUp); + void selectUsingColorPicking(Selection::UnitContainer &units, + const Object *&obj, + const bool withObjectSelection, + const Vec2i &posDown, const Vec2i &posUp); + void selectUsingSelectionBuffer(Selection::UnitContainer &units, + const Object *&obj, + const bool withObjectSelection, + const Vec2i &posDown, const Vec2i &posUp); + void selectUsingFrustumSelection(Selection::UnitContainer &units, + const Object *&obj, + const bool withObjectSelection, + const Vec2i &posDown, const Vec2i &posUp); + + // gl wrap + string getGlInfo(); + string getGlMoreInfo(); + void autoConfig(); + + // clear + void clearBuffers(); + void clearZBuffer(); + + // shadows + void renderShadowsToTexture(const int renderFps); + + // misc + void loadConfig(); + void saveScreen(const string &path, int w = 0, int h = 0); + inline Quad2i getVisibleQuad() const { return visibleQuad; } + inline Quad2i getVisibleQuadFromCamera() const { + return visibleQuadFromCamera; + } + void renderTeamColorPlane(); + void renderSpecialHighlightUnits( + std::map unitHighlightList); + void renderTeamColorCircle(); + void renderMorphEffects(); + + // static + static Shadows strToShadows(const string &s); + static string shadowsToStr(Shadows shadows); + + inline const Game *getGame() { return game; } + + void setAllowRenderUnitTitles(bool value); + inline bool getAllowRenderUnitTitles() { return allowRenderUnitTitles; } + void renderUnitTitles(Font2D *font, Vec3f color); + void renderUnitTitles3D(Font3D *font, Vec3f color); + Vec3f computeScreenPosition(const Vec3f &worldPos); + + void setPhotoMode(bool value) { photoMode = value; } + + inline bool getNo2DMouseRendering() const { return no2DMouseRendering; } + void setNo2DMouseRendering(bool value) { no2DMouseRendering = value; } + + inline bool getShowDebugUI() const { return showDebugUI; } + void setShowDebugUI(bool value) { showDebugUI = value; } + + inline int getShowDebugUILevel() const { return showDebugUILevel; } + void setShowDebugUILevel(int value) { showDebugUILevel = value; } + void cycleShowDebugUILevel(); + + void setLastRenderFps(int value); + inline int getLastRenderFps() const { return lastRenderFps; } + + VisibleQuadContainerCache &getQuadCache(bool updateOnDirtyFrame = true, + bool forceNew = false); + std::pair posInCellQuadCache(Vec2i pos); + // Vec3f getMarkedCellScreenPosQuadCache(Vec2i pos); + void updateMarkedCellScreenPosQuadCache(Vec2i pos); + void forceQuadCacheUpdate(); + void renderVisibleMarkedCells(bool renderTextHint = false, int x = -1, + int y = -1); + void renderMarkedCellsOnMinimap(); + + void renderHighlightedCellsOnMinimap(); + + void removeObjectFromQuadCache(const Object *o); + void removeUnitFromQuadCache(const Unit *unit); + + std::size_t getCurrentPixelByteCount(ResourceScope rs = rsGame) const; + unsigned int getSaveScreenQueueSize(); + + // Texture2D *saveScreenToTexture(int x, int y, int width, int height); + + void renderProgressBar(int size, int x, int y, Font2D *font, + int customWidth = -1, string prefixLabel = "", + bool centeredText = true); + + static Texture2D *findTexture(string logoFilename); + static Texture2D *preloadTexture(string logoFilename); + inline int getCachedSurfaceDataSize() const { + return (int)mapSurfaceData.size(); + } + + // void setCustom3dMenuList(GLuint *customlist3dMenu) { this->customlist3dMenu + // = customlist3dMenu; } inline GLuint * getCustom3dMenuList() const { return + // this->customlist3dMenu; } + void setCustom3dMenu(const MainMenu *mm) { this->custom_mm3d = mm; } + const MainMenu *getCustom3dMenu() { return this->custom_mm3d; } + + // void init3dListMenu(const MainMenu *mm); + + void setProgram(Program *program) { this->program = program; } + + void setupRenderForVideo(); + virtual void renderVideoLoading(int progressPercent); private: - //private misc - float computeSunAngle(float time); - float computeMoonAngle(float time); - Vec4f computeSunPos(float time); - Vec4f computeMoonPos(float time); - inline Vec4f computeWaterColor(float waterLevel, float cellHeight) { - const float waterFactor= 1.5f; - return Vec4f(1.f, 1.f, 1.f, clamp((waterLevel-cellHeight) * waterFactor, 0.f, 1.f)); - } - void checkExtension(const string &extension, const string &msg); - - //selection render - vector renderObjectsFast(bool renderingShadows = false, bool resourceOnly = false, bool colorPickingSelection = false); - vector renderUnitsFast(bool renderingShadows = false, bool colorPickingSelection = false); - - //gl requirements - void checkGlCaps(); - void checkGlOptionalCaps(); - - //gl init - void init3dList(); - void init2dList(); - - //misc - void loadProjectionMatrix(); - void enableProjectiveTexturing(); - - //private aux drawing - void renderSelectionCircle(Vec3f v, int size, float radius, float thickness=0.2f); - bool isHealthBarVisible(const Unit *unit,int healthbarMode); - void renderHealthBar(Vec3f v, Unit *unit, float height, bool lineBorder, const Texture2D *texture=NULL, const Texture2D *backgroundTexture=NULL); - void internalRenderHp(int numberOfBars, int barNumber, float hp, Vec3f posVector, float width, float singleHPheight, Vec3f rightVector, Vec3f upVector); - void renderTeamColorEffect(Vec3f &v, int heigth, int size, Vec3f color, const Texture2D *texture); - void renderArrow(const Vec3f &pos1, const Vec3f &pos2, const Vec3f &color, float width); - //void renderTile(const Vec2i &pos); - void renderQuad(int x, int y, int w, int h, const Texture2D *texture); - - void simpleTask(BaseThread *callingThread,void *userdata); - - //static - static Texture2D::Filter strToTextureFilter(const string &s); - void cleanupScreenshotThread(); - - void render2dMenuSetup(); - void render3dSetup(); - void render3dMenuSetup(const MainMenu *mm); - - int renderResource(const Faction *factionForResourceView, - bool localFactionResourcesOnly,bool twoResourceLines, const ResourceType *rt, - int startRow, int &resourceCountRendered); - + // private misc + float computeSunAngle(float time); + float computeMoonAngle(float time); + Vec4f computeSunPos(float time); + Vec4f computeMoonPos(float time); + inline Vec4f computeWaterColor(float waterLevel, float cellHeight) { + const float waterFactor = 1.5f; + return Vec4f(1.f, 1.f, 1.f, + clamp((waterLevel - cellHeight) * waterFactor, 0.f, 1.f)); + } + void checkExtension(const string &extension, const string &msg); + + // selection render + vector renderObjectsFast(bool renderingShadows = false, + bool resourceOnly = false, + bool colorPickingSelection = false); + vector renderUnitsFast(bool renderingShadows = false, + bool colorPickingSelection = false); + + // gl requirements + void checkGlCaps(); + void checkGlOptionalCaps(); + + // gl init + void init3dList(); + void init2dList(); + + // misc + void loadProjectionMatrix(); + void enableProjectiveTexturing(); + + // private aux drawing + void renderSelectionCircle(Vec3f v, int size, float radius, + float thickness = 0.2f); + bool isHealthBarVisible(const Unit *unit, int healthbarMode); + void renderHealthBar(Vec3f v, Unit *unit, float height, bool lineBorder, + const Texture2D *texture = NULL, + const Texture2D *backgroundTexture = NULL); + void internalRenderHp(int numberOfBars, int barNumber, float hp, + Vec3f posVector, float width, float singleHPheight, + Vec3f rightVector, Vec3f upVector); + void renderTeamColorEffect(Vec3f &v, int heigth, int size, Vec3f color, + const Texture2D *texture); + void renderArrow(const Vec3f &pos1, const Vec3f &pos2, const Vec3f &color, + float width); + // void renderTile(const Vec2i &pos); + void renderQuad(int x, int y, int w, int h, const Texture2D *texture); + + void simpleTask(BaseThread *callingThread, void *userdata); + + // static + static Texture2D::Filter strToTextureFilter(const string &s); + void cleanupScreenshotThread(); + + void render2dMenuSetup(); + void render3dSetup(); + void render3dMenuSetup(const MainMenu *mm); + + int renderResource(const Faction *factionForResourceView, + bool localFactionResourcesOnly, bool twoResourceLines, + const ResourceType *rt, int startRow, + int &resourceCountRendered); }; -}} //end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/graphics/unit_particle_type.cpp b/source/glest_game/graphics/unit_particle_type.cpp index 0deeefd3f..40e84278c 100644 --- a/source/glest_game/graphics/unit_particle_type.cpp +++ b/source/glest_game/graphics/unit_particle_type.cpp @@ -3,382 +3,448 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== #include "unit_particle_type.h" -#include "util.h" -#include "core_data.h" -#include "xml_parser.h" #include "config.h" -#include "game_constants.h" -#include "platform_common.h" #include "conversion.h" +#include "core_data.h" +#include "game_constants.h" #include "leak_dumper.h" +#include "platform_common.h" +#include "util.h" +#include "xml_parser.h" using namespace Shared::Xml; using namespace Shared::Graphics; using namespace Shared::Util; using namespace Shared::PlatformCommon; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class UnitParticleSystemType // ===================================================== UnitParticleSystemType::UnitParticleSystemType() : ParticleSystemType() { - shape = UnitParticleSystem::sLinear; - angle = 0; - radius = 0; - minRadius = 0; - emissionRateFade = 0; - relative = false; - meshName = ""; - relativeDirection = false; - fixed = false; - staticParticleCount = 0; - isVisibleAtNight = true; - isVisibleAtDay = true; - isDaylightAffected = false; - radiusBasedStartenergy = false; - delay = 0; - lifetime = 0; - startTime = 0; - endTime = 1; + shape = UnitParticleSystem::sLinear; + angle = 0; + radius = 0; + minRadius = 0; + emissionRateFade = 0; + relative = false; + meshName = ""; + relativeDirection = false; + fixed = false; + staticParticleCount = 0; + isVisibleAtNight = true; + isVisibleAtDay = true; + isDaylightAffected = false; + radiusBasedStartenergy = false; + delay = 0; + lifetime = 0; + startTime = 0; + endTime = 1; } -void UnitParticleSystemType::load(const XmlNode *particleSystemNode, const string &dir, - RendererInterface *renderer, std::map > > &loadedFileList, - string parentLoader, string techtreePath) { - - ParticleSystemType::load(particleSystemNode, dir, renderer, loadedFileList, - parentLoader,techtreePath); - - //shape - angle= 0.0f; - if(particleSystemNode->hasChild("shape")){ - const XmlNode *shapeNode= particleSystemNode->getChild("shape"); - shape= UnitParticleSystem::strToShape(shapeNode->getAttribute("value")->getRestrictedValue()); - if(shape == UnitParticleSystem::sConical){ - angle= shapeNode->getChild("angle")->getAttribute("value")->getFloatValue(); - } - } else { - shape = UnitParticleSystem::sLinear; - } - if(shape != UnitParticleSystem::sSpherical){ - //direction - const XmlNode *directionNode= particleSystemNode->getChild("direction"); - direction.x= directionNode->getAttribute("x")->getFloatValue(); - direction.y= directionNode->getAttribute("y")->getFloatValue(); - direction.z= directionNode->getAttribute("z")->getFloatValue(); - if((shape == UnitParticleSystem::sConical) && (0.0 == direction.length())) - throw megaglest_runtime_error("direction cannot be zero"); - // ought to warn about 0 directions generally - } - - //emission rate fade - if(particleSystemNode->hasChild("emission-rate-fade")){ - const XmlNode *emissionRateFadeNode= particleSystemNode->getChild("emission-rate-fade"); - emissionRateFade= emissionRateFadeNode->getAttribute("value")->getFloatValue(); - } else { - emissionRateFade = 0; - } - - //radius - const XmlNode *radiusNode= particleSystemNode->getChild("radius"); - radius= radiusNode->getAttribute("value")->getFloatValue(); - - // min radius - if(particleSystemNode->hasChild("min-radius")){ - const XmlNode *minRadiusNode= particleSystemNode->getChild("min-radius"); - minRadius= minRadiusNode->getAttribute("value")->getFloatValue(); - if(minRadius > radius) - throw megaglest_runtime_error("min-radius cannot be bigger than radius"); - } else { - minRadius = 0; - } - if((minRadius == 0) && (shape == UnitParticleSystem::sConical)) { - minRadius = 0.001f; // fudge it so we aren't generating particles that are exactly centred - if(minRadius > radius) - radius = minRadius; - } - - //relative - const XmlNode *relativeNode= particleSystemNode->getChild("relative"); - relative= relativeNode->getAttribute("value")->getBoolValue(); - - - //meshName - if(particleSystemNode->hasChild("meshName")){ - const XmlNode *tmpNode= particleSystemNode->getChild("meshName"); - meshName= tmpNode->getAttribute("value")->getValue(); - } - else{ - meshName=""; - } - - //relativeDirection - if(particleSystemNode->hasChild("relativeDirection")){ - const XmlNode *relativeDirectionNode= particleSystemNode->getChild("relativeDirection"); - relativeDirection= relativeDirectionNode->getAttribute("value")->getBoolValue(); - } - else{ - relativeDirection=true; - } +void UnitParticleSystemType::load( + const XmlNode *particleSystemNode, const string &dir, + RendererInterface *renderer, + std::map>> &loadedFileList, + string parentLoader, string techtreePath) { - if(particleSystemNode->hasChild("static-particle-count")){ - //staticParticleCount - const XmlNode *staticParticleCountNode= particleSystemNode->getChild("static-particle-count"); - staticParticleCount= staticParticleCountNode->getAttribute("value")->getIntValue(); - } - else{ - staticParticleCount=0; + ParticleSystemType::load(particleSystemNode, dir, renderer, loadedFileList, + parentLoader, techtreePath); + + // shape + angle = 0.0f; + if (particleSystemNode->hasChild("shape")) { + const XmlNode *shapeNode = particleSystemNode->getChild("shape"); + shape = UnitParticleSystem::strToShape( + shapeNode->getAttribute("value")->getRestrictedValue()); + if (shape == UnitParticleSystem::sConical) { + angle = + shapeNode->getChild("angle")->getAttribute("value")->getFloatValue(); } - - //isVisibleAtNight - if(particleSystemNode->hasChild("isVisibleAtNight")){ - const XmlNode *isVisibleAtNightNode= particleSystemNode->getChild("isVisibleAtNight"); - isVisibleAtNight= isVisibleAtNightNode->getAttribute("value")->getBoolValue(); - } - else { - isVisibleAtNight=true; - } - - //isVisibleAtDay - if(particleSystemNode->hasChild("isVisibleAtDay")){ - const XmlNode *isVisibleAtDayNode= particleSystemNode->getChild("isVisibleAtDay"); - isVisibleAtDay= isVisibleAtDayNode->getAttribute("value")->getBoolValue(); - } - else { - isVisibleAtDay=true; - } - - //isDaylightAffected - if(particleSystemNode->hasChild("isDaylightAffected")){ - const XmlNode *node= particleSystemNode->getChild("isDaylightAffected"); - isDaylightAffected= node->getAttribute("value")->getBoolValue(); - } - else { - isDaylightAffected=false; - } - - //radiusBasedStartenergy - if(particleSystemNode->hasChild("radiusBasedStartenergy")){ - const XmlNode *isVisibleAtDayNode= particleSystemNode->getChild("radiusBasedStartenergy"); - radiusBasedStartenergy= isVisibleAtDayNode->getAttribute("value")->getBoolValue(); - } - else{ - radiusBasedStartenergy= true; - } - - //fixed - const XmlNode *fixedNode= particleSystemNode->getChild("fixed"); - fixed= fixedNode->getAttribute("value")->getBoolValue(); - - // delay - if(particleSystemNode->hasChild("delay")) { - const XmlNode* delayNode = particleSystemNode->getChild("delay"); - const float delay_secs = delayNode->getAttribute("value")->getFloatValue(); - if(delay_secs < 0) - throw megaglest_runtime_error("particle effect delay cannot be negative"); - delay = (int)delay_secs * GameConstants::updateFps; - } else{ - delay= 0; - } - - // lifetime - if(particleSystemNode->hasChild("lifetime")) { - const XmlNode* lifetimeNode = particleSystemNode->getChild("lifetime"); - const float lifetime_secs = lifetimeNode->getAttribute("value")->getFloatValue(); - if(lifetime_secs < 0 && lifetime_secs != -1) - throw megaglest_runtime_error("particle effect lifetime cannot be negative (-1 means inherited from parent particle)"); - lifetime = (int)lifetime_secs * GameConstants::updateFps; - } else{ - lifetime= -1; //default - } + } else { + shape = UnitParticleSystem::sLinear; + } + if (shape != UnitParticleSystem::sSpherical) { + // direction + const XmlNode *directionNode = particleSystemNode->getChild("direction"); + direction.x = directionNode->getAttribute("x")->getFloatValue(); + direction.y = directionNode->getAttribute("y")->getFloatValue(); + direction.z = directionNode->getAttribute("z")->getFloatValue(); + if ((shape == UnitParticleSystem::sConical) && (0.0 == direction.length())) + throw megaglest_runtime_error("direction cannot be zero"); + // ought to warn about 0 directions generally + } + + // emission rate fade + if (particleSystemNode->hasChild("emission-rate-fade")) { + const XmlNode *emissionRateFadeNode = + particleSystemNode->getChild("emission-rate-fade"); + emissionRateFade = + emissionRateFadeNode->getAttribute("value")->getFloatValue(); + } else { + emissionRateFade = 0; + } + + // radius + const XmlNode *radiusNode = particleSystemNode->getChild("radius"); + radius = radiusNode->getAttribute("value")->getFloatValue(); + + // min radius + if (particleSystemNode->hasChild("min-radius")) { + const XmlNode *minRadiusNode = particleSystemNode->getChild("min-radius"); + minRadius = minRadiusNode->getAttribute("value")->getFloatValue(); + if (minRadius > radius) + throw megaglest_runtime_error("min-radius cannot be bigger than radius"); + } else { + minRadius = 0; + } + if ((minRadius == 0) && (shape == UnitParticleSystem::sConical)) { + minRadius = 0.001f; // fudge it so we aren't generating particles that are + // exactly centred + if (minRadius > radius) + radius = minRadius; + } + + // relative + const XmlNode *relativeNode = particleSystemNode->getChild("relative"); + relative = relativeNode->getAttribute("value")->getBoolValue(); + + // meshName + if (particleSystemNode->hasChild("meshName")) { + const XmlNode *tmpNode = particleSystemNode->getChild("meshName"); + meshName = tmpNode->getAttribute("value")->getValue(); + } else { + meshName = ""; + } + + // relativeDirection + if (particleSystemNode->hasChild("relativeDirection")) { + const XmlNode *relativeDirectionNode = + particleSystemNode->getChild("relativeDirection"); + relativeDirection = + relativeDirectionNode->getAttribute("value")->getBoolValue(); + } else { + relativeDirection = true; + } + + if (particleSystemNode->hasChild("static-particle-count")) { + // staticParticleCount + const XmlNode *staticParticleCountNode = + particleSystemNode->getChild("static-particle-count"); + staticParticleCount = + staticParticleCountNode->getAttribute("value")->getIntValue(); + } else { + staticParticleCount = 0; + } + + // isVisibleAtNight + if (particleSystemNode->hasChild("isVisibleAtNight")) { + const XmlNode *isVisibleAtNightNode = + particleSystemNode->getChild("isVisibleAtNight"); + isVisibleAtNight = + isVisibleAtNightNode->getAttribute("value")->getBoolValue(); + } else { + isVisibleAtNight = true; + } + + // isVisibleAtDay + if (particleSystemNode->hasChild("isVisibleAtDay")) { + const XmlNode *isVisibleAtDayNode = + particleSystemNode->getChild("isVisibleAtDay"); + isVisibleAtDay = isVisibleAtDayNode->getAttribute("value")->getBoolValue(); + } else { + isVisibleAtDay = true; + } + + // isDaylightAffected + if (particleSystemNode->hasChild("isDaylightAffected")) { + const XmlNode *node = particleSystemNode->getChild("isDaylightAffected"); + isDaylightAffected = node->getAttribute("value")->getBoolValue(); + } else { + isDaylightAffected = false; + } + + // radiusBasedStartenergy + if (particleSystemNode->hasChild("radiusBasedStartenergy")) { + const XmlNode *isVisibleAtDayNode = + particleSystemNode->getChild("radiusBasedStartenergy"); + radiusBasedStartenergy = + isVisibleAtDayNode->getAttribute("value")->getBoolValue(); + } else { + radiusBasedStartenergy = true; + } + + // fixed + const XmlNode *fixedNode = particleSystemNode->getChild("fixed"); + fixed = fixedNode->getAttribute("value")->getBoolValue(); + + // delay + if (particleSystemNode->hasChild("delay")) { + const XmlNode *delayNode = particleSystemNode->getChild("delay"); + const float delay_secs = delayNode->getAttribute("value")->getFloatValue(); + if (delay_secs < 0) + throw megaglest_runtime_error("particle effect delay cannot be negative"); + delay = (int)delay_secs * GameConstants::updateFps; + } else { + delay = 0; + } + + // lifetime + if (particleSystemNode->hasChild("lifetime")) { + const XmlNode *lifetimeNode = particleSystemNode->getChild("lifetime"); + const float lifetime_secs = + lifetimeNode->getAttribute("value")->getFloatValue(); + if (lifetime_secs < 0 && lifetime_secs != -1) + throw megaglest_runtime_error( + "particle effect lifetime cannot be negative (-1 means inherited " + "from parent particle)"); + lifetime = (int)lifetime_secs * GameConstants::updateFps; + } else { + lifetime = -1; // default + } } -ObjectParticleSystemType::ObjectParticleSystemType() : UnitParticleSystemType() { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s Line: %d] NEW [%p]\n",__FUNCTION__,__LINE__,this); +ObjectParticleSystemType::ObjectParticleSystemType() + : UnitParticleSystemType() { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s Line: %d] NEW [%p]\n", __FUNCTION__, __LINE__, this); } ObjectParticleSystemType::~ObjectParticleSystemType() { - if(SystemFlags::VERBOSE_MODE_ENABLED) { - printf("In [%s Line: %d] NEW [%p]\n",__FUNCTION__,__LINE__,this); - //printf("%s\n",PlatformExceptionHandler::getStackTrace().c_str()); - } + if (SystemFlags::VERBOSE_MODE_ENABLED) { + printf("In [%s Line: %d] NEW [%p]\n", __FUNCTION__, __LINE__, this); + // printf("%s\n",PlatformExceptionHandler::getStackTrace().c_str()); + } } -const void UnitParticleSystemType::setValues(UnitParticleSystem *ups){ - // whilst we extend ParticleSystemType we don't use ParticleSystemType::setValues() - // add instances of all children; some settings will cascade to all children - for(Children::iterator i=children.begin(); i!=children.end(); ++i){ - UnitParticleSystem *child = new UnitParticleSystem(); - child->setParticleOwner(ups->getParticleOwner()); - child->setParticleType((*i)); - (*i)->setValues(child); - ups->addChild(child); - } - // set values - ups->setModel(model); - ups->setModelCycle(modelCycle); - ups->setTexture(texture); - ups->setPrimitive(UnitParticleSystem::strToPrimitive(primitive)); - ups->setOffset(offset); - ups->setShape(shape); - ups->setAngle(angle); - ups->setDirection(direction); - ups->setColor(color); - ups->setColorNoEnergy(colorNoEnergy); - ups->setSpeed(speed); - ups->setSpeedUpRelative(speedUpRelative); - ups->setSpeedUpConstant(speedUpConstant); - ups->setGravity(gravity); - ups->setParticleSize(size); - ups->setSizeNoEnergy(sizeNoEnergy); - ups->setEmissionRate(emissionRate); - ups->setMaxParticleEnergy(energyMax); - ups->setVarParticleEnergy(energyVar); - ups->setFixed(fixed); - ups->setRelative(relative); - ups->setMeshName(meshName); - ups->setRelativeDirection(relativeDirection); - ups->setDelay(delay); - ups->setLifetime(lifetime); - ups->setEmissionRateFade(emissionRateFade); - ups->setTeamcolorNoEnergy(teamcolorNoEnergy); - ups->setTeamcolorEnergy(teamcolorEnergy); - ups->setAlternations(alternations); - ups->setParticleSystemStartDelay(particleSystemStartDelay); - - ups->setIsVisibleAtNight(isVisibleAtNight); - ups->setIsVisibleAtDay(isVisibleAtDay); - ups->setIsDaylightAffected(isDaylightAffected); - ups->setStaticParticleCount(staticParticleCount); - ups->setRadius(radius); - ups->setMinRadius(minRadius); - ups->setBlendMode(ParticleSystem::strToBlendMode(mode)); - ups->setRadiusBasedStartenergy(radiusBasedStartenergy); - //prepare system for given staticParticleCount - if(staticParticleCount>0) - { - ups->setEmissionRate(0.0f); - ups->setSpeed(0); - direction.x= 0.0f; - direction.y= 0.0f; - direction.z= 0.0f; - ups->setDirection(direction); - } - - ups->setStartTime(startTime); - ups->setEndTime(endTime); +const void UnitParticleSystemType::setValues(UnitParticleSystem *ups) { + // whilst we extend ParticleSystemType we don't use + // ParticleSystemType::setValues() add instances of all children; some + // settings will cascade to all children + for (Children::iterator i = children.begin(); i != children.end(); ++i) { + UnitParticleSystem *child = new UnitParticleSystem(); + child->setParticleOwner(ups->getParticleOwner()); + child->setParticleType((*i)); + (*i)->setValues(child); + ups->addChild(child); + } + // set values + ups->setModel(model); + ups->setModelCycle(modelCycle); + ups->setTexture(texture); + ups->setPrimitive(UnitParticleSystem::strToPrimitive(primitive)); + ups->setOffset(offset); + ups->setShape(shape); + ups->setAngle(angle); + ups->setDirection(direction); + ups->setColor(color); + ups->setColorNoEnergy(colorNoEnergy); + ups->setSpeed(speed); + ups->setSpeedUpRelative(speedUpRelative); + ups->setSpeedUpConstant(speedUpConstant); + ups->setGravity(gravity); + ups->setParticleSize(size); + ups->setSizeNoEnergy(sizeNoEnergy); + ups->setEmissionRate(emissionRate); + ups->setMaxParticleEnergy(energyMax); + ups->setVarParticleEnergy(energyVar); + ups->setFixed(fixed); + ups->setRelative(relative); + ups->setMeshName(meshName); + ups->setRelativeDirection(relativeDirection); + ups->setDelay(delay); + ups->setLifetime(lifetime); + ups->setEmissionRateFade(emissionRateFade); + ups->setTeamcolorNoEnergy(teamcolorNoEnergy); + ups->setTeamcolorEnergy(teamcolorEnergy); + ups->setAlternations(alternations); + ups->setParticleSystemStartDelay(particleSystemStartDelay); + + ups->setIsVisibleAtNight(isVisibleAtNight); + ups->setIsVisibleAtDay(isVisibleAtDay); + ups->setIsDaylightAffected(isDaylightAffected); + ups->setStaticParticleCount(staticParticleCount); + ups->setRadius(radius); + ups->setMinRadius(minRadius); + ups->setBlendMode(ParticleSystem::strToBlendMode(mode)); + ups->setRadiusBasedStartenergy(radiusBasedStartenergy); + // prepare system for given staticParticleCount + if (staticParticleCount > 0) { + ups->setEmissionRate(0.0f); + ups->setSpeed(0); + direction.x = 0.0f; + direction.y = 0.0f; + direction.z = 0.0f; + ups->setDirection(direction); + } + + ups->setStartTime(startTime); + ups->setEndTime(endTime); } -void UnitParticleSystemType::load(const XmlNode *particleFileNode, const string &dir, const string &path, - RendererInterface *renderer, std::map > > &loadedFileList, - string parentLoader, string techtreePath) { - - try{ - XmlTree xmlTree; - - std::map mapExtraTagReplacementValues; - mapExtraTagReplacementValues["$COMMONDATAPATH"] = techtreePath + "/commondata/"; - xmlTree.load(path, Properties::getTagReplacementValues(&mapExtraTagReplacementValues)); - loadedFileList[path].push_back(make_pair(parentLoader,parentLoader)); - const XmlNode *particleSystemNode= xmlTree.getRootNode(); - - if(particleFileNode){ - // immediate children in the particleFileNode will override the particleSystemNode - particleFileNode->setSuper(particleSystemNode); - particleSystemNode= particleFileNode; - } - - UnitParticleSystemType::load(particleSystemNode, dir, renderer, - loadedFileList, parentLoader, techtreePath); - } - catch(const exception &e){ - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,e.what()); - throw megaglest_runtime_error("Error loading ParticleSystem: "+ path + "\n" +e.what()); - } +void UnitParticleSystemType::load( + const XmlNode *particleFileNode, const string &dir, const string &path, + RendererInterface *renderer, + std::map>> &loadedFileList, + string parentLoader, string techtreePath) { + + try { + XmlTree xmlTree; + + std::map mapExtraTagReplacementValues; + mapExtraTagReplacementValues["$COMMONDATAPATH"] = + techtreePath + "/commondata/"; + xmlTree.load(path, Properties::getTagReplacementValues( + &mapExtraTagReplacementValues)); + loadedFileList[path].push_back(make_pair(parentLoader, parentLoader)); + const XmlNode *particleSystemNode = xmlTree.getRootNode(); + + if (particleFileNode) { + // immediate children in the particleFileNode will override the + // particleSystemNode + particleFileNode->setSuper(particleSystemNode); + particleSystemNode = particleFileNode; + } + + UnitParticleSystemType::load(particleSystemNode, dir, renderer, + loadedFileList, parentLoader, techtreePath); + } catch (const exception &e) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", __FILE__, + __FUNCTION__, __LINE__, e.what()); + throw megaglest_runtime_error("Error loading ParticleSystem: " + path + + "\n" + e.what()); + } } void UnitParticleSystemType::loadGame(const XmlNode *rootNode) { - ParticleSystemType::loadGame(rootNode); - - const XmlNode *unitParticleSystemTypeNode = rootNode->getChild("UnitParticleSystemType"); - - shape = static_cast(unitParticleSystemTypeNode->getAttribute("shape")->getIntValue()); - angle = unitParticleSystemTypeNode->getAttribute("angle")->getFloatValue(); - radius = unitParticleSystemTypeNode->getAttribute("radius")->getFloatValue(); - minRadius = unitParticleSystemTypeNode->getAttribute("minRadius")->getFloatValue(); - emissionRateFade = unitParticleSystemTypeNode->getAttribute("emissionRateFade")->getFloatValue(); - direction = Vec3f::strToVec3(unitParticleSystemTypeNode->getAttribute("direction")->getValue()); - relative = (unitParticleSystemTypeNode->getAttribute("relative")->getIntValue() != 0); - if(unitParticleSystemTypeNode->hasAttribute("meshName")){ - meshName = unitParticleSystemTypeNode->getAttribute("meshName")->getValue();} - else { - meshName = ""; - } - relativeDirection = (unitParticleSystemTypeNode->getAttribute("relativeDirection")->getIntValue() != 0); - fixed = (unitParticleSystemTypeNode->getAttribute("fixed")->getIntValue() != 0); - staticParticleCount = unitParticleSystemTypeNode->getAttribute("staticParticleCount")->getIntValue(); - isVisibleAtNight = (unitParticleSystemTypeNode->getAttribute("isVisibleAtNight")->getIntValue() != 0); - isVisibleAtDay = (unitParticleSystemTypeNode->getAttribute("isVisibleAtDay")->getIntValue() != 0); - isDaylightAffected = (unitParticleSystemTypeNode->getAttribute("isDaylightAffected")->getIntValue() != 0); - radiusBasedStartenergy = (unitParticleSystemTypeNode->getAttribute("radiusBasedStartenergy")->getIntValue() != 0); - delay = unitParticleSystemTypeNode->getAttribute("delay")->getIntValue(); - lifetime = unitParticleSystemTypeNode->getAttribute("lifetime")->getIntValue(); - startTime = unitParticleSystemTypeNode->getAttribute("startTime")->getFloatValue(); - endTime = unitParticleSystemTypeNode->getAttribute("endTime")->getFloatValue(); + ParticleSystemType::loadGame(rootNode); + + const XmlNode *unitParticleSystemTypeNode = + rootNode->getChild("UnitParticleSystemType"); + + shape = static_cast( + unitParticleSystemTypeNode->getAttribute("shape")->getIntValue()); + angle = unitParticleSystemTypeNode->getAttribute("angle")->getFloatValue(); + radius = unitParticleSystemTypeNode->getAttribute("radius")->getFloatValue(); + minRadius = + unitParticleSystemTypeNode->getAttribute("minRadius")->getFloatValue(); + emissionRateFade = + unitParticleSystemTypeNode->getAttribute("emissionRateFade") + ->getFloatValue(); + direction = Vec3f::strToVec3( + unitParticleSystemTypeNode->getAttribute("direction")->getValue()); + relative = + (unitParticleSystemTypeNode->getAttribute("relative")->getIntValue() != + 0); + if (unitParticleSystemTypeNode->hasAttribute("meshName")) { + meshName = unitParticleSystemTypeNode->getAttribute("meshName")->getValue(); + } else { + meshName = ""; + } + relativeDirection = + (unitParticleSystemTypeNode->getAttribute("relativeDirection") + ->getIntValue() != 0); + fixed = + (unitParticleSystemTypeNode->getAttribute("fixed")->getIntValue() != 0); + staticParticleCount = + unitParticleSystemTypeNode->getAttribute("staticParticleCount") + ->getIntValue(); + isVisibleAtNight = + (unitParticleSystemTypeNode->getAttribute("isVisibleAtNight") + ->getIntValue() != 0); + isVisibleAtDay = (unitParticleSystemTypeNode->getAttribute("isVisibleAtDay") + ->getIntValue() != 0); + isDaylightAffected = + (unitParticleSystemTypeNode->getAttribute("isDaylightAffected") + ->getIntValue() != 0); + radiusBasedStartenergy = + (unitParticleSystemTypeNode->getAttribute("radiusBasedStartenergy") + ->getIntValue() != 0); + delay = unitParticleSystemTypeNode->getAttribute("delay")->getIntValue(); + lifetime = + unitParticleSystemTypeNode->getAttribute("lifetime")->getIntValue(); + startTime = + unitParticleSystemTypeNode->getAttribute("startTime")->getFloatValue(); + endTime = + unitParticleSystemTypeNode->getAttribute("endTime")->getFloatValue(); } void UnitParticleSystemType::saveGame(XmlNode *rootNode) { - ParticleSystemType::saveGame(rootNode); - - std::map mapTagReplacements; - XmlNode *unitParticleSystemTypeNode = rootNode->addChild("UnitParticleSystemType"); - -// UnitParticleSystem::Shape shape; - unitParticleSystemTypeNode->addAttribute("shape",intToStr(shape), mapTagReplacements); -// float angle; - unitParticleSystemTypeNode->addAttribute("angle",floatToStr(angle,6), mapTagReplacements); -// float radius; - unitParticleSystemTypeNode->addAttribute("radius",floatToStr(radius,6), mapTagReplacements); -// float minRadius; - unitParticleSystemTypeNode->addAttribute("minRadius",floatToStr(minRadius,6), mapTagReplacements); -// float emissionRateFade; - unitParticleSystemTypeNode->addAttribute("emissionRateFade",floatToStr(emissionRateFade,6), mapTagReplacements); -// Vec3f direction; - unitParticleSystemTypeNode->addAttribute("direction",direction.getString(), mapTagReplacements); -// bool relative; - unitParticleSystemTypeNode->addAttribute("relative",intToStr(relative), mapTagReplacements); -// string meshName; - unitParticleSystemTypeNode->addAttribute("meshName",meshName, mapTagReplacements); -// bool relativeDirection; - unitParticleSystemTypeNode->addAttribute("relativeDirection",intToStr(relativeDirection), mapTagReplacements); -// bool fixed; - unitParticleSystemTypeNode->addAttribute("fixed",intToStr(fixed), mapTagReplacements); -// int staticParticleCount; - unitParticleSystemTypeNode->addAttribute("staticParticleCount",intToStr(staticParticleCount), mapTagReplacements); -// bool isVisibleAtNight; - unitParticleSystemTypeNode->addAttribute("isVisibleAtNight",intToStr(isVisibleAtNight), mapTagReplacements); -// bool isVisibleAtDay; - unitParticleSystemTypeNode->addAttribute("isVisibleAtDay",intToStr(isVisibleAtDay), mapTagReplacements); -// bool isDaylightAffected; - unitParticleSystemTypeNode->addAttribute("isDaylightAffected",intToStr(isDaylightAffected), mapTagReplacements); -// bool radiusBasedStartenergy; - unitParticleSystemTypeNode->addAttribute("radiusBasedStartenergy",intToStr(radiusBasedStartenergy), mapTagReplacements); -// int delay; - unitParticleSystemTypeNode->addAttribute("delay",intToStr(delay), mapTagReplacements); -// int lifetime; - unitParticleSystemTypeNode->addAttribute("lifetime",intToStr(lifetime), mapTagReplacements); -// float startTime; - unitParticleSystemTypeNode->addAttribute("startTime",floatToStr(startTime,6), mapTagReplacements); -// float endTime; - unitParticleSystemTypeNode->addAttribute("endTime",floatToStr(endTime,6), mapTagReplacements); + ParticleSystemType::saveGame(rootNode); + + std::map mapTagReplacements; + XmlNode *unitParticleSystemTypeNode = + rootNode->addChild("UnitParticleSystemType"); + + // UnitParticleSystem::Shape shape; + unitParticleSystemTypeNode->addAttribute("shape", intToStr(shape), + mapTagReplacements); + // float angle; + unitParticleSystemTypeNode->addAttribute("angle", floatToStr(angle, 6), + mapTagReplacements); + // float radius; + unitParticleSystemTypeNode->addAttribute("radius", floatToStr(radius, 6), + mapTagReplacements); + // float minRadius; + unitParticleSystemTypeNode->addAttribute( + "minRadius", floatToStr(minRadius, 6), mapTagReplacements); + // float emissionRateFade; + unitParticleSystemTypeNode->addAttribute( + "emissionRateFade", floatToStr(emissionRateFade, 6), mapTagReplacements); + // Vec3f direction; + unitParticleSystemTypeNode->addAttribute("direction", direction.getString(), + mapTagReplacements); + // bool relative; + unitParticleSystemTypeNode->addAttribute("relative", intToStr(relative), + mapTagReplacements); + // string meshName; + unitParticleSystemTypeNode->addAttribute("meshName", meshName, + mapTagReplacements); + // bool relativeDirection; + unitParticleSystemTypeNode->addAttribute( + "relativeDirection", intToStr(relativeDirection), mapTagReplacements); + // bool fixed; + unitParticleSystemTypeNode->addAttribute("fixed", intToStr(fixed), + mapTagReplacements); + // int staticParticleCount; + unitParticleSystemTypeNode->addAttribute( + "staticParticleCount", intToStr(staticParticleCount), mapTagReplacements); + // bool isVisibleAtNight; + unitParticleSystemTypeNode->addAttribute( + "isVisibleAtNight", intToStr(isVisibleAtNight), mapTagReplacements); + // bool isVisibleAtDay; + unitParticleSystemTypeNode->addAttribute( + "isVisibleAtDay", intToStr(isVisibleAtDay), mapTagReplacements); + // bool isDaylightAffected; + unitParticleSystemTypeNode->addAttribute( + "isDaylightAffected", intToStr(isDaylightAffected), mapTagReplacements); + // bool radiusBasedStartenergy; + unitParticleSystemTypeNode->addAttribute("radiusBasedStartenergy", + intToStr(radiusBasedStartenergy), + mapTagReplacements); + // int delay; + unitParticleSystemTypeNode->addAttribute("delay", intToStr(delay), + mapTagReplacements); + // int lifetime; + unitParticleSystemTypeNode->addAttribute("lifetime", intToStr(lifetime), + mapTagReplacements); + // float startTime; + unitParticleSystemTypeNode->addAttribute( + "startTime", floatToStr(startTime, 6), mapTagReplacements); + // float endTime; + unitParticleSystemTypeNode->addAttribute("endTime", floatToStr(endTime, 6), + mapTagReplacements); } -}}//end mamespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/graphics/unit_particle_type.h b/source/glest_game/graphics/unit_particle_type.h index 159d96a87..190b173d2 100644 --- a/source/glest_game/graphics/unit_particle_type.h +++ b/source/glest_game/graphics/unit_particle_type.h @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,93 +13,96 @@ #define _GLEST_GAME_UNITPARTICLETYPE_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include #include +#include -#include "particle.h" #include "factory.h" -#include "texture.h" -#include "vec.h" -#include "xml_parser.h" #include "graphics_interface.h" #include "leak_dumper.h" +#include "particle.h" #include "particle_type.h" +#include "texture.h" +#include "vec.h" +#include "xml_parser.h" using std::string; using namespace Shared::Graphics; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { using Shared::Graphics::ParticleManager; using Shared::Graphics::ParticleSystem; -using Shared::Graphics::UnitParticleSystem; using Shared::Graphics::Texture2D; +using Shared::Graphics::UnitParticleSystem; using Shared::Graphics::Vec3f; using Shared::Graphics::Vec4f; using Shared::Util::MultiFactory; using Shared::Xml::XmlNode; // =========================================================== -// class ParticleSystemType +// class ParticleSystemType // /// A type of particle system // =========================================================== -class UnitParticleSystemType: public ParticleSystemType { +class UnitParticleSystemType : public ParticleSystemType { protected: - UnitParticleSystem::Shape shape; - float angle; - float radius; - float minRadius; - float emissionRateFade; - Vec3f direction; - bool relative; - string meshName; - bool relativeDirection; - bool fixed; - int staticParticleCount; - bool isVisibleAtNight; - bool isVisibleAtDay; - bool isDaylightAffected; - bool radiusBasedStartenergy; - int delay; - int lifetime; - float startTime; - float endTime; - + UnitParticleSystem::Shape shape; + float angle; + float radius; + float minRadius; + float emissionRateFade; + Vec3f direction; + bool relative; + string meshName; + bool relativeDirection; + bool fixed; + int staticParticleCount; + bool isVisibleAtNight; + bool isVisibleAtDay; + bool isDaylightAffected; + bool radiusBasedStartenergy; + int delay; + int lifetime; + float startTime; + float endTime; public: - UnitParticleSystemType(); - virtual ~UnitParticleSystemType() {}; - - void load(const XmlNode *particleSystemNode, const string &dir, - RendererInterface *newTexture, std::map > > &loadedFileList, - string parentLoader, string techtreePath); - void load(const XmlNode *particleFileNode, const string &dir, const string &path, RendererInterface *newTexture, - std::map > > &loadedFileList,string parentLoader, - string techtreePath); - - void setStartTime(float startTime) { this->startTime = startTime; } - float getStartTime() const { return this->startTime; } - void setEndTime(float endTime) { this->endTime = endTime; } - float getEndTime() const { return this->endTime; } - - const void setValues (UnitParticleSystem *uts); - bool hasTexture() const { return(texture != NULL); } - virtual void saveGame(XmlNode *rootNode); - virtual void loadGame(const XmlNode *rootNode); + UnitParticleSystemType(); + virtual ~UnitParticleSystemType(){}; + + void load(const XmlNode *particleSystemNode, const string &dir, + RendererInterface *newTexture, + std::map>> &loadedFileList, + string parentLoader, string techtreePath); + void load(const XmlNode *particleFileNode, const string &dir, + const string &path, RendererInterface *newTexture, + std::map>> &loadedFileList, + string parentLoader, string techtreePath); + + void setStartTime(float startTime) { this->startTime = startTime; } + float getStartTime() const { return this->startTime; } + void setEndTime(float endTime) { this->endTime = endTime; } + float getEndTime() const { return this->endTime; } + + const void setValues(UnitParticleSystem *uts); + bool hasTexture() const { return (texture != NULL); } + virtual void saveGame(XmlNode *rootNode); + virtual void loadGame(const XmlNode *rootNode); }; -class ObjectParticleSystemType: public UnitParticleSystemType { +class ObjectParticleSystemType : public UnitParticleSystemType { public: - ObjectParticleSystemType(); - virtual ~ObjectParticleSystemType(); + ObjectParticleSystemType(); + virtual ~ObjectParticleSystemType(); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/gui/display.cpp b/source/glest_game/gui/display.cpp index 46e8a1e1c..ca0eef72b 100644 --- a/source/glest_game/gui/display.cpp +++ b/source/glest_game/gui/display.cpp @@ -3,182 +3,194 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== #include "display.h" -#include "metrics.h" #include "command_type.h" -#include "util.h" #include "leak_dumper.h" +#include "metrics.h" +#include "util.h" using namespace Shared::Graphics; using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class Display // ===================================================== -Display::Display(){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - colors[0]= Vec4f(1.f, 1.f, 1.f, 0.0f); - colors[1]= Vec4f(1.f, 0.5f, 0.5f, 0.0f); - colors[2]= Vec4f(0.5f, 0.5f, 1.0f, 0.0f); - colors[3]= Vec4f(0.5f, 1.0f, 0.5f, 0.0f); - colors[4]= Vec4f(0.0f, 0.0f, 0.0f, 1.0f); - colors[5]= Vec4f(0.0f, 0.0f, 1.0f, 1.0f); - colors[6]= Vec4f(1.0f, 0.0f, 0.0f, 1.0f); - colors[7]= Vec4f(0.0f, 1.0f, 0.0f, 1.0f); - colors[8]= Vec4f(1.0f, 1.0f, 1.0f, 1.0f); - - currentColor= 0; - clear(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); +Display::Display() { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + colors[0] = Vec4f(1.f, 1.f, 1.f, 0.0f); + colors[1] = Vec4f(1.f, 0.5f, 0.5f, 0.0f); + colors[2] = Vec4f(0.5f, 0.5f, 1.0f, 0.0f); + colors[3] = Vec4f(0.5f, 1.0f, 0.5f, 0.0f); + colors[4] = Vec4f(0.0f, 0.0f, 0.0f, 1.0f); + colors[5] = Vec4f(0.0f, 0.0f, 1.0f, 1.0f); + colors[6] = Vec4f(1.0f, 0.0f, 0.0f, 1.0f); + colors[7] = Vec4f(0.0f, 1.0f, 0.0f, 1.0f); + colors[8] = Vec4f(1.0f, 1.0f, 1.0f, 1.0f); + + currentColor = 0; + clear(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); } void Display::calculateUpDimensions(int index) { - if(index>maxUpIndex){ - maxUpIndex=index; - if(maxUpIndex+1>upCellSideCount*upCellSideCount){ - upCellSideCount=upCellSideCount+1; - upImageSize = static_cast(imageSize) * static_cast(cellSideCount) / static_cast(upCellSideCount) + 0.9f; - } - } + if (index > maxUpIndex) { + maxUpIndex = index; + if (maxUpIndex + 1 > upCellSideCount * upCellSideCount) { + upCellSideCount = upCellSideCount + 1; + upImageSize = static_cast(imageSize) * + static_cast(cellSideCount) / + static_cast(upCellSideCount) + + 0.9f; + } + } } Vec4f Display::getColor() const { - if(currentColor < 0 || currentColor >= colorCount) { - throw megaglest_runtime_error("currentColor >= colorCount"); - } - return colors[currentColor]; + if (currentColor < 0 || currentColor >= colorCount) { + throw megaglest_runtime_error("currentColor >= colorCount"); + } + return colors[currentColor]; } -void Display::setUpImage(int i, const Texture2D *image) -{ - if(i>=upCellCount) throw megaglest_runtime_error("i>=upCellCount in Display::setUpImage"); - upImages[i]= image; - calculateUpDimensions(i); +void Display::setUpImage(int i, const Texture2D *image) { + if (i >= upCellCount) + throw megaglest_runtime_error("i>=upCellCount in Display::setUpImage"); + upImages[i] = image; + calculateUpDimensions(i); } -//misc -void Display::clear(){ - downSelectedPos= invalidPos; - for(int i=0; iimageSize*cellSideCount || y < 0){ - return invalidPos; - } + y = y - (downY - cellSideCount * imageSize); + + if (y > imageSize * cellSideCount || y < 0) { + return invalidPos; + } - int cellX= x/imageSize; - int cellY= (y/imageSize) % cellSideCount; - int index= (cellSideCount-cellY-1)*cellSideCount+cellX;; + int cellX = x / imageSize; + int cellY = (y / imageSize) % cellSideCount; + int index = (cellSideCount - cellY - 1) * cellSideCount + cellX; + ; - if(index<0 || index>=downCellCount || downImages[index]==NULL){ - index= invalidPos; - } + if (index < 0 || index >= downCellCount || downImages[index] == NULL) { + index = invalidPos; + } - return index; + return index; } -int Display::computeDownX(int index) const{ - return (index % cellSideCount) * imageSize; +int Display::computeDownX(int index) const { + return (index % cellSideCount) * imageSize; } -int Display::computeDownY(int index) const{ - return Display::downY - (index/cellSideCount)*imageSize - imageSize; +int Display::computeDownY(int index) const { + return Display::downY - (index / cellSideCount) * imageSize - imageSize; } -int Display::computeUpX(int index) const{ - return (index % upCellSideCount) * upImageSize; +int Display::computeUpX(int index) const { + return (index % upCellSideCount) * upImageSize; } -int Display::computeUpY(int index) const{ - return Metrics::getInstance().getDisplayH() - (index/upCellSideCount)*upImageSize - upImageSize; +int Display::computeUpY(int index) const { + return Metrics::getInstance().getDisplayH() - + (index / upCellSideCount) * upImageSize - upImageSize; } void Display::saveGame(XmlNode *rootNode) const { - std::map mapTagReplacements; - XmlNode *displayNode = rootNode->addChild("Display"); - -// string title; - displayNode->addAttribute("title",title, mapTagReplacements); -// string text; - displayNode->addAttribute("text",text, mapTagReplacements); -// string infoText; - displayNode->addAttribute("infoText",infoText, mapTagReplacements); -// const Texture2D *upImages[upCellCount]; -// const Texture2D *downImages[downCellCount]; -// bool downLighted[downCellCount]; -// const CommandType *commandTypes[downCellCount]; -// CommandClass commandClasses[downCellCount]; -// int progressBar; - displayNode->addAttribute("progressBar",intToStr(progressBar), mapTagReplacements); -// int downSelectedPos; - displayNode->addAttribute("downSelectedPos",intToStr(downSelectedPos), mapTagReplacements); -// Vec4f colors[colorCount]; -// int currentColor; - displayNode->addAttribute("currentColor",intToStr(currentColor), mapTagReplacements); -// int upCellSideCount; -// int upImageSize; -// int maxUpIndex; + std::map mapTagReplacements; + XmlNode *displayNode = rootNode->addChild("Display"); + + // string title; + displayNode->addAttribute("title", title, mapTagReplacements); + // string text; + displayNode->addAttribute("text", text, mapTagReplacements); + // string infoText; + displayNode->addAttribute("infoText", infoText, mapTagReplacements); + // const Texture2D *upImages[upCellCount]; + // const Texture2D *downImages[downCellCount]; + // bool downLighted[downCellCount]; + // const CommandType *commandTypes[downCellCount]; + // CommandClass commandClasses[downCellCount]; + // int progressBar; + displayNode->addAttribute("progressBar", intToStr(progressBar), + mapTagReplacements); + // int downSelectedPos; + displayNode->addAttribute("downSelectedPos", intToStr(downSelectedPos), + mapTagReplacements); + // Vec4f colors[colorCount]; + // int currentColor; + displayNode->addAttribute("currentColor", intToStr(currentColor), + mapTagReplacements); + // int upCellSideCount; + // int upImageSize; + // int maxUpIndex; } void Display::loadGame(const XmlNode *rootNode) { - const XmlNode *displayNode = rootNode->getChild("Display"); - - // string title; - title = displayNode->getAttribute("title")->getValue(); - // string text; - text = displayNode->getAttribute("text")->getValue(); - // string infoText; - infoText = displayNode->getAttribute("infoText")->getValue(); - // const Texture2D *upImages[upCellCount]; - // const Texture2D *downImages[downCellCount]; - // bool downLighted[downCellCount]; - // const CommandType *commandTypes[downCellCount]; - // CommandClass commandClasses[downCellCount]; - // int progressBar; - progressBar = displayNode->getAttribute("progressBar")->getIntValue(); - // int downSelectedPos; - //displayNode->addAttribute("downSelectedPos",intToStr(downSelectedPos), mapTagReplacements); - // Vec4f colors[colorCount]; - // int currentColor; - //currentColor = displayNode->getAttribute("progressBar")->getIntValue(); - // int upCellSideCount; - // int upImageSize; - // int maxUpIndex; + const XmlNode *displayNode = rootNode->getChild("Display"); + + // string title; + title = displayNode->getAttribute("title")->getValue(); + // string text; + text = displayNode->getAttribute("text")->getValue(); + // string infoText; + infoText = displayNode->getAttribute("infoText")->getValue(); + // const Texture2D *upImages[upCellCount]; + // const Texture2D *downImages[downCellCount]; + // bool downLighted[downCellCount]; + // const CommandType *commandTypes[downCellCount]; + // CommandClass commandClasses[downCellCount]; + // int progressBar; + progressBar = displayNode->getAttribute("progressBar")->getIntValue(); + // int downSelectedPos; + // displayNode->addAttribute("downSelectedPos",intToStr(downSelectedPos), + // mapTagReplacements); Vec4f colors[colorCount]; int + // currentColor; currentColor = + // displayNode->getAttribute("progressBar")->getIntValue(); + // int upCellSideCount; + // int upImageSize; + // int maxUpIndex; } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/gui/display.h b/source/glest_game/gui/display.h index a910692de..90263e13a 100644 --- a/source/glest_game/gui/display.h +++ b/source/glest_game/gui/display.h @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,25 +13,26 @@ #define _GLEST_GAME_DISPLAY_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include -#include "texture.h" -#include "util.h" #include "command_type.h" #include "game_util.h" #include "leak_dumper.h" +#include "texture.h" +#include "util.h" +#include using std::string; using Shared::Graphics::Texture2D; -using Shared::Graphics::Vec4f; using Shared::Graphics::Vec3f; +using Shared::Graphics::Vec4f; using Shared::Util::replaceBy; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class Display @@ -39,84 +40,90 @@ namespace Glest{ namespace Game{ /// Display for unit commands, and unit selection // ===================================================== -class Display{ +class Display { public: - static const int cellSideCount= 4; - static const int upCellCount= 36; - static const int downCellCount= cellSideCount*cellSideCount; - static const int colorCount= 9; - static const int imageSize= 32; - static const int invalidPos= -1; - static const int downY = imageSize*9; - static const int infoStringY= imageSize*4; + static const int cellSideCount = 4; + static const int upCellCount = 36; + static const int downCellCount = cellSideCount * cellSideCount; + static const int colorCount = 9; + static const int imageSize = 32; + static const int invalidPos = -1; + static const int downY = imageSize * 9; + static const int infoStringY = imageSize * 4; private: - string title; - string text; - string infoText; - const Texture2D *upImages[upCellCount]; - const Texture2D *downImages[downCellCount]; - Vec3f downImageColor[downCellCount]; - const CommandType *commandTypes[downCellCount]; - CommandClass commandClasses[downCellCount]; - int progressBar; - int downSelectedPos; - Vec4f colors[colorCount]; - int currentColor; - - int upCellSideCount; - int upImageSize; - int maxUpIndex; - + string title; + string text; + string infoText; + const Texture2D *upImages[upCellCount]; + const Texture2D *downImages[downCellCount]; + Vec3f downImageColor[downCellCount]; + const CommandType *commandTypes[downCellCount]; + CommandClass commandClasses[downCellCount]; + int progressBar; + int downSelectedPos; + Vec4f colors[colorCount]; + int currentColor; + + int upCellSideCount; + int upImageSize; + int maxUpIndex; public: - Display(); - - //get - string getTitle() const {return title;} - string getText() const {return text;} - string getInfoText() const {return infoText;} - const Texture2D *getUpImage(int index) const {return upImages[index];} - const Texture2D *getDownImage(int index) const {return downImages[index];} - Vec3f getDownImageColor(int index) const {return downImageColor[index];} - const CommandType *getCommandType(int i) const {return commandTypes[i];} - CommandClass getCommandClass(int i) const {return commandClasses[i];} - Vec4f getColor() const; - int getProgressBar() const {return progressBar;} - int getDownSelectedPos() const {return downSelectedPos;} - int getUpCellSideCount() const {return upCellSideCount;} - int getUpImageSize() const {return upImageSize;} - - //set - void setTitle(const string title) {this->title= formatString(title);} - void setText(const string &text) {this->text= formatString(text);} - void setInfoText(const string infoText) {this->infoText= formatString(infoText);} - void setUpImage(int i, const Texture2D *image); - void setDownImage(int i, const Texture2D *image) {downImages[i]= image;} - void setCommandType(int i, const CommandType *ct) {commandTypes[i]= ct;} - void setCommandClass(int i, const CommandClass cc) {commandClasses[i]= cc;} - void setDownLighted(int i, bool lighted) {downImageColor[i]=lighted?Vec3f(1.f, 1.f, 1.f):Vec3f(0.3f, 0.3f, 0.3);} - void setDownRedLighted(int i) {downImageColor[i]=Vec3f(1.0f, 0.0f, 0.0);} - void setDownOrangeLighted(int i) {downImageColor[i]=Vec3f(1.0f, 0.7f, 0.2);} - void setProgressBar(int i) {progressBar= i;} - void setDownSelectedPos(int i) {downSelectedPos= i;} - - //misc - void clear(); - void switchColor(); - int computeDownIndex(int x, int y) const; - int computeDownX(int index) const; - int computeDownY(int index) const; - int computeUpX(int index) const; - int computeUpY(int index) const; - - void saveGame(XmlNode *rootNode) const; - void loadGame(const XmlNode *rootNode); + Display(); + + // get + string getTitle() const { return title; } + string getText() const { return text; } + string getInfoText() const { return infoText; } + const Texture2D *getUpImage(int index) const { return upImages[index]; } + const Texture2D *getDownImage(int index) const { return downImages[index]; } + Vec3f getDownImageColor(int index) const { return downImageColor[index]; } + const CommandType *getCommandType(int i) const { return commandTypes[i]; } + CommandClass getCommandClass(int i) const { return commandClasses[i]; } + Vec4f getColor() const; + int getProgressBar() const { return progressBar; } + int getDownSelectedPos() const { return downSelectedPos; } + int getUpCellSideCount() const { return upCellSideCount; } + int getUpImageSize() const { return upImageSize; } + + // set + void setTitle(const string title) { this->title = formatString(title); } + void setText(const string &text) { this->text = formatString(text); } + void setInfoText(const string infoText) { + this->infoText = formatString(infoText); + } + void setUpImage(int i, const Texture2D *image); + void setDownImage(int i, const Texture2D *image) { downImages[i] = image; } + void setCommandType(int i, const CommandType *ct) { commandTypes[i] = ct; } + void setCommandClass(int i, const CommandClass cc) { commandClasses[i] = cc; } + void setDownLighted(int i, bool lighted) { + downImageColor[i] = lighted ? Vec3f(1.f, 1.f, 1.f) : Vec3f(0.3f, 0.3f, 0.3); + } + void setDownRedLighted(int i) { downImageColor[i] = Vec3f(1.0f, 0.0f, 0.0); } + void setDownOrangeLighted(int i) { + downImageColor[i] = Vec3f(1.0f, 0.7f, 0.2); + } + void setProgressBar(int i) { progressBar = i; } + void setDownSelectedPos(int i) { downSelectedPos = i; } + + // misc + void clear(); + void switchColor(); + int computeDownIndex(int x, int y) const; + int computeDownX(int index) const; + int computeDownY(int index) const; + int computeUpX(int index) const; + int computeUpY(int index) const; + + void saveGame(XmlNode *rootNode) const; + void loadGame(const XmlNode *rootNode); private: - void calculateUpDimensions(int index); + void calculateUpDimensions(int index); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/gui/gui.cpp b/source/glest_game/gui/gui.cpp index ce6f79f69..da3eaab3f 100644 --- a/source/glest_game/gui/gui.cpp +++ b/source/glest_game/gui/gui.cpp @@ -12,1462 +12,1579 @@ #include "gui.h" -#include #include +#include -#include "world.h" -#include "renderer.h" +#include "display.h" +#include "faction.h" #include "game.h" -#include "upgrade.h" -#include "unit.h" +#include "leak_dumper.h" #include "metrics.h" -#include "display.h" #include "platform_util.h" +#include "renderer.h" #include "sound_renderer.h" +#include "unit.h" +#include "upgrade.h" #include "util.h" -#include "faction.h" -#include "leak_dumper.h" +#include "world.h" -#include "network_types.h" #include "network_manager.h" - +#include "network_types.h" using namespace Shared::Graphics; using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class Mouse3d // ===================================================== -const float Mouse3d::fadeSpeed= 1.f/50.f; +const float Mouse3d::fadeSpeed = 1.f / 50.f; static const int queueCommandKey = vkShift; -Mouse3d::Mouse3d(){ - enabled= false; - rot= 0; - fade= 0.f; +Mouse3d::Mouse3d() { + enabled = false; + rot = 0; + fade = 0.f; } -void Mouse3d::enable(){ - enabled= true; - fade= 0.f; +void Mouse3d::enable() { + enabled = true; + fade = 0.f; } -void Mouse3d::update(){ - if(enabled){ - rot= (rot + 3) % 360; - fade+= fadeSpeed; - if(fade>1.f) fade= 1.f; - } +void Mouse3d::update() { + if (enabled) { + rot = (rot + 3) % 360; + fade += fadeSpeed; + if (fade > 1.f) + fade = 1.f; + } } // =============================== // class SelectionQuad // =============================== -SelectionQuad::SelectionQuad(){ - enabled= false; - posDown= Vec2i(0); - posUp= Vec2i(0); +SelectionQuad::SelectionQuad() { + enabled = false; + posDown = Vec2i(0); + posUp = Vec2i(0); } -void SelectionQuad::setPosDown(const Vec2i &posDown){ - enabled= true; - this->posDown= posDown; - this->posUp= posDown; +void SelectionQuad::setPosDown(const Vec2i &posDown) { + enabled = true; + this->posDown = posDown; + this->posUp = posDown; } -void SelectionQuad::setPosUp(const Vec2i &posUp){ - this->posUp= posUp; -} +void SelectionQuad::setPosUp(const Vec2i &posUp) { this->posUp = posUp; } -void SelectionQuad::disable(){ - enabled= false; -} +void SelectionQuad::disable() { enabled = false; } // ===================================================== // class Gui // ===================================================== -//constructor -Gui::Gui(){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] START\n",__FILE__,__FUNCTION__); - - lastGroupRecall = -1; - posObjWorld= Vec2i(54, 14); - validPosObjWorld= false; - activeCommandType= NULL; - activeCommandClass= ccStop; - selectingBuilding= false; - selectedBuildingFacing = CardinalDir(CardinalDir::NORTH); - selectingPos= false; - selectingMeetingPoint= false; - activePos= invalidPos; - lastPosDisplay= invalidPos; - lastQuadCalcFrame=0; - selectionCalculationFrameSkip=10; - minQuadSize=20; - selectedResourceObjectPos=Vec2i(-1,-1); - highlightedResourceObjectPos=Vec2i(-1,-1); - highlightedUnitId=-1; - hudTexture=NULL; - commander=NULL; - world=NULL; - game=NULL; - gameCamera=NULL; - console=NULL; - choosenBuildingType=NULL; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] END\n",__FILE__,__FUNCTION__); +// constructor +Gui::Gui() { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] START\n", + __FILE__, __FUNCTION__); + + lastGroupRecall = -1; + posObjWorld = Vec2i(54, 14); + validPosObjWorld = false; + activeCommandType = NULL; + activeCommandClass = ccStop; + selectingBuilding = false; + selectedBuildingFacing = CardinalDir(CardinalDir::NORTH); + selectingPos = false; + selectingMeetingPoint = false; + activePos = invalidPos; + lastPosDisplay = invalidPos; + lastQuadCalcFrame = 0; + selectionCalculationFrameSkip = 10; + minQuadSize = 20; + selectedResourceObjectPos = Vec2i(-1, -1); + highlightedResourceObjectPos = Vec2i(-1, -1); + highlightedUnitId = -1; + hudTexture = NULL; + commander = NULL; + world = NULL; + game = NULL; + gameCamera = NULL; + console = NULL; + choosenBuildingType = NULL; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] END\n", + __FILE__, __FUNCTION__); } void Gui::init(Game *game) { - this->commander = game->getCommander(); - this->gameCamera = game->getGameCameraPtr(); - this->console = game->getConsole(); - this->world = game->getWorld(); - this->game = game; + this->commander = game->getCommander(); + this->gameCamera = game->getGameCameraPtr(); + this->console = game->getConsole(); + this->world = game->getWorld(); + this->game = game; - selection.init(this, - world->getThisFactionIndex(), - world->getThisTeamIndex(), - game->isFlagType1BitEnabled(ft1_allow_shared_team_units)); + selection.init(this, world->getThisFactionIndex(), world->getThisTeamIndex(), + game->isFlagType1BitEnabled(ft1_allow_shared_team_units)); } -void Gui::end(){ - selection.clear(); - if(hudTexture != NULL) { - Renderer::getInstance().endTexture(rsGlobal, hudTexture, false); - } - hudTexture = NULL; +void Gui::end() { + selection.clear(); + if (hudTexture != NULL) { + Renderer::getInstance().endTexture(rsGlobal, hudTexture, false); + } + hudTexture = NULL; } // ==================== get ==================== -const UnitType *Gui::getBuilding() const{ - assert(selectingBuilding); - return choosenBuildingType; +const UnitType *Gui::getBuilding() const { + assert(selectingBuilding); + return choosenBuildingType; } -const Object *Gui::getSelectedResourceObject() const{ - if(selectedResourceObjectPos.x==-1){ - return NULL; - } - else { - return world->getMap()->getSurfaceCell(selectedResourceObjectPos)->getObject(); - } +const Object *Gui::getSelectedResourceObject() const { + if (selectedResourceObjectPos.x == -1) { + return NULL; + } else { + return world->getMap() + ->getSurfaceCell(selectedResourceObjectPos) + ->getObject(); + } } -Object *Gui::getHighlightedResourceObject() const{ - if(highlightedResourceObjectPos.x==-1){ - return NULL; - } - else { - if(world == NULL) { - throw megaglest_runtime_error("world == NULL"); - } - if(world->getMap() == NULL) { - throw megaglest_runtime_error("world->getMap() == NULL"); - } - if(world->getMap()->getSurfaceCell(highlightedResourceObjectPos) == NULL) { - throw megaglest_runtime_error("world->getMap()->getSurfaceCell(highlightedResourceObjectPos) == NULL"); - } - return world->getMap()->getSurfaceCell(highlightedResourceObjectPos)->getObject(); - } +Object *Gui::getHighlightedResourceObject() const { + if (highlightedResourceObjectPos.x == -1) { + return NULL; + } else { + if (world == NULL) { + throw megaglest_runtime_error("world == NULL"); + } + if (world->getMap() == NULL) { + throw megaglest_runtime_error("world->getMap() == NULL"); + } + if (world->getMap()->getSurfaceCell(highlightedResourceObjectPos) == NULL) { + throw megaglest_runtime_error("world->getMap()->getSurfaceCell(" + "highlightedResourceObjectPos) == NULL"); + } + return world->getMap() + ->getSurfaceCell(highlightedResourceObjectPos) + ->getObject(); + } } -Unit* Gui::getHighlightedUnit() const{ - if(highlightedUnitId==-1){ - return NULL; - } - else { - return world->findUnitById(highlightedUnitId); - } +Unit *Gui::getHighlightedUnit() const { + if (highlightedUnitId == -1) { + return NULL; + } else { + return world->findUnitById(highlightedUnitId); + } } // ==================== is ==================== -bool Gui::isPlacingBuilding() const{ - return isSelectingPos() && activeCommandType!=NULL && activeCommandType->getClass()==ccBuild; +bool Gui::isPlacingBuilding() const { + return isSelectingPos() && activeCommandType != NULL && + activeCommandType->getClass() == ccBuild; } // ==================== set ==================== -void Gui::invalidatePosObjWorld(){ - validPosObjWorld= false; -} +void Gui::invalidatePosObjWorld() { validPosObjWorld = false; } // ==================== reset state ==================== -void Gui::resetState(){ - selectingBuilding= false; - selectedBuildingFacing = CardinalDir(CardinalDir::NORTH); - selectingPos= false; - selectingMeetingPoint= false; - activePos= invalidPos; - activeCommandClass= ccStop; - activeCommandType= NULL; +void Gui::resetState() { + selectingBuilding = false; + selectedBuildingFacing = CardinalDir(CardinalDir::NORTH); + selectingPos = false; + selectingMeetingPoint = false; + activePos = invalidPos; + activeCommandClass = ccStop; + activeCommandType = NULL; } // ==================== events ==================== -void Gui::update(){ +void Gui::update() { - if(selectionQuad.isEnabled() && selectionQuad.getPosUp().dist(selectionQuad.getPosDown())>minQuadSize){ - computeSelected(false,false); - } - mouse3d.update(); + if (selectionQuad.isEnabled() && + selectionQuad.getPosUp().dist(selectionQuad.getPosDown()) > minQuadSize) { + computeSelected(false, false); + } + mouse3d.update(); } -void Gui::tick(){ - computeDisplay(); -} +void Gui::tick() { computeDisplay(); } -//in display coords +// in display coords bool Gui::mouseValid(int x, int y) { - return computePosDisplay(x, y) != invalidPos; + return computePosDisplay(x, y) != invalidPos; } void Gui::mouseDownLeftDisplay(int x, int y) { - if(selectingPos == false && - selectingMeetingPoint == false) { - - int posDisplay = computePosDisplay(x, y); - - if(posDisplay != invalidPos) { - if(selection.isCommandable()) { - - if(selectingBuilding) { - mouseDownDisplayUnitBuild(posDisplay); - } - else { - mouseDownDisplayUnitSkills(posDisplay); - } - } - else { - resetState(); - } - } - computeDisplay(); - } + if (selectingPos == false && selectingMeetingPoint == false) { + + int posDisplay = computePosDisplay(x, y); + + if (posDisplay != invalidPos) { + if (selection.isCommandable()) { + + if (selectingBuilding) { + mouseDownDisplayUnitBuild(posDisplay); + } else { + mouseDownDisplayUnitSkills(posDisplay); + } + } else { + resetState(); + } + } + computeDisplay(); + } } void Gui::mouseMoveDisplay(int x, int y) { - computeInfoString(computePosDisplay(x, y)); + computeInfoString(computePosDisplay(x, y)); } -void Gui::mouseMoveOutsideDisplay() { - computeInfoString(invalidPos); -} +void Gui::mouseMoveOutsideDisplay() { computeInfoString(invalidPos); } void Gui::mouseDownLeftGraphics(int x, int y, bool prepared) { - if(selectingPos) { - //give standard orders - Vec2i targetPos=game->getMouseCellPos(); - if(prepared || (game->isValidMouseCellPos() && - world->getMap()->isInsideSurface(world->getMap()->toSurfCoords(targetPos)) == true)) { - giveTwoClickOrders(x, y, prepared); - } - resetState(); - } - //set meeting point - else if(selectingMeetingPoint) { - if(selection.isCommandable()) { - Vec2i targetPos=game->getMouseCellPos(); - if(prepared || (game->isValidMouseCellPos() && - world->getMap()->isInsideSurface(world->getMap()->toSurfCoords(targetPos)) == true)) { - - for(int unitIndex = 0; unitIndex < selection.getCount(); ++unitIndex){ - const Unit *unit = selection.getUnit(unitIndex); - if(unit == NULL) { - //ignore - } - else { - commander->trySetMeetingPoint(unit, targetPos); - } - } - } - } - resetState(); - } - else { - selectionQuad.setPosDown(Vec2i(x, y)); - computeSelected(false,false); - } - computeDisplay(); + if (selectingPos) { + // give standard orders + Vec2i targetPos = game->getMouseCellPos(); + if (prepared || (game->isValidMouseCellPos() && + world->getMap()->isInsideSurface( + world->getMap()->toSurfCoords(targetPos)) == true)) { + giveTwoClickOrders(x, y, prepared); + } + resetState(); + } + // set meeting point + else if (selectingMeetingPoint) { + if (selection.isCommandable()) { + Vec2i targetPos = game->getMouseCellPos(); + if (prepared || (game->isValidMouseCellPos() && + world->getMap()->isInsideSurface( + world->getMap()->toSurfCoords(targetPos)) == true)) { + + for (int unitIndex = 0; unitIndex < selection.getCount(); ++unitIndex) { + const Unit *unit = selection.getUnit(unitIndex); + if (unit == NULL) { + // ignore + } else { + commander->trySetMeetingPoint(unit, targetPos); + } + } + } + } + resetState(); + } else { + selectionQuad.setPosDown(Vec2i(x, y)); + computeSelected(false, false); + } + computeDisplay(); } -void Gui::mouseDownRightGraphics(int x, int y , bool prepared) { - if(selectingPos || selectingMeetingPoint) { - resetState(); - } - else if(selection.isCommandable()) { - if(prepared) { - //Vec2i targetPos=game->getMouseCellPos(); - givePreparedDefaultOrders(x, y); - } - else { - Vec2i targetPos=game->getMouseCellPos(); - if(game->isValidMouseCellPos() && - world->getMap()->isInsideSurface(world->getMap()->toSurfCoords(targetPos)) == true) { - giveDefaultOrders(x, y); - } - } - } - computeDisplay(); +void Gui::mouseDownRightGraphics(int x, int y, bool prepared) { + if (selectingPos || selectingMeetingPoint) { + resetState(); + } else if (selection.isCommandable()) { + if (prepared) { + // Vec2i targetPos=game->getMouseCellPos(); + givePreparedDefaultOrders(x, y); + } else { + Vec2i targetPos = game->getMouseCellPos(); + if (game->isValidMouseCellPos() && + world->getMap()->isInsideSurface( + world->getMap()->toSurfCoords(targetPos)) == true) { + giveDefaultOrders(x, y); + } + } + } + computeDisplay(); } void Gui::mouseUpLeftGraphics(int x, int y) { - if(!selectingPos && !selectingMeetingPoint) { - if(selectionQuad.isEnabled()){ - selectionQuad.setPosUp(Vec2i(x, y)); - if(selectionQuad.getPosUp().dist(selectionQuad.getPosDown()) > minQuadSize) { - computeSelected(false,true); - } - if(selection.isCommandable() && random.randRange(0, 1)==0){ - SoundRenderer::getInstance().playFx( - selection.getFrontUnit()->getType()->getSelectionSound(), - selection.getFrontUnit()->getCurrMidHeightVector(), - gameCamera->getPos()); - } - selectionQuad.disable(); - } - } + if (!selectingPos && !selectingMeetingPoint) { + if (selectionQuad.isEnabled()) { + selectionQuad.setPosUp(Vec2i(x, y)); + if (selectionQuad.getPosUp().dist(selectionQuad.getPosDown()) > + minQuadSize) { + computeSelected(false, true); + } + if (selection.isCommandable() && random.randRange(0, 1) == 0) { + SoundRenderer::getInstance().playFx( + selection.getFrontUnit()->getType()->getSelectionSound(), + selection.getFrontUnit()->getCurrMidHeightVector(), + gameCamera->getPos()); + } + selectionQuad.disable(); + } + } } void Gui::mouseMoveGraphics(int x, int y) { - //compute selection - if(selectionQuad.isEnabled()){ - selectionQuad.setPosUp(Vec2i(x, y)); - computeSelected(false,false); - } - - //compute position for building - if(isPlacingBuilding()){ - posObjWorld=game->getMouseCellPos(); - validPosObjWorld= game->isValidMouseCellPos(); - } - - display.setInfoText(""); + // compute selection + if (selectionQuad.isEnabled()) { + selectionQuad.setPosUp(Vec2i(x, y)); + computeSelected(false, false); + } + + // compute position for building + if (isPlacingBuilding()) { + posObjWorld = game->getMouseCellPos(); + validPosObjWorld = game->isValidMouseCellPos(); + } + + display.setInfoText(""); } -void Gui::mouseDoubleClickLeftGraphics(int x, int y){ - if(!selectingPos && !selectingMeetingPoint){ - selectionQuad.setPosDown(Vec2i(x, y)); - computeSelected(true,true); - computeDisplay(); - } +void Gui::mouseDoubleClickLeftGraphics(int x, int y) { + if (!selectingPos && !selectingMeetingPoint) { + selectionQuad.setPosDown(Vec2i(x, y)); + computeSelected(true, true); + computeDisplay(); + } } void Gui::groupKey(int groupIndex) { - if(isKeyDown(vkControl)){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] groupIndex = %d\n",__FILE__,__FUNCTION__,__LINE__,groupIndex); -// bool allAssigned=true; - bool clearGroup=!isKeyDown(vkShift); -// if(!clearGroup){ -// Unit* unit=selection.getFrontUnit(); -// if(unit!=null && unit->getType()->getMultiSelect()==false){ -// return; -// } -// } - bool allAssigned=selection.assignGroup(groupIndex,clearGroup); - if(!allAssigned){ - console->addStdMessage("GroupAssignFailed"); - } - } - else{ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] groupIndex = %d\n",__FILE__,__FUNCTION__,__LINE__,groupIndex); - - int recallGroupCenterCameraTimeout = Config::getInstance().getInt("RecallGroupCenterCameraTimeoutMilliseconds","1500"); - - if(lastGroupRecall == groupIndex && - lastGroupRecallTime.getMillis() > 0 && - lastGroupRecallTime.getMillis() <= recallGroupCenterCameraTimeout) { - - selection.recallGroup(groupIndex,!isKeyDown(vkShift)); - centerCameraOnSelection(); - } - else { - selection.recallGroup(groupIndex,!isKeyDown(vkShift)); - } - - lastGroupRecallTime.start(); - lastGroupRecall = groupIndex; - } + if (isKeyDown(vkControl)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] groupIndex = %d\n", + __FILE__, __FUNCTION__, __LINE__, groupIndex); + // bool allAssigned=true; + bool clearGroup = !isKeyDown(vkShift); + // if(!clearGroup){ + // Unit* unit=selection.getFrontUnit(); + // if(unit!=null && + // unit->getType()->getMultiSelect()==false){ + // return; + // } + // } + bool allAssigned = selection.assignGroup(groupIndex, clearGroup); + if (!allAssigned) { + console->addStdMessage("GroupAssignFailed"); + } + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] groupIndex = %d\n", + __FILE__, __FUNCTION__, __LINE__, groupIndex); + + int recallGroupCenterCameraTimeout = Config::getInstance().getInt( + "RecallGroupCenterCameraTimeoutMilliseconds", "1500"); + + if (lastGroupRecall == groupIndex && lastGroupRecallTime.getMillis() > 0 && + lastGroupRecallTime.getMillis() <= recallGroupCenterCameraTimeout) { + + selection.recallGroup(groupIndex, !isKeyDown(vkShift)); + centerCameraOnSelection(); + } else { + selection.recallGroup(groupIndex, !isKeyDown(vkShift)); + } + + lastGroupRecallTime.start(); + lastGroupRecall = groupIndex; + } } void Gui::hotKey(SDL_KeyboardEvent key) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] key = [%c][%d]\n",__FILE__,__FUNCTION__,key,key); - - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - - //if(key == configKeys.getCharKey("HotKeyCenterCameraOnSelection")) { - if(isKeyPressed(configKeys.getSDLKey("HotKeyCenterCameraOnSelection"),key) == true) { - centerCameraOnSelection(); - } - //else if(key == configKeys.getCharKey("HotKeySelectIdleHarvesterUnit")) { - else if(isKeyPressed(configKeys.getSDLKey("HotKeySelectIdleHarvesterUnit"),key) == true) { - selectInterestingUnit(iutIdleHarvester); - } - //else if(key == configKeys.getCharKey("HotKeySelectBuiltBuilding")) { - else if(isKeyPressed(configKeys.getSDLKey("HotKeySelectBuiltBuilding"),key) == true) { - selectInterestingUnit(iutBuiltBuilding); - } - //else if(key == configKeys.getCharKey("HotKeyDumpWorldToLog")) { - else if(isKeyPressed(configKeys.getSDLKey("HotKeyDumpWorldToLog"),key) == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled == true) { - std::string worldLog = world->DumpWorldToLog(); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] worldLog dumped to [%s]\n",__FILE__,__FUNCTION__,__LINE__,worldLog.c_str()); - } - } - //else if(key == configKeys.getCharKey("HotKeyRotateUnitDuringPlacement")){ - else if(isKeyPressed(configKeys.getSDLKey("HotKeyRotateUnitDuringPlacement"),key) == true) { - // Here the user triggers a unit rotation while placing a unit - if(isPlacingBuilding()) { - if(getBuilding()->getRotationAllowed()){ - ++selectedBuildingFacing; - } - } - } - //else if(key == configKeys.getCharKey("HotKeySelectDamagedUnit")) { - else if(isKeyPressed(configKeys.getSDLKey("HotKeySelectDamagedUnit"),key) == true) { - selectInterestingUnit(iutDamaged); - } - //else if(key == configKeys.getCharKey("HotKeySelectStoreUnit")) { - else if(isKeyPressed(configKeys.getSDLKey("HotKeySelectStoreUnit"),key) == true) { - selectInterestingUnit(iutStore); - } - //else if(key == configKeys.getCharKey("HotKeySelectedUnitsAttack")) { - else if(isKeyPressed(configKeys.getSDLKey("HotKeySelectedUnitsAttack"),key) == true) { - clickCommonCommand(ccAttack); - } - //else if(key == configKeys.getCharKey("HotKeySelectedUnitsStop")) { - else if(isKeyPressed(configKeys.getSDLKey("HotKeySelectedUnitsStop"),key) == true) { - clickCommonCommand(ccStop); - } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s] key = [%c][%d]\n", __FILE__, + __FUNCTION__, key, key); + + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + + // if(key == configKeys.getCharKey("HotKeyCenterCameraOnSelection")) { + if (isKeyPressed(configKeys.getSDLKey("HotKeyCenterCameraOnSelection"), + key) == true) { + centerCameraOnSelection(); + } + // else if(key == configKeys.getCharKey("HotKeySelectIdleHarvesterUnit")) { + else if (isKeyPressed(configKeys.getSDLKey("HotKeySelectIdleHarvesterUnit"), + key) == true) { + selectInterestingUnit(iutIdleHarvester); + } + // else if(key == configKeys.getCharKey("HotKeySelectBuiltBuilding")) { + else if (isKeyPressed(configKeys.getSDLKey("HotKeySelectBuiltBuilding"), + key) == true) { + selectInterestingUnit(iutBuiltBuilding); + } + // else if(key == configKeys.getCharKey("HotKeyDumpWorldToLog")) { + else if (isKeyPressed(configKeys.getSDLKey("HotKeyDumpWorldToLog"), key) == + true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled == + true) { + std::string worldLog = world->DumpWorldToLog(); + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] worldLog dumped to [%s]\n", + __FILE__, __FUNCTION__, __LINE__, + worldLog.c_str()); + } + } + // else if(key == configKeys.getCharKey("HotKeyRotateUnitDuringPlacement")){ + else if (isKeyPressed(configKeys.getSDLKey("HotKeyRotateUnitDuringPlacement"), + key) == true) { + // Here the user triggers a unit rotation while placing a unit + if (isPlacingBuilding()) { + if (getBuilding()->getRotationAllowed()) { + ++selectedBuildingFacing; + } + } + } + // else if(key == configKeys.getCharKey("HotKeySelectDamagedUnit")) { + else if (isKeyPressed(configKeys.getSDLKey("HotKeySelectDamagedUnit"), key) == + true) { + selectInterestingUnit(iutDamaged); + } + // else if(key == configKeys.getCharKey("HotKeySelectStoreUnit")) { + else if (isKeyPressed(configKeys.getSDLKey("HotKeySelectStoreUnit"), key) == + true) { + selectInterestingUnit(iutStore); + } + // else if(key == configKeys.getCharKey("HotKeySelectedUnitsAttack")) { + else if (isKeyPressed(configKeys.getSDLKey("HotKeySelectedUnitsAttack"), + key) == true) { + clickCommonCommand(ccAttack); + } + // else if(key == configKeys.getCharKey("HotKeySelectedUnitsStop")) { + else if (isKeyPressed(configKeys.getSDLKey("HotKeySelectedUnitsStop"), key) == + true) { + clickCommonCommand(ccStop); + } } -void Gui::switchToNextDisplayColor(){ - display.switchColor(); -} +void Gui::switchToNextDisplayColor() { display.switchColor(); } -void Gui::onSelectionChanged(){ - resetState(); - computeDisplay(); +void Gui::onSelectionChanged() { + resetState(); + computeDisplay(); } // ================= PRIVATE ================= -void Gui::giveOneClickOrders(){ - //printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - std::pair result(crFailUndefined,""); - bool queueKeyDown = isKeyDown(queueCommandKey); - if(selection.isUniform()){ - result= commander->tryGiveCommand(&selection, activeCommandType, Vec2i(0), (Unit*)NULL, queueKeyDown); - } - else{ - result= commander->tryGiveCommand(&selection, activeCommandClass, Vec2i(0), (Unit*)NULL, queueKeyDown); - } - addOrdersResultToConsole(activeCommandClass, result); - activeCommandType= NULL; - activeCommandClass= ccStop; +void Gui::giveOneClickOrders() { + // printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + + std::pair result(crFailUndefined, ""); + bool queueKeyDown = isKeyDown(queueCommandKey); + if (selection.isUniform()) { + result = commander->tryGiveCommand(&selection, activeCommandType, Vec2i(0), + (Unit *)NULL, queueKeyDown); + } else { + result = commander->tryGiveCommand(&selection, activeCommandClass, Vec2i(0), + (Unit *)NULL, queueKeyDown); + } + addOrdersResultToConsole(activeCommandClass, result); + activeCommandType = NULL; + activeCommandClass = ccStop; } void Gui::giveDefaultOrders(int x, int y) { - //compute target - //printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - const Unit *targetUnit= NULL; - Vec2i targetPos; - if(computeTarget(Vec2i(x, y), targetPos, targetUnit) == false) { - console->addStdMessage("InvalidPosition"); - return; - } - //printf("In [%s::%s Line: %d] targetUnit = %p\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,targetUnit); - giveDefaultOrders(targetPos.x,targetPos.y,targetUnit,true); - //printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // compute target + // printf("In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + const Unit *targetUnit = NULL; + Vec2i targetPos; + if (computeTarget(Vec2i(x, y), targetPos, targetUnit) == false) { + console->addStdMessage("InvalidPosition"); + return; + } + // printf("In [%s::%s Line: %d] targetUnit = + // %p\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,targetUnit); + giveDefaultOrders(targetPos.x, targetPos.y, targetUnit, true); + // printf("In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); } -void Gui::givePreparedDefaultOrders(int x, int y){ - //printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - giveDefaultOrders(x, y, NULL,false); +void Gui::givePreparedDefaultOrders(int x, int y) { + // printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + giveDefaultOrders(x, y, NULL, false); } -void Gui::giveDefaultOrders(int x, int y,const Unit *targetUnit, bool paintMouse3d) { - //printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - bool queueKeyDown = isKeyDown(queueCommandKey); - Vec2i targetPos=Vec2i(x, y); - - //give order - //printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - std::pair result= commander->tryGiveCommand(&selection, targetPos, targetUnit, queueKeyDown); - - //printf("In [%s::%s Line: %d] selected units = %d result.first = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,selection.getCount(),result.first); - - //graphical result - addOrdersResultToConsole(activeCommandClass, result); - if(result.first == crSuccess || result.first == crSomeFailed) { - if(paintMouse3d) - mouse3d.enable(); - - if(random.randRange(0, 1)==0){ - SoundRenderer::getInstance().playFx( - selection.getFrontUnit()->getType()->getCommandSound(), - selection.getFrontUnit()->getCurrMidHeightVector(), - gameCamera->getPos()); - } - } - - //reset - resetState(); +void Gui::giveDefaultOrders(int x, int y, const Unit *targetUnit, + bool paintMouse3d) { + // printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + bool queueKeyDown = isKeyDown(queueCommandKey); + Vec2i targetPos = Vec2i(x, y); + + // give order + // printf("In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + std::pair result = commander->tryGiveCommand( + &selection, targetPos, targetUnit, queueKeyDown); + + // printf("In [%s::%s Line: %d] selected units = %d result.first = + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,selection.getCount(),result.first); + + // graphical result + addOrdersResultToConsole(activeCommandClass, result); + if (result.first == crSuccess || result.first == crSomeFailed) { + if (paintMouse3d) + mouse3d.enable(); + + if (random.randRange(0, 1) == 0) { + SoundRenderer::getInstance().playFx( + selection.getFrontUnit()->getType()->getCommandSound(), + selection.getFrontUnit()->getCurrMidHeightVector(), + gameCamera->getPos()); + } + } + + // reset + resetState(); } -void Gui::giveTwoClickOrders(int x, int y , bool prepared) { - //printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - std::pair result(crFailUndefined,""); - - //compute target - const Unit *targetUnit= NULL; - Vec2i targetPos; - if(prepared){ - targetPos=Vec2i(x, y); - } - else { - if(computeTarget(Vec2i(x, y), targetPos, targetUnit) == false) { - console->addStdMessage("InvalidPosition"); - return; - } - } - - bool queueKeyDown = isKeyDown(queueCommandKey); - //give orders to the units of this faction - if(selectingBuilding == false) { - if(selection.isUniform()) { - result= commander->tryGiveCommand(&selection, activeCommandType, - targetPos, targetUnit,queueKeyDown); - } - else { - result= commander->tryGiveCommand(&selection, activeCommandClass, - targetPos, targetUnit,queueKeyDown); - } - } - else { - //selecting building - result= commander->tryGiveCommand(&selection, - activeCommandType, posObjWorld, choosenBuildingType, - selectedBuildingFacing,queueKeyDown); +void Gui::giveTwoClickOrders(int x, int y, bool prepared) { + // printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + std::pair result(crFailUndefined, ""); + + // compute target + const Unit *targetUnit = NULL; + Vec2i targetPos; + if (prepared) { + targetPos = Vec2i(x, y); + } else { + if (computeTarget(Vec2i(x, y), targetPos, targetUnit) == false) { + console->addStdMessage("InvalidPosition"); + return; + } + } + + bool queueKeyDown = isKeyDown(queueCommandKey); + // give orders to the units of this faction + if (selectingBuilding == false) { + if (selection.isUniform()) { + result = commander->tryGiveCommand(&selection, activeCommandType, + targetPos, targetUnit, queueKeyDown); + } else { + result = commander->tryGiveCommand(&selection, activeCommandClass, + targetPos, targetUnit, queueKeyDown); + } + } else { + // selecting building + result = commander->tryGiveCommand(&selection, activeCommandType, + posObjWorld, choosenBuildingType, + selectedBuildingFacing, queueKeyDown); + } + + // graphical result + addOrdersResultToConsole(activeCommandClass, result); + if (result.first == crSuccess || result.first == crSomeFailed) { + if (prepared == false) { + mouse3d.enable(); } - //graphical result - addOrdersResultToConsole(activeCommandClass, result); - if(result.first == crSuccess || result.first == crSomeFailed) { - if(prepared == false) { - mouse3d.enable(); - } - - if(random.randRange(0, 1) == 0) { - SoundRenderer::getInstance().playFx( - selection.getFrontUnit()->getType()->getCommandSound(), - selection.getFrontUnit()->getCurrMidHeightVector(), - gameCamera->getPos()); - } - } + if (random.randRange(0, 1) == 0) { + SoundRenderer::getInstance().playFx( + selection.getFrontUnit()->getType()->getCommandSound(), + selection.getFrontUnit()->getCurrMidHeightVector(), + gameCamera->getPos()); + } + } } void Gui::centerCameraOnSelection() { - if(selection.isEmpty() == false) { - Vec3f refPos= selection.getRefPos(); - gameCamera->centerXZ(refPos.x, refPos.z); - } + if (selection.isEmpty() == false) { + Vec3f refPos = selection.getRefPos(); + gameCamera->centerXZ(refPos.x, refPos.z); + } } void Gui::selectInterestingUnit(InterestingUnitType iut) { - const Faction *thisFaction = world->getThisFaction(); - const Unit* previousUnit = NULL; - bool previousFound = true; - - //start at the next harvester - if(selection.getCount() == 1) { - const Unit* refUnit= selection.getFrontUnit(); - - if(refUnit->isInteresting(iut)) { - previousUnit= refUnit; - previousFound= false; - } - } - - //clear selection - selection.clear(); - - //search - for(int index = 0; index < thisFaction->getUnitCount(); ++index){ - Unit* unit = thisFaction->getUnit(index); - - if(previousFound == true) { - if(unit->isInteresting(iut)) { - selection.select(unit,false); - break; - } - } - else{ - if(unit == previousUnit) { - previousFound = true; - } - } - } - - //search again if we have a previous - if(selection.isEmpty() && previousUnit != NULL && previousFound == true) { - for(int index = 0; index < thisFaction->getUnitCount(); ++index) { - Unit* unit = thisFaction->getUnit(index); - - if(unit->isInteresting(iut)) { - selection.select(unit,false); - break; - } - } - } + const Faction *thisFaction = world->getThisFaction(); + const Unit *previousUnit = NULL; + bool previousFound = true; + + // start at the next harvester + if (selection.getCount() == 1) { + const Unit *refUnit = selection.getFrontUnit(); + + if (refUnit->isInteresting(iut)) { + previousUnit = refUnit; + previousFound = false; + } + } + + // clear selection + selection.clear(); + + // search + for (int index = 0; index < thisFaction->getUnitCount(); ++index) { + Unit *unit = thisFaction->getUnit(index); + + if (previousFound == true) { + if (unit->isInteresting(iut)) { + selection.select(unit, false); + break; + } + } else { + if (unit == previousUnit) { + previousFound = true; + } + } + } + + // search again if we have a previous + if (selection.isEmpty() && previousUnit != NULL && previousFound == true) { + for (int index = 0; index < thisFaction->getUnitCount(); ++index) { + Unit *unit = thisFaction->getUnit(index); + + if (unit->isInteresting(iut)) { + selection.select(unit, false); + break; + } + } + } } void Gui::clickCommonCommand(CommandClass commandClass) { - for(int index = 0; index < Display::downCellCount; ++index) { - const CommandType *ct = display.getCommandType(index); + for (int index = 0; index < Display::downCellCount; ++index) { + const CommandType *ct = display.getCommandType(index); - if((ct != NULL && ct->getClass() == commandClass) || - display.getCommandClass(index) == commandClass) { + if ((ct != NULL && ct->getClass() == commandClass) || + display.getCommandClass(index) == commandClass) { - mouseDownDisplayUnitSkills(index); - break; - } - } - computeDisplay(); + mouseDownDisplayUnitSkills(index); + break; + } + } + computeDisplay(); } void Gui::mouseDownDisplayUnitSkills(int posDisplay) { - if(selection.isEmpty() == false) { - if(posDisplay != cancelPos) { - if(posDisplay != meetingPointPos) { - const Unit *unit= selection.getFrontUnit(); - - //uniform selection - if(selection.isUniform()) { - const CommandType *ct = display.getCommandType(posDisplay); - - // try to switch to next attack type - if(activeCommandClass == ccAttack && activeCommandType!=NULL) { - - int maxI = unit->getType()->getCommandTypeCount(); - int cmdTypeId = activeCommandType->getId(); - int cmdTypeIdNext = cmdTypeId+1; - - while(cmdTypeIdNext != cmdTypeId) { - if(cmdTypeIdNext >= maxI) { - cmdTypeIdNext = 0; - } - const CommandType *ctype = display.getCommandType(cmdTypeIdNext); - if(ctype != NULL && ctype->getClass() == ccAttack) { - if(ctype != NULL && unit->getFaction()->reqsOk(ctype)) { - posDisplay=cmdTypeIdNext; - ct = display.getCommandType(posDisplay); - break; - } - } - cmdTypeIdNext++; - } - } - - if(ct != NULL && unit->getFaction()->reqsOk(ct)) { - activeCommandType= ct; - activeCommandClass= activeCommandType->getClass(); - } - else { - posDisplay= invalidPos; - activeCommandType= NULL; - activeCommandClass= ccStop; - return; - } - } - - //non uniform selection - else { - activeCommandType= NULL; - activeCommandClass= display.getCommandClass(posDisplay); - if (activeCommandClass == ccAttack) { - unit= selection.getUnitFromCC(ccAttack); - } - - } - - //give orders depending on command type - if(!selection.isEmpty()){ - const CommandType *ct= selection.getUnit(0)->getType()->getFirstCtOfClass(activeCommandClass); - if (activeCommandClass == ccAttack) { - ct = selection.getUnitFromCC(ccAttack)->getType()->getFirstCtOfClass(activeCommandClass); - } - if(activeCommandType!=NULL && activeCommandType->getClass()==ccBuild){ - assert(selection.isUniform()); - selectingBuilding= true; - } - else if(ct->getClicks()==cOne){ - invalidatePosObjWorld(); - giveOneClickOrders(); - } - else{ - selectingPos= true; - activePos= posDisplay; - } - } - } - else{ - activePos= posDisplay; - selectingMeetingPoint= true; - } - } - else{ - commander->tryCancelCommand(&selection); - } - } + if (selection.isEmpty() == false) { + if (posDisplay != cancelPos) { + if (posDisplay != meetingPointPos) { + const Unit *unit = selection.getFrontUnit(); + + // uniform selection + if (selection.isUniform()) { + const CommandType *ct = display.getCommandType(posDisplay); + + // try to switch to next attack type + if (activeCommandClass == ccAttack && activeCommandType != NULL) { + + int maxI = unit->getType()->getCommandTypeCount(); + int cmdTypeId = activeCommandType->getId(); + int cmdTypeIdNext = cmdTypeId + 1; + + while (cmdTypeIdNext != cmdTypeId) { + if (cmdTypeIdNext >= maxI) { + cmdTypeIdNext = 0; + } + const CommandType *ctype = display.getCommandType(cmdTypeIdNext); + if (ctype != NULL && ctype->getClass() == ccAttack) { + if (ctype != NULL && unit->getFaction()->reqsOk(ctype)) { + posDisplay = cmdTypeIdNext; + ct = display.getCommandType(posDisplay); + break; + } + } + cmdTypeIdNext++; + } + } + + if (ct != NULL && unit->getFaction()->reqsOk(ct)) { + activeCommandType = ct; + activeCommandClass = activeCommandType->getClass(); + } else { + posDisplay = invalidPos; + activeCommandType = NULL; + activeCommandClass = ccStop; + return; + } + } + + // non uniform selection + else { + activeCommandType = NULL; + activeCommandClass = display.getCommandClass(posDisplay); + if (activeCommandClass == ccAttack) { + unit = selection.getUnitFromCC(ccAttack); + } + } + + // give orders depending on command type + if (!selection.isEmpty()) { + const CommandType *ct = + selection.getUnit(0)->getType()->getFirstCtOfClass( + activeCommandClass); + if (activeCommandClass == ccAttack) { + ct = + selection.getUnitFromCC(ccAttack)->getType()->getFirstCtOfClass( + activeCommandClass); + } + if (activeCommandType != NULL && + activeCommandType->getClass() == ccBuild) { + assert(selection.isUniform()); + selectingBuilding = true; + } else if (ct->getClicks() == cOne) { + invalidatePosObjWorld(); + giveOneClickOrders(); + } else { + selectingPos = true; + activePos = posDisplay; + } + } + } else { + activePos = posDisplay; + selectingMeetingPoint = true; + } + } else { + commander->tryCancelCommand(&selection); + } + } } void Gui::mouseDownDisplayUnitBuild(int posDisplay) { - //int factionIndex = world->getThisFactionIndex(); - - if(posDisplay == cancelPos) { - resetState(); - } - else { - if(activeCommandType != NULL && - activeCommandType->getClass() == ccBuild) { - - const BuildCommandType *bct = dynamic_cast(activeCommandType); - if(bct != NULL) { - const UnitType *ut = bct->getBuilding(posDisplay); - - const Unit *unit = selection.getFrontUnit(); - if(unit != NULL && unit->getFaction() != NULL) { - - if(selection.canSelectUnitFactionCheck(unit) == true && - unit->getFaction()->reqsOk(ut)) { - - choosenBuildingType = ut; - selectingPos = true; - selectedBuildingFacing = CardinalDir(CardinalDir::NORTH); - activePos = posDisplay; - } - } - } - } - } -} + // int factionIndex = world->getThisFactionIndex(); + if (posDisplay == cancelPos) { + resetState(); + } else { + if (activeCommandType != NULL && activeCommandType->getClass() == ccBuild) { -string Gui::computeDefaultInfoString() { - string result=""; - - if(selection.isUniform()) { - if(selection.isObserver() || selection.isCommandable()) { - // default is the description extension - result = selection.getFrontUnit()->getDescExtension(game->showTranslatedTechTree()); - } - } - return result; + const BuildCommandType *bct = + dynamic_cast(activeCommandType); + if (bct != NULL) { + const UnitType *ut = bct->getBuilding(posDisplay); + + const Unit *unit = selection.getFrontUnit(); + if (unit != NULL && unit->getFaction() != NULL) { + + if (selection.canSelectUnitFactionCheck(unit) == true && + unit->getFaction()->reqsOk(ut)) { + + choosenBuildingType = ut; + selectingPos = true; + selectedBuildingFacing = CardinalDir(CardinalDir::NORTH); + activePos = posDisplay; + } + } + } + } + } } +string Gui::computeDefaultInfoString() { + string result = ""; -void Gui::computeInfoString(int posDisplay){ - - Lang &lang= Lang::getInstance(); - - lastPosDisplay = posDisplay; - - display.setInfoText(computeDefaultInfoString()); - - if(posDisplay!=invalidPos && selection.isCommandable()){ - if(!selectingBuilding){ - if(posDisplay==cancelPos){ - display.setInfoText(lang.getString("Cancel")); - } - else if(posDisplay==meetingPointPos){ - display.setInfoText(lang.getString("MeetingPoint")); - } - else{ - //uniform selection - if(selection.isUniform()){ - const Unit *unit= selection.getFrontUnit(); - const CommandType *ct= display.getCommandType(posDisplay); - - if(ct!=NULL){ - if(unit->getFaction()->reqsOk(ct)){ - display.setInfoText(ct->getDesc(unit->getTotalUpgrade(),game->showTranslatedTechTree())); - } - else{ - display.setInfoText(ct->getReqDesc(game->showTranslatedTechTree())); - if(ct->getClass()==ccUpgrade){ - string text=""; - const UpgradeCommandType *uct= static_cast(ct); - if(unit->getFaction()->getUpgradeManager()->isUpgrading(uct->getProducedUpgrade())){ - text=lang.getString("Upgrading")+"\n\n"; - } - else if(unit->getFaction()->getUpgradeManager()->isUpgraded(uct->getProducedUpgrade())){ - text=lang.getString("AlreadyUpgraded")+"\n\n"; - } - display.setInfoText(text+ct->getReqDesc(game->showTranslatedTechTree())); - } - //locked by scenario - else if(ct->getClass()==ccProduce){ - string text=""; - const ProduceCommandType *pct= static_cast(ct); - if(unit->getFaction()->isUnitLocked(pct->getProducedUnit())){ - display.setInfoText(lang.getString("LockedByScenario")+"\n\n"+ct->getReqDesc(game->showTranslatedTechTree())); - } - } - else if(ct->getClass()==ccMorph){ - const MorphCommandType *mct= static_cast(ct); - if(unit->getFaction()->isUnitLocked(mct->getMorphUnit())){ - display.setInfoText(lang.getString("LockedByScenario")+"\n\n"+ct->getReqDesc(game->showTranslatedTechTree())); - } - } - } - } - } - - //non uniform selection - else{ - const UnitType *ut= selection.getFrontUnit()->getType(); - CommandClass cc= display.getCommandClass(posDisplay); - if(cc!=ccNull){ - if (cc == ccAttack) { - const Unit* attackingUnit = selection.getUnitFromCC(ccAttack); - display.setInfoText(lang.getString("CommonCommand") + ": " + attackingUnit->getType()->getFirstCtOfClass(cc)->toString(true)); - } else { - display.setInfoText(lang.getString("CommonCommand") + ": " + ut->getFirstCtOfClass(cc)->toString(true)); - } - } - } - } - } - else{ - if(posDisplay==cancelPos){ - display.setInfoText(lang.getString("Return")); - } - else{ - if(activeCommandType!=NULL && activeCommandType->getClass()==ccBuild){ - //locked by scenario - const BuildCommandType *bct= static_cast(activeCommandType); - const Unit *unit= selection.getFrontUnit(); - if(unit->getFaction()->isUnitLocked(bct->getBuilding(posDisplay))){ - display.setInfoText(lang.getString("LockedByScenario")+"\n\n"+bct->getBuilding(posDisplay)->getReqDesc(game->showTranslatedTechTree())); - } else { - bool translatedValue= game->showTranslatedTechTree(); - const UnitType *building=bct->getBuilding(posDisplay); - string str= lang.getString("BuildSpeed",(translatedValue == true ? "" : "english"))+": "+ intToStr(bct->getBuildSkillType()->getSpeed())+"\n"; - str+=""+Lang::getInstance().getString("TimeSteps",(translatedValue == true ? "" : "english"))+": "+intToStr(building->getProductionTime())+"\n"; - int64 speed=bct->getBuildSkillType()->getSpeed()+bct->getBuildSkillType()->getTotalSpeed(unit->getTotalUpgrade()); - int64 time=building->getProductionTime(); - int64 seconds=time*100/speed; - str+=""+Lang::getInstance().getString("Time",(translatedValue == true ? "" : "english"))+": "+intToStr(seconds); - str+="\n\n"; - str+=building->getReqDesc(translatedValue); - display.setInfoText(str); - } - } - } - } - } + if (selection.isUniform()) { + if (selection.isObserver() || selection.isCommandable()) { + // default is the description extension + result = selection.getFrontUnit()->getDescExtension( + game->showTranslatedTechTree()); + } + } + return result; } -void Gui::computeDisplay(){ - - //printf("Start ===> computeDisplay()\n"); - Lang &lang= Lang::getInstance(); - //init - display.clear(); - - // ================ PART 1 ================ - const Object *selectedResourceObject =getSelectedResourceObject(); - if(selection.isEmpty() && selectedResourceObject != NULL && selectedResourceObject->getResource() != NULL) { - Resource *r = selectedResourceObject->getResource(); - display.setTitle(r->getType()->getName(game->showTranslatedTechTree())); - display.setText(lang.getString("Amount")+ ": "+intToStr(r->getAmount())+" / "+intToStr(r->getType()->getDefResPerPatch())); - //display.setProgressBar(r->); - display.setUpImage(0, r->getType()->getImage()); - } - else { - //title, text and progress bar - if(selection.getCount() == 1){ - display.setTitle(selection.getFrontUnit()->getFullName(game->showTranslatedTechTree())); - display.setText(selection.getFrontUnit()->getDesc(game->showTranslatedTechTree())); - display.setProgressBar(selection.getFrontUnit()->getProductionPercent()); - } - - //portraits - int unitIndex = 0; - for(unitIndex = 0; unitIndex < selection.getCount(); ++unitIndex){ - try { - const Unit *unit = selection.getUnit(unitIndex); - if(unit == NULL) { - throw megaglest_runtime_error("unit == NULL"); - } - if(unit->getType() == NULL) { - throw megaglest_runtime_error("unit->getType() == NULL"); - } - if(unit->getType()->getImage() == NULL) { - throw megaglest_runtime_error("unit->getType()->getImage()"); - } - - display.setUpImage(unitIndex, unit->getType()->getImage()); - } - catch(exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Error in unit selection for index: %d error [%s]",unitIndex,ex.what()); - throw megaglest_runtime_error(szBuf, true); - } - } - - // ================ PART 2 ================ - - if(selectingPos || selectingMeetingPoint){ - //printf("selectingPos || selectingMeetingPoint\n"); - display.setDownSelectedPos(activePos); - } - - //printf("computeDisplay selection.isCommandable() = %d\n",selection.isCommandable()); - - if(selection.isCommandable()) { - //printf("selection.isComandable()\n"); - - if(selectingBuilding == false){ - - //cancel button - const Unit *u= selection.getFrontUnit(); - const UnitType *ut= u->getType(); - if(selection.isCancelable()) { - //printf("selection.isCancelable() commandcount = %d\n",selection.getUnit(0)->getCommandSize()); - if(selection.getUnit(0)->getCommandSize() > 0){ - //printf("Current Command [%s]\n",selection.getUnit(0)->getCurrCommand()->toString().c_str()); - } - - display.setDownImage(cancelPos, ut->getCancelImage()); - display.setDownLighted(cancelPos, true); - } - - //meeting point - if(selection.isMeetable()){ - //printf("selection.isMeetable()\n"); - - display.setDownImage(meetingPointPos, ut->getMeetingPointImage()); - display.setDownLighted(meetingPointPos, true); - } - - //printf("computeDisplay selection.isUniform() = %d\n",selection.isUniform()); - if(selection.isUniform()) { - //printf("selection.isUniform()\n"); - - //uniform selection - if(u->isBuilt()){ - //printf("u->isBuilt()\n"); - - int morphPos= 8; - for(int i= 0; i < ut->getCommandTypeCount(); ++i){ - int displayPos= i; - const CommandType *ct= ut->getCommandType(i); - if(ct->getClass() == ccMorph) { - displayPos= morphPos++; - } - - //printf("computeDisplay i = %d displayPos = %d morphPos = %d ct->getClass() = %d [%s]\n",i,displayPos,morphPos,ct->getClass(),ct->getName().c_str()); - const ProducibleType *produced= ct->getProduced(); - int possibleAmount=1; - if(produced != NULL) { - possibleAmount= u->getFaction()->getAmountOfProducable(produced,ct); - } - - display.setDownImage(displayPos, ct->getImage()); - display.setCommandType(displayPos, ct); - display.setCommandClass(displayPos, ct->getClass()); - bool reqOk=u->getFaction()->reqsOk(ct); - display.setDownLighted(displayPos,reqOk); - - if (reqOk && produced != NULL) { - if (possibleAmount == 0) { - display.setDownRedLighted(displayPos); - } else if (selection.getCount() > possibleAmount) { - // orange colors just for command types that produce or morph units!! - const UnitType *unitType=NULL; - if (dynamic_cast(ct) != NULL) { - unitType = dynamic_cast(ct)->getMorphUnit(); - } else if (dynamic_cast(ct) != NULL) { - unitType = dynamic_cast(ct)->getProducedUnit(); - } - if (unitType != NULL) { - if (unitType->getMaxUnitCount() > 0) { - // check for maxUnitCount - int stillAllowed = unitType->getMaxUnitCount() - u->getFaction()->getCountForMaxUnitCount(unitType); - if (stillAllowed > possibleAmount) { - // enough resources to let morph/produce everything possible - display.setDownOrangeLighted(displayPos); - } - } else - // not enough resources to let all morph/produce - display.setDownOrangeLighted(displayPos); - } - } - } - } - } - } - else{ - //printf("selection.isUniform() == FALSE\n"); - //non uniform selection - int lastCommand= 0; - for(int i= 0; i < ccCount; ++i){ - CommandClass cc= static_cast (i); - - //printf("computeDisplay i = %d cc = %d isshared = %d lastCommand = %d\n",i,cc,isSharedCommandClass(cc),lastCommand); - - const Unit* attackingUnit = NULL; - if (cc == ccAttack) { - attackingUnit = selection.getUnitFromCC(ccAttack); - } - - if((cc == ccAttack && attackingUnit != NULL) || (isSharedCommandClass(cc) && cc != ccBuild)){ - display.setDownLighted(lastCommand, true); - - if (cc == ccAttack && attackingUnit != NULL) { - display.setDownImage(lastCommand, attackingUnit->getType()->getFirstCtOfClass(cc)->getImage()); - } else { - display.setDownImage(lastCommand, ut->getFirstCtOfClass(cc)->getImage()); - } - display.setCommandClass(lastCommand, cc); - lastCommand++; - } - } - } - } - else if (activeCommandType != NULL && activeCommandType->getClass() == ccBuild) { - const Unit *u = selection.getFrontUnit(); - const BuildCommandType* bct = static_cast(activeCommandType); - for (int i = 0; i < bct->getBuildingCount(); ++i) { - display.setDownImage(i, bct->getBuilding(i)->getImage()); - - const UnitType *produced = bct->getBuilding(i); - int possibleAmount = 1; - if (produced != NULL) { - possibleAmount = u->getFaction()->getAmountOfProducable(produced, bct); - } - bool reqOk = u->getFaction()->reqsOk(produced); - display.setDownLighted(i, reqOk); - - if (reqOk && produced != NULL) { - if (possibleAmount == 0) { - display.setDownRedLighted(i); - } - } - } - - display.setDownImage(cancelPos, selection.getFrontUnit()->getType()->getCancelImage()); - display.setDownLighted(cancelPos, true); - } - } - } - - // refresh other things - if(!isSelecting() && !isSelectingPos()){ - if(!isSelectingPos() && lastPosDisplay == invalidPos){ - computeInfoString(lastPosDisplay); - } - } +void Gui::computeInfoString(int posDisplay) { + + Lang &lang = Lang::getInstance(); + + lastPosDisplay = posDisplay; + + display.setInfoText(computeDefaultInfoString()); + + if (posDisplay != invalidPos && selection.isCommandable()) { + if (!selectingBuilding) { + if (posDisplay == cancelPos) { + display.setInfoText(lang.getString("Cancel")); + } else if (posDisplay == meetingPointPos) { + display.setInfoText(lang.getString("MeetingPoint")); + } else { + // uniform selection + if (selection.isUniform()) { + const Unit *unit = selection.getFrontUnit(); + const CommandType *ct = display.getCommandType(posDisplay); + + if (ct != NULL) { + if (unit->getFaction()->reqsOk(ct)) { + display.setInfoText(ct->getDesc(unit->getTotalUpgrade(), + game->showTranslatedTechTree())); + } else { + display.setInfoText( + ct->getReqDesc(game->showTranslatedTechTree())); + if (ct->getClass() == ccUpgrade) { + string text = ""; + const UpgradeCommandType *uct = + static_cast(ct); + if (unit->getFaction()->getUpgradeManager()->isUpgrading( + uct->getProducedUpgrade())) { + text = lang.getString("Upgrading") + "\n\n"; + } else if (unit->getFaction()->getUpgradeManager()->isUpgraded( + uct->getProducedUpgrade())) { + text = lang.getString("AlreadyUpgraded") + "\n\n"; + } + display.setInfoText( + text + ct->getReqDesc(game->showTranslatedTechTree())); + } + // locked by scenario + else if (ct->getClass() == ccProduce) { + string text = ""; + const ProduceCommandType *pct = + static_cast(ct); + if (unit->getFaction()->isUnitLocked(pct->getProducedUnit())) { + display.setInfoText( + lang.getString("LockedByScenario") + "\n\n" + + ct->getReqDesc(game->showTranslatedTechTree())); + } + } else if (ct->getClass() == ccMorph) { + const MorphCommandType *mct = + static_cast(ct); + if (unit->getFaction()->isUnitLocked(mct->getMorphUnit())) { + display.setInfoText( + lang.getString("LockedByScenario") + "\n\n" + + ct->getReqDesc(game->showTranslatedTechTree())); + } + } + } + } + } + // non uniform selection + else { + const UnitType *ut = selection.getFrontUnit()->getType(); + CommandClass cc = display.getCommandClass(posDisplay); + if (cc != ccNull) { + if (cc == ccAttack) { + const Unit *attackingUnit = selection.getUnitFromCC(ccAttack); + display.setInfoText( + lang.getString("CommonCommand") + ": " + + attackingUnit->getType()->getFirstCtOfClass(cc)->toString( + true)); + } else { + display.setInfoText(lang.getString("CommonCommand") + ": " + + ut->getFirstCtOfClass(cc)->toString(true)); + } + } + } + } + } else { + if (posDisplay == cancelPos) { + display.setInfoText(lang.getString("Return")); + } else { + if (activeCommandType != NULL && + activeCommandType->getClass() == ccBuild) { + // locked by scenario + const BuildCommandType *bct = + static_cast(activeCommandType); + const Unit *unit = selection.getFrontUnit(); + if (unit->getFaction()->isUnitLocked(bct->getBuilding(posDisplay))) { + display.setInfoText( + lang.getString("LockedByScenario") + "\n\n" + + bct->getBuilding(posDisplay) + ->getReqDesc(game->showTranslatedTechTree())); + } else { + bool translatedValue = game->showTranslatedTechTree(); + const UnitType *building = bct->getBuilding(posDisplay); + string str = + lang.getString("BuildSpeed", + (translatedValue == true ? "" : "english")) + + ": " + intToStr(bct->getBuildSkillType()->getSpeed()) + "\n"; + str += + "" + + Lang::getInstance().getString( + "TimeSteps", (translatedValue == true ? "" : "english")) + + ": " + intToStr(building->getProductionTime()) + "\n"; + int64 speed = bct->getBuildSkillType()->getSpeed() + + bct->getBuildSkillType()->getTotalSpeed( + unit->getTotalUpgrade()); + int64 time = building->getProductionTime(); + int64 seconds = time * 100 / speed; + str += "" + + Lang::getInstance().getString( + "Time", (translatedValue == true ? "" : "english")) + + ": " + intToStr(seconds); + str += "\n\n"; + str += building->getReqDesc(translatedValue); + display.setInfoText(str); + } + } + } + } + } } -int Gui::computePosDisplay(int x, int y){ - int posDisplay= display.computeDownIndex(x, y); - - //printf("computePosDisplay x = %d y = %d posDisplay = %d Display::downCellCount = %d cc = %d ct = %p\n",x,y,posDisplay,Display::downCellCount,display.getCommandClass(posDisplay),display.getCommandType(posDisplay)); - - if(posDisplay < 0 || posDisplay >= Display::downCellCount) { - posDisplay= invalidPos; - //printf("In [%s:%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); - } - else if(selection.isCommandable()) { - if(posDisplay != cancelPos) { - if(posDisplay != meetingPointPos) { - if(selectingBuilding == false) { - //standard selection - if(display.getCommandClass(posDisplay) == ccNull && display.getCommandType(posDisplay) == NULL) { - posDisplay= invalidPos; - //printf("In [%s:%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); - } - } - else { - //building selection - if(activeCommandType != NULL && activeCommandType->getClass() == ccBuild){ - const BuildCommandType *bct= static_cast(activeCommandType); - if(posDisplay >= bct->getBuildingCount()) { - posDisplay= invalidPos; - //printf("In [%s:%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); - } - } - } - } - else{ - //check meeting point - if(!selection.isMeetable()) { - posDisplay= invalidPos; - //printf("In [%s:%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); - } - } - } - else { - //check cancel button - if(selection.isCancelable() == false) { - posDisplay= invalidPos; - //printf("In [%s:%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); - } - } - } - else { - posDisplay= invalidPos; - //printf("In [%s:%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); +void Gui::computeDisplay() { + + // printf("Start ===> computeDisplay()\n"); + Lang &lang = Lang::getInstance(); + // init + display.clear(); + + // ================ PART 1 ================ + const Object *selectedResourceObject = getSelectedResourceObject(); + if (selection.isEmpty() && selectedResourceObject != NULL && + selectedResourceObject->getResource() != NULL) { + Resource *r = selectedResourceObject->getResource(); + display.setTitle(r->getType()->getName(game->showTranslatedTechTree())); + display.setText(lang.getString("Amount") + ": " + intToStr(r->getAmount()) + + " / " + intToStr(r->getType()->getDefResPerPatch())); + // display.setProgressBar(r->); + display.setUpImage(0, r->getType()->getImage()); + } else { + // title, text and progress bar + if (selection.getCount() == 1) { + display.setTitle(selection.getFrontUnit()->getFullName( + game->showTranslatedTechTree())); + display.setText( + selection.getFrontUnit()->getDesc(game->showTranslatedTechTree())); + display.setProgressBar(selection.getFrontUnit()->getProductionPercent()); } - //printf("computePosDisplay returning = %d\n",posDisplay); + // portraits + int unitIndex = 0; + for (unitIndex = 0; unitIndex < selection.getCount(); ++unitIndex) { + try { + const Unit *unit = selection.getUnit(unitIndex); + if (unit == NULL) { + throw megaglest_runtime_error("unit == NULL"); + } + if (unit->getType() == NULL) { + throw megaglest_runtime_error("unit->getType() == NULL"); + } + if (unit->getType()->getImage() == NULL) { + throw megaglest_runtime_error("unit->getType()->getImage()"); + } - return posDisplay; -} + display.setUpImage(unitIndex, unit->getType()->getImage()); + } catch (exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "Error in unit selection for index: %d error [%s]", unitIndex, + ex.what()); + throw megaglest_runtime_error(szBuf, true); + } + } + + // ================ PART 2 ================ + + if (selectingPos || selectingMeetingPoint) { + // printf("selectingPos || selectingMeetingPoint\n"); + display.setDownSelectedPos(activePos); + } -void Gui::addOrdersResultToConsole(CommandClass cc, std::pair result) { - - switch(result.first) { - case crSuccess: - break; - case crFailReqs: - switch(cc){ - case ccBuild: - console->addStdMessage("BuildingNoReqs",result.second); - break; - case ccProduce: - console->addStdMessage("UnitNoReqs",result.second); - break; - case ccMorph: - console->addStdMessage("MorphNoReqs",result.second); - break; - case ccUpgrade: - console->addStdMessage("UpgradeNoReqs",result.second); - break; - default: - break; + // printf("computeDisplay selection.isCommandable() = + // %d\n",selection.isCommandable()); + + if (selection.isCommandable()) { + // printf("selection.isComandable()\n"); + + if (selectingBuilding == false) { + + // cancel button + const Unit *u = selection.getFrontUnit(); + const UnitType *ut = u->getType(); + if (selection.isCancelable()) { + // printf("selection.isCancelable() commandcount = + // %d\n",selection.getUnit(0)->getCommandSize()); + if (selection.getUnit(0)->getCommandSize() > 0) { + // printf("Current Command + // [%s]\n",selection.getUnit(0)->getCurrCommand()->toString().c_str()); + } + + display.setDownImage(cancelPos, ut->getCancelImage()); + display.setDownLighted(cancelPos, true); } - break; - case crFailRes: - switch(cc){ - case ccBuild: - console->addStdMessage("BuildingNoRes",result.second); - break; - case ccProduce: - console->addStdMessage("UnitNoRes",result.second); - break; - case ccMorph: - console->addStdMessage("MorphNoRes",result.second); - break; - case ccUpgrade: - console->addStdMessage("UpgradeNoRes",result.second); - break; - default: - break; + + // meeting point + if (selection.isMeetable()) { + // printf("selection.isMeetable()\n"); + + display.setDownImage(meetingPointPos, ut->getMeetingPointImage()); + display.setDownLighted(meetingPointPos, true); } - break; - case crFailUndefined: - console->addStdMessage("InvalidOrder",result.second); - break; + // printf("computeDisplay selection.isUniform() = + // %d\n",selection.isUniform()); + if (selection.isUniform()) { + // printf("selection.isUniform()\n"); + + // uniform selection + if (u->isBuilt()) { + // printf("u->isBuilt()\n"); + + int morphPos = 8; + for (int i = 0; i < ut->getCommandTypeCount(); ++i) { + int displayPos = i; + const CommandType *ct = ut->getCommandType(i); + if (ct->getClass() == ccMorph) { + displayPos = morphPos++; + } + + // printf("computeDisplay i = %d displayPos = %d morphPos = %d + // ct->getClass() = %d + // [%s]\n",i,displayPos,morphPos,ct->getClass(),ct->getName().c_str()); + const ProducibleType *produced = ct->getProduced(); + int possibleAmount = 1; + if (produced != NULL) { + possibleAmount = + u->getFaction()->getAmountOfProducable(produced, ct); + } + + display.setDownImage(displayPos, ct->getImage()); + display.setCommandType(displayPos, ct); + display.setCommandClass(displayPos, ct->getClass()); + bool reqOk = u->getFaction()->reqsOk(ct); + display.setDownLighted(displayPos, reqOk); + + if (reqOk && produced != NULL) { + if (possibleAmount == 0) { + display.setDownRedLighted(displayPos); + } else if (selection.getCount() > possibleAmount) { + // orange colors just for command types that produce or morph + // units!! + const UnitType *unitType = NULL; + if (dynamic_cast(ct) != NULL) { + unitType = dynamic_cast(ct) + ->getMorphUnit(); + } else if (dynamic_cast(ct) != + NULL) { + unitType = dynamic_cast(ct) + ->getProducedUnit(); + } + if (unitType != NULL) { + if (unitType->getMaxUnitCount() > 0) { + // check for maxUnitCount + int stillAllowed = + unitType->getMaxUnitCount() - + u->getFaction()->getCountForMaxUnitCount(unitType); + if (stillAllowed > possibleAmount) { + // enough resources to let morph/produce everything + // possible + display.setDownOrangeLighted(displayPos); + } + } else + // not enough resources to let all morph/produce + display.setDownOrangeLighted(displayPos); + } + } + } + } + } + } else { + // printf("selection.isUniform() == FALSE\n"); + // non uniform selection + int lastCommand = 0; + for (int i = 0; i < ccCount; ++i) { + CommandClass cc = static_cast(i); + + // printf("computeDisplay i = %d cc = %d isshared = %d lastCommand = + // %d\n",i,cc,isSharedCommandClass(cc),lastCommand); + + const Unit *attackingUnit = NULL; + if (cc == ccAttack) { + attackingUnit = selection.getUnitFromCC(ccAttack); + } + + if ((cc == ccAttack && attackingUnit != NULL) || + (isSharedCommandClass(cc) && cc != ccBuild)) { + display.setDownLighted(lastCommand, true); + + if (cc == ccAttack && attackingUnit != NULL) { + display.setDownImage(lastCommand, attackingUnit->getType() + ->getFirstCtOfClass(cc) + ->getImage()); + } else { + display.setDownImage(lastCommand, + ut->getFirstCtOfClass(cc)->getImage()); + } + display.setCommandClass(lastCommand, cc); + lastCommand++; + } + } + } + } else if (activeCommandType != NULL && + activeCommandType->getClass() == ccBuild) { + const Unit *u = selection.getFrontUnit(); + const BuildCommandType *bct = + static_cast(activeCommandType); + for (int i = 0; i < bct->getBuildingCount(); ++i) { + display.setDownImage(i, bct->getBuilding(i)->getImage()); + + const UnitType *produced = bct->getBuilding(i); + int possibleAmount = 1; + if (produced != NULL) { + possibleAmount = + u->getFaction()->getAmountOfProducable(produced, bct); + } + bool reqOk = u->getFaction()->reqsOk(produced); + display.setDownLighted(i, reqOk); + + if (reqOk && produced != NULL) { + if (possibleAmount == 0) { + display.setDownRedLighted(i); + } + } + } - case crSomeFailed: - console->addStdMessage("SomeOrdersFailed",result.second); - break; + display.setDownImage( + cancelPos, selection.getFrontUnit()->getType()->getCancelImage()); + display.setDownLighted(cancelPos, true); + } + } + } + + // refresh other things + if (!isSelecting() && !isSelectingPos()) { + if (!isSelectingPos() && lastPosDisplay == invalidPos) { + computeInfoString(lastPosDisplay); } + } } -bool Gui::isSharedCommandClass(CommandClass commandClass){ - for(int i=0; igetType()->getFirstCtOfClass(commandClass); - if(ct==NULL || !unit->getFaction()->reqsOk(ct)) - return false; +int Gui::computePosDisplay(int x, int y) { + int posDisplay = display.computeDownIndex(x, y); + + // printf("computePosDisplay x = %d y = %d posDisplay = %d + // Display::downCellCount = %d cc = %d ct = + // %p\n",x,y,posDisplay,Display::downCellCount,display.getCommandClass(posDisplay),display.getCommandType(posDisplay)); + + if (posDisplay < 0 || posDisplay >= Display::downCellCount) { + posDisplay = invalidPos; + // printf("In [%s:%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); + } else if (selection.isCommandable()) { + if (posDisplay != cancelPos) { + if (posDisplay != meetingPointPos) { + if (selectingBuilding == false) { + // standard selection + if (display.getCommandClass(posDisplay) == ccNull && + display.getCommandType(posDisplay) == NULL) { + posDisplay = invalidPos; + // printf("In [%s:%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); + } + } else { + // building selection + if (activeCommandType != NULL && + activeCommandType->getClass() == ccBuild) { + const BuildCommandType *bct = + static_cast(activeCommandType); + if (posDisplay >= bct->getBuildingCount()) { + posDisplay = invalidPos; + // printf("In [%s:%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); + } + } + } + } else { + // check meeting point + if (!selection.isMeetable()) { + posDisplay = invalidPos; + // printf("In [%s:%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); + } + } + } else { + // check cancel button + if (selection.isCancelable() == false) { + posDisplay = invalidPos; + // printf("In [%s:%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); + } } - return true; + } else { + posDisplay = invalidPos; + // printf("In [%s:%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); + } + + // printf("computePosDisplay returning = %d\n",posDisplay); + + return posDisplay; } +void Gui::addOrdersResultToConsole(CommandClass cc, + std::pair result) { + + switch (result.first) { + case crSuccess: + break; + case crFailReqs: + switch (cc) { + case ccBuild: + console->addStdMessage("BuildingNoReqs", result.second); + break; + case ccProduce: + console->addStdMessage("UnitNoReqs", result.second); + break; + case ccMorph: + console->addStdMessage("MorphNoReqs", result.second); + break; + case ccUpgrade: + console->addStdMessage("UpgradeNoReqs", result.second); + break; + default: + break; + } + break; + case crFailRes: + switch (cc) { + case ccBuild: + console->addStdMessage("BuildingNoRes", result.second); + break; + case ccProduce: + console->addStdMessage("UnitNoRes", result.second); + break; + case ccMorph: + console->addStdMessage("MorphNoRes", result.second); + break; + case ccUpgrade: + console->addStdMessage("UpgradeNoRes", result.second); + break; + default: + break; + } + break; -void Gui::computeSelected(bool doubleClick, bool force){ - Selection::UnitContainer units; - - if( force || ( lastQuadCalcFrame+selectionCalculationFrameSkip < game->getTotalRenderFps() ) ){ - lastQuadCalcFrame=game->getTotalRenderFps(); - const Object *selectedResourceObject=NULL; - selectedResourceObjectPos=Vec2i(-1,-1); - if(selectionQuad.isEnabled() && selectionQuad.getPosUp().dist(selectionQuad.getPosDown())getMapPos()); - } - } - else{ - Renderer::getInstance().computeSelected(units, selectedResourceObject, false, selectionQuad.getPosDown(), selectionQuad.getPosUp()); - } - selectingBuilding= false; - activeCommandType= NULL; - - //select all units of the same type if double click - if(doubleClick && units.empty() == false){ - const Unit *refUnit= getRelevantObjectFromSelection(&units); - int factionIndex= refUnit->getFactionIndex(); - for(int i=0; igetFaction(factionIndex)->getUnitCount(); ++i){ - Unit *unit= world->getFaction(factionIndex)->getUnit(i); - if(unit->getPos().dist(refUnit->getPosNotThreadSafe())getType()==refUnit->getType() && unit->isOperative()==refUnit->isOperative() ) - { - units.push_back(unit); - } - } - } - - bool shiftDown= isKeyDown(vkShift); - bool controlDown= isKeyDown(vkControl); - - if(!shiftDown && !controlDown){ - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] about to call selection.clear()\n",__FILE__,__FUNCTION__,__LINE__); - selection.clear(); - } - - if(!controlDown){ - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] about to call selection.select(units)\n",__FILE__,__FUNCTION__,__LINE__); - selection.select(units,shiftDown); - if(!selection.isEmpty()){ - selectedResourceObject=NULL; - } - } - else{ - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] selection.unSelect(units)\n",__FILE__,__FUNCTION__,__LINE__); - selection.unSelect(units); - } - } + case crFailUndefined: + console->addStdMessage("InvalidOrder", result.second); + break; + + case crSomeFailed: + console->addStdMessage("SomeOrdersFailed", result.second); + break; + } } -bool Gui::computeTarget(const Vec2i &screenPos, Vec2i &targetPos, const Unit *&targetUnit){ - Selection::UnitContainer uc; - Renderer &renderer= Renderer::getInstance(); - const Object* obj= NULL; - renderer.computeSelected(uc, obj, true, screenPos, screenPos); - validPosObjWorld= false; - - if(uc.empty() == false){ - targetUnit= getRelevantObjectFromSelection(&uc); - targetPos= targetUnit->getPosNotThreadSafe(); - // we need to respect cellmaps. Searching for a cell which is really occupied - int size=targetUnit->getType()->getSize(); - bool foundUnit=false; - for ( int x= 0;xgetMap()->getCell(Vec2i(targetPos.x+x,targetPos.y+y))->getUnit(targetUnit->getType()->getField())==targetUnit){ - targetPos=Vec2i(targetPos.x+x,targetPos.y+y); - foundUnit=true; - break; - } - } - if(foundUnit) break; - } - highlightedUnitId=targetUnit->getId(); - getHighlightedUnit()->resetHighlight(); - return true; - } - else if(obj != NULL){ - targetUnit= NULL; - highlightedResourceObjectPos=Map::toSurfCoords(obj->getMapPos()); - - Object *selObj = getHighlightedResourceObject(); - if(selObj != NULL) { - selObj->resetHighlight(); - // get real click pos - targetPos=game->getMouseCellPos(); - //validPosObjWorld= true; - //posObjWorld = targetPos; - - int tx= targetPos.x; - int ty= targetPos.y; - - int ox= obj->getMapPos().x; - int oy= obj->getMapPos().y; - - Resource* clickedRecource= world->getMap()->getSurfaceCell(Map::toSurfCoords(obj->getMapPos()))->getResource(); - - // lets see if the click had the same Resource - if(clickedRecource == world->getMap()->getSurfaceCell(Map::toSurfCoords(targetPos))->getResource()){ - // same ressource is meant, so use the user selected position - return true; - } - else{// calculate a valid resource position which is as near as possible to the selected position - Vec2i testIt= Vec2i(obj->getMapPos()); - /////////////// - // test both // - /////////////// - if(ty < oy){ - testIt.y--; - } - else if(ty > oy){ - testIt.y++; - } - if(tx < ox){ - testIt.x--; - } - else if(tx > ox){ - testIt.x++; - } - - if(clickedRecource == world->getMap()->getSurfaceCell(Map::toSurfCoords(testIt))->getResource()){ - // same ressource is meant, so use this position - targetPos= testIt; - //posObjWorld= targetPos; - return true; - } - else{ - testIt= Vec2i(obj->getMapPos()); - } - - ///////////////// - // test y-only // - ///////////////// - if(ty < oy){ - testIt.y--; - } - else if(ty > oy){ - testIt.y++; - } - if(clickedRecource == world->getMap()->getSurfaceCell(Map::toSurfCoords(testIt))->getResource()){ - // same ressource is meant, so use this position - targetPos= testIt; - //posObjWorld= targetPos; - return true; - } - else{ - testIt= Vec2i(obj->getMapPos()); - } - - ///////////////// - // test x-only // - ///////////////// - if(tx < ox){ - testIt.x--; - } - else if(tx > ox){ - testIt.x++; - } - if(clickedRecource == world->getMap()->getSurfaceCell(Map::toSurfCoords(testIt))->getResource()){ - // same ressource is meant, so use this position - targetPos= testIt; - //posObjWorld= targetPos; - return true; - } - } - // give up and use the object position; - targetPos= obj->getMapPos(); - posObjWorld= targetPos; - return true; - } - else { - return false; - } - } - else{ - targetUnit= NULL; - targetPos=game->getMouseCellPos(); - if(game->isValidMouseCellPos()){ - validPosObjWorld= true; - posObjWorld= targetPos; - - if(world->getMap()->getSurfaceCell(Map::toSurfCoords(targetPos))->getResource() != NULL) { - highlightedResourceObjectPos=Map::toSurfCoords(targetPos); - - Object *selObj = getHighlightedResourceObject(); - if(selObj != NULL) { - selObj->resetHighlight(); - } - } - - return true; - } - else{ - return false; - } - } +bool Gui::isSharedCommandClass(CommandClass commandClass) { + for (int i = 0; i < selection.getCount(); ++i) { + const Unit *unit = selection.getUnit(i); + const CommandType *ct = unit->getType()->getFirstCtOfClass(commandClass); + if (ct == NULL || !unit->getFaction()->reqsOk(ct)) + return false; + } + return true; +} + +void Gui::computeSelected(bool doubleClick, bool force) { + Selection::UnitContainer units; + + if (force || (lastQuadCalcFrame + selectionCalculationFrameSkip < + game->getTotalRenderFps())) { + lastQuadCalcFrame = game->getTotalRenderFps(); + const Object *selectedResourceObject = NULL; + selectedResourceObjectPos = Vec2i(-1, -1); + if (selectionQuad.isEnabled() && + selectionQuad.getPosUp().dist(selectionQuad.getPosDown()) < + minQuadSize) { + // Renderer::getInstance().computeSelected(units, selectedResourceObject, + // true, selectionQuad.getPosDown(), selectionQuad.getPosDown()); + Renderer::getInstance().computeSelected(units, selectedResourceObject, + true, selectionQuad.getPosDown(), + selectionQuad.getPosDown()); + if (selectedResourceObject != NULL) { + selectedResourceObjectPos = + Map::toSurfCoords(selectedResourceObject->getMapPos()); + } + } else { + Renderer::getInstance().computeSelected(units, selectedResourceObject, + false, selectionQuad.getPosDown(), + selectionQuad.getPosUp()); + } + selectingBuilding = false; + activeCommandType = NULL; + + // select all units of the same type if double click + if (doubleClick && units.empty() == false) { + const Unit *refUnit = getRelevantObjectFromSelection(&units); + int factionIndex = refUnit->getFactionIndex(); + for (int i = 0; i < world->getFaction(factionIndex)->getUnitCount(); + ++i) { + Unit *unit = world->getFaction(factionIndex)->getUnit(i); + if (unit->getPos().dist(refUnit->getPosNotThreadSafe()) < + doubleClickSelectionRadius && + unit->getType() == refUnit->getType() && + unit->isOperative() == refUnit->isOperative()) { + units.push_back(unit); + } + } + } + + bool shiftDown = isKeyDown(vkShift); + bool controlDown = isKeyDown(vkControl); + + if (!shiftDown && !controlDown) { + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] + // about to call selection.clear()\n",__FILE__,__FUNCTION__,__LINE__); + selection.clear(); + } + + if (!controlDown) { + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] + // about to call + // selection.select(units)\n",__FILE__,__FUNCTION__,__LINE__); + selection.select(units, shiftDown); + if (!selection.isEmpty()) { + selectedResourceObject = NULL; + } + } else { + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] + // selection.unSelect(units)\n",__FILE__,__FUNCTION__,__LINE__); + selection.unSelect(units); + } + } } -Unit* Gui::getRelevantObjectFromSelection(Selection::UnitContainer *uc){ - Unit *resultUnit=NULL; - for(int i= 0; i < (int)uc->size(); ++i) { - resultUnit= uc->at(i); - if(resultUnit->getType()->hasSkillClass(scMove)){// moving units are more relevant than non moving ones - break; - } - } - return resultUnit; +bool Gui::computeTarget(const Vec2i &screenPos, Vec2i &targetPos, + const Unit *&targetUnit) { + Selection::UnitContainer uc; + Renderer &renderer = Renderer::getInstance(); + const Object *obj = NULL; + renderer.computeSelected(uc, obj, true, screenPos, screenPos); + validPosObjWorld = false; + + if (uc.empty() == false) { + targetUnit = getRelevantObjectFromSelection(&uc); + targetPos = targetUnit->getPosNotThreadSafe(); + // we need to respect cellmaps. Searching for a cell which is really + // occupied + int size = targetUnit->getType()->getSize(); + bool foundUnit = false; + for (int x = 0; x < size; ++x) { + for (int y = 0; y < size; ++y) { + if (world->getMap() + ->getCell(Vec2i(targetPos.x + x, targetPos.y + y)) + ->getUnit(targetUnit->getType()->getField()) == targetUnit) { + targetPos = Vec2i(targetPos.x + x, targetPos.y + y); + foundUnit = true; + break; + } + } + if (foundUnit) + break; + } + highlightedUnitId = targetUnit->getId(); + getHighlightedUnit()->resetHighlight(); + return true; + } else if (obj != NULL) { + targetUnit = NULL; + highlightedResourceObjectPos = Map::toSurfCoords(obj->getMapPos()); + + Object *selObj = getHighlightedResourceObject(); + if (selObj != NULL) { + selObj->resetHighlight(); + // get real click pos + targetPos = game->getMouseCellPos(); + // validPosObjWorld= true; + // posObjWorld = targetPos; + + int tx = targetPos.x; + int ty = targetPos.y; + + int ox = obj->getMapPos().x; + int oy = obj->getMapPos().y; + + Resource *clickedRecource = + world->getMap() + ->getSurfaceCell(Map::toSurfCoords(obj->getMapPos())) + ->getResource(); + + // lets see if the click had the same Resource + if (clickedRecource == world->getMap() + ->getSurfaceCell(Map::toSurfCoords(targetPos)) + ->getResource()) { + // same ressource is meant, so use the user selected position + return true; + } else { // calculate a valid resource position which is as near as + // possible to the selected position + Vec2i testIt = Vec2i(obj->getMapPos()); + /////////////// + // test both // + /////////////// + if (ty < oy) { + testIt.y--; + } else if (ty > oy) { + testIt.y++; + } + if (tx < ox) { + testIt.x--; + } else if (tx > ox) { + testIt.x++; + } + + if (clickedRecource == world->getMap() + ->getSurfaceCell(Map::toSurfCoords(testIt)) + ->getResource()) { + // same ressource is meant, so use this position + targetPos = testIt; + // posObjWorld= targetPos; + return true; + } else { + testIt = Vec2i(obj->getMapPos()); + } + + ///////////////// + // test y-only // + ///////////////// + if (ty < oy) { + testIt.y--; + } else if (ty > oy) { + testIt.y++; + } + if (clickedRecource == world->getMap() + ->getSurfaceCell(Map::toSurfCoords(testIt)) + ->getResource()) { + // same ressource is meant, so use this position + targetPos = testIt; + // posObjWorld= targetPos; + return true; + } else { + testIt = Vec2i(obj->getMapPos()); + } + + ///////////////// + // test x-only // + ///////////////// + if (tx < ox) { + testIt.x--; + } else if (tx > ox) { + testIt.x++; + } + if (clickedRecource == world->getMap() + ->getSurfaceCell(Map::toSurfCoords(testIt)) + ->getResource()) { + // same ressource is meant, so use this position + targetPos = testIt; + // posObjWorld= targetPos; + return true; + } + } + // give up and use the object position; + targetPos = obj->getMapPos(); + posObjWorld = targetPos; + return true; + } else { + return false; + } + } else { + targetUnit = NULL; + targetPos = game->getMouseCellPos(); + if (game->isValidMouseCellPos()) { + validPosObjWorld = true; + posObjWorld = targetPos; + + if (world->getMap() + ->getSurfaceCell(Map::toSurfCoords(targetPos)) + ->getResource() != NULL) { + highlightedResourceObjectPos = Map::toSurfCoords(targetPos); + + Object *selObj = getHighlightedResourceObject(); + if (selObj != NULL) { + selObj->resetHighlight(); + } + } + + return true; + } else { + return false; + } + } +} + +Unit *Gui::getRelevantObjectFromSelection(Selection::UnitContainer *uc) { + Unit *resultUnit = NULL; + for (int i = 0; i < (int)uc->size(); ++i) { + resultUnit = uc->at(i); + if (resultUnit->getType()->hasSkillClass( + scMove)) { // moving units are more relevant than non moving ones + break; + } + } + return resultUnit; } void Gui::saveGame(XmlNode *rootNode) const { - std::map mapTagReplacements; - XmlNode *guiNode = rootNode->addChild("Gui"); - - guiNode->addAttribute("random",intToStr(random.getLastNumber()), mapTagReplacements); - guiNode->addAttribute("posObjWorld",posObjWorld.getString(), mapTagReplacements); - guiNode->addAttribute("validPosObjWorld",intToStr(validPosObjWorld), mapTagReplacements); - if(choosenBuildingType != NULL) { - const Faction* thisFaction= world->getThisFaction(); - guiNode->addAttribute("choosenBuildingType",choosenBuildingType->getName(false), mapTagReplacements); - guiNode->addAttribute("choosenBuildingTypeFactionIndex",intToStr(thisFaction->getIndex()), mapTagReplacements); - } - if(activeCommandType != NULL) { - guiNode->addAttribute("activeCommandType",activeCommandType->getName(false), mapTagReplacements); - } - - guiNode->addAttribute("activeCommandClass",intToStr(activeCommandClass), mapTagReplacements); - guiNode->addAttribute("activePos",intToStr(activePos), mapTagReplacements); - guiNode->addAttribute("lastPosDisplay",intToStr(lastPosDisplay), mapTagReplacements); - display.saveGame(guiNode); - selection.saveGame(guiNode); - guiNode->addAttribute("lastQuadCalcFrame",intToStr(lastQuadCalcFrame), mapTagReplacements); - guiNode->addAttribute("selectionCalculationFrameSkip",intToStr(selectionCalculationFrameSkip), mapTagReplacements); - guiNode->addAttribute("minQuadSize",intToStr(minQuadSize), mapTagReplacements); - guiNode->addAttribute("lastGroupRecall",intToStr(lastGroupRecall), mapTagReplacements); - guiNode->addAttribute("selectingBuilding",intToStr(selectingBuilding), mapTagReplacements); - guiNode->addAttribute("selectingPos",intToStr(selectingPos), mapTagReplacements); - guiNode->addAttribute("selectingMeetingPoint",intToStr(selectingMeetingPoint), mapTagReplacements); - guiNode->addAttribute("selectedBuildingFacing",intToStr(selectedBuildingFacing), mapTagReplacements); + std::map mapTagReplacements; + XmlNode *guiNode = rootNode->addChild("Gui"); + + guiNode->addAttribute("random", intToStr(random.getLastNumber()), + mapTagReplacements); + guiNode->addAttribute("posObjWorld", posObjWorld.getString(), + mapTagReplacements); + guiNode->addAttribute("validPosObjWorld", intToStr(validPosObjWorld), + mapTagReplacements); + if (choosenBuildingType != NULL) { + const Faction *thisFaction = world->getThisFaction(); + guiNode->addAttribute("choosenBuildingType", + choosenBuildingType->getName(false), + mapTagReplacements); + guiNode->addAttribute("choosenBuildingTypeFactionIndex", + intToStr(thisFaction->getIndex()), + mapTagReplacements); + } + if (activeCommandType != NULL) { + guiNode->addAttribute("activeCommandType", + activeCommandType->getName(false), + mapTagReplacements); + } + + guiNode->addAttribute("activeCommandClass", intToStr(activeCommandClass), + mapTagReplacements); + guiNode->addAttribute("activePos", intToStr(activePos), mapTagReplacements); + guiNode->addAttribute("lastPosDisplay", intToStr(lastPosDisplay), + mapTagReplacements); + display.saveGame(guiNode); + selection.saveGame(guiNode); + guiNode->addAttribute("lastQuadCalcFrame", intToStr(lastQuadCalcFrame), + mapTagReplacements); + guiNode->addAttribute("selectionCalculationFrameSkip", + intToStr(selectionCalculationFrameSkip), + mapTagReplacements); + guiNode->addAttribute("minQuadSize", intToStr(minQuadSize), + mapTagReplacements); + guiNode->addAttribute("lastGroupRecall", intToStr(lastGroupRecall), + mapTagReplacements); + guiNode->addAttribute("selectingBuilding", intToStr(selectingBuilding), + mapTagReplacements); + guiNode->addAttribute("selectingPos", intToStr(selectingPos), + mapTagReplacements); + guiNode->addAttribute("selectingMeetingPoint", + intToStr(selectingMeetingPoint), mapTagReplacements); + guiNode->addAttribute("selectedBuildingFacing", + intToStr(selectedBuildingFacing), mapTagReplacements); } void Gui::loadGame(const XmlNode *rootNode, World *world) { - const XmlNode *guiNode = rootNode->getChild("Gui"); - - random.setLastNumber(guiNode->getAttribute("random")->getIntValue()); - posObjWorld = Vec2i::strToVec2(guiNode->getAttribute("posObjWorld")->getValue()); - validPosObjWorld = guiNode->getAttribute("validPosObjWorld")->getIntValue() != 0; - if(guiNode->hasAttribute("choosenBuildingType") == true) { - string unitType = guiNode->getAttribute("choosenBuildingType")->getValue(); - int factionIndex = guiNode->getAttribute("choosenBuildingTypeFactionIndex")->getIntValue(); - choosenBuildingType = world->getFaction(factionIndex)->getType()->getUnitType(unitType); - } - activePos = guiNode->getAttribute("activePos")->getIntValue(); - lastPosDisplay = guiNode->getAttribute("lastPosDisplay")->getIntValue(); - display.loadGame(guiNode); - selection.loadGame(guiNode,world); - // don't load this! lastQuadCalcFrame = guiNode->getAttribute("lastQuadCalcFrame")->getIntValue(); - lastQuadCalcFrame = game->getTotalRenderFps(); - selectionCalculationFrameSkip = guiNode->getAttribute("selectionCalculationFrameSkip")->getIntValue(); - minQuadSize = guiNode->getAttribute("minQuadSize")->getIntValue(); - lastGroupRecall = guiNode->getAttribute("lastGroupRecall")->getIntValue(); + const XmlNode *guiNode = rootNode->getChild("Gui"); + + random.setLastNumber(guiNode->getAttribute("random")->getIntValue()); + posObjWorld = + Vec2i::strToVec2(guiNode->getAttribute("posObjWorld")->getValue()); + validPosObjWorld = + guiNode->getAttribute("validPosObjWorld")->getIntValue() != 0; + if (guiNode->hasAttribute("choosenBuildingType") == true) { + string unitType = guiNode->getAttribute("choosenBuildingType")->getValue(); + int factionIndex = + guiNode->getAttribute("choosenBuildingTypeFactionIndex")->getIntValue(); + choosenBuildingType = + world->getFaction(factionIndex)->getType()->getUnitType(unitType); + } + activePos = guiNode->getAttribute("activePos")->getIntValue(); + lastPosDisplay = guiNode->getAttribute("lastPosDisplay")->getIntValue(); + display.loadGame(guiNode); + selection.loadGame(guiNode, world); + // don't load this! lastQuadCalcFrame = + // guiNode->getAttribute("lastQuadCalcFrame")->getIntValue(); + lastQuadCalcFrame = game->getTotalRenderFps(); + selectionCalculationFrameSkip = + guiNode->getAttribute("selectionCalculationFrameSkip")->getIntValue(); + minQuadSize = guiNode->getAttribute("minQuadSize")->getIntValue(); + lastGroupRecall = guiNode->getAttribute("lastGroupRecall")->getIntValue(); } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/gui/gui.h b/source/glest_game/gui/gui.h index c9c8905c9..027d65c3e 100644 --- a/source/glest_game/gui/gui.h +++ b/source/glest_game/gui/gui.h @@ -12,21 +12,22 @@ #ifndef _GLEST_GAME_GUI_H_ #define _GLEST_GAME_GUI_H_ -#include "resource.h" #include "command_type.h" -#include "display.h" #include "commander.h" #include "console.h" -#include "selection.h" -#include "randomgen.h" -#include +#include "display.h" +#include "leak_dumper.h" #include "object.h" #include "platform_common.h" -#include "leak_dumper.h" +#include "randomgen.h" +#include "resource.h" +#include "selection.h" +#include using Shared::Util::RandomGen; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { class Unit; class World; @@ -34,57 +35,52 @@ class CommandType; class GameCamera; class Game; -enum DisplayState{ - dsEmpty, - dsUnitSkills, - dsUnitBuild, - dsEnemy -}; +enum DisplayState { dsEmpty, dsUnitSkills, dsUnitBuild, dsEnemy }; // ===================================================== // class Mouse3d // ===================================================== -class Mouse3d{ +class Mouse3d { public: - static const float fadeSpeed; + static const float fadeSpeed; private: - bool enabled; - int rot; - float fade; + bool enabled; + int rot; + float fade; public: - Mouse3d(); + Mouse3d(); - void enable(); - void update(); + void enable(); + void update(); - bool isEnabled() const {return enabled;} - float getFade() const {return fade;} - int getRot() const {return rot;} + bool isEnabled() const { return enabled; } + float getFade() const { return fade; } + int getRot() const { return rot; } }; // ===================================================== // class SelectionQuad // ===================================================== -class SelectionQuad{ +class SelectionQuad { private: - Vec2i posDown; - Vec2i posUp; - bool enabled; + Vec2i posDown; + Vec2i posUp; + bool enabled; public: - SelectionQuad(); + SelectionQuad(); - bool isEnabled() const {return enabled;} - Vec2i getPosDown() const {return posDown;} - Vec2i getPosUp() const {return posUp;} + bool isEnabled() const { return enabled; } + Vec2i getPosDown() const { return posDown; } + Vec2i getPosUp() const { return posUp; } - void setPosDown(const Vec2i &posDown); - void setPosUp(const Vec2i &posUp); - void disable(); + void setPosDown(const Vec2i &posDown); + void setPosUp(const Vec2i &posUp); + void disable(); }; // ===================================================== @@ -95,144 +91,147 @@ class SelectionQuad{ class Gui { public: - static const int maxSelBuff= 128*5; - static const int upgradeDisplayIndex= 8; + static const int maxSelBuff = 128 * 5; + static const int upgradeDisplayIndex = 8; - static const int meetingPointPos= 14; - static const int cancelPos= 15; - static const int imageCount= 16; + static const int meetingPointPos = 14; + static const int cancelPos = 15; + static const int imageCount = 16; - static const int invalidPos= -1; - static const int doubleClickSelectionRadius= 20; + static const int invalidPos = -1; + static const int doubleClickSelectionRadius = 20; private: - //External objects - RandomGen random; - const Commander *commander; - const World *world; - const Game *game; - GameCamera *gameCamera; - Console *console; - - //Positions - Vec2i posObjWorld; //world coords - bool validPosObjWorld; - - //display - const UnitType *choosenBuildingType; - const CommandType *activeCommandType; - CommandClass activeCommandClass; - int activePos; - int lastPosDisplay; - - //composite - Display display; - Mouse3d mouse3d; - Selection selection; - SelectionQuad selectionQuad; - int lastQuadCalcFrame; - int selectionCalculationFrameSkip; - int minQuadSize; - - Chrono lastGroupRecallTime; - int lastGroupRecall; - - //states - bool selectingBuilding; - bool selectingPos; - bool selectingMeetingPoint; - - CardinalDir selectedBuildingFacing; - Vec2i selectedResourceObjectPos; - Vec2i highlightedResourceObjectPos; - int highlightedUnitId; - - Texture2D* hudTexture; + // External objects + RandomGen random; + const Commander *commander; + const World *world; + const Game *game; + GameCamera *gameCamera; + Console *console; + + // Positions + Vec2i posObjWorld; // world coords + bool validPosObjWorld; + + // display + const UnitType *choosenBuildingType; + const CommandType *activeCommandType; + CommandClass activeCommandClass; + int activePos; + int lastPosDisplay; + + // composite + Display display; + Mouse3d mouse3d; + Selection selection; + SelectionQuad selectionQuad; + int lastQuadCalcFrame; + int selectionCalculationFrameSkip; + int minQuadSize; + + Chrono lastGroupRecallTime; + int lastGroupRecall; + + // states + bool selectingBuilding; + bool selectingPos; + bool selectingMeetingPoint; + + CardinalDir selectedBuildingFacing; + Vec2i selectedResourceObjectPos; + Vec2i highlightedResourceObjectPos; + int highlightedUnitId; + + Texture2D *hudTexture; public: - Gui(); - void init(Game *game); - void end(); - - //get - Vec2i getPosObjWorld() const {return posObjWorld;} - const UnitType *getBuilding() const; - - Texture2D *getHudTexture() const {return hudTexture;} - void setHudTexture(Texture2D* value) { hudTexture = value;} - - const Mouse3d *getMouse3d() const {return &mouse3d;} - const Display *getDisplay() const {return &display;} - const Selection *getSelection() const {return &selection;} - Selection *getSelectionPtr() {return &selection;} - const Object *getSelectedResourceObject() const; - Object *getHighlightedResourceObject() const; - Unit *getHighlightedUnit() const; - - const SelectionQuad *getSelectionQuad() const {return &selectionQuad;} - CardinalDir getSelectedFacing() const {return selectedBuildingFacing;} - bool isSelected(const Unit *unit) const {return selection.hasUnit(unit);} - - bool isValidPosObjWorld() const {return validPosObjWorld;} - bool isSelecting() const {return selectionQuad.isEnabled();} - bool isSelectingPos() const {return selectingPos;} - bool isSelectingBuilding() const {return selectingBuilding;} - bool isPlacingBuilding() const; - - //set - void invalidatePosObjWorld(); - - //events - void update(); - void tick(); - bool mouseValid(int x, int y); - void mouseDownLeftDisplay(int x, int y); - void mouseMoveDisplay(int x, int y); - void mouseMoveOutsideDisplay(); - void mouseDownLeftGraphics(int x, int y, bool prepared); - void mouseDownRightGraphics(int x, int y, bool prepared); - void mouseUpLeftGraphics(int x, int y); - void mouseMoveGraphics(int x, int y); - void mouseDoubleClickLeftGraphics(int x, int y); - void groupKey(int groupIndex); - void hotKey(SDL_KeyboardEvent key); - - //misc - void switchToNextDisplayColor(); - void onSelectionChanged(); - - void saveGame(XmlNode *rootNode) const; - void loadGame(const XmlNode *rootNode, World *world); + Gui(); + void init(Game *game); + void end(); + + // get + Vec2i getPosObjWorld() const { return posObjWorld; } + const UnitType *getBuilding() const; + + Texture2D *getHudTexture() const { return hudTexture; } + void setHudTexture(Texture2D *value) { hudTexture = value; } + + const Mouse3d *getMouse3d() const { return &mouse3d; } + const Display *getDisplay() const { return &display; } + const Selection *getSelection() const { return &selection; } + Selection *getSelectionPtr() { return &selection; } + const Object *getSelectedResourceObject() const; + Object *getHighlightedResourceObject() const; + Unit *getHighlightedUnit() const; + + const SelectionQuad *getSelectionQuad() const { return &selectionQuad; } + CardinalDir getSelectedFacing() const { return selectedBuildingFacing; } + bool isSelected(const Unit *unit) const { return selection.hasUnit(unit); } + + bool isValidPosObjWorld() const { return validPosObjWorld; } + bool isSelecting() const { return selectionQuad.isEnabled(); } + bool isSelectingPos() const { return selectingPos; } + bool isSelectingBuilding() const { return selectingBuilding; } + bool isPlacingBuilding() const; + + // set + void invalidatePosObjWorld(); + + // events + void update(); + void tick(); + bool mouseValid(int x, int y); + void mouseDownLeftDisplay(int x, int y); + void mouseMoveDisplay(int x, int y); + void mouseMoveOutsideDisplay(); + void mouseDownLeftGraphics(int x, int y, bool prepared); + void mouseDownRightGraphics(int x, int y, bool prepared); + void mouseUpLeftGraphics(int x, int y); + void mouseMoveGraphics(int x, int y); + void mouseDoubleClickLeftGraphics(int x, int y); + void groupKey(int groupIndex); + void hotKey(SDL_KeyboardEvent key); + + // misc + void switchToNextDisplayColor(); + void onSelectionChanged(); + + void saveGame(XmlNode *rootNode) const; + void loadGame(const XmlNode *rootNode, World *world); private: - - //orders - void giveDefaultOrders(int x, int y); - void giveDefaultOrders(int x, int y, const Unit *targetUnit, bool paintMouse3d); - void givePreparedDefaultOrders(int x, int y); - void giveOneClickOrders(); - void giveTwoClickOrders(int x, int y, bool prepared); - - //hotkeys - void centerCameraOnSelection(); - void selectInterestingUnit(InterestingUnitType iut); - void clickCommonCommand(CommandClass commandClass); - - //misc - int computePosDisplay(int x, int y); - void computeDisplay(); - void resetState(); - void mouseDownDisplayUnitSkills(int posDisplay); - void mouseDownDisplayUnitBuild(int posDisplay); - void computeInfoString(int posDisplay); - string computeDefaultInfoString(); - void addOrdersResultToConsole(CommandClass cc, std::pair result); - bool isSharedCommandClass(CommandClass commandClass); - void computeSelected(bool doubleCkick,bool force); - bool computeTarget(const Vec2i &screenPos, Vec2i &targetPos, const Unit *&targetUnit); - Unit* getRelevantObjectFromSelection(Selection::UnitContainer *uc); + // orders + void giveDefaultOrders(int x, int y); + void giveDefaultOrders(int x, int y, const Unit *targetUnit, + bool paintMouse3d); + void givePreparedDefaultOrders(int x, int y); + void giveOneClickOrders(); + void giveTwoClickOrders(int x, int y, bool prepared); + + // hotkeys + void centerCameraOnSelection(); + void selectInterestingUnit(InterestingUnitType iut); + void clickCommonCommand(CommandClass commandClass); + + // misc + int computePosDisplay(int x, int y); + void computeDisplay(); + void resetState(); + void mouseDownDisplayUnitSkills(int posDisplay); + void mouseDownDisplayUnitBuild(int posDisplay); + void computeInfoString(int posDisplay); + string computeDefaultInfoString(); + void addOrdersResultToConsole(CommandClass cc, + std::pair result); + bool isSharedCommandClass(CommandClass commandClass); + void computeSelected(bool doubleCkick, bool force); + bool computeTarget(const Vec2i &screenPos, Vec2i &targetPos, + const Unit *&targetUnit); + Unit *getRelevantObjectFromSelection(Selection::UnitContainer *uc); }; -}} //end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/gui/selection.cpp b/source/glest_game/gui/selection.cpp index 180e0d766..e1aac30c2 100644 --- a/source/glest_game/gui/selection.cpp +++ b/source/glest_game/gui/selection.cpp @@ -13,441 +13,469 @@ #include -#include "unit_type.h" -#include "gui.h" #include "config.h" -#include "world.h" +#include "gui.h" #include "leak_dumper.h" +#include "unit_type.h" +#include "world.h" using namespace std; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class Selection // ===================================================== -void Selection::init(Gui *gui, int factionIndex, int teamIndex, bool allowSharedTeamUnits) { - this->factionIndex = factionIndex; - this->teamIndex = teamIndex; - this->allowSharedTeamUnits = allowSharedTeamUnits; - this->gui = gui; - clear(); +void Selection::init(Gui *gui, int factionIndex, int teamIndex, + bool allowSharedTeamUnits) { + this->factionIndex = factionIndex; + this->teamIndex = teamIndex; + this->allowSharedTeamUnits = allowSharedTeamUnits; + this->gui = gui; + clear(); } -Selection::~Selection(){ - clear(); -} +Selection::~Selection() { clear(); } bool Selection::canSelectUnitFactionCheck(const Unit *unit) const { - //check if enemy - if(unit->getFactionIndex() != factionIndex) { - if(this->allowSharedTeamUnits == false || - unit->getFaction()->getTeam() != teamIndex) { - return false; - } - } - - return true; + // check if enemy + if (unit->getFactionIndex() != factionIndex) { + if (this->allowSharedTeamUnits == false || + unit->getFaction()->getTeam() != teamIndex) { + return false; + } + } + + return true; } bool Selection::select(Unit *unit, bool addToSelection) { - bool result = false; - if((int)selectedUnits.size() >= Config::getInstance().getInt("MaxUnitSelectCount",intToStr(maxUnits).c_str())) { - return result; - } - - // Fix Bug reported on sourceforge.net: Glest::Game::Selection::select crash with NULL pointer - ID: 3608835 - if(unit != NULL) { - //check if already selected - for(int index = 0; index < (int)selectedUnits.size(); ++index) { - if(selectedUnits[index] == unit) { - return true; - } - } - - //check if dead - if(unit->isDead() == true) { - return false; - } - - //check if commandable - if(unit->getType()->isCommandable() == false && isEmpty() == false) { - return false; - } - - //check if multisel - if(unit->getType()->getMultiSelect() == false && isEmpty() == false) { - return false; - } - - //check if multitypesel - if(selectedUnits.size() > 0) { - bool isUnifromSelectOK = ( selectedUnits.front()->getType() == unit->getType() && unit->isOperative() == selectedUnits.front()->isOperative()); - if(selectedUnits.front()->getType()->getUniformSelect() == true && !isUnifromSelectOK ) { - if(addToSelection) - return false; - else - clear(); - } - - if (unit->getType()->getUniformSelect() == true - && !isUnifromSelectOK ) { - return false; - } - } - - //check if enemy - if(canSelectUnitFactionCheck(unit) == false && isEmpty() == false) { - return false; - } - - //check existing enemy - //if(selectedUnits.size() == 1 && selectedUnits.front()->getFactionIndex() != factionIndex) { - if(selectedUnits.size() == 1 && canSelectUnitFactionCheck(selectedUnits.front()) == false) { - clear(); - } - - //check existing multisel - if(selectedUnits.size() == 1 && - selectedUnits.front()->getType()->getMultiSelect() == false) { - clear(); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] unit selected [%s]\n",__FILE__,__FUNCTION__,__LINE__,unit->toString().c_str()); - - unit->addObserver(this); - - int unitTypeId = unit->getType()->getId(); - bool inserted = false; - for(int index = 0; index < (int)selectedUnits.size(); ++index) { - - int currentTypeId = selectedUnits[index]->getType()->getId(); - if(unitTypeId <= currentTypeId) { - - //place unit here - selectedUnits.insert(selectedUnits.begin() + index,unit); - inserted = true; - break; - } - } - if(inserted == false) { - selectedUnits.push_back(unit); - } - result = true; - gui->onSelectionChanged(); - } - - return result; + bool result = false; + if ((int)selectedUnits.size() >= + Config::getInstance().getInt("MaxUnitSelectCount", + intToStr(maxUnits).c_str())) { + return result; + } + + // Fix Bug reported on sourceforge.net: Glest::Game::Selection::select crash + // with NULL pointer - ID: 3608835 + if (unit != NULL) { + // check if already selected + for (int index = 0; index < (int)selectedUnits.size(); ++index) { + if (selectedUnits[index] == unit) { + return true; + } + } + + // check if dead + if (unit->isDead() == true) { + return false; + } + + // check if commandable + if (unit->getType()->isCommandable() == false && isEmpty() == false) { + return false; + } + + // check if multisel + if (unit->getType()->getMultiSelect() == false && isEmpty() == false) { + return false; + } + + // check if multitypesel + if (selectedUnits.size() > 0) { + bool isUnifromSelectOK = + (selectedUnits.front()->getType() == unit->getType() && + unit->isOperative() == selectedUnits.front()->isOperative()); + if (selectedUnits.front()->getType()->getUniformSelect() == true && + !isUnifromSelectOK) { + if (addToSelection) + return false; + else + clear(); + } + + if (unit->getType()->getUniformSelect() == true && !isUnifromSelectOK) { + return false; + } + } + + // check if enemy + if (canSelectUnitFactionCheck(unit) == false && isEmpty() == false) { + return false; + } + + // check existing enemy + // if(selectedUnits.size() == 1 && selectedUnits.front()->getFactionIndex() + // != factionIndex) { + if (selectedUnits.size() == 1 && + canSelectUnitFactionCheck(selectedUnits.front()) == false) { + clear(); + } + + // check existing multisel + if (selectedUnits.size() == 1 && + selectedUnits.front()->getType()->getMultiSelect() == false) { + clear(); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d] unit selected [%s]\n", + __FILE__, __FUNCTION__, __LINE__, unit->toString().c_str()); + + unit->addObserver(this); + + int unitTypeId = unit->getType()->getId(); + bool inserted = false; + for (int index = 0; index < (int)selectedUnits.size(); ++index) { + + int currentTypeId = selectedUnits[index]->getType()->getId(); + if (unitTypeId <= currentTypeId) { + + // place unit here + selectedUnits.insert(selectedUnits.begin() + index, unit); + inserted = true; + break; + } + } + if (inserted == false) { + selectedUnits.push_back(unit); + } + result = true; + gui->onSelectionChanged(); + } + + return result; } -void Selection::select(const UnitContainer &units, bool addToSelection){ +void Selection::select(const UnitContainer &units, bool addToSelection) { - //add units to gui - for(UnitIterator it = units.begin(); it != units.end(); ++it) { - select(*it,addToSelection); - } + // add units to gui + for (UnitIterator it = units.begin(); it != units.end(); ++it) { + select(*it, addToSelection); + } } void Selection::unSelect(const UnitContainer &units) { - //add units to gui - for(UnitIterator it = units.begin(); it != units.end(); ++it) { - for(int i = 0; i < (int)selectedUnits.size(); ++i) { - if(selectedUnits[i] == *it) { - unSelect(i); - } - } - } + // add units to gui + for (UnitIterator it = units.begin(); it != units.end(); ++it) { + for (int i = 0; i < (int)selectedUnits.size(); ++i) { + if (selectedUnits[i] == *it) { + unSelect(i); + } + } + } } void Selection::unSelect(int i) { - selectedUnits.erase(selectedUnits.begin() + i); - gui->onSelectionChanged(); + selectedUnits.erase(selectedUnits.begin() + i); + gui->onSelectionChanged(); } -void Selection::clear(){ - selectedUnits.clear(); -} +void Selection::clear() { selectedUnits.clear(); } -bool Selection::isUniform() const{ - if(selectedUnits.empty() == true) { - return true; - } +bool Selection::isUniform() const { + if (selectedUnits.empty() == true) { + return true; + } - const UnitType *ut= selectedUnits.front()->getType(); + const UnitType *ut = selectedUnits.front()->getType(); - for(int i = 0; i < (int)selectedUnits.size(); ++i) { - if(selectedUnits[i]->getType() != ut) { - return false; - } + for (int i = 0; i < (int)selectedUnits.size(); ++i) { + if (selectedUnits[i]->getType() != ut) { + return false; } - return true; + } + return true; } bool Selection::isEnemy() const { - return selectedUnits.size() == 1 && - //selectedUnits.front()->getFactionIndex() != factionIndex; - canSelectUnitFactionCheck(selectedUnits.front()) == false; + return selectedUnits.size() == 1 && + // selectedUnits.front()->getFactionIndex() != factionIndex; + canSelectUnitFactionCheck(selectedUnits.front()) == false; } bool Selection::isObserver() const { - return selectedUnits.size() == 1 && - (teamIndex == (GameConstants::maxPlayers -1 + fpt_Observer)); + return selectedUnits.size() == 1 && + (teamIndex == (GameConstants::maxPlayers - 1 + fpt_Observer)); } bool Selection::isCommandable() const { - //printf("\n\n\n\n********* selection.isCommandable() ---> isEmpty() [%d] isEnemy() [%d] selectedUnits.size() [%d]\n\n",isEmpty(),isEnemy(),(int)selectedUnits.size()); - - return - isEmpty() == false && - isEnemy() == false && - (selectedUnits.size() == 1 && selectedUnits.front()->isAlive() == false) == false && - selectedUnits.front()->getType()->isCommandable(); + // printf("\n\n\n\n********* selection.isCommandable() ---> isEmpty() [%d] + // isEnemy() [%d] selectedUnits.size() + // [%d]\n\n",isEmpty(),isEnemy(),(int)selectedUnits.size()); + + return isEmpty() == false && isEnemy() == false && + (selectedUnits.size() == 1 && + selectedUnits.front()->isAlive() == false) == false && + selectedUnits.front()->getType()->isCommandable(); } bool Selection::isCancelable() const { - return - selectedUnits.size() > 1 || - (selectedUnits.size() == 1 && selectedUnits[0]->anyCommand(true)); + return selectedUnits.size() > 1 || + (selectedUnits.size() == 1 && selectedUnits[0]->anyCommand(true)); } -bool Selection::isMeetable() const{ - return - isUniform() && - isCommandable() && - selectedUnits.front()->getType()->getMeetingPoint(); +bool Selection::isMeetable() const { + return isUniform() && isCommandable() && + selectedUnits.front()->getType()->getMeetingPoint(); } -Vec3f Selection::getRefPos() const{ - return getFrontUnit()->getCurrMidHeightVector(); +Vec3f Selection::getRefPos() const { + return getFrontUnit()->getCurrMidHeightVector(); } -bool Selection::hasUnit(const Unit* unit) const { - return find(selectedUnits.begin(), selectedUnits.end(), unit) != selectedUnits.end(); +bool Selection::hasUnit(const Unit *unit) const { + return find(selectedUnits.begin(), selectedUnits.end(), unit) != + selectedUnits.end(); } -bool Selection::assignGroup(int groupIndex, bool clearGroup,const UnitContainer *pUnits) { - if(groupIndex < 0 || groupIndex >= maxGroups) { - throw megaglest_runtime_error("Invalid value for groupIndex = " + intToStr(groupIndex)); - } - - //clear group - if(true==clearGroup){ - groups[groupIndex].clear(); - } - - //assign new group - const UnitContainer *addUnits = &selectedUnits; - if(pUnits != NULL) { - addUnits = pUnits; - } - - for(unsigned int i = 0; i < addUnits->size(); ++i) { - if(false == addUnitToGroup(groupIndex,(*addUnits)[i])){ - // don't try to add more, group is maybe full - return false; - } - } - return true; +bool Selection::assignGroup(int groupIndex, bool clearGroup, + const UnitContainer *pUnits) { + if (groupIndex < 0 || groupIndex >= maxGroups) { + throw megaglest_runtime_error("Invalid value for groupIndex = " + + intToStr(groupIndex)); + } + + // clear group + if (true == clearGroup) { + groups[groupIndex].clear(); + } + + // assign new group + const UnitContainer *addUnits = &selectedUnits; + if (pUnits != NULL) { + addUnits = pUnits; + } + + for (unsigned int i = 0; i < addUnits->size(); ++i) { + if (false == addUnitToGroup(groupIndex, (*addUnits)[i])) { + // don't try to add more, group is maybe full + return false; + } + } + return true; } /** * returns false if unit cannot be added */ -bool Selection::addUnitToGroup(int groupIndex,Unit *unit) { - if(groupIndex < 0 || groupIndex >= maxGroups) { - throw megaglest_runtime_error("Invalid value for groupIndex = " + intToStr(groupIndex)); - } - bool alreadyExists=false; - bool groupIsFull=(int)groups[groupIndex].size() >= Config::getInstance().getInt("MaxUnitSelectCount",intToStr(maxUnits).c_str()); - - for(int i = 0; i < (int)groups[groupIndex].size(); ++i) { - if(groups[groupIndex][i] == unit) { - alreadyExists=true; - break; - } - } - - if(alreadyExists){ - return true; - } - - // check for non Multiselect units - if((int)groups[groupIndex].size()>0 ){ - if( !unit->getType()->getMultiSelect()){ - //dont add single selection units to already filled group - return false; - } - Unit* unitInGroup=groups[groupIndex][0]; - if( !unitInGroup->getType()->getMultiSelect()){ - //dont add a unit to a group which has a single selection unit - return false; - } - } - - // check for uniformselect units - if((int)groups[groupIndex].size()>0 ) { - Unit* unitInGroup=groups[groupIndex][0]; - if( unit->getType()->getUniformSelect() || unitInGroup->getType()->getUniformSelect() ) { - if( unit->isOperative() != unitInGroup->isOperative()) { - //dont add units that are not in same operative state - return false; - } - if( unitInGroup->getType() != unit->getType()){ - //dont add another unit to a group of uniform selection units - return false; - } - } - } - - if(unit != NULL && !groupIsFull) { - groups[groupIndex].push_back(unit); - return true; - } - else{ - return false; - } +bool Selection::addUnitToGroup(int groupIndex, Unit *unit) { + if (groupIndex < 0 || groupIndex >= maxGroups) { + throw megaglest_runtime_error("Invalid value for groupIndex = " + + intToStr(groupIndex)); + } + bool alreadyExists = false; + bool groupIsFull = (int)groups[groupIndex].size() >= + Config::getInstance().getInt("MaxUnitSelectCount", + intToStr(maxUnits).c_str()); + + for (int i = 0; i < (int)groups[groupIndex].size(); ++i) { + if (groups[groupIndex][i] == unit) { + alreadyExists = true; + break; + } + } + + if (alreadyExists) { + return true; + } + + // check for non Multiselect units + if ((int)groups[groupIndex].size() > 0) { + if (!unit->getType()->getMultiSelect()) { + // dont add single selection units to already filled group + return false; + } + Unit *unitInGroup = groups[groupIndex][0]; + if (!unitInGroup->getType()->getMultiSelect()) { + // dont add a unit to a group which has a single selection unit + return false; + } + } + + // check for uniformselect units + if ((int)groups[groupIndex].size() > 0) { + Unit *unitInGroup = groups[groupIndex][0]; + if (unit->getType()->getUniformSelect() || + unitInGroup->getType()->getUniformSelect()) { + if (unit->isOperative() != unitInGroup->isOperative()) { + // dont add units that are not in same operative state + return false; + } + if (unitInGroup->getType() != unit->getType()) { + // dont add another unit to a group of uniform selection units + return false; + } + } + } + + if (unit != NULL && !groupIsFull) { + groups[groupIndex].push_back(unit); + return true; + } else { + return false; + } } -void Selection::removeUnitFromGroup(int groupIndex,int unitId) { - if(groupIndex < 0 || groupIndex >= maxGroups) { - throw megaglest_runtime_error("Invalid value for groupIndex = " + intToStr(groupIndex)); - } - - for(unsigned int i = 0; i < groups[groupIndex].size(); ++i) { - Unit *unit = groups[groupIndex][i]; - if(unit != NULL && unit->getId() == unitId) { - groups[groupIndex].erase(groups[groupIndex].begin() + i); - break; - } - } +void Selection::removeUnitFromGroup(int groupIndex, int unitId) { + if (groupIndex < 0 || groupIndex >= maxGroups) { + throw megaglest_runtime_error("Invalid value for groupIndex = " + + intToStr(groupIndex)); + } + + for (unsigned int i = 0; i < groups[groupIndex].size(); ++i) { + Unit *unit = groups[groupIndex][i]; + if (unit != NULL && unit->getId() == unitId) { + groups[groupIndex].erase(groups[groupIndex].begin() + i); + break; + } + } } -const Unit* Selection::getUnitFromCC(CommandClass commandClass){ - const Unit *unit = NULL; - for(int i=0; i<(int)selectedUnits.size(); ++i){ - const Unit *unit= selectedUnits[i]; - const CommandType *ct= unit->getType()->getFirstCtOfClass(commandClass); - if(ct != NULL && ct->getClass() == commandClass) return unit; - } - return unit; +const Unit *Selection::getUnitFromCC(CommandClass commandClass) { + const Unit *unit = NULL; + for (int i = 0; i < (int)selectedUnits.size(); ++i) { + const Unit *unit = selectedUnits[i]; + const CommandType *ct = unit->getType()->getFirstCtOfClass(commandClass); + if (ct != NULL && ct->getClass() == commandClass) + return unit; + } + return unit; } -//vector Selection::getUnitsForGroup(int groupIndex) { +// vector Selection::getUnitsForGroup(int groupIndex) { // if(groupIndex < 0 || groupIndex >= maxGroups) { -// throw megaglest_runtime_error("Invalid value for groupIndex = " + intToStr(groupIndex)); +// throw megaglest_runtime_error("Invalid value for groupIndex = " +//+ intToStr(groupIndex)); // } // return groups[groupIndex]; -//} - -void Selection::recallGroup(int groupIndex,bool clearSelection){ - if(groupIndex < 0 || groupIndex >= maxGroups) { - throw megaglest_runtime_error("Invalid value for groupIndex = " + intToStr(groupIndex)); - } - - if(clearSelection==true){ - clear(); - } - for(int i = 0; i < (int)groups[groupIndex].size(); ++i) { - select(groups[groupIndex][i],!clearSelection); - } +// } + +void Selection::recallGroup(int groupIndex, bool clearSelection) { + if (groupIndex < 0 || groupIndex >= maxGroups) { + throw megaglest_runtime_error("Invalid value for groupIndex = " + + intToStr(groupIndex)); + } + + if (clearSelection == true) { + clear(); + } + for (int i = 0; i < (int)groups[groupIndex].size(); ++i) { + select(groups[groupIndex][i], !clearSelection); + } } void Selection::unitEvent(UnitObserver::Event event, const Unit *unit) { - if(event == UnitObserver::eKill) { - - //remove from selection - for(int index = 0; index < (int)selectedUnits.size(); ++index) { - if(selectedUnits[index] == unit){ - selectedUnits.erase(selectedUnits.begin() + index); - break; - } - } - - //remove from groups - for(int index = 0; index < maxGroups; ++index) { - for(int index2 = 0; index2 < (int)groups[index].size(); ++index2) { - if(groups[index][index2] == unit) { - groups[index].erase(groups[index].begin() + index2); - break; - } - } - } - - //notify gui only if no more units to execute the command - //of course the selection changed, but this doesn't matter in this case. - if( selectedUnits.empty() == true) { - gui->onSelectionChanged(); - } - } -} - -void Selection::saveGame(XmlNode *rootNode) const { - - std::map mapTagReplacements; - XmlNode *selectionNode = rootNode->addChild("Selection"); + if (event == UnitObserver::eKill) { - selectionNode->addAttribute("factionIndex",intToStr(factionIndex), mapTagReplacements); - selectionNode->addAttribute("teamIndex",intToStr(teamIndex), mapTagReplacements); - selectionNode->addAttribute("allowSharedTeamUnits",intToStr(allowSharedTeamUnits), mapTagReplacements); + // remove from selection + for (int index = 0; index < (int)selectedUnits.size(); ++index) { + if (selectedUnits[index] == unit) { + selectedUnits.erase(selectedUnits.begin() + index); + break; + } + } - for(unsigned int i = 0; i < selectedUnits.size(); i++) { - Unit *unit = selectedUnits[i]; + // remove from groups + for (int index = 0; index < maxGroups; ++index) { + for (int index2 = 0; index2 < (int)groups[index].size(); ++index2) { + if (groups[index][index2] == unit) { + groups[index].erase(groups[index].begin() + index2); + break; + } + } + } - XmlNode *selectedUnitsNode = selectionNode->addChild("selectedUnits"); - selectedUnitsNode->addAttribute("unitId",intToStr(unit->getId()), mapTagReplacements); - } + // notify gui only if no more units to execute the command + // of course the selection changed, but this doesn't matter in this case. + if (selectedUnits.empty() == true) { + gui->onSelectionChanged(); + } + } +} - for(unsigned int x = 0; x < (unsigned int)maxGroups; ++x) { - XmlNode *groupsNode = selectionNode->addChild("groups"); - for(unsigned int i = 0; i < (unsigned int)groups[x].size(); ++i) { - Unit *unit = groups[x][i]; +void Selection::saveGame(XmlNode *rootNode) const { - XmlNode *selectedUnitsNode = groupsNode->addChild("selectedUnits"); - selectedUnitsNode->addAttribute("unitId",intToStr(unit->getId()), mapTagReplacements); - } - } + std::map mapTagReplacements; + XmlNode *selectionNode = rootNode->addChild("Selection"); + + selectionNode->addAttribute("factionIndex", intToStr(factionIndex), + mapTagReplacements); + selectionNode->addAttribute("teamIndex", intToStr(teamIndex), + mapTagReplacements); + selectionNode->addAttribute("allowSharedTeamUnits", + intToStr(allowSharedTeamUnits), + mapTagReplacements); + + for (unsigned int i = 0; i < selectedUnits.size(); i++) { + Unit *unit = selectedUnits[i]; + + XmlNode *selectedUnitsNode = selectionNode->addChild("selectedUnits"); + selectedUnitsNode->addAttribute("unitId", intToStr(unit->getId()), + mapTagReplacements); + } + + for (unsigned int x = 0; x < (unsigned int)maxGroups; ++x) { + XmlNode *groupsNode = selectionNode->addChild("groups"); + for (unsigned int i = 0; i < (unsigned int)groups[x].size(); ++i) { + Unit *unit = groups[x][i]; + + XmlNode *selectedUnitsNode = groupsNode->addChild("selectedUnits"); + selectedUnitsNode->addAttribute("unitId", intToStr(unit->getId()), + mapTagReplacements); + } + } } void Selection::loadGame(const XmlNode *rootNode, World *world) { - const XmlNode *selectionNode = rootNode->getChild("Selection"); - - factionIndex = selectionNode->getAttribute("factionIndex")->getIntValue(); - teamIndex = selectionNode->getAttribute("teamIndex")->getIntValue(); - if(selectionNode->hasAttribute("allowSharedTeamUnits") == true) { - allowSharedTeamUnits = (selectionNode->getAttribute("allowSharedTeamUnits")->getIntValue() != 0); - } - - vector selectedUnitsNodeList = selectionNode->getChildList("selectedUnits"); - for(unsigned int i = 0; i < selectedUnitsNodeList.size(); ++i) { - XmlNode *selectedUnitsNode = selectedUnitsNodeList[i]; - - int unitId = selectedUnitsNode->getAttribute("unitId")->getIntValue(); - Unit *unit = world->findUnitById(unitId); - //assert(unit != NULL); - //printf("#1 Unit [%s], group: %d\n",unit->getType()->getName().c_str(),i); - selectedUnits.push_back(unit); - } - - vector groupsNodeList = selectionNode->getChildList("groups"); - for(unsigned int i = 0; i < groupsNodeList.size(); ++i) { - XmlNode *groupsNode = groupsNodeList[i]; - - vector selectedGroupsUnitsNodeList = groupsNode->getChildList("selectedUnits"); - for(unsigned int j = 0; j < selectedGroupsUnitsNodeList.size(); ++j) { - XmlNode *selectedGroupsUnitsNode = selectedGroupsUnitsNodeList[j]; - - int unitId = selectedGroupsUnitsNode->getAttribute("unitId")->getIntValue(); - Unit *unit = world->findUnitById(unitId); - //assert(unit != NULL); - //printf("Unit #2 [%s], group: %d\n",unit->getType()->getName().c_str(),i); - groups[i].push_back(unit); - } - } + const XmlNode *selectionNode = rootNode->getChild("Selection"); + + factionIndex = selectionNode->getAttribute("factionIndex")->getIntValue(); + teamIndex = selectionNode->getAttribute("teamIndex")->getIntValue(); + if (selectionNode->hasAttribute("allowSharedTeamUnits") == true) { + allowSharedTeamUnits = + (selectionNode->getAttribute("allowSharedTeamUnits")->getIntValue() != + 0); + } + + vector selectedUnitsNodeList = + selectionNode->getChildList("selectedUnits"); + for (unsigned int i = 0; i < selectedUnitsNodeList.size(); ++i) { + XmlNode *selectedUnitsNode = selectedUnitsNodeList[i]; + + int unitId = selectedUnitsNode->getAttribute("unitId")->getIntValue(); + Unit *unit = world->findUnitById(unitId); + // assert(unit != NULL); + // printf("#1 Unit [%s], group: %d\n",unit->getType()->getName().c_str(),i); + selectedUnits.push_back(unit); + } + + vector groupsNodeList = selectionNode->getChildList("groups"); + for (unsigned int i = 0; i < groupsNodeList.size(); ++i) { + XmlNode *groupsNode = groupsNodeList[i]; + + vector selectedGroupsUnitsNodeList = + groupsNode->getChildList("selectedUnits"); + for (unsigned int j = 0; j < selectedGroupsUnitsNodeList.size(); ++j) { + XmlNode *selectedGroupsUnitsNode = selectedGroupsUnitsNodeList[j]; + + int unitId = + selectedGroupsUnitsNode->getAttribute("unitId")->getIntValue(); + Unit *unit = world->findUnitById(unitId); + // assert(unit != NULL); + // printf("Unit #2 [%s], group: + // %d\n",unit->getType()->getName().c_str(),i); + groups[i].push_back(unit); + } + } } - -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/gui/selection.h b/source/glest_game/gui/selection.h index 8b09de273..6da9a9e1c 100644 --- a/source/glest_game/gui/selection.h +++ b/source/glest_game/gui/selection.h @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,98 +13,101 @@ #define _GLEST_GAME_SELECTION_ #ifdef WIN32 - #include - #include +#include +#include #endif +#include "leak_dumper.h" #include "unit.h" #include -#include "leak_dumper.h" using std::vector; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { class Gui; class World; class HighlightSpecialUnitInfo { public: - float radius; - float thickness; - Vec4f color; + float radius; + float thickness; + Vec4f color; }; // ===================================================== -// class Selection +// class Selection // /// List of selected units and groups // ===================================================== -class Selection: public UnitObserver { +class Selection : public UnitObserver { public: - typedef vector UnitContainer; - typedef UnitContainer::const_iterator UnitIterator; + typedef vector UnitContainer; + typedef UnitContainer::const_iterator UnitIterator; public: - static const int maxGroups = 10; - static const int maxUnits = 36; + static const int maxGroups = 10; + static const int maxUnits = 36; private: - int factionIndex; - int teamIndex; - bool allowSharedTeamUnits; - UnitContainer selectedUnits; - UnitContainer groups[maxGroups]; - Gui *gui; + int factionIndex; + int teamIndex; + bool allowSharedTeamUnits; + UnitContainer selectedUnits; + UnitContainer groups[maxGroups]; + Gui *gui; public: - Selection() : UnitObserver() { - factionIndex = 0; - teamIndex = 0; - allowSharedTeamUnits = false; - gui = NULL; - } - void init(Gui *gui, int factionIndex, int teamIndex, bool allowSharedTeamUnits); - virtual ~Selection(); - - bool select(Unit *unit, bool addToSelection); - void select(const UnitContainer &units, bool addToSelection); - void unSelect(const UnitContainer &units); - void unSelect(int unitIndex); - void clear(); - - bool isEmpty() const {return selectedUnits.empty();} - bool isUniform() const; - bool isEnemy() const; - bool isObserver() const; - - bool isCommandable() const; - bool isCancelable() const; - bool isMeetable() const; - int getCount() const {return (int)selectedUnits.size();} - const Unit *getUnit(int i) const {return selectedUnits[i];} - Unit *getUnitPtr(int i) {return selectedUnits[i];} - const Unit *getFrontUnit() const {return selectedUnits.front();} - const Unit *getUnitFromCC(CommandClass commandClass); - Vec3f getRefPos() const; - bool hasUnit(const Unit* unit) const; - - bool assignGroup(int groupIndex, bool clearGroup=true, const UnitContainer *pUnits=NULL); - bool addUnitToGroup(int groupIndex,Unit *unit); - void removeUnitFromGroup(int groupIndex,int UnitId); - void recallGroup(int groupIndex, bool clearSelection=true); - - //vector getUnitsForGroup(int groupIndex); - - virtual void unitEvent(UnitObserver::Event event, const Unit *unit); - bool canSelectUnitFactionCheck(const Unit *unit) const; - - virtual void saveGame(XmlNode *rootNode) const; - void loadGame(const XmlNode *rootNode, World *world); - + Selection() : UnitObserver() { + factionIndex = 0; + teamIndex = 0; + allowSharedTeamUnits = false; + gui = NULL; + } + void init(Gui *gui, int factionIndex, int teamIndex, + bool allowSharedTeamUnits); + virtual ~Selection(); + + bool select(Unit *unit, bool addToSelection); + void select(const UnitContainer &units, bool addToSelection); + void unSelect(const UnitContainer &units); + void unSelect(int unitIndex); + void clear(); + + bool isEmpty() const { return selectedUnits.empty(); } + bool isUniform() const; + bool isEnemy() const; + bool isObserver() const; + + bool isCommandable() const; + bool isCancelable() const; + bool isMeetable() const; + int getCount() const { return (int)selectedUnits.size(); } + const Unit *getUnit(int i) const { return selectedUnits[i]; } + Unit *getUnitPtr(int i) { return selectedUnits[i]; } + const Unit *getFrontUnit() const { return selectedUnits.front(); } + const Unit *getUnitFromCC(CommandClass commandClass); + Vec3f getRefPos() const; + bool hasUnit(const Unit *unit) const; + + bool assignGroup(int groupIndex, bool clearGroup = true, + const UnitContainer *pUnits = NULL); + bool addUnitToGroup(int groupIndex, Unit *unit); + void removeUnitFromGroup(int groupIndex, int UnitId); + void recallGroup(int groupIndex, bool clearSelection = true); + + // vector getUnitsForGroup(int groupIndex); + + virtual void unitEvent(UnitObserver::Event event, const Unit *unit); + bool canSelectUnitFactionCheck(const Unit *unit) const; + + virtual void saveGame(XmlNode *rootNode) const; + void loadGame(const XmlNode *rootNode, World *world); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/main/battle_end.cpp b/source/glest_game/main/battle_end.cpp index 536ec8ab9..7dfa58d7c 100644 --- a/source/glest_game/main/battle_end.cpp +++ b/source/glest_game/main/battle_end.cpp @@ -3,820 +3,897 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== -#include "battle_end.h" +#include "battle_end.h" -#include "main_menu.h" -#include "program.h" +#include "auto_test.h" +#include "components.h" #include "core_data.h" +#include "game.h" +#include "game_settings.h" #include "lang.h" -#include "util.h" -#include "renderer.h" +#include "leak_dumper.h" #include "main_menu.h" -#include "sound_renderer.h" -#include "components.h" #include "metrics.h" +#include "program.h" +#include "renderer.h" +#include "sound_renderer.h" #include "stats.h" -#include "auto_test.h" +#include "util.h" #include "video_player.h" -#include "game.h" -#include "game_settings.h" -#include "leak_dumper.h" using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== -// class BattleEnd +// class BattleEnd // ===================================================== -BattleEnd::BattleEnd(Program *program, const Stats *stats,ProgramState *originState) : - ProgramState(program), menuBackgroundVideo(NULL), gameSettings(NULL) { - - containerName= "BattleEnd"; - - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d] stats = %p\n",__FILE__,__FUNCTION__,__LINE__,stats); - - this->originState = originState; - if(stats != NULL) { - this->stats= *stats; - } - if(originState != NULL) { - Game *game = dynamic_cast(originState); - if(game != NULL) { - gameSettings = new GameSettings(); - *gameSettings = *(game->getGameSettings()); - } - } - mouseX = 0; - mouseY = 0; - mouse2d = 0; - renderToTexture = NULL; - renderToTextureCount = 0; - - const Metrics &metrics= Metrics::getInstance(); - Lang &lang= Lang::getInstance(); - int buttonWidth = 125; - int xLocation = (metrics.getVirtualW() / 2) - (buttonWidth / 2); - buttonExit.init(xLocation, 80, buttonWidth); - buttonExit.setText(lang.getString("Exit")); - - //mesage box - mainMessageBox.init(lang.getString("Yes"), lang.getString("No")); - mainMessageBox.setEnabled(false); - - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(stats->getVictory(stats->getThisFactionIndex())==true){ - if (Config::getInstance().getString("InternetGamesBlockScenario", "") != "" - && Config::getInstance().getBool("InternetGamesAllowed", "false") == false) { - if(Config::getInstance().getString("InternetGamesBlockScenario")==gameSettings->getScenario()){ - Config::getInstance().setBool("InternetGamesAllowed",true); - Config::getInstance().save(); - } - } - } - - initBackgroundVideo(); - initBackgroundMusic(); - - GraphicComponent::applyAllCustomProperties(containerName); +BattleEnd::BattleEnd(Program *program, const Stats *stats, + ProgramState *originState) + : ProgramState(program), menuBackgroundVideo(NULL), gameSettings(NULL) { + + containerName = "BattleEnd"; + + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s %d] stats = %p\n", __FILE__, + __FUNCTION__, __LINE__, stats); + + this->originState = originState; + if (stats != NULL) { + this->stats = *stats; + } + if (originState != NULL) { + Game *game = dynamic_cast(originState); + if (game != NULL) { + gameSettings = new GameSettings(); + *gameSettings = *(game->getGameSettings()); + } + } + mouseX = 0; + mouseY = 0; + mouse2d = 0; + renderToTexture = NULL; + renderToTextureCount = 0; + + const Metrics &metrics = Metrics::getInstance(); + Lang &lang = Lang::getInstance(); + int buttonWidth = 125; + int xLocation = (metrics.getVirtualW() / 2) - (buttonWidth / 2); + buttonExit.init(xLocation, 80, buttonWidth); + buttonExit.setText(lang.getString("Exit")); + + // mesage box + mainMessageBox.init(lang.getString("Yes"), lang.getString("No")); + mainMessageBox.setEnabled(false); + + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + if (stats->getVictory(stats->getThisFactionIndex()) == true) { + if (Config::getInstance().getString("InternetGamesBlockScenario", "") != + "" && + Config::getInstance().getBool("InternetGamesAllowed", "false") == + false) { + if (Config::getInstance().getString("InternetGamesBlockScenario") == + gameSettings->getScenario()) { + Config::getInstance().setBool("InternetGamesAllowed", true); + Config::getInstance().save(); + } + } + } + + initBackgroundVideo(); + initBackgroundMusic(); + + GraphicComponent::applyAllCustomProperties(containerName); } void BattleEnd::reloadUI() { - Lang &lang= Lang::getInstance(); + Lang &lang = Lang::getInstance(); - buttonExit.setText(lang.getString("Exit")); - mainMessageBox.init(lang.getString("Yes"), lang.getString("No")); + buttonExit.setText(lang.getString("Exit")); + mainMessageBox.init(lang.getString("Yes"), lang.getString("No")); - GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); + GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); } BattleEnd::~BattleEnd() { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); - if(menuBackgroundVideo != NULL) { - menuBackgroundVideo->closePlayer(); - delete menuBackgroundVideo; - menuBackgroundVideo = NULL; - } + if (menuBackgroundVideo != NULL) { + menuBackgroundVideo->closePlayer(); + delete menuBackgroundVideo; + menuBackgroundVideo = NULL; + } - delete gameSettings; - gameSettings = NULL; + delete gameSettings; + gameSettings = NULL; - delete originState; - originState = NULL; + delete originState; + originState = NULL; - if(CoreData::getInstance().hasMainMenuVideoFilename() == false) { - SoundRenderer::getInstance().playMusic(CoreData::getInstance().getMenuMusic()); - } + if (CoreData::getInstance().hasMainMenuVideoFilename() == false) { + SoundRenderer::getInstance().playMusic( + CoreData::getInstance().getMenuMusic()); + } - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); - delete renderToTexture; - renderToTexture = NULL; + delete renderToTexture; + renderToTexture = NULL; - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); } -std::pair BattleEnd::getBattleEndVideo(bool won) { - std::pair result; - - string factionVideoUrl = ""; - string factionVideoUrlFallback = ""; - - if(gameSettings != NULL) { - string currentTechName_factionPreview = gameSettings->getTech(); - string currentFactionName_factionPreview = gameSettings->getFactionTypeName(stats.getThisFactionIndex()); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("#1 tech [%s] faction [%s] won = %d\n",currentTechName_factionPreview.c_str(),currentFactionName_factionPreview.c_str(),won); - - string factionDefinitionXML = Game::findFactionLogoFile(gameSettings, NULL,currentFactionName_factionPreview + ".xml"); - if(factionDefinitionXML != "" && currentFactionName_factionPreview != GameConstants::RANDOMFACTION_SLOTNAME && - currentFactionName_factionPreview != GameConstants::OBSERVER_SLOTNAME && fileExists(factionDefinitionXML) == true) { - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("#2 tech [%s] faction [%s]\n",currentTechName_factionPreview.c_str(),currentFactionName_factionPreview.c_str()); - - XmlTree xmlTree; - std::map mapExtraTagReplacementValues; - xmlTree.load(factionDefinitionXML, Properties::getTagReplacementValues(&mapExtraTagReplacementValues)); - const XmlNode *factionNode= xmlTree.getRootNode(); - if(won == true) { - if(factionNode->hasAttribute("battle-end-win-video") == true) { - factionVideoUrl = factionNode->getAttribute("battle-end-win-video")->getValue(); - } - } - else { - if(factionNode->hasAttribute("battle-end-lose-video") == true) { - factionVideoUrl = factionNode->getAttribute("battle-end-lose-video")->getValue(); - } - } - - if(factionVideoUrl != "" && fileExists(factionVideoUrl) == false) { - string techTreePath = ""; - string factionPath = ""; - std::vector factionPartsList; - Tokenize(factionDefinitionXML,factionPartsList,"factions/"); - if(factionPartsList.size() > 1) { - techTreePath = factionPartsList[0]; - - string factionPath = techTreePath + "factions/" + currentFactionName_factionPreview; - endPathWithSlash(factionPath); - factionVideoUrl = factionPath + factionVideoUrl; - } - } - - if(won == true) { - factionVideoUrlFallback = Game::findFactionLogoFile(gameSettings, NULL,"battle_end_win_video.*"); - } - else { - factionVideoUrlFallback = Game::findFactionLogoFile(gameSettings, NULL,"battle_end_lose_video.*"); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("#3 factionVideoUrl [%s] factionVideoUrlFallback [%s]\n",factionVideoUrl.c_str(),factionVideoUrlFallback.c_str()); - //printf("#3 factionVideoUrl [%s] factionVideoUrlFallback [%s]\n",factionVideoUrl.c_str(),factionVideoUrlFallback.c_str()); - - if(factionVideoUrl == "") { - factionVideoUrl = factionVideoUrlFallback; - factionVideoUrlFallback = ""; - } - } - //printf("currentFactionName_factionPreview [%s] random [%s] observer [%s] factionVideoUrl [%s]\n",currentFactionName_factionPreview.c_str(),GameConstants::RANDOMFACTION_SLOTNAME,GameConstants::OBSERVER_SLOTNAME,factionVideoUrl.c_str()); - } - - if(factionVideoUrl != "") { - result.first = factionVideoUrl; - result.second = factionVideoUrlFallback; - } - else { - result.first = CoreData::getInstance().getBattleEndVideoFilename(won); - result.second = CoreData::getInstance().getBattleEndVideoFilenameFallback(won); - } - - return result; +std::pair BattleEnd::getBattleEndVideo(bool won) { + std::pair result; + + string factionVideoUrl = ""; + string factionVideoUrlFallback = ""; + + if (gameSettings != NULL) { + string currentTechName_factionPreview = gameSettings->getTech(); + string currentFactionName_factionPreview = + gameSettings->getFactionTypeName(stats.getThisFactionIndex()); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("#1 tech [%s] faction [%s] won = %d\n", + currentTechName_factionPreview.c_str(), + currentFactionName_factionPreview.c_str(), won); + + string factionDefinitionXML = Game::findFactionLogoFile( + gameSettings, NULL, currentFactionName_factionPreview + ".xml"); + if (factionDefinitionXML != "" && + currentFactionName_factionPreview != + GameConstants::RANDOMFACTION_SLOTNAME && + currentFactionName_factionPreview != GameConstants::OBSERVER_SLOTNAME && + fileExists(factionDefinitionXML) == true) { + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("#2 tech [%s] faction [%s]\n", + currentTechName_factionPreview.c_str(), + currentFactionName_factionPreview.c_str()); + + XmlTree xmlTree; + std::map mapExtraTagReplacementValues; + xmlTree.load(factionDefinitionXML, Properties::getTagReplacementValues( + &mapExtraTagReplacementValues)); + const XmlNode *factionNode = xmlTree.getRootNode(); + if (won == true) { + if (factionNode->hasAttribute("battle-end-win-video") == true) { + factionVideoUrl = + factionNode->getAttribute("battle-end-win-video")->getValue(); + } + } else { + if (factionNode->hasAttribute("battle-end-lose-video") == true) { + factionVideoUrl = + factionNode->getAttribute("battle-end-lose-video")->getValue(); + } + } + + if (factionVideoUrl != "" && fileExists(factionVideoUrl) == false) { + string techTreePath = ""; + string factionPath = ""; + std::vector factionPartsList; + Tokenize(factionDefinitionXML, factionPartsList, "factions/"); + if (factionPartsList.size() > 1) { + techTreePath = factionPartsList[0]; + + string factionPath = + techTreePath + "factions/" + currentFactionName_factionPreview; + endPathWithSlash(factionPath); + factionVideoUrl = factionPath + factionVideoUrl; + } + } + + if (won == true) { + factionVideoUrlFallback = Game::findFactionLogoFile( + gameSettings, NULL, "battle_end_win_video.*"); + } else { + factionVideoUrlFallback = Game::findFactionLogoFile( + gameSettings, NULL, "battle_end_lose_video.*"); + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("#3 factionVideoUrl [%s] factionVideoUrlFallback [%s]\n", + factionVideoUrl.c_str(), factionVideoUrlFallback.c_str()); + // printf("#3 factionVideoUrl [%s] factionVideoUrlFallback + // [%s]\n",factionVideoUrl.c_str(),factionVideoUrlFallback.c_str()); + + if (factionVideoUrl == "") { + factionVideoUrl = factionVideoUrlFallback; + factionVideoUrlFallback = ""; + } + } + // printf("currentFactionName_factionPreview [%s] random [%s] observer [%s] + // factionVideoUrl + // [%s]\n",currentFactionName_factionPreview.c_str(),GameConstants::RANDOMFACTION_SLOTNAME,GameConstants::OBSERVER_SLOTNAME,factionVideoUrl.c_str()); + } + + if (factionVideoUrl != "") { + result.first = factionVideoUrl; + result.second = factionVideoUrlFallback; + } else { + result.first = CoreData::getInstance().getBattleEndVideoFilename(won); + result.second = + CoreData::getInstance().getBattleEndVideoFilenameFallback(won); + } + + return result; } string BattleEnd::getBattleEndMusic(bool won) { - string result=""; - string resultFallback=""; - - if(gameSettings != NULL) { - string currentTechName_factionPreview = gameSettings->getTech(); - string currentFactionName_factionPreview = gameSettings->getFactionTypeName(stats.getThisFactionIndex()); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("#1 tech [%s] faction [%s] won = %d\n",currentTechName_factionPreview.c_str(),currentFactionName_factionPreview.c_str(),won); - - string factionDefinitionXML = Game::findFactionLogoFile(gameSettings, NULL,currentFactionName_factionPreview + ".xml"); - if(factionDefinitionXML != "" && currentFactionName_factionPreview != GameConstants::RANDOMFACTION_SLOTNAME && - currentFactionName_factionPreview != GameConstants::OBSERVER_SLOTNAME && fileExists(factionDefinitionXML) == true) { - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("#2 tech [%s] faction [%s]\n",currentTechName_factionPreview.c_str(),currentFactionName_factionPreview.c_str()); - - XmlTree xmlTree; - std::map mapExtraTagReplacementValues; - xmlTree.load(factionDefinitionXML, Properties::getTagReplacementValues(&mapExtraTagReplacementValues)); - const XmlNode *factionNode= xmlTree.getRootNode(); - if(won == true) { - if(factionNode->hasAttribute("battle-end-win-music") == true) { - result = factionNode->getAttribute("battle-end-win-music")->getValue(); - } - } - else { - if(factionNode->hasAttribute("battle-end-lose-music") == true) { - result = factionNode->getAttribute("battle-end-lose-music")->getValue(); - } - } - - if(result != "" && fileExists(result) == false) { - string techTreePath = ""; - string factionPath = ""; - std::vector factionPartsList; - Tokenize(factionDefinitionXML,factionPartsList,"factions/"); - if(factionPartsList.size() > 1) { - techTreePath = factionPartsList[0]; - - string factionPath = techTreePath + "factions/" + currentFactionName_factionPreview; - endPathWithSlash(factionPath); - result = factionPath + result; - } - } - - if(won == true) { - resultFallback = Game::findFactionLogoFile(gameSettings, NULL,"battle_end_win_music.*"); - } - else { - resultFallback = Game::findFactionLogoFile(gameSettings, NULL,"battle_end_lose_music.*"); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("#3 result [%s] resultFallback [%s]\n",result.c_str(),resultFallback.c_str()); - //printf("#3 result [%s] resultFallback [%s]\n",result.c_str(),resultFallback.c_str()); - - if(result == "") { - result = resultFallback; - } - } - //printf("currentFactionName_factionPreview [%s] random [%s] observer [%s] factionVideoUrl [%s]\n",currentFactionName_factionPreview.c_str(),GameConstants::RANDOMFACTION_SLOTNAME,GameConstants::OBSERVER_SLOTNAME,factionVideoUrl.c_str()); - } - - if(result == "") { - result = CoreData::getInstance().getBattleEndMusicFilename(won); - } - - return result; + string result = ""; + string resultFallback = ""; + + if (gameSettings != NULL) { + string currentTechName_factionPreview = gameSettings->getTech(); + string currentFactionName_factionPreview = + gameSettings->getFactionTypeName(stats.getThisFactionIndex()); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("#1 tech [%s] faction [%s] won = %d\n", + currentTechName_factionPreview.c_str(), + currentFactionName_factionPreview.c_str(), won); + + string factionDefinitionXML = Game::findFactionLogoFile( + gameSettings, NULL, currentFactionName_factionPreview + ".xml"); + if (factionDefinitionXML != "" && + currentFactionName_factionPreview != + GameConstants::RANDOMFACTION_SLOTNAME && + currentFactionName_factionPreview != GameConstants::OBSERVER_SLOTNAME && + fileExists(factionDefinitionXML) == true) { + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("#2 tech [%s] faction [%s]\n", + currentTechName_factionPreview.c_str(), + currentFactionName_factionPreview.c_str()); + + XmlTree xmlTree; + std::map mapExtraTagReplacementValues; + xmlTree.load(factionDefinitionXML, Properties::getTagReplacementValues( + &mapExtraTagReplacementValues)); + const XmlNode *factionNode = xmlTree.getRootNode(); + if (won == true) { + if (factionNode->hasAttribute("battle-end-win-music") == true) { + result = + factionNode->getAttribute("battle-end-win-music")->getValue(); + } + } else { + if (factionNode->hasAttribute("battle-end-lose-music") == true) { + result = + factionNode->getAttribute("battle-end-lose-music")->getValue(); + } + } + + if (result != "" && fileExists(result) == false) { + string techTreePath = ""; + string factionPath = ""; + std::vector factionPartsList; + Tokenize(factionDefinitionXML, factionPartsList, "factions/"); + if (factionPartsList.size() > 1) { + techTreePath = factionPartsList[0]; + + string factionPath = + techTreePath + "factions/" + currentFactionName_factionPreview; + endPathWithSlash(factionPath); + result = factionPath + result; + } + } + + if (won == true) { + resultFallback = Game::findFactionLogoFile(gameSettings, NULL, + "battle_end_win_music.*"); + } else { + resultFallback = Game::findFactionLogoFile(gameSettings, NULL, + "battle_end_lose_music.*"); + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("#3 result [%s] resultFallback [%s]\n", result.c_str(), + resultFallback.c_str()); + // printf("#3 result [%s] resultFallback + // [%s]\n",result.c_str(),resultFallback.c_str()); + + if (result == "") { + result = resultFallback; + } + } + // printf("currentFactionName_factionPreview [%s] random [%s] observer [%s] + // factionVideoUrl + // [%s]\n",currentFactionName_factionPreview.c_str(),GameConstants::RANDOMFACTION_SLOTNAME,GameConstants::OBSERVER_SLOTNAME,factionVideoUrl.c_str()); + } + + if (result == "") { + result = CoreData::getInstance().getBattleEndMusicFilename(won); + } + + return result; } void BattleEnd::initBackgroundMusic() { - string music = ""; - - if(stats.getThisFactionIndex() >= 0 && stats.getTeam(stats.getThisFactionIndex()) != GameConstants::maxPlayers -1 + fpt_Observer) { - if(stats.getVictory(stats.getThisFactionIndex())){ - //header += lang.getString("Victory"); - music = getBattleEndMusic(true); - } - else{ - //header += lang.getString("Defeat"); - music = getBattleEndMusic(false); - } - - if(music != "" && fileExists(music) == true) { - printf("music [%s] \n",music.c_str()); - - battleEndMusic.open(music); - battleEndMusic.setNext(&battleEndMusic); - - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - soundRenderer.playMusic(&battleEndMusic); - } - } + string music = ""; + + if (stats.getThisFactionIndex() >= 0 && + stats.getTeam(stats.getThisFactionIndex()) != + GameConstants::maxPlayers - 1 + fpt_Observer) { + if (stats.getVictory(stats.getThisFactionIndex())) { + // header += lang.getString("Victory"); + music = getBattleEndMusic(true); + } else { + // header += lang.getString("Defeat"); + music = getBattleEndMusic(false); + } + + if (music != "" && fileExists(music) == true) { + printf("music [%s] \n", music.c_str()); + + battleEndMusic.open(music); + battleEndMusic.setNext(&battleEndMusic); + + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + soundRenderer.playMusic(&battleEndMusic); + } + } } void BattleEnd::initBackgroundVideo() { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && - ::Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == true) { - - if(menuBackgroundVideo != NULL) { - menuBackgroundVideo->closePlayer(); - delete menuBackgroundVideo; - menuBackgroundVideo = NULL; - } - - string videoFile = ""; - string videoFileFallback = ""; - - if(stats.getThisFactionIndex() >= 0 && stats.getTeam(stats.getThisFactionIndex()) != GameConstants::maxPlayers -1 + fpt_Observer) { - if(stats.getVictory(stats.getThisFactionIndex())){ - //header += lang.getString("Victory"); - - //videoFile = CoreData::getInstance().getBattleEndVideoFilename(true); - //videoFileFallback = CoreData::getInstance().getBattleEndVideoFilenameFallback(true); - std::pair wonVideos = getBattleEndVideo(true); - videoFile = wonVideos.first; - videoFileFallback = wonVideos.second; - } - else{ - //header += lang.getString("Defeat"); - //videoFile = CoreData::getInstance().getBattleEndVideoFilename(false); - //videoFileFallback = CoreData::getInstance().getBattleEndVideoFilenameFallback(false); - std::pair lostVideos = getBattleEndVideo(false); - videoFile = lostVideos.first; - videoFileFallback = lostVideos.second; - } - } - else { - //header += "Observer"; - } - - if(fileExists(videoFile) || fileExists(videoFileFallback)) { - printf("videoFile [%s] videoFileFallback [%s]\n",videoFile.c_str(),videoFileFallback.c_str()); - - Context *c= GraphicsInterface::getInstance().getCurrentContext(); - PlatformContextGl *glCtx = static_cast(c)->getPlatformContextGlPtr(); - SDL_Window *window = glCtx->getScreenWindow(); - SDL_Surface *screen = glCtx->getScreenSurface(); - - string vlcPluginsPath = Config::getInstance().getString("VideoPlayerPluginsPath",""); - //printf("screen->w = %d screen->h = %d screen->format->BitsPerPixel = %d\n",screen->w,screen->h,screen->format->BitsPerPixel); - menuBackgroundVideo = new VideoPlayer( - &Renderer::getInstance(), - videoFile, - videoFileFallback, - window, - 0,0, - screen->w, - screen->h, - screen->format->BitsPerPixel, - true, - vlcPluginsPath, - SystemFlags::VERBOSE_MODE_ENABLED); - menuBackgroundVideo->initPlayer(); - } - } + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && + ::Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == true) { + + if (menuBackgroundVideo != NULL) { + menuBackgroundVideo->closePlayer(); + delete menuBackgroundVideo; + menuBackgroundVideo = NULL; + } + + string videoFile = ""; + string videoFileFallback = ""; + + if (stats.getThisFactionIndex() >= 0 && + stats.getTeam(stats.getThisFactionIndex()) != + GameConstants::maxPlayers - 1 + fpt_Observer) { + if (stats.getVictory(stats.getThisFactionIndex())) { + // header += lang.getString("Victory"); + + // videoFile = CoreData::getInstance().getBattleEndVideoFilename(true); + // videoFileFallback = + // CoreData::getInstance().getBattleEndVideoFilenameFallback(true); + std::pair wonVideos = getBattleEndVideo(true); + videoFile = wonVideos.first; + videoFileFallback = wonVideos.second; + } else { + // header += lang.getString("Defeat"); + // videoFile = CoreData::getInstance().getBattleEndVideoFilename(false); + // videoFileFallback = + // CoreData::getInstance().getBattleEndVideoFilenameFallback(false); + std::pair lostVideos = getBattleEndVideo(false); + videoFile = lostVideos.first; + videoFileFallback = lostVideos.second; + } + } else { + // header += "Observer"; + } + + if (fileExists(videoFile) || fileExists(videoFileFallback)) { + printf("videoFile [%s] videoFileFallback [%s]\n", videoFile.c_str(), + videoFileFallback.c_str()); + + Context *c = GraphicsInterface::getInstance().getCurrentContext(); + PlatformContextGl *glCtx = + static_cast(c)->getPlatformContextGlPtr(); + SDL_Window *window = glCtx->getScreenWindow(); + SDL_Surface *screen = glCtx->getScreenSurface(); + + string vlcPluginsPath = + Config::getInstance().getString("VideoPlayerPluginsPath", ""); + // printf("screen->w = %d screen->h = %d screen->format->BitsPerPixel = + // %d\n",screen->w,screen->h,screen->format->BitsPerPixel); + menuBackgroundVideo = new VideoPlayer( + &Renderer::getInstance(), videoFile, videoFileFallback, window, 0, 0, + screen->w, screen->h, screen->format->BitsPerPixel, true, + vlcPluginsPath, SystemFlags::VERBOSE_MODE_ENABLED); + menuBackgroundVideo->initPlayer(); + } + } } void BattleEnd::update() { - if(Config::getInstance().getBool("AutoTest")){ - AutoTest::getInstance().updateBattleEnd(program); - return; - } - mouse2d= (mouse2d+1) % Renderer::maxMouse2dAnim; - - if(this->stats.getIsMasterserverMode() == true) { - if(program->getWantShutdownApplicationAfterGame() == true) { - program->setShutdownApplicationEnabled(true); - return; - } - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - //program->setState(new MainMenu(program)); - program->initServer(program->getWindow(),false,true,true); - return; - } + if (Config::getInstance().getBool("AutoTest")) { + AutoTest::getInstance().updateBattleEnd(program); + return; + } + mouse2d = (mouse2d + 1) % Renderer::maxMouse2dAnim; + + if (this->stats.getIsMasterserverMode() == true) { + if (program->getWantShutdownApplicationAfterGame() == true) { + program->setShutdownApplicationEnabled(true); + return; + } + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + // program->setState(new MainMenu(program)); + program->initServer(program->getWindow(), false, true, true); + return; + } } void BattleEnd::render() { - if(this->stats.getIsMasterserverMode() == true) { - return; - } - Renderer &renderer= Renderer::getInstance(); - //CoreData &coreData= CoreData::getInstance(); - - canRender(); - incrementFps(); - - //printf("In [%s::%s Line: %d] renderToTexture [%p]\n",__FILE__,__FUNCTION__,__LINE__,renderToTexture); - if(menuBackgroundVideo == NULL && renderToTexture != NULL) { - //printf("Rendering from texture!\n"); - - renderer.clearBuffers(); - renderer.reset3dMenu(); - renderer.clearZBuffer(); - - renderer.reset2d(); - - renderer.renderBackground(renderToTexture); - - renderer.renderButton(&buttonExit); - - //exit message box - if(mainMessageBox.getEnabled() && mainMessageBox.getVisible()) { - renderer.renderMessageBox(&mainMessageBox); - } - - renderer.renderMouse2d(mouseX, mouseY, mouse2dAnim); - } - else { - //printf("Rendering to texture!\n"); - - if(menuBackgroundVideo == NULL && renderToTextureCount >= 300) { - renderer.beginRenderToTexture(&renderToTexture); - } - - TextRenderer2D *textRenderer2D = renderer.getTextRenderer(); - TextRenderer3D *textRenderer3D = renderer.getTextRenderer3D(); - TextRenderer *textRenderer = NULL; - - if(Renderer::renderText3DEnabled == true) { - textRenderer= textRenderer3D; - } - else { - textRenderer= textRenderer2D; - } - - Lang &lang= Lang::getInstance(); - - renderer.clearBuffers(); - renderer.reset3dMenu(); - renderer.clearZBuffer(); - renderer.reset2d(); - - if(menuBackgroundVideo != NULL) { - //printf("Rendering video not null!\n"); - - if(menuBackgroundVideo->isPlaying() == true) { - menuBackgroundVideo->playFrame(false); - - //printf("Rendering video playing!\n"); - } - else { - if(menuBackgroundVideo != NULL) { - //initBackgroundVideo(); - menuBackgroundVideo->RestartVideo(); - } - } - } - else { - renderer.renderBackground(CoreData::getInstance().getBackgroundTexture()); - } - - //int winnerIndex = -1; - int bestScore = -1; - //int mostKillsIndex = -1; - int bestKills = -1; - //int mostEnemyKillsIndex = -1; - int bestEnemyKills = -1; - //int leastDeathsIndex = -1; - int leastDeaths = -1; - //int mostUnitsProducedIndex = -1; - int bestUnitsProduced = -1; - //int mostResourcesHarvestedIndex = -1; - int bestResourcesHarvested = -1; - - for(int i=0; i bestKills) { - bestKills = kills; - //mostKillsIndex = i; - } - - int enemykills= stats.getEnemyKills(i); - if(enemykills > bestEnemyKills) { - bestEnemyKills = enemykills; - //mostEnemyKillsIndex = i; - } - - int deaths= stats.getDeaths(i); - if(deaths < leastDeaths || leastDeaths < 0) { - leastDeaths = deaths; - //leastDeathsIndex = i; - } - - int unitsProduced= stats.getUnitsProduced(i); - if(unitsProduced > bestUnitsProduced) { - bestUnitsProduced = unitsProduced; - //mostUnitsProducedIndex = i; - } - - int resourcesHarvested = stats.getResourcesHarvested(i); - if(resourcesHarvested > bestResourcesHarvested) { - bestResourcesHarvested = resourcesHarvested; - //mostResourcesHarvestedIndex = i; - } - - int score= enemykills*100 + unitsProduced*50 + resourcesHarvested/10; - - if(score > bestScore) { - bestScore = score; - //winnerIndex = i; - } - } - - bool disableStatsColorCoding = Config::getInstance().getBool("DisableBattleEndColorCoding","false"); - - if(Renderer::renderText3DEnabled == true) { - textRenderer3D->begin(CoreData::getInstance().getMenuFontNormal3D()); - } - else { - textRenderer2D->begin(CoreData::getInstance().getMenuFontNormal()); - } - - int lm= 20; - int bm= 100; - - int realPlayerCount = 0; - Vec3f normalColor = Vec3f(WHITE.x,WHITE.y,WHITE.z); - for(int i = 0; i < stats.getFactionCount(); ++i) { - if(stats.getTeam(i) == GameConstants::maxPlayers -1 + fpt_Observer) { - continue; - } - - realPlayerCount++; - int textX= lm + 60 + (realPlayerCount*100); - int team= stats.getTeam(i) + 1; - int kills= stats.getKills(i); - int enemykills= stats.getEnemyKills(i); - int deaths= stats.getDeaths(i); - int unitsProduced= stats.getUnitsProduced(i); - int resourcesHarvested= stats.getResourcesHarvested(i); - - int score= enemykills*100 + unitsProduced*50 + resourcesHarvested/10; - string controlString; - - if(stats.getPersonalityType(i) == fpt_Observer) { - controlString= GameConstants::OBSERVER_SLOTNAME; - } - else { - switch(stats.getControl(i)) { - case ctCpuEasy: - controlString= lang.getString("CpuEasy"); - break; - case ctCpu: - controlString= lang.getString("Cpu"); - break; - case ctCpuUltra: - controlString= lang.getString("CpuUltra"); - break; - case ctCpuMega: - controlString= lang.getString("CpuMega"); - break; - case ctNetwork: - controlString= lang.getString("Network"); - break; - case ctHuman: - controlString= lang.getString("Human"); - break; - - case ctNetworkCpuEasy: - controlString= lang.getString("NetworkCpuEasy"); - break; - case ctNetworkCpu: - controlString= lang.getString("NetworkCpu"); - break; - case ctNetworkCpuUltra: - controlString= lang.getString("NetworkCpuUltra"); - break; - case ctNetworkCpuMega: - controlString= lang.getString("NetworkCpuMega"); - break; - - default: - printf("Error control = %d for i = %d\n",stats.getControl(i),i); - assert(false); - break; - }; - } - - if(stats.getControl(i) != ctHuman && stats.getControl(i) != ctNetwork ) { - controlString += "\nx " + floatToStr(stats.getResourceMultiplier(i),1); - } - else if(stats.getPlayerLeftBeforeEnd(i)==true){ - controlString += "\n" +lang.getString("CpuUltra")+"\nx "+floatToStr(stats.getResourceMultiplier(i),1); - } - - if(score == bestScore && stats.getVictory(i)) { - if(CoreData::getInstance().getGameWinnerTexture() != NULL) { - renderer.renderTextureQuad(textX, bm+420,-1,-1,CoreData::getInstance().getGameWinnerTexture(),0.7f); - } - } - - Vec3f color = stats.getPlayerColor(i); - if(stats.getPlayerName(i) != "") { - string textToRender=stats.getPlayerName(i).substr(0,11); - if(stats.getPlayerLeftBeforeEnd(i)==true){ - textToRender+="\n("+getTimeDuationString(stats.getTimePlayerLeft(i),GameConstants::updateFps) + ")"; - } - - textRenderer->render(textToRender.c_str(), textX, bm+400, false, &color); - } - else { - textRenderer->render((lang.getString("Player") + " " + intToStr(i+1)).c_str(), textX, bm+400,false, &color); - } - - Vec3f highliteColor = Vec3f(WHITE.x,WHITE.y,WHITE.z); - if(disableStatsColorCoding == false) { - highliteColor.x = 0.85f; - highliteColor.y = 0.8f; - highliteColor.z = 0.07f; - } - - if(stats.getPersonalityType(i) == fpt_Observer) { - textRenderer->render(lang.getString("GameOver").c_str(), textX, bm+360, false , &normalColor); - } - else { - if(stats.getVictory(i)) { - textRenderer->render(stats.getVictory(i)? lang.getString("Victory").c_str(): lang.getString("Defeat").c_str(), textX, bm+360, false, &highliteColor); - } - else { - textRenderer->render(stats.getVictory(i)? lang.getString("Victory").c_str(): lang.getString("Defeat").c_str(), textX, bm+360, false, &normalColor); - } - } - - textRenderer->render(controlString, textX, bm+320, false, &normalColor); - textRenderer->render(stats.getFactionTypeName(i), textX, bm+280, false, &normalColor); - textRenderer->render(intToStr(team).c_str(), textX, bm+240, false, &normalColor); - - if(kills == bestKills) { - textRenderer->render(intToStr(kills).c_str(), textX, bm+200, false,&highliteColor); - } - else { - textRenderer->render(intToStr(kills).c_str(), textX, bm+200, false, &normalColor); - } - if(enemykills == bestEnemyKills) { - textRenderer->render(intToStr(enemykills).c_str(), textX, bm+180, false , &highliteColor); - } - else { - textRenderer->render(intToStr(enemykills).c_str(), textX, bm+180, false, &normalColor); - } - if(deaths == leastDeaths) { - textRenderer->render(intToStr(deaths).c_str(), textX, bm+160,false,&highliteColor); - } - else { - textRenderer->render(intToStr(deaths).c_str(), textX, bm+160, false, &normalColor); - } - if(unitsProduced == bestUnitsProduced) { - textRenderer->render(intToStr(unitsProduced).c_str(), textX, bm+120,false,&highliteColor); - } - else { - textRenderer->render(intToStr(unitsProduced).c_str(), textX, bm+120, false, &normalColor); - } - if(resourcesHarvested == bestResourcesHarvested) { - textRenderer->render(intToStr(resourcesHarvested).c_str(), textX, bm+80,false,&highliteColor); - } - else { - textRenderer->render(intToStr(resourcesHarvested).c_str(), textX, bm+80, false, &normalColor); - } - if(score == bestScore) { - textRenderer->render(intToStr(score).c_str(), textX, bm+20,false,&highliteColor); - } - else { - textRenderer->render(intToStr(score).c_str(), textX, bm+20, false, &normalColor); - } - } - - textRenderer->render("\n"+(lang.getString("LeftAt")), lm, bm+400, false, &normalColor); - textRenderer->render(lang.getString("Result"), lm, bm+360); - textRenderer->render(lang.getString("Control"), lm, bm+320); - textRenderer->render(lang.getString("Faction"), lm, bm+280); - textRenderer->render(lang.getString("Team"), lm, bm+240); - textRenderer->render(lang.getString("Kills"), lm, bm+200); - textRenderer->render(lang.getString("EnemyKills"), lm, bm+180); - textRenderer->render(lang.getString("Deaths"), lm, bm+160); - textRenderer->render(lang.getString("UnitsProduced"), lm, bm+120); - textRenderer->render(lang.getString("ResourcesHarvested"), lm, bm+80); - textRenderer->render(lang.getString("Score"), lm, bm+20); - - textRenderer->end(); - - if(Renderer::renderText3DEnabled == true) { - textRenderer3D->begin(CoreData::getInstance().getMenuFontVeryBig3D()); - } - else { - textRenderer2D->begin(CoreData::getInstance().getMenuFontVeryBig()); - } - - string header = stats.getDescription() + " - "; - - if(stats.getThisFactionIndex() >= 0 && stats.getTeam(stats.getThisFactionIndex()) != GameConstants::maxPlayers -1 + fpt_Observer) { - if(stats.getVictory(stats.getThisFactionIndex())){ - header += lang.getString("Victory"); - } - else{ - header += lang.getString("Defeat"); - } - } - else { - header += "Observer"; - } - textRenderer->render(header, lm+250, bm+550); - - //GameConstants::updateFps - //string header2 = lang.getString("GameDurationTime","",true) + " " + floatToStr(stats.getWorldTimeElapsed() / 24.0,2); - - string header2 = lang.getString("GameDurationTime","",true) + ": " + getTimeDuationString(stats.getFramesToCalculatePlaytime(),GameConstants::updateFps); - textRenderer->render(header2, lm+250, bm+530); - - header2 = lang.getString("GameMaxConcurrentUnitCount") + ": " + intToStr(stats.getMaxConcurrentUnitCount()); - textRenderer->render(header2, lm+250, bm+510); - - header2 = lang.getString("GameTotalEndGameConcurrentUnitCount") + ": " + intToStr(stats.getTotalEndGameConcurrentUnitCount()); - textRenderer->render(header2, lm+250, bm+490); - - textRenderer->end(); - - renderer.renderButton(&buttonExit); - - //exit message box - if(mainMessageBox.getEnabled() && renderToTextureCount < 300){ - renderer.renderMessageBox(&mainMessageBox); - } - - if(menuBackgroundVideo == NULL && renderToTexture == NULL) { - renderer.renderMouse2d(mouseX, mouseY, mouse2d, 0.f); - } - - if(menuBackgroundVideo == NULL && renderToTextureCount >= 300) { - renderer.endRenderToTexture(&renderToTexture); - } - - if(menuBackgroundVideo == NULL) { - if(renderToTexture == NULL && renderToTextureCount < 300) { - renderToTextureCount++; - } - } - } - - renderer.renderFPSWhenEnabled(lastFps); - - renderer.swapBuffers(); + if (this->stats.getIsMasterserverMode() == true) { + return; + } + Renderer &renderer = Renderer::getInstance(); + // CoreData &coreData= CoreData::getInstance(); + + canRender(); + incrementFps(); + + // printf("In [%s::%s Line: %d] renderToTexture + // [%p]\n",__FILE__,__FUNCTION__,__LINE__,renderToTexture); + if (menuBackgroundVideo == NULL && renderToTexture != NULL) { + // printf("Rendering from texture!\n"); + + renderer.clearBuffers(); + renderer.reset3dMenu(); + renderer.clearZBuffer(); + + renderer.reset2d(); + + renderer.renderBackground(renderToTexture); + + renderer.renderButton(&buttonExit); + + // exit message box + if (mainMessageBox.getEnabled() && mainMessageBox.getVisible()) { + renderer.renderMessageBox(&mainMessageBox); + } + + renderer.renderMouse2d(mouseX, mouseY, mouse2dAnim); + } else { + // printf("Rendering to texture!\n"); + + if (menuBackgroundVideo == NULL && renderToTextureCount >= 300) { + renderer.beginRenderToTexture(&renderToTexture); + } + + TextRenderer2D *textRenderer2D = renderer.getTextRenderer(); + TextRenderer3D *textRenderer3D = renderer.getTextRenderer3D(); + TextRenderer *textRenderer = NULL; + + if (Renderer::renderText3DEnabled == true) { + textRenderer = textRenderer3D; + } else { + textRenderer = textRenderer2D; + } + + Lang &lang = Lang::getInstance(); + + renderer.clearBuffers(); + renderer.reset3dMenu(); + renderer.clearZBuffer(); + renderer.reset2d(); + + if (menuBackgroundVideo != NULL) { + // printf("Rendering video not null!\n"); + + if (menuBackgroundVideo->isPlaying() == true) { + menuBackgroundVideo->playFrame(false); + + // printf("Rendering video playing!\n"); + } else { + if (menuBackgroundVideo != NULL) { + // initBackgroundVideo(); + menuBackgroundVideo->RestartVideo(); + } + } + } else { + renderer.renderBackground(CoreData::getInstance().getBackgroundTexture()); + } + + // int winnerIndex = -1; + int bestScore = -1; + // int mostKillsIndex = -1; + int bestKills = -1; + // int mostEnemyKillsIndex = -1; + int bestEnemyKills = -1; + // int leastDeathsIndex = -1; + int leastDeaths = -1; + // int mostUnitsProducedIndex = -1; + int bestUnitsProduced = -1; + // int mostResourcesHarvestedIndex = -1; + int bestResourcesHarvested = -1; + + for (int i = 0; i < stats.getFactionCount(); ++i) { + if (stats.getTeam(i) == GameConstants::maxPlayers - 1 + fpt_Observer) { + continue; + } + + // int team= stats.getTeam(i) + 1; + int kills = stats.getKills(i); + if (kills > bestKills) { + bestKills = kills; + // mostKillsIndex = i; + } + + int enemykills = stats.getEnemyKills(i); + if (enemykills > bestEnemyKills) { + bestEnemyKills = enemykills; + // mostEnemyKillsIndex = i; + } + + int deaths = stats.getDeaths(i); + if (deaths < leastDeaths || leastDeaths < 0) { + leastDeaths = deaths; + // leastDeathsIndex = i; + } + + int unitsProduced = stats.getUnitsProduced(i); + if (unitsProduced > bestUnitsProduced) { + bestUnitsProduced = unitsProduced; + // mostUnitsProducedIndex = i; + } + + int resourcesHarvested = stats.getResourcesHarvested(i); + if (resourcesHarvested > bestResourcesHarvested) { + bestResourcesHarvested = resourcesHarvested; + // mostResourcesHarvestedIndex = i; + } + + int score = + enemykills * 100 + unitsProduced * 50 + resourcesHarvested / 10; + + if (score > bestScore) { + bestScore = score; + // winnerIndex = i; + } + } + + bool disableStatsColorCoding = + Config::getInstance().getBool("DisableBattleEndColorCoding", "false"); + + if (Renderer::renderText3DEnabled == true) { + textRenderer3D->begin(CoreData::getInstance().getMenuFontNormal3D()); + } else { + textRenderer2D->begin(CoreData::getInstance().getMenuFontNormal()); + } + + int lm = 20; + int bm = 100; + + int realPlayerCount = 0; + Vec3f normalColor = Vec3f(WHITE.x, WHITE.y, WHITE.z); + for (int i = 0; i < stats.getFactionCount(); ++i) { + if (stats.getTeam(i) == GameConstants::maxPlayers - 1 + fpt_Observer) { + continue; + } + + realPlayerCount++; + int textX = lm + 60 + (realPlayerCount * 100); + int team = stats.getTeam(i) + 1; + int kills = stats.getKills(i); + int enemykills = stats.getEnemyKills(i); + int deaths = stats.getDeaths(i); + int unitsProduced = stats.getUnitsProduced(i); + int resourcesHarvested = stats.getResourcesHarvested(i); + + int score = + enemykills * 100 + unitsProduced * 50 + resourcesHarvested / 10; + string controlString; + + if (stats.getPersonalityType(i) == fpt_Observer) { + controlString = GameConstants::OBSERVER_SLOTNAME; + } else { + switch (stats.getControl(i)) { + case ctCpuEasy: + controlString = lang.getString("CpuEasy"); + break; + case ctCpu: + controlString = lang.getString("Cpu"); + break; + case ctCpuUltra: + controlString = lang.getString("CpuUltra"); + break; + case ctCpuMega: + controlString = lang.getString("CpuMega"); + break; + case ctNetwork: + controlString = lang.getString("Network"); + break; + case ctHuman: + controlString = lang.getString("Human"); + break; + + case ctNetworkCpuEasy: + controlString = lang.getString("NetworkCpuEasy"); + break; + case ctNetworkCpu: + controlString = lang.getString("NetworkCpu"); + break; + case ctNetworkCpuUltra: + controlString = lang.getString("NetworkCpuUltra"); + break; + case ctNetworkCpuMega: + controlString = lang.getString("NetworkCpuMega"); + break; + + default: + printf("Error control = %d for i = %d\n", stats.getControl(i), i); + assert(false); + break; + }; + } + + if (stats.getControl(i) != ctHuman && stats.getControl(i) != ctNetwork) { + controlString += "\nx " + floatToStr(stats.getResourceMultiplier(i), 1); + } else if (stats.getPlayerLeftBeforeEnd(i) == true) { + controlString += "\n" + lang.getString("CpuUltra") + "\nx " + + floatToStr(stats.getResourceMultiplier(i), 1); + } + + if (score == bestScore && stats.getVictory(i)) { + if (CoreData::getInstance().getGameWinnerTexture() != NULL) { + renderer.renderTextureQuad( + textX, bm + 420, -1, -1, + CoreData::getInstance().getGameWinnerTexture(), 0.7f); + } + } + + Vec3f color = stats.getPlayerColor(i); + if (stats.getPlayerName(i) != "") { + string textToRender = stats.getPlayerName(i).substr(0, 11); + if (stats.getPlayerLeftBeforeEnd(i) == true) { + textToRender += "\n(" + + getTimeDuationString(stats.getTimePlayerLeft(i), + GameConstants::updateFps) + + ")"; + } + + textRenderer->render(textToRender.c_str(), textX, bm + 400, false, + &color); + } else { + textRenderer->render( + (lang.getString("Player") + " " + intToStr(i + 1)).c_str(), textX, + bm + 400, false, &color); + } + + Vec3f highliteColor = Vec3f(WHITE.x, WHITE.y, WHITE.z); + if (disableStatsColorCoding == false) { + highliteColor.x = 0.85f; + highliteColor.y = 0.8f; + highliteColor.z = 0.07f; + } + + if (stats.getPersonalityType(i) == fpt_Observer) { + textRenderer->render(lang.getString("GameOver").c_str(), textX, + bm + 360, false, &normalColor); + } else { + if (stats.getVictory(i)) { + textRenderer->render(stats.getVictory(i) + ? lang.getString("Victory").c_str() + : lang.getString("Defeat").c_str(), + textX, bm + 360, false, &highliteColor); + } else { + textRenderer->render(stats.getVictory(i) + ? lang.getString("Victory").c_str() + : lang.getString("Defeat").c_str(), + textX, bm + 360, false, &normalColor); + } + } + + textRenderer->render(controlString, textX, bm + 320, false, &normalColor); + textRenderer->render(stats.getFactionTypeName(i), textX, bm + 280, false, + &normalColor); + textRenderer->render(intToStr(team).c_str(), textX, bm + 240, false, + &normalColor); + + if (kills == bestKills) { + textRenderer->render(intToStr(kills).c_str(), textX, bm + 200, false, + &highliteColor); + } else { + textRenderer->render(intToStr(kills).c_str(), textX, bm + 200, false, + &normalColor); + } + if (enemykills == bestEnemyKills) { + textRenderer->render(intToStr(enemykills).c_str(), textX, bm + 180, + false, &highliteColor); + } else { + textRenderer->render(intToStr(enemykills).c_str(), textX, bm + 180, + false, &normalColor); + } + if (deaths == leastDeaths) { + textRenderer->render(intToStr(deaths).c_str(), textX, bm + 160, false, + &highliteColor); + } else { + textRenderer->render(intToStr(deaths).c_str(), textX, bm + 160, false, + &normalColor); + } + if (unitsProduced == bestUnitsProduced) { + textRenderer->render(intToStr(unitsProduced).c_str(), textX, bm + 120, + false, &highliteColor); + } else { + textRenderer->render(intToStr(unitsProduced).c_str(), textX, bm + 120, + false, &normalColor); + } + if (resourcesHarvested == bestResourcesHarvested) { + textRenderer->render(intToStr(resourcesHarvested).c_str(), textX, + bm + 80, false, &highliteColor); + } else { + textRenderer->render(intToStr(resourcesHarvested).c_str(), textX, + bm + 80, false, &normalColor); + } + if (score == bestScore) { + textRenderer->render(intToStr(score).c_str(), textX, bm + 20, false, + &highliteColor); + } else { + textRenderer->render(intToStr(score).c_str(), textX, bm + 20, false, + &normalColor); + } + } + + textRenderer->render("\n" + (lang.getString("LeftAt")), lm, bm + 400, false, + &normalColor); + textRenderer->render(lang.getString("Result"), lm, bm + 360); + textRenderer->render(lang.getString("Control"), lm, bm + 320); + textRenderer->render(lang.getString("Faction"), lm, bm + 280); + textRenderer->render(lang.getString("Team"), lm, bm + 240); + textRenderer->render(lang.getString("Kills"), lm, bm + 200); + textRenderer->render(lang.getString("EnemyKills"), lm, bm + 180); + textRenderer->render(lang.getString("Deaths"), lm, bm + 160); + textRenderer->render(lang.getString("UnitsProduced"), lm, bm + 120); + textRenderer->render(lang.getString("ResourcesHarvested"), lm, bm + 80); + textRenderer->render(lang.getString("Score"), lm, bm + 20); + + textRenderer->end(); + + if (Renderer::renderText3DEnabled == true) { + textRenderer3D->begin(CoreData::getInstance().getMenuFontVeryBig3D()); + } else { + textRenderer2D->begin(CoreData::getInstance().getMenuFontVeryBig()); + } + + string header = stats.getDescription() + " - "; + + if (stats.getThisFactionIndex() >= 0 && + stats.getTeam(stats.getThisFactionIndex()) != + GameConstants::maxPlayers - 1 + fpt_Observer) { + if (stats.getVictory(stats.getThisFactionIndex())) { + header += lang.getString("Victory"); + } else { + header += lang.getString("Defeat"); + } + } else { + header += "Observer"; + } + textRenderer->render(header, lm + 250, bm + 550); + + // GameConstants::updateFps + // string header2 = lang.getString("GameDurationTime","",true) + " " + + // floatToStr(stats.getWorldTimeElapsed() / 24.0,2); + + string header2 = lang.getString("GameDurationTime", "", true) + ": " + + getTimeDuationString(stats.getFramesToCalculatePlaytime(), + GameConstants::updateFps); + textRenderer->render(header2, lm + 250, bm + 530); + + header2 = lang.getString("GameMaxConcurrentUnitCount") + ": " + + intToStr(stats.getMaxConcurrentUnitCount()); + textRenderer->render(header2, lm + 250, bm + 510); + + header2 = lang.getString("GameTotalEndGameConcurrentUnitCount") + ": " + + intToStr(stats.getTotalEndGameConcurrentUnitCount()); + textRenderer->render(header2, lm + 250, bm + 490); + + textRenderer->end(); + + renderer.renderButton(&buttonExit); + + // exit message box + if (mainMessageBox.getEnabled() && renderToTextureCount < 300) { + renderer.renderMessageBox(&mainMessageBox); + } + + if (menuBackgroundVideo == NULL && renderToTexture == NULL) { + renderer.renderMouse2d(mouseX, mouseY, mouse2d, 0.f); + } + + if (menuBackgroundVideo == NULL && renderToTextureCount >= 300) { + renderer.endRenderToTexture(&renderToTexture); + } + + if (menuBackgroundVideo == NULL) { + if (renderToTexture == NULL && renderToTextureCount < 300) { + renderToTextureCount++; + } + } + } + + renderer.renderFPSWhenEnabled(lastFps); + + renderer.swapBuffers(); } -void BattleEnd::keyDown(SDL_KeyboardEvent key){ - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(isKeyPressed(SDLK_ESCAPE,key) == true) { - //program->setState(new MainMenu(program)); - - if(mainMessageBox.getEnabled()) { - mainMessageBox.setEnabled(false); - } - else { - Lang &lang= Lang::getInstance(); - showMessageBox(lang.getString("ExitToRootMenu"), "", true); - } - } - else if(isKeyPressed(SDLK_RETURN,key) && mainMessageBox.getEnabled()) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - program->setState(new MainMenu(program)); - } +void BattleEnd::keyDown(SDL_KeyboardEvent key) { + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); + if (isKeyPressed(SDLK_ESCAPE, key) == true) { + // program->setState(new MainMenu(program)); + + if (mainMessageBox.getEnabled()) { + mainMessageBox.setEnabled(false); + } else { + Lang &lang = Lang::getInstance(); + showMessageBox(lang.getString("ExitToRootMenu"), "", true); + } + } else if (isKeyPressed(SDLK_RETURN, key) && mainMessageBox.getEnabled()) { + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + program->setState(new MainMenu(program)); + } } -void BattleEnd::mouseDownLeft(int x, int y){ - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); - //program->setState(new MainMenu(program)); - - if(buttonExit.mouseClick(x,y)) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); - program->setState(new MainMenu(program)); - } - else if(mainMessageBox.getEnabled()) { - int button= 0; - if(mainMessageBox.mouseClick(x, y, button)) { - if(button==0) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - program->setState(new MainMenu(program)); - } - else { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - //close message box - mainMessageBox.setEnabled(false); - } - } - } - +void BattleEnd::mouseDownLeft(int x, int y) { + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); + // program->setState(new MainMenu(program)); + + if (buttonExit.mouseClick(x, y)) { + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); + program->setState(new MainMenu(program)); + } else if (mainMessageBox.getEnabled()) { + int button = 0; + if (mainMessageBox.mouseClick(x, y, button)) { + if (button == 0) { + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + program->setState(new MainMenu(program)); + } else { + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + // close message box + mainMessageBox.setEnabled(false); + } + } + } } -void BattleEnd::mouseMove(int x, int y, const MouseState *ms){ - mouseX = x; - mouseY = y; - - buttonExit.mouseMove(x, y); - if (mainMessageBox.getEnabled()) { - mainMessageBox.mouseMove(x, y); - } +void BattleEnd::mouseMove(int x, int y, const MouseState *ms) { + mouseX = x; + mouseY = y; + buttonExit.mouseMove(x, y); + if (mainMessageBox.getEnabled()) { + mainMessageBox.mouseMove(x, y); + } } -void BattleEnd::showMessageBox(const string &text, const string &header, bool toggle) { - if(toggle == false) { - mainMessageBox.setEnabled(false); - } - - if(mainMessageBox.getEnabled() == false) { - mainMessageBox.setText(text); - mainMessageBox.setHeader(header); - mainMessageBox.setEnabled(true); - } - else { - mainMessageBox.setEnabled(false); - } +void BattleEnd::showMessageBox(const string &text, const string &header, + bool toggle) { + if (toggle == false) { + mainMessageBox.setEnabled(false); + } + + if (mainMessageBox.getEnabled() == false) { + mainMessageBox.setText(text); + mainMessageBox.setHeader(header); + mainMessageBox.setEnabled(true); + } else { + mainMessageBox.setEnabled(false); + } } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/main/battle_end.h b/source/glest_game/main/battle_end.h index 9434fcd36..4bd812995 100644 --- a/source/glest_game/main/battle_end.h +++ b/source/glest_game/main/battle_end.h @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,65 +13,68 @@ #define _GLEST_GAME_BATTLEEND_H_ #ifdef WIN32 - #include - #include +#include +#include #endif +#include "leak_dumper.h" #include "program.h" #include "stats.h" -#include "leak_dumper.h" -namespace Shared { namespace Graphics { - class VideoPlayer; -}} +namespace Shared { +namespace Graphics { +class VideoPlayer; +} +} // namespace Shared -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { class GameSettings; // ===================================================== -// class BattleEnd +// class BattleEnd // /// ProgramState representing the end of the game // ===================================================== -class BattleEnd: public ProgramState{ +class BattleEnd : public ProgramState { private: - Stats stats; + Stats stats; - GraphicButton buttonExit; - int mouse2d; - GraphicMessageBox mainMessageBox; - Texture2D *renderToTexture; - uint64 renderToTextureCount; - ProgramState *originState; - const char *containerName; + GraphicButton buttonExit; + int mouse2d; + GraphicMessageBox mainMessageBox; + Texture2D *renderToTexture; + uint64 renderToTextureCount; + ProgramState *originState; + const char *containerName; - ::Shared::Graphics::VideoPlayer *menuBackgroundVideo; - GameSettings *gameSettings; - StrSound battleEndMusic; + ::Shared::Graphics::VideoPlayer *menuBackgroundVideo; + GameSettings *gameSettings; + StrSound battleEndMusic; - void showMessageBox(const string &text, const string &header, bool toggle); + void showMessageBox(const string &text, const string &header, bool toggle); public: - BattleEnd(Program *program, const Stats *stats, ProgramState *originState); - ~BattleEnd(); + BattleEnd(Program *program, const Stats *stats, ProgramState *originState); + ~BattleEnd(); - virtual void update(); - virtual void render(); - virtual void keyDown(SDL_KeyboardEvent key); - virtual void mouseDownLeft(int x, int y); - virtual void mouseMove(int x, int y, const MouseState *ms); - //virtual void tick(); - virtual void reloadUI(); + virtual void update(); + virtual void render(); + virtual void keyDown(SDL_KeyboardEvent key); + virtual void mouseDownLeft(int x, int y); + virtual void mouseMove(int x, int y, const MouseState *ms); + // virtual void tick(); + virtual void reloadUI(); private: - - void initBackgroundVideo(); - std::pair getBattleEndVideo(bool won); - string getBattleEndMusic(bool won); - void initBackgroundMusic(); + void initBackgroundVideo(); + std::pair getBattleEndVideo(bool won); + string getBattleEndMusic(bool won); + void initBackgroundMusic(); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/main/intro.cpp b/source/glest_game/main/intro.cpp index 2a57e9d58..93c07f0ff 100644 --- a/source/glest_game/main/intro.cpp +++ b/source/glest_game/main/intro.cpp @@ -10,20 +10,19 @@ // ============================================================== #include "intro.h" -#include "main_menu.h" -#include "util.h" -#include "game_util.h" +#include "auto_test.h" #include "config.h" +#include "core_data.h" +#include "game_util.h" +#include "main_menu.h" +#include "metrics.h" #include "program.h" #include "renderer.h" #include "sound_renderer.h" -#include "core_data.h" -#include "metrics.h" -#include "auto_test.h" #include "util.h" -//#include "glm.h" -//#include "md5util.h" -//#include "Mathlib.h" +// #include "glm.h" +// #include "md5util.h" +// #include "Mathlib.h" #include "video_player.h" @@ -31,797 +30,837 @@ using namespace Shared::Util; using namespace Shared::Graphics; -using namespace Shared::Xml; +using namespace Shared::Xml; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { -//struct Timer { -//public: -// Timer () -// : current_time (0.0), last_time (0.0) { } +// struct Timer { +// public: +// Timer () +// : current_time (0.0), last_time (0.0) { } // -//public: -// void update () { -// last_time = current_time; -// current_time = static_cast(SDL_GetTicks ()) / 1000.0; -// } +// public: +// void update () { +// last_time = current_time; +// current_time = static_cast(SDL_GetTicks ()) / 1000.0; +// } // -// double deltaTime () const { -// return (current_time - last_time); -// } +// double deltaTime () const { +// return (current_time - last_time); +// } // -//public: -// double current_time; -// double last_time; +// public: +// double current_time; +// double last_time; // -//} animTimer; +// } animTimer; // ===================================================== // class Text // ===================================================== -IntroText::IntroText(const string &text, const Vec2i &pos, int time, Font2D *font, Font3D *font3D) { - this->text= text; - this->pos= pos; - this->time= time; - this->texture= NULL; - this->font= font; - this->font3D = font3D; +IntroText::IntroText(const string &text, const Vec2i &pos, int time, + Font2D *font, Font3D *font3D) { + this->text = text; + this->pos = pos; + this->time = time; + this->texture = NULL; + this->font = font; + this->font3D = font3D; } -IntroText::IntroText(const Texture2D *texture, const Vec2i &pos, const Vec2i &size, int time) { - this->pos= pos; - this->size= size; - this->time= time; - this->texture= texture; - this->font= NULL; - this->font3D=NULL; +IntroText::IntroText(const Texture2D *texture, const Vec2i &pos, + const Vec2i &size, int time) { + this->pos = pos; + this->size = size; + this->time = time; + this->texture = texture; + this->font = NULL; + this->font3D = NULL; } // ===================================================== // class Intro // ===================================================== -int Intro::introTime = 50000; -int Intro::appearTime = 2500; -int Intro::showTime = 3500; -int Intro::disapearTime = 2500; - -Intro::Intro(Program *program): - ProgramState(program) -{ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - CoreData &coreData= CoreData::getInstance(); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && - (::Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == false || - CoreData::getInstance().hasIntroVideoFilename() == false)) { - soundRenderer.playMusic(CoreData::getInstance().getIntroMusic()); - } - - const Metrics &metrics= Metrics::getInstance(); - int w= metrics.getVirtualW(); - int h= metrics.getVirtualH(); - timer=0; - mouseX = 0; - mouseY = 0; - mouse2d = 0; - exitAfterIntroVideo = false; - - Renderer &renderer= Renderer::getInstance(); - //renderer.init3dListMenu(NULL); - renderer.initMenu(NULL); - fade= 0.f; - anim= 0.f; - targetCamera= NULL; - t= 0.f; - - startPosition.x= 5;; - startPosition.y= 10; - startPosition.z= 40; - camera.setPosition(startPosition); - - Vec3f startRotation; - startRotation.x= 0; - startRotation.y= 0; - startRotation.z= 0; - - camera.setOrientation(Quaternion(EulerAngles( - degToRad(startRotation.x), - degToRad(startRotation.y), - degToRad(startRotation.z)))); - - Intro::introTime = 3000; - Intro::appearTime = 500; - Intro::showTime = 500; - Intro::disapearTime = 500; - int showIntroPics = 0; - int showIntroPicsTime = 0; - bool showIntroPicsRandom = false; - bool showIntroModels = false; - bool showIntroModelsRandom = false; - modelMinAnimSpeed = 0; - modelMaxAnimSpeed = 0; - - XmlTree xmlTree; - string data_path = getGameReadWritePath(GameConstants::path_data_CacheLookupKey); - xmlTree.load(getGameCustomCoreDataPath(data_path, "data/core/menu/menu.xml"),Properties::getTagReplacementValues()); - const XmlNode *menuNode= xmlTree.getRootNode(); - - if(menuNode->hasChild("intro") == true) { - const XmlNode *introNode= menuNode->getChild("intro"); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); - - //camera - const XmlNode *cameraNode= introNode->getChild("camera"); - - //position - const XmlNode *positionNode= cameraNode->getChild("start-position"); - startPosition.x= positionNode->getAttribute("x")->getFloatValue(); - startPosition.y= positionNode->getAttribute("y")->getFloatValue(); - startPosition.z= positionNode->getAttribute("z")->getFloatValue(); - camera.setPosition(startPosition); - - //rotation - const XmlNode *rotationNode= cameraNode->getChild("start-rotation"); - Vec3f startRotation; - startRotation.x= rotationNode->getAttribute("x")->getFloatValue(); - startRotation.y= rotationNode->getAttribute("y")->getFloatValue(); - startRotation.z= rotationNode->getAttribute("z")->getFloatValue(); - camera.setOrientation(Quaternion(EulerAngles( - degToRad(startRotation.x), - degToRad(startRotation.y), - degToRad(startRotation.z)))); - - // intro info - const XmlNode *introTimeNode= introNode->getChild("intro-time"); - Intro::introTime = introTimeNode->getAttribute("value")->getIntValue(); - const XmlNode *appearTimeNode= introNode->getChild("appear-time"); - Intro::appearTime = appearTimeNode->getAttribute("value")->getIntValue(); - const XmlNode *showTimeNode= introNode->getChild("show-time"); - Intro::showTime = showTimeNode->getAttribute("value")->getIntValue(); - const XmlNode *disappearTimeNode= introNode->getChild("disappear-time"); - Intro::disapearTime = disappearTimeNode->getAttribute("value")->getIntValue(); - const XmlNode *showIntroPicturesNode= introNode->getChild("show-intro-pictures"); - showIntroPics = showIntroPicturesNode->getAttribute("value")->getIntValue(); - showIntroPicsTime = showIntroPicturesNode->getAttribute("time")->getIntValue(); - showIntroPicsRandom = showIntroPicturesNode->getAttribute("random")->getBoolValue(); - - const XmlNode *showIntroModelsNode= introNode->getChild("show-intro-models"); - showIntroModels = showIntroModelsNode->getAttribute("value")->getBoolValue(); - showIntroModelsRandom = showIntroModelsNode->getAttribute("random")->getBoolValue(); - modelMinAnimSpeed = showIntroModelsNode->getAttribute("min-anim-speed")->getFloatValue(); - modelMaxAnimSpeed = showIntroModelsNode->getAttribute("max-anim-speed")->getFloatValue(); - } - - //load main model - modelIndex = 0; - models.clear(); - if(showIntroModels == true) { - - //getGameCustomCoreDataPath(data_path, "data/core/menu/menu.xml") - string introPath = getGameCustomCoreDataPath(data_path, "") + "data/core/menu/main_model/intro*.g3d"; - vector introModels; - findAll(introPath, introModels, false, false); - for(int i = 0; i < (int)introModels.size(); ++i) { - string logo = introModels[i]; - Model *model= renderer.newModel(rsMenu, getGameCustomCoreDataPath(data_path, "") + "data/core/menu/main_model/" + logo); - if(model) { - models.push_back(model); - //printf("#1 Intro model [%s]\n",model->getFileName().c_str()); - } - } - - if(models.empty() == true) { - introPath = data_path + "data/core/menu/main_model/intro*.g3d"; - //vector introModels; - findAll(introPath, introModels, false, false); - for(int i = 0; i < (int)introModels.size(); ++i) { - string logo = introModels[i]; - Model *model= renderer.newModel(rsMenu, data_path + "data/core/menu/main_model/" + logo); - if(model) { - models.push_back(model); - //printf("#2 Intro model [%s]\n",model->getFileName().c_str()); - } - } - } - - if(showIntroModelsRandom == true) { - std::vector modelList; - - //unsigned int seed = time(NULL); - Chrono seed(true); - srand((unsigned int)seed.getCurTicks()); - int failedLookups=0; - std::map usedIndex; - for(;modelList.size() < models.size();) { - int index = rand() % models.size(); - if(usedIndex.find(index) != usedIndex.end()) { - failedLookups++; - srand((unsigned int)seed.getCurTicks() / failedLookups); - continue; - } - //printf("picIndex = %d list count = %d\n",picIndex,coreData.getMiscTextureList().size()); - modelList.push_back(models[index]); - usedIndex[index]=true; - srand((unsigned int)seed.getCurTicks() / (unsigned int)modelList.size()); - } - models = modelList; - } - } - - int displayItemNumber = 1; - int appear= Intro::appearTime; - int disappear= Intro::showTime+Intro::appearTime+(Intro::disapearTime * 2); - - const unsigned int maxIntroLines = 100; - Lang &lang= Lang::getInstance(); - for(unsigned int i = 1; i < maxIntroLines; ++i) { - string introTagName = "IntroText" + intToStr(i); - string introTagTextureName = "IntroTexture" + intToStr(i); - - if(lang.hasString(introTagName,"",true) == true || - lang.hasString(introTagTextureName,"",true) == true) { - string lineText = ""; - - if(lang.hasString(introTagName,"",true) == true) { - lineText = lang.getString(introTagName,"",true); - } - - string showStartTime = "IntroStartMilliseconds" + intToStr(i); - - int displayTime = appear; - if(lang.hasString(showStartTime,"",true) == true) { - displayTime = strToInt(lang.getString(showStartTime,"",true)); - } - else { - if(i == 1) { - displayTime = appear; - } - else if(i == 2) { - displayTime = disappear; - } - else if(i >= 3) { - displayTime = disappear *(++displayItemNumber); - } - } - - // Is this a texture? - if(lang.hasString(introTagName,"",true) == false && - lang.hasString(introTagTextureName,"",true) == true) { - - string introTagTextureWidthName = "IntroTextureWidth" + intToStr(i); - string introTagTextureHeightName = "IntroTextureHeight" + intToStr(i); - - lineText = lang.getString(introTagTextureName,"",true); - Texture2D *logoTexture= renderer.newTexture2D(rsGlobal); - if(logoTexture) { - logoTexture->setMipmap(false); - logoTexture->getPixmap()->load(lineText); - - renderer.initTexture(rsGlobal, logoTexture); - } - - - int textureWidth = 256; - if(logoTexture != NULL) { - textureWidth = logoTexture->getTextureWidth(); - } - if(lang.hasString(introTagTextureWidthName,"",true) == true) { - textureWidth = strToInt(lang.getString(introTagTextureWidthName,"",true)); - } - - int textureHeight = 128; - if(logoTexture != NULL) { - textureHeight = logoTexture->getTextureHeight(); - } - if(lang.hasString(introTagTextureHeightName,"",true) == true) { - textureHeight = strToInt(lang.getString(introTagTextureHeightName,"",true)); - } - - texts.push_back(new IntroText(logoTexture, Vec2i(w/2-(textureWidth/2), h/2-(textureHeight/2)), Vec2i(textureWidth, textureHeight), displayTime)); - } - // This is a line of text - else { - string introTagTextXName = "IntroTextX" + intToStr(i); - string introTagTextYName = "IntroTextY" + intToStr(i); - string introTagTextFontTypeName = "IntroTextFontType" + intToStr(i); - - int textX = -1; - if(lang.hasString(introTagTextXName,"",true) == true) { - string value = lang.getString(introTagTextXName,"",true); - if(value.length() > 0 && - (value[0] == '+' || value[0] == '-')) { - textX = w/2 + strToInt(value); - } - else { - textX = strToInt(value); - } - } - - int textY = -1; - if(lang.hasString(introTagTextYName,"",true) == true) { - string value = lang.getString(introTagTextYName,"",true); - if(value.length() > 0 && - (value[0] == '+' || value[0] == '-')) { - textY = h/2 + strToInt(value); - } - else { - textY = strToInt(value); - } - } - - Font2D *font = coreData.getMenuFontVeryBig(); - Font3D *font3d = coreData.getMenuFontVeryBig3D(); - - if(lang.hasString(introTagTextFontTypeName,"",true) == true) { - string value =lang.getString(introTagTextFontTypeName,"",true); - if(value == "displaynormal") { - font = coreData.getDisplayFont(); - font3d = coreData.getDisplayFont3D(); - } - else if(value == "displaysmall") { - font = coreData.getDisplayFontSmall(); - font3d = coreData.getDisplayFontSmall3D(); - } - else if(value == "menunormal") { - font = coreData.getMenuFontNormal(); - font3d = coreData.getMenuFontNormal3D(); - } - else if(value == "menubig") { - font = coreData.getMenuFontBig(); - font3d = coreData.getMenuFontBig3D(); - } - else if(value == "menuverybig") { - font = coreData.getMenuFontVeryBig(); - font3d = coreData.getMenuFontVeryBig3D(); - } - else if(value == "consolenormal") { - font = coreData.getConsoleFont(); - font3d = coreData.getConsoleFont3D(); - } - - } - texts.push_back(new IntroText(lineText, Vec2i(textX, textY), displayTime, font,font3d)); - } - } - else { - break; - } - } - modelShowTime = disappear *(displayItemNumber); - if(lang.hasString("IntroModelStartMilliseconds","",true) == true) { - modelShowTime = strToInt(lang.getString("IntroModelStartMilliseconds","",true)); - } - else { - modelShowTime = disappear *(displayItemNumber); - } - -/* - string lineText = "Based on award-winning classic Glest"; - texts.push_back(new Text(lineText, Vec2i(-1, -1), appear, coreData.getMenuFontVeryBig(),coreData.getMenuFontVeryBig3D())); - lineText = "the MegaGlest Team presents"; - texts.push_back(new Text(lineText, Vec2i(-1, -1), disappear, coreData.getMenuFontVeryBig(),coreData.getMenuFontVeryBig3D())); - lineText = "a libre software real-time strategy game"; - texts.push_back(new Text(lineText, Vec2i(-1, -1), disappear *(++displayItemNumber), coreData.getMenuFontVeryBig(),coreData.getMenuFontVeryBig3D())); - - texts.push_back(new Text(coreData.getLogoTexture(), Vec2i(w/2-128, h/2-64), Vec2i(256, 128), disappear *(++displayItemNumber))); - texts.push_back(new Text(glestVersionString, Vec2i(w/2+45, h/2-45), disappear *(displayItemNumber++), coreData.getMenuFontNormal(),coreData.getMenuFontNormal3D())); - lineText = "www.megaglest.org"; - //texts.push_back(new Text(lineText, Vec2i(-1, -1), disappear *(displayItemNumber++), coreData.getMenuFontVeryBig(),coreData.getMenuFontVeryBig3D())); - texts.push_back(new Text(lineText, Vec2i(-1, h/2-45-18), disappear *(displayItemNumber-1), coreData.getMenuFontVeryBig(),coreData.getMenuFontVeryBig3D())); -*/ - - - - if(showIntroPics > 0 && coreData.getMiscTextureList().size() > 0) { - const int showMiscTime = showIntroPicsTime; - - std::vector intoTexList; - if(showIntroPicsRandom == true) { - //unsigned int seed = time(NULL); - Chrono seed(true); - srand((unsigned int)seed.getCurTicks()); - int failedLookups=0; - std::map usedIndex; - for(;(int)intoTexList.size() < showIntroPics;) { - int picIndex = rand() % coreData.getMiscTextureList().size(); - if(usedIndex.find(picIndex) != usedIndex.end()) { - failedLookups++; - srand((unsigned int)seed.getCurTicks() / failedLookups); - - if(failedLookups > 10000) { - for(unsigned int i = 0; - i < coreData.getMiscTextureList().size(); ++i) { - if(usedIndex.find(i) == usedIndex.end()) { - picIndex = i; - break; - } - } - } - else { - continue; - } - } - //printf("picIndex = %d list count = %d\n",picIndex,coreData.getMiscTextureList().size()); - intoTexList.push_back(coreData.getMiscTextureList()[picIndex]); - usedIndex[picIndex]=true; - srand((unsigned int)seed.getCurTicks() / (unsigned int)intoTexList.size()); - } - } - else { - for(unsigned int i = 0; - i < (unsigned int)coreData.getMiscTextureList().size() && - i < (unsigned int)showIntroPics; ++i) { - Texture2D *tex = coreData.getMiscTextureList()[i]; - intoTexList.push_back(tex); - } - } - - for(unsigned int i = 0; i < intoTexList.size(); ++i) { - Texture2D *tex = intoTexList[i]; - //printf("tex # %d [%s]\n",i,tex->getPath().c_str()); - - Vec2i texPlacement; - if(i == 0 || i % 9 == 0) { - texPlacement = Vec2i(1, h-tex->getTextureHeight()); - } - else if(i == 1 || i % 9 == 1) { - texPlacement = Vec2i(1, 1); - } - else if(i == 2 || i % 9 == 2) { - texPlacement = Vec2i(w-tex->getTextureWidth(), 1); - } - else if(i == 3 || i % 9 == 3) { - texPlacement = Vec2i(w-tex->getTextureWidth(), h-tex->getTextureHeight()); - } - else if(i == 4 || i % 9 == 4) { - texPlacement = Vec2i(w/2 - tex->getTextureWidth()/2, h-tex->getTextureHeight()); - } - else if(i == 5 || i % 9 == 5) { - texPlacement = Vec2i(w/2 - tex->getTextureWidth()/2, 1); - } - else if(i == 6 || i % 9 == 6) { - texPlacement = Vec2i(1, (h/2) - (tex->getTextureHeight()/2)); - } - else if(i == 7 || i % 9 == 7) { - texPlacement = Vec2i(w-tex->getTextureWidth(), (h/2) - (tex->getTextureHeight()/2)); - } - - int textureStartTime = disappear * displayItemNumber; - if(lang.hasString("IntroTextureStartMilliseconds","",true) == true) { - textureStartTime = strToInt(lang.getString("IntroTextureStartMilliseconds","",true)); - } - - texts.push_back(new IntroText(tex, texPlacement, Vec2i(tex->getTextureWidth(), tex->getTextureHeight()), textureStartTime +(showMiscTime*(i+1)))); - } - } - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - renderer.swapBuffers(); - } - - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && - ::Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == true && - CoreData::getInstance().hasIntroVideoFilename() == true) { - string introVideoFile = CoreData::getInstance().getIntroVideoFilename(); - string introVideoFileFallback = CoreData::getInstance().getIntroVideoFilenameFallback(); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Intro Video [%s] [%s]\n",introVideoFile.c_str(),introVideoFileFallback.c_str()); - - Context *c= GraphicsInterface::getInstance().getCurrentContext(); - PlatformContextGl *glCtx = static_cast(c)->getPlatformContextGlPtr(); - SDL_Window *window = glCtx->getScreenWindow(); - SDL_Surface *screen = glCtx->getScreenSurface(); - - string vlcPluginsPath = Config::getInstance().getString("VideoPlayerPluginsPath",""); - //printf("screen->w = %d screen->h = %d screen->format->BitsPerPixel = %d\n",screen->w,screen->h,screen->format->BitsPerPixel); - ::Shared::Graphics::VideoPlayer player( - &Renderer::getInstance(), - introVideoFile, - introVideoFileFallback, - window, - 0,0, - screen->w, - screen->h, - screen->format->BitsPerPixel, - false, - vlcPluginsPath, - SystemFlags::VERBOSE_MODE_ENABLED); - player.PlayVideo(); - exitAfterIntroVideo = true; - return; - } - - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); +int Intro::introTime = 50000; +int Intro::appearTime = 2500; +int Intro::showTime = 3500; +int Intro::disapearTime = 2500; + +Intro::Intro(Program *program) : ProgramState(program) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + CoreData &coreData = CoreData::getInstance(); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && + (::Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == false || + CoreData::getInstance().hasIntroVideoFilename() == false)) { + soundRenderer.playMusic(CoreData::getInstance().getIntroMusic()); + } + + const Metrics &metrics = Metrics::getInstance(); + int w = metrics.getVirtualW(); + int h = metrics.getVirtualH(); + timer = 0; + mouseX = 0; + mouseY = 0; + mouse2d = 0; + exitAfterIntroVideo = false; + + Renderer &renderer = Renderer::getInstance(); + // renderer.init3dListMenu(NULL); + renderer.initMenu(NULL); + fade = 0.f; + anim = 0.f; + targetCamera = NULL; + t = 0.f; + + startPosition.x = 5; + ; + startPosition.y = 10; + startPosition.z = 40; + camera.setPosition(startPosition); + + Vec3f startRotation; + startRotation.x = 0; + startRotation.y = 0; + startRotation.z = 0; + + camera.setOrientation(Quaternion(EulerAngles(degToRad(startRotation.x), + degToRad(startRotation.y), + degToRad(startRotation.z)))); + + Intro::introTime = 3000; + Intro::appearTime = 500; + Intro::showTime = 500; + Intro::disapearTime = 500; + int showIntroPics = 0; + int showIntroPicsTime = 0; + bool showIntroPicsRandom = false; + bool showIntroModels = false; + bool showIntroModelsRandom = false; + modelMinAnimSpeed = 0; + modelMaxAnimSpeed = 0; + + XmlTree xmlTree; + string data_path = + getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + xmlTree.load(getGameCustomCoreDataPath(data_path, "data/core/menu/menu.xml"), + Properties::getTagReplacementValues()); + const XmlNode *menuNode = xmlTree.getRootNode(); + + if (menuNode->hasChild("intro") == true) { + const XmlNode *introNode = menuNode->getChild("intro"); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + // camera + const XmlNode *cameraNode = introNode->getChild("camera"); + + // position + const XmlNode *positionNode = cameraNode->getChild("start-position"); + startPosition.x = positionNode->getAttribute("x")->getFloatValue(); + startPosition.y = positionNode->getAttribute("y")->getFloatValue(); + startPosition.z = positionNode->getAttribute("z")->getFloatValue(); + camera.setPosition(startPosition); + + // rotation + const XmlNode *rotationNode = cameraNode->getChild("start-rotation"); + Vec3f startRotation; + startRotation.x = rotationNode->getAttribute("x")->getFloatValue(); + startRotation.y = rotationNode->getAttribute("y")->getFloatValue(); + startRotation.z = rotationNode->getAttribute("z")->getFloatValue(); + camera.setOrientation(Quaternion(EulerAngles(degToRad(startRotation.x), + degToRad(startRotation.y), + degToRad(startRotation.z)))); + + // intro info + const XmlNode *introTimeNode = introNode->getChild("intro-time"); + Intro::introTime = introTimeNode->getAttribute("value")->getIntValue(); + const XmlNode *appearTimeNode = introNode->getChild("appear-time"); + Intro::appearTime = appearTimeNode->getAttribute("value")->getIntValue(); + const XmlNode *showTimeNode = introNode->getChild("show-time"); + Intro::showTime = showTimeNode->getAttribute("value")->getIntValue(); + const XmlNode *disappearTimeNode = introNode->getChild("disappear-time"); + Intro::disapearTime = + disappearTimeNode->getAttribute("value")->getIntValue(); + const XmlNode *showIntroPicturesNode = + introNode->getChild("show-intro-pictures"); + showIntroPics = showIntroPicturesNode->getAttribute("value")->getIntValue(); + showIntroPicsTime = + showIntroPicturesNode->getAttribute("time")->getIntValue(); + showIntroPicsRandom = + showIntroPicturesNode->getAttribute("random")->getBoolValue(); + + const XmlNode *showIntroModelsNode = + introNode->getChild("show-intro-models"); + showIntroModels = + showIntroModelsNode->getAttribute("value")->getBoolValue(); + showIntroModelsRandom = + showIntroModelsNode->getAttribute("random")->getBoolValue(); + modelMinAnimSpeed = + showIntroModelsNode->getAttribute("min-anim-speed")->getFloatValue(); + modelMaxAnimSpeed = + showIntroModelsNode->getAttribute("max-anim-speed")->getFloatValue(); + } + + // load main model + modelIndex = 0; + models.clear(); + if (showIntroModels == true) { + + // getGameCustomCoreDataPath(data_path, "data/core/menu/menu.xml") + string introPath = getGameCustomCoreDataPath(data_path, "") + + "data/core/menu/main_model/intro*.g3d"; + vector introModels; + findAll(introPath, introModels, false, false); + for (int i = 0; i < (int)introModels.size(); ++i) { + string logo = introModels[i]; + Model *model = + renderer.newModel(rsMenu, getGameCustomCoreDataPath(data_path, "") + + "data/core/menu/main_model/" + logo); + if (model) { + models.push_back(model); + // printf("#1 Intro model [%s]\n",model->getFileName().c_str()); + } + } + + if (models.empty() == true) { + introPath = data_path + "data/core/menu/main_model/intro*.g3d"; + // vector introModels; + findAll(introPath, introModels, false, false); + for (int i = 0; i < (int)introModels.size(); ++i) { + string logo = introModels[i]; + Model *model = renderer.newModel( + rsMenu, data_path + "data/core/menu/main_model/" + logo); + if (model) { + models.push_back(model); + // printf("#2 Intro model [%s]\n",model->getFileName().c_str()); + } + } + } + + if (showIntroModelsRandom == true) { + std::vector modelList; + + // unsigned int seed = time(NULL); + Chrono seed(true); + srand((unsigned int)seed.getCurTicks()); + int failedLookups = 0; + std::map usedIndex; + for (; modelList.size() < models.size();) { + int index = rand() % models.size(); + if (usedIndex.find(index) != usedIndex.end()) { + failedLookups++; + srand((unsigned int)seed.getCurTicks() / failedLookups); + continue; + } + // printf("picIndex = %d list count = + // %d\n",picIndex,coreData.getMiscTextureList().size()); + modelList.push_back(models[index]); + usedIndex[index] = true; + srand((unsigned int)seed.getCurTicks() / + (unsigned int)modelList.size()); + } + models = modelList; + } + } + + int displayItemNumber = 1; + int appear = Intro::appearTime; + int disappear = + Intro::showTime + Intro::appearTime + (Intro::disapearTime * 2); + + const unsigned int maxIntroLines = 100; + Lang &lang = Lang::getInstance(); + for (unsigned int i = 1; i < maxIntroLines; ++i) { + string introTagName = "IntroText" + intToStr(i); + string introTagTextureName = "IntroTexture" + intToStr(i); + + if (lang.hasString(introTagName, "", true) == true || + lang.hasString(introTagTextureName, "", true) == true) { + string lineText = ""; + + if (lang.hasString(introTagName, "", true) == true) { + lineText = lang.getString(introTagName, "", true); + } + + string showStartTime = "IntroStartMilliseconds" + intToStr(i); + + int displayTime = appear; + if (lang.hasString(showStartTime, "", true) == true) { + displayTime = strToInt(lang.getString(showStartTime, "", true)); + } else { + if (i == 1) { + displayTime = appear; + } else if (i == 2) { + displayTime = disappear; + } else if (i >= 3) { + displayTime = disappear * (++displayItemNumber); + } + } + + // Is this a texture? + if (lang.hasString(introTagName, "", true) == false && + lang.hasString(introTagTextureName, "", true) == true) { + + string introTagTextureWidthName = "IntroTextureWidth" + intToStr(i); + string introTagTextureHeightName = "IntroTextureHeight" + intToStr(i); + + lineText = lang.getString(introTagTextureName, "", true); + Texture2D *logoTexture = renderer.newTexture2D(rsGlobal); + if (logoTexture) { + logoTexture->setMipmap(false); + logoTexture->getPixmap()->load(lineText); + + renderer.initTexture(rsGlobal, logoTexture); + } + + int textureWidth = 256; + if (logoTexture != NULL) { + textureWidth = logoTexture->getTextureWidth(); + } + if (lang.hasString(introTagTextureWidthName, "", true) == true) { + textureWidth = + strToInt(lang.getString(introTagTextureWidthName, "", true)); + } + + int textureHeight = 128; + if (logoTexture != NULL) { + textureHeight = logoTexture->getTextureHeight(); + } + if (lang.hasString(introTagTextureHeightName, "", true) == true) { + textureHeight = + strToInt(lang.getString(introTagTextureHeightName, "", true)); + } + + texts.push_back(new IntroText( + logoTexture, + Vec2i(w / 2 - (textureWidth / 2), h / 2 - (textureHeight / 2)), + Vec2i(textureWidth, textureHeight), displayTime)); + } + // This is a line of text + else { + string introTagTextXName = "IntroTextX" + intToStr(i); + string introTagTextYName = "IntroTextY" + intToStr(i); + string introTagTextFontTypeName = "IntroTextFontType" + intToStr(i); + + int textX = -1; + if (lang.hasString(introTagTextXName, "", true) == true) { + string value = lang.getString(introTagTextXName, "", true); + if (value.length() > 0 && (value[0] == '+' || value[0] == '-')) { + textX = w / 2 + strToInt(value); + } else { + textX = strToInt(value); + } + } + + int textY = -1; + if (lang.hasString(introTagTextYName, "", true) == true) { + string value = lang.getString(introTagTextYName, "", true); + if (value.length() > 0 && (value[0] == '+' || value[0] == '-')) { + textY = h / 2 + strToInt(value); + } else { + textY = strToInt(value); + } + } + + Font2D *font = coreData.getMenuFontVeryBig(); + Font3D *font3d = coreData.getMenuFontVeryBig3D(); + + if (lang.hasString(introTagTextFontTypeName, "", true) == true) { + string value = lang.getString(introTagTextFontTypeName, "", true); + if (value == "displaynormal") { + font = coreData.getDisplayFont(); + font3d = coreData.getDisplayFont3D(); + } else if (value == "displaysmall") { + font = coreData.getDisplayFontSmall(); + font3d = coreData.getDisplayFontSmall3D(); + } else if (value == "menunormal") { + font = coreData.getMenuFontNormal(); + font3d = coreData.getMenuFontNormal3D(); + } else if (value == "menubig") { + font = coreData.getMenuFontBig(); + font3d = coreData.getMenuFontBig3D(); + } else if (value == "menuverybig") { + font = coreData.getMenuFontVeryBig(); + font3d = coreData.getMenuFontVeryBig3D(); + } else if (value == "consolenormal") { + font = coreData.getConsoleFont(); + font3d = coreData.getConsoleFont3D(); + } + } + texts.push_back(new IntroText(lineText, Vec2i(textX, textY), + displayTime, font, font3d)); + } + } else { + break; + } + } + modelShowTime = disappear * (displayItemNumber); + if (lang.hasString("IntroModelStartMilliseconds", "", true) == true) { + modelShowTime = + strToInt(lang.getString("IntroModelStartMilliseconds", "", true)); + } else { + modelShowTime = disappear * (displayItemNumber); + } + + /* + string lineText = "Based on award-winning classic Glest"; + texts.push_back(new Text(lineText, Vec2i(-1, -1), appear, + coreData.getMenuFontVeryBig(),coreData.getMenuFontVeryBig3D())); lineText = + "the MegaGlest Team presents"; texts.push_back(new Text(lineText, Vec2i(-1, + -1), disappear, + coreData.getMenuFontVeryBig(),coreData.getMenuFontVeryBig3D())); lineText = + "a libre software real-time strategy game"; texts.push_back(new + Text(lineText, Vec2i(-1, -1), disappear *(++displayItemNumber), + coreData.getMenuFontVeryBig(),coreData.getMenuFontVeryBig3D())); + + texts.push_back(new Text(coreData.getLogoTexture(), Vec2i(w/2-128, + h/2-64), Vec2i(256, 128), disappear *(++displayItemNumber))); + texts.push_back(new Text(glestVersionString, Vec2i(w/2+45, h/2-45), + disappear *(displayItemNumber++), + coreData.getMenuFontNormal(),coreData.getMenuFontNormal3D())); lineText = + "www.megaglest.org"; + //texts.push_back(new Text(lineText, Vec2i(-1, -1), disappear + *(displayItemNumber++), + coreData.getMenuFontVeryBig(),coreData.getMenuFontVeryBig3D())); + texts.push_back(new Text(lineText, Vec2i(-1, h/2-45-18), disappear + *(displayItemNumber-1), + coreData.getMenuFontVeryBig(),coreData.getMenuFontVeryBig3D())); + */ + + if (showIntroPics > 0 && coreData.getMiscTextureList().size() > 0) { + const int showMiscTime = showIntroPicsTime; + + std::vector intoTexList; + if (showIntroPicsRandom == true) { + // unsigned int seed = time(NULL); + Chrono seed(true); + srand((unsigned int)seed.getCurTicks()); + int failedLookups = 0; + std::map usedIndex; + for (; (int)intoTexList.size() < showIntroPics;) { + int picIndex = rand() % coreData.getMiscTextureList().size(); + if (usedIndex.find(picIndex) != usedIndex.end()) { + failedLookups++; + srand((unsigned int)seed.getCurTicks() / failedLookups); + + if (failedLookups > 10000) { + for (unsigned int i = 0; i < coreData.getMiscTextureList().size(); + ++i) { + if (usedIndex.find(i) == usedIndex.end()) { + picIndex = i; + break; + } + } + } else { + continue; + } + } + // printf("picIndex = %d list count = + // %d\n",picIndex,coreData.getMiscTextureList().size()); + intoTexList.push_back(coreData.getMiscTextureList()[picIndex]); + usedIndex[picIndex] = true; + srand((unsigned int)seed.getCurTicks() / + (unsigned int)intoTexList.size()); + } + } else { + for (unsigned int i = 0; + i < (unsigned int)coreData.getMiscTextureList().size() && + i < (unsigned int)showIntroPics; + ++i) { + Texture2D *tex = coreData.getMiscTextureList()[i]; + intoTexList.push_back(tex); + } + } + + for (unsigned int i = 0; i < intoTexList.size(); ++i) { + Texture2D *tex = intoTexList[i]; + // printf("tex # %d [%s]\n",i,tex->getPath().c_str()); + + Vec2i texPlacement; + if (i == 0 || i % 9 == 0) { + texPlacement = Vec2i(1, h - tex->getTextureHeight()); + } else if (i == 1 || i % 9 == 1) { + texPlacement = Vec2i(1, 1); + } else if (i == 2 || i % 9 == 2) { + texPlacement = Vec2i(w - tex->getTextureWidth(), 1); + } else if (i == 3 || i % 9 == 3) { + texPlacement = + Vec2i(w - tex->getTextureWidth(), h - tex->getTextureHeight()); + } else if (i == 4 || i % 9 == 4) { + texPlacement = Vec2i(w / 2 - tex->getTextureWidth() / 2, + h - tex->getTextureHeight()); + } else if (i == 5 || i % 9 == 5) { + texPlacement = Vec2i(w / 2 - tex->getTextureWidth() / 2, 1); + } else if (i == 6 || i % 9 == 6) { + texPlacement = Vec2i(1, (h / 2) - (tex->getTextureHeight() / 2)); + } else if (i == 7 || i % 9 == 7) { + texPlacement = Vec2i(w - tex->getTextureWidth(), + (h / 2) - (tex->getTextureHeight() / 2)); + } + + int textureStartTime = disappear * displayItemNumber; + if (lang.hasString("IntroTextureStartMilliseconds", "", true) == true) { + textureStartTime = + strToInt(lang.getString("IntroTextureStartMilliseconds", "", true)); + } + + texts.push_back( + new IntroText(tex, texPlacement, + Vec2i(tex->getTextureWidth(), tex->getTextureHeight()), + textureStartTime + (showMiscTime * (i + 1)))); + } + } + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + renderer.swapBuffers(); + } + + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && + ::Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == true && + CoreData::getInstance().hasIntroVideoFilename() == true) { + string introVideoFile = CoreData::getInstance().getIntroVideoFilename(); + string introVideoFileFallback = + CoreData::getInstance().getIntroVideoFilenameFallback(); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Intro Video [%s] [%s]\n", introVideoFile.c_str(), + introVideoFileFallback.c_str()); + + Context *c = GraphicsInterface::getInstance().getCurrentContext(); + PlatformContextGl *glCtx = + static_cast(c)->getPlatformContextGlPtr(); + SDL_Window *window = glCtx->getScreenWindow(); + SDL_Surface *screen = glCtx->getScreenSurface(); + + string vlcPluginsPath = + Config::getInstance().getString("VideoPlayerPluginsPath", ""); + // printf("screen->w = %d screen->h = %d screen->format->BitsPerPixel = + // %d\n",screen->w,screen->h,screen->format->BitsPerPixel); + ::Shared::Graphics::VideoPlayer player( + &Renderer::getInstance(), introVideoFile, introVideoFileFallback, + window, 0, 0, screen->w, screen->h, screen->format->BitsPerPixel, false, + vlcPluginsPath, SystemFlags::VERBOSE_MODE_ENABLED); + player.PlayVideo(); + exitAfterIntroVideo = true; + return; + } + + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); } Intro::~Intro() { - deleteValues(texts.begin(),texts.end()); + deleteValues(texts.begin(), texts.end()); - //deleteValues(introTextureList.begin(),introTextureList.end()); -// if(test) { -// glmDelete(test); -// } + // deleteValues(introTextureList.begin(),introTextureList.end()); + // if(test) { + // glmDelete(test); + // } - //Shared::Graphics::md5::cleanupMD5OpenGL(); + // Shared::Graphics::md5::cleanupMD5OpenGL(); } void Intro::update() { - if(exitAfterIntroVideo == true) { - mouseUpLeft(0, 0); - //cleanup(); - return; - } - timer++; - if(timer > introTime * GameConstants::updateFps / 1000){ - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - cleanup(); - return; - } - - if(Config::getInstance().getBool("AutoTest")){ - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - AutoTest::getInstance().updateIntro(program); - return; - } - - mouse2d= (mouse2d+1) % Renderer::maxMouse2dAnim; - - if(targetCamera != NULL) { - t+= ((0.01f+(1.f-t)/10.f)/20.f)*(60.f/GameConstants::updateFps); - - //interpolate position - camera.setPosition(lastCamera.getPosition().lerp(t, targetCamera->getPosition())); - - //interpolate orientation - Quaternion q= lastCamera.getOrientation().lerp(t, targetCamera->getOrientation()); - camera.setOrientation(q); - - if(t>=1.f){ - targetCamera= NULL; - t= 0.f; - } - } - - //fade - if(fade <= 1.f) { - fade += 0.6f / GameConstants::updateFps; - if(fade > 1.f){ - fade = 1.f; - } - } - - //animation - //const float minSpeed = 0.015f; - //const float minSpeed = 0.010f; - //const float maxSpeed = 0.6f; - const float minSpeed = modelMinAnimSpeed; - const float maxSpeed = modelMaxAnimSpeed; - anim += (maxSpeed / GameConstants::updateFps) / 5 + random.randRange(minSpeed, max(minSpeed + 0.0001f, (maxSpeed / GameConstants::updateFps) / 5.f)); - if(anim > 1.f) { - anim = 0.f; - } - - //animTimer.update(); + if (exitAfterIntroVideo == true) { + mouseUpLeft(0, 0); + // cleanup(); + return; + } + timer++; + if (timer > introTime * GameConstants::updateFps / 1000) { + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + cleanup(); + return; + } + + if (Config::getInstance().getBool("AutoTest")) { + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + AutoTest::getInstance().updateIntro(program); + return; + } + + mouse2d = (mouse2d + 1) % Renderer::maxMouse2dAnim; + + if (targetCamera != NULL) { + t += + ((0.01f + (1.f - t) / 10.f) / 20.f) * (60.f / GameConstants::updateFps); + + // interpolate position + camera.setPosition( + lastCamera.getPosition().lerp(t, targetCamera->getPosition())); + + // interpolate orientation + Quaternion q = + lastCamera.getOrientation().lerp(t, targetCamera->getOrientation()); + camera.setOrientation(q); + + if (t >= 1.f) { + targetCamera = NULL; + t = 0.f; + } + } + + // fade + if (fade <= 1.f) { + fade += 0.6f / GameConstants::updateFps; + if (fade > 1.f) { + fade = 1.f; + } + } + + // animation + // const float minSpeed = 0.015f; + // const float minSpeed = 0.010f; + // const float maxSpeed = 0.6f; + const float minSpeed = modelMinAnimSpeed; + const float maxSpeed = modelMaxAnimSpeed; + anim += (maxSpeed / GameConstants::updateFps) / 5 + + random.randRange(minSpeed, + max(minSpeed + 0.0001f, + (maxSpeed / GameConstants::updateFps) / 5.f)); + if (anim > 1.f) { + anim = 0.f; + } + + // animTimer.update(); } void Intro::renderModelBackground() { - // Black background - glClearColor(0, 0, 0, 1); - - if(models.empty() == false) { - int difTime= 1000 * timer / GameConstants::updateFps - modelShowTime; - int totalModelShowTime = Intro::introTime - modelShowTime; - int individualModelShowTime = totalModelShowTime / (int)models.size(); - - //printf("difTime = %d individualModelShowTime = %d modelIndex = %d\n",difTime,individualModelShowTime,modelIndex); - - //int difTime= 1; - if(difTime > 0) { - if(difTime > ((modelIndex+1) * individualModelShowTime)) { - //int oldmodelIndex = modelIndex; - if(modelIndex + 1 < (int)models.size()) { - modelIndex++; - - //position - //nextCamera.setPosition(camera.getPosition()); -// nextCamera.setPosition(Vec3f(84,-9,11)); -// -// //rotation -// //Vec3f startRotation(0,12,0); -// Vec3f startRotation(0,-80,0); -// nextCamera.setOrientation(Quaternion(EulerAngles( -// degToRad(startRotation.x), -// degToRad(startRotation.y), -// degToRad(startRotation.z)))); -// -// this->targetCamera = &nextCamera; -// this->lastCamera= camera; -// this->t= 0.f; - - } - //printf("oldmodelIndex = %d, modelIndex = %d\n",oldmodelIndex,modelIndex); - } - Renderer &renderer= Renderer::getInstance(); - vector characterModels; - characterModels.push_back(NULL); - characterModels.push_back(NULL); - characterModels.push_back(models[modelIndex]); - const Vec3f characterPosition = startPosition; - renderer.renderMenuBackground(&camera, fade, NULL, characterModels,characterPosition,anim); - } - } + // Black background + glClearColor(0, 0, 0, 1); + + if (models.empty() == false) { + int difTime = 1000 * timer / GameConstants::updateFps - modelShowTime; + int totalModelShowTime = Intro::introTime - modelShowTime; + int individualModelShowTime = totalModelShowTime / (int)models.size(); + + // printf("difTime = %d individualModelShowTime = %d modelIndex = + // %d\n",difTime,individualModelShowTime,modelIndex); + + // int difTime= 1; + if (difTime > 0) { + if (difTime > ((modelIndex + 1) * individualModelShowTime)) { + // int oldmodelIndex = modelIndex; + if (modelIndex + 1 < (int)models.size()) { + modelIndex++; + + // position + // nextCamera.setPosition(camera.getPosition()); + // nextCamera.setPosition(Vec3f(84,-9,11)); + // + // //rotation + // //Vec3f startRotation(0,12,0); + // Vec3f startRotation(0,-80,0); + // nextCamera.setOrientation(Quaternion(EulerAngles( + // degToRad(startRotation.x), + // degToRad(startRotation.y), + // degToRad(startRotation.z)))); + // + // this->targetCamera = + //&nextCamera; this->lastCamera= camera; + //this->t= 0.f; + } + // printf("oldmodelIndex = %d, modelIndex = + // %d\n",oldmodelIndex,modelIndex); + } + Renderer &renderer = Renderer::getInstance(); + vector characterModels; + characterModels.push_back(NULL); + characterModels.push_back(NULL); + characterModels.push_back(models[modelIndex]); + const Vec3f characterPosition = startPosition; + renderer.renderMenuBackground(&camera, fade, NULL, characterModels, + characterPosition, anim); + } + } } void Intro::render() { - Renderer &renderer= Renderer::getInstance(); - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - return; - } - - canRender(); - incrementFps(); - - renderer.clearBuffers(); - renderer.reset3dMenu(); - - renderer.clearZBuffer(); - renderer.loadCameraMatrix(&camera); - - renderModelBackground(); - renderer.renderParticleManager(rsMenu); - - renderer.reset2d(); - - for(int i = 0; i < (int)texts.size(); ++i) { - IntroText *text= texts[i]; - - int difTime= 1000 * timer / GameConstants::updateFps - text->getTime(); - - if(difTime > 0 && difTime < appearTime + showTime + disapearTime) { - float alpha= 1.f; - if(difTime > 0 && difTime < appearTime) { - //apearing - alpha= static_cast(difTime) / appearTime; - } - else if(difTime > 0 && difTime < appearTime + showTime + disapearTime) { - //disappearing - alpha= 1.f- static_cast(difTime - appearTime - showTime) / disapearTime; - } - - if(text->getText().empty() == false) { - int renderX = text->getPos().x; - int renderY = text->getPos().y; - - if(Renderer::renderText3DEnabled) { - if(renderX < 0) { - const Metrics &metrics= Metrics::getInstance(); - int w= metrics.getVirtualW(); - renderX = (w / 2) - (text->getFont3D()->getMetrics()->getTextWidth(text->getText()) / 2); - } - if(renderY < 0) { - const Metrics &metrics= Metrics::getInstance(); - int h= metrics.getVirtualH(); - renderY = (h / 2) + (text->getFont3D()->getMetrics()->getHeight(text->getText()) / 2); - } - - renderer.renderText3D( - text->getText(), text->getFont3D(), alpha, - renderX, renderY, false); - } - else { - if(renderX < 0) { - const Metrics &metrics= Metrics::getInstance(); - int w= metrics.getVirtualW(); - renderX = (w / 2); - } - if(renderY < 0) { - const Metrics &metrics= Metrics::getInstance(); - int h= metrics.getVirtualH(); - renderY = (h / 2); - } - - renderer.renderText( - text->getText(), text->getFont(), alpha, - renderX, renderY, true); - } - } - - if(text->getTexture()!=NULL){ - renderer.renderTextureQuad( - text->getPos().x, text->getPos().y, - text->getSize().x, text->getSize().y, - text->getTexture(), alpha); - } - } - } - - if(program != NULL) program->renderProgramMsgBox(); - - if(this->forceMouseRender == true) renderer.renderMouse2d(mouseX, mouseY, mouse2d, 0.f); - - bool showIntroTiming = Config::getInstance().getBool("ShowIntroTiming","false"); - if(showIntroTiming == true && Intro::introTime > 0) { - CoreData &coreData= CoreData::getInstance(); - int difTime= 1000 * timer / GameConstants::updateFps; - string timingText = intToStr(difTime) + " / " + intToStr(Intro::introTime); - - if(Renderer::renderText3DEnabled) { - //const Metrics &metrics= Metrics::getInstance(); - //int w= metrics.getVirtualW(); - //int h= metrics.getVirtualH(); - - renderer.renderText3D( - timingText, coreData.getMenuFontVeryBig3D(), 1, - 10, 20, false); - } - else { - //const Metrics &metrics= Metrics::getInstance(); - //int w= metrics.getVirtualW(); - //int h= metrics.getVirtualH(); - - renderer.renderText( - timingText, coreData.getMenuFontVeryBig(), 1, - 10, 20, false); - } - } - - renderer.renderFPSWhenEnabled(lastFps); - renderer.swapBuffers(); + Renderer &renderer = Renderer::getInstance(); + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + return; + } + + canRender(); + incrementFps(); + + renderer.clearBuffers(); + renderer.reset3dMenu(); + + renderer.clearZBuffer(); + renderer.loadCameraMatrix(&camera); + + renderModelBackground(); + renderer.renderParticleManager(rsMenu); + + renderer.reset2d(); + + for (int i = 0; i < (int)texts.size(); ++i) { + IntroText *text = texts[i]; + + int difTime = 1000 * timer / GameConstants::updateFps - text->getTime(); + + if (difTime > 0 && difTime < appearTime + showTime + disapearTime) { + float alpha = 1.f; + if (difTime > 0 && difTime < appearTime) { + // apearing + alpha = static_cast(difTime) / appearTime; + } else if (difTime > 0 && + difTime < appearTime + showTime + disapearTime) { + // disappearing + alpha = 1.f - static_cast(difTime - appearTime - showTime) / + disapearTime; + } + + if (text->getText().empty() == false) { + int renderX = text->getPos().x; + int renderY = text->getPos().y; + + if (Renderer::renderText3DEnabled) { + if (renderX < 0) { + const Metrics &metrics = Metrics::getInstance(); + int w = metrics.getVirtualW(); + renderX = (w / 2) - (text->getFont3D()->getMetrics()->getTextWidth( + text->getText()) / + 2); + } + if (renderY < 0) { + const Metrics &metrics = Metrics::getInstance(); + int h = metrics.getVirtualH(); + renderY = + (h / 2) + + (text->getFont3D()->getMetrics()->getHeight(text->getText()) / + 2); + } + + renderer.renderText3D(text->getText(), text->getFont3D(), alpha, + renderX, renderY, false); + } else { + if (renderX < 0) { + const Metrics &metrics = Metrics::getInstance(); + int w = metrics.getVirtualW(); + renderX = (w / 2); + } + if (renderY < 0) { + const Metrics &metrics = Metrics::getInstance(); + int h = metrics.getVirtualH(); + renderY = (h / 2); + } + + renderer.renderText(text->getText(), text->getFont(), alpha, renderX, + renderY, true); + } + } + + if (text->getTexture() != NULL) { + renderer.renderTextureQuad(text->getPos().x, text->getPos().y, + text->getSize().x, text->getSize().y, + text->getTexture(), alpha); + } + } + } + + if (program != NULL) + program->renderProgramMsgBox(); + + if (this->forceMouseRender == true) + renderer.renderMouse2d(mouseX, mouseY, mouse2d, 0.f); + + bool showIntroTiming = + Config::getInstance().getBool("ShowIntroTiming", "false"); + if (showIntroTiming == true && Intro::introTime > 0) { + CoreData &coreData = CoreData::getInstance(); + int difTime = 1000 * timer / GameConstants::updateFps; + string timingText = intToStr(difTime) + " / " + intToStr(Intro::introTime); + + if (Renderer::renderText3DEnabled) { + // const Metrics &metrics= Metrics::getInstance(); + // int w= metrics.getVirtualW(); + // int h= metrics.getVirtualH(); + + renderer.renderText3D(timingText, coreData.getMenuFontVeryBig3D(), 1, 10, + 20, false); + } else { + // const Metrics &metrics= Metrics::getInstance(); + // int w= metrics.getVirtualW(); + // int h= metrics.getVirtualH(); + + renderer.renderText(timingText, coreData.getMenuFontVeryBig(), 1, 10, 20, + false); + } + } + + renderer.renderFPSWhenEnabled(lastFps); + renderer.swapBuffers(); } void Intro::keyDown(SDL_KeyboardEvent key) { - SDL_keysym keystate = key.keysym; - //printf("keystate.mod = %d key = unicode[%d] regular[%d] lalt [%d] ralt [%d] alt [%d]\n",keystate.mod,key.keysym.unicode,key.keysym.sym,(keystate.mod & KMOD_LALT),(keystate.mod & KMOD_RALT),(keystate.mod & KMOD_ALT)); - - if(keystate.mod & (KMOD_LALT | KMOD_RALT)) { - //printf("ALT KEY #1\n"); - - if(isKeyPressed(SDLK_RETURN,key) == true || - isKeyPressed(SDLK_RALT,key) == true || - isKeyPressed(SDLK_LALT,key) == true) { - return; - } - } - - //printf("Exiting intro\n"); - mouseUpLeft(0, 0); + SDL_keysym keystate = key.keysym; + // printf("keystate.mod = %d key = unicode[%d] regular[%d] lalt [%d] ralt [%d] + // alt [%d]\n",keystate.mod,key.keysym.unicode,key.keysym.sym,(keystate.mod & + // KMOD_LALT),(keystate.mod & KMOD_RALT),(keystate.mod & KMOD_ALT)); + + if (keystate.mod & (KMOD_LALT | KMOD_RALT)) { + // printf("ALT KEY #1\n"); + + if (isKeyPressed(SDLK_RETURN, key) == true || + isKeyPressed(SDLK_RALT, key) == true || + isKeyPressed(SDLK_LALT, key) == true) { + return; + } + } + + // printf("Exiting intro\n"); + mouseUpLeft(0, 0); } void Intro::mouseUpLeft(int x, int y) { - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - soundRenderer.stopMusic(CoreData::getInstance().getIntroMusic()); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + soundRenderer.stopMusic(CoreData::getInstance().getIntroMusic()); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); - if(CoreData::getInstance().hasMainMenuVideoFilename() == false) { - soundRenderer.playMusic(CoreData::getInstance().getMenuMusic()); - } + if (CoreData::getInstance().hasMainMenuVideoFilename() == false) { + soundRenderer.playMusic(CoreData::getInstance().getMenuMusic()); + } - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); - cleanup(); + cleanup(); } void Intro::cleanup() { - Renderer::getInstance().endMenu(); + Renderer::getInstance().endMenu(); - program->setState(new MainMenu(program)); + program->setState(new MainMenu(program)); } void Intro::mouseMove(int x, int y, const MouseState *ms) { - mouseX = x; - mouseY = y; + mouseX = x; + mouseY = y; } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/main/intro.h b/source/glest_game/main/intro.h index 50b4abbea..bd4641831 100644 --- a/source/glest_game/main/intro.h +++ b/source/glest_game/main/intro.h @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -14,35 +14,36 @@ #include -#include "program.h" -#include "font.h" -#include "vec.h" -#include "texture.h" #include "camera.h" +#include "font.h" #include "model.h" +#include "program.h" #include "randomgen.h" +#include "texture.h" +#include "vec.h" #include "leak_dumper.h" using std::vector; -using Shared::Graphics::Vec2i; -using Shared::Graphics::Vec2f; -using Shared::Graphics::Vec3f; using Shared::Graphics::Font2D; using Shared::Graphics::Font3D; using Shared::Graphics::Texture2D; +using Shared::Graphics::Vec2f; +using Shared::Graphics::Vec2i; +using Shared::Graphics::Vec3f; using Shared::Graphics::Camera; using Shared::Graphics::Model; using Shared::Util::RandomGen; -//class GLMmodel; +// class GLMmodel; -//namespace Shared{ namespace Graphics { namespace md5 { -//class Md5Object; -//}}} +// namespace Shared{ namespace Graphics { namespace md5 { +// class Md5Object; +// }}} -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class Text @@ -50,79 +51,82 @@ namespace Glest{ namespace Game{ class IntroText { private: - string text; - Vec2i pos; - Vec2i size; - int time; - Font2D *font; - Font3D *font3D; - const Texture2D *texture; + string text; + Vec2i pos; + Vec2i size; + int time; + Font2D *font; + Font3D *font3D; + const Texture2D *texture; public: - IntroText(const string &text, const Vec2i &pos, int time, Font2D *font, Font3D *font3D); - IntroText(const Texture2D *texture, const Vec2i &pos, const Vec2i &size, int time); - - const string &getText() const {return text;} - Font2D *getFont() {return font;} - Font3D *getFont3D() {return font3D;} - const Vec2i &getPos() const {return pos;} - const Vec2i &getSize() const {return size;} - int getTime() const {return time;} - const Texture2D *getTexture() const {return texture;} + IntroText(const string &text, const Vec2i &pos, int time, Font2D *font, + Font3D *font3D); + IntroText(const Texture2D *texture, const Vec2i &pos, const Vec2i &size, + int time); + + const string &getText() const { return text; } + Font2D *getFont() { return font; } + Font3D *getFont3D() { return font3D; } + const Vec2i &getPos() const { return pos; } + const Vec2i &getSize() const { return size; } + int getTime() const { return time; } + const Texture2D *getTexture() const { return texture; } }; // ===================================================== -// class Intro +// class Intro // /// ProgramState representing the intro // ===================================================== -class Intro: public ProgramState { +class Intro : public ProgramState { private: - static int introTime; - static int appearTime; - static int showTime; - static int disapearTime; + static int introTime; + static int appearTime; + static int showTime; + static int disapearTime; private: - vector texts; - int timer; - int mouse2d; - - //Model *mainModel; - int modelIndex; - float modelMinAnimSpeed; - float modelMaxAnimSpeed; - vector models; - Camera nextCamera; - Camera camera; - Camera lastCamera; - const Camera *targetCamera; - float t; - RandomGen random; - float anim; - float fade; - Vec3f startPosition; - int modelShowTime; - - //GLMmodel* test; - //Shared::Graphics::md5::Md5Object *md5Test; - - bool exitAfterIntroVideo; - void cleanup(); - void renderModelBackground(); + vector texts; + int timer; + int mouse2d; + + // Model *mainModel; + int modelIndex; + float modelMinAnimSpeed; + float modelMaxAnimSpeed; + vector models; + Camera nextCamera; + Camera camera; + Camera lastCamera; + const Camera *targetCamera; + float t; + RandomGen random; + float anim; + float fade; + Vec3f startPosition; + int modelShowTime; + + // GLMmodel* test; + // Shared::Graphics::md5::Md5Object *md5Test; + + bool exitAfterIntroVideo; + void cleanup(); + void renderModelBackground(); public: - explicit Intro(Program *program); - virtual ~Intro(); - - virtual void update(); - virtual void render(); - virtual void keyDown(SDL_KeyboardEvent key); - virtual void mouseUpLeft(int x, int y); - void mouseMove(int x, int y, const MouseState *ms); + explicit Intro(Program *program); + virtual ~Intro(); + + virtual void update(); + virtual void render(); + virtual void keyDown(SDL_KeyboardEvent key); + virtual void mouseUpLeft(int x, int y); + void mouseMove(int x, int y, const MouseState *ms); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/main/main.cpp b/source/glest_game/main/main.cpp index bc9fd177b..7738c3a28 100644 --- a/source/glest_game/main/main.cpp +++ b/source/glest_game/main/main.cpp @@ -9,59 +9,59 @@ // ============================================================== #ifdef WIN32 - #include - #include - #include - #include +#include +#include +#include +#include #endif #ifdef HAVE_GOOGLE_BREAKPAD #include "handler/exception_handler.h" #endif -#include "math_wrapper.h" #include "main.h" +#include "math_wrapper.h" -#include #include +#include - -#include "steamshim_child.h" -#include "steam.h" +#include "ImageReaders.h" +#include "config.h" #include "game.h" +#include "game_util.h" #include "main_menu.h" -#include "program.h" -#include "config.h" #include "metrics.h" -#include "game_util.h" -#include "platform_util.h" -#include "platform_main.h" #include "network_interface.h" -#include "ImageReaders.h" +#include "platform_main.h" +#include "platform_util.h" +#include "program.h" #include "renderer.h" #include "simple_threads.h" -//#include -#include "font.h" -#include -#include "menu_state_masterserver.h" -#include "checksum.h" -#include -#include "sound_renderer.h" -#include "font_gl.h" +#include "steam.h" +#include "steamshim_child.h" +// #include #include "FileReader.h" +#include "auto_test.h" #include "cache_manager.h" -#include +#include "checksum.h" +#include "common_scoped_ptr.h" #include "core_data.h" +#include "font.h" +#include "font_gl.h" #include "font_text.h" -#include -#include "string_utils.h" -#include "auto_test.h" -#include "lua_script.h" #include "interpolation.h" -#include "common_scoped_ptr.h" +#include "lua_script.h" +#include "menu_state_masterserver.h" +#include "sound_renderer.h" +#include "string_utils.h" +#include +#include +#include +#include // To handle signal catching -#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__FreeBSD__) && !defined(BSD) +#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__FreeBSD__) && \ + !defined(BSD) #include #endif @@ -73,19 +73,19 @@ #endif #ifndef WIN32 - #include +#include - #define stricmp strcasecmp - #define strnicmp strncasecmp - #define _strnicmp strncasecmp +#define stricmp strcasecmp +#define strnicmp strncasecmp +#define _strnicmp strncasecmp #endif -#include -#include "network_message.h" -#include "network_protocol.h" #include "conversion.h" #include "gen_uuid.h" -//#include "intro.h" +#include "network_message.h" +#include "network_protocol.h" +#include +// #include "intro.h" #include "leak_dumper.h" #if defined(WIN32) @@ -114,23 +114,24 @@ using namespace Shared; * @namespace Game * Namespace used for game related code. */ -namespace Glest { namespace Game { +namespace Glest { +namespace Game { -static string tempDataLocation = getUserHome(); -static string mg_app_name = ""; -static string mailStringSupport = ""; -static bool sdl_quitCalled = false; +static string tempDataLocation = getUserHome(); +static string mg_app_name = ""; +static string mailStringSupport = ""; +static bool sdl_quitCalled = false; -static bool disableheadless_console = false; -static bool disableBacktrace = false; -static bool gameInitialized = false; +static bool disableheadless_console = false; +static bool disableBacktrace = false; +static bool gameInitialized = false; -static Program *mainProgram = NULL; -static FileCRCPreCacheThread *preCacheThread = NULL; +static Program *mainProgram = NULL; +static FileCRCPreCacheThread *preCacheThread = NULL; #ifdef WIN32 -static string runtimeErrorMsg = ""; +static string runtimeErrorMsg = ""; // keeps in scope for duration of the application -//SocketManager *winSockManager = NULL; +// SocketManager *winSockManager = NULL; #endif @@ -138,200 +139,241 @@ static string runtimeErrorMsg = ""; auto_ptr errorHandlerPtr; #endif -class NavtiveLanguageNameListCacheGenerator : public SimpleTaskCallbackInterface { - virtual void simpleTask(BaseThread *callingThread,void *userdata) { - Lang &lang = Lang::getInstance(); - lang.getDiscoveredLanguageList(true); - } +class NavtiveLanguageNameListCacheGenerator + : public SimpleTaskCallbackInterface { + virtual void simpleTask(BaseThread *callingThread, void *userdata) { + Lang &lang = Lang::getInstance(); + lang.getDiscoveredLanguageList(true); + } }; // ===================================================== // class ExceptionHandler // ===================================================== -class ExceptionHandler: public PlatformExceptionHandler{ +class ExceptionHandler : public PlatformExceptionHandler { public: - #if defined(__WIN32__) && !defined(__GNUC__) - virtual void handle(LPEXCEPTION_POINTERS pointers); + virtual void handle(LPEXCEPTION_POINTERS pointers); #endif - virtual void handle(); + virtual void handle(); - static void logError(const char *msg, bool confirmToConsole); - static void handleRuntimeError(const megaglest_runtime_error &ex); - static void handleRuntimeError(const char *msg, bool getStackTraceString); - static int DisplayMessage(const char *msg, bool exitApp); + static void logError(const char *msg, bool confirmToConsole); + static void handleRuntimeError(const megaglest_runtime_error &ex); + static void handleRuntimeError(const char *msg, bool getStackTraceString); + static int DisplayMessage(const char *msg, bool exitApp); }; void cleanupCRCThread() { - if(preCacheThread != NULL) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - const double MAX_THREAD_WAIT = 60; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("START - shutting down crc threads\n"); - time_t elapsed = time(NULL); - preCacheThread->signalQuit(); - for(;preCacheThread->canShutdown(false) == false && - difftime((long int)time(NULL),elapsed) <= MAX_THREAD_WAIT;) { - } - if(difftime((long int)time(NULL),elapsed) <= MAX_THREAD_WAIT) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("B - shutting down crc threads\n"); - - for(;preCacheThread->shutdownAndWait() == false && - difftime((long int)time(NULL),elapsed) <= MAX_THREAD_WAIT;) { - } - if(preCacheThread->getRunningStatus() == false) { - delete preCacheThread; - preCacheThread=NULL; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("C - shutting down crc threads\n"); - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - } - else { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("D - shutting down crc threads\n"); - - if(preCacheThread->canShutdown(false) == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - delete preCacheThread; - preCacheThread=NULL; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("E - shutting down crc threads\n"); - } - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("F - shutting down crc threads\n"); - preCacheThread = NULL; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (preCacheThread != NULL) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + + const double MAX_THREAD_WAIT = 60; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("START - shutting down crc threads\n"); + time_t elapsed = time(NULL); + preCacheThread->signalQuit(); + for (; preCacheThread->canShutdown(false) == false && + difftime((long int)time(NULL), elapsed) <= MAX_THREAD_WAIT;) { + } + if (difftime((long int)time(NULL), elapsed) <= MAX_THREAD_WAIT) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("B - shutting down crc threads\n"); + + for (; preCacheThread->shutdownAndWait() == false && + difftime((long int)time(NULL), elapsed) <= MAX_THREAD_WAIT;) { + } + if (preCacheThread->getRunningStatus() == false) { + delete preCacheThread; + preCacheThread = NULL; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("C - shutting down crc threads\n"); + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + } else { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("D - shutting down crc threads\n"); + + if (preCacheThread->canShutdown(false) == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + delete preCacheThread; + preCacheThread = NULL; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("E - shutting down crc threads\n"); + } + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("F - shutting down crc threads\n"); + preCacheThread = NULL; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); } static void cleanupProcessObjects() { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - showCursor(true); - restoreVideoMode(::Shared::Platform::Window::getSDLWindow(), true); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("#1 IRCCLient Cache SHUTDOWN\n"); - IRCThread * &ircClient = CacheManager::getCachedItem< IRCThread * >(GameConstants::ircClientCacheLookupKey); - if(ircClient != NULL) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("#2 IRCCLient Cache SHUTDOWN\n"); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + showCursor(true); + restoreVideoMode(::Shared::Platform::Window::getSDLWindow(), true); + } - ircClient->disconnect(); - ircClient->signalQuit(); - ircClient = NULL; - sleep(0); - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("#4 IRCCLient Cache SHUTDOWN\n"); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("#1 IRCCLient Cache SHUTDOWN\n"); + IRCThread *&ircClient = CacheManager::getCachedItem( + GameConstants::ircClientCacheLookupKey); + if (ircClient != NULL) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("#2 IRCCLient Cache SHUTDOWN\n"); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + ircClient->disconnect(); + ircClient->signalQuit(); + ircClient = NULL; + sleep(0); + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("#4 IRCCLient Cache SHUTDOWN\n"); - cleanupCRCThread(); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + cleanupCRCThread(); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); - if(Renderer::isEnded() == false) { - Renderer::getInstance().end(); - CoreData &coreData= CoreData::getInstance(); - coreData.cleanup(); - } + if (Renderer::isEnded() == false) { + Renderer::getInstance().end(); + CoreData &coreData = CoreData::getInstance(); + coreData.cleanup(); + } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); - SystemFlags::Close(); - SystemFlags::SHUTDOWN_PROGRAM_MODE=true; + SystemFlags::Close(); + SystemFlags::SHUTDOWN_PROGRAM_MODE = true; - //printf("Closing IRC CLient %d\n",__LINE__); + // printf("Closing IRC CLient %d\n",__LINE__); - Thread::shutdownThreads(); + Thread::shutdownThreads(); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("start running threads = " MG_SIZE_T_SPECIFIER "\n",Thread::getThreadList().size()); - time_t elapsed = time(NULL); - int lastLazyThreadDump = 0; - for(;Thread::getThreadList().size() > 0 && - difftime((long int)time(NULL),elapsed) <= 10;) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("start running threads = " MG_SIZE_T_SPECIFIER "\n", + Thread::getThreadList().size()); + time_t elapsed = time(NULL); + int lastLazyThreadDump = 0; + for (; Thread::getThreadList().size() > 0 && + difftime((long int)time(NULL), elapsed) <= 10;) { - if(difftime((long int)time(NULL),elapsed) > 1) { - if(lastLazyThreadDump != (int)difftime((long int)time(NULL),elapsed)) { - lastLazyThreadDump = difftime((long int)time(NULL),elapsed); + if (difftime((long int)time(NULL), elapsed) > 1) { + if (lastLazyThreadDump != (int)difftime((long int)time(NULL), elapsed)) { + lastLazyThreadDump = difftime((long int)time(NULL), elapsed); - printf("Waiting for the following threads to exit [" MG_SIZE_T_SPECIFIER "]:\n",Thread::getThreadList().size()); + printf("Waiting for the following threads to exit [" MG_SIZE_T_SPECIFIER + "]:\n", + Thread::getThreadList().size()); - for(int i = 0; i < (int)Thread::getThreadList().size(); ++i) { - BaseThread *baseThread = dynamic_cast(Thread::getThreadList()[i]); - printf("Thread index: %d ptr [%p] isBaseThread: %d, Name: [%s]\n",i,baseThread,(baseThread != NULL ? 1 : 0),(baseThread != NULL ? baseThread->getUniqueID().c_str() : "")); - } - } - } + for (int i = 0; i < (int)Thread::getThreadList().size(); ++i) { + BaseThread *baseThread = + dynamic_cast(Thread::getThreadList()[i]); + printf("Thread index: %d ptr [%p] isBaseThread: %d, Name: [%s]\n", i, + baseThread, (baseThread != NULL ? 1 : 0), + (baseThread != NULL ? baseThread->getUniqueID().c_str() + : "")); + } + } } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("end running threads = " MG_SIZE_T_SPECIFIER "\n",Thread::getThreadList().size()); + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("end running threads = " MG_SIZE_T_SPECIFIER "\n", + Thread::getThreadList().size()); - Thread::shutdownThreads(); + Thread::shutdownThreads(); - std::map &crcPlayerTextureCache = CacheManager::getCachedItem< std::map >(GameConstants::playerTextureCacheLookupKey); - crcPlayerTextureCache.clear(); + std::map &crcPlayerTextureCache = + CacheManager::getCachedItem>( + GameConstants::playerTextureCacheLookupKey); + crcPlayerTextureCache.clear(); - std::map &crcFactionPreviewTextureCache = CacheManager::getCachedItem< std::map >(GameConstants::factionPreviewTextureCacheLookupKey); - crcFactionPreviewTextureCache.clear(); + std::map &crcFactionPreviewTextureCache = + CacheManager::getCachedItem>( + GameConstants::factionPreviewTextureCacheLookupKey); + crcFactionPreviewTextureCache.clear(); - std::map const * >* > &list2d = FileReader::getFileReadersMap(); - deleteMapValues(list2d.begin(),list2d.end()); - std::map const * >* > &list3d = FileReader::getFileReadersMap(); - deleteMapValues(list3d.begin(),list3d.end()); + std::map const *> *> &list2d = + FileReader::getFileReadersMap(); + deleteMapValues(list2d.begin(), list2d.end()); + std::map const *> *> &list3d = + FileReader::getFileReadersMap(); + deleteMapValues(list3d.begin(), list3d.end()); #if defined(WANT_XERCES) - XmlIo::getInstance().cleanup(); + XmlIo::getInstance().cleanup(); #endif - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); - SystemFlags::globalCleanupHTTP(); - CacheManager::cleanupMutexes(); + SystemFlags::globalCleanupHTTP(); + CacheManager::cleanupMutexes(); } #if defined(WIN32) && !defined(__GNUC__) -void fatal(const char *s, ...) // failure exit +void fatal(const char *s, ...) // failure exit { - static int errors = 0; - errors++; - - if(errors <= 5) { // print up to two extra recursive errors - defvformatstring(msg,s,s); - string errText = string(msg) + " [" + runtimeErrorMsg + "]"; - //puts(msg); - string sErr = string(mg_app_name) + " fatal error"; - SystemFlags::OutputDebug(SystemFlags::debugError,"%s\n",errText.c_str()); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s\n",errText.c_str()); - - if(errors <= 1) { // avoid recursion - if(SDL_WasInit(SDL_INIT_VIDEO)) { - SDL_SetRelativeMouseMode(SDL_FALSE); - } - #ifdef WIN32 - LPWSTR wstr = Ansi2WideString(errText.c_str()); - LPWSTR wstr1 = Ansi2WideString(sErr.c_str()); + static int errors = 0; + errors++; + + if (errors <= 5) { // print up to two extra recursive errors + defvformatstring(msg, s, s); + string errText = string(msg) + " [" + runtimeErrorMsg + "]"; + // puts(msg); + string sErr = string(mg_app_name) + " fatal error"; + SystemFlags::OutputDebug(SystemFlags::debugError, "%s\n", errText.c_str()); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s\n", errText.c_str()); + + if (errors <= 1) { // avoid recursion + if (SDL_WasInit(SDL_INIT_VIDEO)) { + SDL_SetRelativeMouseMode(SDL_FALSE); + } +#ifdef WIN32 + LPWSTR wstr = Ansi2WideString(errText.c_str()); + LPWSTR wstr1 = Ansi2WideString(sErr.c_str()); - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - MessageBox(NULL, wstr, wstr1, MB_OK|MB_SYSTEMMODAL); - } + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + MessageBox(NULL, wstr, wstr1, MB_OK | MB_SYSTEMMODAL); + } - if(wstr) delete [] wstr; - if(wstr1) delete [] wstr1; - #endif - } + if (wstr) + delete[] wstr; + if (wstr1) + delete[] wstr1; +#endif } + } - // Now try to shutdown threads if possible - delete mainProgram; - mainProgram = NULL; - // END + // Now try to shutdown threads if possible + delete mainProgram; + mainProgram = NULL; + // END - if(sdl_quitCalled == false) { - sdl_quitCalled = true; - SDL_Quit(); - } - exit(EXIT_FAILURE); + if (sdl_quitCalled == false) { + sdl_quitCalled = true; + SDL_Quit(); + } + exit(EXIT_FAILURE); } std::string get_module_path(HMODULE module = 0) { @@ -342,7 +384,8 @@ std::string get_module_path(HMODULE module = 0) { void write_module_name(string &out, HANDLE process, DWORD64 program_counter) { DWORD64 module_base = SymGetModuleBase64(process, program_counter); if (module_base) { - std::string module_name = get_module_path(reinterpret_cast(module_base)); + std::string module_name = + get_module_path(reinterpret_cast(module_base)); if (!module_name.empty()) out += module_name + "|"; else @@ -353,7 +396,7 @@ void write_module_name(string &out, HANDLE process, DWORD64 program_counter) { } void write_function_name(string &out, HANDLE process, DWORD64 program_counter) { - SYMBOL_INFO_PACKAGE sym = { sizeof(sym) }; + SYMBOL_INFO_PACKAGE sym = {sizeof(sym)}; sym.si.MaxNameLen = MAX_SYM_NAME; if (SymFromAddr(process, program_counter, 0, &sym.si)) { out += string(sym.si.Name) + "()"; @@ -362,33 +405,34 @@ void write_function_name(string &out, HANDLE process, DWORD64 program_counter) { } } -void write_file_and_line(string & out, HANDLE process, DWORD64 program_counter) { - IMAGEHLP_LINE64 ih_line = { sizeof(IMAGEHLP_LINE64) }; +void write_file_and_line(string &out, HANDLE process, DWORD64 program_counter) { + IMAGEHLP_LINE64 ih_line = {sizeof(IMAGEHLP_LINE64)}; DWORD dummy = 0; if (SymGetLineFromAddr64(process, program_counter, &dummy, &ih_line)) { - out += string("|") + string(ih_line.FileName) + ":" + intToStr(ih_line.LineNumber); + out += string("|") + string(ih_line.FileName) + ":" + + intToStr(ih_line.LineNumber); } } void generate_stack_trace(string &out, CONTEXT ctx, int skip) { STACKFRAME64 sf = {}; #if !defined(_WIN64) - sf.AddrPC.Offset = ctx.Eip; + sf.AddrPC.Offset = ctx.Eip; #else - sf.AddrPC.Offset = ctx.Rip; + sf.AddrPC.Offset = ctx.Rip; #endif - sf.AddrPC.Mode = AddrModeFlat; + sf.AddrPC.Mode = AddrModeFlat; #if !defined(_WIN64) sf.AddrStack.Offset = ctx.Esp; #else sf.AddrStack.Offset = ctx.Rsp; #endif - sf.AddrStack.Mode = AddrModeFlat; + sf.AddrStack.Mode = AddrModeFlat; #if !defined(_WIN64) sf.AddrFrame.Offset = ctx.Ebp; #else sf.AddrFrame.Offset = ctx.Rbp; #endif - sf.AddrFrame.Mode = AddrModeFlat; + sf.AddrFrame.Mode = AddrModeFlat; HANDLE process = GetCurrentProcess(); HANDLE thread = GetCurrentThread(); @@ -401,77 +445,76 @@ void generate_stack_trace(string &out, CONTEXT ctx, int skip) { for (;;) { SetLastError(0); #if !defined(_WIN64) - BOOL stack_walk_ok = StackWalk64(IMAGE_FILE_MACHINE_I386, + BOOL stack_walk_ok = + StackWalk64(IMAGE_FILE_MACHINE_I386, #else - BOOL stack_walk_ok = StackWalk64(IMAGE_FILE_MACHINE_AMD64, + BOOL stack_walk_ok = + StackWalk64(IMAGE_FILE_MACHINE_AMD64, #endif - process, thread, &sf, - (tryThreadContext == false ? &threadContext : &ctx), - 0, &SymFunctionTableAccess64, - &SymGetModuleBase64, 0); + process, thread, &sf, + (tryThreadContext == false ? &threadContext : &ctx), 0, + &SymFunctionTableAccess64, &SymGetModuleBase64, 0); if (!stack_walk_ok || !sf.AddrFrame.Offset) { - if(tryThreadContext == true) { - tryThreadContext = false; - if(GetThreadContext(thread, &threadContext) != 0) { + if (tryThreadContext == true) { + tryThreadContext = false; + if (GetThreadContext(thread, &threadContext) != 0) { #if !defined(_WIN64) - sf.AddrPC.Offset = threadContext.Eip; + sf.AddrPC.Offset = threadContext.Eip; #else - sf.AddrPC.Offset = threadContext.Rip; + sf.AddrPC.Offset = threadContext.Rip; #endif - sf.AddrPC.Mode = AddrModeFlat; + sf.AddrPC.Mode = AddrModeFlat; #if !defined(_WIN64) - sf.AddrStack.Offset = threadContext.Esp; + sf.AddrStack.Offset = threadContext.Esp; #else - sf.AddrStack.Offset = threadContext.Rsp; + sf.AddrStack.Offset = threadContext.Rsp; #endif - sf.AddrStack.Mode = AddrModeFlat; + sf.AddrStack.Mode = AddrModeFlat; #if !defined(_WIN64) - sf.AddrFrame.Offset = threadContext.Ebp; + sf.AddrFrame.Offset = threadContext.Ebp; #else - sf.AddrFrame.Offset = threadContext.Rbp; + sf.AddrFrame.Offset = threadContext.Rbp; #endif - sf.AddrFrame.Mode = AddrModeFlat; - } - else { - return; - } - } - else { - return; - } - } + sf.AddrFrame.Mode = AddrModeFlat; + } else { + return; + } + } else { + return; + } + } if (skip) { - --skip; - } - else { + --skip; + } else { // write the address - out += intToStr(sf.AddrPC.Offset) + "|"; + out += intToStr(sf.AddrPC.Offset) + "|"; - write_module_name(out, process, sf.AddrPC.Offset); - write_function_name(out, process, sf.AddrPC.Offset); - write_file_and_line(out, process, sf.AddrPC.Offset); + write_module_name(out, process, sf.AddrPC.Offset); + write_function_name(out, process, sf.AddrPC.Offset); + write_file_and_line(out, process, sf.AddrPC.Offset); - out += "\n"; + out += "\n"; } } } struct UntypedException { - explicit UntypedException(const EXCEPTION_RECORD & er) - : exception_object(reinterpret_cast(er.ExceptionInformation[1])), - type_array(reinterpret_cast<_ThrowInfo *>(er.ExceptionInformation[2])->pCatchableTypeArray) - {} - void * exception_object; - _CatchableTypeArray * type_array; + explicit UntypedException(const EXCEPTION_RECORD &er) + : exception_object(reinterpret_cast(er.ExceptionInformation[1])), + type_array(reinterpret_cast<_ThrowInfo *>(er.ExceptionInformation[2]) + ->pCatchableTypeArray) {} + void *exception_object; + _CatchableTypeArray *type_array; }; -void * exception_cast_worker(const UntypedException & e, const type_info & ti) { +void *exception_cast_worker(const UntypedException &e, const type_info &ti) { for (int i = 0; i < e.type_array->nCatchableTypes; ++i) { - _CatchableType & type_i = *e.type_array->arrayOfCatchableTypes[i]; - const std::type_info & ti_i = *reinterpret_cast(type_i.pType); + _CatchableType &type_i = *e.type_array->arrayOfCatchableTypes[i]; + const std::type_info &ti_i = + *reinterpret_cast(type_i.pType); if (ti_i == ti) { - char * base_address = reinterpret_cast(e.exception_object); + char *base_address = reinterpret_cast(e.exception_object); base_address += type_i.thisDisplacement.mdisp; return base_address; } @@ -479,62 +522,55 @@ void * exception_cast_worker(const UntypedException & e, const type_info & ti) { return 0; } -template -T * exception_cast(const UntypedException & e) { - const std::type_info & ti = typeid(T); +template T *exception_cast(const UntypedException &e) { + const std::type_info &ti = typeid(T); return reinterpret_cast(exception_cast_worker(e, ti)); } void stackdumper(unsigned int type, EXCEPTION_POINTERS *ep, bool fatalExit) { #ifdef HAVE_GOOGLE_BREAKPAD - if(errorHandlerPtr.get() != NULL) { - errorHandlerPtr->WriteMinidump(); - } + if (errorHandlerPtr.get() != NULL) { + errorHandlerPtr->WriteMinidump(); + } #endif - if(!ep) { - fatal("unknown type"); - return; - } - EXCEPTION_RECORD *er = ep->ExceptionRecord; - CONTEXT *context = ep->ContextRecord; - string out=""; - int skip = 0; - - switch (er->ExceptionCode) { - case 0xE06D7363: { // C++ exception - UntypedException ue(*er); - if (std::exception * e = exception_cast(ue)) { - const std::type_info & ti = typeid(*e); - out += string(ti.name()) + ":" + string(e->what()); - } - else { - out += "Unknown C++ exception thrown."; - } - skip = 2; // skip RaiseException and _CxxThrowException - } break; - case EXCEPTION_ACCESS_VIOLATION: { - out += string("Access violation. Illegal ") - + (er->ExceptionInformation[0] ? "write" : "read") - + string(" by ") - + intToStr((int)er->ExceptionAddress) - + string(" at ") - + intToStr(er->ExceptionInformation[1]); - } break; - default: { - out += "SEH exception thrown. Exception code: " - + er->ExceptionCode - + string(" at ") - + intToStr((int)er->ExceptionAddress); - } - } - - generate_stack_trace(out, *context, skip); - - if(fatalExit == true) { - fatal(out.c_str()); - } - else { - ExceptionHandler::logError(out.c_str(), true); - } + if (!ep) { + fatal("unknown type"); + return; + } + EXCEPTION_RECORD *er = ep->ExceptionRecord; + CONTEXT *context = ep->ContextRecord; + string out = ""; + int skip = 0; + + switch (er->ExceptionCode) { + case 0xE06D7363: { // C++ exception + UntypedException ue(*er); + if (std::exception *e = exception_cast(ue)) { + const std::type_info &ti = typeid(*e); + out += string(ti.name()) + ":" + string(e->what()); + } else { + out += "Unknown C++ exception thrown."; + } + skip = 2; // skip RaiseException and _CxxThrowException + } break; + case EXCEPTION_ACCESS_VIOLATION: { + out += string("Access violation. Illegal ") + + (er->ExceptionInformation[0] ? "write" : "read") + string(" by ") + + intToStr((int)er->ExceptionAddress) + string(" at ") + + intToStr(er->ExceptionInformation[1]); + } break; + default: { + out += "SEH exception thrown. Exception code: " + er->ExceptionCode + + string(" at ") + intToStr((int)er->ExceptionAddress); + } + } + + generate_stack_trace(out, *context, skip); + + if (fatalExit == true) { + fatal(out.c_str()); + } else { + ExceptionHandler::logError(out.c_str(), true); + } } #endif @@ -542,892 +578,1036 @@ void stackdumper(unsigned int type, EXCEPTION_POINTERS *ep, bool fatalExit) { // class ExceptionHandler // ===================================================== #if defined(WIN32) && !defined(__GNUC__) - void ExceptionHandler::handle(LPEXCEPTION_POINTERS pointers) { - string msg = "#1 An error occurred and " + string(mg_app_name) + " will close.\nPlease report this bug to: " + string(mailString); - msg += ", attaching the generated " + getCrashDumpFileName()+ " file."; +void ExceptionHandler::handle(LPEXCEPTION_POINTERS pointers) { + string msg = "#1 An error occurred and " + string(mg_app_name) + + " will close.\nPlease report this bug to: " + string(mailString); + msg += ", attaching the generated " + getCrashDumpFileName() + " file."; - SystemFlags::OutputDebug(SystemFlags::debugError,"%s\n",msg.c_str()); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s\n",msg.c_str()); + SystemFlags::OutputDebug(SystemFlags::debugError, "%s\n", msg.c_str()); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s\n", msg.c_str()); - stackdumper(0, pointers, false); + stackdumper(0, pointers, false); - if(mainProgram && gameInitialized == true) { - mainProgram->showMessage(msg.c_str()); - } + if (mainProgram && gameInitialized == true) { + mainProgram->showMessage(msg.c_str()); + } - message(msg.c_str(),GlobalStaticFlags::getIsNonGraphicalModeEnabled(),tempDataLocation); + message(msg.c_str(), GlobalStaticFlags::getIsNonGraphicalModeEnabled(), + tempDataLocation); } #endif - void ExceptionHandler::handle() { - string msg = "#1 An error occurred and " + string(mg_app_name) + " will close.\nPlease report this bug to: " + string(mailString); +void ExceptionHandler::handle() { + string msg = "#1 An error occurred and " + string(mg_app_name) + + " will close.\nPlease report this bug to: " + string(mailString); #ifdef WIN32 - msg += ", attaching the generated " + getCrashDumpFileName()+ " file."; + msg += ", attaching the generated " + getCrashDumpFileName() + " file."; #endif - SystemFlags::OutputDebug(SystemFlags::debugError,"%s\n",msg.c_str()); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s\n",msg.c_str()); + SystemFlags::OutputDebug(SystemFlags::debugError, "%s\n", msg.c_str()); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s\n", msg.c_str()); - if(mainProgram && gameInitialized == true) { - mainProgram->showMessage(msg.c_str()); - } + if (mainProgram && gameInitialized == true) { + mainProgram->showMessage(msg.c_str()); + } + + message(msg.c_str(), GlobalStaticFlags::getIsNonGraphicalModeEnabled(), + tempDataLocation); +} - message(msg.c_str(),GlobalStaticFlags::getIsNonGraphicalModeEnabled(),tempDataLocation); - } - - void ExceptionHandler::logError(const char *msg, bool confirmToConsole) { - string errorLogFile = "error.log"; - if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - errorLogFile = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + errorLogFile; - } - else { - string userData = Config::getInstance().getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - errorLogFile = userData + errorLogFile; - } +void ExceptionHandler::logError(const char *msg, bool confirmToConsole) { + string errorLogFile = "error.log"; + if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { + errorLogFile = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + + errorLogFile; + } else { + string userData = Config::getInstance().getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + errorLogFile = userData + errorLogFile; + } #if defined(WIN32) && !defined(__MINGW32__) - FILE *fp = _wfopen(utf8_decode(errorLogFile).c_str(), L"w"); - std::ofstream logFile(fp); + FILE *fp = _wfopen(utf8_decode(errorLogFile).c_str(), L"w"); + std::ofstream logFile(fp); #else - std::ofstream logFile; - logFile.open(errorLogFile.c_str(), ios_base::out | ios_base::trunc); + std::ofstream logFile; + logFile.open(errorLogFile.c_str(), ios_base::out | ios_base::trunc); #endif - if(logFile.is_open() == true) { - //time_t curtime = time (NULL); - //struct tm *loctime = localtime (&curtime); - struct tm loctime = threadsafe_localtime(systemtime_now()); - char szBuf2[100]=""; - strftime(szBuf2,100,"%Y-%m-%d %H:%M:%S",&loctime); + if (logFile.is_open() == true) { + // time_t curtime = time (NULL); + // struct tm *loctime = localtime (&curtime); + struct tm loctime = threadsafe_localtime(systemtime_now()); + char szBuf2[100] = ""; + strftime(szBuf2, 100, "%Y-%m-%d %H:%M:%S", &loctime); - logFile << "[" << szBuf2 << "] Runtime Error information:" << std::endl; - logFile << "======================================================" << std::endl; - logFile << (msg != NULL ? msg : "null") << std::endl; - logFile.close(); + logFile << "[" << szBuf2 << "] Runtime Error information:" << std::endl; + logFile << "======================================================" + << std::endl; + logFile << (msg != NULL ? msg : "null") << std::endl; + logFile.close(); #if defined(WIN32) && !defined(__MINGW32__) - if(fp) { - fclose(fp); - } + if (fp) { + fclose(fp); + } #endif - if(confirmToConsole == true) { - printf("Error saved to logfile [%s]\n",errorLogFile.c_str()); - fflush(stdout); - } - } - else { - if(confirmToConsole == true) { - printf("COULD NOT SAVE TO ERROR logfile [%s]\n",errorLogFile.c_str()); - fflush(stdout); - } - } - } - - void ExceptionHandler::handleRuntimeError(const megaglest_runtime_error &ex) { - const char *msg = ex.what(); - handleRuntimeError(msg,false); - } - - void ExceptionHandler::handleRuntimeError(const char *msg, bool getStackTraceString) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - static bool inErrorNow = false; - if(inErrorNow == true) { - printf("\n=====================================\n"); - printf("\n** Already in error handler aborting, msg [%s]\n",msg); - fflush(stdout); - abort(); - //return; - } - inErrorNow = true; - - logError(msg,true); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] program = %p gameInitialized = %d msg [%s]\n",__FILE__,__FUNCTION__,__LINE__,mainProgram,gameInitialized,msg); - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] [%s] gameInitialized = %d, program = %p\n",__FILE__,__FUNCTION__,__LINE__,msg,gameInitialized,mainProgram); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] [%s] gameInitialized = %d, program = %p\n",__FILE__,__FUNCTION__,__LINE__,msg,gameInitialized,mainProgram); - - string errMsg = (msg != NULL ? msg : "null"); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - bool gotStackTrace = false; - if(getStackTraceString == true && disableBacktrace == false && sdl_quitCalled == false) { - string stackTrace = getStackTrace(); - errMsg += stackTrace; - gotStackTrace = true; - } + if (confirmToConsole == true) { + printf("Error saved to logfile [%s]\n", errorLogFile.c_str()); + fflush(stdout); + } + } else { + if (confirmToConsole == true) { + printf("COULD NOT SAVE TO ERROR logfile [%s]\n", errorLogFile.c_str()); + fflush(stdout); + } + } +} + +void ExceptionHandler::handleRuntimeError(const megaglest_runtime_error &ex) { + const char *msg = ex.what(); + handleRuntimeError(msg, false); +} + +void ExceptionHandler::handleRuntimeError(const char *msg, + bool getStackTraceString) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + + static bool inErrorNow = false; + if (inErrorNow == true) { + printf("\n=====================================\n"); + printf("\n** Already in error handler aborting, msg [%s]\n", msg); + fflush(stdout); + abort(); + // return; + } + inErrorNow = true; + + logError(msg, true); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] program = %p gameInitialized = %d msg [%s]\n", + __FILE__, __FUNCTION__, __LINE__, mainProgram, gameInitialized, msg); + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d] [%s] gameInitialized = %d, program = %p\n", + __FILE__, __FUNCTION__, __LINE__, msg, gameInitialized, mainProgram); + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] [%s] gameInitialized = %d, program = %p\n", + __FILE__, __FUNCTION__, __LINE__, msg, gameInitialized, mainProgram); + + string errMsg = (msg != NULL ? msg : "null"); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + + bool gotStackTrace = false; + if (getStackTraceString == true && disableBacktrace == false && + sdl_quitCalled == false) { + string stackTrace = getStackTrace(); + errMsg += stackTrace; + gotStackTrace = true; + } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); - logError(errMsg.c_str(),false); + logError(errMsg.c_str(), false); - if(gotStackTrace == true) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] [%s]\n",__FILE__,__FUNCTION__,__LINE__,errMsg.c_str()); + if (gotStackTrace == true) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] [%s]\n", __FILE__, + __FUNCTION__, __LINE__, errMsg.c_str()); + } + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] [%s]\n", __FILE__, + __FUNCTION__, __LINE__, errMsg.c_str()); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + + // abort(); + + if (mainProgram && gameInitialized == true) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + + if (mainProgram->getState() != NULL) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + mainProgram->showMessage(errMsg.c_str()); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + + if (glActiveTexture != NULL) { + for (; GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && + mainProgram->isMessageShowing();) { + ::Shared::Platform::Window::handleEvent(); + try { + mainProgram->loop(); + } catch (const exception &e) { + printf("\n=====================================\n"); + printf("\n** Already in error handler exiting error rendering, msg " + "[%s]\n", + e.what()); + fflush(stdout); + break; + } } - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] [%s]\n",__FILE__,__FUNCTION__,__LINE__,errMsg.c_str()); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - //abort(); - - if(mainProgram && gameInitialized == true) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(mainProgram->getState() != NULL) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - mainProgram->showMessage(errMsg.c_str()); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(glActiveTexture != NULL) { - for(;GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && mainProgram->isMessageShowing();) { - ::Shared::Platform::Window::handleEvent(); - try { - mainProgram->loop(); - } - catch(const exception &e) { - printf("\n=====================================\n"); - printf("\n** Already in error handler exiting error rendering, msg [%s]\n",e.what()); - fflush(stdout); - break; - } - } - } - } - else { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - mainProgram->showMessage(errMsg.c_str()); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(glActiveTexture != NULL) { - for(;GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && mainProgram->isMessageShowing();) { - ::Shared::Platform::Window::handleEvent(); - try { - mainProgram->loop(); - } - catch(const exception &e) { - printf("\n=====================================\n"); - printf("\n** Already in error handler exiting error rendering, msg [%s]\n",e.what()); - fflush(stdout); - break; - } - } - } - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + } + } else { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + mainProgram->showMessage(errMsg.c_str()); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + + if (glActiveTexture != NULL) { + for (; GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && + mainProgram->isMessageShowing();) { + ::Shared::Platform::Window::handleEvent(); + try { + mainProgram->loop(); + } catch (const exception &e) { + printf("\n=====================================\n"); + printf("\n** Already in error handler exiting error rendering, msg " + "[%s]\n", + e.what()); + fflush(stdout); + break; + } } - else { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + } + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + } else { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); - string err = "#2 An error occurred and "; - if(sdl_quitCalled == false) { - err += mg_app_name; - } - err += " will close.\nError msg = [" + errMsg + "]\n\nPlease report this bug to "; - if(sdl_quitCalled == false) { - err += mailStringSupport; - } + string err = "#2 An error occurred and "; + if (sdl_quitCalled == false) { + err += mg_app_name; + } + err += " will close.\nError msg = [" + errMsg + + "]\n\nPlease report this bug to "; + if (sdl_quitCalled == false) { + err += mailStringSupport; + } #ifdef WIN32 - err += string(", attaching the generated ") + getCrashDumpFileName() + string(" file."); + err += string(", attaching the generated ") + getCrashDumpFileName() + + string(" file."); #endif - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); - message(err,GlobalStaticFlags::getIsNonGraphicalModeEnabled(),tempDataLocation); - } + message(err, GlobalStaticFlags::getIsNonGraphicalModeEnabled(), + tempDataLocation); + } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); - // Now try to shutdown threads if possible - delete mainProgram; - mainProgram = NULL; - // END + // Now try to shutdown threads if possible + delete mainProgram; + mainProgram = NULL; + // END - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); #ifdef WIN32 - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - showCursor(true); - restoreVideoMode(::Shared::Platform::Window::getSDLWindow(), true); - } + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + showCursor(true); + restoreVideoMode(::Shared::Platform::Window::getSDLWindow(), true); + } - runtimeErrorMsg = errMsg; - inErrorNow = false; - throw runtimeErrorMsg; + runtimeErrorMsg = errMsg; + inErrorNow = false; + throw runtimeErrorMsg; #endif - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - cleanupProcessObjects(); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + cleanupProcessObjects(); - if(sdl_quitCalled == false) { - sdl_quitCalled = true; - SDL_Quit(); - } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - inErrorNow = false; + if (sdl_quitCalled == false) { + sdl_quitCalled = true; + SDL_Quit(); + } - abort(); - } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); - int ExceptionHandler::DisplayMessage(const char *msg, bool exitApp) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] msg [%s] exitApp = %d\n",__FILE__,__FUNCTION__,__LINE__,msg,exitApp); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] msg [%s] exitApp = %d\n",__FILE__,__FUNCTION__,__LINE__,msg,exitApp); + inErrorNow = false; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] msg [%s] exitApp = %d\n",__FILE__,__FUNCTION__,__LINE__,msg,exitApp); + abort(); +} - if(mainProgram && gameInitialized == true) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] msg [%s] exitApp = %d\n",__FILE__,__FUNCTION__,__LINE__,msg,exitApp); - mainProgram->showMessage(msg); - } - else { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] msg [%s] exitApp = %d\n",__FILE__,__FUNCTION__,__LINE__,msg,exitApp); - message(msg,GlobalStaticFlags::getIsNonGraphicalModeEnabled(),tempDataLocation); - } +int ExceptionHandler::DisplayMessage(const char *msg, bool exitApp) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] msg [%s] exitApp = %d\n", __FILE__, + __FUNCTION__, __LINE__, msg, exitApp); + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] msg [%s] exitApp = %d\n", + __FILE__, __FUNCTION__, __LINE__, msg, exitApp); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] msg [%s] exitApp = %d\n", __FILE__, + __FUNCTION__, __LINE__, msg, exitApp); + + if (mainProgram && gameInitialized == true) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] msg [%s] exitApp = %d\n", __FILE__, + __FUNCTION__, __LINE__, msg, exitApp); + mainProgram->showMessage(msg); + } else { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] msg [%s] exitApp = %d\n", __FILE__, + __FUNCTION__, __LINE__, msg, exitApp); + message(msg, GlobalStaticFlags::getIsNonGraphicalModeEnabled(), + tempDataLocation); + } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] msg [%s] exitApp = %d\n",__FILE__,__FUNCTION__,__LINE__,msg,exitApp); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] msg [%s] exitApp = %d\n", __FILE__, + __FUNCTION__, __LINE__, msg, exitApp); - if(exitApp == true) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s\n",msg); + if (exitApp == true) { + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s\n", msg); - // Now try to shutdown threads if possible - delete mainProgram; - mainProgram = NULL; - // END + // Now try to shutdown threads if possible + delete mainProgram; + mainProgram = NULL; + // END - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] msg [%s] exitApp = %d\n",__FILE__,__FUNCTION__,__LINE__,msg,exitApp); - cleanupProcessObjects(); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] msg [%s] exitApp = %d\n", __FILE__, + __FUNCTION__, __LINE__, msg, exitApp); + cleanupProcessObjects(); - if(sdl_quitCalled == false) { - sdl_quitCalled = true; - SDL_Quit(); - } - exit(-1); - } + if (sdl_quitCalled == false) { + sdl_quitCalled = true; + SDL_Quit(); + } + exit(-1); + } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] msg [%s] exitApp = %d\n",__FILE__,__FUNCTION__,__LINE__,msg,exitApp); - return 0; - } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] msg [%s] exitApp = %d\n", __FILE__, + __FUNCTION__, __LINE__, msg, exitApp); + return 0; +} // ===================================================== // class MainWindow // ===================================================== -MainWindow::MainWindow(Program *program) : WindowGl(), popupMenu("MainWindow", "popupMenu") { - this->program= program; - //this->popupMenu.registerGraphicComponentOnlyFontCallbacks("MainWindow", "popupMenu"); - this->popupMenu.setEnabled(false); - this->popupMenu.setVisible(false); - this->triggerLanguageToggle = false; - this->triggerLanguage = ""; - this->cancelLanguageSelection = -1; +MainWindow::MainWindow(Program *program) + : WindowGl(), popupMenu("MainWindow", "popupMenu") { + this->program = program; + // this->popupMenu.registerGraphicComponentOnlyFontCallbacks("MainWindow", + // "popupMenu"); + this->popupMenu.setEnabled(false); + this->popupMenu.setVisible(false); + this->triggerLanguageToggle = false; + this->triggerLanguage = ""; + this->cancelLanguageSelection = -1; } -MainWindow::~MainWindow(){ - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - delete program; - program = NULL; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); +MainWindow::~MainWindow() { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + delete program; + program = NULL; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); } int MainWindow::getDesiredScreenWidth() { - Config &config= Config::getInstance(); - return config.getInt("ScreenWidth"); + Config &config = Config::getInstance(); + return config.getInt("ScreenWidth"); } int MainWindow::getDesiredScreenHeight() { - Config &config= Config::getInstance(); - return config.getInt("ScreenHeight"); + Config &config = Config::getInstance(); + return config.getInt("ScreenHeight"); } void MainWindow::eventToggleFullScreen(bool isFullscreen) { - WindowGl::eventToggleFullScreen(isFullscreen); - - if(isFullscreen) { - Metrics::reload(this->program->getWindow()->getScreenWidth(), - this->program->getWindow()->getScreenHeight()); - } - else { - Config &config= Config::getInstance(); - Metrics::reload(config.getInt("ScreenWidth"),config.getInt("ScreenHeight")); - //window->setText(config.getString("WindowTitle","MegaGlest")); - //this->mainMenu->init(); - } + WindowGl::eventToggleFullScreen(isFullscreen); + if (isFullscreen) { + Metrics::reload(this->program->getWindow()->getScreenWidth(), + this->program->getWindow()->getScreenHeight()); + } else { + Config &config = Config::getInstance(); + Metrics::reload(config.getInt("ScreenWidth"), + config.getInt("ScreenHeight")); + // window->setText(config.getString("WindowTitle","MegaGlest")); + // this->mainMenu->init(); + } } -void MainWindow::eventMouseDown(int x, int y, MouseButton mouseButton){ - const Metrics &metrics = Metrics::getInstance(); - int vx = metrics.toVirtualX(x); - int vy = metrics.toVirtualY(getH() - y); - - if(program == NULL) { - throw megaglest_runtime_error("In [MainWindow::eventMouseDown] ERROR, program == NULL!"); - } - - if(popupMenu.getVisible() == true && popupMenu.mouseClick(vx, vy)) { - std::pair result = popupMenu.mouseClickedMenuItem(vx, vy); - - popupMenu.setEnabled(false); - popupMenu.setVisible(false); - - // Exit game - if(result.first != cancelLanguageSelection) { - Lang &lang= Lang::getInstance(); - map languageList = lang.getDiscoveredLanguageList(true); - for(map::iterator iterMap = languageList.begin(); - iterMap != languageList.end(); ++iterMap) { - string matchLanguage = iterMap->first + "-" + iterMap->second; - if(matchLanguage == result.second) { - this->triggerLanguageToggle = true; - this->triggerLanguage = iterMap->first; - break; - } - } - - } - - return; - } - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - switch(mouseButton) { - case mbLeft: - program->mouseDownLeft(vx, vy); - break; - case mbRight: - //program->mouseDownRight(vx, vy); - break; - case mbCenter: - //program->mouseDownCenter(vx, vy); - break; - default: - break; - } - - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - ProgramState *programState = program->getState(); - if(programState != NULL) { - switch(mouseButton) { - case mbLeft: - programState->mouseDownLeft(vx, vy); - break; - case mbRight: - programState->mouseDownRight(vx, vy); - break; - case mbCenter: - programState->mouseDownCenter(vx, vy); - break; - default: - break; - } - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - } - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); -} - -void MainWindow::eventMouseUp(int x, int y, MouseButton mouseButton){ - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); +void MainWindow::eventMouseDown(int x, int y, MouseButton mouseButton) { + const Metrics &metrics = Metrics::getInstance(); + int vx = metrics.toVirtualX(x); + int vy = metrics.toVirtualY(getH() - y); - const Metrics &metrics = Metrics::getInstance(); - int vx = metrics.toVirtualX(x); - int vy = metrics.toVirtualY(getH() - y); + if (program == NULL) { + throw megaglest_runtime_error( + "In [MainWindow::eventMouseDown] ERROR, program == NULL!"); + } - if(program == NULL) { - throw megaglest_runtime_error("In [MainWindow::eventMouseUp] ERROR, program == NULL!"); + if (popupMenu.getVisible() == true && popupMenu.mouseClick(vx, vy)) { + std::pair result = popupMenu.mouseClickedMenuItem(vx, vy); + + popupMenu.setEnabled(false); + popupMenu.setVisible(false); + + // Exit game + if (result.first != cancelLanguageSelection) { + Lang &lang = Lang::getInstance(); + map languageList = lang.getDiscoveredLanguageList(true); + for (map::iterator iterMap = languageList.begin(); + iterMap != languageList.end(); ++iterMap) { + string matchLanguage = iterMap->first + "-" + iterMap->second; + if (matchLanguage == result.second) { + this->triggerLanguageToggle = true; + this->triggerLanguage = iterMap->first; + break; + } + } } - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - ProgramState *programState = program->getState(); - - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(programState != NULL) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + return; + } + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + switch (mouseButton) { + case mbLeft: + program->mouseDownLeft(vx, vy); + break; + case mbRight: + // program->mouseDownRight(vx, vy); + break; + case mbCenter: + // program->mouseDownCenter(vx, vy); + break; + default: + break; + } - switch(mouseButton) { - case mbLeft: - programState->mouseUpLeft(vx, vy); - break; - case mbRight: - programState->mouseUpRight(vx, vy); - break; - case mbCenter: - programState->mouseUpCenter(vx, vy); - break; - default: - break; - } - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + ProgramState *programState = program->getState(); + if (programState != NULL) { + switch (mouseButton) { + case mbLeft: + programState->mouseDownLeft(vx, vy); + break; + case mbRight: + programState->mouseDownRight(vx, vy); + break; + case mbCenter: + programState->mouseDownCenter(vx, vy); + break; + default: + break; } - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + } + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); } -void MainWindow::eventMouseDoubleClick(int x, int y, MouseButton mouseButton) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - const Metrics &metrics= Metrics::getInstance(); - int vx = metrics.toVirtualX(x); - int vy = metrics.toVirtualY(getH() - y); +void MainWindow::eventMouseUp(int x, int y, MouseButton mouseButton) { + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); - if(program == NULL) { - throw megaglest_runtime_error("In [MainWindow::eventMouseDoubleClick] ERROR, program == NULL!"); - } + const Metrics &metrics = Metrics::getInstance(); + int vx = metrics.toVirtualX(x); + int vy = metrics.toVirtualY(getH() - y); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (program == NULL) { + throw megaglest_runtime_error( + "In [MainWindow::eventMouseUp] ERROR, program == NULL!"); + } - ProgramState *programState = program->getState(); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + ProgramState *programState = program->getState(); + + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + if (programState != NULL) { + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + switch (mouseButton) { + case mbLeft: + programState->mouseUpLeft(vx, vy); + break; + case mbRight: + programState->mouseUpRight(vx, vy); + break; + case mbCenter: + programState->mouseUpCenter(vx, vy); + break; + default: + break; + } + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + } + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); +} - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); +void MainWindow::eventMouseDoubleClick(int x, int y, MouseButton mouseButton) { + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); - if(programState != NULL) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + const Metrics &metrics = Metrics::getInstance(); + int vx = metrics.toVirtualX(x); + int vy = metrics.toVirtualY(getH() - y); - switch(mouseButton){ - case mbLeft: - programState->mouseDoubleClickLeft(vx, vy); - break; - case mbRight: - programState->mouseDoubleClickRight(vx, vy); - break; - case mbCenter: - programState->mouseDoubleClickCenter(vx, vy); - break; - default: - break; - } + if (program == NULL) { + throw megaglest_runtime_error( + "In [MainWindow::eventMouseDoubleClick] ERROR, program == NULL!"); + } - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + ProgramState *programState = program->getState(); + + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + if (programState != NULL) { + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + switch (mouseButton) { + case mbLeft: + programState->mouseDoubleClickLeft(vx, vy); + break; + case mbRight: + programState->mouseDoubleClickRight(vx, vy); + break; + case mbCenter: + programState->mouseDoubleClickCenter(vx, vy); + break; + default: + break; } - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + } + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); } -void MainWindow::eventMouseMove(int x, int y, const MouseState *ms){ +void MainWindow::eventMouseMove(int x, int y, const MouseState *ms) { - const Metrics &metrics= Metrics::getInstance(); - int vx = metrics.toVirtualX(x); - int vy = metrics.toVirtualY(getH() - y); + const Metrics &metrics = Metrics::getInstance(); + int vx = metrics.toVirtualX(x); + int vy = metrics.toVirtualY(getH() - y); - if(program == NULL) { - throw megaglest_runtime_error("In [MainWindow::eventMouseMove] ERROR, program == NULL!"); - } + if (program == NULL) { + throw megaglest_runtime_error( + "In [MainWindow::eventMouseMove] ERROR, program == NULL!"); + } - program->eventMouseMove(vx, vy, ms); + program->eventMouseMove(vx, vy, ms); - ProgramState *programState = program->getState(); - if(programState != NULL) { - programState->mouseMove(vx, vy, ms); - } + ProgramState *programState = program->getState(); + if (programState != NULL) { + programState->mouseMove(vx, vy, ms); + } } void MainWindow::eventMouseWheel(int x, int y, int zDelta) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); - const Metrics &metrics= Metrics::getInstance(); - int vx = metrics.toVirtualX(x); - int vy = metrics.toVirtualY(getH() - y); + const Metrics &metrics = Metrics::getInstance(); + int vx = metrics.toVirtualX(x); + int vy = metrics.toVirtualY(getH() - y); - if(program == NULL) { - throw megaglest_runtime_error("In [MainWindow::eventMouseMove] ERROR, program == NULL!"); - } + if (program == NULL) { + throw megaglest_runtime_error( + "In [MainWindow::eventMouseMove] ERROR, program == NULL!"); + } - ProgramState *programState = program->getState(); + ProgramState *programState = program->getState(); - if(programState != NULL) { - programState->eventMouseWheel(vx, vy, zDelta); - } + if (programState != NULL) { + programState->eventMouseWheel(vx, vy, zDelta); + } - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); } void MainWindow::render() { - if(popupMenu.getVisible() == true) { - Renderer &renderer= Renderer::getInstance(); - renderer.renderPopupMenu(&popupMenu); - } + if (popupMenu.getVisible() == true) { + Renderer &renderer = Renderer::getInstance(); + renderer.renderPopupMenu(&popupMenu); + } } void MainWindow::showLanguages() { - Lang &lang= Lang::getInstance(); - std::vector menuItems; - map languageList = lang.getDiscoveredLanguageList(true); - for(map::iterator iterMap = languageList.begin(); - iterMap != languageList.end(); ++iterMap) { - menuItems.push_back(iterMap->first + "-" + iterMap->second); - } - - menuItems.push_back(lang.getString("Exit")); - cancelLanguageSelection = (int)menuItems.size()-1; - - popupMenu.setW(100); - popupMenu.setH(100); - popupMenu.init(lang.getString("GameMenuTitle"),menuItems); - popupMenu.setEnabled(true); - popupMenu.setVisible(true); + Lang &lang = Lang::getInstance(); + std::vector menuItems; + map languageList = lang.getDiscoveredLanguageList(true); + for (map::iterator iterMap = languageList.begin(); + iterMap != languageList.end(); ++iterMap) { + menuItems.push_back(iterMap->first + "-" + iterMap->second); + } + + menuItems.push_back(lang.getString("Exit")); + cancelLanguageSelection = (int)menuItems.size() - 1; + + popupMenu.setW(100); + popupMenu.setH(100); + popupMenu.init(lang.getString("GameMenuTitle"), menuItems); + popupMenu.setEnabled(true); + popupMenu.setVisible(true); } void MainWindow::toggleLanguage(string language) { - popupMenu.setEnabled(false); - popupMenu.setVisible(false); - this->triggerLanguageToggle = false; - this->triggerLanguage = ""; - - Lang &lang= Lang::getInstance(); - string currentLanguage = lang.getLanguage(); - - string newLanguageSelected = language; - if(language == "") { - newLanguageSelected = currentLanguage; - - vector langResults; - string data_path = getGameReadWritePath(GameConstants::path_data_CacheLookupKey); - - string userDataPath = getGameCustomCoreDataPath(data_path, ""); - findAll(userDataPath + "data/lang/*.lng", langResults, true, false); - - vector langResults2; - findAll(data_path + "data/lang/*.lng", langResults2, true); - if(langResults2.empty() && langResults.empty()) { - throw megaglest_runtime_error("There are no lang files"); - } - for(unsigned int i = 0; i < langResults2.size(); ++i) { - string testLanguage = langResults2[i]; - if(std::find(langResults.begin(),langResults.end(),testLanguage) == langResults.end()) { - langResults.push_back(testLanguage); - } - } - - for(unsigned int i = 0; i < langResults.size(); ++i) { - string testLanguage = langResults[i]; - if(testLanguage == currentLanguage) { - if( i+1 < langResults.size()) { - newLanguageSelected = langResults[i+1]; - } - else { - newLanguageSelected = langResults[0]; - } - break; - } - } - } - if(newLanguageSelected != currentLanguage) { - lang.loadGameStrings(newLanguageSelected); - program->reloadUI(); - program->consoleAddLine(lang.getString("Language") + " " + newLanguageSelected); - } + popupMenu.setEnabled(false); + popupMenu.setVisible(false); + this->triggerLanguageToggle = false; + this->triggerLanguage = ""; + + Lang &lang = Lang::getInstance(); + string currentLanguage = lang.getLanguage(); + + string newLanguageSelected = language; + if (language == "") { + newLanguageSelected = currentLanguage; + + vector langResults; + string data_path = + getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + + string userDataPath = getGameCustomCoreDataPath(data_path, ""); + findAll(userDataPath + "data/lang/*.lng", langResults, true, false); + + vector langResults2; + findAll(data_path + "data/lang/*.lng", langResults2, true); + if (langResults2.empty() && langResults.empty()) { + throw megaglest_runtime_error("There are no lang files"); + } + for (unsigned int i = 0; i < langResults2.size(); ++i) { + string testLanguage = langResults2[i]; + if (std::find(langResults.begin(), langResults.end(), testLanguage) == + langResults.end()) { + langResults.push_back(testLanguage); + } + } + + for (unsigned int i = 0; i < langResults.size(); ++i) { + string testLanguage = langResults[i]; + if (testLanguage == currentLanguage) { + if (i + 1 < langResults.size()) { + newLanguageSelected = langResults[i + 1]; + } else { + newLanguageSelected = langResults[0]; + } + break; + } + } + } + if (newLanguageSelected != currentLanguage) { + lang.loadGameStrings(newLanguageSelected); + program->reloadUI(); + program->consoleAddLine(lang.getString("Language") + " " + + newLanguageSelected); + } } bool MainWindow::eventTextInput(std::string text) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] [%s]\n",__FILE__,__FUNCTION__,__LINE__,text.c_str()); + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] [%s]\n", __FILE__, + __FUNCTION__, __LINE__, text.c_str()); - if(program == NULL) { - throw megaglest_runtime_error("In [MainWindow::eventKeyDown] ERROR, program == NULL!"); - } + if (program == NULL) { + throw megaglest_runtime_error( + "In [MainWindow::eventKeyDown] ERROR, program == NULL!"); + } - bool result = program->textInput(text); + bool result = program->textInput(text); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] result = %d\n",__FILE__,__FUNCTION__,__LINE__,result); + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] result = %d\n", __FILE__, + __FUNCTION__, __LINE__, result); - return result; + return result; } bool MainWindow::eventSdlKeyDown(SDL_KeyboardEvent key) { - if(program == NULL) { - throw megaglest_runtime_error("In [MainWindow::eventKeyDown] ERROR, program == NULL!"); - } - return program->sdlKeyDown(key); + if (program == NULL) { + throw megaglest_runtime_error( + "In [MainWindow::eventKeyDown] ERROR, program == NULL!"); + } + return program->sdlKeyDown(key); } void MainWindow::eventKeyDown(SDL_KeyboardEvent key) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] [%d]\n",__FILE__,__FUNCTION__,__LINE__,key.keysym.sym); + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] [%d]\n", __FILE__, + __FUNCTION__, __LINE__, key.keysym.sym); - //printf("In mainwindow checking keypress for key [%d]\n",key.keysym.sym); + // printf("In mainwindow checking keypress for key [%d]\n",key.keysym.sym); - SDL_keysym keystate = key.keysym; + SDL_keysym keystate = key.keysym; - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] key = [%c][%d]\n",__FILE__,__FUNCTION__,__LINE__,key,key); + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] key = [%c][%d]\n", __FILE__, + __FUNCTION__, __LINE__, key, key); - if(program == NULL) { - throw megaglest_runtime_error("In [MainWindow::eventKeyDown] ERROR, program == NULL!"); - } + if (program == NULL) { + throw megaglest_runtime_error( + "In [MainWindow::eventKeyDown] ERROR, program == NULL!"); + } - if(popupMenu.getVisible() == true && isKeyPressed(SDLK_ESCAPE,key) == true) { - this->popupMenu.setEnabled(false); - this->popupMenu.setVisible(false); - return; - } + if (popupMenu.getVisible() == true && + isKeyPressed(SDLK_ESCAPE, key) == true) { + this->popupMenu.setEnabled(false); + this->popupMenu.setVisible(false); + return; + } - program->keyDown(key); + program->keyDown(key); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); - if(keystate.mod & (KMOD_LALT | KMOD_RALT)) { - //if(key == vkReturn) { - if(isKeyPressed(SDLK_RETURN,key) == true) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] ALT-ENTER pressed\n",__FILE__,__FUNCTION__,__LINE__); + if (keystate.mod & (KMOD_LALT | KMOD_RALT)) { + // if(key == vkReturn) { + if (isKeyPressed(SDLK_RETURN, key) == true) { + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] ALT-ENTER pressed\n", + __FILE__, __FUNCTION__, __LINE__); - // This stupidity only required in win32. - // We reload the textures so that the canvas paints textures properly + // This stupidity only required in win32. + // We reload the textures so that the canvas paints textures properly #ifdef WIN32 - if(Window::getAllowAltEnterFullscreenToggle() == true) { - Renderer &renderer= Renderer::getInstance(); - renderer.reinitAll(); - } + if (Window::getAllowAltEnterFullscreenToggle() == true) { + Renderer &renderer = Renderer::getInstance(); + renderer.reinitAll(); + } #endif - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - } - } - - //printf("In mainwindow checking keypress for key [%d] mod [%d] modvalue: %d\n",key.keysym.sym,keystate.mod,(keystate.mod & (KMOD_LCTRL | KMOD_RCTRL))); - - if(program != NULL && program->isInSpecialKeyCaptureEvent() == false) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - vector modifiersToCheck; - modifiersToCheck.push_back(KMOD_LCTRL); - modifiersToCheck.push_back(KMOD_RCTRL); - modifiersToCheck.push_back(KMOD_LALT); - modifiersToCheck.push_back(KMOD_RALT); - modifiersToCheck.push_back(KMOD_LSHIFT); - modifiersToCheck.push_back(KMOD_RSHIFT); - - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - if(isKeyPressed(configKeys.getSDLKey("HotKeyShowDebug"),key) == true) { - - Renderer &renderer= Renderer::getInstance(); - if(keystate.mod & (KMOD_LALT | KMOD_RALT)) { - renderer.cycleShowDebugUILevel(); - printf("**Cycled Debug UI level to: %d\n",renderer.getShowDebugUILevel()); - } - else { - bool showDebugUI = renderer.getShowDebugUI(); - renderer.setShowDebugUI(!showDebugUI); - } - } - else if((keystate.mod & (KMOD_LCTRL | KMOD_RCTRL)) && - isKeyPressed(configKeys.getSDLKey("SwitchLanguage"),key) == true) { - if((keystate.mod & (KMOD_LSHIFT | KMOD_RSHIFT))) { - this->triggerLanguageToggle = true; - this->triggerLanguage = ""; - } - else { - showLanguages(); - } - } - else if(isKeyPressed(configKeys.getSDLKey("ReloadINI"),key,modifiersToCheck) == true) { - Config &config = Config::getInstance(); - config.reload(); - } - else if(isKeyPressed(configKeys.getSDLKey("Screenshot"),key,modifiersToCheck) == true) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Screenshot key pressed\n"); - - string userData = Config::getInstance().getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - - string path = userData + GameConstants::folder_path_screenshots; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Screenshot checking path [%s]\n",path.c_str()); - - if(isdir(path.c_str()) == false) { - createDirectoryPaths(path); - } - - if(isdir(path.c_str()) == true) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Screenshot path [%s]\n",path.c_str()); - - Config &config= Config::getInstance(); - string fileFormat = config.getString("ScreenShotFileType","jpg"); - - unsigned int queueSize = Renderer::getInstance().getSaveScreenQueueSize(); - - for(int i=0; i < 5000; ++i) { - path = userData + GameConstants::folder_path_screenshots; - path += string("screen") + intToStr(i + queueSize) + string(".") + fileFormat; + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + } + } + + // printf("In mainwindow checking keypress for key [%d] mod [%d] modvalue: + // %d\n",key.keysym.sym,keystate.mod,(keystate.mod & (KMOD_LCTRL | + // KMOD_RCTRL))); + + if (program != NULL && program->isInSpecialKeyCaptureEvent() == false) { + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + vector modifiersToCheck; + modifiersToCheck.push_back(KMOD_LCTRL); + modifiersToCheck.push_back(KMOD_RCTRL); + modifiersToCheck.push_back(KMOD_LALT); + modifiersToCheck.push_back(KMOD_RALT); + modifiersToCheck.push_back(KMOD_LSHIFT); + modifiersToCheck.push_back(KMOD_RSHIFT); + + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + if (isKeyPressed(configKeys.getSDLKey("HotKeyShowDebug"), key) == true) { + + Renderer &renderer = Renderer::getInstance(); + if (keystate.mod & (KMOD_LALT | KMOD_RALT)) { + renderer.cycleShowDebugUILevel(); + printf("**Cycled Debug UI level to: %d\n", + renderer.getShowDebugUILevel()); + } else { + bool showDebugUI = renderer.getShowDebugUI(); + renderer.setShowDebugUI(!showDebugUI); + } + } else if ((keystate.mod & (KMOD_LCTRL | KMOD_RCTRL)) && + isKeyPressed(configKeys.getSDLKey("SwitchLanguage"), key) == + true) { + if ((keystate.mod & (KMOD_LSHIFT | KMOD_RSHIFT))) { + this->triggerLanguageToggle = true; + this->triggerLanguage = ""; + } else { + showLanguages(); + } + } else if (isKeyPressed(configKeys.getSDLKey("ReloadINI"), key, + modifiersToCheck) == true) { + Config &config = Config::getInstance(); + config.reload(); + } else if (isKeyPressed(configKeys.getSDLKey("Screenshot"), key, + modifiersToCheck) == true) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Screenshot key pressed\n"); + + string userData = Config::getInstance().getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + + string path = userData + GameConstants::folder_path_screenshots; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Screenshot checking path [%s]\n", path.c_str()); + + if (isdir(path.c_str()) == false) { + createDirectoryPaths(path); + } + + if (isdir(path.c_str()) == true) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Screenshot path [%s]\n", path.c_str()); + + Config &config = Config::getInstance(); + string fileFormat = config.getString("ScreenShotFileType", "jpg"); + + unsigned int queueSize = + Renderer::getInstance().getSaveScreenQueueSize(); + + for (int i = 0; i < 5000; ++i) { + path = userData + GameConstants::folder_path_screenshots; + path += string("screen") + intToStr(i + queueSize) + string(".") + + fileFormat; #ifdef WIN32 - FILE *f= _wfopen(utf8_decode(path).c_str(), L"rb"); + FILE *f = _wfopen(utf8_decode(path).c_str(), L"rb"); #else - FILE *f= fopen(path.c_str(), "rb"); + FILE *f = fopen(path.c_str(), "rb"); #endif - if(f == NULL) { - Lang &lang= Lang::getInstance(); - char szBuf[8096]=""; - if(lang.getString("ScreenshotSavedTo").length() > 0 && lang.getString("ScreenshotSavedTo")[0] != '?') { - snprintf(szBuf,8096,lang.getString("ScreenshotSavedTo").c_str(),path.c_str()); - } - else { - snprintf(szBuf,8096,"Screenshot will be saved to: %s",path.c_str()); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] %s\n",__FILE__,__FUNCTION__,__LINE__,szBuf); - - bool showScreenshotSavedMsg = Config::getInstance().getBool("DisableScreenshotConsoleText","false"); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Screenshot console showScreenshotSavedMsg = %d\n",showScreenshotSavedMsg); - - if(showScreenshotSavedMsg == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Screenshot console [%s]\n",szBuf); - program->consoleAddLine(szBuf); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Screenshot save to [%s]\n",path.c_str()); - Renderer::getInstance().saveScreen(path); - break; - } - else { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("CANNOT save Screenshot [%s]\n",path.c_str()); - fclose(f); - } - } - } - } - } - - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); -} + if (f == NULL) { + Lang &lang = Lang::getInstance(); + char szBuf[8096] = ""; + if (lang.getString("ScreenshotSavedTo").length() > 0 && + lang.getString("ScreenshotSavedTo")[0] != '?') { + snprintf(szBuf, 8096, lang.getString("ScreenshotSavedTo").c_str(), + path.c_str()); + } else { + snprintf(szBuf, 8096, "Screenshot will be saved to: %s", + path.c_str()); + } -void MainWindow::eventKeyUp(SDL_KeyboardEvent key) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] [%d]\n",__FILE__,__FUNCTION__,__LINE__,key); - if(program == NULL) { - throw megaglest_runtime_error("In [MainWindow::eventKeyUp] ERROR, program == NULL!"); - } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] %s\n", __FILE__, __FUNCTION__, + __LINE__, szBuf); - program->keyUp(key); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] [%d]\n",__FILE__,__FUNCTION__,__LINE__,key); -} + bool showScreenshotSavedMsg = Config::getInstance().getBool( + "DisableScreenshotConsoleText", "false"); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Screenshot console showScreenshotSavedMsg = %d\n", + showScreenshotSavedMsg); -void MainWindow::eventKeyPress(SDL_KeyboardEvent c) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] [%d]\n",__FILE__,__FUNCTION__,__LINE__,c); - if(program == NULL) { - throw megaglest_runtime_error("In [MainWindow::eventKeyPress] ERROR, program == NULL!"); - } + if (showScreenshotSavedMsg == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Screenshot console [%s]\n", szBuf); + program->consoleAddLine(szBuf); + } - program->keyPress(c); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Screenshot save to [%s]\n", path.c_str()); + Renderer::getInstance().saveScreen(path); + break; + } else { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("CANNOT save Screenshot [%s]\n", path.c_str()); + fclose(f); + } + } + } + } + } - if(program != NULL && program->isInSpecialKeyCaptureEvent() == false) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); +} - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - if(isKeyPressed(configKeys.getSDLKey("HotKeyToggleOSMouseEnabled"),c) == true) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); +void MainWindow::eventKeyUp(SDL_KeyboardEvent key) { + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] [%d]\n", __FILE__, + __FUNCTION__, __LINE__, key); + if (program == NULL) { + throw megaglest_runtime_error( + "In [MainWindow::eventKeyUp] ERROR, program == NULL!"); + } - bool showCursorState = false; - int state = SDL_ShowCursor(SDL_QUERY); - if(state == SDL_DISABLE) { - showCursorState = true; - } + program->keyUp(key); + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] [%d]\n", __FILE__, + __FUNCTION__, __LINE__, key); +} - showCursor(showCursorState); - Renderer &renderer= Renderer::getInstance(); - renderer.setNo2DMouseRendering(showCursorState); +void MainWindow::eventKeyPress(SDL_KeyboardEvent c) { + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] [%d]\n", __FILE__, + __FUNCTION__, __LINE__, c); + if (program == NULL) { + throw megaglest_runtime_error( + "In [MainWindow::eventKeyPress] ERROR, program == NULL!"); + } - Window::lastShowMouseState = SDL_ShowCursor(SDL_QUERY); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] Window::lastShowMouseState = %d\n",__FILE__,__FUNCTION__,__LINE__,Window::lastShowMouseState); - } - } - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] [%d]\n",__FILE__,__FUNCTION__,__LINE__,c); + program->keyPress(c); + + if (program != NULL && program->isInSpecialKeyCaptureEvent() == false) { + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + if (isKeyPressed(configKeys.getSDLKey("HotKeyToggleOSMouseEnabled"), c) == + true) { + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + bool showCursorState = false; + int state = SDL_ShowCursor(SDL_QUERY); + if (state == SDL_DISABLE) { + showCursorState = true; + } + + showCursor(showCursorState); + Renderer &renderer = Renderer::getInstance(); + renderer.setNo2DMouseRendering(showCursorState); + + Window::lastShowMouseState = SDL_ShowCursor(SDL_QUERY); + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] Window::lastShowMouseState = %d\n", __FILE__, + __FUNCTION__, __LINE__, Window::lastShowMouseState); + } + } + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] [%d]\n", __FILE__, + __FUNCTION__, __LINE__, c); } void MainWindow::eventWindowEvent(SDL_WindowEvent event) { - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] [%d]\n",__FILE__,__FUNCTION__,__LINE__,event.event); - if(program == NULL) { - throw megaglest_runtime_error("In [MainWindow::eventKeyPress] ERROR, program == NULL!"); - } - -// if(program->getState() != NULL && dynamic_cast(program->getState()) != NULL) { -// printf("In eventWindowEvent skip\n"); -// return; -// } - //Renderer &renderer= Renderer::getInstance(); - switch(event.event) { - case SDL_WINDOWEVENT_ENTER: - { - //printf("In SDL_WINDOWEVENT_ENTER\n"); -// bool showCursorState = Window::lastShowMouseState; -// showCursor(showCursorState); -// renderer.setNo2DMouseRendering(showCursorState); -// -// Window::lastShowMouseState = SDL_ShowCursor(SDL_QUERY); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] Window::lastShowMouseState = %d\n",__FILE__,__FUNCTION__,__LINE__,Window::lastShowMouseState); - } - break; - case SDL_WINDOWEVENT_LEAVE: - { - //printf("In SDL_WINDOWEVENT_LEAVE\n"); -// bool showCursorState = false; -// int state = SDL_ShowCursor(SDL_QUERY); -// if(state == SDL_DISABLE) { -// showCursorState = true; -// } -// showCursor(showCursorState); -// renderer.setNo2DMouseRendering(showCursorState); -// -// Window::lastShowMouseState = SDL_ShowCursor(SDL_QUERY); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] Window::lastShowMouseState = %d\n",__FILE__,__FUNCTION__,__LINE__,Window::lastShowMouseState); - } - break; - case SDL_WINDOWEVENT_FOCUS_GAINED: - { - //printf("SDL_WINDOWEVENT_FOCUS_GAINED\n"); -// bool showCursorState = Window::lastShowMouseState; -// showCursor(showCursorState); -// renderer.setNo2DMouseRendering(showCursorState); -// -// Window::lastShowMouseState = SDL_ShowCursor(SDL_QUERY); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] Window::lastShowMouseState = %d\n",__FILE__,__FUNCTION__,__LINE__,Window::lastShowMouseState); - } - break; - case SDL_WINDOWEVENT_FOCUS_LOST: - { - //printf("SDL_WINDOWEVENT_FOCUS_LOST\n"); -// bool showCursorState = false; -// int state = SDL_ShowCursor(SDL_QUERY); -// if(state == SDL_DISABLE) { -// showCursorState = true; -// } -// showCursor(showCursorState); -// renderer.setNo2DMouseRendering(showCursorState); -// -// Window::lastShowMouseState = SDL_ShowCursor(SDL_QUERY); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] Window::lastShowMouseState = %d\n",__FILE__,__FUNCTION__,__LINE__,Window::lastShowMouseState); - } - break; + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] [%d]\n", __FILE__, + __FUNCTION__, __LINE__, event.event); + if (program == NULL) { + throw megaglest_runtime_error( + "In [MainWindow::eventKeyPress] ERROR, program == NULL!"); + } - } + // if(program->getState() != NULL && dynamic_cast(program->getState()) != NULL) { printf("In eventWindowEvent + // skip\n"); return; + // } + // Renderer &renderer= Renderer::getInstance(); + switch (event.event) { + case SDL_WINDOWEVENT_ENTER: { + // printf("In SDL_WINDOWEVENT_ENTER\n"); + // bool showCursorState = Window::lastShowMouseState; + // showCursor(showCursorState); + // renderer.setNo2DMouseRendering(showCursorState); + // + // Window::lastShowMouseState = SDL_ShowCursor(SDL_QUERY); + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] Window::lastShowMouseState = %d\n", __FILE__, + __FUNCTION__, __LINE__, Window::lastShowMouseState); + } break; + case SDL_WINDOWEVENT_LEAVE: { + // printf("In SDL_WINDOWEVENT_LEAVE\n"); + // bool showCursorState = false; + // int state = SDL_ShowCursor(SDL_QUERY); + // if(state == SDL_DISABLE) { + // showCursorState = true; + // } + // showCursor(showCursorState); + // renderer.setNo2DMouseRendering(showCursorState); + // + // Window::lastShowMouseState = SDL_ShowCursor(SDL_QUERY); + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] Window::lastShowMouseState = %d\n", __FILE__, + __FUNCTION__, __LINE__, Window::lastShowMouseState); + } break; + case SDL_WINDOWEVENT_FOCUS_GAINED: { + // printf("SDL_WINDOWEVENT_FOCUS_GAINED\n"); + // bool showCursorState = Window::lastShowMouseState; + // showCursor(showCursorState); + // renderer.setNo2DMouseRendering(showCursorState); + // + // Window::lastShowMouseState = SDL_ShowCursor(SDL_QUERY); + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] Window::lastShowMouseState = %d\n", __FILE__, + __FUNCTION__, __LINE__, Window::lastShowMouseState); + } break; + case SDL_WINDOWEVENT_FOCUS_LOST: { + // printf("SDL_WINDOWEVENT_FOCUS_LOST\n"); + // bool showCursorState = false; + // int state = SDL_ShowCursor(SDL_QUERY); + // if(state == SDL_DISABLE) { + // showCursorState = true; + // } + // showCursor(showCursorState); + // renderer.setNo2DMouseRendering(showCursorState); + // + // Window::lastShowMouseState = SDL_ShowCursor(SDL_QUERY); + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] Window::lastShowMouseState = %d\n", __FILE__, + __FUNCTION__, __LINE__, Window::lastShowMouseState); + } break; + } - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] [%d]\n",__FILE__,__FUNCTION__,__LINE__,event.event); + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] [%d]\n", __FILE__, + __FUNCTION__, __LINE__, event.event); } void MainWindow::eventActivate(bool active) { - if(!active){ - //minimize(); - } + if (!active) { + // minimize(); + } } void MainWindow::eventResize(SizeState sizeState) { - if(program == NULL) { - throw megaglest_runtime_error("In [MainWindow::eventResize] ERROR, program == NULL!"); - } + if (program == NULL) { + throw megaglest_runtime_error( + "In [MainWindow::eventResize] ERROR, program == NULL!"); + } - program->resize(sizeState); + program->resize(sizeState); } -void MainWindow::eventClose(){ - delete program; - program= NULL; +void MainWindow::eventClose() { + delete program; + program = NULL; } -void MainWindow::setProgram(Program *program) { - this->program= program; -} +void MainWindow::setProgram(Program *program) { this->program = program; } // ===================================================== // Main @@ -1435,4507 +1615,5364 @@ void MainWindow::setProgram(Program *program) { SystemFlags debugger; void print_SDL_version(const char *preamble, SDL_version *v) { - printf("%s %u.%u.%u\n", preamble, v->major, v->minor, v->patch); + printf("%s %u.%u.%u\n", preamble, v->major, v->minor, v->patch); } -int setupGameItemPaths(int argc, char** argv, Config *config) { - // Setup path cache for files and folders used in the game - std::map &pathCache = CacheManager::getCachedItem< std::map >(GameConstants::pathCacheLookupKey); - - Properties devProperties; - string devPropertyFile = Properties::getApplicationPath() + "glest-dev.ini"; - if(fileExists(devPropertyFile) == true) { - devProperties.load(devPropertyFile); - - if(devProperties.hasString("ServerListPath") == true) { - string devItem = devProperties.getString("ServerListPath"); - if(devItem != "") { - endPathWithSlash(devItem); - } - if(config != NULL) { - config->setString("ServerListPath",devItem,true); - } - } - - if(devProperties.hasString("GlestKeysIniPath") == true) { - string devItem = devProperties.getString("GlestKeysIniPath"); - if(devItem != "") { - endPathWithSlash(devItem); - } - if(config != NULL) { - config->setString("GlestKeysIniPath",devItem,true); - } - } - } - - //GAME_ARG_DATA_PATH - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_DATA_PATH]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_DATA_PATH]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_DATA_PATH]),&foundParamIndIndex); - } - string customPath = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(customPath,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string customPathValue = paramPartTokens[1]; - Properties::applyTagsToValue(customPathValue); - if(customPathValue != "") { - endPathWithSlash(customPathValue); - } - pathCache[GameConstants::path_data_CacheLookupKey] = customPathValue; - Properties::setApplicationDataPath(pathCache[GameConstants::path_data_CacheLookupKey]); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Using custom data path [%s]\n",customPathValue.c_str()); - } - else { - - printf("\nInvalid path specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - printParameterHelp(argv[0],false); - return 1; - } +int setupGameItemPaths(int argc, char **argv, Config *config) { + // Setup path cache for files and folders used in the game + std::map &pathCache = + CacheManager::getCachedItem>( + GameConstants::pathCacheLookupKey); + + Properties devProperties; + string devPropertyFile = Properties::getApplicationPath() + "glest-dev.ini"; + if (fileExists(devPropertyFile) == true) { + devProperties.load(devPropertyFile); + + if (devProperties.hasString("ServerListPath") == true) { + string devItem = devProperties.getString("ServerListPath"); + if (devItem != "") { + endPathWithSlash(devItem); + } + if (config != NULL) { + config->setString("ServerListPath", devItem, true); + } } - else if(config != NULL) { - bool foundPath = false; - string customPathValue = ""; + if (devProperties.hasString("GlestKeysIniPath") == true) { + string devItem = devProperties.getString("GlestKeysIniPath"); + if (devItem != "") { + endPathWithSlash(devItem); + } + if (config != NULL) { + config->setString("GlestKeysIniPath", devItem, true); + } + } + } - if(fileExists(devPropertyFile) == true && devProperties.hasString("DataPath") == true) { - foundPath = true; - customPathValue = devProperties.getString("DataPath",""); - } - else if(config->getString("DataPath","") != "") { - foundPath = true; - customPathValue = config->getString("DataPath",""); - } + // GAME_ARG_DATA_PATH + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_DATA_PATH]) == true) { + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_DATA_PATH]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_DATA_PATH]), + &foundParamIndIndex); + } + string customPath = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(customPath, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string customPathValue = paramPartTokens[1]; + Properties::applyTagsToValue(customPathValue); + if (customPathValue != "") { + endPathWithSlash(customPathValue); + } + pathCache[GameConstants::path_data_CacheLookupKey] = customPathValue; + Properties::setApplicationDataPath( + pathCache[GameConstants::path_data_CacheLookupKey]); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Using custom data path [%s]\n", customPathValue.c_str()); + } else { + + printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + printParameterHelp(argv[0], false); + return 1; + } + } else if (config != NULL) { + + bool foundPath = false; + string customPathValue = ""; + + if (fileExists(devPropertyFile) == true && + devProperties.hasString("DataPath") == true) { + foundPath = true; + customPathValue = devProperties.getString("DataPath", ""); + } else if (config->getString("DataPath", "") != "") { + foundPath = true; + customPathValue = config->getString("DataPath", ""); + } - if(foundPath == true) { - pathCache[GameConstants::path_data_CacheLookupKey] = customPathValue; + if (foundPath == true) { + pathCache[GameConstants::path_data_CacheLookupKey] = customPathValue; - if(customPathValue != "") { - endPathWithSlash(customPathValue); - } + if (customPathValue != "") { + endPathWithSlash(customPathValue); + } - Properties::setApplicationDataPath(pathCache[GameConstants::path_data_CacheLookupKey]); + Properties::setApplicationDataPath( + pathCache[GameConstants::path_data_CacheLookupKey]); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Using ini specified data path [%s]\n",config->getString("DataPath","").c_str()); - } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Using ini specified data path [%s]\n", + config->getString("DataPath", "").c_str()); } + } - //GAME_ARG_INI_PATH - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_INI_PATH]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_INI_PATH]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_INI_PATH]),&foundParamIndIndex); - } - string customPath = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(customPath,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string customPathValue = paramPartTokens[1]; - Properties::applyTagsToValue(customPathValue); - pathCache[GameConstants::path_ini_CacheLookupKey]=customPathValue; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Using custom ini path [%s]\n",customPathValue.c_str()); - } - else { - - printf("\nInvalid path specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - printParameterHelp(argv[0],false); - return 1; - } + // GAME_ARG_INI_PATH + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_INI_PATH]) == true) { + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_INI_PATH]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_INI_PATH]), + &foundParamIndIndex); + } + string customPath = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(customPath, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string customPathValue = paramPartTokens[1]; + Properties::applyTagsToValue(customPathValue); + pathCache[GameConstants::path_ini_CacheLookupKey] = customPathValue; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Using custom ini path [%s]\n", customPathValue.c_str()); + } else { + + printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + printParameterHelp(argv[0], false); + return 1; } + } - //GAME_ARG_LOG_PATH - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LOG_PATH]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_LOG_PATH]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_LOG_PATH]),&foundParamIndIndex); - } - string customPath = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(customPath,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string customPathValue = paramPartTokens[1]; - Properties::applyTagsToValue(customPathValue); - pathCache[GameConstants::path_logs_CacheLookupKey]=customPathValue; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Using custom logs path [%s]\n",customPathValue.c_str()); - } - else { - - printf("\nInvalid path specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - printParameterHelp(argv[0],false); - return 1; - } + // GAME_ARG_LOG_PATH + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LOG_PATH]) == true) { + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_LOG_PATH]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_LOG_PATH]), + &foundParamIndIndex); } - else if(config != NULL) { - - bool foundPath = false; - string customPathValue = ""; - - if(fileExists(devPropertyFile) == true && devProperties.hasString("LogPath") == true) { - foundPath = true; - customPathValue = devProperties.getString("LogPath",""); - } - else if(config->getString("LogPath","") != "") { - foundPath = true; - customPathValue = config->getString("LogPath",""); - } - - if(foundPath == true) { - pathCache[GameConstants::path_logs_CacheLookupKey] = customPathValue; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Using ini specified logs path [%s]\n",config->getString("LogPath","").c_str()); - } + string customPath = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(customPath, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string customPathValue = paramPartTokens[1]; + Properties::applyTagsToValue(customPathValue); + pathCache[GameConstants::path_logs_CacheLookupKey] = customPathValue; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Using custom logs path [%s]\n", customPathValue.c_str()); + } else { + + printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + printParameterHelp(argv[0], false); + return 1; + } + } else if (config != NULL) { + + bool foundPath = false; + string customPathValue = ""; + + if (fileExists(devPropertyFile) == true && + devProperties.hasString("LogPath") == true) { + foundPath = true; + customPathValue = devProperties.getString("LogPath", ""); + } else if (config->getString("LogPath", "") != "") { + foundPath = true; + customPathValue = config->getString("LogPath", ""); } - Text::DEFAULT_FONT_PATH = pathCache[GameConstants::path_data_CacheLookupKey]; - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_FONT_PATH]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_FONT_PATH]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_FONT_PATH]),&foundParamIndIndex); - } - string customPath = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(customPath,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string customPathValue = paramPartTokens[1]; - Properties::applyTagsToValue(customPathValue); - - Text::DEFAULT_FONT_PATH_ABSOLUTE = customPathValue; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Using custom fonts path [%s]\n",customPathValue.c_str()); - } - else { + if (foundPath == true) { + pathCache[GameConstants::path_logs_CacheLookupKey] = customPathValue; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Using ini specified logs path [%s]\n", + config->getString("LogPath", "").c_str()); + } + } - printf("\nInvalid path specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - printParameterHelp(argv[0],false); - return 1; - } + Text::DEFAULT_FONT_PATH = pathCache[GameConstants::path_data_CacheLookupKey]; + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_FONT_PATH]) == true) { + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_FONT_PATH]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_FONT_PATH]), + &foundParamIndIndex); } + string customPath = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(customPath, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string customPathValue = paramPartTokens[1]; + Properties::applyTagsToValue(customPathValue); + + Text::DEFAULT_FONT_PATH_ABSOLUTE = customPathValue; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Using custom fonts path [%s]\n", customPathValue.c_str()); + } else { + + printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + printParameterHelp(argv[0], false); + return 1; + } + } - return 0; + return 0; } void setupLogging(Config &config, bool haveSpecialOutputCommandLineOption) { - SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled = config.getBool("DebugMode","false"); - SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled = config.getBool("DebugNetwork","false"); - SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled = config.getBool("DebugPerformance","false"); - SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled = config.getBool("DebugWorldSynch","false"); - SystemFlags::getSystemSettingType(SystemFlags::debugUnitCommands).enabled = config.getBool("DebugUnitCommands","false"); - SystemFlags::getSystemSettingType(SystemFlags::debugPathFinder).enabled = config.getBool("DebugPathFinder","false"); - SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled = config.getBool("DebugLUA","false"); - LuaScript::setDebugModeEnabled(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled); - SystemFlags::getSystemSettingType(SystemFlags::debugSound).enabled = config.getBool("DebugSound","false"); - SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled = config.getBool("DebugError","true"); + SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled = + config.getBool("DebugMode", "false"); + SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled = + config.getBool("DebugNetwork", "false"); + SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled = + config.getBool("DebugPerformance", "false"); + SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled = + config.getBool("DebugWorldSynch", "false"); + SystemFlags::getSystemSettingType(SystemFlags::debugUnitCommands).enabled = + config.getBool("DebugUnitCommands", "false"); + SystemFlags::getSystemSettingType(SystemFlags::debugPathFinder).enabled = + config.getBool("DebugPathFinder", "false"); + SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled = + config.getBool("DebugLUA", "false"); + LuaScript::setDebugModeEnabled( + SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled); + SystemFlags::getSystemSettingType(SystemFlags::debugSound).enabled = + config.getBool("DebugSound", "false"); + SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled = + config.getBool("DebugError", "true"); + + string userData = config.getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } - string userData = config.getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); +#ifdef HAVE_GOOGLE_BREAKPAD + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("#1 In setting up errorHandlerPtr->set_dump_path [%p]...\n", + errorHandlerPtr.get()); + if (errorHandlerPtr.get() != NULL) { + string dumpFilePath; + if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { + dumpFilePath = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey); + } else { + dumpFilePath = userData; } -#ifdef HAVE_GOOGLE_BREAKPAD - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("#1 In setting up errorHandlerPtr->set_dump_path [%p]...\n",errorHandlerPtr.get()); - if(errorHandlerPtr.get() != NULL) { - string dumpFilePath; - if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - dumpFilePath = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey); - } - else { - dumpFilePath = userData; - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("#2 In setting up errorHandlerPtr->set_dump_path...\n"); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("#2 In setting up errorHandlerPtr->set_dump_path...\n"); #if defined(WIN32) - wstring dumpfilepath = utf8_decode(dumpFilePath); - if(SystemFlags::VERBOSE_MODE_ENABLED) wprintf(L"Hooking up google_breakpad::ExceptionHandler to save dmp files to [%s]...\n",dumpfilepath.c_str()); - errorHandlerPtr->set_dump_path(dumpfilepath); + wstring dumpfilepath = utf8_decode(dumpFilePath); + if (SystemFlags::VERBOSE_MODE_ENABLED) + wprintf(L"Hooking up google_breakpad::ExceptionHandler to save dmp files " + L"to [%s]...\n", + dumpfilepath.c_str()); + errorHandlerPtr->set_dump_path(dumpfilepath); #else - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Hooking up google_breakpad::ExceptionHandler to save dmp files to [%s]...\n",dumpFilePath.c_str()); - //errorHandlerPtr->set_dump_path(dumpfilepath); - google_breakpad::MinidumpDescriptor descriptor(dumpFilePath); - errorHandlerPtr->set_minidump_descriptor(descriptor); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Hooking up google_breakpad::ExceptionHandler to save dmp files " + "to [%s]...\n", + dumpFilePath.c_str()); + // errorHandlerPtr->set_dump_path(dumpfilepath); + google_breakpad::MinidumpDescriptor descriptor(dumpFilePath); + errorHandlerPtr->set_minidump_descriptor(descriptor); #endif - - } + } #endif - string debugLogFile = config.getString("DebugLogFile",""); - if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - debugLogFile = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + debugLogFile; - } - else { - debugLogFile = userData + debugLogFile; - } + string debugLogFile = config.getString("DebugLogFile", ""); + if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { + debugLogFile = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + + debugLogFile; + } else { + debugLogFile = userData + debugLogFile; + } - string debugWorldSynchLogFile = config.getString("DebugLogFileWorldSynch",""); - if(debugWorldSynchLogFile == "") { - debugWorldSynchLogFile = debugLogFile; - } - else if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - debugWorldSynchLogFile = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + debugWorldSynchLogFile; - } - else { - debugWorldSynchLogFile = userData + debugWorldSynchLogFile; - } + string debugWorldSynchLogFile = + config.getString("DebugLogFileWorldSynch", ""); + if (debugWorldSynchLogFile == "") { + debugWorldSynchLogFile = debugLogFile; + } else if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != + "") { + debugWorldSynchLogFile = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + + debugWorldSynchLogFile; + } else { + debugWorldSynchLogFile = userData + debugWorldSynchLogFile; + } - string debugPerformanceLogFile = config.getString("DebugLogFilePerformance",""); - if(debugPerformanceLogFile == "") { - debugPerformanceLogFile = debugLogFile; - } - else if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - debugPerformanceLogFile = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + debugPerformanceLogFile; - } - else { - debugPerformanceLogFile = userData + debugPerformanceLogFile; - } + string debugPerformanceLogFile = + config.getString("DebugLogFilePerformance", ""); + if (debugPerformanceLogFile == "") { + debugPerformanceLogFile = debugLogFile; + } else if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != + "") { + debugPerformanceLogFile = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + + debugPerformanceLogFile; + } else { + debugPerformanceLogFile = userData + debugPerformanceLogFile; + } - string debugNetworkLogFile = config.getString("DebugLogFileNetwork",""); - if(debugNetworkLogFile == "") { - debugNetworkLogFile = debugLogFile; - } - else if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - debugNetworkLogFile = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + debugNetworkLogFile; - } - else { - debugNetworkLogFile = userData + debugNetworkLogFile; - } + string debugNetworkLogFile = config.getString("DebugLogFileNetwork", ""); + if (debugNetworkLogFile == "") { + debugNetworkLogFile = debugLogFile; + } else if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != + "") { + debugNetworkLogFile = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + + debugNetworkLogFile; + } else { + debugNetworkLogFile = userData + debugNetworkLogFile; + } - string debugUnitCommandsLogFile = config.getString("DebugLogFileUnitCommands",""); - if(debugUnitCommandsLogFile == "") { - debugUnitCommandsLogFile = debugLogFile; - } - else if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - debugUnitCommandsLogFile = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + debugUnitCommandsLogFile; - } - else { - debugUnitCommandsLogFile = userData + debugUnitCommandsLogFile; + string debugUnitCommandsLogFile = + config.getString("DebugLogFileUnitCommands", ""); + if (debugUnitCommandsLogFile == "") { + debugUnitCommandsLogFile = debugLogFile; + } else if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != + "") { + debugUnitCommandsLogFile = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + + debugUnitCommandsLogFile; + } else { + debugUnitCommandsLogFile = userData + debugUnitCommandsLogFile; + } + + string debugPathFinderLogFile = + config.getString("DebugLogFilePathFinder", ""); + if (debugPathFinderLogFile == "") { + debugPathFinderLogFile = debugLogFile; + } else if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != + "") { + debugPathFinderLogFile = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + + debugPathFinderLogFile; + } else { + debugPathFinderLogFile = userData + debugPathFinderLogFile; + } + + string debugLUALogFile = config.getString("DebugLogFileLUA", ""); + if (debugLUALogFile == "") { + debugLUALogFile = debugLogFile; + } else if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != + "") { + debugLUALogFile = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + + debugLUALogFile; + } else { + debugLUALogFile = userData + debugLUALogFile; + } + + string debugSoundLogFile = config.getString("DebugLogFileSound", ""); + if (debugSoundLogFile == "") { + debugSoundLogFile = debugLogFile; + } else if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != + "") { + debugSoundLogFile = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + + debugSoundLogFile; + } else { + debugSoundLogFile = userData + debugSoundLogFile; + } + + string debugErrorLogFile = config.getString("DebugLogFileError", ""); + + SystemFlags::getSystemSettingType(SystemFlags::debugSystem).debugLogFileName = + debugLogFile; + SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .debugLogFileName = debugNetworkLogFile; + SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .debugLogFileName = debugPerformanceLogFile; + SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .debugLogFileName = debugWorldSynchLogFile; + SystemFlags::getSystemSettingType(SystemFlags::debugUnitCommands) + .debugLogFileName = debugUnitCommandsLogFile; + SystemFlags::getSystemSettingType(SystemFlags::debugPathFinder) + .debugLogFileName = debugPathFinderLogFile; + SystemFlags::getSystemSettingType(SystemFlags::debugLUA).debugLogFileName = + debugLUALogFile; + SystemFlags::getSystemSettingType(SystemFlags::debugSound).debugLogFileName = + debugSoundLogFile; + SystemFlags::getSystemSettingType(SystemFlags::debugError).debugLogFileName = + debugErrorLogFile; + + if (haveSpecialOutputCommandLineOption == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf( + "--- Startup log settings are ---\ndebugSystem " + "[%d][%s]\ndebugNetwork [%d][%s]\ndebugPerformance " + "[%d][%s]\ndebugWorldSynch " + "[%d][%s]\ndebugUnitCommands[%d][%s]\ndebugPathFinder[%d][%s]" + "\ndebugLUA [%d][%s]\ndebugSound [%d][%s]\ndebugError [%d][%s]\n", + SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled, + debugLogFile.c_str(), + SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled, + debugNetworkLogFile.c_str(), + SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled, + debugPerformanceLogFile.c_str(), + SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled, + debugWorldSynchLogFile.c_str(), + SystemFlags::getSystemSettingType(SystemFlags::debugUnitCommands) + .enabled, + debugUnitCommandsLogFile.c_str(), + SystemFlags::getSystemSettingType(SystemFlags::debugPathFinder) + .enabled, + debugPathFinderLogFile.c_str(), + SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled, + debugLUALogFile.c_str(), + SystemFlags::getSystemSettingType(SystemFlags::debugSound).enabled, + debugSoundLogFile.c_str(), + SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled, + debugErrorLogFile.c_str()); + } +} + +void runTilesetValidationForPath(string tilesetPath, string tilesetName, + World &world, bool purgeUnusedFiles, + bool purgeDuplicateFiles, + bool showDuplicateFiles, bool gitPurgeFiles, + double &purgedMegaBytes) { + Checksum checksum; + + // bool techtree_errors = false; + + std::map>> loadedFileList; + vector pathList; + pathList.push_back(tilesetPath); + world.loadTileset(pathList, tilesetName, &checksum, loadedFileList); + + // Fixup paths with .. + { + std::map>> newLoadedFileList; + for (std::map>>::iterator iterMap = + loadedFileList.begin(); + iterMap != loadedFileList.end(); ++iterMap) { + string loadedFile = iterMap->first; + + replaceAll(loadedFile, "//", "/"); + replaceAll(loadedFile, "\\\\", "\\"); + updatePathClimbingParts(loadedFile); + + if (newLoadedFileList.find(loadedFile) != newLoadedFileList.end()) { + for (unsigned int xx1 = 0; xx1 < iterMap->second.size(); ++xx1) { + pair &newVal = iterMap->second[xx1]; + replaceAll(newVal.first, "//", "/"); + replaceAll(newVal.first, "\\\\", "\\"); + updatePathClimbingParts(newVal.first); + replaceAll(newVal.second, "//", "/"); + replaceAll(newVal.second, "\\\\", "\\"); + updatePathClimbingParts(newVal.second); + + newLoadedFileList[loadedFile].push_back(newVal); + } + } else { + for (unsigned int xx1 = 0; xx1 < iterMap->second.size(); ++xx1) { + pair &newVal = iterMap->second[xx1]; + replaceAll(newVal.first, "//", "/"); + replaceAll(newVal.first, "\\\\", "\\"); + updatePathClimbingParts(newVal.first); + replaceAll(newVal.second, "//", "/"); + replaceAll(newVal.second, "\\\\", "\\"); + updatePathClimbingParts(newVal.second); + } + + newLoadedFileList[loadedFile] = iterMap->second; + } } + loadedFileList = newLoadedFileList; + } + + // Validate the faction setup to ensure we don't have any bad associations + // std::vector resultErrors = + // world.validateFactionTypes(); - string debugPathFinderLogFile = config.getString("DebugLogFilePathFinder",""); - if(debugPathFinderLogFile == "") { - debugPathFinderLogFile = debugLogFile; + // Now check for unused files in the techtree + std::map>> foundFileList; + for (unsigned int i = 0; i < pathList.size(); ++i) { + string path = pathList[i]; + endPathWithSlash(path); + path = path + tilesetName + "/"; + + replaceAll(path, "//", "/"); + replaceAll(path, "\\\\", "\\"); + + vector foundFiles = + getFolderTreeContentsListRecursively(path + "*.", ""); + for (unsigned int j = 0; j < foundFiles.size(); ++j) { + string file = foundFiles[j]; + replaceAll(file, "//", "/"); + replaceAll(file, "\\\\", "\\"); + + replaceAll(file, "//", "/"); + replaceAll(file, "\\\\", "\\"); + + foundFileList[file].push_back(make_pair(path, path)); } - else if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - debugPathFinderLogFile = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + debugPathFinderLogFile; + } + + printf("Found tileset filecount = " MG_SIZE_T_SPECIFIER + ", used = " MG_SIZE_T_SPECIFIER "\n", + foundFileList.size(), loadedFileList.size()); + + int purgeCount = 0; + bool foundUnusedFile = false; + for (std::map>>::iterator iterMap = + foundFileList.begin(); + iterMap != foundFileList.end(); ++iterMap) { + string foundFile = iterMap->first; + replaceAll(foundFile, "//", "/"); + replaceAll(foundFile, "\\\\", "\\"); + + if (loadedFileList.find(foundFile) == loadedFileList.end() && + foundFile.find("lang/") == foundFile.npos) { + if (foundUnusedFile == false) { + printf("\nLine ref: %d, Warning, unused files were detected - " + "START:\n=====================\n", + __LINE__); + } + foundUnusedFile = true; + + printf("[%s]\n", foundFile.c_str()); + + string fileName = extractFileFromDirectoryPath(foundFile); + if (loadedFileList.find(fileName) != loadedFileList.end()) { + printf("possible match on [%s] ?\n", + loadedFileList.find(fileName)->first.c_str()); + } else if (purgeUnusedFiles == true) { + off_t fileSize = getFileSize(foundFile); + // convert to MB + purgedMegaBytes += ((double)fileSize / 1048576.0); + purgeCount++; + + if (gitPurgeFiles == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "git rm \"%s\"", foundFile.c_str()); + bool gitOk = executeShellCommand(szBuf, 0); + if (gitOk == false) { + throw megaglest_runtime_error("Call to command failed [" + + string(szBuf) + "]"); + } + } else { + removeFile(foundFile); + } + } } - else { - debugPathFinderLogFile = userData + debugPathFinderLogFile; + } + if (foundUnusedFile == true) { + if (purgedMegaBytes > 0) { + printf("Purged %.2f MB (%d) in files\n", purgedMegaBytes, purgeCount); } + printf("\nLine ref: %d, Warning, unused files were detected - END:\n", + __LINE__); + } - string debugLUALogFile = config.getString("DebugLogFileLUA",""); - if(debugLUALogFile == "") { - debugLUALogFile = debugLogFile; + if (showDuplicateFiles == true) { + std::map> mapDuplicateFiles; + // Now check for duplicate data content + for (std::map>>::iterator iterMap = + loadedFileList.begin(); + iterMap != loadedFileList.end(); ++iterMap) { + string fileName = iterMap->first; + Checksum checksum; + checksum.addFile(fileName); + uint32 crcValue = checksum.getSum(); + mapDuplicateFiles[crcValue].push_back(fileName); } - else if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - debugLUALogFile = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + debugLUALogFile; - } - else { - debugLUALogFile = userData + debugLUALogFile; + + double duplicateMegaBytesPurged = 0; + int duplicateCountPurged = 0; + + double duplicateMegaBytes = 0; + int duplicateCount = 0; + + bool foundDuplicates = false; + for (std::map>::iterator iterMap = + mapDuplicateFiles.begin(); + iterMap != mapDuplicateFiles.end(); ++iterMap) { + vector &fileList = iterMap->second; + if (fileList.size() > 1) { + if (foundDuplicates == false) { + foundDuplicates = true; + printf("\nWarning, duplicate files were detected - " + "START:\n=====================\n"); + } + + map parentList; + for (unsigned int idx = 0; idx < fileList.size(); ++idx) { + string duplicateFile = fileList[idx]; + if (idx > 0) { + off_t fileSize = getFileSize(duplicateFile); + // convert to MB + duplicateMegaBytes += ((double)fileSize / 1048576.0); + duplicateCount++; + } else { + printf("\n"); + } + + printf("[%s]\n", duplicateFile.c_str()); + std::map>>::iterator iterFind = + loadedFileList.find(duplicateFile); + if (iterFind != loadedFileList.end()) { + for (unsigned int jdx = 0; jdx < iterFind->second.size(); jdx++) { + parentList[iterFind->second[jdx].first]++; + } + } + } + + for (map::iterator iterMap1 = parentList.begin(); + iterMap1 != parentList.end(); ++iterMap1) { + + if (iterMap1 == parentList.begin()) { + printf("\tParents:\n"); + } + printf("\t[%s]\n", iterMap1->first.c_str()); + } + + if (purgeDuplicateFiles == true) { + + string newCommonFileName = ""; + for (unsigned int idx = 0; idx < fileList.size(); ++idx) { + string duplicateFile = fileList[idx]; + string fileExt = extractExtension(duplicateFile); + if (fileExt == "wav" || fileExt == "ogg") { + off_t fileSize = getFileSize(duplicateFile); + if (idx == 0) { + newCommonFileName = "$COMMONDATAPATH/sounds/" + + extractFileFromDirectoryPath(duplicateFile); + + string expandedNewCommonFileName = newCommonFileName; + + std::map mapExtraTagReplacementValues; + + mapExtraTagReplacementValues = + Properties::getTagReplacementValues( + &mapExtraTagReplacementValues); + Properties::applyTagsToValue(expandedNewCommonFileName, + &mapExtraTagReplacementValues); + replaceAll(expandedNewCommonFileName, "//", "/"); + createDirectoryPaths( + extractDirectoryPathFromFile(expandedNewCommonFileName)); + + if (gitPurgeFiles == true) { + copyFileTo(duplicateFile, expandedNewCommonFileName); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "git rm \"%s\"", duplicateFile.c_str()); + bool gitOk = executeShellCommand(szBuf, 0); + if (gitOk == false) { + throw megaglest_runtime_error("Call to command failed [" + + string(szBuf) + "]"); + } + printf("*** Duplicate file:\n[%s]\nwas git rm and copied " + "to:\n[%s]\n", + duplicateFile.c_str(), + expandedNewCommonFileName.c_str()); + } else { + // int result = 0; + int result = rename(duplicateFile.c_str(), + expandedNewCommonFileName.c_str()); + if (result != 0) { + char szBuf[8096] = ""; + char *errmsg = strerror(errno); + snprintf(szBuf, 8096, + "!!! Error [%s] Could not rename [%s] to [%s]!", + errmsg, duplicateFile.c_str(), + expandedNewCommonFileName.c_str()); + throw megaglest_runtime_error(szBuf); + } else { + printf("*** Duplicate file:\n[%s]\nwas renamed to:\n[%s]\n", + duplicateFile.c_str(), + expandedNewCommonFileName.c_str()); + } + } + } else { + if (gitPurgeFiles == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "git rm \"%s\"", duplicateFile.c_str()); + bool gitOk = executeShellCommand(szBuf, 0); + if (gitOk == false) { + throw megaglest_runtime_error("Call to command failed [" + + string(szBuf) + "]"); + } + printf("*** Duplicate file:\n[%s]\nwas git rm\n", + duplicateFile.c_str()); + } else { + removeFile(duplicateFile); + } + printf("*** Duplicate file:\n[%s]\nwas removed\n", + duplicateFile.c_str()); + + // convert to MB + duplicateMegaBytesPurged += ((double)fileSize / 1048576.0); + duplicateCountPurged++; + } + } + } + + std::map mapUniqueParentList; + + for (unsigned int idx = 0; idx < fileList.size(); ++idx) { + string duplicateFile = fileList[idx]; + string fileExt = extractExtension(duplicateFile); + if (fileExt == "wav" || fileExt == "ogg") { + std::map>>::iterator + iterFind2 = loadedFileList.find(duplicateFile); + if (iterFind2 != loadedFileList.end()) { + for (unsigned int jdx1 = 0; jdx1 < iterFind2->second.size(); + jdx1++) { + string parentFile = iterFind2->second[jdx1].first; + string searchText = iterFind2->second[jdx1].second; + + if (mapUniqueParentList.find(parentFile) == + mapUniqueParentList.end()) { + printf( + "*** Searching parent file:\n[%s]\nfor duplicate file " + "reference:\n[%s]\nto replace with newname:\n[%s]\n", + parentFile.c_str(), searchText.c_str(), + newCommonFileName.c_str()); + bool foundText = searchAndReplaceTextInFile( + parentFile, searchText, newCommonFileName, false); + printf("foundText = %d\n", foundText); + if (foundText == false) { + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "Line ref = %d, Error finding text [%s] in file [%s]", + __LINE__, searchText.c_str(), parentFile.c_str()); + throw megaglest_runtime_error(szBuf); + } + mapUniqueParentList[parentFile]++; + } + } + } + } + } + } else { + string newCommonFileName = ""; + for (unsigned int idx = 0; idx < fileList.size(); ++idx) { + string duplicateFile = fileList[idx]; + string fileExt = extractExtension(duplicateFile); + if (fileExt == "wav" || fileExt == "ogg") { + // off_t fileSize = getFileSize(duplicateFile); + if (idx == 0) { + newCommonFileName = "$COMMONDATAPATH/sounds/" + + extractFileFromDirectoryPath(duplicateFile); + break; + } + } + } + + for (unsigned int idx = 0; idx < fileList.size(); ++idx) { + string duplicateFile = fileList[idx]; + string fileExt = extractExtension(duplicateFile); + if (fileExt == "wav" || fileExt == "ogg") { + std::map>>::iterator + iterFind4 = loadedFileList.find(duplicateFile); + if (iterFind4 != loadedFileList.end()) { + for (unsigned int jdx = 0; jdx < iterFind4->second.size(); + jdx++) { + string parentFile = iterFind4->second[jdx].first; + string searchText = iterFind4->second[jdx].second; + + bool foundText = searchAndReplaceTextInFile( + parentFile, searchText, newCommonFileName, true); + if (foundText == false) { + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "Line ref = %d, Error finding text\n[%s]\nin " + "file\n[%s]\nnew Common File [%s]\n", + __LINE__, searchText.c_str(), parentFile.c_str(), + newCommonFileName.c_str()); + printf("\n\n===============================================" + "==\n%s", + szBuf); + + throw megaglest_runtime_error(szBuf); + } + } + } + } + } + } + } } + if (foundDuplicates == true) { + printf("Duplicates %.2f MB (%d) in files\n", duplicateMegaBytes, + duplicateCount); + printf("Duplicates purged %.2f MB (%d) in files\n", + duplicateMegaBytesPurged, duplicateCountPurged); - string debugSoundLogFile = config.getString("DebugLogFileSound",""); - if(debugSoundLogFile == "") { - debugSoundLogFile = debugLogFile; + printf("\nWarning, duplicate files were detected - END:\n"); } - else if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - debugSoundLogFile = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + debugSoundLogFile; + } + + // if(techtree_errors == false) { + printf( + "\nValidation found NO ERRORS for tilesetPath [%s] tilesetName [%s]:\n", + tilesetPath.c_str(), tilesetName.c_str()); + //} + + printf("----------------------------------------------------------------"); +} + +void runTechValidationForPath(string techPath, string techName, + const std::vector &filteredFactionList, + World &world, bool purgeUnusedFiles, + bool purgeDuplicateFiles, bool showDuplicateFiles, + bool gitPurgeFiles, double &purgedMegaBytes) { + + string techTreeFolder = techPath + techName; + string techTreeFactionFolder = techTreeFolder + "/factions/"; + vector factionsList; + findDirs(techTreeFactionFolder, factionsList, false, false); + + if (factionsList.empty() == false) { + Checksum checksum; + set factions; + for (int j = 0; j < (int)factionsList.size(); ++j) { + if (filteredFactionList.empty() == true || + std::find(filteredFactionList.begin(), filteredFactionList.end(), + factionsList[j]) != filteredFactionList.end()) { + factions.insert(factionsList[j]); + } } - else { - debugSoundLogFile = userData + debugSoundLogFile; + + printf( + "\n----------------------------------------------------------------"); + printf("\nChecking techPath [%s] techName [%s] total faction count = %d\n", + techPath.c_str(), techName.c_str(), (int)factionsList.size()); + for (int j = 0; j < (int)factionsList.size(); ++j) { + if (filteredFactionList.empty() == true || + std::find(filteredFactionList.begin(), filteredFactionList.end(), + factionsList[j]) != filteredFactionList.end()) { + printf("Using faction [%s]\n", factionsList[j].c_str()); + } } - string debugErrorLogFile = config.getString("DebugLogFileError",""); + if (factions.empty() == false) { + bool techtree_errors = false; + + std::map>> loadedFileList; + vector pathList; + pathList.push_back(techPath); + Config &config = Config::getInstance(); + vector otherTechPaths = config.getPathListForType(ptTechs, ""); + pathList.insert(pathList.end(), otherTechPaths.begin(), + otherTechPaths.end()); + + try { + world.loadTech(pathList, techName, factions, &checksum, loadedFileList, + true); + + // Fixup paths with .. + { + std::map>> newLoadedFileList; + for (std::map>>::iterator + iterMap = loadedFileList.begin(); + iterMap != loadedFileList.end(); ++iterMap) { + string loadedFile = iterMap->first; + + replaceAll(loadedFile, "//", "/"); + replaceAll(loadedFile, "\\\\", "\\"); + updatePathClimbingParts(loadedFile); + + if (newLoadedFileList.find(loadedFile) != newLoadedFileList.end()) { + for (unsigned int xx1 = 0; xx1 < iterMap->second.size(); ++xx1) { + pair &newVal = iterMap->second[xx1]; + replaceAll(newVal.first, "//", "/"); + replaceAll(newVal.first, "\\\\", "\\"); + updatePathClimbingParts(newVal.first); + replaceAll(newVal.second, "//", "/"); + replaceAll(newVal.second, "\\\\", "\\"); + updatePathClimbingParts(newVal.second); + + newLoadedFileList[loadedFile].push_back(newVal); + } + } else { + for (unsigned int xx1 = 0; xx1 < iterMap->second.size(); ++xx1) { + pair &newVal = iterMap->second[xx1]; + replaceAll(newVal.first, "//", "/"); + replaceAll(newVal.first, "\\\\", "\\"); + updatePathClimbingParts(newVal.first); + replaceAll(newVal.second, "//", "/"); + replaceAll(newVal.second, "\\\\", "\\"); + updatePathClimbingParts(newVal.second); + } + + newLoadedFileList[loadedFile] = iterMap->second; + } + } + loadedFileList = newLoadedFileList; + } - SystemFlags::getSystemSettingType(SystemFlags::debugSystem).debugLogFileName = debugLogFile; - SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).debugLogFileName = debugNetworkLogFile; - SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).debugLogFileName = debugPerformanceLogFile; - SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).debugLogFileName = debugWorldSynchLogFile; - SystemFlags::getSystemSettingType(SystemFlags::debugUnitCommands).debugLogFileName = debugUnitCommandsLogFile; - SystemFlags::getSystemSettingType(SystemFlags::debugPathFinder).debugLogFileName = debugPathFinderLogFile; - SystemFlags::getSystemSettingType(SystemFlags::debugLUA).debugLogFileName = debugLUALogFile; - SystemFlags::getSystemSettingType(SystemFlags::debugSound).debugLogFileName = debugSoundLogFile; - SystemFlags::getSystemSettingType(SystemFlags::debugError).debugLogFileName = debugErrorLogFile; + // Validate the faction setup to ensure we don't have any bad + // associations + std::vector resultErrors = world.validateFactionTypes(); + if (resultErrors.empty() == false) { + techtree_errors = true; + // Display the validation errors + string errorText = "\nErrors were detected:\n=====================\n"; + for (int i = 0; i < (int)resultErrors.size(); ++i) { + if (i > 0) { + errorText += "\n"; + } + errorText = errorText + resultErrors[i]; + } + errorText += "\n=====================\n"; + printf("%s", errorText.c_str()); + } - if(haveSpecialOutputCommandLineOption == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("--- Startup log settings are ---\ndebugSystem [%d][%s]\ndebugNetwork [%d][%s]\ndebugPerformance [%d][%s]\ndebugWorldSynch [%d][%s]\ndebugUnitCommands[%d][%s]\ndebugPathFinder[%d][%s]\ndebugLUA [%d][%s]\ndebugSound [%d][%s]\ndebugError [%d][%s]\n", - SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled, - debugLogFile.c_str(), - SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled, - debugNetworkLogFile.c_str(), - SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled, - debugPerformanceLogFile.c_str(), - SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled, - debugWorldSynchLogFile.c_str(), - SystemFlags::getSystemSettingType(SystemFlags::debugUnitCommands).enabled, - debugUnitCommandsLogFile.c_str(), - SystemFlags::getSystemSettingType(SystemFlags::debugPathFinder).enabled, - debugPathFinderLogFile.c_str(), - SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled, - debugLUALogFile.c_str(), - SystemFlags::getSystemSettingType(SystemFlags::debugSound).enabled, - debugSoundLogFile.c_str(), - SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled, - debugErrorLogFile.c_str()); - } -} + // Validate the faction resource setup to ensure we don't have any bad + // associations + printf("\nChecking resources, count = %d\n", + world.getTechTree()->getResourceTypeCount()); -void runTilesetValidationForPath(string tilesetPath, string tilesetName, - World &world, bool purgeUnusedFiles,bool purgeDuplicateFiles, - bool showDuplicateFiles, bool gitPurgeFiles,double &purgedMegaBytes) { - Checksum checksum; - - //bool techtree_errors = false; - - std::map > > loadedFileList; - vector pathList; - pathList.push_back(tilesetPath); - world.loadTileset(pathList, tilesetName,&checksum, loadedFileList); - - // Fixup paths with .. - { - std::map > > newLoadedFileList; - for( std::map > >::iterator iterMap = loadedFileList.begin(); - iterMap != loadedFileList.end(); ++iterMap) { - string loadedFile = iterMap->first; - - replaceAll(loadedFile,"//","/"); - replaceAll(loadedFile,"\\\\","\\"); - updatePathClimbingParts(loadedFile); - - if(newLoadedFileList.find(loadedFile) != newLoadedFileList.end()) { - for(unsigned int xx1 = 0; xx1 < iterMap->second.size(); ++xx1) { - pair &newVal = iterMap->second[xx1]; - replaceAll(newVal.first,"//","/"); - replaceAll(newVal.first,"\\\\","\\"); - updatePathClimbingParts(newVal.first); - replaceAll(newVal.second,"//","/"); - replaceAll(newVal.second,"\\\\","\\"); - updatePathClimbingParts(newVal.second); - - newLoadedFileList[loadedFile].push_back(newVal); - } - } - else { - for(unsigned int xx1 = 0; xx1 < iterMap->second.size(); ++xx1) { - pair &newVal = iterMap->second[xx1]; - replaceAll(newVal.first,"//","/"); - replaceAll(newVal.first,"\\\\","\\"); - updatePathClimbingParts(newVal.first); - replaceAll(newVal.second,"//","/"); - replaceAll(newVal.second,"\\\\","\\"); - updatePathClimbingParts(newVal.second); - } - - newLoadedFileList[loadedFile] = iterMap->second; - } - } - loadedFileList = newLoadedFileList; - } - - // Validate the faction setup to ensure we don't have any bad associations -// std::vector resultErrors = world.validateFactionTypes(); - - // Now check for unused files in the techtree - std::map > > foundFileList; - for(unsigned int i = 0; i < pathList.size(); ++i) { - string path = pathList[i]; - endPathWithSlash(path); - path = path + tilesetName + "/"; - - replaceAll(path, "//", "/"); - replaceAll(path, "\\\\", "\\"); - - vector foundFiles = getFolderTreeContentsListRecursively(path + "*.", ""); - for(unsigned int j = 0; j < foundFiles.size(); ++j) { - string file = foundFiles[j]; - replaceAll(file, "//", "/"); - replaceAll(file, "\\\\", "\\"); - - replaceAll(file,"//","/"); - replaceAll(file,"\\\\","\\"); - - foundFileList[file].push_back(make_pair(path,path)); - } - } - - printf("Found tileset filecount = " MG_SIZE_T_SPECIFIER ", used = " MG_SIZE_T_SPECIFIER "\n",foundFileList.size(),loadedFileList.size()); - - int purgeCount = 0; - bool foundUnusedFile = false; - for( std::map > >::iterator iterMap = foundFileList.begin(); - iterMap != foundFileList.end(); ++iterMap) { - string foundFile = iterMap->first; - replaceAll(foundFile, "//", "/"); - replaceAll(foundFile, "\\\\", "\\"); - - if(loadedFileList.find(foundFile) == loadedFileList.end() && - foundFile.find("lang/") == foundFile.npos) { - if(foundUnusedFile == false) { - printf("\nLine ref: %d, Warning, unused files were detected - START:\n=====================\n",__LINE__); - } - foundUnusedFile = true; - - printf("[%s]\n",foundFile.c_str()); - - string fileName = extractFileFromDirectoryPath(foundFile); - if(loadedFileList.find(fileName) != loadedFileList.end()) { - printf("possible match on [%s] ?\n",loadedFileList.find(fileName)->first.c_str()); - } - else if(purgeUnusedFiles == true) { - off_t fileSize = getFileSize(foundFile); - // convert to MB - purgedMegaBytes += ((double)fileSize / 1048576.0); - purgeCount++; - - if(gitPurgeFiles == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"git rm \"%s\"",foundFile.c_str()); - bool gitOk = executeShellCommand(szBuf,0); - if(gitOk == false) { - throw megaglest_runtime_error("Call to command failed [" + string(szBuf) + "]"); - } - } - else { - removeFile(foundFile); - } - } - } - } - if(foundUnusedFile == true) { - if(purgedMegaBytes > 0) { - printf("Purged %.2f MB (%d) in files\n",purgedMegaBytes,purgeCount); - } - printf("\nLine ref: %d, Warning, unused files were detected - END:\n",__LINE__); - } - - if(showDuplicateFiles == true) { - std::map > mapDuplicateFiles; - // Now check for duplicate data content - for(std::map > >::iterator iterMap = loadedFileList.begin(); - iterMap != loadedFileList.end(); ++iterMap) { - string fileName = iterMap->first; - Checksum checksum; - checksum.addFile(fileName); - uint32 crcValue = checksum.getSum(); - mapDuplicateFiles[crcValue].push_back(fileName); - } - - double duplicateMegaBytesPurged=0; - int duplicateCountPurged=0; - - double duplicateMegaBytes=0; - int duplicateCount=0; - - bool foundDuplicates = false; - for(std::map >::iterator iterMap = mapDuplicateFiles.begin(); - iterMap != mapDuplicateFiles.end(); ++iterMap) { - vector &fileList = iterMap->second; - if(fileList.size() > 1) { - if(foundDuplicates == false) { - foundDuplicates = true; - printf("\nWarning, duplicate files were detected - START:\n=====================\n"); - } - - map parentList; - for(unsigned int idx = 0; idx < fileList.size(); ++idx) { - string duplicateFile = fileList[idx]; - if(idx > 0) { - off_t fileSize = getFileSize(duplicateFile); - // convert to MB - duplicateMegaBytes += ((double)fileSize / 1048576.0); - duplicateCount++; - } - else { - printf("\n"); - } - - printf("[%s]\n",duplicateFile.c_str()); - std::map > >::iterator iterFind = loadedFileList.find(duplicateFile); - if(iterFind != loadedFileList.end()) { - for(unsigned int jdx = 0; jdx < iterFind->second.size(); jdx++) { - parentList[iterFind->second[jdx].first]++; - } - } - } - - for(map::iterator iterMap1 = parentList.begin(); - iterMap1 != parentList.end(); ++iterMap1) { - - if(iterMap1 == parentList.begin()) { - printf("\tParents:\n"); - } - printf("\t[%s]\n",iterMap1->first.c_str()); - } - - if(purgeDuplicateFiles == true) { - - string newCommonFileName = ""; - for(unsigned int idx = 0; idx < fileList.size(); ++idx) { - string duplicateFile = fileList[idx]; - string fileExt = extractExtension(duplicateFile); - if(fileExt == "wav" || fileExt == "ogg") { - off_t fileSize = getFileSize(duplicateFile); - if(idx == 0) { - newCommonFileName = "$COMMONDATAPATH/sounds/" + extractFileFromDirectoryPath(duplicateFile); - - string expandedNewCommonFileName = newCommonFileName; - - std::map mapExtraTagReplacementValues; - - mapExtraTagReplacementValues = Properties::getTagReplacementValues(&mapExtraTagReplacementValues); - Properties::applyTagsToValue(expandedNewCommonFileName,&mapExtraTagReplacementValues); - replaceAll(expandedNewCommonFileName, "//", "/"); - createDirectoryPaths(extractDirectoryPathFromFile(expandedNewCommonFileName)); - - if(gitPurgeFiles == true) { - copyFileTo(duplicateFile, expandedNewCommonFileName); - - char szBuf[8096]=""; - snprintf(szBuf,8096,"git rm \"%s\"",duplicateFile.c_str()); - bool gitOk = executeShellCommand(szBuf,0); - if(gitOk == false) { - throw megaglest_runtime_error("Call to command failed [" + string(szBuf) + "]"); - } - printf("*** Duplicate file:\n[%s]\nwas git rm and copied to:\n[%s]\n",duplicateFile.c_str(),expandedNewCommonFileName.c_str()); - } - else { - //int result = 0; - int result = rename(duplicateFile.c_str(),expandedNewCommonFileName.c_str()); - if(result != 0) { - char szBuf[8096]=""; - char *errmsg = strerror(errno); - snprintf(szBuf,8096,"!!! Error [%s] Could not rename [%s] to [%s]!",errmsg,duplicateFile.c_str(),expandedNewCommonFileName.c_str()); - throw megaglest_runtime_error(szBuf); - } - else { - printf("*** Duplicate file:\n[%s]\nwas renamed to:\n[%s]\n",duplicateFile.c_str(),expandedNewCommonFileName.c_str()); - } - } - } - else { - if(gitPurgeFiles == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"git rm \"%s\"",duplicateFile.c_str()); - bool gitOk = executeShellCommand(szBuf,0); - if(gitOk == false) { - throw megaglest_runtime_error("Call to command failed [" + string(szBuf) + "]"); - } - printf("*** Duplicate file:\n[%s]\nwas git rm\n",duplicateFile.c_str()); - } - else { - removeFile(duplicateFile); - } - printf("*** Duplicate file:\n[%s]\nwas removed\n",duplicateFile.c_str()); - - // convert to MB - duplicateMegaBytesPurged += ((double)fileSize / 1048576.0); - duplicateCountPurged++; - } - } - } - - std::map mapUniqueParentList; - - for(unsigned int idx = 0; idx < fileList.size(); ++idx) { - string duplicateFile = fileList[idx]; - string fileExt = extractExtension(duplicateFile); - if(fileExt == "wav" || fileExt == "ogg") { - std::map > >::iterator iterFind2 = loadedFileList.find(duplicateFile); - if(iterFind2 != loadedFileList.end()) { - for(unsigned int jdx1 = 0; jdx1 < iterFind2->second.size(); jdx1++) { - string parentFile = iterFind2->second[jdx1].first; - string searchText = iterFind2->second[jdx1].second; - - if(mapUniqueParentList.find(parentFile) == mapUniqueParentList.end()) { - printf("*** Searching parent file:\n[%s]\nfor duplicate file reference:\n[%s]\nto replace with newname:\n[%s]\n",parentFile.c_str(),searchText.c_str(),newCommonFileName.c_str()); - bool foundText = searchAndReplaceTextInFile(parentFile, searchText, newCommonFileName, false); - printf("foundText = %d\n",foundText); - if(foundText == false) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Line ref = %d, Error finding text [%s] in file [%s]",__LINE__,searchText.c_str(),parentFile.c_str()); - throw megaglest_runtime_error(szBuf); - } - mapUniqueParentList[parentFile]++; - } - } - } - } - } - } - else { - string newCommonFileName = ""; - for(unsigned int idx = 0; idx < fileList.size(); ++idx) { - string duplicateFile = fileList[idx]; - string fileExt = extractExtension(duplicateFile); - if(fileExt == "wav" || fileExt == "ogg") { - //off_t fileSize = getFileSize(duplicateFile); - if(idx == 0) { - newCommonFileName = "$COMMONDATAPATH/sounds/" + extractFileFromDirectoryPath(duplicateFile); - break; - } - } - } - - for(unsigned int idx = 0; idx < fileList.size(); ++idx) { - string duplicateFile = fileList[idx]; - string fileExt = extractExtension(duplicateFile); - if(fileExt == "wav" || fileExt == "ogg") { - std::map > >::iterator iterFind4 = loadedFileList.find(duplicateFile); - if(iterFind4 != loadedFileList.end()) { - for(unsigned int jdx = 0; jdx < iterFind4->second.size(); jdx++) { - string parentFile = iterFind4->second[jdx].first; - string searchText = iterFind4->second[jdx].second; - - bool foundText = searchAndReplaceTextInFile(parentFile, searchText, newCommonFileName, true); - if(foundText == false) { - - char szBuf[8096]=""; - snprintf(szBuf,8096,"Line ref = %d, Error finding text\n[%s]\nin file\n[%s]\nnew Common File [%s]\n",__LINE__,searchText.c_str(),parentFile.c_str(),newCommonFileName.c_str()); - printf("\n\n=================================================\n%s",szBuf); - - throw megaglest_runtime_error(szBuf); - } - } - } - } - } - } - } - } - if(foundDuplicates == true) { - printf("Duplicates %.2f MB (%d) in files\n",duplicateMegaBytes,duplicateCount); - printf("Duplicates purged %.2f MB (%d) in files\n",duplicateMegaBytesPurged,duplicateCountPurged); - - printf("\nWarning, duplicate files were detected - END:\n"); - } - } - - //if(techtree_errors == false) { - printf("\nValidation found NO ERRORS for tilesetPath [%s] tilesetName [%s]:\n",tilesetPath.c_str(), tilesetName.c_str()); - //} - - printf("----------------------------------------------------------------"); -} + for (int i = 0; i < world.getTechTree()->getResourceTypeCount(); ++i) { + printf("Found techtree resource [%s]\n", + world.getTechTree()->getResourceType(i)->getName().c_str()); + } -void runTechValidationForPath(string techPath, string techName, - const std::vector &filteredFactionList, World &world, - bool purgeUnusedFiles,bool purgeDuplicateFiles, bool showDuplicateFiles, - bool gitPurgeFiles,double &purgedMegaBytes) { - - string techTreeFolder = techPath + techName; - string techTreeFactionFolder = techTreeFolder + "/factions/"; - vector factionsList; - findDirs(techTreeFactionFolder, factionsList, false, false); - - if(factionsList.empty() == false) { - Checksum checksum; - set factions; - for(int j = 0; j < (int)factionsList.size(); ++j) { - if( filteredFactionList.empty() == true || - std::find(filteredFactionList.begin(),filteredFactionList.end(),factionsList[j]) != filteredFactionList.end()) { - factions.insert(factionsList[j]); - } - } - - printf("\n----------------------------------------------------------------"); - printf("\nChecking techPath [%s] techName [%s] total faction count = %d\n",techPath.c_str(), techName.c_str(),(int)factionsList.size()); - for(int j = 0; j < (int)factionsList.size(); ++j) { - if( filteredFactionList.empty() == true || - std::find(filteredFactionList.begin(),filteredFactionList.end(),factionsList[j]) != filteredFactionList.end()) { - printf("Using faction [%s]\n",factionsList[j].c_str()); - } - } - - if(factions.empty() == false) { - bool techtree_errors = false; - - std::map > > loadedFileList; - vector pathList; - pathList.push_back(techPath); - Config &config = Config::getInstance(); - vector otherTechPaths = config.getPathListForType(ptTechs,""); - pathList.insert(pathList.end(), otherTechPaths.begin(), otherTechPaths.end()); - - try { - world.loadTech(pathList, techName, factions, &checksum, loadedFileList, true); - - // Fixup paths with .. - { - std::map > > newLoadedFileList; - for( std::map > >::iterator iterMap = loadedFileList.begin(); - iterMap != loadedFileList.end(); ++iterMap) { - string loadedFile = iterMap->first; - - replaceAll(loadedFile,"//","/"); - replaceAll(loadedFile,"\\\\","\\"); - updatePathClimbingParts(loadedFile); - - if(newLoadedFileList.find(loadedFile) != newLoadedFileList.end()) { - for(unsigned int xx1 = 0; xx1 < iterMap->second.size(); ++xx1) { - pair &newVal = iterMap->second[xx1]; - replaceAll(newVal.first,"//","/"); - replaceAll(newVal.first,"\\\\","\\"); - updatePathClimbingParts(newVal.first); - replaceAll(newVal.second,"//","/"); - replaceAll(newVal.second,"\\\\","\\"); - updatePathClimbingParts(newVal.second); - - newLoadedFileList[loadedFile].push_back(newVal); - } - } - else { - for(unsigned int xx1 = 0; xx1 < iterMap->second.size(); ++xx1) { - pair &newVal = iterMap->second[xx1]; - replaceAll(newVal.first,"//","/"); - replaceAll(newVal.first,"\\\\","\\"); - updatePathClimbingParts(newVal.first); - replaceAll(newVal.second,"//","/"); - replaceAll(newVal.second,"\\\\","\\"); - updatePathClimbingParts(newVal.second); - } - - newLoadedFileList[loadedFile] = iterMap->second; - } - } - loadedFileList = newLoadedFileList; - } - - // Validate the faction setup to ensure we don't have any bad associations - std::vector resultErrors = world.validateFactionTypes(); - if(resultErrors.empty() == false) { - techtree_errors = true; - // Display the validation errors - string errorText = "\nErrors were detected:\n=====================\n"; - for(int i = 0; i < (int)resultErrors.size(); ++i) { - if(i > 0) { - errorText += "\n"; - } - errorText = errorText + resultErrors[i]; - } - errorText += "\n=====================\n"; - printf("%s",errorText.c_str()); - } - - // Validate the faction resource setup to ensure we don't have any bad associations - printf("\nChecking resources, count = %d\n",world.getTechTree()->getResourceTypeCount()); - - for(int i = 0; i < world.getTechTree()->getResourceTypeCount(); ++i) { - printf("Found techtree resource [%s]\n",world.getTechTree()->getResourceType(i)->getName().c_str()); - } - - resultErrors = world.validateResourceTypes(); - if(resultErrors.empty() == false) { - techtree_errors = true; - // Display the validation errors - string errorText = "\nErrors were detected:\n=====================\n"; - for(int i = 0; i < (int)resultErrors.size(); ++i) { - if(i > 0) { - errorText += "\n"; - } - errorText = errorText + resultErrors[i]; - } - errorText += "\n=====================\n"; - printf("%s",errorText.c_str()); - } - - // Now check for unused files in the techtree - std::map > > foundFileList; - for(unsigned int i = 0; i < pathList.size(); ++i) { - string path = pathList[i]; - endPathWithSlash(path); - path = path + techName + "/"; - - replaceAll(path, "//", "/"); - replaceAll(path, "\\\\", "\\"); - - vector foundFiles = getFolderTreeContentsListRecursively(path + "*.", ""); - for(unsigned int j = 0; j < foundFiles.size(); ++j) { - string file = foundFiles[j]; - replaceAll(file, "//", "/"); - replaceAll(file, "\\\\", "\\"); - - // ignore loading screen, preview screen and hud - if( file.find(GameConstants::LOADING_SCREEN_FILE) != string::npos || - file.find(GameConstants::PREVIEW_SCREEN_FILE) != string::npos || - file.find(GameConstants::HUD_SCREEN_FILE) != string::npos) { - continue; - } - - // ignore commondata since we are not loading all factions - if(filteredFactionList.size() > 0) { - if( file.find("/commondata/") != string::npos) { - continue; - } - } - - if(file.find("/factions/") != string::npos) { - bool includeFaction = false; - for ( set::iterator it = factions.begin(); it != factions.end(); ++it ) { - string currentFaction = *it; - if(file.find("/factions/" + currentFaction) != string::npos) { - includeFaction = true; - break; - } - } - if(includeFaction == false) { - continue; - } - } - - replaceAll(file,"//","/"); - replaceAll(file,"\\\\","\\"); - - foundFileList[file].push_back(make_pair(path,path)); - } - } - - printf("Found techtree filecount = " MG_SIZE_T_SPECIFIER ", used = " MG_SIZE_T_SPECIFIER "\n",foundFileList.size(),loadedFileList.size()); - - int purgeCount = 0; - bool foundUnusedFile = false; - for( std::map > >::iterator iterMap = foundFileList.begin(); - iterMap != foundFileList.end(); ++iterMap) { - string foundFile = iterMap->first; - replaceAll(foundFile, "//", "/"); - replaceAll(foundFile, "\\\\", "\\"); - - if(loadedFileList.find(foundFile) == loadedFileList.end() && - foundFile.find("lang/") == foundFile.npos) { - if(foundUnusedFile == false) { - printf("\nLine ref: %d, Warning, unused files were detected - START:\n=====================\n",__LINE__); - } - foundUnusedFile = true; - - printf("[%s]\n",foundFile.c_str()); - - string fileName = extractFileFromDirectoryPath(foundFile); - if(loadedFileList.find(fileName) != loadedFileList.end()) { - printf("possible match on [%s] ?\n",loadedFileList.find(fileName)->first.c_str()); - } - else if(purgeUnusedFiles == true) { - off_t fileSize = getFileSize(foundFile); - // convert to MB - purgedMegaBytes += ((double)fileSize / 1048576.0); - purgeCount++; - - if(gitPurgeFiles == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"git rm \"%s\"",foundFile.c_str()); - bool gitOk = executeShellCommand(szBuf,0); - if(gitOk == false) { - throw megaglest_runtime_error("Call to command failed [" + string(szBuf) + "]"); - } - } - else { - removeFile(foundFile); - } - } - } - } - if(foundUnusedFile == true) { - if(purgedMegaBytes > 0) { - printf("Purged %.2f MB (%d) in files\n",purgedMegaBytes,purgeCount); - } - printf("\nLine ref: %d, Warning, unused files were detected - END:\n",__LINE__); - } - - if(showDuplicateFiles == true) { - std::map > mapDuplicateFiles; - // Now check for duplicate data content - for(std::map > >::iterator iterMap = loadedFileList.begin(); - iterMap != loadedFileList.end(); ++iterMap) { - string fileName = iterMap->first; - Checksum checksum; - checksum.addFile(fileName); - uint32 crcValue = checksum.getSum(); - if(crcValue == 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Error calculating CRC for file [%s]",fileName.c_str()); - throw megaglest_runtime_error(szBuf); - } - mapDuplicateFiles[crcValue].push_back(fileName); - } - - double duplicateMegaBytesPurged=0; - int duplicateCountPurged=0; - - double duplicateMegaBytes=0; - int duplicateCount=0; - - bool foundDuplicates = false; - for(std::map >::iterator iterMap = mapDuplicateFiles.begin(); - iterMap != mapDuplicateFiles.end(); ++iterMap) { - vector &fileList = iterMap->second; - if(fileList.size() > 1) { - if(foundDuplicates == false) { - foundDuplicates = true; - printf("\nWarning, duplicate files were detected - START:\n=====================\n"); - } - - printf("----- START duplicate files for CRC [%u] count [" MG_SIZE_T_SPECIFIER "] first file is [%s]\n",iterMap->first,fileList.size(),fileList[0].c_str()); - - map parentList; - for(unsigned int idx = 0; idx < fileList.size(); ++idx) { - string duplicateFile = fileList[idx]; - if(idx > 0) { - off_t fileSize = getFileSize(duplicateFile); - // convert to MB - duplicateMegaBytes += ((double)fileSize / 1048576.0); - duplicateCount++; - } - else { - printf("\n"); - } - - printf("[%s]\n",duplicateFile.c_str()); - std::map > >::iterator iterFind = loadedFileList.find(duplicateFile); - if(iterFind != loadedFileList.end()) { - for(unsigned int jdx = 0; jdx < iterFind->second.size(); jdx++) { - parentList[iterFind->second[jdx].first]++; - } - } - - string newCommonFileName = "$COMMONDATAPATH/sounds/" + extractFileFromDirectoryPath(duplicateFile); - string expandedNewCommonFileName = newCommonFileName; - std::map mapExtraTagReplacementValues; - string techCommonData = techPath + techName + "/commondata/"; - replaceAll(techCommonData, "//", "/"); - mapExtraTagReplacementValues["$COMMONDATAPATH"] = techCommonData; - mapExtraTagReplacementValues = Properties::getTagReplacementValues(&mapExtraTagReplacementValues); - Properties::applyTagsToValue(expandedNewCommonFileName,&mapExtraTagReplacementValues); - replaceAll(expandedNewCommonFileName, "//", "/"); - } - - printf("----- Finding parents for duplicate files [" MG_SIZE_T_SPECIFIER "] first file is [%s]\n",fileList.size(),fileList[0].c_str()); - - for(map::iterator iterMap1 = parentList.begin(); - iterMap1 != parentList.end(); ++iterMap1) { - - if(iterMap1 == parentList.begin()) { - printf("\tParents:\n"); - } - printf("\t[%s]\n",iterMap1->first.c_str()); - } - - if(purgeDuplicateFiles == true) { - - printf("----- move / remove duplicate files [" MG_SIZE_T_SPECIFIER "] first file is [%s]\n",fileList.size(),fileList[0].c_str()); - // First move first duplicate to commondata and delete all other copies - string newCommonFileName = ""; - for(unsigned int idx = 0; idx < fileList.size(); ++idx) { - string duplicateFile = fileList[idx]; - string fileExt = extractExtension(duplicateFile); - if(fileExt == "wav" || fileExt == "ogg") { - off_t fileSize = getFileSize(duplicateFile); - - printf("#1 [%u / " MG_SIZE_T_SPECIFIER "] removing duplicate [%s]\n",idx,fileList.size(),duplicateFile.c_str()); - - if(idx == 0) { - newCommonFileName = "$COMMONDATAPATH/sounds/" + extractFileFromDirectoryPath(duplicateFile); - - string expandedNewCommonFileName = newCommonFileName; - - std::map mapExtraTagReplacementValues; - - string techCommonData = techPath + techName + "/commondata/"; - replaceAll(techCommonData, "//", "/"); - - mapExtraTagReplacementValues["$COMMONDATAPATH"] = techCommonData; - mapExtraTagReplacementValues = Properties::getTagReplacementValues(&mapExtraTagReplacementValues); - Properties::applyTagsToValue(expandedNewCommonFileName,&mapExtraTagReplacementValues); - replaceAll(expandedNewCommonFileName, "//", "/"); - createDirectoryPaths(extractDirectoryPathFromFile(expandedNewCommonFileName)); - - if(gitPurgeFiles == true) { - copyFileTo(duplicateFile, expandedNewCommonFileName); - - char szBuf[8096]=""; - snprintf(szBuf,8096,"git rm \"%s\"",duplicateFile.c_str()); - bool gitOk = executeShellCommand(szBuf,0); - if(gitOk == false) { - throw megaglest_runtime_error("Call to command failed [" + string(szBuf) + "]"); - } - printf("*** Duplicate file:\n[%s]\nwas git rm and copied to:\n[%s]\n",duplicateFile.c_str(),expandedNewCommonFileName.c_str()); - } - else { - printf("moving duplicate [%s] to common data [%s] expanded to [%s]\n",duplicateFile.c_str(),newCommonFileName.c_str(),expandedNewCommonFileName.c_str()); - - int result = rename(duplicateFile.c_str(),expandedNewCommonFileName.c_str()); - if(result != 0) { - char szBuf[8096]=""; - char *errmsg = strerror(errno); - snprintf(szBuf,8096,"!!! Error [%s] Could not rename [%s] to [%s]!",errmsg,duplicateFile.c_str(),expandedNewCommonFileName.c_str()); - throw megaglest_runtime_error(szBuf); - } - else { - printf("*** Duplicate file:\n[%s]\nwas renamed to:\n[%s]\n",duplicateFile.c_str(),expandedNewCommonFileName.c_str()); - } - } - } - else { - if(gitPurgeFiles == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"git rm \"%s\"",duplicateFile.c_str()); - bool gitOk = executeShellCommand(szBuf,0); - if(gitOk == false) { - throw megaglest_runtime_error("Call to command failed [" + string(szBuf) + "]"); - } - printf("*** Duplicate file:\n[%s]\nwas git rm\n",duplicateFile.c_str()); - } - else { - printf("removing duplicate [%s]\n",duplicateFile.c_str()); - removeFile(duplicateFile); - } - printf("*** Duplicate file:\n[%s]\nwas removed\n",duplicateFile.c_str()); - - // convert to MB - duplicateMegaBytesPurged += ((double)fileSize / 1048576.0); - duplicateCountPurged++; - } - } - } - - printf("----- update XML files for duplicate files [" MG_SIZE_T_SPECIFIER "] first file is [%s]\n",fileList.size(),fileList[0].c_str()); - std::map mapUniqueParentList; - - // Update the XML files to point to the new single copy in commondata - for(unsigned int idx = 0; idx < fileList.size(); ++idx) { - string duplicateFile = fileList[idx]; - string fileExt = extractExtension(duplicateFile); - if(fileExt == "wav" || fileExt == "ogg") { - std::map > >::iterator iterFind2 = loadedFileList.find(duplicateFile); - if(iterFind2 != loadedFileList.end()) { - for(unsigned int jdx1 = 0; jdx1 < iterFind2->second.size(); jdx1++) { - string parentFile = iterFind2->second[jdx1].first; - string searchText = iterFind2->second[jdx1].second; - - if(mapUniqueParentList.find(parentFile) == mapUniqueParentList.end()) { - printf("*** Searching parent file:\n[%s]\nfor duplicate file reference:\n[%s]\nto replace with newname:\n[%s]\n",parentFile.c_str(),searchText.c_str(),newCommonFileName.c_str()); - bool foundText = searchAndReplaceTextInFile(parentFile, searchText, newCommonFileName, false); - printf("foundText = %d\n",foundText); - if(foundText == false) { - - string techCommonData = techPath + techName + "/commondata/"; - replaceAll(techCommonData, "//", "/"); - - if(StartsWith(searchText, techCommonData) == true) { - printf("WARNING #1 [%d] techCommonData check\n[%s]\n[%s]\n[%s]\n[%s]\n", - foundText,parentFile.c_str(),techCommonData.c_str(),searchText.c_str(),newCommonFileName.c_str()); - - replaceAll(searchText, techCommonData, "$COMMONDATAPATH/"); - foundText = searchAndReplaceTextInFile(parentFile, searchText, newCommonFileName, false); - - printf("WARNING #2 [%d] techCommonData check\n[%s]\n[%s]\n[%s]\n[%s]\n", - foundText,parentFile.c_str(),techCommonData.c_str(),searchText.c_str(),newCommonFileName.c_str()); - } - if(foundText == false) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Line ref = %d, Error finding text\n[%s]\nin file\n[%s]\nnew Common File [%s]\n",__LINE__,searchText.c_str(),parentFile.c_str(),newCommonFileName.c_str()); - printf("\n\n=================================================\n%s",szBuf); - - throw megaglest_runtime_error(szBuf); - } - } - mapUniqueParentList[parentFile]++; - } - } - } - } - } - } - else { - - string newCommonFileName = ""; - for(unsigned int idx = 0; idx < fileList.size(); ++idx) { - string duplicateFile = fileList[idx]; - string fileExt = extractExtension(duplicateFile); - if(fileExt == "wav" || fileExt == "ogg") { - //off_t fileSize = getFileSize(duplicateFile); - if(idx == 0) { - newCommonFileName = "$COMMONDATAPATH/sounds/" + extractFileFromDirectoryPath(duplicateFile); - break; - } - } - } - - for(unsigned int idx = 0; idx < fileList.size(); ++idx) { - string duplicateFile = fileList[idx]; - string fileExt = extractExtension(duplicateFile); - if(fileExt == "wav" || fileExt == "ogg") { - std::map > >::iterator iterFind4 = loadedFileList.find(duplicateFile); - if(iterFind4 != loadedFileList.end()) { - for(unsigned int jdx = 0; jdx < iterFind4->second.size(); jdx++) { - string parentFile = iterFind4->second[jdx].first; - string searchText = iterFind4->second[jdx].second; - - bool foundText = searchAndReplaceTextInFile(parentFile, searchText, newCommonFileName, true); - - if(foundText == false) { - string techCommonData = techPath + techName + "/commondata/"; - replaceAll(techCommonData, "//", "/"); - - if(StartsWith(searchText, techCommonData) == true) { - replaceAll(searchText, techCommonData, "$COMMONDATAPATH/"); - foundText = searchAndReplaceTextInFile(parentFile, searchText, newCommonFileName, true); - - } - if(foundText == false) { - - // Check if the sound file already references commandata - foundText = searchAndReplaceTextInFile(parentFile, newCommonFileName, newCommonFileName, true); - if(foundText == false) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Line ref = %d, Error finding text\n[%s]\nin file\n[%s]\nnew Common File [%s]\n",__LINE__,searchText.c_str(),parentFile.c_str(),newCommonFileName.c_str()); - printf("\n\n=================================================\n%s",szBuf); - - throw megaglest_runtime_error(szBuf); - } - } - } - } - } - } - } - } - - - printf("----- END duplicate files [" MG_SIZE_T_SPECIFIER "] first file is [%s]\n",fileList.size(),fileList[0].c_str()); - } - } - if(foundDuplicates == true) { - printf("Duplicates %.2f MB (%d) in files\n",duplicateMegaBytes,duplicateCount); - printf("Duplicates purged %.2f MB (%d) in files\n",duplicateMegaBytesPurged,duplicateCountPurged); - - printf("\nWarning, duplicate files were detected - END:\n"); - } - } - } - catch(const megaglest_runtime_error &ex) { - techtree_errors = true; - printf("\n\n****ERROR**** detected while validating the techName: %s\nMESSAGE: %s\n",techName.c_str(),ex.what()); - } - - if(techtree_errors == false) { - printf("\nValidation found NO ERRORS for techPath [%s] techName [%s] factions checked (count = %d):\n",techPath.c_str(), techName.c_str(),(int)factions.size()); - for ( set::iterator it = factions.begin(); it != factions.end(); ++it ) { - printf("Faction [%s]\n",(*it).c_str()); - } - } - } - printf("----------------------------------------------------------------"); - } - else if(folderExists(techTreeFolder) == true) { - printf("\nWarning, No factions were found for the techtree located in: [%s]\n",techTreeFolder.c_str()); - } + resultErrors = world.validateResourceTypes(); + if (resultErrors.empty() == false) { + techtree_errors = true; + // Display the validation errors + string errorText = "\nErrors were detected:\n=====================\n"; + for (int i = 0; i < (int)resultErrors.size(); ++i) { + if (i > 0) { + errorText += "\n"; + } + errorText = errorText + resultErrors[i]; + } + errorText += "\n=====================\n"; + printf("%s", errorText.c_str()); + } + + // Now check for unused files in the techtree + std::map>> foundFileList; + for (unsigned int i = 0; i < pathList.size(); ++i) { + string path = pathList[i]; + endPathWithSlash(path); + path = path + techName + "/"; + + replaceAll(path, "//", "/"); + replaceAll(path, "\\\\", "\\"); + + vector foundFiles = + getFolderTreeContentsListRecursively(path + "*.", ""); + for (unsigned int j = 0; j < foundFiles.size(); ++j) { + string file = foundFiles[j]; + replaceAll(file, "//", "/"); + replaceAll(file, "\\\\", "\\"); + + // ignore loading screen, preview screen and hud + if (file.find(GameConstants::LOADING_SCREEN_FILE) != string::npos || + file.find(GameConstants::PREVIEW_SCREEN_FILE) != string::npos || + file.find(GameConstants::HUD_SCREEN_FILE) != string::npos) { + continue; + } + + // ignore commondata since we are not loading all factions + if (filteredFactionList.size() > 0) { + if (file.find("/commondata/") != string::npos) { + continue; + } + } + + if (file.find("/factions/") != string::npos) { + bool includeFaction = false; + for (set::iterator it = factions.begin(); + it != factions.end(); ++it) { + string currentFaction = *it; + if (file.find("/factions/" + currentFaction) != string::npos) { + includeFaction = true; + break; + } + } + if (includeFaction == false) { + continue; + } + } + + replaceAll(file, "//", "/"); + replaceAll(file, "\\\\", "\\"); + + foundFileList[file].push_back(make_pair(path, path)); + } + } + + printf("Found techtree filecount = " MG_SIZE_T_SPECIFIER + ", used = " MG_SIZE_T_SPECIFIER "\n", + foundFileList.size(), loadedFileList.size()); + + int purgeCount = 0; + bool foundUnusedFile = false; + for (std::map>>::iterator iterMap = + foundFileList.begin(); + iterMap != foundFileList.end(); ++iterMap) { + string foundFile = iterMap->first; + replaceAll(foundFile, "//", "/"); + replaceAll(foundFile, "\\\\", "\\"); + + if (loadedFileList.find(foundFile) == loadedFileList.end() && + foundFile.find("lang/") == foundFile.npos) { + if (foundUnusedFile == false) { + printf("\nLine ref: %d, Warning, unused files were detected - " + "START:\n=====================\n", + __LINE__); + } + foundUnusedFile = true; + + printf("[%s]\n", foundFile.c_str()); + + string fileName = extractFileFromDirectoryPath(foundFile); + if (loadedFileList.find(fileName) != loadedFileList.end()) { + printf("possible match on [%s] ?\n", + loadedFileList.find(fileName)->first.c_str()); + } else if (purgeUnusedFiles == true) { + off_t fileSize = getFileSize(foundFile); + // convert to MB + purgedMegaBytes += ((double)fileSize / 1048576.0); + purgeCount++; + + if (gitPurgeFiles == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "git rm \"%s\"", foundFile.c_str()); + bool gitOk = executeShellCommand(szBuf, 0); + if (gitOk == false) { + throw megaglest_runtime_error("Call to command failed [" + + string(szBuf) + "]"); + } + } else { + removeFile(foundFile); + } + } + } + } + if (foundUnusedFile == true) { + if (purgedMegaBytes > 0) { + printf("Purged %.2f MB (%d) in files\n", purgedMegaBytes, + purgeCount); + } + printf("\nLine ref: %d, Warning, unused files were detected - END:\n", + __LINE__); + } + + if (showDuplicateFiles == true) { + std::map> mapDuplicateFiles; + // Now check for duplicate data content + for (std::map>>::iterator + iterMap = loadedFileList.begin(); + iterMap != loadedFileList.end(); ++iterMap) { + string fileName = iterMap->first; + Checksum checksum; + checksum.addFile(fileName); + uint32 crcValue = checksum.getSum(); + if (crcValue == 0) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "Error calculating CRC for file [%s]", + fileName.c_str()); + throw megaglest_runtime_error(szBuf); + } + mapDuplicateFiles[crcValue].push_back(fileName); + } + + double duplicateMegaBytesPurged = 0; + int duplicateCountPurged = 0; + + double duplicateMegaBytes = 0; + int duplicateCount = 0; + + bool foundDuplicates = false; + for (std::map>::iterator iterMap = + mapDuplicateFiles.begin(); + iterMap != mapDuplicateFiles.end(); ++iterMap) { + vector &fileList = iterMap->second; + if (fileList.size() > 1) { + if (foundDuplicates == false) { + foundDuplicates = true; + printf("\nWarning, duplicate files were detected - " + "START:\n=====================\n"); + } + + printf("----- START duplicate files for CRC [%u] count " + "[" MG_SIZE_T_SPECIFIER "] first file is [%s]\n", + iterMap->first, fileList.size(), fileList[0].c_str()); + + map parentList; + for (unsigned int idx = 0; idx < fileList.size(); ++idx) { + string duplicateFile = fileList[idx]; + if (idx > 0) { + off_t fileSize = getFileSize(duplicateFile); + // convert to MB + duplicateMegaBytes += ((double)fileSize / 1048576.0); + duplicateCount++; + } else { + printf("\n"); + } + + printf("[%s]\n", duplicateFile.c_str()); + std::map>>::iterator + iterFind = loadedFileList.find(duplicateFile); + if (iterFind != loadedFileList.end()) { + for (unsigned int jdx = 0; jdx < iterFind->second.size(); + jdx++) { + parentList[iterFind->second[jdx].first]++; + } + } + + string newCommonFileName = + "$COMMONDATAPATH/sounds/" + + extractFileFromDirectoryPath(duplicateFile); + string expandedNewCommonFileName = newCommonFileName; + std::map mapExtraTagReplacementValues; + string techCommonData = techPath + techName + "/commondata/"; + replaceAll(techCommonData, "//", "/"); + mapExtraTagReplacementValues["$COMMONDATAPATH"] = + techCommonData; + mapExtraTagReplacementValues = + Properties::getTagReplacementValues( + &mapExtraTagReplacementValues); + Properties::applyTagsToValue(expandedNewCommonFileName, + &mapExtraTagReplacementValues); + replaceAll(expandedNewCommonFileName, "//", "/"); + } + + printf("----- Finding parents for duplicate files " + "[" MG_SIZE_T_SPECIFIER "] first file is [%s]\n", + fileList.size(), fileList[0].c_str()); + + for (map::iterator iterMap1 = parentList.begin(); + iterMap1 != parentList.end(); ++iterMap1) { + + if (iterMap1 == parentList.begin()) { + printf("\tParents:\n"); + } + printf("\t[%s]\n", iterMap1->first.c_str()); + } + + if (purgeDuplicateFiles == true) { + + printf( + "----- move / remove duplicate files [" MG_SIZE_T_SPECIFIER + "] first file is [%s]\n", + fileList.size(), fileList[0].c_str()); + // First move first duplicate to commondata and delete all other + // copies + string newCommonFileName = ""; + for (unsigned int idx = 0; idx < fileList.size(); ++idx) { + string duplicateFile = fileList[idx]; + string fileExt = extractExtension(duplicateFile); + if (fileExt == "wav" || fileExt == "ogg") { + off_t fileSize = getFileSize(duplicateFile); + + printf("#1 [%u / " MG_SIZE_T_SPECIFIER + "] removing duplicate [%s]\n", + idx, fileList.size(), duplicateFile.c_str()); + + if (idx == 0) { + newCommonFileName = + "$COMMONDATAPATH/sounds/" + + extractFileFromDirectoryPath(duplicateFile); + + string expandedNewCommonFileName = newCommonFileName; + + std::map mapExtraTagReplacementValues; + + string techCommonData = + techPath + techName + "/commondata/"; + replaceAll(techCommonData, "//", "/"); + + mapExtraTagReplacementValues["$COMMONDATAPATH"] = + techCommonData; + mapExtraTagReplacementValues = + Properties::getTagReplacementValues( + &mapExtraTagReplacementValues); + Properties::applyTagsToValue( + expandedNewCommonFileName, + &mapExtraTagReplacementValues); + replaceAll(expandedNewCommonFileName, "//", "/"); + createDirectoryPaths(extractDirectoryPathFromFile( + expandedNewCommonFileName)); + + if (gitPurgeFiles == true) { + copyFileTo(duplicateFile, expandedNewCommonFileName); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "git rm \"%s\"", + duplicateFile.c_str()); + bool gitOk = executeShellCommand(szBuf, 0); + if (gitOk == false) { + throw megaglest_runtime_error( + "Call to command failed [" + string(szBuf) + "]"); + } + printf("*** Duplicate file:\n[%s]\nwas git rm and " + "copied to:\n[%s]\n", + duplicateFile.c_str(), + expandedNewCommonFileName.c_str()); + } else { + printf("moving duplicate [%s] to common data [%s] " + "expanded to [%s]\n", + duplicateFile.c_str(), newCommonFileName.c_str(), + expandedNewCommonFileName.c_str()); + + int result = rename(duplicateFile.c_str(), + expandedNewCommonFileName.c_str()); + if (result != 0) { + char szBuf[8096] = ""; + char *errmsg = strerror(errno); + snprintf( + szBuf, 8096, + "!!! Error [%s] Could not rename [%s] to [%s]!", + errmsg, duplicateFile.c_str(), + expandedNewCommonFileName.c_str()); + throw megaglest_runtime_error(szBuf); + } else { + printf("*** Duplicate file:\n[%s]\nwas renamed " + "to:\n[%s]\n", + duplicateFile.c_str(), + expandedNewCommonFileName.c_str()); + } + } + } else { + if (gitPurgeFiles == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "git rm \"%s\"", + duplicateFile.c_str()); + bool gitOk = executeShellCommand(szBuf, 0); + if (gitOk == false) { + throw megaglest_runtime_error( + "Call to command failed [" + string(szBuf) + "]"); + } + printf("*** Duplicate file:\n[%s]\nwas git rm\n", + duplicateFile.c_str()); + } else { + printf("removing duplicate [%s]\n", + duplicateFile.c_str()); + removeFile(duplicateFile); + } + printf("*** Duplicate file:\n[%s]\nwas removed\n", + duplicateFile.c_str()); + + // convert to MB + duplicateMegaBytesPurged += + ((double)fileSize / 1048576.0); + duplicateCountPurged++; + } + } + } + + printf("----- update XML files for duplicate files " + "[" MG_SIZE_T_SPECIFIER "] first file is [%s]\n", + fileList.size(), fileList[0].c_str()); + std::map mapUniqueParentList; + + // Update the XML files to point to the new single copy in + // commondata + for (unsigned int idx = 0; idx < fileList.size(); ++idx) { + string duplicateFile = fileList[idx]; + string fileExt = extractExtension(duplicateFile); + if (fileExt == "wav" || fileExt == "ogg") { + std::map>>::iterator + iterFind2 = loadedFileList.find(duplicateFile); + if (iterFind2 != loadedFileList.end()) { + for (unsigned int jdx1 = 0; + jdx1 < iterFind2->second.size(); jdx1++) { + string parentFile = iterFind2->second[jdx1].first; + string searchText = iterFind2->second[jdx1].second; + + if (mapUniqueParentList.find(parentFile) == + mapUniqueParentList.end()) { + printf("*** Searching parent file:\n[%s]\nfor " + "duplicate file reference:\n[%s]\nto replace " + "with newname:\n[%s]\n", + parentFile.c_str(), searchText.c_str(), + newCommonFileName.c_str()); + bool foundText = searchAndReplaceTextInFile( + parentFile, searchText, newCommonFileName, false); + printf("foundText = %d\n", foundText); + if (foundText == false) { + + string techCommonData = + techPath + techName + "/commondata/"; + replaceAll(techCommonData, "//", "/"); + + if (StartsWith(searchText, techCommonData) == + true) { + printf("WARNING #1 [%d] techCommonData " + "check\n[%s]\n[%s]\n[%s]\n[%s]\n", + foundText, parentFile.c_str(), + techCommonData.c_str(), searchText.c_str(), + newCommonFileName.c_str()); + + replaceAll(searchText, techCommonData, + "$COMMONDATAPATH/"); + foundText = searchAndReplaceTextInFile( + parentFile, searchText, newCommonFileName, + false); + + printf("WARNING #2 [%d] techCommonData " + "check\n[%s]\n[%s]\n[%s]\n[%s]\n", + foundText, parentFile.c_str(), + techCommonData.c_str(), searchText.c_str(), + newCommonFileName.c_str()); + } + if (foundText == false) { + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "Line ref = %d, Error finding text\n[%s]\nin " + "file\n[%s]\nnew Common File [%s]\n", + __LINE__, searchText.c_str(), + parentFile.c_str(), + newCommonFileName.c_str()); + printf("\n\n=====================================" + "============\n%s", + szBuf); + + throw megaglest_runtime_error(szBuf); + } + } + mapUniqueParentList[parentFile]++; + } + } + } + } + } + } else { + + string newCommonFileName = ""; + for (unsigned int idx = 0; idx < fileList.size(); ++idx) { + string duplicateFile = fileList[idx]; + string fileExt = extractExtension(duplicateFile); + if (fileExt == "wav" || fileExt == "ogg") { + // off_t fileSize = getFileSize(duplicateFile); + if (idx == 0) { + newCommonFileName = + "$COMMONDATAPATH/sounds/" + + extractFileFromDirectoryPath(duplicateFile); + break; + } + } + } + + for (unsigned int idx = 0; idx < fileList.size(); ++idx) { + string duplicateFile = fileList[idx]; + string fileExt = extractExtension(duplicateFile); + if (fileExt == "wav" || fileExt == "ogg") { + std::map>>::iterator + iterFind4 = loadedFileList.find(duplicateFile); + if (iterFind4 != loadedFileList.end()) { + for (unsigned int jdx = 0; jdx < iterFind4->second.size(); + jdx++) { + string parentFile = iterFind4->second[jdx].first; + string searchText = iterFind4->second[jdx].second; + + bool foundText = searchAndReplaceTextInFile( + parentFile, searchText, newCommonFileName, true); + + if (foundText == false) { + string techCommonData = + techPath + techName + "/commondata/"; + replaceAll(techCommonData, "//", "/"); + + if (StartsWith(searchText, techCommonData) == true) { + replaceAll(searchText, techCommonData, + "$COMMONDATAPATH/"); + foundText = searchAndReplaceTextInFile( + parentFile, searchText, newCommonFileName, + true); + } + if (foundText == false) { + + // Check if the sound file already references + // commandata + foundText = searchAndReplaceTextInFile( + parentFile, newCommonFileName, + newCommonFileName, true); + if (foundText == false) { + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "Line ref = %d, Error finding text\n[%s]\nin " + "file\n[%s]\nnew Common File [%s]\n", + __LINE__, searchText.c_str(), + parentFile.c_str(), + newCommonFileName.c_str()); + printf("\n\n=====================================" + "============\n%s", + szBuf); + + throw megaglest_runtime_error(szBuf); + } + } + } + } + } + } + } + } + + printf("----- END duplicate files [" MG_SIZE_T_SPECIFIER + "] first file is [%s]\n", + fileList.size(), fileList[0].c_str()); + } + } + if (foundDuplicates == true) { + printf("Duplicates %.2f MB (%d) in files\n", duplicateMegaBytes, + duplicateCount); + printf("Duplicates purged %.2f MB (%d) in files\n", + duplicateMegaBytesPurged, duplicateCountPurged); + + printf("\nWarning, duplicate files were detected - END:\n"); + } + } + } catch (const megaglest_runtime_error &ex) { + techtree_errors = true; + printf("\n\n****ERROR**** detected while validating the techName: " + "%s\nMESSAGE: %s\n", + techName.c_str(), ex.what()); + } + + if (techtree_errors == false) { + printf("\nValidation found NO ERRORS for techPath [%s] techName [%s] " + "factions checked (count = %d):\n", + techPath.c_str(), techName.c_str(), (int)factions.size()); + for (set::iterator it = factions.begin(); it != factions.end(); + ++it) { + printf("Faction [%s]\n", (*it).c_str()); + } + } + } + printf("----------------------------------------------------------------"); + } else if (folderExists(techTreeFolder) == true) { + printf( + "\nWarning, No factions were found for the techtree located in: [%s]\n", + techTreeFolder.c_str()); + } } +void runTechTranslationExtractionForPath( + string techPath, string techName, + const std::vector &filteredFactionList, World &world) { + vector factionsList; + findDirs(techPath + techName + "/factions/", factionsList, false, false); + + if (factionsList.empty() == false) { + Checksum checksum; + set factions; + for (int j = 0; j < (int)factionsList.size(); ++j) { + if (filteredFactionList.empty() == true || + std::find(filteredFactionList.begin(), filteredFactionList.end(), + factionsList[j]) != filteredFactionList.end()) { + factions.insert(factionsList[j]); + } + } -void runTechTranslationExtractionForPath(string techPath, string techName, - const std::vector &filteredFactionList, World &world) { - vector factionsList; - findDirs(techPath + techName + "/factions/", factionsList, false, false); - - if(factionsList.empty() == false) { - Checksum checksum; - set factions; - for(int j = 0; j < (int)factionsList.size(); ++j) { - if( filteredFactionList.empty() == true || - std::find(filteredFactionList.begin(),filteredFactionList.end(),factionsList[j]) != filteredFactionList.end()) { - factions.insert(factionsList[j]); - } - } - - printf("\n----------------------------------------------------------------"); - printf("\nChecking techPath [%s] techName [%s] total faction count = %d\n",techPath.c_str(), techName.c_str(),(int)factionsList.size()); - for(int j = 0; j < (int)factionsList.size(); ++j) { - if( filteredFactionList.empty() == true || - std::find(filteredFactionList.begin(),filteredFactionList.end(),factionsList[j]) != filteredFactionList.end()) { - printf("Using faction [%s]\n",factionsList[j].c_str()); - } - } - - if(factions.empty() == false) { - std::map > > loadedFileList; - vector pathList; - pathList.push_back(techPath); - Config &config = Config::getInstance(); - vector otherTechPaths = config.getPathListForType(ptTechs,""); - pathList.insert(pathList.end(), otherTechPaths.begin(), otherTechPaths.end()); - - try { - world.loadTech(pathList, techName, factions, &checksum, loadedFileList, true); - - const TechTree *techtree = world.getTechTree(); - string translationFile = techtree->getPath(); - endPathWithSlash(translationFile); - translationFile += "lang/" + techName + "_default.lng"; - if(fileExists(translationFile) == false) { - string txFilePath = extractDirectoryPathFromFile(translationFile); - createDirectoryPaths(txFilePath); + printf( + "\n----------------------------------------------------------------"); + printf("\nChecking techPath [%s] techName [%s] total faction count = %d\n", + techPath.c_str(), techName.c_str(), (int)factionsList.size()); + for (int j = 0; j < (int)factionsList.size(); ++j) { + if (filteredFactionList.empty() == true || + std::find(filteredFactionList.begin(), filteredFactionList.end(), + factionsList[j]) != filteredFactionList.end()) { + printf("Using faction [%s]\n", factionsList[j].c_str()); + } + } + + if (factions.empty() == false) { + std::map>> loadedFileList; + vector pathList; + pathList.push_back(techPath); + Config &config = Config::getInstance(); + vector otherTechPaths = config.getPathListForType(ptTechs, ""); + pathList.insert(pathList.end(), otherTechPaths.begin(), + otherTechPaths.end()); + + try { + world.loadTech(pathList, techName, factions, &checksum, loadedFileList, + true); + + const TechTree *techtree = world.getTechTree(); + string translationFile = techtree->getPath(); + endPathWithSlash(translationFile); + translationFile += "lang/" + techName + "_default.lng"; + if (fileExists(translationFile) == false) { + string txFilePath = extractDirectoryPathFromFile(translationFile); + createDirectoryPaths(txFilePath); #if defined(WIN32) && !defined(__MINGW32__) - FILE *fp = _wfopen(utf8_decode(translationFile).c_str(), L"w"); - std::ofstream txFile(fp); + FILE *fp = _wfopen(utf8_decode(translationFile).c_str(), L"w"); + std::ofstream txFile(fp); #else - std::ofstream txFile; - txFile.open(translationFile.c_str(), ios_base::out | ios_base::trunc); + std::ofstream txFile; + txFile.open(translationFile.c_str(), ios_base::out | ios_base::trunc); #endif - if(txFile.is_open() == true) { - string _transl_TechTreeName = techName; - replaceAll(_transl_TechTreeName,"_"," "); - txFile << "; TechTree" << std::endl; - txFile << "TechTreeName=" << _transl_TechTreeName << std::endl; - - txFile << "; -------------------------------------" << std::endl; - txFile << "; Types of Armor" << std::endl; - for(int index = 0; index < techtree->getArmorTypeCount(); ++index) { - const ArmorType *at = techtree->getArmorTypeByIndex(index); - string _transl_ArmorTypeName = at->getName(false); - replaceAll(_transl_ArmorTypeName,"_"," "); - txFile << "ArmorTypeName_" << at->getName(false) << "=" << _transl_ArmorTypeName << std::endl; - } - - txFile << "; --------------------" << std::endl; - txFile << "; Types of Attack" << std::endl; - for(int index = 0; index < techtree->getAttackTypeCount(); ++index) { - const AttackType *at = techtree->getAttackTypeByIndex(index); - string _transl_AttackTypeName = at->getName(false); - replaceAll(_transl_AttackTypeName,"_"," "); - txFile << "AttackTypeName_" << at->getName(false) << "=" << _transl_AttackTypeName << std::endl; - } - - txFile << "; --------------------" << std::endl; - txFile << "; Types of Resources" << std::endl; - for(int index = 0; index < techtree->getResourceTypeCount(); ++index) { - const ResourceType *rt = techtree->getResourceType(index); - string _transl_ResourceTypeName = rt->getName(false); - replaceAll(_transl_ResourceTypeName,"_"," "); - txFile << "ResourceTypeName_" << rt->getName(false) << "=" << _transl_ResourceTypeName << std::endl; - } - - //txFile << "FactionName_" << GameConstants::OBSERVER_SLOTNAME << "=" << GameConstants::OBSERVER_SLOTNAME << std::endl; - //txFile << "FactionName_" << GameConstants::RANDOMFACTION_SLOTNAME << "=" << GameConstants::RANDOMFACTION_SLOTNAME << std::endl; - for(int index = 0; index < techtree->getTypeCount(); ++index) { - const FactionType *ft = techtree->getType(index); - string _transl_FactionName = ft->getName(false); - replaceAll(_transl_FactionName,"_"," "); - txFile << "; -----------------------------------------------------------------------------" << std::endl; - txFile << "; Faction" << std::endl; - txFile << "FactionName_" << ft->getName(false) << "=" << _transl_FactionName << std::endl; - - txFile << "; -------------------------------------" << std::endl; - txFile << "; Types of Upgrades for this Faction" << std::endl; - for(int upgradeIndex = 0; upgradeIndex < ft->getUpgradeTypeCount(); ++upgradeIndex) { - const UpgradeType *upt = ft->getUpgradeType(upgradeIndex); - string _transl_UpgradeTypeName = upt->getName(false); - replaceAll(_transl_UpgradeTypeName,"_"," "); - txFile << "UpgradeTypeName_" << upt->getName(false) << "=" << _transl_UpgradeTypeName << std::endl; - } - - for(int unitIndex = 0; unitIndex < ft->getUnitTypeCount(); ++unitIndex) { - const UnitType *ut = ft->getUnitType(unitIndex); - string _transl_UnitTypeName = ut->getName(false); - replaceAll(_transl_UnitTypeName,"_"," "); - txFile << "; -------------------------------------" << std::endl; - txFile << "; Unit" << std::endl; - txFile << "UnitTypeName_" << ut->getName(false) << "=" << _transl_UnitTypeName << std::endl; - - txFile << "; --------------------" << std::endl; - txFile << "; Levels for this Unit" << std::endl; - for(int levelIndex = 0; levelIndex < ut->getLevelCount(); ++levelIndex) { - const Level *level = ut->getLevel(levelIndex); - string _transl_LevelName = level->getName(false); - replaceAll(_transl_LevelName,"_"," "); - txFile << "LevelName_" << level->getName(false) << "=" << _transl_LevelName << std::endl; - } - - txFile << "; --------------------" << std::endl; - txFile << "; Types of Commands for this Unit" << std::endl; - for(int commandIndex = 0; commandIndex < ut->getCommandTypeCount(); ++commandIndex) { - const CommandType *ct = ut->getCommandType(commandIndex); - string _transl_CommandName = ct->getName(false); - replaceAll(_transl_CommandName,"_"," "); - txFile << "CommandName_" << ct->getName(false) << "=" << _transl_CommandName << std::endl; - } - } - } - txFile << "; -------------------------------------" << std::endl; - } - txFile.close(); + if (txFile.is_open() == true) { + string _transl_TechTreeName = techName; + replaceAll(_transl_TechTreeName, "_", " "); + txFile << "; TechTree" << std::endl; + txFile << "TechTreeName=" << _transl_TechTreeName << std::endl; + + txFile << "; -------------------------------------" << std::endl; + txFile << "; Types of Armor" << std::endl; + for (int index = 0; index < techtree->getArmorTypeCount(); + ++index) { + const ArmorType *at = techtree->getArmorTypeByIndex(index); + string _transl_ArmorTypeName = at->getName(false); + replaceAll(_transl_ArmorTypeName, "_", " "); + txFile << "ArmorTypeName_" << at->getName(false) << "=" + << _transl_ArmorTypeName << std::endl; + } + + txFile << "; --------------------" << std::endl; + txFile << "; Types of Attack" << std::endl; + for (int index = 0; index < techtree->getAttackTypeCount(); + ++index) { + const AttackType *at = techtree->getAttackTypeByIndex(index); + string _transl_AttackTypeName = at->getName(false); + replaceAll(_transl_AttackTypeName, "_", " "); + txFile << "AttackTypeName_" << at->getName(false) << "=" + << _transl_AttackTypeName << std::endl; + } + + txFile << "; --------------------" << std::endl; + txFile << "; Types of Resources" << std::endl; + for (int index = 0; index < techtree->getResourceTypeCount(); + ++index) { + const ResourceType *rt = techtree->getResourceType(index); + string _transl_ResourceTypeName = rt->getName(false); + replaceAll(_transl_ResourceTypeName, "_", " "); + txFile << "ResourceTypeName_" << rt->getName(false) << "=" + << _transl_ResourceTypeName << std::endl; + } + + // txFile << "FactionName_" << GameConstants::OBSERVER_SLOTNAME << + // "=" << GameConstants::OBSERVER_SLOTNAME << std::endl; txFile << + // "FactionName_" << GameConstants::RANDOMFACTION_SLOTNAME << "=" << + // GameConstants::RANDOMFACTION_SLOTNAME << std::endl; + for (int index = 0; index < techtree->getTypeCount(); ++index) { + const FactionType *ft = techtree->getType(index); + string _transl_FactionName = ft->getName(false); + replaceAll(_transl_FactionName, "_", " "); + txFile << "; " + "------------------------------------------------------" + "-----------------------" + << std::endl; + txFile << "; Faction" << std::endl; + txFile << "FactionName_" << ft->getName(false) << "=" + << _transl_FactionName << std::endl; + + txFile << "; -------------------------------------" << std::endl; + txFile << "; Types of Upgrades for this Faction" << std::endl; + for (int upgradeIndex = 0; + upgradeIndex < ft->getUpgradeTypeCount(); ++upgradeIndex) { + const UpgradeType *upt = ft->getUpgradeType(upgradeIndex); + string _transl_UpgradeTypeName = upt->getName(false); + replaceAll(_transl_UpgradeTypeName, "_", " "); + txFile << "UpgradeTypeName_" << upt->getName(false) << "=" + << _transl_UpgradeTypeName << std::endl; + } + + for (int unitIndex = 0; unitIndex < ft->getUnitTypeCount(); + ++unitIndex) { + const UnitType *ut = ft->getUnitType(unitIndex); + string _transl_UnitTypeName = ut->getName(false); + replaceAll(_transl_UnitTypeName, "_", " "); + txFile << "; -------------------------------------" + << std::endl; + txFile << "; Unit" << std::endl; + txFile << "UnitTypeName_" << ut->getName(false) << "=" + << _transl_UnitTypeName << std::endl; + + txFile << "; --------------------" << std::endl; + txFile << "; Levels for this Unit" << std::endl; + for (int levelIndex = 0; levelIndex < ut->getLevelCount(); + ++levelIndex) { + const Level *level = ut->getLevel(levelIndex); + string _transl_LevelName = level->getName(false); + replaceAll(_transl_LevelName, "_", " "); + txFile << "LevelName_" << level->getName(false) << "=" + << _transl_LevelName << std::endl; + } + + txFile << "; --------------------" << std::endl; + txFile << "; Types of Commands for this Unit" << std::endl; + for (int commandIndex = 0; + commandIndex < ut->getCommandTypeCount(); ++commandIndex) { + const CommandType *ct = ut->getCommandType(commandIndex); + string _transl_CommandName = ct->getName(false); + replaceAll(_transl_CommandName, "_", " "); + txFile << "CommandName_" << ct->getName(false) << "=" + << _transl_CommandName << std::endl; + } + } + } + txFile << "; -------------------------------------" << std::endl; + } + txFile.close(); #if defined(WIN32) && !defined(__MINGW32__) - if(fp) { - fclose(fp); - } + if (fp) { + fclose(fp); + } #endif - } - else { - printf("\n** Cannot product techtree translation file [%s] for techPath [%s] techName [%s] because the file already exists!\n",translationFile.c_str(),techPath.c_str(), techName.c_str()); - } - } - catch(const megaglest_runtime_error &ex) { - printf("\n\n****ERROR**** detected while loading the techName: %s\nMESSAGE: %s\n",techName.c_str(),ex.what()); - } - - } - printf("----------------------------------------------------------------"); - } + } else { + printf( + "\n** Cannot product techtree translation file [%s] for techPath " + "[%s] techName [%s] because the file already exists!\n", + translationFile.c_str(), techPath.c_str(), techName.c_str()); + } + } catch (const megaglest_runtime_error &ex) { + printf("\n\n****ERROR**** detected while loading the techName: " + "%s\nMESSAGE: %s\n", + techName.c_str(), ex.what()); + } + } + printf("----------------------------------------------------------------"); + } } -void runTechTranslationExtraction(int argc, char** argv) { - printf("====== Started Translation Extraction ======\n"); +void runTechTranslationExtraction(int argc, char **argv) { + printf("====== Started Translation Extraction ======\n"); + + Config &config = Config::getInstance(); + + // Did the user pass a specific list of factions to validate? + std::vector filteredFactionList; + + vector results; + findDirs(config.getPathListForType(ptTechs), results); + vector techTreeFiles = results; + // Did the user pass a specific list of techtrees to validate? + std::vector filteredTechTreeList; + if (hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_TRANSLATE_TECHTREES]) + + string("=")) == true) { + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_TRANSLATE_TECHTREES]) + + string("="), + &foundParamIndIndex); + string filterList = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(filterList, paramPartTokens, "="); + if (paramPartTokens.size() >= 2) { + string techtreeList = paramPartTokens[1]; + Tokenize(techtreeList, filteredTechTreeList, ","); + + if (filteredTechTreeList.empty() == false) { + printf("Filtering techtrees and only looking for the following:\n"); + for (int idx = 0; idx < (int)filteredTechTreeList.size(); ++idx) { + filteredTechTreeList[idx] = trim(filteredTechTreeList[idx]); + printf("%s\n", filteredTechTreeList[idx].c_str()); + } + } + } + } - Config &config = Config::getInstance(); + { + printf("\n---------------- Loading factions inside world ----------------"); + World world; - // Did the user pass a specific list of factions to validate? - std::vector filteredFactionList; + vector techPaths = config.getPathListForType(ptTechs); + for (int idx = 0; idx < (int)techPaths.size(); idx++) { + string &techPath = techPaths[idx]; + endPathWithSlash(techPath); - vector results; - findDirs(config.getPathListForType(ptTechs), results); - vector techTreeFiles = results; - // Did the user pass a specific list of techtrees to validate? - std::vector filteredTechTreeList; - if(hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_TRANSLATE_TECHTREES]) + string("=")) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_TRANSLATE_TECHTREES]) + string("="),&foundParamIndIndex); - string filterList = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(filterList,paramPartTokens,"="); - if(paramPartTokens.size() >= 2) { - string techtreeList = paramPartTokens[1]; - Tokenize(techtreeList,filteredTechTreeList,","); - - if(filteredTechTreeList.empty() == false) { - printf("Filtering techtrees and only looking for the following:\n"); - for(int idx = 0; idx < (int)filteredTechTreeList.size(); ++idx) { - filteredTechTreeList[idx] = trim(filteredTechTreeList[idx]); - printf("%s\n",filteredTechTreeList[idx].c_str()); + for (int idx2 = 0; idx2 < (int)techTreeFiles.size(); idx2++) { + string &techName = techTreeFiles[idx2]; + + if (filteredTechTreeList.empty() == true || + std::find(filteredTechTreeList.begin(), filteredTechTreeList.end(), + techName) != filteredTechTreeList.end()) { + + runTechTranslationExtractionForPath(techPath, techName, + filteredFactionList, world); + } + } + } + + printf("\n====== Finished Translation ======\n"); + } +} + +void runTechValidationReport(int argc, char **argv) { + printf("====== Started Validation ======\n"); + + bool purgeDuplicateFiles = false; + bool showDuplicateFiles = true; + bool purgeUnusedFiles = false; + bool gitPurgeFiles = false; + + double purgedMegaBytes = 0; + Config &config = Config::getInstance(); + + // Did the user pass a specific scenario to validate? + if (hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_VALIDATE_SCENARIO]) + + string("=")) == true) { + + int foundParamIndIndex = -1; + hasCommandArgument( + argc, argv, string(GAME_ARGS[GAME_ARG_VALIDATE_SCENARIO]) + string("="), + &foundParamIndIndex); + + string filterList = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(filterList, paramPartTokens, "="); + + if (paramPartTokens.size() >= 2) { + string validateScenarioName = paramPartTokens[1]; + + printf("Filtering scenario: %s\n", validateScenarioName.c_str()); + + if (paramPartTokens.size() >= 3) { + if (paramPartTokens[2] == "purgeunused") { + purgeUnusedFiles = true; + printf("*NOTE All unused scenario files will be deleted!\n"); + } + } + + { + printf("\n---------------- Loading scenario inside world " + "----------------\n"); + + bool scenarioFound = false; + World world; + std::vector filteredFactionList; + + vector scenarioPaths = config.getPathListForType(ptScenarios); + for (int idx = 0; idx < (int)scenarioPaths.size(); idx++) { + string &scenarioPath = scenarioPaths[idx]; + endPathWithSlash(scenarioPath); + + vector scenarioList; + findDirs(scenarioPath, scenarioList, false, false); + for (int idx2 = 0; idx2 < (int)scenarioList.size(); idx2++) { + string &scenarioName = scenarioList[idx2]; + + if (scenarioName == validateScenarioName) { + scenarioFound = true; + + string file = + scenarioPath + scenarioName + "/" + scenarioName + ".xml"; + + XmlTree xmlTree; + xmlTree.load(file, Properties::getTagReplacementValues()); + const XmlNode *scenarioNode = xmlTree.getRootNode(); + string techName = scenarioNode->getChild("tech-tree") + ->getAttribute("value") + ->getValue(); + + // Self Contained techtree? + string scenarioTechtree = scenarioPath + scenarioName + "/" + + techName + "/" + techName + ".xml"; + + printf("\nFound Scenario [%s] looking for techtree [%s]...\n", + scenarioName.c_str(), scenarioTechtree.c_str()); + + if (fileExists(scenarioTechtree) == true) { + string techPath = scenarioPath + scenarioName + "/"; + + printf("\nFound Scenario [%s] with custom techtree [%s] " + "validating...\n", + scenarioName.c_str(), techName.c_str()); + runTechValidationForPath(techPath, techName, + filteredFactionList, world, + purgeUnusedFiles, showDuplicateFiles, + false, false, purgedMegaBytes); + } else { + vector techPaths = config.getPathListForType(ptTechs); + for (int idx = 0; idx < (int)techPaths.size(); idx++) { + string &techPath = techPaths[idx]; + endPathWithSlash(techPath); + scenarioTechtree = + techPath + "/" + techName + "/" + techName + ".xml"; + if (fileExists(scenarioTechtree) == true) { + printf("\nFound Scenario [%s] with techtree [%s] " + "validating...\n", + scenarioName.c_str(), techName.c_str()); + runTechValidationForPath( + techPath, techName, filteredFactionList, world, + purgeUnusedFiles, showDuplicateFiles, false, false, + purgedMegaBytes); + + break; + } } + } } + } + } + + if (scenarioFound == false) { + printf("\nWARNING, the scenario [%s] was NOT FOUND!\n", + validateScenarioName.c_str()); } + printf("\n====== Finished Validation ======\n"); + } + return; + } else { + printf("\nInvalid missing scenario specified on commandline [%s] value " + "[%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + return; } + } - { + // Did the user pass a specific list of factions to validate? + std::vector filteredFactionList; + if (hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_VALIDATE_FACTIONS]) + + string("=")) == true) { + int foundParamIndIndex = -1; + hasCommandArgument( + argc, argv, string(GAME_ARGS[GAME_ARG_VALIDATE_FACTIONS]) + string("="), + &foundParamIndIndex); + + string filterList = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(filterList, paramPartTokens, "="); + + if (paramPartTokens.size() >= 2) { + string factionList = paramPartTokens[1]; + Tokenize(factionList, filteredFactionList, ","); + + if (filteredFactionList.empty() == false) { + printf("Filtering factions and only looking for the following:\n"); + for (int idx = 0; idx < (int)filteredFactionList.size(); ++idx) { + filteredFactionList[idx] = trim(filteredFactionList[idx]); + printf("%s\n", filteredFactionList[idx].c_str()); + } + } + + if (paramPartTokens.size() >= 3) { + if (paramPartTokens[2] == "purgeunused") { + purgeUnusedFiles = true; + printf("*NOTE All unused faction files will be deleted!\n"); + } + } + } + } + vector results; + findDirs(config.getPathListForType(ptTechs), results); + vector techTreeFiles = results; + // Did the user pass a specific list of techtrees to validate? + std::vector filteredTechTreeList; + if (hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_VALIDATE_TECHTREES]) + + string("=")) == true) { + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_VALIDATE_TECHTREES]) + + string("="), + &foundParamIndIndex); + string filterList = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(filterList, paramPartTokens, "="); + if (paramPartTokens.size() >= 2) { + string techtreeList = paramPartTokens[1]; + Tokenize(techtreeList, filteredTechTreeList, ","); + + if (filteredTechTreeList.empty() == false) { + printf("Filtering techtrees and only looking for the following:\n"); + for (int idx = 0; idx < (int)filteredTechTreeList.size(); ++idx) { + filteredTechTreeList[idx] = trim(filteredTechTreeList[idx]); + printf("%s\n", filteredTechTreeList[idx].c_str()); + } + } + + if (paramPartTokens.size() >= 3) { + if (paramPartTokens[2] == "purgeunused") { + purgeUnusedFiles = true; + printf("*NOTE All unused techtree files will be deleted!\n"); + } else if (paramPartTokens[2] == "purgeduplicates") { + purgeDuplicateFiles = true; + printf("*NOTE All duplicate techtree files will be merged!\n"); + } else if (paramPartTokens[2] == "gitdelete") { + gitPurgeFiles = true; + printf("*NOTE All unused / duplicate techtree files will be removed " + "from git!\n"); + } else if (paramPartTokens[2] == "hideduplicates") { + showDuplicateFiles = false; + printf("*NOTE All duplicate techtree files will NOT be shown!\n"); + } + } + if (paramPartTokens.size() >= 4) { + if (paramPartTokens[3] == "purgeunused") { + purgeUnusedFiles = true; + printf("*NOTE All unused techtree files will be deleted!\n"); + } else if (paramPartTokens[3] == "purgeduplicates") { + purgeDuplicateFiles = true; + printf("*NOTE All duplicate techtree files will be merged!\n"); + } else if (paramPartTokens[3] == "gitdelete") { + gitPurgeFiles = true; + printf("*NOTE All unused / duplicate techtree files will be removed " + "from git!\n"); + } else if (paramPartTokens[3] == "hideduplicates") { + showDuplicateFiles = false; + printf("*NOTE All duplicate techtree files will NOT be shown!\n"); + } + } + if (paramPartTokens.size() >= 5) { + if (paramPartTokens[4] == "purgeunused") { + purgeUnusedFiles = true; + printf("*NOTE All unused techtree files will be deleted!\n"); + } else if (paramPartTokens[4] == "purgeduplicates") { + purgeDuplicateFiles = true; + printf("*NOTE All duplicate techtree files will be merged!\n"); + } else if (paramPartTokens[4] == "gitdelete") { + gitPurgeFiles = true; + printf("*NOTE All unused / duplicate techtree files will be removed " + "from git!\n"); + } else if (paramPartTokens[4] == "hideduplicates") { + showDuplicateFiles = false; + printf("*NOTE All duplicate techtree files will NOT be shown!\n"); + } + } + } + } + + { printf("\n---------------- Loading factions inside world ----------------"); World world; vector techPaths = config.getPathListForType(ptTechs); - for(int idx = 0; idx < (int)techPaths.size(); idx++) { - string &techPath = techPaths[idx]; - endPathWithSlash(techPath); + for (int idx = 0; idx < (int)techPaths.size(); idx++) { + string &techPath = techPaths[idx]; + endPathWithSlash(techPath); + + for (int idx2 = 0; idx2 < (int)techTreeFiles.size(); idx2++) { + string &techName = techTreeFiles[idx2]; + + if (filteredTechTreeList.empty() == true || + std::find(filteredTechTreeList.begin(), filteredTechTreeList.end(), + techName) != filteredTechTreeList.end()) { + + runTechValidationForPath(techPath, techName, filteredFactionList, + world, purgeUnusedFiles, purgeDuplicateFiles, + showDuplicateFiles, gitPurgeFiles, + purgedMegaBytes); + } + } + } + + printf("\n====== Finished Validation ======\n"); + } +} + +void runTilesetValidationReport(int argc, char **argv) { + printf("====== Started Validation ======\n"); + + Config &config = Config::getInstance(); - for(int idx2 = 0; idx2 < (int)techTreeFiles.size(); idx2++) { - string &techName = techTreeFiles[idx2]; + // Did the user pass a specific tileset to validate? + if (hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_VALIDATE_TILESET]) + + string("=")) == true) { + int foundParamIndIndex = -1; + hasCommandArgument( + argc, argv, string(GAME_ARGS[GAME_ARG_VALIDATE_TILESET]) + string("="), + &foundParamIndIndex); - if( filteredTechTreeList.empty() == true || - std::find(filteredTechTreeList.begin(),filteredTechTreeList.end(),techName) != filteredTechTreeList.end()) { + string filterList = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(filterList, paramPartTokens, "="); - runTechTranslationExtractionForPath(techPath, techName, - filteredFactionList,world); + if (paramPartTokens.size() >= 2) { + string validateTilesetName = paramPartTokens[1]; + + printf("Filtering tileset: %s\n", validateTilesetName.c_str()); + + bool purgeUnusedFiles = false; + if (paramPartTokens.size() >= 3) { + if (paramPartTokens[2] == "purgeunused") { + purgeUnusedFiles = true; + printf("*NOTE All unused tileset files will be deleted!\n"); + } + } + + { + printf("\n---------------- Loading tileset inside world " + "----------------\n"); + + World world; + double purgedMegaBytes = 0; + bool showDuplicateFiles = true; + + bool tilesetFound = false; + + vector tilesetPaths = config.getPathListForType(ptTilesets); + for (int idx = 0; idx < (int)tilesetPaths.size(); idx++) { + string &tilesetPath = tilesetPaths[idx]; + endPathWithSlash(tilesetPath); + + vector tilesetList; + findDirs(tilesetPath, tilesetList, false, false); + for (int idx2 = 0; idx2 < (int)tilesetList.size(); idx2++) { + string &tilesetName = tilesetList[idx2]; + if (tilesetName == validateTilesetName) { + tilesetFound = true; + runTilesetValidationForPath(tilesetPath, tilesetName, world, + purgeUnusedFiles, showDuplicateFiles, + false, false, purgedMegaBytes); } + } + } + + if (tilesetFound == false) { + printf("*ERROR The specified tileset [%s] was NOT FOUND!\n", + validateTilesetName.c_str()); + } + printf("\n====== Finished Validation ======\n"); + } + return; + } else { + printf("\nInvalid missing tileset specified on commandline [%s] value " + "[%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + return; + } + } else { + printf("\nInvalid missing tileset specified on commandline\n\n"); + return; + } +} + +void ShowINISettings(int argc, char **argv, Config &config, + Config &configKeys) { + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_SHOW_INI_SETTINGS]) == + true) { + vector filteredPropertyList; + if (hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_SHOW_INI_SETTINGS]) + + string("=")) == true) { + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_SHOW_INI_SETTINGS]) + + string("="), + &foundParamIndIndex); + string filterList = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(filterList, paramPartTokens, "="); + if (paramPartTokens.size() >= 2) { + string tokenList = paramPartTokens[1]; + Tokenize(tokenList, filteredPropertyList, ","); + + if (filteredPropertyList.empty() == false) { + printf("Filtering properties and only looking for the following:\n"); + for (int idx = 0; idx < (int)filteredPropertyList.size(); ++idx) { + filteredPropertyList[idx] = trim(filteredPropertyList[idx]); + printf("%s\n", filteredPropertyList[idx].c_str()); + } } + } } - printf("\n====== Finished Translation ======\n"); + printf("\nMain settings report\n"); + printf("====================\n"); + vector> mergedMainSettings = + config.getMergedProperties(); + vector> mergedKeySettings = + configKeys.getMergedProperties(); + + // Figure out the max # of tabs we need to format display nicely + int tabCount = 1; + for (int i = 0; i < (int)mergedMainSettings.size(); ++i) { + const pair &nameValue = mergedMainSettings[i]; + + bool displayProperty = false; + if (filteredPropertyList.empty() == false) { + if (find(filteredPropertyList.begin(), filteredPropertyList.end(), + nameValue.first) != filteredPropertyList.end()) { + displayProperty = true; + } + } else { + displayProperty = true; + } + + if (displayProperty == true) { + int requredTabs = ((int)nameValue.first.length() / 8) + 1; + if (nameValue.first.length() % 8) { + requredTabs++; + } + if (requredTabs > tabCount) { + tabCount = requredTabs; + } + } + } + for (int i = 0; i < (int)mergedKeySettings.size(); ++i) { + const pair &nameValue = mergedKeySettings[i]; + + bool displayProperty = false; + if (filteredPropertyList.empty() == false) { + if (find(filteredPropertyList.begin(), filteredPropertyList.end(), + nameValue.first) != filteredPropertyList.end()) { + displayProperty = true; + } + } else { + displayProperty = true; + } + + if (displayProperty == true) { + int requredTabs = ((int)nameValue.first.length() / 8) + 1; + if (nameValue.first.length() % 8) { + requredTabs++; + } + if (requredTabs > tabCount) { + tabCount = requredTabs; + } + } + } + + // Output the properties + for (int i = 0; i < (int)mergedMainSettings.size(); ++i) { + const pair &nameValue = mergedMainSettings[i]; + + bool displayProperty = false; + if (filteredPropertyList.empty() == false) { + if (find(filteredPropertyList.begin(), filteredPropertyList.end(), + nameValue.first) != filteredPropertyList.end()) { + displayProperty = true; + } + } else { + displayProperty = true; + } + + if (displayProperty == true) { + printf("Property Name [%s]", nameValue.first.c_str()); + + int tabs = ((int)nameValue.first.length() / 8) + 1; + for (int j = 0; j < (tabCount - tabs); ++j) { + printf("\t"); + } + + string displayValue = nameValue.second; + if (nameValue.first == "TranslationGetURLPassword") { + displayValue = "*****"; + } + + printf("Value [%s]\n", displayValue.c_str()); + } + } + + printf("\n\nMain key binding settings report\n"); + printf("====================================\n"); + + for (int i = 0; i < (int)mergedKeySettings.size(); ++i) { + const pair &nameValue = mergedKeySettings[i]; + + bool displayProperty = false; + if (filteredPropertyList.empty() == false) { + if (find(filteredPropertyList.begin(), filteredPropertyList.end(), + nameValue.first) != filteredPropertyList.end()) { + displayProperty = true; + } + } else { + displayProperty = true; + } + + if (displayProperty == true) { + printf("Property Name [%s]", nameValue.first.c_str()); + + int tabs = ((int)nameValue.first.length() / 8) + 1; + for (int j = 0; j < (tabCount - tabs); ++j) { + printf("\t"); + } + + printf("Value [%s]\n", nameValue.second.c_str()); + } } + } +} +Steam &initSteamInstance() { + Steam *&steamInstance = CacheManager::getCachedItem( + GameConstants::steamCacheInstanceKey); + if (steamInstance == NULL) { + steamInstance = new Steam(); + } + return *steamInstance; } +void setupSteamSettings(bool steamEnabled, bool steamResetStats, + bool debugEnabled) { + Config &config = Config::getInstance(); + config.setBool("SteamEnabled", steamEnabled, true); + if (steamEnabled) { + printf("*NOTE: Steam Integration Enabled.\n"); -void runTechValidationReport(int argc, char** argv) { - printf("====== Started Validation ======\n"); + if (debugEnabled) { + printf("*NOTE: Steam Debugging Enabled.\n"); + } + Steam::setDebugEnabled(debugEnabled); - bool purgeDuplicateFiles = false; - bool showDuplicateFiles = true; - bool purgeUnusedFiles = false; - bool gitPurgeFiles = false; + Steam &steam = initSteamInstance(); - double purgedMegaBytes=0; - Config &config = Config::getInstance(); + // For Debugging purposes: + if (steamResetStats) { + printf( + "*WARNING: Steam Stats / Achievements are being RESET by request!\n"); + steam.resetStats(true); + } - // Did the user pass a specific scenario to validate? - if(hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_VALIDATE_SCENARIO]) + string("=")) == true) { + string steamPlayerName = steam.userName(); + string steamLang = steam.lang(); + printf("Steam Integration Enabled!\nSteam User Name is [%s] Language is " + "[%s]\n", + steamPlayerName.c_str(), steamLang.c_str()); + + bool needToSaveConfig = false; + string currentPLayerName = config.getString("NetPlayerName", ""); + if (currentPLayerName == "newbie" || currentPLayerName == "") { + config.setString("NetPlayerName", steamPlayerName); + needToSaveConfig = true; + } + if (needToSaveConfig == true) { + config.save(); + } + } +} - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_VALIDATE_SCENARIO]) + string("="),&foundParamIndIndex); +void CheckForDuplicateData() { + Config &config = Config::getInstance(); - string filterList = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(filterList,paramPartTokens,"="); + string duplicateWarnings = ""; - if(paramPartTokens.size() >= 2) { - string validateScenarioName = paramPartTokens[1]; + try { - printf("Filtering scenario: %s\n",validateScenarioName.c_str()); + { - if(paramPartTokens.size() >= 3) { - if(paramPartTokens[2] == "purgeunused") { - purgeUnusedFiles = true; - printf("*NOTE All unused scenario files will be deleted!\n"); - } + string scenarioDir = ""; + vector pathList = config.getPathListForType(ptMaps, scenarioDir); + vector invalidMapList; + vector maps = MapPreview::findAllValidMaps( + pathList, scenarioDir, false, true, &invalidMapList); + std::sort(maps.begin(), maps.end()); + + if (maps.empty() == true) { + throw megaglest_runtime_error("No maps were found!", true); + } else if (invalidMapList.empty() == false) { + string errorMsg = + "Warning invalid maps were detected (will be ignored):\n"; + for (int i = 0; i < (int)invalidMapList.size(); ++i) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "map [%s]\n", invalidMapList[i].c_str()); + + errorMsg += szBuf; + } + duplicateWarnings += errorMsg; + } + + vector duplicateMapsToRename; + for (int i = 0; i < (int)maps.size(); ++i) { + string map1 = maps[i]; + for (int j = 0; j < (int)maps.size(); ++j) { + if (i != j) { + string map2 = maps[j]; + + if (map1 == map2) { + if (std::find(duplicateMapsToRename.begin(), + duplicateMapsToRename.end(), + map1) == duplicateMapsToRename.end()) { + duplicateMapsToRename.push_back(map1); + } } + } + } + } + if (duplicateMapsToRename.empty() == false) { + string errorMsg = "Warning duplicate maps were detected and renamed:\n"; + for (int i = 0; i < (int)duplicateMapsToRename.size(); ++i) { + string currentPath = pathList[1]; + endPathWithSlash(currentPath); + + string oldFile = currentPath + duplicateMapsToRename[i]; + string newFile = currentPath + duplicateMapsToRename[i]; + string ext = extractExtension(newFile); + newFile = newFile.substr(0, newFile.length() - ext.length() - 1); + newFile = newFile + "_custom." + ext; + + char szBuf[8096] = ""; + int result = rename(oldFile.c_str(), newFile.c_str()); + if (result != 0) { + char *errmsg = strerror(errno); + snprintf(szBuf, 8096, "Error [%s]\nCould not rename [%s] to [%s]!", + errmsg, oldFile.c_str(), newFile.c_str()); + throw megaglest_runtime_error(szBuf, true); + } else { + snprintf(szBuf, 8096, "map [%s] in [%s]\nwas renamed to [%s]", + duplicateMapsToRename[i].c_str(), oldFile.c_str(), + newFile.c_str()); + } + errorMsg += szBuf; + } + duplicateWarnings += errorMsg; + } + } - { - printf("\n---------------- Loading scenario inside world ----------------\n"); - - bool scenarioFound = false; - World world; - std::vector filteredFactionList; - - vector scenarioPaths = config.getPathListForType(ptScenarios); - for(int idx = 0; idx < (int)scenarioPaths.size(); idx++) { - string &scenarioPath = scenarioPaths[idx]; - endPathWithSlash(scenarioPath); - - vector scenarioList; - findDirs(scenarioPath, scenarioList, false, false); - for(int idx2 = 0; idx2 < (int)scenarioList.size(); idx2++) { - string &scenarioName = scenarioList[idx2]; - - if(scenarioName == validateScenarioName) { - scenarioFound = true; - - string file = scenarioPath + scenarioName + "/" + scenarioName + ".xml"; - - XmlTree xmlTree; - xmlTree.load(file,Properties::getTagReplacementValues()); - const XmlNode *scenarioNode= xmlTree.getRootNode(); - string techName = scenarioNode->getChild("tech-tree")->getAttribute("value")->getValue(); - - // Self Contained techtree? - string scenarioTechtree = scenarioPath + scenarioName + "/" + techName + "/" + techName + ".xml"; - - printf("\nFound Scenario [%s] looking for techtree [%s]...\n",scenarioName.c_str(),scenarioTechtree.c_str()); - - if(fileExists(scenarioTechtree) == true) { - string techPath = scenarioPath + scenarioName + "/"; - - printf("\nFound Scenario [%s] with custom techtree [%s] validating...\n",scenarioName.c_str(),techName.c_str()); - runTechValidationForPath(techPath, techName, filteredFactionList, - world, purgeUnusedFiles, showDuplicateFiles, false, false, purgedMegaBytes); - } - else { - vector techPaths = config.getPathListForType(ptTechs); - for(int idx = 0; idx < (int)techPaths.size(); idx++) { - string &techPath = techPaths[idx]; - endPathWithSlash(techPath); - scenarioTechtree = techPath + "/" + techName + "/" + techName + ".xml"; - if(fileExists(scenarioTechtree) == true) { - printf("\nFound Scenario [%s] with techtree [%s] validating...\n",scenarioName.c_str(),techName.c_str()); - runTechValidationForPath(techPath, techName, filteredFactionList, - world, purgeUnusedFiles, showDuplicateFiles, false, false, purgedMegaBytes); - - break; - } - } - } - } - } + { + // tilesets + std::vector tileSets; + vector tilesetPaths = config.getPathListForType(ptTilesets); + findDirs(tilesetPaths, tileSets, false, true); + + if (tileSets.empty()) { + throw megaglest_runtime_error("No tilesets were found!", true); + } + + vector duplicateTilesetsToRename; + for (int i = 0; i < (int)tileSets.size(); ++i) { + string tileSet1 = tileSets[i]; + for (int j = 0; j < (int)tileSets.size(); ++j) { + if (i != j) { + string tileSet2 = tileSets[j]; + if (tileSet1 == tileSet2) { + if (std::find(duplicateTilesetsToRename.begin(), + duplicateTilesetsToRename.end(), + tileSet1) == duplicateTilesetsToRename.end()) { + duplicateTilesetsToRename.push_back(tileSet1); + } } - - if(scenarioFound == false) { - printf("\nWARNING, the scenario [%s] was NOT FOUND!\n",validateScenarioName.c_str()); + } + } + } + if (duplicateTilesetsToRename.empty() == false) { + string errorMsg = + "Warning duplicate tilesets were detected and renamed:\n"; + + for (int i = 0; i < (int)duplicateTilesetsToRename.size(); ++i) { + string currentPath = tilesetPaths[1]; + endPathWithSlash(currentPath); + + string oldFile = currentPath + duplicateTilesetsToRename[i]; + string newFile = currentPath + duplicateTilesetsToRename[i]; + newFile = newFile + "_custom"; + + char szBuf[8096] = ""; + int result = rename(oldFile.c_str(), newFile.c_str()); + if (result != 0) { + char *errmsg = strerror(errno); + snprintf(szBuf, 8096, "Error [%s]\nCould not rename [%s] to [%s]!", + errmsg, oldFile.c_str(), newFile.c_str()); + throw megaglest_runtime_error(szBuf, true); + } else { + snprintf(szBuf, 8096, "tileset [%s] in [%s]\nwas renamed to [%s]", + duplicateTilesetsToRename[i].c_str(), oldFile.c_str(), + newFile.c_str()); + + string tilesetName = extractFileFromDirectoryPath(oldFile); + oldFile = newFile + "/" + tilesetName + ".xml"; + newFile = newFile + "/" + tilesetName + "_custom.xml"; + + result = rename(oldFile.c_str(), newFile.c_str()); + + if (result != 0) { + char *errmsg = strerror(errno); + snprintf(szBuf, 8096, + "Error [%s]\nCould not rename [%s] to [%s]!", errmsg, + oldFile.c_str(), newFile.c_str()); + throw megaglest_runtime_error(szBuf, true); } - printf("\n====== Finished Validation ======\n"); + } + errorMsg += szBuf; + } + duplicateWarnings += errorMsg; + } + } + + { + vector techPaths = config.getPathListForType(ptTechs); + vector techTrees; + findDirs(techPaths, techTrees, false, true); + if (techTrees.empty()) { + throw megaglest_runtime_error("No tech-trees were found (dup)!", true); + } + + vector duplicateTechtreesToRename; + for (int i = 0; i < (int)techTrees.size(); ++i) { + string techtree1 = techTrees[i]; + for (int j = 0; j < (int)techTrees.size(); ++j) { + if (i != j) { + string techtree2 = techTrees[j]; + if (techtree1 == techtree2) { + if (std::find(duplicateTechtreesToRename.begin(), + duplicateTechtreesToRename.end(), + techtree1) == duplicateTechtreesToRename.end()) { + duplicateTechtreesToRename.push_back(techtree1); + } } - return; + } } - else { - printf("\nInvalid missing scenario specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - return; + } + if (duplicateTechtreesToRename.empty() == false) { + string errorMsg = + "Warning duplicate techtrees were detected and renamed:\n"; + + for (int i = 0; i < (int)duplicateTechtreesToRename.size(); ++i) { + string currentPath = techPaths[1]; + endPathWithSlash(currentPath); + + string oldFile = currentPath + duplicateTechtreesToRename[i]; + string newFile = currentPath + duplicateTechtreesToRename[i]; + newFile = newFile + "_custom"; + + char szBuf[8096] = ""; + int result = rename(oldFile.c_str(), newFile.c_str()); + if (result != 0) { + char *errmsg = strerror(errno); + snprintf(szBuf, 8096, "Error [%s]\nCould not rename [%s] to [%s]!", + errmsg, oldFile.c_str(), newFile.c_str()); + throw megaglest_runtime_error(szBuf, true); + } else { + snprintf(szBuf, 8096, "techtree [%s] in [%s]\nwas renamed to [%s]", + duplicateTechtreesToRename[i].c_str(), oldFile.c_str(), + newFile.c_str()); + + string tilesetName = extractFileFromDirectoryPath(oldFile); + oldFile = newFile + "/" + tilesetName + ".xml"; + newFile = newFile + "/" + tilesetName + "_custom.xml"; + + int rename_result = rename(oldFile.c_str(), newFile.c_str()); + if (rename_result != 0) { + printf("Error renaming [%s] to [%s]\n", oldFile.c_str(), + newFile.c_str()); + } + } + errorMsg += szBuf; } + duplicateWarnings += errorMsg; + } } - // Did the user pass a specific list of factions to validate? - std::vector filteredFactionList; - if(hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_VALIDATE_FACTIONS]) + string("=")) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_VALIDATE_FACTIONS]) + string("="),&foundParamIndIndex); + } catch (const megaglest_runtime_error &ex) { + if (mainProgram) { + mainProgram->getState()->setForceMouseRender(true); + } + ExceptionHandler::DisplayMessage(ex.what(), false); + } - string filterList = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(filterList,paramPartTokens,"="); + if (duplicateWarnings != "") { + if (mainProgram) { + mainProgram->getState()->setForceMouseRender(true); + } + ExceptionHandler::DisplayMessage(duplicateWarnings.c_str(), false); + } +} - if(paramPartTokens.size() >= 2) { - string factionList = paramPartTokens[1]; - Tokenize(factionList,filteredFactionList,","); +int handleCreateDataArchivesCommand(int argc, char **argv) { + int return_value = 1; + if (hasCommandArgument(argc, argv, + GAME_ARGS[GAME_ARG_CREATE_DATA_ARCHIVES]) == true) { + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_CREATE_DATA_ARCHIVES]) + + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_CREATE_DATA_ARCHIVES]), + &foundParamIndIndex); + } + string paramValue = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(paramValue, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string compress_item = paramPartTokens[1]; + bool includeMainData = false; + if (paramPartTokens.size() >= 3 && paramPartTokens[2] == "include_main") { + includeMainData = true; + } + + Config &config = Config::getInstance(); + string fileArchiveExtension = + config.getString("FileArchiveExtension", ""); + string fileArchiveCompressCommand = + config.getString("FileArchiveCompressCommand", ""); + string fileArchiveCompressCommandParameters = + config.getString("FileArchiveCompressCommandParameters", ""); + int32 fileArchiveCompressCommandSuccessResult = + config.getInt("FileArchiveCompressCommandSuccessResult", "0"); + + string userData = config.getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + + int typesSelected = 0; + if (compress_item == "techtrees" || compress_item == "all") { + typesSelected++; + + vector pathList = config.getPathListForType(ptTechs, ""); + vector results; + findDirs(pathList, results); + + printf( + "Techtrees found:\n===========================================\n"); + for (unsigned int i = 0; i < results.size(); ++i) { + string name = results[i]; + + for (unsigned int j = 0; j < pathList.size(); ++j) { + string techPath = pathList[j]; + if (techPath != "") { + endPathWithSlash(techPath); + } - if(filteredFactionList.empty() == false) { - printf("Filtering factions and only looking for the following:\n"); - for(int idx = 0; idx < (int)filteredFactionList.size(); ++idx) { - filteredFactionList[idx] = trim(filteredFactionList[idx]); - printf("%s\n",filteredFactionList[idx].c_str()); + vector results2; + findDirs(techPath + name + "/factions", results2, false, true); + if (results2.empty() == false) { + string techtreePath = techPath + name; + if (includeMainData == false) { + if (techtreePath.find(userData) == techPath.npos) { + printf("Skipping techtree: [%s]\n", techtreePath.c_str()); + continue; } + } + + string downloadArchive = techtreePath + fileArchiveExtension; + + if (fileExists(downloadArchive) == true) { + bool removed = removeFile(downloadArchive); + if (removed == false) { + printf("Error could not remove old file: [%s]\n", + downloadArchive.c_str()); + } + } + string compressCmd = getFullFileArchiveCompressCommand( + fileArchiveCompressCommand, + fileArchiveCompressCommandParameters, downloadArchive, + techtreePath); + + printf("Running compression command: %s\n", compressCmd.c_str()); + + if (executeShellCommand( + compressCmd, fileArchiveCompressCommandSuccessResult) == + false) { + printf("Error could not create new file: [%s]\n", + downloadArchive.c_str()); + } + + if (fileExists(downloadArchive) == true) { + off_t fileSize = getFileSize(downloadArchive); + // convert to MB + double megaBytes = ((double)fileSize / 1048576.0); + printf("%s [download archive %.2fMB]\n", name.c_str(), + megaBytes); + } + } + } + } + printf("===========================================\nTotal:" + " " MG_SIZE_T_SPECIFIER "\n", + results.size()); + } + if (compress_item == "tilesets" || compress_item == "all") { + typesSelected++; + + vector pathList = config.getPathListForType(ptTilesets, ""); + vector results; + findDirs(pathList, results); + + printf( + "Tilesets found:\n===========================================\n"); + for (unsigned int i = 0; i < results.size(); ++i) { + string name = results[i]; + + for (unsigned int j = 0; j < pathList.size(); ++j) { + string tilesetPath = pathList[j]; + if (tilesetPath != "") { + endPathWithSlash(tilesetPath); } - if(paramPartTokens.size() >= 3) { - if(paramPartTokens[2] == "purgeunused") { - purgeUnusedFiles = true; - printf("*NOTE All unused faction files will be deleted!\n"); - } + if (fileExists(tilesetPath + name + "/" + name + ".xml") == true) { + string tilesetDataPath = tilesetPath + name; + if (includeMainData == false) { + if (tilesetPath.find(userData) == tilesetPath.npos) { + printf("Skipping tileset data: [%s]\n", + tilesetDataPath.c_str()); + continue; + } + } + + string downloadArchive = tilesetDataPath + fileArchiveExtension; + + if (fileExists(downloadArchive) == true) { + bool removed = removeFile(downloadArchive); + if (removed == false) { + printf("Error could not remove old file: [%s]\n", + downloadArchive.c_str()); + } + } + string compressCmd = getFullFileArchiveCompressCommand( + fileArchiveCompressCommand, + fileArchiveCompressCommandParameters, downloadArchive, + tilesetDataPath); + + printf("Running compression command: %s\n", compressCmd.c_str()); + + if (executeShellCommand( + compressCmd, fileArchiveCompressCommandSuccessResult) == + false) { + printf("Error could not create new file: [%s]\n", + downloadArchive.c_str()); + } + + if (fileExists(downloadArchive) == true) { + off_t fileSize = getFileSize(downloadArchive); + // convert to MB + double megaBytes = ((double)fileSize / 1048576.0); + printf("%s [download archive %.2fMB]\n", name.c_str(), + megaBytes); + } + + break; } + } } + printf("===========================================\nTotal:" + " " MG_SIZE_T_SPECIFIER "\n", + results.size()); + } + if (typesSelected == 0) { + printf("Compress item [%s] is not valid!\n", compress_item.c_str()); + return_value = 1; + } else + return_value = 0; + } else { + printf( + "\nInvalid missing map specified on commandline [%s] value [%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + + return_value = 1; + } + } + + return return_value; +} + +int handleShowCRCValuesCommand(int argc, char **argv) { + int return_value = 1; + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_SHOW_MAP_CRC]) == + true) { + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_SHOW_MAP_CRC]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_SHOW_MAP_CRC]), + &foundParamIndIndex); + } + string paramValue = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(paramValue, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string itemName = paramPartTokens[1]; + + string file = Config::getMapPath(itemName, "", false); + if (file != "") { + Checksum checksum; + checksum.addFile(file); + uint32 crcValue = checksum.getSum(); + + printf("CRC value for map [%s] file [%s] is [%u]\n", itemName.c_str(), + file.c_str(), crcValue); + + return_value = 0; + } else { + printf("Map [%s] was NOT FOUND\n", itemName.c_str()); + return_value = 1; + } + } else { + printf( + "\nInvalid missing map specified on commandline [%s] value [%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + + return_value = 1; + } + } + + else if (hasCommandArgument(argc, argv, + GAME_ARGS[GAME_ARG_SHOW_TILESET_CRC]) == true) { + int foundParamIndIndex = -1; + hasCommandArgument( + argc, argv, string(GAME_ARGS[GAME_ARG_SHOW_TILESET_CRC]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_SHOW_TILESET_CRC]), + &foundParamIndIndex); + } + string paramValue = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(paramValue, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string itemName = paramPartTokens[1]; + + Config &config = Config::getInstance(); + uint32 crcValue = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTilesets, ""), + string("/") + itemName + string("/*"), ".xml", NULL, true); + if (crcValue != 0) { + printf("CRC value for tileset [%s] is [%u]\n", itemName.c_str(), + crcValue); + + return_value = 0; + } else { + printf("Tileset [%s] was NOT FOUND\n", itemName.c_str()); + return_value = 1; + } + } else { + printf("\nInvalid missing tileset specified on commandline [%s] value " + "[%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + + return_value = 1; + } + } + + else if (hasCommandArgument(argc, argv, + GAME_ARGS[GAME_ARG_SHOW_TECHTREE_CRC]) == true) { + int foundParamIndIndex = -1; + hasCommandArgument( + argc, argv, string(GAME_ARGS[GAME_ARG_SHOW_TECHTREE_CRC]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_SHOW_TECHTREE_CRC]), + &foundParamIndIndex); } + string paramValue = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(paramValue, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string itemName = paramPartTokens[1]; + + Config &config = Config::getInstance(); + uint32 crcValue = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTechs, ""), "/" + itemName + "/*", ".xml", + NULL, true); + if (crcValue != 0) { + printf("CRC value for techtree [%s] is [%u]\n", itemName.c_str(), + crcValue); + + return_value = 0; + } else { + printf("Techtree [%s] was NOT FOUND\n", itemName.c_str()); + + return_value = 1; + } + } else { + printf("\nInvalid missing techtree specified on commandline [%s] value " + "[%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + + return_value = 1; + } + } + + else if (hasCommandArgument(argc, argv, + GAME_ARGS[GAME_ARG_SHOW_SCENARIO_CRC]) == true) { + int foundParamIndIndex = -1; + hasCommandArgument( + argc, argv, string(GAME_ARGS[GAME_ARG_SHOW_SCENARIO_CRC]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_SHOW_SCENARIO_CRC]), + &foundParamIndIndex); + } + string paramValue = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(paramValue, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string itemName = paramPartTokens[1]; + + Config &config = Config::getInstance(); + uint32 crcValue = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptScenarios, ""), "/" + itemName + "/*", + ".xml", NULL, true); + if (crcValue != 0) { + printf("CRC value for scenario [%s] is [%u]\n", itemName.c_str(), + crcValue); + + return_value = 0; + } else { + printf("Scenario [%s] was NOT FOUND\n", itemName.c_str()); + return_value = 1; + } + } else { + printf("\nInvalid missing scenario specified on commandline [%s] value " + "[%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + + return_value = 0; + } + } + + else if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_SHOW_PATH_CRC]) == + true) { + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_SHOW_PATH_CRC]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_SHOW_PATH_CRC]), + &foundParamIndIndex); + } + + string paramValue = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(paramValue, paramPartTokens, "="); + if (paramPartTokens.size() >= 3 && paramPartTokens[1].length() > 0) { + string itemName = paramPartTokens[1]; + string itemNameFilter = paramPartTokens[2]; + uint32 crcValue = getFolderTreeContentsCheckSumRecursively( + itemName, itemNameFilter, NULL, true); + + printf("CRC value for path [%s] filter [%s] is [%u]\n", itemName.c_str(), + itemNameFilter.c_str(), crcValue); + + return_value = 0; + } else { + if (paramPartTokens.size() < 2) { + printf( + "\nInvalid missing path and filter specified on commandline [%s] " + "value [%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + } + if (paramPartTokens.size() < 3) { + printf( + "\nInvalid missing filter specified on commandline [%s] value " + "[%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 3 ? paramPartTokens[2].c_str() : NULL)); + } + + return_value = 1; + } + } + + return return_value; +} + +int handleListDataCommand(int argc, char **argv) { + int return_value = 1; + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_MAPS]) == true) { + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_LIST_MAPS]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_LIST_MAPS]), + &foundParamIndIndex); + } + + Config &config = Config::getInstance(); + vector pathList = config.getPathListForType(ptMaps, ""); + vector maps = + MapPreview::findAllValidMaps(pathList, "", false, true); + std::sort(maps.begin(), maps.end()); + + string paramValue = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(paramValue, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string itemNameFilter = paramPartTokens[1]; + printf("Using filter for maps list [%s]\n", itemNameFilter.c_str()); + + vector filteredMaps; + for (unsigned int i = 0; i < maps.size(); ++i) { + string mapName = maps[i]; + if (itemNameFilter.find("*") != itemNameFilter.npos) { + if (StartsWith(mapName, itemNameFilter.substr( + 0, itemNameFilter.find("*"))) == true) { + filteredMaps.push_back(mapName); + } + } else if (mapName == itemNameFilter) { + filteredMaps.push_back(mapName); + } + } + maps = filteredMaps; + } + + printf("Maps found:\n===========================================\n"); + for (unsigned int i = 0; i < maps.size(); ++i) { + string mapName = maps[i]; + printf("%s\n", mapName.c_str()); + } + printf("===========================================\nTotal:" + " " MG_SIZE_T_SPECIFIER "\n", + maps.size()); + + return_value = 0; + } + + else if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_TECHTRESS]) == + true) { + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_LIST_TECHTRESS]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_LIST_TECHTRESS]), + &foundParamIndIndex); + } + + Config &config = Config::getInstance(); + vector pathList = config.getPathListForType(ptTechs, ""); vector results; - findDirs(config.getPathListForType(ptTechs), results); - vector techTreeFiles = results; - // Did the user pass a specific list of techtrees to validate? - std::vector filteredTechTreeList; - if(hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_VALIDATE_TECHTREES]) + string("=")) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_VALIDATE_TECHTREES]) + string("="),&foundParamIndIndex); - string filterList = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(filterList,paramPartTokens,"="); - if(paramPartTokens.size() >= 2) { - string techtreeList = paramPartTokens[1]; - Tokenize(techtreeList,filteredTechTreeList,","); - - if(filteredTechTreeList.empty() == false) { - printf("Filtering techtrees and only looking for the following:\n"); - for(int idx = 0; idx < (int)filteredTechTreeList.size(); ++idx) { - filteredTechTreeList[idx] = trim(filteredTechTreeList[idx]); - printf("%s\n",filteredTechTreeList[idx].c_str()); - } - } + findDirs(pathList, results); + + bool showfactions = false; + string paramValue = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(paramValue, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string cmd = paramPartTokens[1]; + if (cmd == "showfactions") { + showfactions = true; + } else { + throw megaglest_runtime_error("unknown command for techtreelist [" + + cmd + "]"); + } + printf("Using special command for techtree list [%s]\n", cmd.c_str()); + } - if(paramPartTokens.size() >= 3) { - if(paramPartTokens[2] == "purgeunused") { - purgeUnusedFiles = true; - printf("*NOTE All unused techtree files will be deleted!\n"); - } - else if(paramPartTokens[2] == "purgeduplicates") { - purgeDuplicateFiles = true; - printf("*NOTE All duplicate techtree files will be merged!\n"); - } - else if(paramPartTokens[2] == "gitdelete") { - gitPurgeFiles = true; - printf("*NOTE All unused / duplicate techtree files will be removed from git!\n"); - } - else if(paramPartTokens[2] == "hideduplicates") { - showDuplicateFiles = false; - printf("*NOTE All duplicate techtree files will NOT be shown!\n"); - } - } - if(paramPartTokens.size() >= 4) { - if(paramPartTokens[3] == "purgeunused") { - purgeUnusedFiles = true; - printf("*NOTE All unused techtree files will be deleted!\n"); - } - else if(paramPartTokens[3] == "purgeduplicates") { - purgeDuplicateFiles = true; - printf("*NOTE All duplicate techtree files will be merged!\n"); - } - else if(paramPartTokens[3] == "gitdelete") { - gitPurgeFiles = true; - printf("*NOTE All unused / duplicate techtree files will be removed from git!\n"); - } - else if(paramPartTokens[3] == "hideduplicates") { - showDuplicateFiles = false; - printf("*NOTE All duplicate techtree files will NOT be shown!\n"); - } - } - if(paramPartTokens.size() >= 5) { - if(paramPartTokens[4] == "purgeunused") { - purgeUnusedFiles = true; - printf("*NOTE All unused techtree files will be deleted!\n"); - } - else if(paramPartTokens[4] == "purgeduplicates") { - purgeDuplicateFiles = true; - printf("*NOTE All duplicate techtree files will be merged!\n"); - } - else if(paramPartTokens[4] == "gitdelete") { - gitPurgeFiles = true; - printf("*NOTE All unused / duplicate techtree files will be removed from git!\n"); - } - else if(paramPartTokens[4] == "hideduplicates") { - showDuplicateFiles = false; - printf("*NOTE All duplicate techtree files will NOT be shown!\n"); - } + printf("Techtrees found:\n===========================================\n"); + for (unsigned int i = 0; i < results.size(); ++i) { + string name = results[i]; + + for (unsigned int j = 0; j < pathList.size(); ++j) { + string techPath = pathList[j]; + if (techPath != "") { + endPathWithSlash(techPath); + } + vector results2; + findDirs(techPath + name + "/factions", results2, false, true); + if (results2.empty() == false) { + string downloadArchive = techPath + name + ".7z"; + + if (fileExists(downloadArchive) == true) { + off_t fileSize = getFileSize(downloadArchive); + // convert to MB + double megaBytes = ((double)fileSize / 1048576.0); + printf("%s [download archive %.2fMB]\n", name.c_str(), megaBytes); + } else { + printf("%s\n", name.c_str()); + } + + if (showfactions == true) { + printf("--> Factions:\n"); + for (unsigned int k = 0; k < results2.size(); ++k) { + string name2 = results2[k]; + printf("--> %s\n", name2.c_str()); } + printf("--> Total Factions: " MG_SIZE_T_SPECIFIER "\n", + results2.size()); + break; + } + } + } + } + printf("===========================================\nTotal " + "Techtrees: " MG_SIZE_T_SPECIFIER "\n", + results.size()); + + return_value = 0; + } + + else if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_SCENARIOS]) == + true) { + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_LIST_SCENARIOS]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_LIST_SCENARIOS]), + &foundParamIndIndex); + } + + Config &config = Config::getInstance(); + vector pathList = config.getPathListForType(ptScenarios, ""); + vector results; + findDirs(pathList, results); + + string paramValue = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(paramValue, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string itemNameFilter = paramPartTokens[1]; + printf("Using filter for scenarios list [%s]\n", itemNameFilter.c_str()); + + vector filtered; + for (unsigned int i = 0; i < results.size(); ++i) { + string name = results[i]; + if (itemNameFilter.find("*") != itemNameFilter.npos) { + if (StartsWith(name, itemNameFilter.substr( + 0, itemNameFilter.find("*"))) == true) { + filtered.push_back(name); + } + } else if (name == itemNameFilter) { + filtered.push_back(name); + } + } + results = filtered; + } + + printf("Scenarios found:\n===========================================\n"); + for (unsigned int i = 0; i < results.size(); ++i) { + string name = results[i]; + printf("%s\n", name.c_str()); + } + printf("===========================================\nTotal:" + " " MG_SIZE_T_SPECIFIER "\n", + results.size()); + + return_value = 0; + } + + else if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_TILESETS]) == + true) { + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_LIST_TILESETS]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_LIST_TILESETS]), + &foundParamIndIndex); + } + + Config &config = Config::getInstance(); + vector pathList = config.getPathListForType(ptTilesets, ""); + vector results; + findDirs(pathList, results); + + string paramValue = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(paramValue, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string itemNameFilter = paramPartTokens[1]; + printf("Using filter for tilesets list [%s]\n", itemNameFilter.c_str()); + + vector filtered; + for (unsigned int i = 0; i < results.size(); ++i) { + string name = results[i]; + if (itemNameFilter.find("*") != itemNameFilter.npos) { + if (StartsWith(name, itemNameFilter.substr( + 0, itemNameFilter.find("*"))) == true) { + filtered.push_back(name); + } + } else if (name == itemNameFilter) { + filtered.push_back(name); + } + } + results = filtered; + } + + printf("Tilesets found:\n===========================================\n"); + for (unsigned int i = 0; i < results.size(); ++i) { + string name = results[i]; + + for (unsigned int j = 0; j < pathList.size(); ++j) { + string tilesetPath = pathList[j]; + if (tilesetPath != "") { + endPathWithSlash(tilesetPath); } + if (fileExists(tilesetPath + name + "/" + name + ".xml") == true) { + string downloadArchive = tilesetPath + name + ".7z"; + if (fileExists(downloadArchive) == true) { + off_t fileSize = getFileSize(downloadArchive); + // convert to MB + double megaBytes = ((double)fileSize / 1048576.0); + printf("%s [download archive %.2fMB]\n", name.c_str(), megaBytes); + } else { + printf("%s\n", name.c_str()); + } + + break; + } + } + } + printf("===========================================\nTotal:" + " " MG_SIZE_T_SPECIFIER "\n", + results.size()); + + return_value = 0; + } + + else if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_TUTORIALS]) == + true) { + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_LIST_TUTORIALS]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_LIST_TUTORIALS]), + &foundParamIndIndex); } - { - printf("\n---------------- Loading factions inside world ----------------"); - World world; + Config &config = Config::getInstance(); + vector pathList = config.getPathListForType(ptTutorials, ""); + vector results; + findDirs(pathList, results); + + string paramValue = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(paramValue, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string itemNameFilter = paramPartTokens[1]; + printf("Using filter for tutorials list [%s]\n", itemNameFilter.c_str()); + + vector filtered; + for (unsigned int i = 0; i < results.size(); ++i) { + string name = results[i]; + if (itemNameFilter.find("*") != itemNameFilter.npos) { + if (StartsWith(name, itemNameFilter.substr( + 0, itemNameFilter.find("*"))) == true) { + filtered.push_back(name); + } + } else if (name == itemNameFilter) { + filtered.push_back(name); + } + } + results = filtered; + } + + printf("Tutorials found:\n===========================================\n"); + for (unsigned int i = 0; i < results.size(); ++i) { + string name = results[i]; + + for (unsigned int j = 0; j < pathList.size(); ++j) { + string tutorialsPath = pathList[j]; + if (tutorialsPath != "") { + endPathWithSlash(tutorialsPath); + } + if (fileExists(tutorialsPath + name + "/" + name + ".xml") == true) { + string downloadArchive = tutorialsPath + name + ".7z"; + if (fileExists(downloadArchive) == true) { + off_t fileSize = getFileSize(downloadArchive); + // convert to MB + double megaBytes = ((double)fileSize / 1048576.0); + printf("%s [download archive %.2fMB]\n", name.c_str(), megaBytes); + } else { + printf("%s\n", name.c_str()); + } + + break; + } + } + } + printf("===========================================\nTotal:" + " " MG_SIZE_T_SPECIFIER "\n", + results.size()); + + return_value = 0; + } + + return return_value; +} + +int glestMain(int argc, char **argv) { +#ifdef SL_LEAK_DUMP + // AllocInfo::set_application_binary(executable_path(argv[0],true)); + string &app = AllocInfo::get_application_binary(); + app = executable_path(argv[0], true); + // want_full_leak_stacktrace = true; + // want_full_leak_stacktrace_line_numbers = true; + +#endif + + Thread::setMainThreadId(); + // printf("START ALLOC char 200\n"); + // char *ptr = new char[200]; + // printf("END ALLOC char 200\n"); + // return -1; + SystemFlags::VERBOSE_MODE_ENABLED = false; + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VERBOSE_MODE]) == + true) { + SystemFlags::VERBOSE_MODE_ENABLED = true; + Thread::setEnableVerboseMode(true); + // LuaScript::setDebugModeEnabled(true); + } + // DEbug testing threads + // Thread::setEnableVerboseMode(true); + + PlatformExceptionHandler::application_binary = executable_path(argv[0], true); + mg_app_name = GameConstants::application_name; + mailStringSupport = mailString; + SystemFlags::ENABLE_THREADED_LOGGING = false; + disableBacktrace = false; + bool foundInvalidArgs = false; + preCacheThread = NULL; + +#ifndef NO_APPIMAGE + Properties::setAppDirPath(); +#ifdef APPIMAGE_NODATA + Properties::setAppimageDirPath(); +#endif +#endif + + Properties::setApplicationPath(executable_path(argv[0])); + Properties::setApplicationDataPath(executable_path(argv[0])); + Properties::setGameVersion(glestVersionString); + + ServerSocket::setMaxPlayerCount(GameConstants::maxPlayers); + + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_DISABLE_BACKTRACE]) == + true) { + disableBacktrace = true; + } + PlatformExceptionHandler::disableBacktrace = disableBacktrace; + +#if defined(CUSTOM_DATA_INSTALL_PATH) + if (SystemFlags::VERBOSE_MODE_ENABLED) +#ifndef NO_APPIMAGE + printf("\n\nCUSTOM_DATA_INSTALL_PATH = [%s]\n\n", + Properties::appendAppImagePath( + formatPath(TOSTRING(CUSTOM_DATA_INSTALL_PATH))) + .c_str()); +#else + printf("\n\nCUSTOM_DATA_INSTALL_PATH = [%s]\n\n", + formatPath(TOSTRING(CUSTOM_DATA_INSTALL_PATH)).c_str()); +#endif +#endif + + const int knownArgCount = sizeof(GAME_ARGS) / sizeof(GAME_ARGS[0]); + for (int idx = 1; idx < argc; ++idx) { + if (hasCommandArgument(knownArgCount, (char **)&GAME_ARGS[0], argv[idx], + NULL, 0, true) == false) { + foundInvalidArgs = true; + printf("\nInvalid argument: %s", argv[idx]); + } + } + + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_HELP]) == true || + foundInvalidArgs == true) { + + printParameterHelp(argv[0], foundInvalidArgs); + return 2; + } + + if (hasCommandArgument( + argc, argv, string(GAME_ARGS[GAME_ARG_MASTERSERVER_MODE])) == true) { + // isMasterServerModeEnabled = true; + // Window::setMasterserverMode(isMasterServerModeEnabled); + GlobalStaticFlags::setIsNonGraphicalModeEnabled(true); + + int foundParamIndIndex = -1; + hasCommandArgument( + argc, argv, string(GAME_ARGS[GAME_ARG_MASTERSERVER_MODE]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_MASTERSERVER_MODE]), + &foundParamIndIndex); + } + string paramValue = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(paramValue, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string headless_command_list = paramPartTokens[1]; + + vector paramHeadlessCommandList; + Tokenize(headless_command_list, paramHeadlessCommandList, ","); + + for (unsigned int i = 0; i < paramHeadlessCommandList.size(); ++i) { + string headless_command = paramHeadlessCommandList[i]; + if (headless_command == "exit") { + printf("Forcing quit after game has completed [%s]\n", + headless_command.c_str()); + Program::setWantShutdownApplicationAfterGame(true); + } else if (headless_command == "vps") { + printf("Disabled reading from console [%s]\n", + headless_command.c_str()); + disableheadless_console = true; + } else if (headless_command == "lan") { + printf("Forcing local LAN mode [%s]\n", headless_command.c_str()); + GlobalStaticFlags::setFlag(gsft_lan_mode); + } + } + } + } + + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_SERVER_TITLE]) == + true) { + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_SERVER_TITLE]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_SERVER_TITLE]), + &foundParamIndIndex); + } + string paramValue = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(paramValue, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + Config &config = Config::getInstance(); + string serverTitle = paramPartTokens[1]; + printf("Forcing serverTitle[%s]\n", serverTitle.c_str()); + + config.setString("ServerTitle", serverTitle, true); + } else { + printf("\nInvalid missing server title specified on commandline [%s] " + "value [%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + + return 1; + } + } + + // #ifdef WIN32 + // SocketManager winSockManager; + // #endif + + bool haveSpecialOutputCommandLineOption = false; + + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_OPENGL_INFO]) == true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_SDL_INFO]) == true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LUA_INFO]) == true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_CURL_INFO]) == true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_XERCES_INFO]) == true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VERSION]) == true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_SHOW_INI_SETTINGS]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VALIDATE_TECHTREES]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VALIDATE_FACTIONS]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VALIDATE_SCENARIO]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VALIDATE_TILESET]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_TRANSLATE_TECHTREES]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_MAPS]) == true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_TECHTRESS]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_SCENARIOS]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_TILESETS]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_TUTORIALS]) == + true || + hasCommandArgument(argc, argv, + GAME_ARGS[GAME_ARG_CREATE_DATA_ARCHIVES]) == true) { + haveSpecialOutputCommandLineOption = true; + } + + if (haveSpecialOutputCommandLineOption == false || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VERSION]) == true) { + printf("%s %s", extractFileFromDirectoryPath(argv[0]).c_str(), + getNetworkPlatformFreeVersionString().c_str()); + // printf("\nCompiled using: %s on: %s platform: %s endianness: + //%s",getCompilerNameString().c_str(),getCompileDateTime().c_str(),getPlatformNameString().c_str(),(::Shared::PlatformByteOrder::isBigEndian() + //== true ? "big" : "little")); + printf("\nCompiled using: %s platform: %s endianness: %s", + getCompilerNameString().c_str(), getPlatformNameString().c_str(), + (::Shared::PlatformByteOrder::isBigEndian() == true ? "big" + : "little")); + + // printf("\n\nData type sizes int8 = " MG_SIZE_T_SPECIFIER " int16 = + //" MG_SIZE_T_SPECIFIER " int32 = " MG_SIZE_T_SPECIFIER " int64 = " + // MG_SIZE_T_SPECIFIER + //"\n\n",sizeof(int8),sizeof(int16),sizeof(int32),sizeof(int64)); + // + // Config::getInstance().setBool("DebugNetworkPackets",true,true); + // NetworkMessageIntro data(424336, "mg_version_x","player_x", 3, + // nmgstOk,444444, 555555, "english"); unsigned char *buf = + // data.packMessage(); printf("\nSend packet size = + //%u\n%s\n",data.getPackedSize(),data.toString().c_str()); + // data.dump_packet("Send data", buf, data.getPackedSize()); + // //delete [] buf; + // + // NetworkMessageIntro data2; + // data2.unpackMessage(buf); + // printf("\nReceive packet size = + //%u\n%s\n",data2.getPackedSize(),data2.toString().c_str()); + // data2.dump_packet("nReceive data", buf, data2.getPackedSize()); + // delete [] buf; + + // SwitchSetupRequest data("factionname", 3,-1,2,"softcoder",10, + // 11,"eng"); + // + // unsigned char *buf = data.packMessage(); + // printf("\nSend packet size = %u\n%s\nTeam = %d faction [%s] + // currentFactionIndex = %d toFactionIndex = %d [%s] [%s] %d + //%d\n",data.getPackedSize(),buf,data.getToTeam(),data.getSelectedFactionName().c_str(),data.getCurrentFactionIndex(),data.getToFactionIndex(),data.getNetworkPlayerLanguage().c_str(),data.getNetworkPlayerName().c_str(),data.getNetworkPlayerStatus(),data.getSwitchFlags()); + // //delete [] buf; + // + // data.unpackMessage(buf); + // printf("\nGot packet size = %u\n%s\nTeam = %d faction [%s] + // currentFactionIndex = %d toFactionIndex = %d [%s] [%s] %d + //%d\n",data.getPackedSize(),buf,data.getToTeam(),data.getSelectedFactionName().c_str(),data.getCurrentFactionIndex(),data.getToFactionIndex(),data.getNetworkPlayerLanguage().c_str(),data.getNetworkPlayerName().c_str(),data.getNetworkPlayerStatus(),data.getSwitchFlags()); + // delete [] buf; + + // int8 a = 1; + // uint8 b = 2; + // int16 c = 3; + // uint16 d = 4; + // int32 e = 5; + // uint32 f = 6; + // + // printf("\nPack test #1: + //[%d][%u][%d][%u][%d][%u]\n,",a,b,c,d,e,f); + // + // unsigned char *buf = new unsigned char[100]; + // unsigned int packedsize = pack(buf, "cChHlL", + // a, + // b, + // c, + // d, + // e, + // f); + // + // printf("Pack test #2: [%u][%s]\n,",packedsize,buf); + // + // int8 a1 = 0; + // uint8 b1 = 0; + // int16 c1 = 0; + // uint16 d1 = 0; + // int32 e1 = 0; + // uint32 f1 = 0; + // + // unpack(buf, "cChHlL", + // &a1, + // &b1, + // &c1, + // &d1, + // &e1, + // &f1); + // + // printf("UnPack test #3: + //[%d][%u][%d][%u][%d][%u]\n,",a1,b1,c1,d1,e1,f1); + + if (SystemFlags::VERBOSE_MODE_ENABLED == true) { + int8 testVar = 111; + printf("\nEndian value = %d", testVar); + testVar = ::Shared::PlatformByteOrder::toCommonEndian(testVar); + printf("\nEndian to common value = %d", testVar); + testVar = ::Shared::PlatformByteOrder::fromCommonEndian(testVar); + printf("\nEndian from common value = %d", testVar); + + printf("\nint8 sizeof = " MG_SIZE_T_SPECIFIER "", sizeof(int8)); + printf("\nSwitchSetupRequest sizeof = " MG_SIZE_T_SPECIFIER "", + SwitchSetupRequest().getDataSize()); + } + + printf("\nGIT: [%s]", getGITRevisionString().c_str()); + +#ifdef USE_STREFLOP + +#if defined(STREFLOP_SSE) + const char *instruction_set = "[SSE]"; +#elif defined(STREFLOP_X87) + const char *instruction_set = "[X87]"; +#elif defined(STREFLOP_SOFT) + const char *instruction_set = "[S" + "OF" + "TF" + "LO" + "AT" + "]"; +#else + const char *instruction_set = "[none]"; +#endif + +#if defined(STREFLOP_NO_DENORMALS) + const char *denormals = "[no-denormals]"; +#else + const char *denormals = "[denormals]"; +#endif + + printf(" - using STREFLOP %s - %s\n", instruction_set, denormals); + +#else + printf("\n"); +#endif + } + + setGameVersion(glestVersionString); + setGameGITVersion(getRAWGITRevisionString()); + +#ifdef WIN32 + CheckPacketThrottling(); +#endif + + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_OPENGL_INFO]) == true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_SDL_INFO]) == true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LUA_INFO]) == true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_CURL_INFO]) == true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_XERCES_INFO]) == true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VERSION]) == true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_SHOW_INI_SETTINGS]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VALIDATE_TECHTREES]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VALIDATE_FACTIONS]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VALIDATE_SCENARIO]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VALIDATE_TILESET]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_TRANSLATE_TECHTREES]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_MAPS]) == true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_TECHTRESS]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_SCENARIOS]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_TILESETS]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_TUTORIALS]) == + true || + hasCommandArgument(argc, argv, + GAME_ARGS[GAME_ARG_CREATE_DATA_ARCHIVES]) == true) { + VideoPlayer::setDisabled(true); + } + + // throw megaglest_runtime_error("Test!"); - vector techPaths = config.getPathListForType(ptTechs); - for(int idx = 0; idx < (int)techPaths.size(); idx++) { - string &techPath = techPaths[idx]; - endPathWithSlash(techPath); + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_SDL_INFO]) == true) { + SDL_version ver; - for(int idx2 = 0; idx2 < (int)techTreeFiles.size(); idx2++) { - string &techName = techTreeFiles[idx2]; + // Prints the compile time version + SDL_VERSION(&ver); + print_SDL_version("SDL compile-time version", &ver); - if( filteredTechTreeList.empty() == true || - std::find(filteredTechTreeList.begin(),filteredTechTreeList.end(),techName) != filteredTechTreeList.end()) { + // Prints the run-time version + SDL_GetVersion(&ver); + print_SDL_version("SDL runtime version", &ver); + // const SDL_VideoInfo *vidInfo = SDL_GetVideoInfo(); + // printf("Video card Memory: %u\n",vidInfo->video_mem); + } - runTechValidationForPath(techPath, techName, filteredFactionList, - world, purgeUnusedFiles,purgeDuplicateFiles, - showDuplicateFiles,gitPurgeFiles,purgedMegaBytes); - } + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LUA_INFO]) == true) { + printf("LUA version: %s\n", LUA_RELEASE); + } + + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_CURL_INFO]) == true) { + curl_version_info_data *curlVersion = curl_version_info(CURLVERSION_NOW); + printf("CURL version: %s [%s] SSL enabled: %d\n", curlVersion->version, + (curlVersion->ssl_version != NULL ? curlVersion->ssl_version : ""), + ((curlVersion->features & CURL_VERSION_SSL) == CURL_VERSION_SSL + ? true + : false)); + if (curlVersion->protocols != NULL && curlVersion->protocols[0] != NULL) { + printf("protocols: "); + for (unsigned int i = 0; + curlVersion->protocols != NULL && curlVersion->protocols[i] != NULL; + ++i) { + printf("%s ", curlVersion->protocols[i]); + if (i > 0 && i % 10 == 0) { + printf("\n "); } + } + printf("\n"); } + } - printf("\n====== Finished Validation ======\n"); - } +#if defined(WANT_XERCES) -} + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_XERCES_INFO]) == true) { + printf("XERCES version: %s\n", XERCES_FULLVERSIONDOT); + } -void runTilesetValidationReport(int argc, char** argv) { - printf("====== Started Validation ======\n"); +#endif - Config &config = Config::getInstance(); + if ((hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VERSION]) == true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_SDL_INFO]) == true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LUA_INFO]) == true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_CURL_INFO]) == true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_XERCES_INFO]) == + true) && + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_OPENGL_INFO]) == + false && + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VALIDATE_TECHTREES]) == + false && + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VALIDATE_FACTIONS]) == + false && + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VALIDATE_SCENARIO]) == + false && + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VALIDATE_TILESET]) == + false && + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_TRANSLATE_TECHTREES]) == + false && + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_MAPS]) == false && + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_TECHTRESS]) == + false && + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_SCENARIOS]) == + false && + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_TILESETS]) == + false && + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_TUTORIALS]) == + false && + hasCommandArgument(argc, argv, + GAME_ARGS[GAME_ARG_CREATE_DATA_ARCHIVES]) == false) { + return 0; + } - // Did the user pass a specific tileset to validate? - if(hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_VALIDATE_TILESET]) + string("=")) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_VALIDATE_TILESET]) + string("="),&foundParamIndIndex); + if (hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_MOD])) == true) { - string filterList = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(filterList,paramPartTokens,"="); + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_MOD]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_MOD]), + &foundParamIndIndex); + } + string scenarioName = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(scenarioName, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string autoloadModName = paramPartTokens[1]; + if (Properties::applyTagsToValue(autoloadModName) == true) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Property key [%s] now has value [%s]\n", + Config::ACTIVE_MOD_PROPERTY_NAME, autoloadModName.c_str()); + } + + Config::setCustomRuntimeProperty(Config::ACTIVE_MOD_PROPERTY_NAME, + autoloadModName); + + printf("Setting mod active [%s]\n", autoloadModName.c_str()); + } else { + printf( + "\nInvalid mod pathname specified on commandline [%s] mod [%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + printParameterHelp(argv[0], foundInvalidArgs); + return 1; + } + } - if(paramPartTokens.size() >= 2) { - string validateTilesetName = paramPartTokens[1]; + SystemFlags::init(haveSpecialOutputCommandLineOption); + // SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled = + // true; SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled + // = true; + + MainWindow *mainWindow = NULL; + Program *program = NULL; + ExceptionHandler exceptionHandler; + exceptionHandler.install(getCrashDumpFileName()); + + int shutdownFadeSoundMilliseconds = 1000; + Chrono chronoshutdownFadeSound; + SimpleTaskThread *soundThreadManager = NULL; + + try { + // Setup paths to game items (like data, logs, ini etc) + int setupResult = setupGameItemPaths(argc, argv, NULL); + if (setupResult != 0) { + return setupResult; + } - printf("Filtering tileset: %s\n",validateTilesetName.c_str()); + // Attempt to read ini files + Config &config = Config::getInstance(); + setupGameItemPaths(argc, argv, &config); - bool purgeUnusedFiles = false; - if(paramPartTokens.size() >= 3) { - if(paramPartTokens[2] == "purgeunused") { - purgeUnusedFiles = true; - printf("*NOTE All unused tileset files will be deleted!\n"); - } - } + setupSteamSettings( + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_STEAM]), + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_STEAM_RESET_STATS]), + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_STEAM_DEBUG])); - { - printf("\n---------------- Loading tileset inside world ----------------\n"); - - World world; - double purgedMegaBytes=0; - bool showDuplicateFiles = true; - - bool tilesetFound = false; - - vector tilesetPaths = config.getPathListForType(ptTilesets); - for(int idx = 0; idx < (int)tilesetPaths.size(); idx++) { - string &tilesetPath = tilesetPaths[idx]; - endPathWithSlash(tilesetPath); - - vector tilesetList; - findDirs(tilesetPath, tilesetList, false, false); - for(int idx2 = 0; idx2 < (int)tilesetList.size(); idx2++) { - string &tilesetName = tilesetList[idx2]; - if(tilesetName == validateTilesetName) { - tilesetFound = true; - runTilesetValidationForPath(tilesetPath, tilesetName, - world, purgeUnusedFiles, showDuplicateFiles, - false, false, purgedMegaBytes); - } - } - } + if (config.getString("PlayerId", "") == "") { + char uuid_str[38]; + get_uuid_string(uuid_str, sizeof(uuid_str)); - if(tilesetFound == false) { - printf("*ERROR The specified tileset [%s] was NOT FOUND!\n",validateTilesetName.c_str()); - } - printf("\n====== Finished Validation ======\n"); - } - return; - } - else { - printf("\nInvalid missing tileset specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - return; - } + config.setString("PlayerId", uuid_str); + config.save(); } - else { - printf("\nInvalid missing tileset specified on commandline\n\n"); - return; - } -} - -void ShowINISettings(int argc, char **argv,Config &config,Config &configKeys) { - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_SHOW_INI_SETTINGS]) == true) { - vector filteredPropertyList; - if(hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_SHOW_INI_SETTINGS]) + string("=")) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_SHOW_INI_SETTINGS]) + string("="),&foundParamIndIndex); - string filterList = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(filterList,paramPartTokens,"="); - if(paramPartTokens.size() >= 2) { - string tokenList = paramPartTokens[1]; - Tokenize(tokenList,filteredPropertyList,","); - - if(filteredPropertyList.empty() == false) { - printf("Filtering properties and only looking for the following:\n"); - for(int idx = 0; idx < (int)filteredPropertyList.size(); ++idx) { - filteredPropertyList[idx] = trim(filteredPropertyList[idx]); - printf("%s\n",filteredPropertyList[idx].c_str()); - } - } - } - } - - printf("\nMain settings report\n"); - printf("====================\n"); - vector > mergedMainSettings = config.getMergedProperties(); - vector > mergedKeySettings = configKeys.getMergedProperties(); - - // Figure out the max # of tabs we need to format display nicely - int tabCount = 1; - for(int i = 0; i < (int)mergedMainSettings.size(); ++i) { - const pair &nameValue = mergedMainSettings[i]; - bool displayProperty = false; - if(filteredPropertyList.empty() == false) { - if(find(filteredPropertyList.begin(),filteredPropertyList.end(),nameValue.first) != filteredPropertyList.end()) { - displayProperty = true; - } - } - else { - displayProperty = true; - } + // printf("Players UUID: [%s]\n",config.getString("PlayerId","").c_str()); - if(displayProperty == true) { - int requredTabs = ((int)nameValue.first.length() / 8)+1; - if(nameValue.first.length() % 8) { - requredTabs++; - } - if(requredTabs > tabCount) { - tabCount = requredTabs; - } - } - } - for(int i = 0; i < (int)mergedKeySettings.size(); ++i) { - const pair &nameValue = mergedKeySettings[i]; + if (config.getBool("DisableLuaSandbox", "false") == true) { + LuaScript::setDisableSandbox(true); + } - bool displayProperty = false; - if(filteredPropertyList.empty() == false) { - if(find(filteredPropertyList.begin(),filteredPropertyList.end(),nameValue.first) != filteredPropertyList.end()) { - displayProperty = true; - } - } - else { - displayProperty = true; - } + if (hasCommandArgument(argc, argv, + GAME_ARGS[GAME_ARG_DEBUG_NETWORK_PACKETS]) == true) { + printf("*NOTE: debugging network packets.\n"); + config.setBool("DebugNetworkPackets", true, true); + } - if(displayProperty == true) { - int requredTabs = ((int)nameValue.first.length() / 8)+1; - if(nameValue.first.length() % 8) { - requredTabs++; - } - if(requredTabs > tabCount) { - tabCount = requredTabs; - } - } - } + if (hasCommandArgument(argc, argv, + GAME_ARGS[GAME_ARG_DEBUG_NETWORK_PACKET_SIZES]) == + true) { + printf("*NOTE: debugging network packet SIZES.\n"); + config.setBool("DebugNetworkPacketSizes", true, true); + } - // Output the properties - for(int i = 0; i < (int)mergedMainSettings.size(); ++i) { - const pair &nameValue = mergedMainSettings[i]; + if (hasCommandArgument(argc, argv, + GAME_ARGS[GAME_ARG_DEBUG_NETWORK_PACKET_STATS]) == + true) { + printf("*NOTE: debugging network packet STATISTICS.\n"); + config.setBool("DebugNetworkPacketStats", true, true); + } - bool displayProperty = false; - if(filteredPropertyList.empty() == false) { - if(find(filteredPropertyList.begin(),filteredPropertyList.end(),nameValue.first) != filteredPropertyList.end()) { - displayProperty = true; - } - } - else { - displayProperty = true; - } + if (hasCommandArgument(argc, argv, + GAME_ARGS[GAME_ARG_ENABLE_NEW_PROTOCOL]) == true) { + printf("*NOTE: enabling new network protocol.\n"); + NetworkMessage::useOldProtocol = false; + } - if(displayProperty == true) { - printf("Property Name [%s]",nameValue.first.c_str()); + Socket::setBroadCastPort(config.getInt( + "BroadcastPort", intToStr(Socket::getBroadCastPort()).c_str())); - int tabs = ((int)nameValue.first.length() / 8) + 1; - for(int j = 0; j < (tabCount - tabs); ++j) { - printf("\t"); - } + Socket::disableNagle = config.getBool("DisableNagle", "false"); + if (Socket::disableNagle) { + printf("*WARNING users wants to disable the socket nagle algorithm.\n"); + } + Socket::DEFAULT_SOCKET_SENDBUF_SIZE = + config.getInt("DefaultSocketSendBufferSize", + intToStr(Socket::DEFAULT_SOCKET_SENDBUF_SIZE).c_str()); + if (Socket::DEFAULT_SOCKET_SENDBUF_SIZE >= 0) { + printf("*WARNING users wants to set default socket send buffer size to: " + "%d\n", + Socket::DEFAULT_SOCKET_SENDBUF_SIZE); + } + Socket::DEFAULT_SOCKET_RECVBUF_SIZE = + config.getInt("DefaultSocketReceiveBufferSize", + intToStr(Socket::DEFAULT_SOCKET_RECVBUF_SIZE).c_str()); + if (Socket::DEFAULT_SOCKET_RECVBUF_SIZE >= 0) { + printf("*WARNING users wants to set default socket receive buffer size " + "to: %d\n", + Socket::DEFAULT_SOCKET_RECVBUF_SIZE); + } - string displayValue = nameValue.second; - if(nameValue.first == "TranslationGetURLPassword") { - displayValue = "*****"; - } + shutdownFadeSoundMilliseconds = + config.getInt("ShutdownFadeSoundMilliseconds", + intToStr(shutdownFadeSoundMilliseconds).c_str()); - printf("Value [%s]\n",displayValue.c_str()); - } - } + string userData = config.getString("UserData_Root", ""); + if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { + userData = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey); + } + if (userData != "") { + endPathWithSlash(userData); + } - printf("\n\nMain key binding settings report\n"); - printf("====================================\n"); + string data_path_check = + getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + string userDataPath_check = getGameCustomCoreDataPath(data_path_check, ""); + if (data_path_check == userDataPath_check) { + printf("****WARNING**** your game data path and user data path are the " + "same.\nThis will likely create problems: %s\n", + data_path_check.c_str()); + throw megaglest_runtime_error( + "Regular and User data paths cannot have the same value [" + + userDataPath_check + "]"); + } - for(int i = 0; i < (int)mergedKeySettings.size(); ++i) { - const pair &nameValue = mergedKeySettings[i]; + if (userData != "") { + if (isdir(userData.c_str()) == false) { + createDirectoryPaths(userData); + } + } + string crcCachePath = userData + "cache/"; + if (isdir(crcCachePath.c_str()) == false) { + createDirectoryPaths(crcCachePath); + } + setCRCCacheFilePath(crcCachePath); - bool displayProperty = false; - if(filteredPropertyList.empty() == false) { - if(find(filteredPropertyList.begin(),filteredPropertyList.end(),nameValue.first) != filteredPropertyList.end()) { - displayProperty = true; - } - } - else { - displayProperty = true; - } + string savedGamePath = userData + "saved/"; + if (isdir(savedGamePath.c_str()) == false) { + createDirectoryPaths(savedGamePath); + } - if(displayProperty == true) { - printf("Property Name [%s]",nameValue.first.c_str()); + string tempDataPath = userData + "temp/"; + tempDataLocation = tempDataPath; + if (isdir(tempDataPath.c_str()) == true) { + removeFolder(tempDataPath); + } + createDirectoryPaths(tempDataPath); + + string binaryNameOld = Properties::getApplicationPath() + + extractFileFromDirectoryPath( + PlatformExceptionHandler::application_binary) + + "__REMOVE"; + if (fileExists(binaryNameOld)) { + removeFile(binaryNameOld); + } - int tabs = ((int)nameValue.first.length() / 8) + 1; - for(int j = 0; j < (tabCount - tabs); ++j) { - printf("\t"); - } + string netInterfaces = config.getString("NetworkInterfaces", ""); + if (netInterfaces != "") { + // printf("Using network interfaces: %s\n",netInterfaces.c_str()); + std::vector intfList; + Tokenize(netInterfaces, intfList, ","); + Socket::setIntfTypes(intfList); + } - printf("Value [%s]\n",nameValue.second.c_str()); - } + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_USE_PORTS]) == true) { + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_USE_PORTS]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_USE_PORTS]), + &foundParamIndIndex); + } + string paramValue = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(paramValue, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string portsToUse = paramPartTokens[1]; + + vector paramPartPortsTokens; + Tokenize(portsToUse, paramPartPortsTokens, ","); + if (paramPartPortsTokens.size() >= 2 && + paramPartPortsTokens[1].length() > 0) { + int internalPort = strToInt(paramPartPortsTokens[0]); + int externalPort = strToInt(paramPartPortsTokens[1]); + + printf("Forcing internal port# %d, external port# %d\n", internalPort, + externalPort); + + config.setInt("PortServer", internalPort, true); + config.setInt("PortExternal", externalPort, true); + config.setInt("FTPServerPort", internalPort + 1, true); + + if (paramPartPortsTokens.size() >= 3 && + paramPartPortsTokens[2].length() > 0) { + int statusPort = strToInt(paramPartPortsTokens[2]); + + printf("Forcing status port# %d\n", statusPort); + + config.setInt("ServerAdminPort", statusPort, true); + } + } else { + printf("\nInvalid ports specified on commandline [%s] value [%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() + : NULL)); + return 1; } + } else { + printf( + "\nInvalid missing ports specified on commandline [%s] value " + "[%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + return 1; + } } -} -Steam & initSteamInstance() { - Steam *&steamInstance = CacheManager::getCachedItem< Steam *>(GameConstants::steamCacheInstanceKey); - if(steamInstance == NULL) { - steamInstance = new Steam(); - } - return *steamInstance; -} + if (hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_MASTERSERVER_STATUS])) == + true) { + Ip ip("localhost"); + int port = Config::getInstance().getInt( + "ServerAdminPort", intToStr(GameConstants::serverAdminPort).c_str()); + ClientSocket clientSocket; + clientSocket.setBlock(false); + clientSocket.connect(ip, port); + if (clientSocket.isConnected() == true) { + clientSocket.setBlock(true); + + char szBuf[8096] = ""; + clientSocket.receive(&szBuf[0], 8095, false); + std::cout << szBuf << std::endl; + } else { + std::cout + << "Could not connect (possibly no clients connected) to host: " + << ip.getString() << " port: " << port << std::endl; + } + + return 0; + } -void setupSteamSettings(bool steamEnabled, bool steamResetStats, bool debugEnabled) { - Config &config = Config::getInstance(); - config.setBool("SteamEnabled",steamEnabled,true); - if(steamEnabled) { - printf("*NOTE: Steam Integration Enabled.\n"); - - if(debugEnabled) { - printf("*NOTE: Steam Debugging Enabled.\n"); - } - Steam::setDebugEnabled(debugEnabled); - - Steam &steam = initSteamInstance(); - - // For Debugging purposes: - if(steamResetStats) { - printf("*WARNING: Steam Stats / Achievements are being RESET by request!\n"); - steam.resetStats(true); - } - - string steamPlayerName = steam.userName(); - string steamLang = steam.lang(); - printf("Steam Integration Enabled!\nSteam User Name is [%s] Language is [%s]\n", steamPlayerName.c_str(), steamLang.c_str()); - - bool needToSaveConfig=false; - string currentPLayerName = config.getString("NetPlayerName",""); - if( currentPLayerName == "newbie" || currentPLayerName == "" ) { - config.setString("NetPlayerName",steamPlayerName); - needToSaveConfig=true; - } - if( needToSaveConfig == true ) { - config.save(); - } - } -} + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_DISABLE_SOUND]) == + true || + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_MASTERSERVER_MODE])) == + true) { + config.setString("FactorySound", "None", true); + if (hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_MASTERSERVER_MODE])) == + true) { + // Logger::getInstance().setMasterserverMode(true); + // Model::setMasterserverMode(true); + // Shared::Sound::Sound::setMasterserverMode(true); + } + } -void CheckForDuplicateData() { - Config &config = Config::getInstance(); + if (hasCommandArgument(argc, argv, + GAME_ARGS[GAME_ARG_DISABLE_OPENGL_CAPS_CHECK]) == + true || + config.getBool("CheckGlCaps") == false) { + printf("**WARNING** disabling opengl capability checking...\n"); + config.setBool("CheckGlCaps", false, true); + } - string duplicateWarnings=""; + bool enableATIHacks = config.getBool("EnableATIHacks", "false"); + if (enableATIHacks == true) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("**WARNING** Enabling ATI video card hacks\n"); + TextureGl::setEnableATIHacks(enableATIHacks); + } - try { + Renderer::renderText3DEnabled = + config.getBool("Enable3DFontRendering", + intToStr(Renderer::renderText3DEnabled).c_str()); + + if (config.getBool("EnableLegacyFonts", "false") == true || + hasCommandArgument(argc, argv, + GAME_ARGS[GAME_ARG_ENABLE_LEGACYFONTS]) == true) { + ::Shared::Graphics::Font::forceLegacyFonts = true; + Renderer::renderText3DEnabled = false; + printf("**WARNING** Forcing Legacy Fonts Enabled\n"); + } else { + Renderer::renderText3DEnabled = + config.getBool("Enable3DFontRendering", + intToStr(Renderer::renderText3DEnabled).c_str()); + } + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_USE_RESOLUTION]) == + true) { + int foundParamIndIndex = -1; + hasCommandArgument( + argc, argv, string(GAME_ARGS[GAME_ARG_USE_RESOLUTION]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_USE_RESOLUTION]), + &foundParamIndIndex); + } + string paramValue = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(paramValue, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string settings = paramPartTokens[1]; + printf("Forcing resolution [%s]\n", settings.c_str()); + + paramPartTokens.clear(); + Tokenize(settings, paramPartTokens, "x"); + if (paramPartTokens.size() >= 2) { + int newScreenWidth = strToInt(paramPartTokens[0]); + config.setInt("ScreenWidth", newScreenWidth, true); + + int newScreenHeight = strToInt(paramPartTokens[1]); + config.setInt("ScreenHeight", newScreenHeight, true); + } else { + printf("\nInvalid missing resolution settings specified on " + "commandline [%s] value [%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() + : NULL)); + return 1; + } + } else { + printf( + "\nInvalid missing resolution setting specified on commandline " + "[%s] value [%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + return 1; + } + } - { + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_USE_COLORBITS]) == + true) { + int foundParamIndIndex = -1; + hasCommandArgument( + argc, argv, string(GAME_ARGS[GAME_ARG_USE_COLORBITS]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_USE_COLORBITS]), + &foundParamIndIndex); + } + string paramValue = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(paramValue, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string settings = paramPartTokens[1]; + printf("Forcing colorbits [%s]\n", settings.c_str()); + + int newColorBits = strToInt(settings); + config.setInt("ColorBits", newColorBits, true); + } else { + printf( + "\nInvalid missing colorbits settings specified on commandline " + "[%s] value [%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + return 1; + } + } - string scenarioDir = ""; - vector pathList = config.getPathListForType(ptMaps,scenarioDir); - vector invalidMapList; - vector maps = MapPreview::findAllValidMaps(pathList,scenarioDir,false,true,&invalidMapList); - std::sort(maps.begin(),maps.end()); - - if(maps.empty() == true) { - throw megaglest_runtime_error("No maps were found!",true); - } - else if(invalidMapList.empty() == false) { - string errorMsg = "Warning invalid maps were detected (will be ignored):\n"; - for(int i = 0; i < (int)invalidMapList.size(); ++i) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"map [%s]\n",invalidMapList[i].c_str()); - - errorMsg += szBuf; - } - duplicateWarnings += errorMsg; - } - - vector duplicateMapsToRename; - for(int i = 0; i < (int)maps.size(); ++i) { - string map1 = maps[i]; - for(int j = 0; j < (int)maps.size(); ++j) { - if(i != j) { - string map2 = maps[j]; - - if(map1 == map2) { - if(std::find(duplicateMapsToRename.begin(),duplicateMapsToRename.end(),map1) == duplicateMapsToRename.end()) { - duplicateMapsToRename.push_back(map1); - } - } - } - } - } - if(duplicateMapsToRename.empty() == false) { - string errorMsg = "Warning duplicate maps were detected and renamed:\n"; - for(int i = 0; i < (int)duplicateMapsToRename.size(); ++i) { - string currentPath = pathList[1]; - endPathWithSlash(currentPath); - - string oldFile = currentPath + duplicateMapsToRename[i]; - string newFile = currentPath + duplicateMapsToRename[i]; - string ext = extractExtension(newFile); - newFile = newFile.substr( 0, newFile.length()-ext.length()-1); - newFile = newFile + "_custom." + ext; - - char szBuf[8096]=""; - int result = rename(oldFile.c_str(),newFile.c_str()); - if(result != 0) { - char *errmsg = strerror(errno); - snprintf(szBuf,8096,"Error [%s]\nCould not rename [%s] to [%s]!",errmsg,oldFile.c_str(),newFile.c_str()); - throw megaglest_runtime_error(szBuf,true); - } - else { - snprintf(szBuf,8096,"map [%s] in [%s]\nwas renamed to [%s]",duplicateMapsToRename[i].c_str(),oldFile.c_str(),newFile.c_str()); - } - errorMsg += szBuf; - } - duplicateWarnings += errorMsg; - } + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_USE_DEPTHBITS]) == + true) { + int foundParamIndIndex = -1; + hasCommandArgument( + argc, argv, string(GAME_ARGS[GAME_ARG_USE_DEPTHBITS]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_USE_DEPTHBITS]), + &foundParamIndIndex); + } + string paramValue = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(paramValue, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string settings = paramPartTokens[1]; + printf("Forcing depthbits [%s]\n", settings.c_str()); + + int newDepthBits = strToInt(settings); + config.setInt("DepthBits", newDepthBits, true); + } else { + printf( + "\nInvalid missing depthbits setting specified on commandline [%s] " + "value [%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + return 1; + } } - { - //tilesets - std::vector tileSets; - vector tilesetPaths = config.getPathListForType(ptTilesets); - findDirs(tilesetPaths, tileSets, false, true); - - if (tileSets.empty()) { - throw megaglest_runtime_error("No tilesets were found!",true); - } - - vector duplicateTilesetsToRename; - for(int i = 0; i < (int)tileSets.size(); ++i) { - string tileSet1 = tileSets[i]; - for(int j = 0; j < (int)tileSets.size(); ++j) { - if(i != j) { - string tileSet2= tileSets[j]; - if(tileSet1 == tileSet2) { - if(std::find(duplicateTilesetsToRename.begin(),duplicateTilesetsToRename.end(),tileSet1) == duplicateTilesetsToRename.end()) { - duplicateTilesetsToRename.push_back(tileSet1); - } - } - } - } - } - if(duplicateTilesetsToRename.empty() == false) { - string errorMsg = "Warning duplicate tilesets were detected and renamed:\n"; - - for(int i = 0; i < (int)duplicateTilesetsToRename.size(); ++i) { - string currentPath = tilesetPaths[1]; - endPathWithSlash(currentPath); - - string oldFile = currentPath + duplicateTilesetsToRename[i]; - string newFile = currentPath + duplicateTilesetsToRename[i]; - newFile = newFile + "_custom"; - - char szBuf[8096]=""; - int result = rename(oldFile.c_str(),newFile.c_str()); - if(result != 0) { - char *errmsg = strerror(errno); - snprintf(szBuf,8096,"Error [%s]\nCould not rename [%s] to [%s]!",errmsg,oldFile.c_str(),newFile.c_str()); - throw megaglest_runtime_error(szBuf,true); - } - else { - snprintf(szBuf,8096,"tileset [%s] in [%s]\nwas renamed to [%s]",duplicateTilesetsToRename[i].c_str(),oldFile.c_str(),newFile.c_str()); - - string tilesetName = extractFileFromDirectoryPath(oldFile); - oldFile = newFile + "/" + tilesetName + ".xml"; - newFile = newFile + "/" + tilesetName + "_custom.xml"; - - result = rename(oldFile.c_str(),newFile.c_str()); - - if(result != 0) { - char *errmsg = strerror(errno); - snprintf(szBuf,8096,"Error [%s]\nCould not rename [%s] to [%s]!",errmsg,oldFile.c_str(),newFile.c_str()); - throw megaglest_runtime_error(szBuf,true); - } - - } - errorMsg += szBuf; - } - duplicateWarnings += errorMsg; - } + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_USE_FULLSCREEN]) == + true) { + int foundParamIndIndex = -1; + hasCommandArgument( + argc, argv, string(GAME_ARGS[GAME_ARG_USE_FULLSCREEN]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_USE_FULLSCREEN]), + &foundParamIndIndex); + } + string paramValue = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(paramValue, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string settings = paramPartTokens[1]; + printf("Forcing fullscreen [%s]\n", settings.c_str()); + + bool newFullScreenMode = strToBool(settings); + config.setBool("Windowed", !newFullScreenMode, true); + } else { + printf( + "\nInvalid missing fullscreen setting specified on commandline " + "[%s] value [%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + return 1; + } } - { - vector techPaths = config.getPathListForType(ptTechs); - vector techTrees; - findDirs(techPaths, techTrees, false, true); - if(techTrees.empty()) { - throw megaglest_runtime_error("No tech-trees were found (dup)!",true); - } - - vector duplicateTechtreesToRename; - for(int i = 0; i < (int)techTrees.size(); ++i) { - string techtree1 = techTrees[i]; - for(int j = 0; j < (int)techTrees.size(); ++j) { - if(i != j) { - string techtree2 = techTrees[j]; - if(techtree1 == techtree2) { - if(std::find(duplicateTechtreesToRename.begin(),duplicateTechtreesToRename.end(),techtree1) == duplicateTechtreesToRename.end()) { - duplicateTechtreesToRename.push_back(techtree1); - } - } - } - } - } - if(duplicateTechtreesToRename.empty() == false) { - string errorMsg = "Warning duplicate techtrees were detected and renamed:\n"; - - for(int i = 0; i < (int)duplicateTechtreesToRename.size(); ++i) { - string currentPath = techPaths[1]; - endPathWithSlash(currentPath); - - string oldFile = currentPath + duplicateTechtreesToRename[i]; - string newFile = currentPath + duplicateTechtreesToRename[i]; - newFile = newFile + "_custom"; - - char szBuf[8096]=""; - int result = rename(oldFile.c_str(),newFile.c_str()); - if(result != 0) { - char *errmsg = strerror(errno); - snprintf(szBuf,8096,"Error [%s]\nCould not rename [%s] to [%s]!",errmsg,oldFile.c_str(),newFile.c_str()); - throw megaglest_runtime_error(szBuf,true); - } - else { - snprintf(szBuf,8096,"techtree [%s] in [%s]\nwas renamed to [%s]",duplicateTechtreesToRename[i].c_str(),oldFile.c_str(),newFile.c_str()); - - string tilesetName = extractFileFromDirectoryPath(oldFile); - oldFile = newFile + "/" + tilesetName + ".xml"; - newFile = newFile + "/" + tilesetName + "_custom.xml"; - - int rename_result = rename(oldFile.c_str(),newFile.c_str()); - if(rename_result != 0) { - printf("Error renaming [%s] to [%s]\n",oldFile.c_str(),newFile.c_str()); - } - } - errorMsg += szBuf; - } - duplicateWarnings += errorMsg; - } - } - - } - catch(const megaglest_runtime_error &ex) { - if(mainProgram) { - mainProgram->getState()->setForceMouseRender(true); - } - ExceptionHandler::DisplayMessage(ex.what(), false); - } - - if(duplicateWarnings != "") { - if(mainProgram) { - mainProgram->getState()->setForceMouseRender(true); - } - ExceptionHandler::DisplayMessage(duplicateWarnings.c_str(), false); + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_SET_GAMMA]) == true) { + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_SET_GAMMA]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_SET_GAMMA]), + &foundParamIndIndex); + } + string paramValue = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(paramValue, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string settings = paramPartTokens[1]; + printf("Forcing gamma [%s]\n", settings.c_str()); + + float newGammaValue = strToFloat(settings); + config.setFloat("GammaValue", newGammaValue, true); + } else { + printf( + "\nInvalid missing gamma setting specified on commandline [%s] " + "value [%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + return 1; + } } -} -int handleCreateDataArchivesCommand(int argc, char** argv) { - int return_value = 1; - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_CREATE_DATA_ARCHIVES]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_CREATE_DATA_ARCHIVES]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_CREATE_DATA_ARCHIVES]),&foundParamIndIndex); - } - string paramValue = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(paramValue,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string compress_item = paramPartTokens[1]; - bool includeMainData = false; - if(paramPartTokens.size() >= 3 && paramPartTokens[2] == "include_main") { - includeMainData = true; - } - - Config &config = Config::getInstance(); - string fileArchiveExtension = config.getString("FileArchiveExtension",""); - string fileArchiveCompressCommand = config.getString("FileArchiveCompressCommand",""); - string fileArchiveCompressCommandParameters = config.getString("FileArchiveCompressCommandParameters",""); - int32 fileArchiveCompressCommandSuccessResult = config.getInt("FileArchiveCompressCommandSuccessResult","0"); - - string userData = config.getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - - int typesSelected = 0; - if(compress_item == "techtrees" || compress_item == "all") { - typesSelected++; - - vector pathList = config.getPathListForType(ptTechs,""); - vector results; - findDirs(pathList, results); - - printf("Techtrees found:\n===========================================\n"); - for(unsigned int i = 0; i < results.size(); ++i) { - string name = results[i]; - - for(unsigned int j = 0; j < pathList.size(); ++j) { - string techPath = pathList[j]; - if(techPath != "") { - endPathWithSlash(techPath); - } - - vector results2; - findDirs(techPath + name + "/factions", results2, false,true); - if(results2.empty() == false) { - string techtreePath = techPath + name; - if(includeMainData == false) { - if(techtreePath.find(userData) == techPath.npos) { - printf("Skipping techtree: [%s]\n",techtreePath.c_str()); - continue; - } - } - - string downloadArchive = techtreePath + fileArchiveExtension; - - if(fileExists(downloadArchive) == true) { - bool removed = removeFile(downloadArchive); - if(removed == false) { - printf("Error could not remove old file: [%s]\n",downloadArchive.c_str()); - } - } - string compressCmd = getFullFileArchiveCompressCommand( - fileArchiveCompressCommand, - fileArchiveCompressCommandParameters, - downloadArchive,techtreePath ); - - printf("Running compression command: %s\n",compressCmd.c_str()); - - if(executeShellCommand(compressCmd,fileArchiveCompressCommandSuccessResult) == false) { - printf("Error could not create new file: [%s]\n",downloadArchive.c_str()); - } - - if(fileExists(downloadArchive) == true) { - off_t fileSize = getFileSize(downloadArchive); - // convert to MB - double megaBytes = ((double)fileSize / 1048576.0); - printf("%s [download archive %.2fMB]\n",name.c_str(),megaBytes); - } - } - } - } - printf("===========================================\nTotal: " MG_SIZE_T_SPECIFIER "\n",results.size()); - } - if(compress_item == "tilesets" || compress_item == "all") { - typesSelected++; - - vector pathList = config.getPathListForType(ptTilesets,""); - vector results; - findDirs(pathList, results); - - printf("Tilesets found:\n===========================================\n"); - for(unsigned int i = 0; i < results.size(); ++i) { - string name = results[i]; - - for(unsigned int j = 0; j < pathList.size(); ++j) { - string tilesetPath = pathList[j]; - if(tilesetPath != "") { - endPathWithSlash(tilesetPath); - } - - if(fileExists(tilesetPath + name + "/" + name + ".xml") == true) { - string tilesetDataPath = tilesetPath + name; - if(includeMainData == false) { - if(tilesetPath.find(userData) == tilesetPath.npos) { - printf("Skipping tileset data: [%s]\n",tilesetDataPath.c_str()); - continue; - } - } - - string downloadArchive = tilesetDataPath + fileArchiveExtension; - - if(fileExists(downloadArchive) == true) { - bool removed = removeFile(downloadArchive); - if(removed == false) { - printf("Error could not remove old file: [%s]\n",downloadArchive.c_str()); - } - } - string compressCmd = getFullFileArchiveCompressCommand( - fileArchiveCompressCommand, - fileArchiveCompressCommandParameters, - downloadArchive,tilesetDataPath ); - - printf("Running compression command: %s\n",compressCmd.c_str()); - - if(executeShellCommand(compressCmd,fileArchiveCompressCommandSuccessResult) == false) { - printf("Error could not create new file: [%s]\n",downloadArchive.c_str()); - } - - if(fileExists(downloadArchive) == true) { - off_t fileSize = getFileSize(downloadArchive); - // convert to MB - double megaBytes = ((double)fileSize / 1048576.0); - printf("%s [download archive %.2fMB]\n",name.c_str(),megaBytes); - } - - break; - } - } - } - printf("===========================================\nTotal: " MG_SIZE_T_SPECIFIER "\n",results.size()); - - } - if(typesSelected == 0) { - printf("Compress item [%s] is not valid!\n",compress_item.c_str()); - return_value = 1; - } - else - return_value = 0; - } - else { - printf("\nInvalid missing map specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - - return_value = 1; - } - } - - return return_value; -} + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_DISABLE_VIDEOS]) == + true) { + VideoPlayer::setDisabled(true); + } else if (config.getBool("EnableVideos", "true") == false) { + VideoPlayer::setDisabled(true); + } -int handleShowCRCValuesCommand(int argc, char** argv) { - int return_value = 1; - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_SHOW_MAP_CRC]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_SHOW_MAP_CRC]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_SHOW_MAP_CRC]),&foundParamIndIndex); - } - string paramValue = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(paramValue,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string itemName = paramPartTokens[1]; - - string file = Config::getMapPath(itemName,"",false); - if(file != "") { - Checksum checksum; - checksum.addFile(file); - uint32 crcValue = checksum.getSum(); - - printf("CRC value for map [%s] file [%s] is [%u]\n",itemName.c_str(),file.c_str(),crcValue); - - return_value = 0; - } - else { - printf("Map [%s] was NOT FOUND\n",itemName.c_str()); - return_value = 1; - } - } - else { - printf("\nInvalid missing map specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - - return_value = 1; - } - } - - else if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_SHOW_TILESET_CRC]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_SHOW_TILESET_CRC]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_SHOW_TILESET_CRC]),&foundParamIndIndex); - } - string paramValue = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(paramValue,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string itemName = paramPartTokens[1]; - - Config &config = Config::getInstance(); - uint32 crcValue = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTilesets,""), string("/") + itemName + string("/*"), ".xml", NULL, true); - if(crcValue != 0) { - printf("CRC value for tileset [%s] is [%u]\n",itemName.c_str(),crcValue); - - return_value = 0; - } - else { - printf("Tileset [%s] was NOT FOUND\n",itemName.c_str()); - return_value = 1; - } - } - else { - printf("\nInvalid missing tileset specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - - return_value = 1; - } - } - - else if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_SHOW_TECHTREE_CRC]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_SHOW_TECHTREE_CRC]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_SHOW_TECHTREE_CRC]),&foundParamIndIndex); - } - string paramValue = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(paramValue,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string itemName = paramPartTokens[1]; - - Config &config = Config::getInstance(); - uint32 crcValue = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), "/" + itemName + "/*", ".xml", NULL, true); - if(crcValue != 0) { - printf("CRC value for techtree [%s] is [%u]\n",itemName.c_str(),crcValue); - - return_value = 0; - } - else { - printf("Techtree [%s] was NOT FOUND\n",itemName.c_str()); - - return_value = 1; - } - } - else { - printf("\nInvalid missing techtree specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - - return_value = 1; - } - } - - else if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_SHOW_SCENARIO_CRC]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_SHOW_SCENARIO_CRC]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_SHOW_SCENARIO_CRC]),&foundParamIndIndex); - } - string paramValue = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(paramValue,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string itemName = paramPartTokens[1]; - - Config &config = Config::getInstance(); - uint32 crcValue = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptScenarios,""), "/" + itemName + "/*", ".xml", NULL, true); - if(crcValue != 0) { - printf("CRC value for scenario [%s] is [%u]\n",itemName.c_str(),crcValue); - - return_value = 0; - } - else { - printf("Scenario [%s] was NOT FOUND\n",itemName.c_str()); - return_value = 1; - } - } - else { - printf("\nInvalid missing scenario specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - - return_value = 0; - } - } - - else if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_SHOW_PATH_CRC]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_SHOW_PATH_CRC]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_SHOW_PATH_CRC]),&foundParamIndIndex); - } - - string paramValue = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(paramValue,paramPartTokens,"="); - if(paramPartTokens.size() >= 3 && paramPartTokens[1].length() > 0) { - string itemName = paramPartTokens[1]; - string itemNameFilter = paramPartTokens[2]; - uint32 crcValue = getFolderTreeContentsCheckSumRecursively(itemName, itemNameFilter, NULL, true); - - printf("CRC value for path [%s] filter [%s] is [%u]\n",itemName.c_str(),itemNameFilter.c_str(),crcValue); - - return_value = 0; - } - else { - if(paramPartTokens.size() < 2) { - printf("\nInvalid missing path and filter specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - } - if(paramPartTokens.size() < 3) { - printf("\nInvalid missing filter specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 3 ? paramPartTokens[2].c_str() : NULL)); - } - - return_value = 1; - } - } - - return return_value; -} + // Set some statics based on ini entries + SystemFlags::ENABLE_THREADED_LOGGING = + config.getBool("ThreadedLogging", "true"); + FontGl::setDefault_fontType( + config.getString("DefaultFont", FontGl::getDefault_fontType().c_str())); + UPNP_Tools::isUPNP = !config.getBool("DisableUPNP", "false"); + Texture::useTextureCompression = + config.getBool("EnableTextureCompression", "false"); + + // 256 for English + // 30000 for Chinese + ::Shared::Graphics::Font::charCount = + config.getInt("FONT_CHARCOUNT", + intToStr(::Shared::Graphics::Font::charCount).c_str()); + ::Shared::Graphics::Font::fontTypeName = config.getString( + "FONT_TYPENAME", ::Shared::Graphics::Font::fontTypeName.c_str()); + ::Shared::Graphics::Font::fontIsMultibyte = config.getBool( + "FONT_MULTIBYTE", + intToStr(::Shared::Graphics::Font::fontIsMultibyte).c_str()); + ::Shared::Graphics::Font::fontIsRightToLeft = config.getBool( + "FONT_RIGHTTOLEFT", + intToStr(::Shared::Graphics::Font::fontIsRightToLeft).c_str()); + ::Shared::Graphics::Font::baseSize = config.getInt( + "FONT_BASE_SIZE", intToStr(::Shared::Graphics::Font::baseSize).c_str()); + ::Shared::Graphics::Font::scaleFontValue = config.getFloat( + "FONT_SCALE_SIZE", + floatToStr(::Shared::Graphics::Font::scaleFontValue).c_str()); + ::Shared::Graphics::Font::scaleFontValueCenterHFactor = config.getFloat( + "FONT_SCALE_CENTERH_FACTOR", + floatToStr(::Shared::Graphics::Font::scaleFontValueCenterHFactor) + .c_str()); + ::Shared::Graphics::Font::langHeightText = config.getString( + "FONT_HEIGHT_TEXT", ::Shared::Graphics::Font::langHeightText.c_str()); + ::Shared::Graphics::Font::fontSupportMixedRightToLeft = config.getBool( + "FONT_RIGHTTOLEFT_MIXED_SUPPORT", + intToStr(::Shared::Graphics::Font::fontSupportMixedRightToLeft) + .c_str()); + + // Example values: + // DEFAULT_CHARSET (English) = 1 + // GB2312_CHARSET (Chinese) = 134 + ::Shared::Platform::PlatformContextGl::charSet = config.getInt( + "FONT_CHARSET", + intToStr(::Shared::Platform::PlatformContextGl::charSet).c_str()); + if (config.getBool("No2DMouseRendering", "false") == false) { + showCursor(false); + // showWindowCursorState = false; + } + if (config.getInt("DEFAULT_HTTP_TIMEOUT", + intToStr(SystemFlags::DEFAULT_HTTP_TIMEOUT).c_str()) >= + 0) { + SystemFlags::DEFAULT_HTTP_TIMEOUT = + config.getInt("DEFAULT_HTTP_TIMEOUT", + intToStr(SystemFlags::DEFAULT_HTTP_TIMEOUT).c_str()); + } -int handleListDataCommand(int argc, char** argv) { - int return_value = 1; - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_MAPS]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_LIST_MAPS]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_LIST_MAPS]),&foundParamIndIndex); - } - - Config &config = Config::getInstance(); - vector pathList = config.getPathListForType(ptMaps,""); - vector maps = MapPreview::findAllValidMaps(pathList,"",false,true); - std::sort(maps.begin(),maps.end()); - - string paramValue = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(paramValue,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string itemNameFilter = paramPartTokens[1]; - printf("Using filter for maps list [%s]\n",itemNameFilter.c_str()); - - vector filteredMaps; - for(unsigned int i = 0; i < maps.size(); ++i) { - string mapName = maps[i]; - if(itemNameFilter.find("*") != itemNameFilter.npos) { - if(StartsWith(mapName, itemNameFilter.substr(0,itemNameFilter.find("*"))) == true) { - filteredMaps.push_back(mapName); - } - } - else if(mapName == itemNameFilter) { - filteredMaps.push_back(mapName); - } - } - maps = filteredMaps; - } - - printf("Maps found:\n===========================================\n"); - for(unsigned int i = 0; i < maps.size(); ++i) { - string mapName = maps[i]; - printf("%s\n",mapName.c_str()); - } - printf("===========================================\nTotal: " MG_SIZE_T_SPECIFIER "\n",maps.size()); - - return_value = 0; - } - - else if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_TECHTRESS]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_LIST_TECHTRESS]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_LIST_TECHTRESS]),&foundParamIndIndex); - } - - Config &config = Config::getInstance(); - vector pathList = config.getPathListForType(ptTechs,""); - vector results; - findDirs(pathList, results); - - bool showfactions=false; - string paramValue = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(paramValue,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string cmd = paramPartTokens[1]; - if(cmd == "showfactions") { - showfactions = true; - } - else { - throw megaglest_runtime_error("unknown command for techtreelist [" + cmd + "]"); - } - printf("Using special command for techtree list [%s]\n",cmd.c_str()); - } - - printf("Techtrees found:\n===========================================\n"); - for(unsigned int i = 0; i < results.size(); ++i) { - string name = results[i]; - - for(unsigned int j = 0; j < pathList.size(); ++j) { - string techPath = pathList[j]; - if(techPath != "") { - endPathWithSlash(techPath); - } - vector results2; - findDirs(techPath + name + "/factions", results2, false,true); - if(results2.empty() == false) { - string downloadArchive = techPath + name + ".7z"; - - if(fileExists(downloadArchive) == true) { - off_t fileSize = getFileSize(downloadArchive); - // convert to MB - double megaBytes = ((double)fileSize / 1048576.0); - printf("%s [download archive %.2fMB]\n",name.c_str(),megaBytes); - } - else { - printf("%s\n",name.c_str()); - } - - if(showfactions == true) { - printf("--> Factions:\n"); - for(unsigned int k = 0; k < results2.size(); ++k) { - string name2 = results2[k]; - printf("--> %s\n",name2.c_str()); - } - printf("--> Total Factions: " MG_SIZE_T_SPECIFIER "\n",results2.size()); - break; - } - } - } - } - printf("===========================================\nTotal Techtrees: " MG_SIZE_T_SPECIFIER "\n",results.size()); - - return_value = 0; - } - - else if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_SCENARIOS]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_LIST_SCENARIOS]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_LIST_SCENARIOS]),&foundParamIndIndex); - } - - Config &config = Config::getInstance(); - vector pathList = config.getPathListForType(ptScenarios,""); - vector results; - findDirs(pathList, results); - - string paramValue = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(paramValue,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string itemNameFilter = paramPartTokens[1]; - printf("Using filter for scenarios list [%s]\n",itemNameFilter.c_str()); - - vector filtered; - for(unsigned int i = 0; i < results.size(); ++i) { - string name = results[i]; - if(itemNameFilter.find("*") != itemNameFilter.npos) { - if(StartsWith(name, itemNameFilter.substr(0,itemNameFilter.find("*"))) == true) { - filtered.push_back(name); - } - } - else if(name == itemNameFilter) { - filtered.push_back(name); - } - } - results = filtered; - } - - printf("Scenarios found:\n===========================================\n"); - for(unsigned int i = 0; i < results.size(); ++i) { - string name = results[i]; - printf("%s\n",name.c_str()); - } - printf("===========================================\nTotal: " MG_SIZE_T_SPECIFIER "\n",results.size()); - - return_value = 0; - } - - else if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_TILESETS]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_LIST_TILESETS]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_LIST_TILESETS]),&foundParamIndIndex); - } - - Config &config = Config::getInstance(); - vector pathList = config.getPathListForType(ptTilesets,""); - vector results; - findDirs(pathList, results); - - string paramValue = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(paramValue,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string itemNameFilter = paramPartTokens[1]; - printf("Using filter for tilesets list [%s]\n",itemNameFilter.c_str()); - - vector filtered; - for(unsigned int i = 0; i < results.size(); ++i) { - string name = results[i]; - if(itemNameFilter.find("*") != itemNameFilter.npos) { - if(StartsWith(name, itemNameFilter.substr(0,itemNameFilter.find("*"))) == true) { - filtered.push_back(name); - } - } - else if(name == itemNameFilter) { - filtered.push_back(name); - } - } - results = filtered; - } - - printf("Tilesets found:\n===========================================\n"); - for(unsigned int i = 0; i < results.size(); ++i) { - string name = results[i]; - - for(unsigned int j = 0; j < pathList.size(); ++j) { - string tilesetPath = pathList[j]; - if(tilesetPath != "") { - endPathWithSlash(tilesetPath); - } - if(fileExists(tilesetPath + name + "/" + name + ".xml") == true) { - string downloadArchive = tilesetPath + name + ".7z"; - if(fileExists(downloadArchive) == true) { - off_t fileSize = getFileSize(downloadArchive); - // convert to MB - double megaBytes = ((double)fileSize / 1048576.0); - printf("%s [download archive %.2fMB]\n",name.c_str(),megaBytes); - } - else { - printf("%s\n",name.c_str()); - } - - break; - } - } - } - printf("===========================================\nTotal: " MG_SIZE_T_SPECIFIER "\n",results.size()); - - return_value = 0; - } - - else if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_TUTORIALS]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_LIST_TUTORIALS]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_LIST_TUTORIALS]),&foundParamIndIndex); - } - - Config &config = Config::getInstance(); - vector pathList = config.getPathListForType(ptTutorials,""); - vector results; - findDirs(pathList, results); - - string paramValue = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(paramValue,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string itemNameFilter = paramPartTokens[1]; - printf("Using filter for tutorials list [%s]\n",itemNameFilter.c_str()); - - vector filtered; - for(unsigned int i = 0; i < results.size(); ++i) { - string name = results[i]; - if(itemNameFilter.find("*") != itemNameFilter.npos) { - if(StartsWith(name, itemNameFilter.substr(0,itemNameFilter.find("*"))) == true) { - filtered.push_back(name); - } - } - else if(name == itemNameFilter) { - filtered.push_back(name); - } - } - results = filtered; - } - - printf("Tutorials found:\n===========================================\n"); - for(unsigned int i = 0; i < results.size(); ++i) { - string name = results[i]; - - for(unsigned int j = 0; j < pathList.size(); ++j) { - string tutorialsPath = pathList[j]; - if(tutorialsPath != "") { - endPathWithSlash(tutorialsPath); - } - if(fileExists(tutorialsPath + name + "/" + name + ".xml") == true) { - string downloadArchive = tutorialsPath + name + ".7z"; - if(fileExists(downloadArchive) == true) { - off_t fileSize = getFileSize(downloadArchive); - // convert to MB - double megaBytes = ((double)fileSize / 1048576.0); - printf("%s [download archive %.2fMB]\n",name.c_str(),megaBytes); - } - else { - printf("%s\n",name.c_str()); - } - - break; - } - } - } - printf("===========================================\nTotal: " MG_SIZE_T_SPECIFIER "\n",results.size()); - - return_value = 0; - } - - return return_value; -} + bool allowAltEnterFullscreenToggle = config.getBool( + "AllowAltEnterFullscreenToggle", + boolToStr( + ::Shared::Platform::Window::getAllowAltEnterFullscreenToggle()) + .c_str()); + ::Shared::Platform::Window::setAllowAltEnterFullscreenToggle( + allowAltEnterFullscreenToggle); -int glestMain(int argc, char** argv) { -#ifdef SL_LEAK_DUMP - //AllocInfo::set_application_binary(executable_path(argv[0],true)); - string &app = AllocInfo::get_application_binary(); - app = executable_path(argv[0],true); - //want_full_leak_stacktrace = true; - //want_full_leak_stacktrace_line_numbers = true; + if (config.getBool("noTeamColors", "false") == true) { + MeshCallbackTeamColor::noTeamColors = true; + } -#endif + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LUA_DEBUG]) == true) { + printf("Forcing LUA debugging enabled!\n"); + config.setBool("DebugLUA", true, true); + } - Thread::setMainThreadId(); -// printf("START ALLOC char 200\n"); - //char *ptr = new char[200]; -// printf("END ALLOC char 200\n"); -// return -1; - SystemFlags::VERBOSE_MODE_ENABLED = false; - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VERBOSE_MODE]) == true) { - SystemFlags::VERBOSE_MODE_ENABLED = true; - Thread::setEnableVerboseMode(true); - //LuaScript::setDebugModeEnabled(true); - } - // DEbug testing threads - //Thread::setEnableVerboseMode(true); - - PlatformExceptionHandler::application_binary= executable_path(argv[0],true); - mg_app_name = GameConstants::application_name; - mailStringSupport = mailString; - SystemFlags::ENABLE_THREADED_LOGGING = false; - disableBacktrace = false; - bool foundInvalidArgs = false; - preCacheThread=NULL; + // Setup debug logging etc + setupLogging(config, haveSpecialOutputCommandLineOption); + + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] Font::charCount = %d, Font::fontTypeName [%s] " + "Shared::Platform::PlatformContextGl::charSet = %d, " + "Font::fontIsMultibyte = %d, fontIsRightToLeft = %d\n", + __FILE__, __FUNCTION__, __LINE__, ::Shared::Graphics::Font::charCount, + ::Shared::Graphics::Font::fontTypeName.c_str(), + ::Shared::Platform::PlatformContextGl::charSet, + ::Shared::Graphics::Font::fontIsMultibyte, + ::Shared::Graphics::Font::fontIsRightToLeft); + + NetworkInterface::setDisplayMessageFunction( + ExceptionHandler::DisplayMessage); + MenuStateMasterserver::setDisplayMessageFunction( + ExceptionHandler::DisplayMessage); -#ifndef NO_APPIMAGE - Properties::setAppDirPath(); -#ifdef APPIMAGE_NODATA - Properties::setAppimageDirPath(); -#endif +#ifdef USE_STREFLOP + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "%s, STREFLOP enabled.\n", + getNetworkVersionString().c_str()); +#else + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "%s, STREFLOP NOT enabled.\n", + getNetworkVersionString().c_str()); #endif - Properties::setApplicationPath(executable_path(argv[0])); - Properties::setApplicationDataPath(executable_path(argv[0])); - Properties::setGameVersion(glestVersionString); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + SystemFlags::OutputDebug(SystemFlags::debugUnitCommands, "START\n"); + SystemFlags::OutputDebug(SystemFlags::debugPathFinder, "START\n"); + + // Setup hotkeys from key ini files + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys), + std::pair(Config::glestkeys_ini_filename, + Config::glestuserkeys_ini_filename), + std::pair(true, false), + config.getString("GlestKeysIniPath", "")); + + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_SHOW_INI_SETTINGS]) == + true) { + ShowINISettings(argc, argv, config, configKeys); + return 0; + } + + // Explicitly disable VBO's + if (config.getBool("DisableVBO", "false") == true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_DISABLE_VBO]) == + true) { + setVBOSupported(false); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("**INFO** Disabling VBOs\n"); + } - ServerSocket::setMaxPlayerCount(GameConstants::maxPlayers); + if (config.getBool("DisableVertexInterpolation", "false") || + hasCommandArgument(argc, argv, + GAME_ARGS[GAME_ARG_DISABLE_VERTEX_INTERPOLATION])) { + InterpolationData::setEnableInterpolation(false); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("**INFO** Disabling Interpolation\n"); + } - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_DISABLE_BACKTRACE]) == true) { - disableBacktrace = true; + if (config.getBool("EnableVSynch", "false") == true) { + ::Shared::Platform::Window::setTryVSynch(true); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("**ENABLED OPENGL VSYNCH**\n"); } - PlatformExceptionHandler::disableBacktrace= disableBacktrace; -#if defined(CUSTOM_DATA_INSTALL_PATH) - if(SystemFlags::VERBOSE_MODE_ENABLED) -#ifndef NO_APPIMAGE - printf("\n\nCUSTOM_DATA_INSTALL_PATH = [%s]\n\n",Properties::appendAppImagePath(formatPath(TOSTRING(CUSTOM_DATA_INSTALL_PATH))).c_str()); + // float pingTime = Socket::getAveragePingMS("soft-haus.com"); + // printf("Ping time = %f\n",pingTime); + + // Load the language strings + Lang &lang = Lang::getInstance(); + string language = config.getString("Lang"); + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_USE_LANGUAGE]) == + true) { + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_USE_LANGUAGE]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_USE_LANGUAGE]), + &foundParamIndIndex); + } + string paramValue = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(paramValue, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + language = paramPartTokens[1]; + printf("Forcing language [%s]\n", language.c_str()); + } else { + printf( + "\nInvalid missing language specified on commandline [%s] value " + "[%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + return 1; + } + } else { +#ifdef _WIN32 + int localeBufferSize = + GetLocaleInfo(LOCALE_SYSTEM_DEFAULT, LOCALE_SISO639LANGNAME, NULL, 0); + wchar_t *sysLocale = new wchar_t[localeBufferSize]; + GetLocaleInfo(LOCALE_SYSTEM_DEFAULT, LOCALE_SISO639LANGNAME, sysLocale, + localeBufferSize); + + // String langValue(sysLocale); + // const char *lang_locale = langValue.c_str(); + char langValue[1024] = ""; + wcstombs(langValue, sysLocale, 1023); + const char *lang_locale = &langValue[0]; + + delete[] sysLocale; #else - printf("\n\nCUSTOM_DATA_INSTALL_PATH = [%s]\n\n",formatPath(TOSTRING(CUSTOM_DATA_INSTALL_PATH)).c_str()); -#endif + const char *lang_locale = setlocale(LC_ALL, ""); #endif - const int knownArgCount = sizeof(GAME_ARGS) / sizeof(GAME_ARGS[0]); - for(int idx = 1; idx < argc; ++idx) { - if( hasCommandArgument(knownArgCount, (char **)&GAME_ARGS[0], argv[idx], NULL, 0, true) == false) { - foundInvalidArgs = true; - printf("\nInvalid argument: %s",argv[idx]); - } - } - - if( hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_HELP]) == true || - foundInvalidArgs == true) { - - printParameterHelp(argv[0],foundInvalidArgs); - return 2; - } - - if( hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_MASTERSERVER_MODE])) == true) { - //isMasterServerModeEnabled = true; - //Window::setMasterserverMode(isMasterServerModeEnabled); - GlobalStaticFlags::setIsNonGraphicalModeEnabled(true); - - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_MASTERSERVER_MODE]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_MASTERSERVER_MODE]),&foundParamIndIndex); - } - string paramValue = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(paramValue,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string headless_command_list = paramPartTokens[1]; - - vector paramHeadlessCommandList; - Tokenize(headless_command_list,paramHeadlessCommandList,","); - - for(unsigned int i = 0; i < paramHeadlessCommandList.size(); ++i) { - string headless_command = paramHeadlessCommandList[i]; - if(headless_command == "exit") { - printf("Forcing quit after game has completed [%s]\n",headless_command.c_str()); - Program::setWantShutdownApplicationAfterGame(true); - } - else if(headless_command == "vps") { - printf("Disabled reading from console [%s]\n",headless_command.c_str()); - disableheadless_console = true; - } - else if(headless_command == "lan") { - printf("Forcing local LAN mode [%s]\n",headless_command.c_str()); - GlobalStaticFlags::setFlag(gsft_lan_mode); - } - } - } - } - - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_SERVER_TITLE]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_SERVER_TITLE]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_SERVER_TITLE]),&foundParamIndIndex); - } - string paramValue = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(paramValue,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - Config &config = Config::getInstance(); - string serverTitle = paramPartTokens[1]; - printf("Forcing serverTitle[%s]\n",serverTitle.c_str()); - - config.setString("ServerTitle",serverTitle,true); - } - else { - printf("\nInvalid missing server title specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - - return 1; - } - } - - - -//#ifdef WIN32 - //SocketManager winSockManager; -//#endif - - bool haveSpecialOutputCommandLineOption = false; - - if( hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_OPENGL_INFO]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_SDL_INFO]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LUA_INFO]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_CURL_INFO]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_XERCES_INFO]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VERSION]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_SHOW_INI_SETTINGS]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VALIDATE_TECHTREES]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VALIDATE_FACTIONS]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VALIDATE_SCENARIO]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VALIDATE_TILESET]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_TRANSLATE_TECHTREES]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_MAPS]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_TECHTRESS]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_SCENARIOS]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_TILESETS]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_TUTORIALS]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_CREATE_DATA_ARCHIVES]) == true) { - haveSpecialOutputCommandLineOption = true; - } - - if( haveSpecialOutputCommandLineOption == false || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VERSION]) == true) { - printf("%s %s",extractFileFromDirectoryPath(argv[0]).c_str(),getNetworkPlatformFreeVersionString().c_str()); -// printf("\nCompiled using: %s on: %s platform: %s endianness: %s",getCompilerNameString().c_str(),getCompileDateTime().c_str(),getPlatformNameString().c_str(),(::Shared::PlatformByteOrder::isBigEndian() == true ? "big" : "little")); - printf("\nCompiled using: %s platform: %s endianness: %s",getCompilerNameString().c_str(),getPlatformNameString().c_str(),(::Shared::PlatformByteOrder::isBigEndian() == true ? "big" : "little")); - -// printf("\n\nData type sizes int8 = " MG_SIZE_T_SPECIFIER " int16 = " MG_SIZE_T_SPECIFIER " int32 = " MG_SIZE_T_SPECIFIER " int64 = " MG_SIZE_T_SPECIFIER "\n\n",sizeof(int8),sizeof(int16),sizeof(int32),sizeof(int64)); -// -// Config::getInstance().setBool("DebugNetworkPackets",true,true); -// NetworkMessageIntro data(424336, "mg_version_x","player_x", 3, nmgstOk,444444, 555555, "english"); -// unsigned char *buf = data.packMessage(); -// printf("\nSend packet size = %u\n%s\n",data.getPackedSize(),data.toString().c_str()); -// data.dump_packet("Send data", buf, data.getPackedSize()); -// //delete [] buf; -// -// NetworkMessageIntro data2; -// data2.unpackMessage(buf); -// printf("\nReceive packet size = %u\n%s\n",data2.getPackedSize(),data2.toString().c_str()); -// data2.dump_packet("nReceive data", buf, data2.getPackedSize()); -// delete [] buf; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Locale is: [%s]\n", lang_locale); -// SwitchSetupRequest data("factionname", 3,-1,2,"softcoder",10, 11,"eng"); -// -// unsigned char *buf = data.packMessage(); -// printf("\nSend packet size = %u\n%s\nTeam = %d faction [%s] currentFactionIndex = %d toFactionIndex = %d [%s] [%s] %d %d\n",data.getPackedSize(),buf,data.getToTeam(),data.getSelectedFactionName().c_str(),data.getCurrentFactionIndex(),data.getToFactionIndex(),data.getNetworkPlayerLanguage().c_str(),data.getNetworkPlayerName().c_str(),data.getNetworkPlayerStatus(),data.getSwitchFlags()); -// //delete [] buf; -// -// data.unpackMessage(buf); -// printf("\nGot packet size = %u\n%s\nTeam = %d faction [%s] currentFactionIndex = %d toFactionIndex = %d [%s] [%s] %d %d\n",data.getPackedSize(),buf,data.getToTeam(),data.getSelectedFactionName().c_str(),data.getCurrentFactionIndex(),data.getToFactionIndex(),data.getNetworkPlayerLanguage().c_str(),data.getNetworkPlayerName().c_str(),data.getNetworkPlayerStatus(),data.getSwitchFlags()); -// delete [] buf; - -// int8 a = 1; -// uint8 b = 2; -// int16 c = 3; -// uint16 d = 4; -// int32 e = 5; -// uint32 f = 6; -// -// printf("\nPack test #1: [%d][%u][%d][%u][%d][%u]\n,",a,b,c,d,e,f); -// -// unsigned char *buf = new unsigned char[100]; -// unsigned int packedsize = pack(buf, "cChHlL", -// a, -// b, -// c, -// d, -// e, -// f); -// -// printf("Pack test #2: [%u][%s]\n,",packedsize,buf); -// -// int8 a1 = 0; -// uint8 b1 = 0; -// int16 c1 = 0; -// uint16 d1 = 0; -// int32 e1 = 0; -// uint32 f1 = 0; -// -// unpack(buf, "cChHlL", -// &a1, -// &b1, -// &c1, -// &d1, -// &e1, -// &f1); -// -// printf("UnPack test #3: [%d][%u][%d][%u][%d][%u]\n,",a1,b1,c1,d1,e1,f1); + if (lang_locale != NULL && strlen(lang_locale) >= 2) { + if (config.getBool("AutoLocaleLanguageDetect", "true") == true) { + language = lang_locale; + language = language.substr(0, 2); + printf("Auto setting language [%s]\n", language.c_str()); - if(SystemFlags::VERBOSE_MODE_ENABLED == true) { - int8 testVar = 111; - printf("\nEndian value = %d",testVar); - testVar = ::Shared::PlatformByteOrder::toCommonEndian(testVar); - printf("\nEndian to common value = %d",testVar); - testVar = ::Shared::PlatformByteOrder::fromCommonEndian(testVar); - printf("\nEndian from common value = %d",testVar); + config.setString("AutoLocaleLanguageDetect", "false"); + config.save(); + } + } + } - printf("\nint8 sizeof = " MG_SIZE_T_SPECIFIER "",sizeof(int8)); - printf("\nSwitchSetupRequest sizeof = " MG_SIZE_T_SPECIFIER "",SwitchSetupRequest().getDataSize()); - } + if (hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_AUTO_TEST])) == + true || + Config::getInstance().getBool("AutoTest", "false") == true) { + printf("Running in auto test mode\n"); + } + if (hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_AUTO_TEST])) == + true) { + Config::getInstance().setBool("AutoTest", true, true); + + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_AUTO_TEST]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_AUTO_TEST]), + &foundParamIndIndex); + } + string paramValue = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(paramValue, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + vector paramPartTokens2; + Tokenize(paramPartTokens[1], paramPartTokens2, ","); + if (paramPartTokens2.empty() == false && + paramPartTokens2[0].length() > 0) { + string newMaxSeconds = paramPartTokens2[0]; + time_t newTimeMaxSeconds = strToInt(newMaxSeconds); + AutoTest::setMaxGameTime(newTimeMaxSeconds); + printf("Forcing maximum game time to [%ld] seconds (%.2f minutes)\n", + (long int)newTimeMaxSeconds, + ((double)newTimeMaxSeconds / 60.0)); + } + if (paramPartTokens2.size() >= 3 && paramPartTokens2[2].length() > 0) { + string autoTestCmd = paramPartTokens2[2]; + if (autoTestCmd == "exit") { + printf("Detected auto test command [%s], will exit after game.\n", + autoTestCmd.c_str()); + + AutoTest::setWantExitGameWhenDone(true); + } else { + printf("WARNING: Detected and UNKNOWN auto test command [%s].\n", + autoTestCmd.c_str()); + } + } - printf("\nGIT: [%s]",getGITRevisionString().c_str()); + if (paramPartTokens2.size() >= 2 && paramPartTokens2[1].length() > 0) { + string newGameSettingsFileToLoad = paramPartTokens2[1]; -#ifdef USE_STREFLOP + printf("About to auto test using game settings file [%s]\n", + newGameSettingsFileToLoad.c_str()); + AutoTest::setLoadGameSettingsFile(newGameSettingsFileToLoad); + } + } + } -#if defined(STREFLOP_SSE) - const char *instruction_set = "[SSE]"; -#elif defined(STREFLOP_X87) - const char *instruction_set = "[X87]"; -#elif defined(STREFLOP_SOFT) - const char *instruction_set = "[SOFTFLOAT]"; -#else - const char *instruction_set = "[none]"; -#endif + Renderer &renderer = Renderer::getInstance(); + lang.loadGameStrings(language, false, true); -#if defined(STREFLOP_NO_DENORMALS) - const char *denormals = "[no-denormals]"; -#else - const char *denormals = "[denormals]"; -#endif + if (lang.hasString("FONT_HEIGHT_TEXT")) { + ::Shared::Graphics::Font::langHeightText = config.getString( + "FONT_HEIGHT_TEXT", ::Shared::Graphics::Font::langHeightText.c_str()); + } + + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_FONT_BASESIZE]) == + true) { + int foundParamIndIndex = -1; + hasCommandArgument( + argc, argv, string(GAME_ARGS[GAME_ARG_FONT_BASESIZE]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_FONT_BASESIZE]), + &foundParamIndIndex); + } + string paramValue = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(paramValue, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string newfontBaseSize = paramPartTokens[1]; + printf("Forcing font base size[%s]\n", newfontBaseSize.c_str()); + + ::Shared::Graphics::Font::baseSize = strToInt(newfontBaseSize); + } else { + printf( + "\nInvalid missing font base size specified on commandline [%s] " + "value [%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + + return 1; + } + } - printf(" - using STREFLOP %s - %s\n",instruction_set,denormals); + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] Font::charCount = %d, Font::fontTypeName [%s] " + "Shared::Platform::PlatformContextGl::charSet = %d, " + "Font::fontIsMultibyte = %d, Font::fontIsRightToLeft = %d\n", + __FILE__, __FUNCTION__, __LINE__, ::Shared::Graphics::Font::charCount, + ::Shared::Graphics::Font::fontTypeName.c_str(), + ::Shared::Platform::PlatformContextGl::charSet, + ::Shared::Graphics::Font::fontIsMultibyte, + ::Shared::Graphics::Font::fontIsRightToLeft); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Using Font::charCount = %d, Font::fontTypeName [%s] " + "Shared::Platform::PlatformContextGl::charSet = %d, " + "Font::fontIsMultibyte = %d, Font::fontIsRightToLeft = %d\n", + ::Shared::Graphics::Font::charCount, + ::Shared::Graphics::Font::fontTypeName.c_str(), + ::Shared::Platform::PlatformContextGl::charSet, + ::Shared::Graphics::Font::fontIsMultibyte, + ::Shared::Graphics::Font::fontIsRightToLeft); + + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_USE_FONT]) == true) { + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_USE_FONT]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_USE_FONT]), + &foundParamIndIndex); + } + string paramValue = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(paramValue, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string newfont = paramPartTokens[1]; + + Properties::applyTagsToValue(newfont); + printf("Forcing font [%s]\n", newfont.c_str()); +#if defined(WIN32) + string newEnvValue = "MEGAGLEST_FONT=" + newfont; + _putenv(newEnvValue.c_str()); #else - printf("\n"); + setenv("MEGAGLEST_FONT", newfont.c_str(), 1); #endif - } - - setGameVersion(glestVersionString); - setGameGITVersion(getRAWGITRevisionString()); + } else { + printf( + "\nInvalid missing font specified on commandline [%s] value " + "[%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + return 1; + } + } -#ifdef WIN32 - CheckPacketThrottling(); -#endif + if (hasCommandArgument(argc, argv, + GAME_ARGS[GAME_ARG_CREATE_DATA_ARCHIVES]) == true) { + return handleCreateDataArchivesCommand(argc, argv); + } - if( hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_OPENGL_INFO]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_SDL_INFO]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LUA_INFO]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_CURL_INFO]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_XERCES_INFO]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VERSION]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_SHOW_INI_SETTINGS]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VALIDATE_TECHTREES]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VALIDATE_FACTIONS]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VALIDATE_SCENARIO]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VALIDATE_TILESET]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_TRANSLATE_TECHTREES]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_MAPS]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_TECHTRESS]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_SCENARIOS]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_TILESETS]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_TUTORIALS]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_CREATE_DATA_ARCHIVES]) == true) { - VideoPlayer::setDisabled(true); - } - - //throw megaglest_runtime_error("Test!"); - - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_SDL_INFO]) == true) { - SDL_version ver; - - // Prints the compile time version - SDL_VERSION(&ver); - print_SDL_version("SDL compile-time version", &ver); - - // Prints the run-time version - SDL_GetVersion(&ver); - print_SDL_version("SDL runtime version", &ver); - //const SDL_VideoInfo *vidInfo = SDL_GetVideoInfo(); - //printf("Video card Memory: %u\n",vidInfo->video_mem); - } - - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LUA_INFO]) == true) { - printf("LUA version: %s\n", LUA_RELEASE); - } - - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_CURL_INFO]) == true) { - curl_version_info_data *curlVersion= curl_version_info(CURLVERSION_NOW); - printf("CURL version: %s [%s] SSL enabled: %d\n", curlVersion->version,(curlVersion->ssl_version != NULL ? curlVersion->ssl_version : ""),((curlVersion->features & CURL_VERSION_SSL) == CURL_VERSION_SSL ? true : false)); - if(curlVersion->protocols != NULL && curlVersion->protocols[0] != NULL) { - printf("protocols: "); - for(unsigned int i = 0; curlVersion->protocols != NULL && curlVersion->protocols[i] != NULL; ++i) { - printf("%s ", curlVersion->protocols[i]); - if(i > 0 && i % 10 == 0) { - printf("\n "); - } - } - printf("\n"); - } - } + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_SHOW_MAP_CRC]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_SHOW_TILESET_CRC]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_SHOW_TECHTREE_CRC]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_SHOW_SCENARIO_CRC]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_SHOW_PATH_CRC]) == + true) { + return handleShowCRCValuesCommand(argc, argv); + } -#if defined(WANT_XERCES) + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_MAPS]) == true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_TECHTRESS]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_SCENARIOS]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_TILESETS]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_LIST_TUTORIALS]) == + true) { + return handleListDataCommand(argc, argv); + } - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_XERCES_INFO]) == true) { - printf("XERCES version: %s\n", XERCES_FULLVERSIONDOT); - } + program = new Program(); + mainProgram = program; + renderer.setProgram(program); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPathFinder) + .enabled == true) { + renderer.setAllowRenderUnitTitles( + SystemFlags::getSystemSettingType(SystemFlags::debugPathFinder) + .enabled); + SystemFlags::OutputDebug( + SystemFlags::debugPathFinder, + "In [%s::%s Line: %d] renderer.setAllowRenderUnitTitles = %d\n", + __FILE__, __FUNCTION__, __LINE__, + SystemFlags::getSystemSettingType(SystemFlags::debugPathFinder) + .enabled); + } + renderer.setAllowRenderUnitTitles(true); -#endif + string screenShotsPath = userData + GameConstants::folder_path_screenshots; + if (isdir(screenShotsPath.c_str()) == false) { + createDirectoryPaths(screenShotsPath); + } - if( (hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VERSION]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_SDL_INFO]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LUA_INFO]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_CURL_INFO]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_XERCES_INFO]) == true) && - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_OPENGL_INFO]) == false && - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VALIDATE_TECHTREES]) == false && - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VALIDATE_FACTIONS]) == false && - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VALIDATE_SCENARIO]) == false && - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VALIDATE_TILESET]) == false && - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_TRANSLATE_TECHTREES]) == false && - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_MAPS]) == false && - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_TECHTRESS]) == false && - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_SCENARIOS]) == false && - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_TILESETS]) == false && - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_TUTORIALS]) == false && - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_CREATE_DATA_ARCHIVES]) == false) { - return 0; - } - - if(hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_MOD])) == true) { - - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_MOD]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_MOD]),&foundParamIndIndex); - } - string scenarioName = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(scenarioName,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string autoloadModName = paramPartTokens[1]; - if(Properties::applyTagsToValue(autoloadModName) == true) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Property key [%s] now has value [%s]\n",Config::ACTIVE_MOD_PROPERTY_NAME,autoloadModName.c_str()); - } - - Config::setCustomRuntimeProperty(Config::ACTIVE_MOD_PROPERTY_NAME,autoloadModName); - - printf("Setting mod active [%s]\n",autoloadModName.c_str()); - } - else { - printf("\nInvalid mod pathname specified on commandline [%s] mod [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - printParameterHelp(argv[0],foundInvalidArgs); - return 1; - } - } - - SystemFlags::init(haveSpecialOutputCommandLineOption); - //SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled = true; - //SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled = true; - - MainWindow *mainWindow= NULL; - Program *program= NULL; - ExceptionHandler exceptionHandler; - exceptionHandler.install( getCrashDumpFileName() ); - - int shutdownFadeSoundMilliseconds = 1000; - Chrono chronoshutdownFadeSound; - SimpleTaskThread *soundThreadManager = NULL; - - try { - // Setup paths to game items (like data, logs, ini etc) - int setupResult = setupGameItemPaths(argc, argv, NULL); - if(setupResult != 0) { - return setupResult; + // Cache Player textures - START + string data_path = + getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + std::map &crcPlayerTextureCache = + CacheManager::getCachedItem>( + GameConstants::playerTextureCacheLookupKey); + for (int index = 0; index < GameConstants::maxPlayers; ++index) { + string playerTexture = getGameCustomCoreDataPath( + data_path, + "data/core/faction_textures/faction" + intToStr(index) + ".tga"); + if (fileExists(playerTexture) == true) { + Texture2D *texture = Renderer::getInstance().newTexture2D(rsGlobal); + if (texture) { + texture->load(playerTexture); } - - // Attempt to read ini files - Config &config = Config::getInstance(); - setupGameItemPaths(argc, argv, &config); - - setupSteamSettings(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_STEAM]), - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_STEAM_RESET_STATS]), - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_STEAM_DEBUG])); - - if(config.getString("PlayerId","") == "") { - char uuid_str[38]; - get_uuid_string(uuid_str,sizeof(uuid_str)); - - config.setString("PlayerId",uuid_str); - config.save(); - } - - //printf("Players UUID: [%s]\n",config.getString("PlayerId","").c_str()); - - if(config.getBool("DisableLuaSandbox","false") == true) { - LuaScript::setDisableSandbox(true); - } - - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_DEBUG_NETWORK_PACKETS]) == true) { - printf("*NOTE: debugging network packets.\n"); - config.setBool("DebugNetworkPackets",true,true); - } - - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_DEBUG_NETWORK_PACKET_SIZES]) == true) { - printf("*NOTE: debugging network packet SIZES.\n"); - config.setBool("DebugNetworkPacketSizes",true,true); - } - - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_DEBUG_NETWORK_PACKET_STATS]) == true) { - printf("*NOTE: debugging network packet STATISTICS.\n"); - config.setBool("DebugNetworkPacketStats",true,true); - } - - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_ENABLE_NEW_PROTOCOL]) == true) { - printf("*NOTE: enabling new network protocol.\n"); - NetworkMessage::useOldProtocol = false; - } - - Socket::setBroadCastPort(config.getInt("BroadcastPort",intToStr(Socket::getBroadCastPort()).c_str())); - - Socket::disableNagle = config.getBool("DisableNagle","false"); - if(Socket::disableNagle) { - printf("*WARNING users wants to disable the socket nagle algorithm.\n"); - } - Socket::DEFAULT_SOCKET_SENDBUF_SIZE = config.getInt("DefaultSocketSendBufferSize",intToStr(Socket::DEFAULT_SOCKET_SENDBUF_SIZE).c_str()); - if(Socket::DEFAULT_SOCKET_SENDBUF_SIZE >= 0) { - printf("*WARNING users wants to set default socket send buffer size to: %d\n",Socket::DEFAULT_SOCKET_SENDBUF_SIZE); - } - Socket::DEFAULT_SOCKET_RECVBUF_SIZE = config.getInt("DefaultSocketReceiveBufferSize",intToStr(Socket::DEFAULT_SOCKET_RECVBUF_SIZE).c_str()); - if(Socket::DEFAULT_SOCKET_RECVBUF_SIZE >= 0) { - printf("*WARNING users wants to set default socket receive buffer size to: %d\n",Socket::DEFAULT_SOCKET_RECVBUF_SIZE); - } - - shutdownFadeSoundMilliseconds = config.getInt("ShutdownFadeSoundMilliseconds",intToStr(shutdownFadeSoundMilliseconds).c_str()); - - string userData = config.getString("UserData_Root",""); - if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - userData = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey); - } - if(userData != "") { - endPathWithSlash(userData); + crcPlayerTextureCache[index] = texture; + } else { + crcPlayerTextureCache[index] = NULL; + } + } + // Cache Player textures - END + + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + mainWindow = new MainWindow(program); + + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + GameSettings startupGameSettings; + + // parse command line + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_SERVER]) == true) { + program->initServer(mainWindow, false, true); + gameInitialized = true; + } else if (hasCommandArgument( + argc, argv, string(GAME_ARGS[GAME_ARG_MASTERSERVER_MODE])) == + true) { + program->initServer(mainWindow, false, true, true); + gameInitialized = true; + } else if (hasCommandArgument( + argc, argv, + string(GAME_ARGS[GAME_ARG_AUTOSTART_LASTGAME])) == true) { + program->initServer(mainWindow, true, false); + gameInitialized = true; + } else if (hasCommandArgument( + argc, argv, + string(GAME_ARGS[GAME_ARG_AUTOSTART_LAST_SAVED_GAME])) == + true) { + string fileName = ""; + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_AUTOSTART_LAST_SAVED_GAME]) + + string("="), + &foundParamIndIndex); + if (foundParamIndIndex >= 0) { + string loadfileName = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(loadfileName, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + fileName = paramPartTokens[1]; + + if (fileExists(fileName) == false) { + // Save the file now + string saveGameFile = "saved/" + fileName; + if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != + "") { + saveGameFile = getGameReadWritePath( + GameConstants::path_logs_CacheLookupKey) + + saveGameFile; + } else { + saveGameFile = userData + saveGameFile; + } + if (fileExists(saveGameFile) == true) { + fileName = saveGameFile; + } + } + + if (fileExists(fileName) == false) { + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "File specified for loading a saved game cannot be found: [%s]", + fileName.c_str()); + printf("\n\n=======================================================" + "===============================\n%s\n======================" + "===========================================================" + "=====\n\n\n", + szBuf); + + throw megaglest_runtime_error(szBuf); + } } - - string data_path_check = getGameReadWritePath(GameConstants::path_data_CacheLookupKey); - string userDataPath_check = getGameCustomCoreDataPath(data_path_check, ""); - if(data_path_check == userDataPath_check) { - printf("****WARNING**** your game data path and user data path are the same.\nThis will likely create problems: %s\n",data_path_check.c_str()); - throw megaglest_runtime_error("Regular and User data paths cannot have the same value [" + userDataPath_check + "]"); + } + program->initSavedGame(mainWindow, false, fileName); + gameInitialized = true; + } else if (hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_PREVIEW_MAP])) == + true) { + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_PREVIEW_MAP]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_PREVIEW_MAP]), + &foundParamIndIndex); + } + string mapName = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(mapName, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + vector paramPartTokens2; + string tileset = "forest"; + Tokenize(paramPartTokens[1], paramPartTokens2, ","); + if (paramPartTokens2.size() >= 2 && paramPartTokens2[1].length() > 0) { + tileset = paramPartTokens2[1]; } - - if(userData != "") { - if(isdir(userData.c_str()) == false) { - createDirectoryPaths(userData); - } - } - string crcCachePath = userData + "cache/"; - if(isdir(crcCachePath.c_str()) == false) { - createDirectoryPaths(crcCachePath); + string autoloadMapName = paramPartTokens2[0]; + + GameSettings *gameSettings = &startupGameSettings; + gameSettings->setMap(autoloadMapName); + gameSettings->setTileset(tileset); + gameSettings->setTech("megapack"); + gameSettings->setDefaultUnits(false); + gameSettings->setDefaultResources(false); + gameSettings->setDefaultVictoryConditions(true); + gameSettings->setFogOfWar(false); + gameSettings->setAllowObservers(true); + gameSettings->setPathFinderType(pfBasic); + + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + ControlType ct = ctClosed; + + gameSettings->setNetworkPlayerStatuses(i, npst_None); + gameSettings->setFactionControl(i, ct); + gameSettings->setStartLocationIndex(i, i); + gameSettings->setResourceMultiplierIndex(i, 10); + gameSettings->setNetworkPlayerName( + i, GameConstants::NETWORK_SLOT_CLOSED_SLOTNAME); } - setCRCCacheFilePath(crcCachePath); - string savedGamePath = userData + "saved/"; - if(isdir(savedGamePath.c_str()) == false) { - createDirectoryPaths(savedGamePath); + ControlType ct = ctHuman; + + gameSettings->setNetworkPlayerStatuses(0, npst_None); + gameSettings->setFactionControl(0, ct); + gameSettings->setFactionTypeName( + 0, formatString(GameConstants::OBSERVER_SLOTNAME)); + gameSettings->setTeam(0, GameConstants::maxPlayers + fpt_Observer - 1); + gameSettings->setStartLocationIndex(0, 0); + gameSettings->setNetworkPlayerName(0, GameConstants::OBSERVER_SLOTNAME); + + gameSettings->setFactionCount(1); + + Config &config = Config::getInstance(); + gameSettings->setEnableServerControlledAI( + config.getBool("ServerControlledAI", "true")); + gameSettings->setNetworkFramePeriod( + config.getInt("NetworkSendFrameCount", "20")); + + program->initServer(mainWindow, gameSettings); + gameInitialized = true; + } else { + printf( + "\nInvalid map name specified on commandline [%s] map [%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + printParameterHelp(argv[0], foundInvalidArgs); + delete mainWindow; + mainWindow = NULL; + return 1; + } + } + + else if (hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_CONNECT])) == true) { + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_CONNECT]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_CONNECT]), + &foundParamIndIndex); + } + string serverToConnectTo = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(serverToConnectTo, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string autoConnectServer = paramPartTokens[1]; + + int port = config.getInt("PortServer", + intToStr(GameConstants::serverPort).c_str()); + vector paramPartTokens2; + Tokenize(autoConnectServer, paramPartTokens2, ":"); + autoConnectServer = paramPartTokens2[0]; + if (paramPartTokens2.size() >= 2 && paramPartTokens2[1].length() > 0) { + port = strToInt(paramPartTokens2[1]); } - string tempDataPath = userData + "temp/"; - tempDataLocation = tempDataPath; - if(isdir(tempDataPath.c_str()) == true) { - removeFolder(tempDataPath); + printf("Connecting to host [%s] using port: %d\n", + autoConnectServer.c_str(), port); + if (autoConnectServer == "auto-connect") { + program->initClientAutoFindHost(mainWindow); + } else { + program->initClient(mainWindow, autoConnectServer, port); } - createDirectoryPaths(tempDataPath); + gameInitialized = true; + } else { + + printf( + "\nInvalid host specified on commandline [%s] host [%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + printParameterHelp(argv[0], foundInvalidArgs); + delete mainWindow; + mainWindow = NULL; + return 1; + } + } - string binaryNameOld = Properties::getApplicationPath() + extractFileFromDirectoryPath(PlatformExceptionHandler::application_binary) + "__REMOVE"; - if(fileExists(binaryNameOld)) { - removeFile(binaryNameOld); + else if (hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_CLIENT])) == true) { + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_CLIENT]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_CLIENT]), + &foundParamIndIndex); + } + string serverToConnectTo = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(serverToConnectTo, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string autoConnectServer = paramPartTokens[1]; + + if (autoConnectServer == "auto-connect") { + program->initClientAutoFindHost(mainWindow); + } else { + program->initClient(mainWindow, autoConnectServer); } + gameInitialized = true; + } else { + + printf( + "\nInvalid host specified on commandline [%s] host [%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + printParameterHelp(argv[0], foundInvalidArgs); + delete mainWindow; + mainWindow = NULL; + return 1; + } + } else if (hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_LOADSCENARIO])) == + true) { + + int foundParamIndIndex = -1; + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_LOADSCENARIO]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, string(GAME_ARGS[GAME_ARG_LOADSCENARIO]), + &foundParamIndIndex); + } + string scenarioName = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(scenarioName, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string autoloadScenarioName = paramPartTokens[1]; + + program->initScenario(mainWindow, autoloadScenarioName); + gameInitialized = true; + } else { + printf( + "\nInvalid scenario name specified on commandline [%s] scenario " + "[%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + printParameterHelp(argv[0], foundInvalidArgs); + delete mainWindow; + mainWindow = NULL; + return 1; + } + } else { + program->initNormal(mainWindow); + } + + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d] OpenGL Info:\n%s\n", + __FILE__, __FUNCTION__, __LINE__, renderer.getGlInfo().c_str()); + + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_OPENGL_INFO]) == + true) { + printf("%s", renderer.getGlInfo().c_str()); + printf("%s", renderer.getGlMoreInfo().c_str()); + + delete mainWindow; + mainWindow = NULL; + return 0; + } - string netInterfaces = config.getString("NetworkInterfaces",""); - if(netInterfaces != "") { - //printf("Using network interfaces: %s\n",netInterfaces.c_str()); - std::vector intfList; - Tokenize(netInterfaces,intfList,","); - Socket::setIntfTypes(intfList); + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_CONVERT_MODELS]) == + true) { + int foundParamIndIndex = -1; + hasCommandArgument( + argc, argv, string(GAME_ARGS[GAME_ARG_CONVERT_MODELS]) + string("="), + &foundParamIndIndex); + if (foundParamIndIndex < 0) { + hasCommandArgument(argc, argv, + string(GAME_ARGS[GAME_ARG_CONVERT_MODELS]), + &foundParamIndIndex); + } + string paramValue = argv[foundParamIndIndex]; + vector paramPartTokens; + Tokenize(paramValue, paramPartTokens, "="); + if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { + string modelFile = paramPartTokens[1]; + printf("About to convert model(s) [%s]\n", modelFile.c_str()); + + string textureFormat = ""; + if (paramPartTokens.size() >= 3 && paramPartTokens[1].length() > 0) { + textureFormat = paramPartTokens[2]; + printf("About to convert using texture format [%s]\n", + textureFormat.c_str()); } - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_USE_PORTS]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_USE_PORTS]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_USE_PORTS]),&foundParamIndIndex); - } - string paramValue = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(paramValue,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string portsToUse = paramPartTokens[1]; - - vector paramPartPortsTokens; - Tokenize(portsToUse,paramPartPortsTokens,","); - if(paramPartPortsTokens.size() >= 2 && paramPartPortsTokens[1].length() > 0) { - int internalPort = strToInt(paramPartPortsTokens[0]); - int externalPort = strToInt(paramPartPortsTokens[1]); - - printf("Forcing internal port# %d, external port# %d\n",internalPort,externalPort); - - config.setInt("PortServer",internalPort,true); - config.setInt("PortExternal",externalPort,true); - config.setInt("FTPServerPort",internalPort+1,true); - - if(paramPartPortsTokens.size() >= 3 && paramPartPortsTokens[2].length() > 0) { - int statusPort = strToInt(paramPartPortsTokens[2]); - - printf("Forcing status port# %d\n",statusPort); - - config.setInt("ServerAdminPort",statusPort,true); - } - } - else { - printf("\nInvalid ports specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - return 1; - } - } - else { - printf("\nInvalid missing ports specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - return 1; - } - } - - if(hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_MASTERSERVER_STATUS])) == true) { - Ip ip("localhost"); - int port = Config::getInstance().getInt("ServerAdminPort", intToStr(GameConstants::serverAdminPort).c_str()); - ClientSocket clientSocket; - clientSocket.setBlock(false); - clientSocket.connect(ip, port); - if(clientSocket.isConnected() == true) { - clientSocket.setBlock(true); - - char szBuf[8096]=""; - clientSocket.receive(&szBuf[0],8095,false); - std::cout << szBuf << std::endl; - } - else { - std::cout << "Could not connect (possibly no clients connected) to host: " << ip.getString() << " port: " << port << std::endl; - } - - return 0; + bool keepsmallest = false; + if (paramPartTokens.size() >= 4 && paramPartTokens[1].length() > 0) { + keepsmallest = (paramPartTokens[3] == "keepsmallest"); + printf("About to convert using keepsmallest = %d\n", keepsmallest); } - if( hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_DISABLE_SOUND]) == true || - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_MASTERSERVER_MODE])) == true) { - config.setString("FactorySound","None",true); - if(hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_MASTERSERVER_MODE])) == true) { - //Logger::getInstance().setMasterserverMode(true); - //Model::setMasterserverMode(true); - //Shared::Sound::Sound::setMasterserverMode(true); - } - } - - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_DISABLE_OPENGL_CAPS_CHECK]) == true || - config.getBool("CheckGlCaps") == false) { - printf("**WARNING** disabling opengl capability checking...\n"); - config.setBool("CheckGlCaps",false,true); - } - - bool enableATIHacks = config.getBool("EnableATIHacks","false"); - if(enableATIHacks == true) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("**WARNING** Enabling ATI video card hacks\n"); - TextureGl::setEnableATIHacks(enableATIHacks); - } - - Renderer::renderText3DEnabled = config.getBool("Enable3DFontRendering",intToStr(Renderer::renderText3DEnabled).c_str()); - - if(config.getBool("EnableLegacyFonts","false") == true || hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_ENABLE_LEGACYFONTS]) == true) { - ::Shared::Graphics::Font::forceLegacyFonts = true; - Renderer::renderText3DEnabled = false; - printf("**WARNING** Forcing Legacy Fonts Enabled\n"); + showCursor(true); + + const Metrics &metrics = Metrics::getInstance(); + renderer.clearBuffers(); + renderer.clearZBuffer(); + renderer.reset2d(); + + if (CoreData::getInstance().getMenuFontBig3D() != NULL) { + renderer.renderText3D("Please wait, converting models...", + CoreData::getInstance().getMenuFontBig3D(), + Vec3f(1.f, 1.f, 0.f), + (metrics.getScreenW() / 2) - 400, + (metrics.getScreenH() / 2), true); + } else { + renderer.renderText("Please wait, converting models...", + CoreData::getInstance().getMenuFontBig(), + Vec3f(1.f, 1.f, 0.f), + (metrics.getScreenW() / 2) - 400, + (metrics.getScreenH() / 2), true); } - else { - Renderer::renderText3DEnabled = config.getBool("Enable3DFontRendering",intToStr(Renderer::renderText3DEnabled).c_str()); + renderer.swapBuffers(); + + std::vector models; + if (isdir(modelFile.c_str()) == true) { + models = getFolderTreeContentsListRecursively(modelFile, ".g3d"); + } else { + models.push_back(modelFile); } - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_USE_RESOLUTION]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_USE_RESOLUTION]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_USE_RESOLUTION]),&foundParamIndIndex); - } - string paramValue = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(paramValue,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string settings = paramPartTokens[1]; - printf("Forcing resolution [%s]\n",settings.c_str()); - - paramPartTokens.clear(); - Tokenize(settings,paramPartTokens,"x"); - if(paramPartTokens.size() >= 2) { - int newScreenWidth = strToInt(paramPartTokens[0]); - config.setInt("ScreenWidth",newScreenWidth,true); - - int newScreenHeight = strToInt(paramPartTokens[1]); - config.setInt("ScreenHeight",newScreenHeight,true); - } - else { - printf("\nInvalid missing resolution settings specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - return 1; - } - } - else { - printf("\nInvalid missing resolution setting specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - return 1; - } + sleep(0); + ::Shared::Platform::Window::handleEvent(); + SDL_PumpEvents(); + + int result = 0; + char szTextBuf[8096] = ""; + for (unsigned int i = 0; i < models.size(); ++i) { + string &file = models[i]; + + renderer.clearBuffers(); + renderer.clearZBuffer(); + renderer.reset2d(); + snprintf(szTextBuf, 8096, + "Please wait, converting models [%u of " MG_SIZE_T_SPECIFIER + "] ...", + i, models.size()); + + if (CoreData::getInstance().getMenuFontBig3D() != NULL) { + renderer.renderText3D( + szTextBuf, CoreData::getInstance().getMenuFontBig3D(), + Vec3f(1.f, 1.f, 0.f), (metrics.getScreenW() / 2) - 400, + (metrics.getScreenH() / 2), true); + } else { + renderer.renderText( + szTextBuf, CoreData::getInstance().getMenuFontBig(), + Vec3f(1.f, 1.f, 0.f), (metrics.getScreenW() / 2) - 400, + (metrics.getScreenH() / 2), true); + } + renderer.swapBuffers(); + + sleep(0); + ::Shared::Platform::Window::handleEvent(); + SDL_PumpEvents(); + + try { + printf("About to load model [%s] [%u of " MG_SIZE_T_SPECIFIER "]\n", + file.c_str(), i, models.size()); + Model *model = renderer.newModel(rsGlobal, file); + printf("About to save converted model [%s]\n", file.c_str()); + model->save(file, textureFormat, keepsmallest); + Renderer::getInstance().endModel(rsGlobal, model); + } catch (const exception &ex) { + result = 1; + printf("ERROR loading model [%s] message [%s]\n", file.c_str(), + ex.what()); + } } - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_USE_COLORBITS]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_USE_COLORBITS]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_USE_COLORBITS]),&foundParamIndIndex); - } - string paramValue = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(paramValue,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string settings = paramPartTokens[1]; - printf("Forcing colorbits [%s]\n",settings.c_str()); - - int newColorBits = strToInt(settings); - config.setInt("ColorBits",newColorBits,true); - } - else { - printf("\nInvalid missing colorbits settings specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - return 1; - } - } - - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_USE_DEPTHBITS]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_USE_DEPTHBITS]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_USE_DEPTHBITS]),&foundParamIndIndex); - } - string paramValue = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(paramValue,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string settings = paramPartTokens[1]; - printf("Forcing depthbits [%s]\n",settings.c_str()); - - int newDepthBits = strToInt(settings); - config.setInt("DepthBits",newDepthBits,true); - } - else { - printf("\nInvalid missing depthbits setting specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - return 1; - } - } - - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_USE_FULLSCREEN]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_USE_FULLSCREEN]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_USE_FULLSCREEN]),&foundParamIndIndex); - } - string paramValue = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(paramValue,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string settings = paramPartTokens[1]; - printf("Forcing fullscreen [%s]\n",settings.c_str()); - - bool newFullScreenMode = strToBool(settings); - config.setBool("Windowed",!newFullScreenMode,true); - } - else { - printf("\nInvalid missing fullscreen setting specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - return 1; - } - } - - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_SET_GAMMA]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_SET_GAMMA]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_SET_GAMMA]),&foundParamIndIndex); - } - string paramValue = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(paramValue,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string settings = paramPartTokens[1]; - printf("Forcing gamma [%s]\n",settings.c_str()); - - float newGammaValue = strToFloat(settings); - config.setFloat("GammaValue",newGammaValue,true); - } - else { - printf("\nInvalid missing gamma setting specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - return 1; - } - } - - - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_DISABLE_VIDEOS]) == true) { - VideoPlayer::setDisabled(true); - } - else if(config.getBool("EnableVideos","true") == false) { - VideoPlayer::setDisabled(true); - } - - // Set some statics based on ini entries - SystemFlags::ENABLE_THREADED_LOGGING = config.getBool("ThreadedLogging","true"); - FontGl::setDefault_fontType(config.getString("DefaultFont",FontGl::getDefault_fontType().c_str())); - UPNP_Tools::isUPNP = !config.getBool("DisableUPNP","false"); - Texture::useTextureCompression = config.getBool("EnableTextureCompression","false"); - - // 256 for English - // 30000 for Chinese - ::Shared::Graphics::Font::charCount = config.getInt("FONT_CHARCOUNT",intToStr(::Shared::Graphics::Font::charCount).c_str()); - ::Shared::Graphics::Font::fontTypeName = config.getString("FONT_TYPENAME",::Shared::Graphics::Font::fontTypeName.c_str()); - ::Shared::Graphics::Font::fontIsMultibyte = config.getBool("FONT_MULTIBYTE",intToStr(::Shared::Graphics::Font::fontIsMultibyte).c_str()); - ::Shared::Graphics::Font::fontIsRightToLeft = config.getBool("FONT_RIGHTTOLEFT",intToStr(::Shared::Graphics::Font::fontIsRightToLeft).c_str()); - ::Shared::Graphics::Font::baseSize = config.getInt("FONT_BASE_SIZE",intToStr(::Shared::Graphics::Font::baseSize).c_str()); - ::Shared::Graphics::Font::scaleFontValue = config.getFloat("FONT_SCALE_SIZE",floatToStr(::Shared::Graphics::Font::scaleFontValue).c_str()); - ::Shared::Graphics::Font::scaleFontValueCenterHFactor = config.getFloat("FONT_SCALE_CENTERH_FACTOR",floatToStr(::Shared::Graphics::Font::scaleFontValueCenterHFactor).c_str()); - ::Shared::Graphics::Font::langHeightText = config.getString("FONT_HEIGHT_TEXT",::Shared::Graphics::Font::langHeightText.c_str()); - ::Shared::Graphics::Font::fontSupportMixedRightToLeft = config.getBool("FONT_RIGHTTOLEFT_MIXED_SUPPORT",intToStr(::Shared::Graphics::Font::fontSupportMixedRightToLeft).c_str()); - - // Example values: - // DEFAULT_CHARSET (English) = 1 - // GB2312_CHARSET (Chinese) = 134 - ::Shared::Platform::PlatformContextGl::charSet = config.getInt("FONT_CHARSET",intToStr(::Shared::Platform::PlatformContextGl::charSet).c_str()); - if(config.getBool("No2DMouseRendering","false") == false) { - showCursor(false); - //showWindowCursorState = false; - } - if(config.getInt("DEFAULT_HTTP_TIMEOUT",intToStr(SystemFlags::DEFAULT_HTTP_TIMEOUT).c_str()) >= 0) { - SystemFlags::DEFAULT_HTTP_TIMEOUT = config.getInt("DEFAULT_HTTP_TIMEOUT",intToStr(SystemFlags::DEFAULT_HTTP_TIMEOUT).c_str()); - } - - bool allowAltEnterFullscreenToggle = config.getBool("AllowAltEnterFullscreenToggle",boolToStr(::Shared::Platform::Window::getAllowAltEnterFullscreenToggle()).c_str()); - ::Shared::Platform::Window::setAllowAltEnterFullscreenToggle(allowAltEnterFullscreenToggle); - - if(config.getBool("noTeamColors","false") == true) { - MeshCallbackTeamColor::noTeamColors = true; - } - - - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LUA_DEBUG]) == true) { - printf("Forcing LUA debugging enabled!\n"); - config.setBool("DebugLUA",true, true); - } - - // Setup debug logging etc - setupLogging(config, haveSpecialOutputCommandLineOption); - - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] Font::charCount = %d, Font::fontTypeName [%s] Shared::Platform::PlatformContextGl::charSet = %d, Font::fontIsMultibyte = %d, fontIsRightToLeft = %d\n",__FILE__,__FUNCTION__,__LINE__,::Shared::Graphics::Font::charCount,::Shared::Graphics::Font::fontTypeName.c_str(),::Shared::Platform::PlatformContextGl::charSet,::Shared::Graphics::Font::fontIsMultibyte, ::Shared::Graphics::Font::fontIsRightToLeft); - - NetworkInterface::setDisplayMessageFunction(ExceptionHandler::DisplayMessage); - MenuStateMasterserver::setDisplayMessageFunction(ExceptionHandler::DisplayMessage); + delete mainWindow; + mainWindow = NULL; + return result; + } else { + printf( + "\nInvalid model specified on commandline [%s] texture [%s]\n\n", + argv[foundParamIndIndex], + (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); + printParameterHelp(argv[0], foundInvalidArgs); + delete mainWindow; + mainWindow = NULL; + return 1; + } + } -#ifdef USE_STREFLOP - SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s, STREFLOP enabled.\n",getNetworkVersionString().c_str()); -#else - SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s, STREFLOP NOT enabled.\n",getNetworkVersionString().c_str()); -#endif + if (hasCommandArgument(argc, argv, + GAME_ARGS[GAME_ARG_VALIDATE_TECHTREES]) == true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VALIDATE_FACTIONS]) == + true || + hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VALIDATE_SCENARIO]) == + true) { + runTechValidationReport(argc, argv); + + delete mainWindow; + mainWindow = NULL; + return 0; + } + + if (hasCommandArgument(argc, argv, + GAME_ARGS[GAME_ARG_TRANSLATE_TECHTREES]) == true) { + runTechTranslationExtraction(argc, argv); + delete mainWindow; + mainWindow = NULL; + return 0; + } - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - SystemFlags::OutputDebug(SystemFlags::debugUnitCommands,"START\n"); - SystemFlags::OutputDebug(SystemFlags::debugPathFinder,"START\n"); + if (hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_VALIDATE_TILESET]) == + true) { + runTilesetValidationReport(argc, argv); - // Setup hotkeys from key ini files - Config &configKeys = Config::getInstance( - std::pair(cfgMainKeys,cfgUserKeys), - std::pair(Config::glestkeys_ini_filename,Config::glestuserkeys_ini_filename), - std::pair(true,false),config.getString("GlestKeysIniPath","")); + delete mainWindow; + mainWindow = NULL; + return 0; + } - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + gameInitialized = true; - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_SHOW_INI_SETTINGS]) == true) { - ShowINISettings(argc,argv,config,configKeys); - return 0; - } + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); - // Explicitly disable VBO's - if(config.getBool("DisableVBO","false") == true || hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_DISABLE_VBO]) == true) { - setVBOSupported(false); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("**INFO** Disabling VBOs\n"); - } - - if(config.getBool("DisableVertexInterpolation","false") || hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_DISABLE_VERTEX_INTERPOLATION])) { - InterpolationData::setEnableInterpolation(false); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("**INFO** Disabling Interpolation\n"); - } + CheckForDuplicateData(); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); - if(config.getBool("EnableVSynch","false") == true) { - ::Shared::Platform::Window::setTryVSynch(true); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("**ENABLED OPENGL VSYNCH**\n"); - } + // throw "BLAH!"; - //float pingTime = Socket::getAveragePingMS("soft-haus.com"); - //printf("Ping time = %f\n",pingTime); - - // Load the language strings - Lang &lang= Lang::getInstance(); - string language = config.getString("Lang"); - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_USE_LANGUAGE]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_USE_LANGUAGE]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_USE_LANGUAGE]),&foundParamIndIndex); - } - string paramValue = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(paramValue,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - language = paramPartTokens[1]; - printf("Forcing language [%s]\n",language.c_str()); - } - else { - printf("\nInvalid missing language specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - return 1; - } - } - else { -#ifdef _WIN32 - int localeBufferSize = GetLocaleInfo(LOCALE_SYSTEM_DEFAULT, LOCALE_SISO639LANGNAME, NULL, 0); - wchar_t *sysLocale = new wchar_t[localeBufferSize]; - GetLocaleInfo(LOCALE_SYSTEM_DEFAULT, LOCALE_SISO639LANGNAME, sysLocale,localeBufferSize); + // START Test out SIGSEGV error handling + // int *foo = (int*)-1; // make a bad pointer + // printf("%d\n", *foo); // causes segfault + // END - //String langValue(sysLocale); - //const char *lang_locale = langValue.c_str(); - char langValue[1024]=""; - wcstombs(langValue,sysLocale, 1023); - const char *lang_locale = &langValue[0]; + bool startCRCPrecacheThread = config.getBool("PreCacheCRCThread", "true"); + // printf("### In [%s::%s Line: %d] precache thread enabled = %d + // SystemFlags::VERBOSE_MODE_ENABLED = + // %d\n",__FILE__,__FUNCTION__,__LINE__,startCRCPrecacheThread,SystemFlags::VERBOSE_MODE_ENABLED); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] precache thread enabled = %d\n", __FILE__, + __FUNCTION__, __LINE__, startCRCPrecacheThread); + if (startCRCPrecacheThread == true && + GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + static string mutexOwnerId = + string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + + intToStr(__LINE__); + vector techDataPaths = config.getPathListForType(ptTechs); + + FileCRCPreCacheThread::setPreCacheThreadCacheLookupKey( + GameConstants::preCacheThreadCacheLookupKey); + FileCRCPreCacheThread *&preCacheCRCThreadPtr = + CacheManager::getCachedItem( + GameConstants::preCacheThreadCacheLookupKey); + if (preCacheCRCThreadPtr == NULL) { + preCacheCRCThreadPtr = new FileCRCPreCacheThread(); + } + preCacheThread = preCacheCRCThreadPtr; + preCacheThread->setUniqueID(mutexOwnerId); + preCacheThread->setTechDataPaths(techDataPaths); + // preCacheThread->setFileCRCPreCacheThreadCallbackInterface(&preCacheThreadGame); + preCacheThread->start(); + } - delete [] sysLocale; -#else - const char *lang_locale = setlocale(LC_ALL,""); -#endif + auto_ptr lngCacheGen; + auto_ptr languageCacheGen; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Locale is: [%s]\n", lang_locale); - - if(lang_locale != NULL && strlen(lang_locale) >= 2) { - if(config.getBool("AutoLocaleLanguageDetect","true") == true) { - language = lang_locale; - language = language.substr(0,2); - printf("Auto setting language [%s]\n",language.c_str()); - - config.setString("AutoLocaleLanguageDetect","false"); - config.save(); - } - } - } - - if(hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_AUTO_TEST])) == true || - Config::getInstance().getBool("AutoTest","false") == true) { - printf("Running in auto test mode\n"); - } - if(hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_AUTO_TEST])) == true) { - Config::getInstance().setBool("AutoTest",true,true); - - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_AUTO_TEST]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_AUTO_TEST]),&foundParamIndIndex); - } - string paramValue = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(paramValue,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - vector paramPartTokens2; - Tokenize(paramPartTokens[1],paramPartTokens2,","); - if(paramPartTokens2.empty() == false && paramPartTokens2[0].length() > 0) { - string newMaxSeconds = paramPartTokens2[0]; - time_t newTimeMaxSeconds = strToInt(newMaxSeconds); - AutoTest::setMaxGameTime(newTimeMaxSeconds); - printf("Forcing maximum game time to [%ld] seconds (%.2f minutes)\n",(long int)newTimeMaxSeconds,((double)newTimeMaxSeconds / 60.0)); - } - if(paramPartTokens2.size() >= 3 && paramPartTokens2[2].length() > 0) { - string autoTestCmd = paramPartTokens2[2]; - if(autoTestCmd == "exit") { - printf("Detected auto test command [%s], will exit after game.\n",autoTestCmd.c_str()); - - AutoTest::setWantExitGameWhenDone(true); - } - else { - printf("WARNING: Detected and UNKNOWN auto test command [%s].\n",autoTestCmd.c_str()); - } - } - - if(paramPartTokens2.size() >= 2 && paramPartTokens2[1].length() > 0) { - string newGameSettingsFileToLoad = paramPartTokens2[1]; - - printf("About to auto test using game settings file [%s]\n",newGameSettingsFileToLoad.c_str()); - AutoTest::setLoadGameSettingsFile(newGameSettingsFileToLoad); - } - } - } - - Renderer &renderer= Renderer::getInstance(); - lang.loadGameStrings(language,false, true); - - if( lang.hasString("FONT_HEIGHT_TEXT")) { - ::Shared::Graphics::Font::langHeightText = config.getString("FONT_HEIGHT_TEXT",::Shared::Graphics::Font::langHeightText.c_str()); - } + bool startNativeLanguageNamesPrecacheThread = + config.getBool("PreCacheNativeLanguageNamesThread", "true"); + if (startNativeLanguageNamesPrecacheThread == true && + GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + lngCacheGen.reset(new NavtiveLanguageNameListCacheGenerator()); + languageCacheGen.reset(new SimpleTaskThread(lngCacheGen.get(), 1)); - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_FONT_BASESIZE]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_FONT_BASESIZE]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_FONT_BASESIZE]),&foundParamIndIndex); - } - string paramValue = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(paramValue,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string newfontBaseSize = paramPartTokens[1]; - printf("Forcing font base size[%s]\n",newfontBaseSize.c_str()); - - ::Shared::Graphics::Font::baseSize = strToInt(newfontBaseSize); - } - else { - printf("\nInvalid missing font base size specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - - return 1; - } - } - - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] Font::charCount = %d, Font::fontTypeName [%s] Shared::Platform::PlatformContextGl::charSet = %d, Font::fontIsMultibyte = %d, Font::fontIsRightToLeft = %d\n",__FILE__,__FUNCTION__,__LINE__,::Shared::Graphics::Font::charCount,::Shared::Graphics::Font::fontTypeName.c_str(),::Shared::Platform::PlatformContextGl::charSet,::Shared::Graphics::Font::fontIsMultibyte,::Shared::Graphics::Font::fontIsRightToLeft); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Using Font::charCount = %d, Font::fontTypeName [%s] Shared::Platform::PlatformContextGl::charSet = %d, Font::fontIsMultibyte = %d, Font::fontIsRightToLeft = %d\n",::Shared::Graphics::Font::charCount,::Shared::Graphics::Font::fontTypeName.c_str(),::Shared::Platform::PlatformContextGl::charSet,::Shared::Graphics::Font::fontIsMultibyte,::Shared::Graphics::Font::fontIsRightToLeft); - - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_USE_FONT]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_USE_FONT]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_USE_FONT]),&foundParamIndIndex); - } - string paramValue = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(paramValue,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string newfont = paramPartTokens[1]; - - Properties::applyTagsToValue(newfont); - printf("Forcing font [%s]\n",newfont.c_str()); + languageCacheGen->start(); + } -#if defined(WIN32) - string newEnvValue = "MEGAGLEST_FONT=" + newfont; - _putenv(newEnvValue.c_str()); -#else - setenv("MEGAGLEST_FONT",newfont.c_str(),1); -#endif - } - else { - printf("\nInvalid missing font specified on commandline [%s] value [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - return 1; - } - } - - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_CREATE_DATA_ARCHIVES]) == true) { - return handleCreateDataArchivesCommand(argc, argv); - } - - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_SHOW_MAP_CRC]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_SHOW_TILESET_CRC]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_SHOW_TECHTREE_CRC]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_SHOW_SCENARIO_CRC]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_SHOW_PATH_CRC]) == true) { - return handleShowCRCValuesCommand(argc, argv); - } - - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_MAPS]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_TECHTRESS]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_SCENARIOS]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_TILESETS]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_LIST_TUTORIALS]) == true) { - return handleListDataCommand(argc, argv); - - } - - program= new Program(); - mainProgram = program; - renderer.setProgram(program); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPathFinder).enabled == true) { - renderer.setAllowRenderUnitTitles(SystemFlags::getSystemSettingType(SystemFlags::debugPathFinder).enabled); - SystemFlags::OutputDebug(SystemFlags::debugPathFinder,"In [%s::%s Line: %d] renderer.setAllowRenderUnitTitles = %d\n",__FILE__,__FUNCTION__,__LINE__,SystemFlags::getSystemSettingType(SystemFlags::debugPathFinder).enabled); - } - renderer.setAllowRenderUnitTitles(true); - - string screenShotsPath = userData + GameConstants::folder_path_screenshots; - if(isdir(screenShotsPath.c_str()) == false) { - createDirectoryPaths(screenShotsPath); - } + // test + // Shared::Platform::MessageBox(NULL,"Mark's test.","Test",0); + // throw megaglest_runtime_error("test!"); + // ExceptionHandler::DisplayMessage("test!", false); - // Cache Player textures - START - string data_path = getGameReadWritePath(GameConstants::path_data_CacheLookupKey); - std::map &crcPlayerTextureCache = CacheManager::getCachedItem< std::map >(GameConstants::playerTextureCacheLookupKey); - for(int index = 0; index < GameConstants::maxPlayers; ++index) { - string playerTexture = getGameCustomCoreDataPath(data_path, "data/core/faction_textures/faction" + intToStr(index) + ".tga"); - if(fileExists(playerTexture) == true) { - Texture2D *texture = Renderer::getInstance().newTexture2D(rsGlobal); - if(texture) { - texture->load(playerTexture); - } - crcPlayerTextureCache[index] = texture; - } - else { - crcPlayerTextureCache[index] = NULL; - } - } - // Cache Player textures - END - - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - mainWindow= new MainWindow(program); - - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - GameSettings startupGameSettings; - - //parse command line - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_SERVER]) == true) { - program->initServer(mainWindow,false,true); - gameInitialized = true; - } - else if(hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_MASTERSERVER_MODE])) == true) { - program->initServer(mainWindow,false,true,true); - gameInitialized = true; - } - else if(hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_AUTOSTART_LASTGAME])) == true) { - program->initServer(mainWindow,true,false); - gameInitialized = true; - } - else if(hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_AUTOSTART_LAST_SAVED_GAME])) == true) { - string fileName = ""; - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_AUTOSTART_LAST_SAVED_GAME]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex >= 0) { - string loadfileName = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(loadfileName,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - fileName = paramPartTokens[1]; - - if(fileExists(fileName) == false) { - // Save the file now - string saveGameFile = "saved/" + fileName; - if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - saveGameFile = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + saveGameFile; - } - else { - saveGameFile = userData + saveGameFile; - } - if(fileExists(saveGameFile) == true) { - fileName = saveGameFile; - } - } - - if(fileExists(fileName) == false) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"File specified for loading a saved game cannot be found: [%s]",fileName.c_str()); - printf("\n\n======================================================================================\n%s\n======================================================================================\n\n\n",szBuf); - - throw megaglest_runtime_error(szBuf); - } - } - } - program->initSavedGame(mainWindow,false,fileName); - gameInitialized = true; - } - else if(hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_PREVIEW_MAP])) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_PREVIEW_MAP]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_PREVIEW_MAP]),&foundParamIndIndex); - } - string mapName = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(mapName,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - vector paramPartTokens2; - string tileset="forest"; - Tokenize(paramPartTokens[1],paramPartTokens2,","); - if(paramPartTokens2.size() >= 2 && paramPartTokens2[1].length() > 0) { - tileset = paramPartTokens2[1]; - } - string autoloadMapName = paramPartTokens2[0]; - - GameSettings *gameSettings = &startupGameSettings; - gameSettings->setMap(autoloadMapName); - gameSettings->setTileset(tileset); - gameSettings->setTech("megapack"); - gameSettings->setDefaultUnits(false); - gameSettings->setDefaultResources(false); - gameSettings->setDefaultVictoryConditions(true); - gameSettings->setFogOfWar(false); - gameSettings->setAllowObservers(true); - gameSettings->setPathFinderType(pfBasic); - - for(int i = 0; i < GameConstants::maxPlayers; ++i) { - ControlType ct= ctClosed; - - gameSettings->setNetworkPlayerStatuses(i, npst_None); - gameSettings->setFactionControl(i, ct); - gameSettings->setStartLocationIndex(i, i); - gameSettings->setResourceMultiplierIndex(i, 10); - gameSettings->setNetworkPlayerName(i, GameConstants::NETWORK_SLOT_CLOSED_SLOTNAME); - } - - ControlType ct= ctHuman; - - gameSettings->setNetworkPlayerStatuses(0, npst_None); - gameSettings->setFactionControl(0, ct); - gameSettings->setFactionTypeName(0, formatString(GameConstants::OBSERVER_SLOTNAME)); - gameSettings->setTeam(0, GameConstants::maxPlayers + fpt_Observer - 1); - gameSettings->setStartLocationIndex(0, 0); - gameSettings->setNetworkPlayerName(0, GameConstants::OBSERVER_SLOTNAME); - - gameSettings->setFactionCount(1); - - Config &config = Config::getInstance(); - gameSettings->setEnableServerControlledAI(config.getBool("ServerControlledAI","true")); - gameSettings->setNetworkFramePeriod(config.getInt("NetworkSendFrameCount","20")); - - program->initServer(mainWindow,gameSettings); - gameInitialized = true; - } - else { - printf("\nInvalid map name specified on commandline [%s] map [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - printParameterHelp(argv[0],foundInvalidArgs); - delete mainWindow; - mainWindow=NULL; - return 1; - } - } - - else if(hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_CONNECT])) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_CONNECT]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_CONNECT]),&foundParamIndIndex); - } - string serverToConnectTo = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(serverToConnectTo,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string autoConnectServer = paramPartTokens[1]; - - int port = config.getInt("PortServer",intToStr(GameConstants::serverPort).c_str()); - vector paramPartTokens2; - Tokenize(autoConnectServer,paramPartTokens2,":"); - autoConnectServer = paramPartTokens2[0]; - if(paramPartTokens2.size() >= 2 && paramPartTokens2[1].length() > 0) { - port = strToInt(paramPartTokens2[1]); - } - - printf("Connecting to host [%s] using port: %d\n",autoConnectServer.c_str(),port); - if(autoConnectServer == "auto-connect") { - program->initClientAutoFindHost(mainWindow); - } - else { - program->initClient(mainWindow, autoConnectServer,port); - } - gameInitialized = true; - } - else { - - printf("\nInvalid host specified on commandline [%s] host [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - printParameterHelp(argv[0],foundInvalidArgs); - delete mainWindow; - mainWindow=NULL; - return 1; - } - } - - else if(hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_CLIENT])) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_CLIENT]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_CLIENT]),&foundParamIndIndex); - } - string serverToConnectTo = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(serverToConnectTo,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string autoConnectServer = paramPartTokens[1]; - - if(autoConnectServer == "auto-connect") { - program->initClientAutoFindHost(mainWindow); - } - else { - program->initClient(mainWindow, autoConnectServer); - } - gameInitialized = true; - } - else { - - printf("\nInvalid host specified on commandline [%s] host [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - printParameterHelp(argv[0],foundInvalidArgs); - delete mainWindow; - mainWindow=NULL; - return 1; - } - } - else if(hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_LOADSCENARIO])) == true) { - - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_LOADSCENARIO]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_LOADSCENARIO]),&foundParamIndIndex); - } - string scenarioName = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(scenarioName,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string autoloadScenarioName = paramPartTokens[1]; - - program->initScenario(mainWindow, autoloadScenarioName); - gameInitialized = true; - } - else { - printf("\nInvalid scenario name specified on commandline [%s] scenario [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - printParameterHelp(argv[0],foundInvalidArgs); - delete mainWindow; - mainWindow=NULL; - return 1; - } - } - else { - program->initNormal(mainWindow); - } - - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] OpenGL Info:\n%s\n",__FILE__,__FUNCTION__,__LINE__,renderer.getGlInfo().c_str()); - - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_OPENGL_INFO]) == true) { - printf("%s",renderer.getGlInfo().c_str()); - printf("%s",renderer.getGlMoreInfo().c_str()); - - delete mainWindow; - mainWindow=NULL; - return 0; - } - - if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_CONVERT_MODELS]) == true) { - int foundParamIndIndex = -1; - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_CONVERT_MODELS]) + string("="),&foundParamIndIndex); - if(foundParamIndIndex < 0) { - hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_CONVERT_MODELS]),&foundParamIndIndex); - } - string paramValue = argv[foundParamIndIndex]; - vector paramPartTokens; - Tokenize(paramValue,paramPartTokens,"="); - if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) { - string modelFile = paramPartTokens[1]; - printf("About to convert model(s) [%s]\n",modelFile.c_str()); - - string textureFormat = ""; - if(paramPartTokens.size() >= 3 && paramPartTokens[1].length() > 0) { - textureFormat = paramPartTokens[2]; - printf("About to convert using texture format [%s]\n",textureFormat.c_str()); - } - - bool keepsmallest = false; - if(paramPartTokens.size() >= 4 && paramPartTokens[1].length() > 0) { - keepsmallest = (paramPartTokens[3] == "keepsmallest"); - printf("About to convert using keepsmallest = %d\n",keepsmallest); - } - - showCursor(true); - - const Metrics &metrics= Metrics::getInstance(); - renderer.clearBuffers(); - renderer.clearZBuffer(); - renderer.reset2d(); - - if(CoreData::getInstance().getMenuFontBig3D() != NULL) { - renderer.renderText3D( - "Please wait, converting models...", - CoreData::getInstance().getMenuFontBig3D(), - Vec3f(1.f, 1.f, 0.f), (metrics.getScreenW() / 2) - 400, - (metrics.getScreenH() / 2), true); - } - else { - renderer.renderText( - "Please wait, converting models...", - CoreData::getInstance().getMenuFontBig(), - Vec3f(1.f, 1.f, 0.f), (metrics.getScreenW() / 2) - 400, - (metrics.getScreenH() / 2), true); - } - renderer.swapBuffers(); - - std::vector models; - if(isdir(modelFile.c_str()) == true) { - models = getFolderTreeContentsListRecursively(modelFile, ".g3d"); - } - else { - models.push_back(modelFile); - } - - sleep(0); - ::Shared::Platform::Window::handleEvent(); - SDL_PumpEvents(); - - int result = 0; - char szTextBuf[8096]=""; - for(unsigned int i =0; i < models.size(); ++i) { - string &file = models[i]; - - renderer.clearBuffers(); - renderer.clearZBuffer(); - renderer.reset2d(); - snprintf(szTextBuf,8096,"Please wait, converting models [%u of " MG_SIZE_T_SPECIFIER "] ...",i,models.size()); - - if(CoreData::getInstance().getMenuFontBig3D() != NULL) { - renderer.renderText3D( - szTextBuf, - CoreData::getInstance().getMenuFontBig3D(), - Vec3f(1.f, 1.f, 0.f), (metrics.getScreenW() / 2) - 400, - (metrics.getScreenH() / 2), true); - } - else { - renderer.renderText( - szTextBuf, - CoreData::getInstance().getMenuFontBig(), - Vec3f(1.f, 1.f, 0.f), (metrics.getScreenW() / 2) - 400, - (metrics.getScreenH() / 2), true); - } - renderer.swapBuffers(); - - sleep(0); - ::Shared::Platform::Window::handleEvent(); - SDL_PumpEvents(); - - try { - printf("About to load model [%s] [%u of " MG_SIZE_T_SPECIFIER "]\n",file.c_str(),i,models.size()); - Model *model = renderer.newModel(rsGlobal, file); - printf("About to save converted model [%s]\n",file.c_str()); - model->save(file,textureFormat,keepsmallest); - Renderer::getInstance().endModel(rsGlobal, model); - } - catch(const exception &ex) { - result = 1; - printf("ERROR loading model [%s] message [%s]\n",file.c_str(),ex.what()); - } - - } - - delete mainWindow; - mainWindow=NULL; - return result; - } - else { - printf("\nInvalid model specified on commandline [%s] texture [%s]\n\n",argv[foundParamIndIndex],(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL)); - printParameterHelp(argv[0],foundInvalidArgs); - delete mainWindow; - mainWindow=NULL; - return 1; - } - } - - if( hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VALIDATE_TECHTREES]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VALIDATE_FACTIONS]) == true || - hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VALIDATE_SCENARIO]) == true) { - runTechValidationReport(argc, argv); - - delete mainWindow; - mainWindow=NULL; - return 0; - } - - if( hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_TRANSLATE_TECHTREES]) == true) { - runTechTranslationExtraction(argc, argv); - delete mainWindow; - mainWindow=NULL; - return 0; - } - - if( hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_VALIDATE_TILESET]) == true) { - runTilesetValidationReport(argc, argv); - - delete mainWindow; - mainWindow=NULL; - return 0; - } - - gameInitialized = true; - - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - CheckForDuplicateData(); - - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - //throw "BLAH!"; - - // START Test out SIGSEGV error handling - //int *foo = (int*)-1; // make a bad pointer - //printf("%d\n", *foo); // causes segfault - // END - - bool startCRCPrecacheThread = config.getBool("PreCacheCRCThread","true"); - //printf("### In [%s::%s Line: %d] precache thread enabled = %d SystemFlags::VERBOSE_MODE_ENABLED = %d\n",__FILE__,__FUNCTION__,__LINE__,startCRCPrecacheThread,SystemFlags::VERBOSE_MODE_ENABLED); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] precache thread enabled = %d\n",__FILE__,__FUNCTION__,__LINE__,startCRCPrecacheThread); - if (startCRCPrecacheThread == true - && GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); - vector techDataPaths = config.getPathListForType(ptTechs); - - FileCRCPreCacheThread::setPreCacheThreadCacheLookupKey(GameConstants::preCacheThreadCacheLookupKey); - FileCRCPreCacheThread * &preCacheCRCThreadPtr = CacheManager::getCachedItem< FileCRCPreCacheThread * >(GameConstants::preCacheThreadCacheLookupKey); - if(preCacheCRCThreadPtr == NULL) { - preCacheCRCThreadPtr = new FileCRCPreCacheThread(); - } - preCacheThread = preCacheCRCThreadPtr; - preCacheThread->setUniqueID(mutexOwnerId); - preCacheThread->setTechDataPaths(techDataPaths); - //preCacheThread->setFileCRCPreCacheThreadCallbackInterface(&preCacheThreadGame); - preCacheThread->start(); - } - - auto_ptr lngCacheGen; - auto_ptr languageCacheGen; - - bool startNativeLanguageNamesPrecacheThread = config.getBool("PreCacheNativeLanguageNamesThread","true"); - if(startNativeLanguageNamesPrecacheThread == true && - GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - lngCacheGen.reset(new NavtiveLanguageNameListCacheGenerator()); - languageCacheGen.reset(new SimpleTaskThread(lngCacheGen.get(),1)); - - languageCacheGen->start(); - } - - // test - //Shared::Platform::MessageBox(NULL,"Mark's test.","Test",0); - //throw megaglest_runtime_error("test!"); - //ExceptionHandler::DisplayMessage("test!", false); - - // Check for commands being input from stdin - string command=""; + // Check for commands being input from stdin + string command = ""; #ifndef WIN32 - pollfd cinfd[1]; + pollfd cinfd[1]; #else - HANDLE h = 0; + HANDLE h = 0; #endif - if(disableheadless_console == false) { + if (disableheadless_console == false) { #ifndef WIN32 - // Theoretically this should always be 0, but one fileno call isn't going to hurt, and if - // we try to run somewhere that stdin isn't fd 0 then it will still just work - cinfd[0].fd = fileno(stdin); - cinfd[0].events = POLLIN; + // Theoretically this should always be 0, but one fileno call isn't going + // to hurt, and if we try to run somewhere that stdin isn't fd 0 then it + // will still just work + cinfd[0].fd = fileno(stdin); + cinfd[0].events = POLLIN; #else - h = GetStdHandle(STD_INPUT_HANDLE); - //DWORD dwMode; - //GetConsoleMode(h, &dwMode); - //SetConsoleMode(h, dwMode & ~ENABLE_MOUSE_INPUT); - FlushConsoleInputBuffer(h); + h = GetStdHandle(STD_INPUT_HANDLE); + // DWORD dwMode; + // GetConsoleMode(h, &dwMode); + // SetConsoleMode(h, dwMode & ~ENABLE_MOUSE_INPUT); + FlushConsoleInputBuffer(h); #endif - } - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - printf("Headless server is now running...\n"); - printf("To shutdown type: quit\n"); - printf("All commands require you to press ENTER\n"); - } - - //throw megaglest_runtime_error("Test!"); - //printf("About to throw an exception...\n"); - //throw 123; - - //main loop - while(program->isShutdownApplicationEnabled() == false && ::Shared::Platform::Window::handleEvent()) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - - if(disableheadless_console == false) { - #ifndef WIN32 - int pollresult = poll(cinfd, 1, 0); - int pollerror = errno; - if(pollresult) - #else - // This is problematic because input on Windows is not line-buffered so this will return - // even if getline may block. I haven't found a good way to fix it, so for the moment - // I just strongly suggest only running the server from the Python frontend, which does - // line buffer input. This does work okay as long as the user doesn't enter characters - // without pressing enter, and then try to end the server another way (say a remote - // console command), in which case we'll still be waiting for the stdin EOL and hang. - - DWORD saveMode; - GetConsoleMode(h, &saveMode); - DWORD dwMode = saveMode; - dwMode &= ~ENABLE_MOUSE_INPUT; - dwMode &= ~ENABLE_WINDOW_INPUT; - SetConsoleMode(h, dwMode); - - bool gotData = (WaitForSingleObject(h, 0) == WAIT_OBJECT_0); - SetConsoleMode(h, saveMode); - if(gotData == true) - #endif - { + } + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + printf("Headless server is now running...\n"); + printf("To shutdown type: quit\n"); + printf("All commands require you to press ENTER\n"); + } + + // throw megaglest_runtime_error("Test!"); + // printf("About to throw an exception...\n"); + // throw 123; + // main loop + while (program->isShutdownApplicationEnabled() == false && + ::Shared::Platform::Window::handleEvent()) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + + if (disableheadless_console == false) { +#ifndef WIN32 + int pollresult = poll(cinfd, 1, 0); + int pollerror = errno; + if (pollresult) +#else + // This is problematic because input on Windows is not line-buffered + // so this will return even if getline may block. I haven't found a + // good way to fix it, so for the moment I just strongly suggest only + // running the server from the Python frontend, which does line buffer + // input. This does work okay as long as the user doesn't enter + // characters without pressing enter, and then try to end the server + // another way (say a remote console command), in which case we'll + // still be waiting for the stdin EOL and hang. + + DWORD saveMode; + GetConsoleMode(h, &saveMode); + DWORD dwMode = saveMode; + dwMode &= ~ENABLE_MOUSE_INPUT; + dwMode &= ~ENABLE_WINDOW_INPUT; + SetConsoleMode(h, dwMode); + + bool gotData = (WaitForSingleObject(h, 0) == WAIT_OBJECT_0); + SetConsoleMode(h, saveMode); + if (gotData == true) +#endif + { #ifdef WIN32 - bool skip = true; - DWORD nNumberOfCharsToRead = 1024; - DWORD nRead = 0; - INPUT_RECORD irInRec[1025]; - - PeekConsoleInput(h,&irInRec[0],nNumberOfCharsToRead,&nRead); - for(int i = 0; i < nRead; ++i) { - INPUT_RECORD &inr = irInRec[i]; - - //printf("inr.EventType = %d\n",inr.EventType); - if(inr.EventType == KEY_EVENT) { - if(inr.Event.KeyEvent.bKeyDown) { - char cHoldKey = inr.Event.KeyEvent.uChar.AsciiChar; - if(cHoldKey == '\r') { - skip = false; - break; - } - } - } - } + bool skip = true; + DWORD nNumberOfCharsToRead = 1024; + DWORD nRead = 0; + INPUT_RECORD irInRec[1025]; + + PeekConsoleInput(h, &irInRec[0], nNumberOfCharsToRead, &nRead); + for (int i = 0; i < nRead; ++i) { + INPUT_RECORD &inr = irInRec[i]; + + // printf("inr.EventType = %d\n",inr.EventType); + if (inr.EventType == KEY_EVENT) { + if (inr.Event.KeyEvent.bKeyDown) { + char cHoldKey = inr.Event.KeyEvent.uChar.AsciiChar; + if (cHoldKey == '\r') { + skip = false; + break; + } + } + } + } #else - bool skip = false; + bool skip = false; #endif - if(skip == false) { - getline(cin, command); - cin.clear(); + if (skip == false) { + getline(cin, command); + cin.clear(); - printf("server command [%s]\n",command.c_str()); - if(command == "quit") { - break; - } + printf("server command [%s]\n", command.c_str()); + if (command == "quit") { + break; + } #ifndef WIN32 - if (cinfd[0].revents & POLLNVAL) { - printf("invalid file descriptor\n"); - } - if (cinfd[0].revents & POLLERR) { - printf("error in file descriptor\n"); - } - if (cinfd[0].revents & POLLHUP) { - printf("hang up in file descriptor\n"); - } - - if(pollresult < 0) { - printf("pollresult = %d errno = %d [%s]\n",pollresult,pollerror,strerror(pollerror)); - - cinfd[0].fd = fileno(stdin); - cinfd[0].events = POLLIN; - } -#endif - } - } - } - //printf("looping\n"); - } - - program->loop(); - - // Because OpenGL really doesn't do multi-threading well -// if(difftime(time(NULL),lastTextureLoadEvent) >= 3) { -// lastTextureLoadEvent = time(NULL); -// vector textureList = preCacheThread->getPendingTextureList(1); -// for(unsigned int i = 0; i < textureList.size(); ++i) { -// Texture2D * factionLogo = textureList[i]; -// if(factionLogo != NULL) { -// printf("\n\n\n\n|||||||||||||||||||||||||| Load texture [%s]\n",factionLogo->getPath().c_str()); -// //Renderer::findTexture(factionLogo); -// renderer.initTexture(rsGlobal,factionLogo); -// } -// } -// } - } - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - printf("\nHeadless server is about to quit...\n"); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] starting normal application shutdown\n",__FILE__,__FUNCTION__,__LINE__); - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - soundThreadManager = program->getSoundThreadManager(true); - if(soundThreadManager) { - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - soundRenderer.stopAllSounds(shutdownFadeSoundMilliseconds); - chronoshutdownFadeSound.start(); - } - } - - cleanupCRCThread(); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - showCursor(true); - //showWindowCursorState = true; - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - } - catch(const megaglest_runtime_error &e) { - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - soundThreadManager = (program != NULL ? program->getSoundThreadManager(true) : NULL); - if(soundThreadManager) { - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - soundRenderer.stopAllSounds(shutdownFadeSoundMilliseconds); - chronoshutdownFadeSound.start(); - } - if(program != NULL && - program->getTryingRendererInit() == true && - program->getRendererInitOk() == false) { - - message(e.what(),GlobalStaticFlags::getIsNonGraphicalModeEnabled(),tempDataLocation); - } - } - - if(program == NULL || program->getTryingRendererInit() == false || - (program->getTryingRendererInit() == true && - program->getRendererInitOk() == true)) { - - ExceptionHandler::handleRuntimeError(e); - } - } - catch(const exception &e) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - soundThreadManager = (program != NULL ? program->getSoundThreadManager(true) : NULL); - if(soundThreadManager) { - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - soundRenderer.stopAllSounds(shutdownFadeSoundMilliseconds); - chronoshutdownFadeSound.start(); - } - } - - ExceptionHandler::handleRuntimeError(e.what(),true); - } - catch(const char *e) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - soundThreadManager = (program != NULL ? program->getSoundThreadManager(true) : NULL); - if(soundThreadManager) { - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - soundRenderer.stopAllSounds(shutdownFadeSoundMilliseconds); - chronoshutdownFadeSound.start(); - } - } - - ExceptionHandler::handleRuntimeError(e,true); - } - catch(const string &ex) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - soundThreadManager = (program != NULL ? program->getSoundThreadManager(true) : NULL); - if(soundThreadManager) { - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - soundRenderer.stopAllSounds(shutdownFadeSoundMilliseconds); - chronoshutdownFadeSound.start(); - } - } - - ExceptionHandler::handleRuntimeError(ex.c_str(),true); - } -#if !defined(HAVE_GOOGLE_BREAKPAD) - catch(...) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - soundThreadManager = (program != NULL ? program->getSoundThreadManager(true) : NULL); - if(soundThreadManager) { - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - soundRenderer.stopAllSounds(shutdownFadeSoundMilliseconds); - chronoshutdownFadeSound.start(); - } - } - - ExceptionHandler::handleRuntimeError("Unknown error [main]!",true); - } + if (cinfd[0].revents & POLLNVAL) { + printf("invalid file descriptor\n"); + } + if (cinfd[0].revents & POLLERR) { + printf("error in file descriptor\n"); + } + if (cinfd[0].revents & POLLHUP) { + printf("hang up in file descriptor\n"); + } + + if (pollresult < 0) { + printf("pollresult = %d errno = %d [%s]\n", pollresult, + pollerror, strerror(pollerror)); + + cinfd[0].fd = fileno(stdin); + cinfd[0].events = POLLIN; + } #endif + } + } + } + // printf("looping\n"); + } + + program->loop(); + + // Because OpenGL really doesn't do multi-threading well + // if(difftime(time(NULL),lastTextureLoadEvent) >= + // 3) { lastTextureLoadEvent = time(NULL); + // vector textureList = preCacheThread->getPendingTextureList(1); for(unsigned int i = 0; i < + // textureList.size(); ++i) { Texture2D + // * factionLogo = textureList[i]; if(factionLogo != NULL) { + // printf("\n\n\n\n|||||||||||||||||||||||||| + // Load texture [%s]\n",factionLogo->getPath().c_str()); + // //Renderer::findTexture(factionLogo); + // renderer.initTexture(rsGlobal,factionLogo); + // } + // } + // } + } + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + printf("\nHeadless server is about to quit...\n"); + } - cleanupCRCThread(); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] starting normal application shutdown\n", + __FILE__, __FUNCTION__, __LINE__); + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + soundThreadManager = program->getSoundThreadManager(true); + if (soundThreadManager) { + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + soundRenderer.stopAllSounds(shutdownFadeSoundMilliseconds); + chronoshutdownFadeSound.start(); + } + } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + cleanupCRCThread(); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + showCursor(true); + // showWindowCursorState = true; + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + } catch (const megaglest_runtime_error &e) { + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + soundThreadManager = + (program != NULL ? program->getSoundThreadManager(true) : NULL); + if (soundThreadManager) { + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + soundRenderer.stopAllSounds(shutdownFadeSoundMilliseconds); + chronoshutdownFadeSound.start(); + } + if (program != NULL && program->getTryingRendererInit() == true && + program->getRendererInitOk() == false) { + + message(e.what(), GlobalStaticFlags::getIsNonGraphicalModeEnabled(), + tempDataLocation); + } + } - delete mainWindow; - mainWindow = NULL; + if (program == NULL || program->getTryingRendererInit() == false || + (program->getTryingRendererInit() == true && + program->getRendererInitOk() == true)) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + ExceptionHandler::handleRuntimeError(e); + } + } catch (const exception &e) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + soundThreadManager = + (program != NULL ? program->getSoundThreadManager(true) : NULL); + if (soundThreadManager) { + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + soundRenderer.stopAllSounds(shutdownFadeSoundMilliseconds); + chronoshutdownFadeSound.start(); + } + } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - GraphicComponent::clearRegisteredComponents(); + ExceptionHandler::handleRuntimeError(e.what(), true); + } catch (const char *e) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + soundThreadManager = + (program != NULL ? program->getSoundThreadManager(true) : NULL); + if (soundThreadManager) { + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + soundRenderer.stopAllSounds(shutdownFadeSoundMilliseconds); + chronoshutdownFadeSound.start(); + } + } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + ExceptionHandler::handleRuntimeError(e, true); + } catch (const string &ex) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + soundThreadManager = + (program != NULL ? program->getSoundThreadManager(true) : NULL); + if (soundThreadManager) { + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + soundRenderer.stopAllSounds(shutdownFadeSoundMilliseconds); + chronoshutdownFadeSound.start(); + } + } - if(soundThreadManager) { - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - if( Config::getInstance().getString("FactorySound","") != "None" && - soundRenderer.isVolumeTurnedOff() == false) { + ExceptionHandler::handleRuntimeError(ex.c_str(), true); + } +#if !defined(HAVE_GOOGLE_BREAKPAD) + catch (...) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + soundThreadManager = + (program != NULL ? program->getSoundThreadManager(true) : NULL); + if (soundThreadManager) { + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + soundRenderer.stopAllSounds(shutdownFadeSoundMilliseconds); + chronoshutdownFadeSound.start(); + } + } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + ExceptionHandler::handleRuntimeError("Unknown error [main]!", true); + } +#endif - for(;chronoshutdownFadeSound.getMillis() <= shutdownFadeSoundMilliseconds;) { - sleep(10); - } - } + cleanupCRCThread(); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + delete mainWindow; + mainWindow = NULL; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + GraphicComponent::clearRegisteredComponents(); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + if (soundThreadManager) { + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + if (Config::getInstance().getString("FactorySound", "") != "None" && + soundRenderer.isVolumeTurnedOff() == false) { + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + for (; chronoshutdownFadeSound.getMillis() <= + shutdownFadeSoundMilliseconds;) { + sleep(10); + } + } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); - BaseThread::shutdownAndWait(soundThreadManager); + BaseThread::shutdownAndWait(soundThreadManager); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); - delete soundThreadManager; - soundThreadManager = NULL; - } + delete soundThreadManager; + soundThreadManager = NULL; + } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); - return 0; + return 0; } -#if defined(__GNUC__) && !defined(__FreeBSD__) && !defined(BSD) +#if defined(__GNUC__) && !defined(__FreeBSD__) && !defined(BSD) void handleSIGSEGV(int sig) { - char szBuf[8096]=""; - snprintf(szBuf, 8096,"In [%s::%s Line: %d] Error detected: signal %d:\n",__FILE__,__FUNCTION__,__LINE__, sig); - printf("%s",szBuf); - //abort(); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d] Error detected: signal %d:\n", + __FILE__, __FUNCTION__, __LINE__, sig); + printf("%s", szBuf); + // abort(); - ExceptionHandler::handleRuntimeError(szBuf,true); + ExceptionHandler::handleRuntimeError(szBuf, true); } #endif @@ -5944,19 +6981,24 @@ void handleSIGSEGV(int sig) { #if defined(WIN32) // Callback when minidump written. static bool MinidumpCallback(const wchar_t *dump_path, - const wchar_t *minidump_id, - void *context, - EXCEPTION_POINTERS* exinfo, - MDRawAssertionInfo* assertion, - bool succeeded) { + const wchar_t *minidump_id, void *context, + EXCEPTION_POINTERS *exinfo, + MDRawAssertionInfo *assertion, bool succeeded) { printf("\n======= In MinidumpCallback...\n"); - wprintf(L"\n***ERROR details captured:\nCrash minidump folder: %s\nfile: %s.dmp\nSucceeded: %d\n", (dump_path != NULL ? dump_path : L"(null)"),(minidump_id != NULL ? minidump_id : L"(null)"),succeeded); - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - wchar_t szBuf[8096]; - int bufBytes = _snwprintf(szBuf,8096,L"An unhandled error was detected.\n\nA crash dump file has been created in the folder:\n%s\nCrash dump filename is: %s.dmp",dump_path,minidump_id); - szBuf[bufBytes] = '\0'; - MessageBox(NULL, szBuf, L"Unhandled error", MB_OK|MB_SYSTEMMODAL); + wprintf(L"\n***ERROR details captured:\nCrash minidump folder: %s\nfile: " + L"%s.dmp\nSucceeded: %d\n", + (dump_path != NULL ? dump_path : L"(null)"), + (minidump_id != NULL ? minidump_id : L"(null)"), succeeded); + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + wchar_t szBuf[8096]; + int bufBytes = _snwprintf( + szBuf, 8096, + L"An unhandled error was detected.\n\nA crash dump file has been " + L"created in the folder:\n%s\nCrash dump filename is: %s.dmp", + dump_path, minidump_id); + szBuf[bufBytes] = '\0'; + MessageBox(NULL, szBuf, L"Unhandled error", MB_OK | MB_SYSTEMMODAL); } return succeeded; @@ -5965,16 +7007,22 @@ static bool MinidumpCallback(const wchar_t *dump_path, #else // Callback when minidump written. -static bool MinidumpCallback(const google_breakpad::MinidumpDescriptor& descriptor, - void* context, - bool succeeded) { +static bool +MinidumpCallback(const google_breakpad::MinidumpDescriptor &descriptor, + void *context, bool succeeded) { printf("\n======= In MinidumpCallback...\n"); - printf("\n***ERROR details captured:\nCrash minidump folder: %s\nfile: %s\nSucceeded: %d\n", descriptor.directory().c_str(),descriptor.path(),succeeded); - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - char szBuf[8096]; - snprintf(szBuf,8096,"An unhandled error was detected.\n\nA crash dump file has been created in the folder:\n%s\nCrash dump filename is: %s",descriptor.directory().c_str(),descriptor.path()); - message(szBuf,GlobalStaticFlags::getIsNonGraphicalModeEnabled(),tempDataLocation); + printf("\n***ERROR details captured:\nCrash minidump folder: %s\nfile: " + "%s\nSucceeded: %d\n", + descriptor.directory().c_str(), descriptor.path(), succeeded); + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + char szBuf[8096]; + snprintf(szBuf, 8096, + "An unhandled error was detected.\n\nA crash dump file has been " + "created in the folder:\n%s\nCrash dump filename is: %s", + descriptor.directory().c_str(), descriptor.path()); + message(szBuf, GlobalStaticFlags::getIsNonGraphicalModeEnabled(), + tempDataLocation); } return succeeded; @@ -5986,154 +7034,168 @@ static bool MinidumpCallback(const google_breakpad::MinidumpDescriptor& descript #ifdef WIN32 void EnableCrashingOnCrashes() { - typedef BOOL (WINAPI *tGetPolicy)(LPDWORD lpFlags); - typedef BOOL (WINAPI *tSetPolicy)(DWORD dwFlags); - const DWORD EXCEPTION_SWALLOWING = 0x1; - - HMODULE kernel32 = LoadLibraryA("kernel32.dll"); - if(kernel32 != 0) { - tGetPolicy pGetPolicy = (tGetPolicy)GetProcAddress(kernel32, "GetProcessUserModeExceptionPolicy"); - tSetPolicy pSetPolicy = (tSetPolicy)GetProcAddress(kernel32, "SetProcessUserModeExceptionPolicy"); - if (pGetPolicy && pSetPolicy) { - DWORD dwFlags; - if (pGetPolicy(&dwFlags)) { - // Turn off the filter - pSetPolicy(dwFlags & ~EXCEPTION_SWALLOWING); - } - } - } + typedef BOOL(WINAPI * tGetPolicy)(LPDWORD lpFlags); + typedef BOOL(WINAPI * tSetPolicy)(DWORD dwFlags); + const DWORD EXCEPTION_SWALLOWING = 0x1; + + HMODULE kernel32 = LoadLibraryA("kernel32.dll"); + if (kernel32 != 0) { + tGetPolicy pGetPolicy = (tGetPolicy)GetProcAddress( + kernel32, "GetProcessUserModeExceptionPolicy"); + tSetPolicy pSetPolicy = (tSetPolicy)GetProcAddress( + kernel32, "SetProcessUserModeExceptionPolicy"); + if (pGetPolicy && pSetPolicy) { + DWORD dwFlags; + if (pGetPolicy(&dwFlags)) { + // Turn off the filter + pSetPolicy(dwFlags & ~EXCEPTION_SWALLOWING); + } + } + } } #endif -int glestMainSEHWrapper(int argc, char** argv) { - int result = 0; +int glestMainSEHWrapper(int argc, char **argv) { + int result = 0; #ifdef WIN32_STACK_TRACE - //printf("Hooking up WIN32_STACK_TRACE...\n"); -__try { + // printf("Hooking up WIN32_STACK_TRACE...\n"); + __try { #endif - //application_binary= executable_path(argv[0],true); - //printf("\n\nargv0 [%s] application_binary [%s]\n\n",argv[0],application_binary.c_str()); + // application_binary= executable_path(argv[0],true); + // printf("\n\nargv0 [%s] application_binary + // [%s]\n\n",argv[0],application_binary.c_str()); -#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__FreeBSD__) && !defined(BSD) +#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__FreeBSD__) && \ + !defined(BSD) - if(hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_DISABLE_SIGSEGV_HANDLER])) == false) { - signal(SIGSEGV, handleSIGSEGV); - } + if (hasCommandArgument( + argc, argv, string(GAME_ARGS[GAME_ARG_DISABLE_SIGSEGV_HANDLER])) == + false) { + signal(SIGSEGV, handleSIGSEGV); + } // http://developerweb.net/viewtopic.php?id=3013 - //signal(SIGPIPE, SIG_IGN); + // signal(SIGPIPE, SIG_IGN); #endif - initSpecialStrings(); - - IRCThread::setGlobalCacheContainerName(GameConstants::ircClientCacheLookupKey); - result = glestMain(argc, argv); + initSpecialStrings(); + + IRCThread::setGlobalCacheContainerName( + GameConstants::ircClientCacheLookupKey); + result = glestMain(argc, argv); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - cleanupProcessObjects(); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + cleanupProcessObjects(); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); #ifdef WIN32 - //delete winSockManager; - //winSockManager = NULL; + // delete winSockManager; + // winSockManager = NULL; #endif - if(sdl_quitCalled == false) { - sdl_quitCalled = true; - SDL_Quit(); + if (sdl_quitCalled == false) { + sdl_quitCalled = true; + SDL_Quit(); } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + #ifdef WIN32_STACK_TRACE -} -__except(stackdumper(0, GetExceptionInformation(),true), EXCEPTION_CONTINUE_SEARCH) { - return 0; -} + } __except (stackdumper(0, GetExceptionInformation(), true), + EXCEPTION_CONTINUE_SEARCH) { + return 0; + } #endif -return result; + return result; } -int glestMainWrapper(int argc, char** argv) { - //setlocale(LC_ALL, "zh_TW.UTF-8"); - //setlocale(LC_ALL, ""); +int glestMainWrapper(int argc, char **argv) { + // setlocale(LC_ALL, "zh_TW.UTF-8"); + // setlocale(LC_ALL, ""); #ifdef WIN32 - EnableCrashingOnCrashes(); + EnableCrashingOnCrashes(); #endif #if defined(HAVE_GOOGLE_BREAKPAD) -/* - handler = new ExceptionHandler(const wstring& dump_path, - FilterCallback filter, - MinidumpCallback callback, - void* callback_context, - int handler_types, - MINIDUMP_TYPE dump_type, - const wchar_t* pipe_name, - const CustomClientInfo* custom_info); -*/ - - // See this link about swallowed exceptions in Win 7: http://blog.paulbetts.org/index.php/2010/07/20/the-case-of-the-disappearing-onload-exception-user-mode-callback-exceptions-in-x64/ - //DWORD dwFlags; - //if (GetProcessUserModeExceptionPolicy(&dwFlags)) { - // SetProcessUserModeExceptionPolicy(dwFlags & ~PROCESS_CALLBACK_FILTER_ENABLED); // turn off bit 1 - //} - - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Hooking up google_breakpad::ExceptionHandler...\n"); + /* + handler = new ExceptionHandler(const wstring& dump_path, + FilterCallback + filter, MinidumpCallback callback, void* callback_context, int + handler_types, MINIDUMP_TYPE dump_type, const wchar_t* pipe_name, const + CustomClientInfo* custom_info); + */ + + // See this link about swallowed exceptions in Win 7: + // http://blog.paulbetts.org/index.php/2010/07/20/the-case-of-the-disappearing-onload-exception-user-mode-callback-exceptions-in-x64/ + // DWORD dwFlags; + // if (GetProcessUserModeExceptionPolicy(&dwFlags)) { + // SetProcessUserModeExceptionPolicy(dwFlags & + //~PROCESS_CALLBACK_FILTER_ENABLED); // turn off bit 1 + //} + + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Hooking up + // google_breakpad::ExceptionHandler...\n"); #if defined(WIN32) - wstring dumpfilepath = utf8_decode("."); - //google_breakpad::ExceptionHandler handler(dumpfilepath, NULL, MinidumpCallback, NULL, true); - errorHandlerPtr.reset(new google_breakpad::ExceptionHandler(dumpfilepath, NULL, MinidumpCallback, - NULL, google_breakpad::ExceptionHandler::HANDLER_ALL)); + wstring dumpfilepath = utf8_decode("."); + // google_breakpad::ExceptionHandler handler(dumpfilepath, NULL, + // MinidumpCallback, NULL, true); + errorHandlerPtr.reset(new google_breakpad::ExceptionHandler( + dumpfilepath, NULL, MinidumpCallback, NULL, + google_breakpad::ExceptionHandler::HANDLER_ALL)); #else - google_breakpad::MinidumpDescriptor descriptor("."); - errorHandlerPtr.reset(new google_breakpad::ExceptionHandler(descriptor, NULL, MinidumpCallback, NULL, true,-1)); + google_breakpad::MinidumpDescriptor descriptor("."); + errorHandlerPtr.reset(new google_breakpad::ExceptionHandler( + descriptor, NULL, MinidumpCallback, NULL, true, -1)); #endif -// ExceptionHandler(const wstring& dump_path, -// FilterCallback filter, -// MinidumpCallback callback, -// void* callback_context, -// int handler_types); + // ExceptionHandler(const wstring& dump_path, + // FilterCallback filter, + // MinidumpCallback callback, + // void* callback_context, + // int handler_types); #endif -#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__FreeBSD__) && !defined(BSD) -//#ifdef DEBUG - //printf("MTRACE will be called...\n"); - //mtrace (); -//#endif +#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__FreeBSD__) && \ + !defined(BSD) + // #ifdef DEBUG + // printf("MTRACE will be called...\n"); + // mtrace (); +// #endif #endif #ifdef WIN32 - //winSockManager = new SocketManager(); - SocketManager winSockManager; + // winSockManager = new SocketManager(); + SocketManager winSockManager; #endif - - bool isSteamMode = hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_STEAM]); - if (isSteamMode == true) { - if (!STEAMSHIM_init()) { - printf("\nSteam API init failed, terminating.\n"); - return 42; - } - } + bool isSteamMode = hasCommandArgument(argc, argv, GAME_ARGS[GAME_ARG_STEAM]); + if (isSteamMode == true) { + if (!STEAMSHIM_init()) { + printf("\nSteam API init failed, terminating.\n"); + return 42; + } + } - int result = glestMainSEHWrapper(argc, argv); + int result = glestMainSEHWrapper(argc, argv); - if (isSteamMode == true) { - printf("\nSteam API deinit.\n"); - STEAMSHIM_deinit(); - } + if (isSteamMode == true) { + printf("\nSteam API deinit.\n"); + STEAMSHIM_deinit(); + } - return result; + return result; } -}}//end namespace +} // namespace Game +} // namespace Glest MAIN_FUNCTION(Glest::Game::glestMainWrapper) diff --git a/source/glest_game/main/main.h b/source/glest_game/main/main.h index e8e1646c7..db5937299 100644 --- a/source/glest_game/main/main.h +++ b/source/glest_game/main/main.h @@ -12,15 +12,16 @@ #ifndef _GLEST_GAME_MAIN_H_ #define _GLEST_GAME_MAIN_H_ -#include +#include "leak_dumper.h" #include "program.h" #include "window_gl.h" -#include "leak_dumper.h" +#include using Shared::Platform::MouseButton; using Shared::Platform::MouseState; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class MainWindow @@ -28,49 +29,50 @@ namespace Glest{ namespace Game{ /// Main program window // ===================================================== -class MainWindow: public WindowGl { +class MainWindow : public WindowGl { private: - Program* program; - PopupMenu popupMenu; - int cancelLanguageSelection; - bool triggerLanguageToggle; - string triggerLanguage; + Program *program; + PopupMenu popupMenu; + int cancelLanguageSelection; + bool triggerLanguageToggle; + string triggerLanguage; - void showLanguages(); + void showLanguages(); public: - explicit MainWindow(Program *program); - ~MainWindow(); + explicit MainWindow(Program *program); + ~MainWindow(); - void setProgram(Program *program); + void setProgram(Program *program); - virtual void eventMouseDown(int x, int y, MouseButton mouseButton); - virtual void eventMouseUp(int x, int y, MouseButton mouseButton); - virtual void eventMouseDoubleClick(int x, int y, MouseButton mouseButton); - virtual void eventMouseMove(int x, int y, const MouseState *mouseState); - virtual bool eventTextInput(std::string text); - virtual bool eventSdlKeyDown(SDL_KeyboardEvent key); - virtual void eventKeyDown(SDL_KeyboardEvent key); - virtual void eventMouseWheel(int x, int y, int zDelta); - virtual void eventKeyUp(SDL_KeyboardEvent key); - virtual void eventKeyPress(SDL_KeyboardEvent c); - virtual void eventActivate(bool active); - virtual void eventResize(SizeState sizeState); - virtual void eventClose(); - virtual void eventWindowEvent(SDL_WindowEvent event); + virtual void eventMouseDown(int x, int y, MouseButton mouseButton); + virtual void eventMouseUp(int x, int y, MouseButton mouseButton); + virtual void eventMouseDoubleClick(int x, int y, MouseButton mouseButton); + virtual void eventMouseMove(int x, int y, const MouseState *mouseState); + virtual bool eventTextInput(std::string text); + virtual bool eventSdlKeyDown(SDL_KeyboardEvent key); + virtual void eventKeyDown(SDL_KeyboardEvent key); + virtual void eventMouseWheel(int x, int y, int zDelta); + virtual void eventKeyUp(SDL_KeyboardEvent key); + virtual void eventKeyPress(SDL_KeyboardEvent c); + virtual void eventActivate(bool active); + virtual void eventResize(SizeState sizeState); + virtual void eventClose(); + virtual void eventWindowEvent(SDL_WindowEvent event); - virtual void render(); - void toggleLanguage(string language); - bool getTriggerLanguageToggle() const { return triggerLanguageToggle; } - string getTriggerLanguage() const { return triggerLanguage; } + virtual void render(); + void toggleLanguage(string language); + bool getTriggerLanguageToggle() const { return triggerLanguageToggle; } + string getTriggerLanguage() const { return triggerLanguage; } - virtual int getDesiredScreenWidth(); - virtual int getDesiredScreenHeight(); + virtual int getDesiredScreenWidth(); + virtual int getDesiredScreenHeight(); protected: - virtual void eventToggleFullScreen(bool isFullscreen); + virtual void eventToggleFullScreen(bool isFullscreen); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/main/program.cpp b/source/glest_game/main/program.cpp index 8b54e60f3..2e9b23502 100644 --- a/source/glest_game/main/program.cpp +++ b/source/glest_game/main/program.cpp @@ -11,24 +11,24 @@ #include "program.h" -#include "sound.h" -#include "renderer.h" #include "config.h" +#include "core_data.h" #include "game.h" -#include "main_menu.h" #include "intro.h" -#include "world.h" -#include "main.h" -#include "sound_renderer.h" +#include "leak_dumper.h" #include "logger.h" -#include "profiler.h" -#include "core_data.h" -#include "metrics.h" -#include "network_manager.h" +#include "main.h" +#include "main_menu.h" #include "menu_state_custom_game.h" #include "menu_state_join_game.h" #include "menu_state_scenario.h" -#include "leak_dumper.h" +#include "metrics.h" +#include "network_manager.h" +#include "profiler.h" +#include "renderer.h" +#include "sound.h" +#include "sound_renderer.h" +#include "world.h" using namespace Shared::Util; using namespace Shared::Graphics; @@ -38,9 +38,10 @@ using namespace Shared::Graphics::Gl; // class Program // ===================================================== -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { -const int Program::maxTimes= 10; +const int Program::maxTimes = 10; Program *Program::singleton = NULL; const int SOUND_THREAD_UPDATE_MILLISECONDS = 25; @@ -52,128 +53,136 @@ const char *ProgramState::MAIN_PROGRAM_RENDER_KEY = "MEGAGLEST.RENDER"; // ===================================================== ProgramState::ProgramState(Program *program) { - this->program= program; - this->forceMouseRender = false; - this->mouseX = 0; - this->mouseY = 0; - this->mouse2dAnim = 0; - this->fps= 0; - this->lastFps= 0; - this->startX=0; - this->startY=0; + this->program = program; + this->forceMouseRender = false; + this->mouseX = 0; + this->mouseY = 0; + this->mouse2dAnim = 0; + this->fps = 0; + this->lastFps = 0; + this->startX = 0; + this->startY = 0; } void ProgramState::restoreToStartXY() { - SDL_WarpMouseInWindow(this->program->getWindow()->getSDLWindow(), startX, startY); + SDL_WarpMouseInWindow(this->program->getWindow()->getSDLWindow(), startX, + startY); } -void ProgramState::incrementFps() { - fps++; -} +void ProgramState::incrementFps() { fps++; } void ProgramState::tick() { - lastFps= fps; - fps= 0; + lastFps = fps; + fps = 0; } bool ProgramState::canRender(bool sleepIfCannotRender) { - int maxFPSCap = Config::getInstance().getInt("RenderFPSCap","500"); - int sleepMillis = Config::getInstance().getInt("RenderFPSCapSleepMillis","1"); - //Renderer &renderer= Renderer::getInstance(); - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - maxFPSCap = Config::getInstance().getInt("RenderFPSCapHeadless","250"); - sleepMillis = Config::getInstance().getInt("RenderFPSCapHeadlessSleepMillis","1"); - } - - if(lastFps > maxFPSCap) { - if(sleepIfCannotRender == true) { - sleep(sleepMillis); - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] sleeping because lastFps = %d, maxFPSCap = %d sleepMillis = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,lastFps,maxFPSCap,sleepMillis); - } - return false; - } - return true; + int maxFPSCap = Config::getInstance().getInt("RenderFPSCap", "500"); + int sleepMillis = + Config::getInstance().getInt("RenderFPSCapSleepMillis", "1"); + // Renderer &renderer= Renderer::getInstance(); + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + maxFPSCap = Config::getInstance().getInt("RenderFPSCapHeadless", "250"); + sleepMillis = + Config::getInstance().getInt("RenderFPSCapHeadlessSleepMillis", "1"); + } + + if (lastFps > maxFPSCap) { + if (sleepIfCannotRender == true) { + sleep(sleepMillis); + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] + // sleeping because lastFps = %d, maxFPSCap = %d sleepMillis = + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,lastFps,maxFPSCap,sleepMillis); + } + return false; + } + return true; } void ProgramState::render() { - Renderer &renderer= Renderer::getInstance(); - - canRender(); - incrementFps(); - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - renderer.clearBuffers(); - renderer.reset2d(); - renderer.renderMessageBox(program->getMsgBox()); - renderer.renderMouse2d(mouseX, mouseY, mouse2dAnim); - renderer.swapBuffers(); - } + Renderer &renderer = Renderer::getInstance(); + + canRender(); + incrementFps(); + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + renderer.clearBuffers(); + renderer.reset2d(); + renderer.renderMessageBox(program->getMsgBox()); + renderer.renderMouse2d(mouseX, mouseY, mouse2dAnim); + renderer.swapBuffers(); + } } void ProgramState::update() { - mouse2dAnim = (mouse2dAnim +1) % Renderer::maxMouse2dAnim; + mouse2dAnim = (mouse2dAnim + 1) % Renderer::maxMouse2dAnim; } void ProgramState::mouseMove(int x, int y, const MouseState *mouseState) { - mouseX = x; - mouseY = y; - program->getMsgBox()->mouseMove(x, y); + mouseX = x; + mouseY = y; + program->getMsgBox()->mouseMove(x, y); } -Program::ShowMessageProgramState::ShowMessageProgramState(Program *program, const char *msg) : - ProgramState(program) { - userWantsExit = false; - msgBox.registerGraphicComponent("ShowMessageProgramState", "msgBox"); - msgBox.init("Ok"); - - if(msg) { - fprintf(stderr, "%s\n", msg); - msgBox.setText(msg); - } - else { - msgBox.setText("Mega-Glest has crashed."); - } - - mouse2dAnim = mouseY = mouseX = 0; - this->msg = (msg ? msg : ""); +Program::ShowMessageProgramState::ShowMessageProgramState(Program *program, + const char *msg) + : ProgramState(program) { + userWantsExit = false; + msgBox.registerGraphicComponent("ShowMessageProgramState", "msgBox"); + msgBox.init("Ok"); + + if (msg) { + fprintf(stderr, "%s\n", msg); + msgBox.setText(msg); + } else { + msgBox.setText("Mega-Glest has crashed."); + } + + mouse2dAnim = mouseY = mouseX = 0; + this->msg = (msg ? msg : ""); } void Program::ShowMessageProgramState::render() { - Renderer &renderer= Renderer::getInstance(); - renderer.clearBuffers(); - renderer.reset2d(); - renderer.renderMessageBox(&msgBox); - renderer.renderMouse2d(mouseX, mouseY, mouse2dAnim); - renderer.swapBuffers(); + Renderer &renderer = Renderer::getInstance(); + renderer.clearBuffers(); + renderer.reset2d(); + renderer.renderMessageBox(&msgBox); + renderer.renderMouse2d(mouseX, mouseY, mouse2dAnim); + renderer.swapBuffers(); } void Program::ShowMessageProgramState::mouseDownLeft(int x, int y) { - int button= 0; - if(msgBox.mouseClick(x,y,button)) { - program->exit(); - userWantsExit = true; - } + int button = 0; + if (msgBox.mouseClick(x, y, button)) { + program->exit(); + userWantsExit = true; + } } void Program::ShowMessageProgramState::keyPress(SDL_KeyboardEvent c) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d] c = [%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,c.keysym.sym); - - // if user pressed return we exit - //if(c == 13) { - if(isKeyPressed(SDLK_RETURN,c) == true) { - program->exit(); - userWantsExit = true; - } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s %d] c = [%d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, c.keysym.sym); + + // if user pressed return we exit + // if(c == 13) { + if (isKeyPressed(SDLK_RETURN, c) == true) { + program->exit(); + userWantsExit = true; + } } -void Program::ShowMessageProgramState::mouseMove(int x, int y, const MouseState &mouseState) { - mouseX = x; - mouseY = y; - msgBox.mouseMove(x, y); +void Program::ShowMessageProgramState::mouseMove(int x, int y, + const MouseState &mouseState) { + mouseX = x; + mouseY = y; + msgBox.mouseMove(x, y); } void Program::ShowMessageProgramState::update() { - mouse2dAnim = (mouse2dAnim +1) % Renderer::maxMouse2dAnim; + mouse2dAnim = (mouse2dAnim + 1) % Renderer::maxMouse2dAnim; } // ===================== PUBLIC ======================== @@ -182,792 +191,1087 @@ bool Program::rendererInitOk = false; bool Program::tryingRendererInit = false; Program::Program() : msgBox("Program", "msgBox") { - //this->masterserverMode = false; - this->window = NULL; - this->shutdownApplicationEnabled = false; - this->skipRenderFrameCount = 0; - this->messageBoxIsSystemError = false; - this->programStateOldSystemError = NULL; - this->programState= NULL; - this->singleton = this; - this->soundThreadManager = NULL; - - //mesage box - Lang &lang= Lang::getInstance(); - //msgBox.registerGraphicComponent("Program", "msgBox"); - msgBox.init(lang.getString("Ok")); - msgBox.setEnabled(false); -} - -//bool Program::isMasterserverMode() const { -// return this->masterserverMode; -//} - -void Program::initNormal(WindowGl *window){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - Config &config = Config::getInstance(); - init(window); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - setState(new Intro(this)); - showCursor(config.getBool("No2DMouseRendering","false")); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // this->masterserverMode = false; + this->window = NULL; + this->shutdownApplicationEnabled = false; + this->skipRenderFrameCount = 0; + this->messageBoxIsSystemError = false; + this->programStateOldSystemError = NULL; + this->programState = NULL; + this->singleton = this; + this->soundThreadManager = NULL; + + // mesage box + Lang &lang = Lang::getInstance(); + // msgBox.registerGraphicComponent("Program", "msgBox"); + msgBox.init(lang.getString("Ok")); + msgBox.setEnabled(false); } -void Program::initSavedGame(WindowGl *window,bool masterserverMode, string saveGameFile) { - init(window); - MainMenu *mainMenu= new MainMenu(this); - setState(mainMenu); +// bool Program::isMasterserverMode() const { +// return this->masterserverMode; +// } + +void Program::initNormal(WindowGl *window) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + Config &config = Config::getInstance(); + init(window); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + setState(new Intro(this)); + showCursor(config.getBool("No2DMouseRendering", "false")); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); +} - if(saveGameFile == "") { - Config &config = Config::getInstance(); - saveGameFile = config.getString("LastSavedGame",""); - if(saveGameFile == "") { - saveGameFile = GameConstants::saveGameFileDefault; - if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - saveGameFile = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + saveGameFile; - } - else { - string userData = Config::getInstance().getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - saveGameFile = userData + saveGameFile; - } - } - } +void Program::initSavedGame(WindowGl *window, bool masterserverMode, + string saveGameFile) { + init(window); + MainMenu *mainMenu = new MainMenu(this); + setState(mainMenu); + + if (saveGameFile == "") { + Config &config = Config::getInstance(); + saveGameFile = config.getString("LastSavedGame", ""); + if (saveGameFile == "") { + saveGameFile = GameConstants::saveGameFileDefault; + if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { + saveGameFile = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + + saveGameFile; + } else { + string userData = Config::getInstance().getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + saveGameFile = userData + saveGameFile; + } + } + } - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Loading game from [%s]\n",saveGameFile.c_str()); - printf("Loading saved game from [%s]\n",saveGameFile.c_str()); + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Loading game from + // [%s]\n",saveGameFile.c_str()); + printf("Loading saved game from [%s]\n", saveGameFile.c_str()); - Game::loadGame(saveGameFile,this,masterserverMode); + Game::loadGame(saveGameFile, this, masterserverMode); } -void Program::initServer(WindowGl *window, bool autostart,bool openNetworkSlots, - bool masterserverMode) { - //this->masterserverMode = masterserverMode; - init(window); - MainMenu *mainMenu= new MainMenu(this); - setState(mainMenu); - mainMenu->setState(new MenuStateCustomGame(this, mainMenu, openNetworkSlots, pNewGame, autostart, NULL, masterserverMode)); +void Program::initServer(WindowGl *window, bool autostart, + bool openNetworkSlots, bool masterserverMode) { + // this->masterserverMode = masterserverMode; + init(window); + MainMenu *mainMenu = new MainMenu(this); + setState(mainMenu); + mainMenu->setState(new MenuStateCustomGame(this, mainMenu, openNetworkSlots, + pNewGame, autostart, NULL, + masterserverMode)); } void Program::initServer(WindowGl *window, GameSettings *settings) { - init(window); - MainMenu *mainMenu= new MainMenu(this); - setState(mainMenu); - mainMenu->setState(new MenuStateCustomGame(this, mainMenu, false, pNewGame, true, settings)); + init(window); + MainMenu *mainMenu = new MainMenu(this); + setState(mainMenu); + mainMenu->setState( + new MenuStateCustomGame(this, mainMenu, false, pNewGame, true, settings)); } void Program::initClient(WindowGl *window, const Ip &serverIp, int portNumber) { - init(window); - MainMenu *mainMenu= new MainMenu(this); - setState(mainMenu); - mainMenu->setState(new MenuStateJoinGame(this, mainMenu, true, serverIp,portNumber)); + init(window); + MainMenu *mainMenu = new MainMenu(this); + setState(mainMenu); + mainMenu->setState( + new MenuStateJoinGame(this, mainMenu, true, serverIp, portNumber)); } void Program::initClientAutoFindHost(WindowGl *window) { - init(window); - MainMenu *mainMenu= new MainMenu(this); - setState(mainMenu); - bool autoFindHost = true; - mainMenu->setState(new MenuStateJoinGame(this, mainMenu, &autoFindHost)); - + init(window); + MainMenu *mainMenu = new MainMenu(this); + setState(mainMenu); + bool autoFindHost = true; + mainMenu->setState(new MenuStateJoinGame(this, mainMenu, &autoFindHost)); } void Program::initScenario(WindowGl *window, string autoloadScenarioName) { - init(window); - MainMenu *mainMenu= new MainMenu(this); - setState(mainMenu); - mainMenu->setState(new MenuStateScenario(this, mainMenu, false, - Config::getInstance().getPathListForType(ptScenarios),autoloadScenarioName)); + init(window); + MainMenu *mainMenu = new MainMenu(this); + setState(mainMenu); + mainMenu->setState(new MenuStateScenario( + this, mainMenu, false, + Config::getInstance().getPathListForType(ptScenarios), + autoloadScenarioName)); } -Program::~Program(){ - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - delete programState; - programState = NULL; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - Renderer::getInstance().end(); - CoreData &coreData= CoreData::getInstance(); - coreData.cleanup(); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //restore video mode - restoreDisplaySettings(); - singleton = NULL; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(soundThreadManager != NULL) { - BaseThread::shutdownAndWait(soundThreadManager); - delete soundThreadManager; - soundThreadManager = NULL; - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +Program::~Program() { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + delete programState; + programState = NULL; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + Renderer::getInstance().end(); + CoreData &coreData = CoreData::getInstance(); + coreData.cleanup(); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + // restore video mode + restoreDisplaySettings(); + singleton = NULL; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + if (soundThreadManager != NULL) { + BaseThread::shutdownAndWait(soundThreadManager); + delete soundThreadManager; + soundThreadManager = NULL; + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); } void Program::restoreStateFromSystemError() { - messageBoxIsSystemError = false; - if(this->programStateOldSystemError == NULL) { - setState(new Intro(this)); - } - else { - setState(this->programStateOldSystemError); - } + messageBoxIsSystemError = false; + if (this->programStateOldSystemError == NULL) { + setState(new Intro(this)); + } else { + setState(this->programStateOldSystemError); + } } bool Program::textInput(std::string text) { - if(msgBox.getEnabled()) { - return false; - } - //delegate event - return programState->textInput(text); + if (msgBox.getEnabled()) { + return false; + } + // delegate event + return programState->textInput(text); } bool Program::sdlKeyDown(SDL_KeyboardEvent key) { - //delegate event - return programState->sdlKeyDown(key); + // delegate event + return programState->sdlKeyDown(key); } void Program::keyDown(SDL_KeyboardEvent key) { - if(msgBox.getEnabled()) { - //SDL_keysym keystate = Window::getKeystate(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //if(key == vkEscape || key == SDLK_ESCAPE || - // ((key == vkReturn || key == SDLK_RETURN || key == SDLK_KP_ENTER) && !(keystate.mod & (KMOD_LALT | KMOD_RALT)))) { - if(isKeyPressed(SDLK_ESCAPE,key) == true || ((isKeyPressed(SDLK_RETURN,key) == true) && !(key.keysym.mod & (KMOD_LALT | KMOD_RALT)))) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //printf("---> keystate [%d]\n",keystate); - msgBox.setEnabled(false); - if(messageBoxIsSystemError == true) { - restoreStateFromSystemError(); - } - } - } - //delegate event - programState->keyDown(key); + if (msgBox.getEnabled()) { + // SDL_keysym keystate = Window::getKeystate(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // if(key == vkEscape || key == SDLK_ESCAPE || + // ((key == vkReturn || key == SDLK_RETURN || key == SDLK_KP_ENTER) && + //!(keystate.mod & (KMOD_LALT | KMOD_RALT)))) { + if (isKeyPressed(SDLK_ESCAPE, key) == true || + ((isKeyPressed(SDLK_RETURN, key) == true) && + !(key.keysym.mod & (KMOD_LALT | KMOD_RALT)))) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // printf("---> keystate [%d]\n",keystate); + msgBox.setEnabled(false); + if (messageBoxIsSystemError == true) { + restoreStateFromSystemError(); + } + } + } + // delegate event + programState->keyDown(key); } -void Program::keyUp(SDL_KeyboardEvent key) { - programState->keyUp(key); -} +void Program::keyUp(SDL_KeyboardEvent key) { programState->keyUp(key); } -void Program::keyPress(SDL_KeyboardEvent c) { - programState->keyPress(c); -} +void Program::keyPress(SDL_KeyboardEvent c) { programState->keyPress(c); } void Program::mouseDownLeft(int x, int y) { - if(msgBox.getEnabled()) { - int button= 0; - if(msgBox.mouseClick(x, y, button)) { - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //close message box - msgBox.setEnabled(false); - if(messageBoxIsSystemError == true) { - restoreStateFromSystemError(); - } - } - } + if (msgBox.getEnabled()) { + int button = 0; + if (msgBox.mouseClick(x, y, button)) { + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // close message box + msgBox.setEnabled(false); + if (messageBoxIsSystemError == true) { + restoreStateFromSystemError(); + } + } + } } void Program::eventMouseMove(int x, int y, const MouseState *ms) { - if (msgBox.getEnabled()) { - msgBox.mouseMove(x, y); - } + if (msgBox.getEnabled()) { + msgBox.mouseMove(x, y); + } } -void Program::simpleTask(BaseThread *callingThread,void *userdata) { - loopWorker(); +void Program::simpleTask(BaseThread *callingThread, void *userdata) { + loopWorker(); } -void Program::loop() { - loopWorker(); -} +void Program::loop() { loopWorker(); } void Program::loopWorker() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] ================================= MAIN LOOP START ================================= \n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //Renderer &renderer= Renderer::getInstance(); - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && window) { - MainWindow *mainWindow = dynamic_cast(window); - if(mainWindow) { - //mainWindow->render(); - if(mainWindow->getTriggerLanguageToggle()) { - mainWindow->toggleLanguage(mainWindow->getTriggerLanguage()); - } - } - } - - Chrono chronoPerformanceCounts; - - bool showPerfStats = Config::getInstance().getBool("ShowPerfStats","false"); - Chrono chronoPerf; - char perfBuf[8096]=""; - std::vector perfList; - if(showPerfStats) chronoPerf.start(); - - Chrono chronoLoop; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chronoLoop.start(); - - Chrono chrono; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); - - //render - assert(programState != NULL); - - if(this->programState->quitTriggered() == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - Stats endStats = this->programState->quitAndToggleState(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - Game::exitGameState(this, endStats); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - return; + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] ================================= MAIN LOOP " + "START ================================= \n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + // Renderer &renderer= Renderer::getInstance(); + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && window) { + MainWindow *mainWindow = dynamic_cast(window); + if (mainWindow) { + // mainWindow->render(); + if (mainWindow->getTriggerLanguageToggle()) { + mainWindow->toggleLanguage(mainWindow->getTriggerLanguage()); + } + } + } + + Chrono chronoPerformanceCounts; + + bool showPerfStats = Config::getInstance().getBool("ShowPerfStats", "false"); + Chrono chronoPerf; + char perfBuf[8096] = ""; + std::vector perfList; + if (showPerfStats) + chronoPerf.start(); + + Chrono chronoLoop; + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) + chronoLoop.start(); + + Chrono chrono; + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) + chrono.start(); + + // render + assert(programState != NULL); + + if (this->programState->quitTriggered() == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + Stats endStats = this->programState->quitAndToggleState(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + Game::exitGameState(this, endStats); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + return; + } + ProgramState *prevState = this->programState; + + if (showPerfStats) { + sprintf(perfBuf, "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + assert(programState != NULL); + + chronoPerformanceCounts.start(); + + programState->render(); + + programState->addPerformanceCount(ProgramState::MAIN_PROGRAM_RENDER_KEY, + chronoPerformanceCounts.getMillis()); + + if (showPerfStats) { + sprintf(perfBuf, "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s] Line: %d programState->render took msecs: %lld " + "==============> MAIN LOOP RENDERING\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // update camera + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) + chrono.start(); + + chronoPerformanceCounts.start(); + + while (updateCameraTimer.isTime()) { + programState->updateCamera(); + } + + programState->addPerformanceCount("programState->updateCamera()", + chronoPerformanceCounts.getMillis()); + + if (showPerfStats) { + sprintf(perfBuf, "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s] Line: %d programState->render took msecs: %lld " + "==============> MAIN LOOP CAMERA UPDATING\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // update world + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) + chrono.start(); + int updateCount = 0; + while (prevState == this->programState && updateTimer.isTime()) { + Chrono chronoUpdateLoop; + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled) + chronoUpdateLoop.start(); + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER + " updateCount: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis(), updateCount); + perfList.push_back(perfBuf); } - ProgramState *prevState = this->programState; - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - assert(programState != NULL); - - chronoPerformanceCounts.start(); - - programState->render(); - - programState->addPerformanceCount(ProgramState::MAIN_PROGRAM_RENDER_KEY,chronoPerformanceCounts.getMillis()); - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d programState->render took msecs: %lld ==============> MAIN LOOP RENDERING\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - //update camera - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); + GraphicComponent::update(); + programState->update(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chronoUpdateLoop.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] programState->update took " + "msecs: %lld, updateCount = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, + chronoUpdateLoop.getMillis(), updateCount); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chronoUpdateLoop.getMillis() > 0) + chronoUpdateLoop.start(); + + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER + " updateCount: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis(), updateCount); + perfList.push_back(perfBuf); + } + if (prevState == this->programState) { + chronoPerformanceCounts.start(); + + if (soundThreadManager == NULL || + soundThreadManager->isThreadExecutionLagging()) { + if (soundThreadManager != NULL) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s %d] ERROR / WARNING " + "soundThreadManager->isThreadExecutionLagging is TRUE\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s %d] ERROR / WARNING " + "soundThreadManager->isThreadExecutionLagging is TRUE\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } + SoundRenderer::getInstance().update(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chronoUpdateLoop.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] SoundRenderer::getInstance().update() took " + "msecs: %lld, updateCount = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoUpdateLoop.getMillis(), updateCount); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chronoUpdateLoop.getMillis() > 0) + chronoUpdateLoop.start(); + } + + programState->addPerformanceCount("SoundRenderer::getInstance().update()", + chronoPerformanceCounts.getMillis()); + + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER + " updateCount: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis(), updateCount); + perfList.push_back(perfBuf); + } + + chronoPerformanceCounts.start(); + + NetworkManager::getInstance().update(); + + programState->addPerformanceCount( + "NetworkManager::getInstance().update()", + chronoPerformanceCounts.getMillis()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chronoUpdateLoop.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] NetworkManager::getInstance().update() took " + "msecs: %lld, updateCount = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoUpdateLoop.getMillis(), updateCount); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chronoUpdateLoop.getMillis() > 0) + chronoUpdateLoop.start(); + + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER + " updateCount: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis(), updateCount); + perfList.push_back(perfBuf); + } + } + updateCount++; + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s] Line: %d AFTER programState->update took msecs: %lld " + "==============> MAIN LOOP BODY LOGIC, updateCount = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + chrono.getMillis(), updateCount); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (showPerfStats) { + sprintf(perfBuf, "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } + + if (prevState == this->programState) { + // fps timer chronoPerformanceCounts.start(); - while(updateCameraTimer.isTime()) { - programState->updateCamera(); - } - - programState->addPerformanceCount("programState->updateCamera()",chronoPerformanceCounts.getMillis()); - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d programState->render took msecs: %lld ==============> MAIN LOOP CAMERA UPDATING\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - //update world - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); - int updateCount = 0; - while(prevState == this->programState && updateTimer.isTime()) { - Chrono chronoUpdateLoop; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chronoUpdateLoop.start(); - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER " updateCount: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis(),updateCount); - perfList.push_back(perfBuf); - } - - GraphicComponent::update(); - programState->update(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chronoUpdateLoop.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] programState->update took msecs: %lld, updateCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoUpdateLoop.getMillis(),updateCount); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chronoUpdateLoop.getMillis() > 0) chronoUpdateLoop.start(); - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER " updateCount: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis(),updateCount); - perfList.push_back(perfBuf); - } - - if(prevState == this->programState) { - chronoPerformanceCounts.start(); - - if(soundThreadManager == NULL || soundThreadManager->isThreadExecutionLagging()) { - if(soundThreadManager != NULL) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d] ERROR / WARNING soundThreadManager->isThreadExecutionLagging is TRUE\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s %d] ERROR / WARNING soundThreadManager->isThreadExecutionLagging is TRUE\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - SoundRenderer::getInstance().update(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chronoUpdateLoop.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] SoundRenderer::getInstance().update() took msecs: %lld, updateCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoUpdateLoop.getMillis(),updateCount); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chronoUpdateLoop.getMillis() > 0) chronoUpdateLoop.start(); - } - - programState->addPerformanceCount("SoundRenderer::getInstance().update()",chronoPerformanceCounts.getMillis()); - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER " updateCount: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis(),updateCount); - perfList.push_back(perfBuf); - } - - chronoPerformanceCounts.start(); - - NetworkManager::getInstance().update(); - - programState->addPerformanceCount("NetworkManager::getInstance().update()",chronoPerformanceCounts.getMillis()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chronoUpdateLoop.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] NetworkManager::getInstance().update() took msecs: %lld, updateCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoUpdateLoop.getMillis(),updateCount); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chronoUpdateLoop.getMillis() > 0) chronoUpdateLoop.start(); - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER " updateCount: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis(),updateCount); - perfList.push_back(perfBuf); - } - - } - updateCount++; - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d AFTER programState->update took msecs: %lld ==============> MAIN LOOP BODY LOGIC, updateCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis(),updateCount); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - if(prevState == this->programState) { - //fps timer - chronoPerformanceCounts.start(); - - chrono.start(); - while(fpsTimer.isTime()) { - programState->tick(); - } - - programState->addPerformanceCount("programState->tick()",chronoPerformanceCounts.getMillis()); - - if(showPerfStats) { - sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis()); - perfList.push_back(perfBuf); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d programState->render took msecs: %lld ==============> MAIN LOOP TICKING\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d programState->render took msecs: %lld ==============> MAIN LOOP TICKING\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); + chrono.start(); + while (fpsTimer.isTime()) { + programState->tick(); + } - } + programState->addPerformanceCount("programState->tick()", + chronoPerformanceCounts.getMillis()); - if(showPerfStats && chronoPerf.getMillis() >= 100) { - for(unsigned int x = 0; x < perfList.size(); ++x) { - printf("%s",perfList[x].c_str()); - } - } + if (showPerfStats) { + sprintf(perfBuf, + "In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chronoPerf.getMillis()); + perfList.push_back(perfBuf); + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] ------------------------------- MAIN LOOP END, stats: loop took msecs: %lld -------------------------------\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoLoop.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s] Line: %d programState->render took msecs: %lld " + "==============> MAIN LOOP TICKING\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled && + // chrono.getMillis() > 0) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d + // programState->render took msecs: %lld ==============> MAIN LOOP + // TICKING\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + } + + if (showPerfStats && chronoPerf.getMillis() >= 100) { + for (unsigned int x = 0; x < perfList.size(); ++x) { + printf("%s", perfList[x].c_str()); + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] ------------------------------- MAIN LOOP END, " + "stats: loop took msecs: %lld -------------------------------\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + chronoLoop.getMillis()); } -void Program::resize(SizeState sizeState){ - - switch(sizeState){ - case ssMinimized: - //restoreVideoMode(); - break; - case ssMaximized: - case ssRestored: - //setDisplaySettings(); - //renderer.reloadResources(); - break; - } +void Program::resize(SizeState sizeState) { + + switch (sizeState) { + case ssMinimized: + // restoreVideoMode(); + break; + case ssMaximized: + case ssRestored: + // setDisplaySettings(); + // renderer.reloadResources(); + break; + } } // ==================== misc ==================== void Program::renderProgramMsgBox() { - Renderer &renderer= Renderer::getInstance(); - if(msgBox.getEnabled()) { - renderer.renderMessageBox(&msgBox); - } - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && window) { - MainWindow *mainWindow = dynamic_cast(window); - if(mainWindow) { - mainWindow->render(); - } - } - + Renderer &renderer = Renderer::getInstance(); + if (msgBox.getEnabled()) { + renderer.renderMessageBox(&msgBox); + } + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && window) { + MainWindow *mainWindow = dynamic_cast(window); + if (mainWindow) { + mainWindow->render(); + } + } } void Program::setState(ProgramState *programStateNew, bool cleanupOldState) { - try { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - this->programStateOldSystemError = this->programState; - bool msgBoxEnabled = msgBox.getEnabled(); - - if(dynamic_cast(programStateNew) != NULL) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - int X = 0; - int Y = 0; - SDL_GetMouseState(&X,&Y); - programStateNew->setStartXY(X,Y); - Logger::getInstance().setProgress(0); - Logger::getInstance().setState(""); - - - SDL_PumpEvents(); - - showCursor(true); - SDL_PumpEvents(); - sleep(0); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - - if(cleanupOldState == true) { - if(this->programState != programStateNew) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - this->programStateOldSystemError = NULL; - delete this->programState; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - this->programState = NULL; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //mesage box - Lang &lang= Lang::getInstance(); - msgBox.init(lang.getString("Ok")); - msgBox.setEnabled(msgBoxEnabled); - - fpsTimer.init(1, maxTimes); - updateTimer.init(GameConstants::updateFps, maxTimes); - updateCameraTimer.init(GameConstants::cameraFps, maxTimes); - - this->programState= programStateNew; - assert(programStateNew != NULL); - if(programStateNew == NULL) { - throw megaglest_runtime_error("programStateNew == NULL"); - } - programStateNew->load(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - programStateNew->init(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - updateTimer.reset(); - updateCameraTimer.reset(); - fpsTimer.reset(); - - Config &config = Config::getInstance(); - if(dynamic_cast(programStateNew) != NULL && msgBoxEnabled == true) { - showCursor(true); - } else { - showCursor(config.getBool("No2DMouseRendering","false")); - } - - this->programStateOldSystemError = NULL; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - catch(megaglest_runtime_error& e) { - //printf("3333333 ex.wantStackTrace() = %d\n",e.wantStackTrace()); - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d]\nError [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,szBuf); - //abort(); - //printf("44444444a ex.wantStackTrace() = %d\n",e.wantStackTrace()); - - messageBoxIsSystemError = true; - string errorMsg = e.what(); - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - if(dynamic_cast(programStateNew) != NULL) { - try { - Game *game = dynamic_cast(programStateNew); - Renderer &renderer= Renderer::getInstance(); - game->setQuitPendingIndicator();// by this the world is no more updated - renderer.initGame(game,game->getGameCameraPtr()); - } - catch(megaglest_runtime_error& ex2) { - errorMsg += "\n" + string(ex2.what()); - } - } - } - - //printf("44444444b ex.wantStackTrace() = %d\n",e.wantStackTrace()); - this->showMessage(errorMsg.c_str()); - //setState(new Intro(this)); - } - catch(const exception &e){ - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d]\nError [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,szBuf); - //abort(); - - messageBoxIsSystemError = true; - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - if(dynamic_cast(programStateNew) != NULL) { - Game *game = dynamic_cast(programStateNew); - Renderer &renderer= Renderer::getInstance(); - renderer.initGame(game,game->getGameCameraPtr()); - } - } - - this->showMessage(e.what()); - //setState(new Intro(this)); - } -} - -void Program::exit() { - window->destroy(); -} + try { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + this->programStateOldSystemError = this->programState; + bool msgBoxEnabled = msgBox.getEnabled(); + + if (dynamic_cast(programStateNew) != NULL) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + int X = 0; + int Y = 0; + SDL_GetMouseState(&X, &Y); + programStateNew->setStartXY(X, Y); + Logger::getInstance().setProgress(0); + Logger::getInstance().setState(""); + + SDL_PumpEvents(); + + showCursor(true); + SDL_PumpEvents(); + sleep(0); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + } -// ==================== PRIVATE ==================== + if (cleanupOldState == true) { + if (this->programState != programStateNew) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + this->programStateOldSystemError = NULL; + delete this->programState; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + this->programState = NULL; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } + } -void Program::initResolution() { - const Metrics &metrics = Metrics::getInstance(); - if(window->getScreenWidth() != metrics.getScreenW() || - window->getScreenHeight() != metrics.getScreenH()) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // mesage box + Lang &lang = Lang::getInstance(); + msgBox.init(lang.getString("Ok")); + msgBox.setEnabled(msgBoxEnabled); + + fpsTimer.init(1, maxTimes); + updateTimer.init(GameConstants::updateFps, maxTimes); + updateCameraTimer.init(GameConstants::cameraFps, maxTimes); + + this->programState = programStateNew; + assert(programStateNew != NULL); + if (programStateNew == NULL) { + throw megaglest_runtime_error("programStateNew == NULL"); + } + programStateNew->load(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + programStateNew->init(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + updateTimer.reset(); + updateCameraTimer.reset(); + fpsTimer.reset(); + + Config &config = Config::getInstance(); + if (dynamic_cast(programStateNew) != NULL && + msgBoxEnabled == true) { + showCursor(true); + } else { + showCursor(config.getBool("No2DMouseRendering", "false")); + } - int oldW = metrics.getScreenW(); - int oldH = metrics.getScreenH(); + this->programStateOldSystemError = NULL; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + } catch (megaglest_runtime_error &e) { + // printf("3333333 ex.wantStackTrace() = %d\n",e.wantStackTrace()); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d]\nError [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, e.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, szBuf); + // abort(); + // printf("44444444a ex.wantStackTrace() = %d\n",e.wantStackTrace()); + + messageBoxIsSystemError = true; + string errorMsg = e.what(); + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + if (dynamic_cast(programStateNew) != NULL) { + try { + Game *game = dynamic_cast(programStateNew); + Renderer &renderer = Renderer::getInstance(); + game->setQuitPendingIndicator(); // by this the world is no more + // updated + renderer.initGame(game, game->getGameCameraPtr()); + } catch (megaglest_runtime_error &ex2) { + errorMsg += "\n" + string(ex2.what()); + } + } + } - Config &config= Config::getInstance(); - config.setInt("ScreenWidth",window->getScreenWidth(),true); - config.setInt("ScreenHeight",window->getScreenHeight(),true); + // printf("44444444b ex.wantStackTrace() = %d\n",e.wantStackTrace()); + this->showMessage(errorMsg.c_str()); + // setState(new Intro(this)); + } catch (const exception &e) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d]\nError [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, e.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, szBuf); + // abort(); + + messageBoxIsSystemError = true; + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + if (dynamic_cast(programStateNew) != NULL) { + Game *game = dynamic_cast(programStateNew); + Renderer &renderer = Renderer::getInstance(); + renderer.initGame(game, game->getGameCameraPtr()); + } + } - metrics.reload(window->getScreenWidth(), window->getScreenHeight()); - printf("MainWindow forced change of resolution to desktop values (%d x %d) instead of (%d x %d)\n",metrics.getScreenW(), metrics.getScreenH(),oldW,oldH); - } + this->showMessage(e.what()); + // setState(new Intro(this)); + } } -void Program::init(WindowGl *window, bool initSound, bool toggleFullScreen){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - this->window= window; - Config &config= Config::getInstance(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void Program::exit() { window->destroy(); } - //set video mode - if(toggleFullScreen == false) { - setDisplaySettings(); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //window - //window->setText("MegaGlest"); - window->setStyle(config.getBool("Windowed")? wsWindowedFixed: wsFullscreen); - window->setPos(0, 0); - window->setSize(config.getInt("ScreenWidth"), config.getInt("ScreenHeight")); - window->create(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //timers - fpsTimer.init(1, maxTimes); - updateTimer.init(GameConstants::updateFps, maxTimes); - updateCameraTimer.init(GameConstants::cameraFps, maxTimes); +// ==================== PRIVATE ==================== - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void Program::initResolution() { + const Metrics &metrics = Metrics::getInstance(); + if (window->getScreenWidth() != metrics.getScreenW() || + window->getScreenHeight() != metrics.getScreenH()) { + + int oldW = metrics.getScreenW(); + int oldH = metrics.getScreenH(); + + Config &config = Config::getInstance(); + config.setInt("ScreenWidth", window->getScreenWidth(), true); + config.setInt("ScreenHeight", window->getScreenHeight(), true); + + metrics.reload(window->getScreenWidth(), window->getScreenHeight()); + printf("MainWindow forced change of resolution to desktop values (%d x %d) " + "instead of (%d x %d)\n", + metrics.getScreenW(), metrics.getScreenH(), oldW, oldH); + } +} - //log start - Logger &logger= Logger::getInstance(); - string logFile = "glest.log"; - if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - logFile = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + logFile; +void Program::init(WindowGl *window, bool initSound, bool toggleFullScreen) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + this->window = window; + Config &config = Config::getInstance(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // set video mode + if (toggleFullScreen == false) { + setDisplaySettings(); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // window + // window->setText("MegaGlest"); + window->setStyle(config.getBool("Windowed") ? wsWindowedFixed : wsFullscreen); + window->setPos(0, 0); + window->setSize(config.getInt("ScreenWidth"), config.getInt("ScreenHeight")); + window->create(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // timers + fpsTimer.init(1, maxTimes); + updateTimer.init(GameConstants::updateFps, maxTimes); + updateCameraTimer.init(GameConstants::cameraFps, maxTimes); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // log start + Logger &logger = Logger::getInstance(); + string logFile = "glest.log"; + if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { + logFile = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + logFile; + } else { + string userData = config.getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); } - else { - string userData = config.getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - logFile = userData + logFile; + logFile = userData + logFile; + } + logger.setFile(logFile); + logger.clear(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // lang + // Lang &lang= Lang::getInstance(); + Lang::getInstance(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // render + Renderer &renderer = Renderer::getInstance(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + window->initGl(config.getInt("ColorBits"), config.getInt("DepthBits"), + config.getInt("StencilBits"), + config.getBool("HardwareAcceleration", "false"), + config.getBool("FullScreenAntiAliasing", "false"), + config.getFloat("GammaValue", "0.0")); + window->setText(config.getString("WindowTitle", "MegaGlest")); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + window->makeCurrentGl(); + initResolution(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // coreData, needs renderer, but must load before renderer init + CoreData &coreData = CoreData::getInstance(); + coreData.load(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // init renderer (load global textures) + tryingRendererInit = true; + renderer.init(); + tryingRendererInit = false; + rendererInitOk = true; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // sound + if (initSound == true && toggleFullScreen == false) { + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + bool initOk = soundRenderer.init(window); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] initOk = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, initOk); + + // Test sound system failed + // initOk = false; + // END + + if (initOk == false) { + string sError = "Sound System could not be initialized!"; + this->showMessage(sError.c_str()); } - logger.setFile(logFile); - logger.clear(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //lang - //Lang &lang= Lang::getInstance(); - Lang::getInstance(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //render - Renderer &renderer= Renderer::getInstance(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - window->initGl(config.getInt("ColorBits"), - config.getInt("DepthBits"), - config.getInt("StencilBits"), - config.getBool("HardwareAcceleration","false"), - config.getBool("FullScreenAntiAliasing","false"), - config.getFloat("GammaValue","0.0")); - window->setText(config.getString("WindowTitle","MegaGlest")); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - window->makeCurrentGl(); - initResolution(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //coreData, needs renderer, but must load before renderer init - CoreData &coreData= CoreData::getInstance(); - coreData.load(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //init renderer (load global textures) - tryingRendererInit = true; - renderer.init(); - tryingRendererInit = false; - rendererInitOk = true; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //sound - if(initSound == true && toggleFullScreen == false) { - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - bool initOk = soundRenderer.init(window); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] initOk = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,initOk); - - // Test sound system failed - //initOk = false; - // END - - if(initOk == false) { - string sError = "Sound System could not be initialized!"; - this->showMessage(sError.c_str()); - } - - // Run sound streaming in a background thread if enabled - if(SoundRenderer::getInstance().runningThreaded() == true) { - if(BaseThread::shutdownAndWait(soundThreadManager) == true) { - delete soundThreadManager; - } - static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); - soundThreadManager = new SimpleTaskThread(&SoundRenderer::getInstance(),0,SOUND_THREAD_UPDATE_MILLISECONDS); - soundThreadManager->setUniqueID(mutexOwnerId); - soundThreadManager->start(); - } - } + // Run sound streaming in a background thread if enabled + if (SoundRenderer::getInstance().runningThreaded() == true) { + if (BaseThread::shutdownAndWait(soundThreadManager) == true) { + delete soundThreadManager; + } + static string mutexOwnerId = + string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + + intToStr(__LINE__); + soundThreadManager = new SimpleTaskThread( + &SoundRenderer::getInstance(), 0, SOUND_THREAD_UPDATE_MILLISECONDS); + soundThreadManager->setUniqueID(mutexOwnerId); + soundThreadManager->start(); + } + } - NetworkInterface::setAllowGameDataSynchCheck(Config::getInstance().getBool("AllowGameDataSynchCheck","false")); - NetworkInterface::setAllowDownloadDataSynch(Config::getInstance().getBool("AllowDownloadDataSynch","false")); + NetworkInterface::setAllowGameDataSynchCheck( + Config::getInstance().getBool("AllowGameDataSynchCheck", "false")); + NetworkInterface::setAllowDownloadDataSynch( + Config::getInstance().getBool("AllowDownloadDataSynch", "false")); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); } void Program::reloadUI() { - if(programState) { - programState->reloadUI(); - } + if (programState) { + programState->reloadUI(); + } } -void Program::setDisplaySettings(){ +void Program::setDisplaySettings() { - Config &config= Config::getInstance(); + Config &config = Config::getInstance(); - if(!config.getBool("Windowed")) { + if (!config.getBool("Windowed")) { - //int freq= config.getInt("RefreshFrequency"); - int colorBits= config.getInt("ColorBits"); - int screenWidth= config.getInt("ScreenWidth"); - int screenHeight= config.getInt("ScreenHeight"); + // int freq= config.getInt("RefreshFrequency"); + int colorBits = config.getInt("ColorBits"); + int screenWidth = config.getInt("ScreenWidth"); + int screenHeight = config.getInt("ScreenHeight"); - if(config.getBool("AutoMaxFullScreen","false") == true) { - getFullscreenVideoInfo(colorBits,screenWidth,screenHeight,!config.getBool("Windowed")); - config.setInt("ColorBits",colorBits); - config.setInt("ScreenWidth",screenWidth); - config.setInt("ScreenHeight",screenHeight); - } - } - changeVideoModeFullScreen(!config.getBool("Windowed")); + if (config.getBool("AutoMaxFullScreen", "false") == true) { + getFullscreenVideoInfo(colorBits, screenWidth, screenHeight, + !config.getBool("Windowed")); + config.setInt("ColorBits", colorBits); + config.setInt("ScreenWidth", screenWidth); + config.setInt("ScreenHeight", screenHeight); + } + } + changeVideoModeFullScreen(!config.getBool("Windowed")); } -void Program::restoreDisplaySettings(){ - Config &config= Config::getInstance(); +void Program::restoreDisplaySettings() { + Config &config = Config::getInstance(); - if(!config.getBool("Windowed")){ - restoreVideoMode(this->getWindow()->getSDLWindow()); - } + if (!config.getBool("Windowed")) { + restoreVideoMode(this->getWindow()->getSDLWindow()); + } } -bool Program::isMessageShowing() { - return msgBox.getEnabled(); -} +bool Program::isMessageShowing() { return msgBox.getEnabled(); } void Program::showMessage(const char *msg) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d] msg [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,msg); - - msgBox.setText(msg); - msgBox.setEnabled(true); - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - printf("Message:\n%s\n",msg); - - if(messageBoxIsSystemError == true) { - messageBoxIsSystemError = false; - //setState(new Intro(this)); - initServer(window,false,true,true); - } - } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s %d] msg [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, msg); + + msgBox.setText(msg); + msgBox.setEnabled(true); + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + printf("Message:\n%s\n", msg); + + if (messageBoxIsSystemError == true) { + messageBoxIsSystemError = false; + // setState(new Intro(this)); + initServer(window, false, true, true); + } + } } void Program::stopSoundSystem() { - if(soundThreadManager != NULL) { - BaseThread::shutdownAndWait(soundThreadManager); - delete soundThreadManager; - soundThreadManager = NULL; - } + if (soundThreadManager != NULL) { + BaseThread::shutdownAndWait(soundThreadManager); + delete soundThreadManager; + soundThreadManager = NULL; + } } void Program::startSoundSystem() { - stopSoundSystem(); - if(SoundRenderer::getInstance().runningThreaded() == true) { - static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); - soundThreadManager = new SimpleTaskThread(&SoundRenderer::getInstance(),0,SOUND_THREAD_UPDATE_MILLISECONDS); - soundThreadManager->setUniqueID(mutexOwnerId); - soundThreadManager->start(); - } + stopSoundSystem(); + if (SoundRenderer::getInstance().runningThreaded() == true) { + static string mutexOwnerId = + string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + + intToStr(__LINE__); + soundThreadManager = new SimpleTaskThread(&SoundRenderer::getInstance(), 0, + SOUND_THREAD_UPDATE_MILLISECONDS); + soundThreadManager->setUniqueID(mutexOwnerId); + soundThreadManager->start(); + } } -//void Program::resetSoundSystem() { +// void Program::resetSoundSystem() { // startSoundSystem(); -//} +// } -//void Program::reInitGl() { +// void Program::reInitGl() { // if(window != NULL) { // Config &config= Config::getInstance(); // window->initGl(config.getInt("ColorBits"), @@ -979,20 +1283,21 @@ void Program::startSoundSystem() { // window->setText(config.getString("WindowTitle","MegaGlest")); // initResolution(); // } -//} +// } void Program::consoleAddLine(string line) { - if(programState != NULL) { - programState->consoleAddLine(line); - } + if (programState != NULL) { + programState->consoleAddLine(line); + } } -SimpleTaskThread * Program::getSoundThreadManager(bool takeOwnership) { - SimpleTaskThread *result = soundThreadManager; - if(takeOwnership) { - soundThreadManager = NULL; - } - return result; +SimpleTaskThread *Program::getSoundThreadManager(bool takeOwnership) { + SimpleTaskThread *result = soundThreadManager; + if (takeOwnership) { + soundThreadManager = NULL; + } + return result; } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/main/program.h b/source/glest_game/main/program.h index 6f2720c17..b8aeadd1b 100644 --- a/source/glest_game/main/program.h +++ b/source/glest_game/main/program.h @@ -13,30 +13,31 @@ #define _GLEST_GAME_PROGRAM_H_ #ifdef WIN32 - #include - #include +#include +#include #endif +#include "components.h" #include "context.h" +#include "leak_dumper.h" #include "platform_util.h" -#include "window_gl.h" -#include "socket.h" -#include "components.h" -#include "window.h" #include "simple_threads.h" +#include "socket.h" #include "stats.h" -#include "leak_dumper.h" +#include "window.h" +#include "window_gl.h" -using Shared::Platform::MouseButton; using Shared::Graphics::Context; -using Shared::Platform::WindowGl; -using Shared::Platform::SizeState; +using Shared::Platform::Ip; +using Shared::Platform::MouseButton; using Shared::Platform::MouseState; +using Shared::Platform::SizeState; +using Shared::Platform::WindowGl; using Shared::PlatformCommon::PerformanceTimer; -using Shared::Platform::Ip; using namespace Shared::PlatformCommon; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { class Program; class MainWindow; @@ -51,69 +52,71 @@ class GameSettings; class ProgramState { protected: - Program *program; + Program *program; - int mouseX; - int mouseY; - int mouse2dAnim; + int mouseX; + int mouseY; + int mouse2dAnim; - int startX; - int startY; - bool forceMouseRender; + int startX; + int startY; + bool forceMouseRender; - int fps; - int lastFps; + int fps; + int lastFps; public: - - static const char *MAIN_PROGRAM_RENDER_KEY; - - explicit ProgramState(Program *program); - virtual ~ProgramState(){}; - - int getFps() const { return fps; } - int getLastFps() const { return lastFps; } - - //virtual void render()=0; - virtual bool canRender(bool sleepIfCannotRender=true); - virtual void render(); - virtual void update(); - virtual void updateCamera(){}; - virtual void tick(); - virtual void init(){}; - virtual void load(){}; - virtual void end(){}; - virtual void mouseDownLeft(int x, int y){}; - virtual void mouseUpLeft(int x, int y){}; - virtual void mouseUpRight(int x, int y){} - virtual void mouseUpCenter(int x, int y){} - virtual void mouseDownRight(int x, int y){}; - virtual void mouseDownCenter(int x, int y){} - virtual void mouseDoubleClickLeft(int x, int y){}; - virtual void mouseDoubleClickRight(int x, int y){} - virtual void mouseDoubleClickCenter(int x, int y){} - virtual void eventMouseWheel(int x, int y, int zDelta){} - virtual void mouseMove(int x, int y, const MouseState *mouseState); - virtual bool textInput(std::string text){ return false; }; - virtual void keyDown(SDL_KeyboardEvent key){}; - virtual bool sdlKeyDown(SDL_KeyboardEvent key){ return false; }; - virtual void keyUp(SDL_KeyboardEvent key){}; - virtual void keyPress(SDL_KeyboardEvent c){}; - virtual void setStartXY(int X,int Y) { startX=X; startY=Y; } - virtual void restoreToStartXY(); - virtual bool isInSpecialKeyCaptureEvent() { return false; } - virtual bool quitTriggered() { return false; } - virtual Stats quitAndToggleState() { return Stats(); }; - virtual Program * getProgram() { return program; } - virtual const Program * getProgramConstPtr() { return program; } - virtual void setForceMouseRender(bool value) { forceMouseRender=value;} - virtual void consoleAddLine(string line) { }; - - virtual void reloadUI() {}; - virtual void addPerformanceCount(string key,int64 value) {}; + static const char *MAIN_PROGRAM_RENDER_KEY; + + explicit ProgramState(Program *program); + virtual ~ProgramState(){}; + + int getFps() const { return fps; } + int getLastFps() const { return lastFps; } + + // virtual void render()=0; + virtual bool canRender(bool sleepIfCannotRender = true); + virtual void render(); + virtual void update(); + virtual void updateCamera(){}; + virtual void tick(); + virtual void init(){}; + virtual void load(){}; + virtual void end(){}; + virtual void mouseDownLeft(int x, int y){}; + virtual void mouseUpLeft(int x, int y){}; + virtual void mouseUpRight(int x, int y) {} + virtual void mouseUpCenter(int x, int y) {} + virtual void mouseDownRight(int x, int y){}; + virtual void mouseDownCenter(int x, int y) {} + virtual void mouseDoubleClickLeft(int x, int y){}; + virtual void mouseDoubleClickRight(int x, int y) {} + virtual void mouseDoubleClickCenter(int x, int y) {} + virtual void eventMouseWheel(int x, int y, int zDelta) {} + virtual void mouseMove(int x, int y, const MouseState *mouseState); + virtual bool textInput(std::string text) { return false; }; + virtual void keyDown(SDL_KeyboardEvent key){}; + virtual bool sdlKeyDown(SDL_KeyboardEvent key) { return false; }; + virtual void keyUp(SDL_KeyboardEvent key){}; + virtual void keyPress(SDL_KeyboardEvent c){}; + virtual void setStartXY(int X, int Y) { + startX = X; + startY = Y; + } + virtual void restoreToStartXY(); + virtual bool isInSpecialKeyCaptureEvent() { return false; } + virtual bool quitTriggered() { return false; } + virtual Stats quitAndToggleState() { return Stats(); }; + virtual Program *getProgram() { return program; } + virtual const Program *getProgramConstPtr() { return program; } + virtual void setForceMouseRender(bool value) { forceMouseRender = value; } + virtual void consoleAddLine(string line){}; + + virtual void reloadUI(){}; + virtual void addPerformanceCount(string key, int64 value){}; protected: - virtual void incrementFps(); + virtual void incrementFps(); }; // =============================== @@ -122,124 +125,136 @@ class ProgramState { class Program { private: - static const int maxTimes; - SimpleTaskThread *soundThreadManager; - - class ShowMessageProgramState : public ProgramState { - GraphicMessageBox msgBox; - int mouseX; - int mouseY; - int mouse2dAnim; - string msg; - bool userWantsExit; - - public: - ShowMessageProgramState(Program *program, const char *msg); - - virtual void render(); - virtual void mouseDownLeft(int x, int y); - virtual void mouseMove(int x, int y, const MouseState &mouseState); - virtual void keyPress(SDL_KeyboardEvent c); - virtual void update(); - virtual bool wantExit() { return userWantsExit; } - }; + static const int maxTimes; + SimpleTaskThread *soundThreadManager; + class ShowMessageProgramState : public ProgramState { + GraphicMessageBox msgBox; + int mouseX; + int mouseY; + int mouse2dAnim; + string msg; + bool userWantsExit; + + public: + ShowMessageProgramState(Program *program, const char *msg); + + virtual void render(); + virtual void mouseDownLeft(int x, int y); + virtual void mouseMove(int x, int y, const MouseState &mouseState); + virtual void keyPress(SDL_KeyboardEvent c); + virtual void update(); + virtual bool wantExit() { return userWantsExit; } + }; private: - ProgramState *programState; + ProgramState *programState; - PerformanceTimer fpsTimer; - PerformanceTimer updateTimer; - PerformanceTimer updateCameraTimer; + PerformanceTimer fpsTimer; + PerformanceTimer updateTimer; + PerformanceTimer updateCameraTimer; - WindowGl *window; - static Program *singleton; + WindowGl *window; + static Program *singleton; - GraphicMessageBox msgBox; - int skipRenderFrameCount; + GraphicMessageBox msgBox; + int skipRenderFrameCount; - bool messageBoxIsSystemError; - ProgramState *programStateOldSystemError; + bool messageBoxIsSystemError; + ProgramState *programStateOldSystemError; - //bool masterserverMode; - bool shutdownApplicationEnabled; - static bool wantShutdownApplicationAfterGame; + // bool masterserverMode; + bool shutdownApplicationEnabled; + static bool wantShutdownApplicationAfterGame; - static bool tryingRendererInit; - static bool rendererInitOk; + static bool tryingRendererInit; + static bool rendererInitOk; public: - Program(); - virtual ~Program(); - - static bool getTryingRendererInit() { return tryingRendererInit; } - static bool getRendererInitOk() { return rendererInitOk; } - - static Program *getInstance() { return singleton; } - - static void setWantShutdownApplicationAfterGame(bool value) { wantShutdownApplicationAfterGame = value; } - static bool getWantShutdownApplicationAfterGame() { return wantShutdownApplicationAfterGame; } - - //bool isMasterserverMode() const; - bool isShutdownApplicationEnabled() const { return shutdownApplicationEnabled; } - void setShutdownApplicationEnabled(bool value) { shutdownApplicationEnabled = value; } - - GraphicMessageBox * getMsgBox() { return &msgBox; } - void initNormal(WindowGl *window); - void initServer(WindowGl *window,bool autostart=false,bool openNetworkSlots=false,bool masterserverMode=false); - void initServer(WindowGl *window, GameSettings *settings); - void initSavedGame(WindowGl *window,bool masterserverMode=false,string saveGameFile=""); - void initClient(WindowGl *window, const Ip &serverIp,int portNumber=-1); - void initClientAutoFindHost(WindowGl *window); - void initScenario(WindowGl *window, string autoloadScenarioName); - - //main - bool textInput(std::string text); - void keyDown(SDL_KeyboardEvent key); - bool sdlKeyDown(SDL_KeyboardEvent key); - void keyUp(SDL_KeyboardEvent key); - void keyPress(SDL_KeyboardEvent c); - - void loop(); - void loopWorker(); - void resize(SizeState sizeState); - void showMessage(const char *msg); - bool isMessageShowing(); - - //misc - void setState(ProgramState *programStateNew,bool cleanupOldState=true); - ProgramState * getState() { return programState;} - WindowGl * getWindow() { return window; } - const WindowGl * getWindowConstPtr() const { return window; } - void init(WindowGl *window, bool initSound=true, bool toggleFullScreen=false); - void exit(); - - virtual void simpleTask(BaseThread *callingThread,void *userdata); - - void mouseDownLeft(int x, int y); - void eventMouseMove(int x, int y, const MouseState *ms); - - void renderProgramMsgBox(); - bool isInSpecialKeyCaptureEvent() { return programState->isInSpecialKeyCaptureEvent(); } - - //void reInitGl(); - //void resetSoundSystem(); - void stopSoundSystem(); - void startSoundSystem(); - - virtual void consoleAddLine(string line); - - virtual SimpleTaskThread * getSoundThreadManager(bool takeOwnership); - virtual void reloadUI(); + Program(); + virtual ~Program(); + + static bool getTryingRendererInit() { return tryingRendererInit; } + static bool getRendererInitOk() { return rendererInitOk; } + + static Program *getInstance() { return singleton; } + + static void setWantShutdownApplicationAfterGame(bool value) { + wantShutdownApplicationAfterGame = value; + } + static bool getWantShutdownApplicationAfterGame() { + return wantShutdownApplicationAfterGame; + } + + // bool isMasterserverMode() const; + bool isShutdownApplicationEnabled() const { + return shutdownApplicationEnabled; + } + void setShutdownApplicationEnabled(bool value) { + shutdownApplicationEnabled = value; + } + + GraphicMessageBox *getMsgBox() { return &msgBox; } + void initNormal(WindowGl *window); + void initServer(WindowGl *window, bool autostart = false, + bool openNetworkSlots = false, bool masterserverMode = false); + void initServer(WindowGl *window, GameSettings *settings); + void initSavedGame(WindowGl *window, bool masterserverMode = false, + string saveGameFile = ""); + void initClient(WindowGl *window, const Ip &serverIp, int portNumber = -1); + void initClientAutoFindHost(WindowGl *window); + void initScenario(WindowGl *window, string autoloadScenarioName); + + // main + bool textInput(std::string text); + void keyDown(SDL_KeyboardEvent key); + bool sdlKeyDown(SDL_KeyboardEvent key); + void keyUp(SDL_KeyboardEvent key); + void keyPress(SDL_KeyboardEvent c); + + void loop(); + void loopWorker(); + void resize(SizeState sizeState); + void showMessage(const char *msg); + bool isMessageShowing(); + + // misc + void setState(ProgramState *programStateNew, bool cleanupOldState = true); + ProgramState *getState() { return programState; } + WindowGl *getWindow() { return window; } + const WindowGl *getWindowConstPtr() const { return window; } + void init(WindowGl *window, bool initSound = true, + bool toggleFullScreen = false); + void exit(); + + virtual void simpleTask(BaseThread *callingThread, void *userdata); + + void mouseDownLeft(int x, int y); + void eventMouseMove(int x, int y, const MouseState *ms); + + void renderProgramMsgBox(); + bool isInSpecialKeyCaptureEvent() { + return programState->isInSpecialKeyCaptureEvent(); + } + + // void reInitGl(); + // void resetSoundSystem(); + void stopSoundSystem(); + void startSoundSystem(); + + virtual void consoleAddLine(string line); + + virtual SimpleTaskThread *getSoundThreadManager(bool takeOwnership); + virtual void reloadUI(); private: - - void setDisplaySettings(); - void restoreDisplaySettings(); - void restoreStateFromSystemError(); - void initResolution(); + void setDisplaySettings(); + void restoreDisplaySettings(); + void restoreStateFromSystemError(); + void initResolution(); }; -}} //end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/menu/main_menu.cpp b/source/glest_game/menu/main_menu.cpp index e965b7e57..39608c231 100644 --- a/source/glest_game/menu/main_menu.cpp +++ b/source/glest_game/menu/main_menu.cpp @@ -11,23 +11,23 @@ #include "main_menu.h" -#include "renderer.h" -#include "sound.h" #include "config.h" -#include "program.h" -#include "game_util.h" -#include "game.h" -#include "platform_util.h" -#include "sound_renderer.h" #include "core_data.h" #include "faction.h" +#include "game.h" +#include "game_util.h" +#include "menu_state_root.h" #include "metrics.h" #include "network_manager.h" #include "network_message.h" +#include "platform_util.h" +#include "program.h" +#include "renderer.h" #include "socket.h" -#include "menu_state_root.h" -#include "video_player.h" +#include "sound.h" +#include "sound_renderer.h" #include "string_utils.h" +#include "video_player.h" #include "leak_dumper.h" @@ -35,498 +35,538 @@ using namespace Shared::Sound; using namespace Shared::Platform; using namespace Shared::Util; using namespace Shared::Graphics; -using namespace Shared::Xml; +using namespace Shared::Xml; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class MainMenu // ===================================================== // ===================== PUBLIC ======================== -MenuState * MainMenu::oldstate=NULL; +MenuState *MainMenu::oldstate = NULL; -MainMenu::MainMenu(Program *program) : ProgramState(program), menuBackgroundVideo(NULL) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); +MainMenu::MainMenu(Program *program) + : ProgramState(program), menuBackgroundVideo(NULL) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); - //printf("In MainMenu::MainMenu()\n"); + // printf("In MainMenu::MainMenu()\n"); - mouseX=100; - mouseY=100; + mouseX = 100; + mouseY = 100; - state= NULL; - this->program= program; + state = NULL; + this->program = program; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); - Config &config = Config::getInstance(); - if(config.getString("CustomMenuTextColor","") != "") { - string customMenuTextColor = config.getString("CustomMenuTextColor"); - Vec3f customTextColor = Vec3f::strToVec3(customMenuTextColor); - GraphicComponent::setCustomTextColor(customTextColor); - } + Config &config = Config::getInstance(); + if (config.getString("CustomMenuTextColor", "") != "") { + string customMenuTextColor = config.getString("CustomMenuTextColor"); + Vec3f customTextColor = Vec3f::strToVec3(customMenuTextColor); + GraphicComponent::setCustomTextColor(customTextColor); + } - setState(new MenuStateRoot(program, this)); + setState(new MenuStateRoot(program, this)); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); } void MainMenu::reloadUI() { - if(state) { - state->reloadUI(); - } + if (state) { + state->reloadUI(); + } } MainMenu::~MainMenu() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); - - //printf("In MainMenu::~MainMenu()\n"); - - if(menuBackgroundVideo != NULL) { - menuBackgroundVideo->closePlayer(); - delete menuBackgroundVideo; - menuBackgroundVideo = NULL; - } - delete state; - state = NULL; - delete oldstate; - oldstate = NULL; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); - - Renderer::getInstance().endMenu(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); - - //SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - //soundRenderer.stopAllSounds(); - GraphicComponent::setCustomTextColor(Vec3f(1.0f,1.0f,1.0f)); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + // printf("In MainMenu::~MainMenu()\n"); + + if (menuBackgroundVideo != NULL) { + menuBackgroundVideo->closePlayer(); + delete menuBackgroundVideo; + menuBackgroundVideo = NULL; + } + delete state; + state = NULL; + delete oldstate; + oldstate = NULL; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + Renderer::getInstance().endMenu(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + // SoundRenderer &soundRenderer= SoundRenderer::getInstance(); + // soundRenderer.stopAllSounds(); + GraphicComponent::setCustomTextColor(Vec3f(1.0f, 1.0f, 1.0f)); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); } void MainMenu::init() { - Renderer::getInstance().initMenu(this); + Renderer::getInstance().initMenu(this); - initBackgroundVideo(); + initBackgroundVideo(); } void MainMenu::initBackgroundVideo() { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && - ::Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == true && - CoreData::getInstance().hasMainMenuVideoFilename() == true) { - string introVideoFile = CoreData::getInstance().getMainMenuVideoFilename(); - string introVideoFileFallback = CoreData::getInstance().getMainMenuVideoFilenameFallback(); - - Context *c= GraphicsInterface::getInstance().getCurrentContext(); - PlatformContextGl *glCtx = static_cast(c)->getPlatformContextGlPtr(); - SDL_Window *window = glCtx->getScreenWindow(); - SDL_Surface *screen = glCtx->getScreenSurface(); - - string vlcPluginsPath = Config::getInstance().getString("VideoPlayerPluginsPath",""); - //printf("screen->w = %d screen->h = %d screen->format->BitsPerPixel = %d\n",screen->w,screen->h,screen->format->BitsPerPixel); - menuBackgroundVideo = new VideoPlayer( - &Renderer::getInstance(), - introVideoFile, - introVideoFileFallback, - window, - 0,0, - screen->w, - screen->h, - screen->format->BitsPerPixel, - true, - vlcPluginsPath, - SystemFlags::VERBOSE_MODE_ENABLED); - menuBackgroundVideo->initPlayer(); - } + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && + ::Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == true && + CoreData::getInstance().hasMainMenuVideoFilename() == true) { + string introVideoFile = CoreData::getInstance().getMainMenuVideoFilename(); + string introVideoFileFallback = + CoreData::getInstance().getMainMenuVideoFilenameFallback(); + + Context *c = GraphicsInterface::getInstance().getCurrentContext(); + PlatformContextGl *glCtx = + static_cast(c)->getPlatformContextGlPtr(); + SDL_Window *window = glCtx->getScreenWindow(); + SDL_Surface *screen = glCtx->getScreenSurface(); + + string vlcPluginsPath = + Config::getInstance().getString("VideoPlayerPluginsPath", ""); + // printf("screen->w = %d screen->h = %d screen->format->BitsPerPixel = + // %d\n",screen->w,screen->h,screen->format->BitsPerPixel); + menuBackgroundVideo = new VideoPlayer( + &Renderer::getInstance(), introVideoFile, introVideoFileFallback, + window, 0, 0, screen->w, screen->h, screen->format->BitsPerPixel, true, + vlcPluginsPath, SystemFlags::VERBOSE_MODE_ENABLED); + menuBackgroundVideo->initPlayer(); + } } -//asynchronus render update +// asynchronus render update void MainMenu::render() { - Renderer &renderer= Renderer::getInstance(); - - canRender(); - incrementFps(); - - if(state->isMasterserverMode() == false) { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - - if(state->isVideoPlaying() == true) { - if(menuBackgroundVideo != NULL) { - if(menuBackgroundVideo->isPlaying() == true) { - menuBackgroundVideo->closePlayer(); - delete menuBackgroundVideo; - menuBackgroundVideo = NULL; - } - } - } - else if(menuBackgroundVideo == NULL) { - initBackgroundVideo(); - } - renderer.clearBuffers(); - - //3d - renderer.reset3dMenu(); - renderer.clearZBuffer(); - - //printf("In [%s::%s Line: %d] menuBackgroundVideo [%p]\n",__FILE__,__FUNCTION__,__LINE__,menuBackgroundVideo); - - if(menuBackgroundVideo == NULL) { - renderer.loadCameraMatrix(menuBackground.getCamera()); - renderer.renderMenuBackground(&menuBackground); - renderer.renderParticleManager(rsMenu); - } - - //2d - renderer.reset2d(); - - if(menuBackgroundVideo != NULL) { - if(menuBackgroundVideo->isPlaying() == true) { - menuBackgroundVideo->playFrame(false); - } - else { - menuBackgroundVideo->RestartVideo(); - } - } - } - state->render(); - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - renderer.renderMouse2d(mouseX, mouseY, mouse2dAnim); - renderer.renderFPSWhenEnabled(lastFps); - renderer.swapBuffers(); - } - } + Renderer &renderer = Renderer::getInstance(); + + canRender(); + incrementFps(); + + if (state->isMasterserverMode() == false) { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + + if (state->isVideoPlaying() == true) { + if (menuBackgroundVideo != NULL) { + if (menuBackgroundVideo->isPlaying() == true) { + menuBackgroundVideo->closePlayer(); + delete menuBackgroundVideo; + menuBackgroundVideo = NULL; + } + } + } else if (menuBackgroundVideo == NULL) { + initBackgroundVideo(); + } + renderer.clearBuffers(); + + // 3d + renderer.reset3dMenu(); + renderer.clearZBuffer(); + + // printf("In [%s::%s Line: %d] menuBackgroundVideo + // [%p]\n",__FILE__,__FUNCTION__,__LINE__,menuBackgroundVideo); + + if (menuBackgroundVideo == NULL) { + renderer.loadCameraMatrix(menuBackground.getCamera()); + renderer.renderMenuBackground(&menuBackground); + renderer.renderParticleManager(rsMenu); + } + + // 2d + renderer.reset2d(); + + if (menuBackgroundVideo != NULL) { + if (menuBackgroundVideo->isPlaying() == true) { + menuBackgroundVideo->playFrame(false); + } else { + menuBackgroundVideo->RestartVideo(); + } + } + } + state->render(); + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + renderer.renderMouse2d(mouseX, mouseY, mouse2dAnim); + renderer.renderFPSWhenEnabled(lastFps); + renderer.swapBuffers(); + } + } } -//syncronus update -void MainMenu::update(){ - if(menuBackgroundVideo == NULL) { - Renderer::getInstance().updateParticleManager(rsMenu); - } - mouse2dAnim= (mouse2dAnim +1) % Renderer::maxMouse2dAnim; - if(menuBackgroundVideo == NULL) { - menuBackground.update(); - } - state->update(); +// syncronus update +void MainMenu::update() { + if (menuBackgroundVideo == NULL) { + Renderer::getInstance().updateParticleManager(rsMenu); + } + mouse2dAnim = (mouse2dAnim + 1) % Renderer::maxMouse2dAnim; + if (menuBackgroundVideo == NULL) { + menuBackground.update(); + } + state->update(); } -//event magangement: mouse click -void MainMenu::mouseMove(int x, int y, const MouseState *ms){ - mouseX= x; mouseY= y; - state->mouseMove(x, y, ms); +// event magangement: mouse click +void MainMenu::mouseMove(int x, int y, const MouseState *ms) { + mouseX = x; + mouseY = y; + state->mouseMove(x, y, ms); } -void MainMenu::eventMouseWheel(int x, int y,int zDelta){ - state->eventMouseWheel(x, y, zDelta); +void MainMenu::eventMouseWheel(int x, int y, int zDelta) { + state->eventMouseWheel(x, y, zDelta); } -//returns if exiting -void MainMenu::mouseDownLeft(int x, int y){ - if(GraphicComponent::getFade()<0.2f) return; - state->mouseClick(x, y, mbLeft); +// returns if exiting +void MainMenu::mouseDownLeft(int x, int y) { + if (GraphicComponent::getFade() < 0.2f) + return; + state->mouseClick(x, y, mbLeft); } -void MainMenu::mouseDoubleClickLeft(int x, int y){ - if(GraphicComponent::getFade()<0.2f) return; - state->mouseDoubleClick(x, y, mbLeft); +void MainMenu::mouseDoubleClickLeft(int x, int y) { + if (GraphicComponent::getFade() < 0.2f) + return; + state->mouseDoubleClick(x, y, mbLeft); } -void MainMenu::mouseDoubleClickRight(int x, int y){ - if(GraphicComponent::getFade()<0.2f) return; - state->mouseDoubleClick(x, y, mbRight); +void MainMenu::mouseDoubleClickRight(int x, int y) { + if (GraphicComponent::getFade() < 0.2f) + return; + state->mouseDoubleClick(x, y, mbRight); } -void MainMenu::mouseDownRight(int x, int y){ - if(GraphicComponent::getFade()<0.2f) return; - state->mouseClick(x, y, mbRight); +void MainMenu::mouseDownRight(int x, int y) { + if (GraphicComponent::getFade() < 0.2f) + return; + state->mouseClick(x, y, mbRight); } -void MainMenu::mouseUpLeft(int x, int y){ - if(GraphicComponent::getFade()<0.2f) return; - state->mouseUp(x, y, mbLeft); +void MainMenu::mouseUpLeft(int x, int y) { + if (GraphicComponent::getFade() < 0.2f) + return; + state->mouseUp(x, y, mbLeft); } -bool MainMenu::textInput(std::string text) { - return state->textInput(text); -} -void MainMenu::keyDown(SDL_KeyboardEvent key) { - state->keyDown(key); -} +bool MainMenu::textInput(std::string text) { return state->textInput(text); } +void MainMenu::keyDown(SDL_KeyboardEvent key) { state->keyDown(key); } -void MainMenu::keyUp(SDL_KeyboardEvent key) { - state->keyUp(key); -} +void MainMenu::keyUp(SDL_KeyboardEvent key) { state->keyUp(key); } -void MainMenu::keyPress(SDL_KeyboardEvent c) { - state->keyPress(c); -} +void MainMenu::keyPress(SDL_KeyboardEvent c) { state->keyPress(c); } void MainMenu::setState(MenuState *newstate) { - //printf("In [%s::%s Line: %d] oldstate [%p] newstate [%p] this->state [%p]\n",__FILE__,__FUNCTION__,__LINE__,oldstate,newstate,this->state); - - //printf("In MainMenu::setState() #1\n"); - - if(oldstate != NULL && oldstate != newstate) { - MenuState *oldstatePtr = oldstate; - delete oldstate; - - //printf("In MainMenu::setState() #2\n"); - - //printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(oldstatePtr != this->state) { - oldstate=this->state; - //printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - //printf("In MainMenu::setState() #3\n"); - } - else { - oldstate = NULL; - //printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - //printf("In MainMenu::setState() #4\n"); - } - } - else { - oldstate=this->state; - //printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - //printf("In MainMenu::setState() #5\n"); - } - - if(this->state != NULL) { - - } - - //printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - this->state= newstate; - - GraphicComponent::resetFade(); - if(newstate) { - menuBackground.setTargetCamera(newstate->getCamera()); - } + // printf("In [%s::%s Line: %d] oldstate [%p] newstate [%p] this->state + // [%p]\n",__FILE__,__FUNCTION__,__LINE__,oldstate,newstate,this->state); + + // printf("In MainMenu::setState() #1\n"); + + if (oldstate != NULL && oldstate != newstate) { + MenuState *oldstatePtr = oldstate; + delete oldstate; + + // printf("In MainMenu::setState() #2\n"); + + // printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (oldstatePtr != this->state) { + oldstate = this->state; + // printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + // printf("In MainMenu::setState() #3\n"); + } else { + oldstate = NULL; + // printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + // printf("In MainMenu::setState() #4\n"); + } + } else { + oldstate = this->state; + // printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + // printf("In MainMenu::setState() #5\n"); + } + + if (this->state != NULL) { + } + + // printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + this->state = newstate; + + GraphicComponent::resetFade(); + if (newstate) { + menuBackground.setTargetCamera(newstate->getCamera()); + } } bool MainMenu::isInSpecialKeyCaptureEvent() { - return state->isInSpecialKeyCaptureEvent(); + return state->isInSpecialKeyCaptureEvent(); } void MainMenu::consoleAddLine(string line) { - if(state != NULL) { - state->consoleAddLine(line); - } + if (state != NULL) { + state->consoleAddLine(line); + } } // ===================================================== // class MenuState // ===================================================== -MenuState::MenuState(Program *program, MainMenu *mainMenu, const string &stateName) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); - this->containerName = "MenuState"; - this->program= program; - this->mainMenu= mainMenu; - console.registerGraphicComponent(containerName, "menuStateConsole"); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); - //switch on menu music again, it might be muted - Config &config = Config::getInstance(); - float configVolume = (config.getInt("SoundVolumeMusic") / 100.f); - CoreData::getInstance().getMenuMusic()->setVolume(configVolume); - - string data_path = getGameReadWritePath(GameConstants::path_data_CacheLookupKey); - - //camera - XmlTree xmlTree; - xmlTree.load(getGameCustomCoreDataPath(data_path, "data/core/menu/menu.xml"),Properties::getTagReplacementValues()); - const XmlNode *menuNode= xmlTree.getRootNode(); - const XmlNode *cameraNode= menuNode->getChild("camera"); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); - - //position - const XmlNode *positionNode= cameraNode->getChild(stateName + "-position"); - Vec3f startPosition; - startPosition.x= positionNode->getAttribute("x")->getFloatValue(); - startPosition.y= positionNode->getAttribute("y")->getFloatValue(); - startPosition.z= positionNode->getAttribute("z")->getFloatValue(); - camera.setPosition(startPosition); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); - - //rotation - const XmlNode *rotationNode= cameraNode->getChild(stateName + "-rotation"); - Vec3f startRotation; - startRotation.x= rotationNode->getAttribute("x")->getFloatValue(); - startRotation.y= rotationNode->getAttribute("y")->getFloatValue(); - startRotation.z= rotationNode->getAttribute("z")->getFloatValue(); - camera.setOrientation(Quaternion(EulerAngles( - degToRad(startRotation.x), - degToRad(startRotation.y), - degToRad(startRotation.z)))); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); +MenuState::MenuState(Program *program, MainMenu *mainMenu, + const string &stateName) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); + this->containerName = "MenuState"; + this->program = program; + this->mainMenu = mainMenu; + console.registerGraphicComponent(containerName, "menuStateConsole"); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); + // switch on menu music again, it might be muted + Config &config = Config::getInstance(); + float configVolume = (config.getInt("SoundVolumeMusic") / 100.f); + CoreData::getInstance().getMenuMusic()->setVolume(configVolume); + + string data_path = + getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + + // camera + XmlTree xmlTree; + xmlTree.load(getGameCustomCoreDataPath(data_path, "data/core/menu/menu.xml"), + Properties::getTagReplacementValues()); + const XmlNode *menuNode = xmlTree.getRootNode(); + const XmlNode *cameraNode = menuNode->getChild("camera"); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + // position + const XmlNode *positionNode = cameraNode->getChild(stateName + "-position"); + Vec3f startPosition; + startPosition.x = positionNode->getAttribute("x")->getFloatValue(); + startPosition.y = positionNode->getAttribute("y")->getFloatValue(); + startPosition.z = positionNode->getAttribute("z")->getFloatValue(); + camera.setPosition(startPosition); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + // rotation + const XmlNode *rotationNode = cameraNode->getChild(stateName + "-rotation"); + Vec3f startRotation; + startRotation.x = rotationNode->getAttribute("x")->getFloatValue(); + startRotation.y = rotationNode->getAttribute("y")->getFloatValue(); + startRotation.z = rotationNode->getAttribute("z")->getFloatValue(); + camera.setOrientation(Quaternion(EulerAngles(degToRad(startRotation.x), + degToRad(startRotation.y), + degToRad(startRotation.z)))); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); } MenuState::~MenuState() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); - GraphicComponent::clearRegisteredComponents(this->containerName); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); + GraphicComponent::clearRegisteredComponents(this->containerName); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); } void MenuState::consoleAddLine(string line) { - bool onlyWantChatMsgs = console.getOnlyChatMessagesInStoredLines(); - if(onlyWantChatMsgs == true) { - console.setOnlyChatMessagesInStoredLines(false); - } - console.addLine(line); - if(onlyWantChatMsgs == true) { - console.setOnlyChatMessagesInStoredLines(true); - } + bool onlyWantChatMsgs = console.getOnlyChatMessagesInStoredLines(); + if (onlyWantChatMsgs == true) { + console.setOnlyChatMessagesInStoredLines(false); + } + console.addLine(line); + if (onlyWantChatMsgs == true) { + console.setOnlyChatMessagesInStoredLines(true); + } } void MenuState::reloadUI() { - //console.resetFonts(); + // console.resetFonts(); } -void MenuState::setActiveInputLabel(GraphicLabel *newLabel, GraphicLabel **activeInputLabelPtr) { - GraphicLabel *activeInputLabelEdit = *activeInputLabelPtr; - if(newLabel != NULL) { - if(newLabel == activeInputLabelEdit) { - return; - } - string text= newLabel->getText(); - size_t found = text.find_last_of("_"); - if (found == string::npos || found != text.length()-1) { - text += "_"; - } - newLabel->setText(text); - //textCharLength = extractKeyPressedUnicodeLength(text); - newLabel->setTextCharLengthList(extractKeyPressedUnicodeLength(text)); - } - if(activeInputLabelEdit != NULL && activeInputLabelEdit->getText().empty() == false) { - string text= activeInputLabelEdit->getText(); - size_t found = text.find_last_of("_"); - if (found != string::npos && found == text.length()-1) { - //printf("Removing trailing edit char, found = %d [%d][%s]\n",found,text.length(),text.c_str()); - text = text.substr(0,found); - } - activeInputLabelEdit->setText(text); - //textCharLength = extractKeyPressedUnicodeLength(text); - activeInputLabelEdit->setTextCharLengthList(extractKeyPressedUnicodeLength(text)); - activeInputLabelEdit->setEditModeEnabled(false); - } - if(newLabel != NULL) { - *activeInputLabelPtr = newLabel; - newLabel->setEditModeEnabled(true); - } - else { - *activeInputLabelPtr = NULL; - } +void MenuState::setActiveInputLabel(GraphicLabel *newLabel, + GraphicLabel **activeInputLabelPtr) { + GraphicLabel *activeInputLabelEdit = *activeInputLabelPtr; + if (newLabel != NULL) { + if (newLabel == activeInputLabelEdit) { + return; + } + string text = newLabel->getText(); + size_t found = text.find_last_of("_"); + if (found == string::npos || found != text.length() - 1) { + text += "_"; + } + newLabel->setText(text); + // textCharLength = extractKeyPressedUnicodeLength(text); + newLabel->setTextCharLengthList(extractKeyPressedUnicodeLength(text)); + } + if (activeInputLabelEdit != NULL && + activeInputLabelEdit->getText().empty() == false) { + string text = activeInputLabelEdit->getText(); + size_t found = text.find_last_of("_"); + if (found != string::npos && found == text.length() - 1) { + // printf("Removing trailing edit char, found = %d + // [%d][%s]\n",found,text.length(),text.c_str()); + text = text.substr(0, found); + } + activeInputLabelEdit->setText(text); + // textCharLength = extractKeyPressedUnicodeLength(text); + activeInputLabelEdit->setTextCharLengthList( + extractKeyPressedUnicodeLength(text)); + activeInputLabelEdit->setEditModeEnabled(false); + } + if (newLabel != NULL) { + *activeInputLabelPtr = newLabel; + newLabel->setEditModeEnabled(true); + } else { + *activeInputLabelPtr = NULL; + } } - -bool MenuState::keyPressEditLabel(SDL_KeyboardEvent c, GraphicLabel **activeInputLabelPtr){ - if(isKeyPressed(SDLK_ESCAPE,c,false) == true || - isKeyPressed(SDLK_RETURN,c,false) == true ) { - GraphicLabel *activeInputLabel = *activeInputLabelPtr; - setActiveInputLabel(NULL,activeInputLabelPtr); - //textCharLength.clear(); - activeInputLabel->clearTextCharLengthList(); - return true; - } - return false; +bool MenuState::keyPressEditLabel(SDL_KeyboardEvent c, + GraphicLabel **activeInputLabelPtr) { + if (isKeyPressed(SDLK_ESCAPE, c, false) == true || + isKeyPressed(SDLK_RETURN, c, false) == true) { + GraphicLabel *activeInputLabel = *activeInputLabelPtr; + setActiveInputLabel(NULL, activeInputLabelPtr); + // textCharLength.clear(); + activeInputLabel->clearTextCharLengthList(); + return true; + } + return false; } -bool MenuState::textInputEditLabel(string input, GraphicLabel **activeInputLabelPtr) { - bool eventHandled = false; - GraphicLabel *activeInputLabel = *activeInputLabelPtr; - if(activeInputLabel != NULL) { - int maxTextSize= activeInputLabel->getMaxEditWidth(); - - //if((c>='0' && c<='9') || (c>='a' && c<='z') || (c>='A' && c<='Z') || - // (c=='-') || (c=='(') || (c==')')) { - //if(isAllowedInputTextKey(key)) - { - if((int)activeInputLabel->getTextCharLengthList().size() < maxTextSize) { - string text= activeInputLabel->getText(); - - if(text.size() > 0) { - size_t found = text.find_last_of("_"); - if (found == string::npos || found != text.length()-1) { - text += input; - activeInputLabel->addTextCharLengthToList(input.length()); - } - else { - text = text.substr(0,found) + input + "_"; - //int lastCharLen = activeInputLabel->getTextCharLengthList()[activeInputLabel->getTextCharLengthList().size()-1]; - activeInputLabel->deleteTextCharLengthFromList(); - activeInputLabel->addTextCharLengthToList(input.length()); - activeInputLabel->addTextCharLengthToList(1); - } - } - else { - text = input; - activeInputLabel->addTextCharLengthToList(input.length()); - } - //delete [] utfStr; - - activeInputLabel->setText(text); - - eventHandled = true; - } - } - } - return eventHandled; +bool MenuState::textInputEditLabel(string input, + GraphicLabel **activeInputLabelPtr) { + bool eventHandled = false; + GraphicLabel *activeInputLabel = *activeInputLabelPtr; + if (activeInputLabel != NULL) { + int maxTextSize = activeInputLabel->getMaxEditWidth(); + + // if((c>='0' && c<='9') || (c>='a' && c<='z') || (c>='A' && c<='Z') || + // (c=='-') || (c=='(') || (c==')')) { + // if(isAllowedInputTextKey(key)) + { + if ((int)activeInputLabel->getTextCharLengthList().size() < maxTextSize) { + string text = activeInputLabel->getText(); + + if (text.size() > 0) { + size_t found = text.find_last_of("_"); + if (found == string::npos || found != text.length() - 1) { + text += input; + activeInputLabel->addTextCharLengthToList(input.length()); + } else { + text = text.substr(0, found) + input + "_"; + // int lastCharLen = + // activeInputLabel->getTextCharLengthList()[activeInputLabel->getTextCharLengthList().size()-1]; + activeInputLabel->deleteTextCharLengthFromList(); + activeInputLabel->addTextCharLengthToList(input.length()); + activeInputLabel->addTextCharLengthToList(1); + } + } else { + text = input; + activeInputLabel->addTextCharLengthToList(input.length()); + } + // delete [] utfStr; + + activeInputLabel->setText(text); + + eventHandled = true; + } + } + } + return eventHandled; } -bool MenuState::keyDownEditLabel(SDL_KeyboardEvent c, GraphicLabel **activeInputLabelPtr) { - bool eventHandled = false; - GraphicLabel *activeInputLabel = *activeInputLabelPtr; - if(activeInputLabel != NULL) { - string text = activeInputLabel->getText(); - if(isKeyPressed(SDLK_BACKSPACE,c) == true && text.length() > 0) { - //printf("BSPACE text [%s]\n",text.c_str()); - - bool hasUnderscore = false; - bool delChar = false; - size_t found = text.find_last_of("_"); - if (found == string::npos || found != text.length()-1) { - //printf("A text.length() = %d textCharLength.size() = %d\n",text.length(),textCharLength.size()); - if(activeInputLabel->getTextCharLengthList()[activeInputLabel->getTextCharLengthList().size()-1] >= 1) { - delChar = true; - } - } - else { - //printf("B text.length() = %d textCharLength.size() = %d\n",text.length(),textCharLength.size()); - hasUnderscore = true; - if(activeInputLabel->getTextCharLengthList().size() >= 2 && activeInputLabel->getTextCharLengthList()[activeInputLabel->getTextCharLengthList().size()-2] >= 1) { - delChar = true; - } - } - if(delChar == true) { - if(hasUnderscore) { - //if(textCharLength.size() > 1) { - if(activeInputLabel->getTextCharLengthList().size() > 1) { - //printf("Underscore erase start\n"); - for(unsigned int i = 0; i < (unsigned int)activeInputLabel->getTextCharLengthList()[activeInputLabel->getTextCharLengthList().size()-2]; ++i) { - text.erase(text.end() -2); - } - //printf("AFTER DEL textCharLength.size() = %d textCharLength[textCharLength.size()-1] = %d text.length() = %d\n",textCharLength.size(),textCharLength[textCharLength.size()-1],text.length()); - activeInputLabel->deleteTextCharLengthFromList(); - activeInputLabel->deleteTextCharLengthFromList(); - activeInputLabel->addTextCharLengthToList(1); - } - } - else { - for(unsigned int i = 0; i < (unsigned int)activeInputLabel->getTextCharLengthList()[activeInputLabel->getTextCharLengthList().size()-1]; ++i) { - text.erase(text.end() -1); - } - activeInputLabel->deleteTextCharLengthFromList(); - } - } - activeInputLabel->setText(text); - eventHandled = true; - } - } - return eventHandled; +bool MenuState::keyDownEditLabel(SDL_KeyboardEvent c, + GraphicLabel **activeInputLabelPtr) { + bool eventHandled = false; + GraphicLabel *activeInputLabel = *activeInputLabelPtr; + if (activeInputLabel != NULL) { + string text = activeInputLabel->getText(); + if (isKeyPressed(SDLK_BACKSPACE, c) == true && text.length() > 0) { + // printf("BSPACE text [%s]\n",text.c_str()); + + bool hasUnderscore = false; + bool delChar = false; + size_t found = text.find_last_of("_"); + if (found == string::npos || found != text.length() - 1) { + // printf("A text.length() = %d textCharLength.size() = + // %d\n",text.length(),textCharLength.size()); + if (activeInputLabel->getTextCharLengthList() + [activeInputLabel->getTextCharLengthList().size() - 1] >= 1) { + delChar = true; + } + } else { + // printf("B text.length() = %d textCharLength.size() = + // %d\n",text.length(),textCharLength.size()); + hasUnderscore = true; + if (activeInputLabel->getTextCharLengthList().size() >= 2 && + activeInputLabel->getTextCharLengthList() + [activeInputLabel->getTextCharLengthList().size() - 2] >= + 1) { + delChar = true; + } + } + if (delChar == true) { + if (hasUnderscore) { + // if(textCharLength.size() > 1) { + if (activeInputLabel->getTextCharLengthList().size() > 1) { + // printf("Underscore erase start\n"); + for (unsigned int i = 0; + i < (unsigned int)activeInputLabel->getTextCharLengthList() + [activeInputLabel->getTextCharLengthList().size() - 2]; + ++i) { + text.erase(text.end() - 2); + } + // printf("AFTER DEL textCharLength.size() = %d + // textCharLength[textCharLength.size()-1] = %d text.length() = + // %d\n",textCharLength.size(),textCharLength[textCharLength.size()-1],text.length()); + activeInputLabel->deleteTextCharLengthFromList(); + activeInputLabel->deleteTextCharLengthFromList(); + activeInputLabel->addTextCharLengthToList(1); + } + } else { + for (unsigned int i = 0; + i < (unsigned int)activeInputLabel->getTextCharLengthList() + [activeInputLabel->getTextCharLengthList().size() - 1]; + ++i) { + text.erase(text.end() - 1); + } + activeInputLabel->deleteTextCharLengthFromList(); + } + } + activeInputLabel->setText(text); + eventHandled = true; + } + } + return eventHandled; } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/menu/main_menu.h b/source/glest_game/menu/main_menu.h index 455ffb3cd..c5a3b4184 100644 --- a/source/glest_game/menu/main_menu.h +++ b/source/glest_game/menu/main_menu.h @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,25 +13,28 @@ #define _GLEST_GAME_MAINMENU_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include "lang.h" -#include "console.h" -#include "vec.h" -#include "world.h" -#include "program.h" #include "components.h" -#include "menu_background.h" +#include "console.h" #include "game_settings.h" +#include "lang.h" #include "leak_dumper.h" +#include "menu_background.h" +#include "program.h" +#include "vec.h" +#include "world.h" -namespace Shared { namespace Graphics { - class VideoPlayer; -}} +namespace Shared { +namespace Graphics { +class VideoPlayer; +} +} // namespace Shared -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { class MenuState; @@ -41,108 +44,112 @@ class MenuState; /// Main menu ProgramState // ===================================================== -class MainMenu: public ProgramState { - +class MainMenu : public ProgramState { + private: - static MenuState *oldstate; - //up - Program *program; - - //shared - GameSettings gameSettings; - MenuBackground menuBackground; - ::Shared::Graphics::VideoPlayer *menuBackgroundVideo; + static MenuState *oldstate; + // up + Program *program; - MenuState *state; + // shared + GameSettings gameSettings; + MenuBackground menuBackground; + ::Shared::Graphics::VideoPlayer *menuBackgroundVideo; - //shared - int mouseX, mouseY; - int mouse2dAnim; + MenuState *state; - void initBackgroundVideo(); + // shared + int mouseX, mouseY; + int mouse2dAnim; + + void initBackgroundVideo(); public: - explicit MainMenu(Program *program); - virtual ~MainMenu(); - - MenuBackground *getMenuBackground() {return &menuBackground;} - const MenuBackground *getConstMenuBackground() const {return &menuBackground;} - - virtual void render(); - virtual void update(); - virtual void init(); - virtual void mouseMove(int x, int y, const MouseState *mouseState); - virtual void eventMouseWheel(int x, int y,int zDelta); - virtual void mouseDownLeft(int x, int y); - virtual void mouseDoubleClickLeft(int x, int y); - virtual void mouseDoubleClickRight(int x, int y); - virtual void mouseDownRight(int x, int y); - virtual void mouseUpLeft(int x, int y); - virtual bool textInput(std::string text); - virtual void keyDown(SDL_KeyboardEvent key); - virtual void keyUp(SDL_KeyboardEvent key); - virtual void keyPress(SDL_KeyboardEvent key); - - void setState(MenuState *state); - virtual bool isInSpecialKeyCaptureEvent(); - - int getMouseX() const {return mouseX;} - int getMouseY() const {return mouseY;} - int getMouse2dAnim() const {return mouse2dAnim;} - virtual void consoleAddLine(string line); - virtual void reloadUI(); + explicit MainMenu(Program *program); + virtual ~MainMenu(); + + MenuBackground *getMenuBackground() { return &menuBackground; } + const MenuBackground *getConstMenuBackground() const { + return &menuBackground; + } + + virtual void render(); + virtual void update(); + virtual void init(); + virtual void mouseMove(int x, int y, const MouseState *mouseState); + virtual void eventMouseWheel(int x, int y, int zDelta); + virtual void mouseDownLeft(int x, int y); + virtual void mouseDoubleClickLeft(int x, int y); + virtual void mouseDoubleClickRight(int x, int y); + virtual void mouseDownRight(int x, int y); + virtual void mouseUpLeft(int x, int y); + virtual bool textInput(std::string text); + virtual void keyDown(SDL_KeyboardEvent key); + virtual void keyUp(SDL_KeyboardEvent key); + virtual void keyPress(SDL_KeyboardEvent key); + + void setState(MenuState *state); + virtual bool isInSpecialKeyCaptureEvent(); + + int getMouseX() const { return mouseX; } + int getMouseY() const { return mouseY; } + int getMouse2dAnim() const { return mouse2dAnim; } + virtual void consoleAddLine(string line); + virtual void reloadUI(); }; - // =============================== -// class MenuState +// class MenuState // =============================== class MenuState { protected: - Program *program; + Program *program; - MainMenu *mainMenu; - Camera camera; + MainMenu *mainMenu; + Camera camera; - const char *containerName; - Console console; + const char *containerName; + Console console; - //vector textCharLength; + // vector textCharLength; protected: - - void setActiveInputLabel(GraphicLabel *newLabel, GraphicLabel **activeInputLabelPtr); - bool textInputEditLabel(string input, GraphicLabel **activeInputLabelPtr); - bool keyPressEditLabel(SDL_KeyboardEvent c, GraphicLabel **activeInputLabelPtr); - bool keyDownEditLabel(SDL_KeyboardEvent c, GraphicLabel **activeInputLabelPtr); + void setActiveInputLabel(GraphicLabel *newLabel, + GraphicLabel **activeInputLabelPtr); + bool textInputEditLabel(string input, GraphicLabel **activeInputLabelPtr); + bool keyPressEditLabel(SDL_KeyboardEvent c, + GraphicLabel **activeInputLabelPtr); + bool keyDownEditLabel(SDL_KeyboardEvent c, + GraphicLabel **activeInputLabelPtr); public: - MenuState(Program *program, MainMenu *mainMenu, const string &stateName); - virtual ~MenuState(); - virtual void mouseClick(int x, int y, MouseButton mouseButton)=0; - virtual void mouseDoubleClick(int x, int y, MouseButton mouseButton)=0; - virtual void mouseUp(int x, int y, const MouseButton mouseButton){}; - virtual void mouseMove(int x, int y, const MouseState *mouseState)=0; - virtual void eventMouseWheel(int x, int y, int zDelta){}; - virtual void render()=0; - virtual void update(){}; - - virtual bool textInput(std::string text) {return false; } - virtual void keyDown(SDL_KeyboardEvent key){}; - virtual void keyPress(SDL_KeyboardEvent c){}; - virtual void keyUp(SDL_KeyboardEvent key){}; - - virtual bool isMasterserverMode() const {return false;} - const Camera *getCamera() const {return &camera;} - - virtual bool isInSpecialKeyCaptureEvent() { return false; } - virtual void consoleAddLine(string line); - virtual void reloadUI(); - - virtual bool isVideoPlaying() { return false; }; + MenuState(Program *program, MainMenu *mainMenu, const string &stateName); + virtual ~MenuState(); + virtual void mouseClick(int x, int y, MouseButton mouseButton) = 0; + virtual void mouseDoubleClick(int x, int y, MouseButton mouseButton) = 0; + virtual void mouseUp(int x, int y, const MouseButton mouseButton){}; + virtual void mouseMove(int x, int y, const MouseState *mouseState) = 0; + virtual void eventMouseWheel(int x, int y, int zDelta){}; + virtual void render() = 0; + virtual void update(){}; + + virtual bool textInput(std::string text) { return false; } + virtual void keyDown(SDL_KeyboardEvent key){}; + virtual void keyPress(SDL_KeyboardEvent c){}; + virtual void keyUp(SDL_KeyboardEvent key){}; + + virtual bool isMasterserverMode() const { return false; } + const Camera *getCamera() const { return &camera; } + + virtual bool isInSpecialKeyCaptureEvent() { return false; } + virtual void consoleAddLine(string line); + virtual void reloadUI(); + + virtual bool isVideoPlaying() { return false; }; }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/menu/menu_background.cpp b/source/glest_game/menu/menu_background.cpp index d4128c432..16a34f495 100644 --- a/source/glest_game/menu/menu_background.cpp +++ b/source/glest_game/menu/menu_background.cpp @@ -13,225 +13,236 @@ #include -#include "renderer.h" -#include "core_data.h" #include "config.h" -#include "xml_parser.h" -#include "util.h" +#include "core_data.h" #include "game_constants.h" #include "game_util.h" #include "leak_dumper.h" +#include "renderer.h" +#include "util.h" +#include "xml_parser.h" using namespace Shared::Util; using namespace Shared::Xml; using namespace Shared::Graphics; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class MenuBackground // ===================================================== MenuBackground::MenuBackground() : rps(NULL) { - Renderer &renderer= Renderer::getInstance(); - - //load data - string data_path = getGameReadWritePath(GameConstants::path_data_CacheLookupKey); - - XmlTree xmlTree; - xmlTree.load(getGameCustomCoreDataPath(data_path, "data/core/menu/menu.xml"),Properties::getTagReplacementValues()); - const XmlNode *menuNode= xmlTree.getRootNode(); - - //water - const XmlNode *waterNode= menuNode->getChild("water"); - water= waterNode->getAttribute("value")->getBoolValue(); - if(water){ - waterHeight= waterNode->getAttribute("height")->getFloatValue(); - - //water texture - waterTexture= renderer.newTexture2D(rsMenu); - if(waterTexture) { - waterTexture->getPixmap()->init(4); - waterTexture->getPixmap()->load(getGameCustomCoreDataPath(data_path, "data/core/menu/textures/water.tga")); - } - } - - //fog - const XmlNode *fogNode= menuNode->getChild("fog"); - fog= fogNode->getAttribute("value")->getBoolValue(); - if(fog){ - fogDensity= fogNode->getAttribute("density")->getFloatValue(); - } - - //rain - bool withRainEffect = Config::getInstance().getBool("RainEffectMenu","true"); - if(withRainEffect == true) { - rain= menuNode->getChild("rain")->getAttribute("value")->getBoolValue(); - if(rain) { - createRainParticleSystem(); - } - } - else { - rain = false; - } - - //camera - const XmlNode *cameraNode= menuNode->getChild("camera"); - - //position - const XmlNode *positionNode= cameraNode->getChild("start-position"); - Vec3f startPosition; - startPosition.x= positionNode->getAttribute("x")->getFloatValue(); - startPosition.y= positionNode->getAttribute("y")->getFloatValue(); - startPosition.z= positionNode->getAttribute("z")->getFloatValue(); - camera.setPosition(startPosition); - - //rotation - const XmlNode *rotationNode= cameraNode->getChild("start-rotation"); - Vec3f startRotation; - startRotation.x= rotationNode->getAttribute("x")->getFloatValue(); - startRotation.y= rotationNode->getAttribute("y")->getFloatValue(); - startRotation.z= rotationNode->getAttribute("z")->getFloatValue(); - camera.setOrientation(Quaternion(EulerAngles( - degToRad(startRotation.x), - degToRad(startRotation.y), - degToRad(startRotation.z)))); - - //load main model - string mainModelFile = "data/core/menu/main_model/menu_main.g3d"; - if(menuNode->hasChild("menu-background-model") == true) { - //mainModel->load(data_path + "data/core/menu/main_model/menu_main.g3d"); - const XmlNode *mainMenuModelNode= menuNode->getChild("menu-background-model"); - mainModelFile = mainMenuModelNode->getAttribute("value")->getRestrictedValue(); + Renderer &renderer = Renderer::getInstance(); + + // load data + string data_path = + getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + + XmlTree xmlTree; + xmlTree.load(getGameCustomCoreDataPath(data_path, "data/core/menu/menu.xml"), + Properties::getTagReplacementValues()); + const XmlNode *menuNode = xmlTree.getRootNode(); + + // water + const XmlNode *waterNode = menuNode->getChild("water"); + water = waterNode->getAttribute("value")->getBoolValue(); + if (water) { + waterHeight = waterNode->getAttribute("height")->getFloatValue(); + + // water texture + waterTexture = renderer.newTexture2D(rsMenu); + if (waterTexture) { + waterTexture->getPixmap()->init(4); + waterTexture->getPixmap()->load(getGameCustomCoreDataPath( + data_path, "data/core/menu/textures/water.tga")); + } + } + + // fog + const XmlNode *fogNode = menuNode->getChild("fog"); + fog = fogNode->getAttribute("value")->getBoolValue(); + if (fog) { + fogDensity = fogNode->getAttribute("density")->getFloatValue(); + } + + // rain + bool withRainEffect = Config::getInstance().getBool("RainEffectMenu", "true"); + if (withRainEffect == true) { + rain = menuNode->getChild("rain")->getAttribute("value")->getBoolValue(); + if (rain) { + createRainParticleSystem(); } - mainModel = renderer.newModel(rsMenu, getGameCustomCoreDataPath(data_path, mainModelFile)); - - //models - for(int i=0; i<5; ++i) { - characterModels[i] = renderer.newModel(rsMenu, getGameCustomCoreDataPath(data_path, "data/core/menu/about_models/character"+intToStr(i)+".g3d")); - } - - //about position - positionNode= cameraNode->getChild("about-position"); - aboutPosition.x= positionNode->getAttribute("x")->getFloatValue(); - aboutPosition.y= positionNode->getAttribute("y")->getFloatValue(); - aboutPosition.z= positionNode->getAttribute("z")->getFloatValue(); - //rotationNode= cameraNode->getChild("about-rotation"); - - targetCamera= NULL; - t= 0.f; - fade= 0.f; - anim= 0.f; + } else { + rain = false; + } + + // camera + const XmlNode *cameraNode = menuNode->getChild("camera"); + + // position + const XmlNode *positionNode = cameraNode->getChild("start-position"); + Vec3f startPosition; + startPosition.x = positionNode->getAttribute("x")->getFloatValue(); + startPosition.y = positionNode->getAttribute("y")->getFloatValue(); + startPosition.z = positionNode->getAttribute("z")->getFloatValue(); + camera.setPosition(startPosition); + + // rotation + const XmlNode *rotationNode = cameraNode->getChild("start-rotation"); + Vec3f startRotation; + startRotation.x = rotationNode->getAttribute("x")->getFloatValue(); + startRotation.y = rotationNode->getAttribute("y")->getFloatValue(); + startRotation.z = rotationNode->getAttribute("z")->getFloatValue(); + camera.setOrientation(Quaternion(EulerAngles(degToRad(startRotation.x), + degToRad(startRotation.y), + degToRad(startRotation.z)))); + + // load main model + string mainModelFile = "data/core/menu/main_model/menu_main.g3d"; + if (menuNode->hasChild("menu-background-model") == true) { + // mainModel->load(data_path + "data/core/menu/main_model/menu_main.g3d"); + const XmlNode *mainMenuModelNode = + menuNode->getChild("menu-background-model"); + mainModelFile = + mainMenuModelNode->getAttribute("value")->getRestrictedValue(); + } + mainModel = renderer.newModel( + rsMenu, getGameCustomCoreDataPath(data_path, mainModelFile)); + + // models + for (int i = 0; i < 5; ++i) { + characterModels[i] = renderer.newModel( + rsMenu, getGameCustomCoreDataPath( + data_path, "data/core/menu/about_models/character" + + intToStr(i) + ".g3d")); + } + + // about position + positionNode = cameraNode->getChild("about-position"); + aboutPosition.x = positionNode->getAttribute("x")->getFloatValue(); + aboutPosition.y = positionNode->getAttribute("y")->getFloatValue(); + aboutPosition.z = positionNode->getAttribute("z")->getFloatValue(); + // rotationNode= cameraNode->getChild("about-rotation"); + + targetCamera = NULL; + t = 0.f; + fade = 0.f; + anim = 0.f; } MenuBackground::~MenuBackground() { - //printf("In ~MenuBackground() rps = %p\n",rps); + // printf("In ~MenuBackground() rps = %p\n",rps); - cleanup(); + cleanup(); } void MenuBackground::cleanup() { - //printf("In MenuBackground::cleanup() rps = %p\n",rps); - - if(rps != NULL) { - Renderer &renderer= Renderer::getInstance(); - if(renderer.validateParticleSystemStillExists(rps,rsMenu) == true) { - rps->fade(); - vector particleSystems; - particleSystems.push_back(rps); - renderer.cleanupParticleSystems(particleSystems, rsMenu); - } - - rps = NULL; - } + // printf("In MenuBackground::cleanup() rps = %p\n",rps); + + if (rps != NULL) { + Renderer &renderer = Renderer::getInstance(); + if (renderer.validateParticleSystemStillExists(rps, rsMenu) == true) { + rps->fade(); + vector particleSystems; + particleSystems.push_back(rps); + renderer.cleanupParticleSystems(particleSystems, rsMenu); + } + + rps = NULL; + } } void MenuBackground::createRainParticleSystem() { - //printf("In MenuBackground::createRainParticleSystem() rps = %p\n",rps); - - if(rps == NULL) { - rps= new RainParticleSystem(); - rps->setSpeed(12.f/GameConstants::updateFps); - rps->setEmissionRate(25); - rps->setWind(-90.f, 4.f/GameConstants::updateFps); - rps->setPos(Vec3f(0.f, 25.f, 0.f)); - rps->setColor(Vec4f(1.f, 1.f, 1.f, 0.2f)); - rps->setRadius(30.f); - - Renderer &renderer= Renderer::getInstance(); - renderer.manageParticleSystem(rps, rsMenu); - - for(int i=0; isetSpeed(12.f / GameConstants::updateFps); + rps->setEmissionRate(25); + rps->setWind(-90.f, 4.f / GameConstants::updateFps); + rps->setPos(Vec3f(0.f, 25.f, 0.f)); + rps->setColor(Vec4f(1.f, 1.f, 1.f, 0.2f)); + rps->setRadius(30.f); + + Renderer &renderer = Renderer::getInstance(); + renderer.manageParticleSystem(rps, rsMenu); + + for (int i = 0; i < raindropCount; ++i) { + raindropStates[i] = random.randRange(0.f, 1.f); + raindropPos[i] = computeRaindropPos(); + } + } } -void MenuBackground::setTargetCamera(const Camera *targetCamera){ - this->targetCamera= targetCamera; - this->lastCamera= camera; - t= 0.f; +void MenuBackground::setTargetCamera(const Camera *targetCamera) { + this->targetCamera = targetCamera; + this->lastCamera = camera; + t = 0.f; } void MenuBackground::update() { - //rain drops - bool withRainEffect = Config::getInstance().getBool("RainEffectMenu","true"); - if(withRainEffect == true) { - if(rain == false) { - rain = true; - createRainParticleSystem(); - } - - for(int i=0; i=1.f){ - raindropStates[i]= 0.f; - raindropPos[i]= computeRaindropPos(); - } - } - } - else if(rain == true) { - rain = false; - - cleanup(); - } - - if(targetCamera!=NULL){ - t+= ((0.01f+(1.f-t)/10.f)/20.f)*(60.f/GameConstants::updateFps); - - //interpolate position - camera.setPosition(lastCamera.getPosition().lerp(t, targetCamera->getPosition())); - - //interpolate orientation - Quaternion q= lastCamera.getOrientation().lerp(t, targetCamera->getOrientation()); - camera.setOrientation(q); - - if(t>=1.f){ - targetCamera= NULL; - t= 0.f; - } - } - - //fade - if(fade<=1.f){ - fade+= 0.6f/GameConstants::updateFps; - if(fade>1.f){ - fade= 1.f; - } - } - - //animation - anim+=(0.6f/GameConstants::updateFps)/5+random.randRange(0.f, (0.6f/GameConstants::updateFps)/5.f); - if(anim>1.f){ - anim= 0.f; - } + // rain drops + bool withRainEffect = Config::getInstance().getBool("RainEffectMenu", "true"); + if (withRainEffect == true) { + if (rain == false) { + rain = true; + createRainParticleSystem(); + } + + for (int i = 0; i < raindropCount; ++i) { + raindropStates[i] += 1.f / GameConstants::updateFps; + if (raindropStates[i] >= 1.f) { + raindropStates[i] = 0.f; + raindropPos[i] = computeRaindropPos(); + } + } + } else if (rain == true) { + rain = false; + + cleanup(); + } + + if (targetCamera != NULL) { + t += + ((0.01f + (1.f - t) / 10.f) / 20.f) * (60.f / GameConstants::updateFps); + + // interpolate position + camera.setPosition( + lastCamera.getPosition().lerp(t, targetCamera->getPosition())); + + // interpolate orientation + Quaternion q = + lastCamera.getOrientation().lerp(t, targetCamera->getOrientation()); + camera.setOrientation(q); + + if (t >= 1.f) { + targetCamera = NULL; + t = 0.f; + } + } + + // fade + if (fade <= 1.f) { + fade += 0.6f / GameConstants::updateFps; + if (fade > 1.f) { + fade = 1.f; + } + } + + // animation + anim += (0.6f / GameConstants::updateFps) / 5 + + random.randRange(0.f, (0.6f / GameConstants::updateFps) / 5.f); + if (anim > 1.f) { + anim = 0.f; + } } Vec2f MenuBackground::computeRaindropPos() { - float f= static_cast(meshSize); - return Vec2f(random.randRange(-f, f), random.randRange(-f, f)); + float f = static_cast(meshSize); + return Vec2f(random.randRange(-f, f), random.randRange(-f, f)); } -}}//end namespace - +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/menu/menu_background.h b/source/glest_game/menu/menu_background.h index 5b685c6f9..ebc4155af 100644 --- a/source/glest_game/menu/menu_background.h +++ b/source/glest_game/menu/menu_background.h @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,105 +13,106 @@ #define _GLEST_GAME_MENUBACKGROUND_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include "particle.h" #include "camera.h" -#include "vec.h" -#include "texture.h" +#include "leak_dumper.h" #include "model.h" +#include "particle.h" #include "randomgen.h" -#include "leak_dumper.h" +#include "texture.h" +#include "vec.h" -using Shared::Graphics::RainParticleSystem; -using Shared::Graphics::FireParticleSystem; using Shared::Graphics::Camera; -using Shared::Graphics::Vec3f; -using Shared::Graphics::Vec2f; -using Shared::Graphics::Texture2D; +using Shared::Graphics::FireParticleSystem; using Shared::Graphics::Model; +using Shared::Graphics::RainParticleSystem; +using Shared::Graphics::Texture2D; +using Shared::Graphics::Vec2f; +using Shared::Graphics::Vec3f; using Shared::Util::RandomGen; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // =========================================================== -// class MenuBackground +// class MenuBackground // -/// Holds the data to display the 3D environment +/// Holds the data to display the 3D environment /// in the MenuState // =========================================================== -class MenuBackground{ +class MenuBackground { public: - static const int meshSize= 32; - static const int raindropCount= 1000; - static const int characterCount= 5; + static const int meshSize = 32; + static const int raindropCount = 1000; + static const int characterCount = 5; private: - Model *mainModel; - - //water - bool water; - float waterHeight; - Texture2D *waterTexture; - - //fog - bool fog; - float fogDensity; - - //rain - bool rain; - Vec2f raindropPos[raindropCount]; - float raindropStates[raindropCount]; - - //camera - Camera camera; - Camera lastCamera; - const Camera *targetCamera; - float t; - - //misc - RandomGen random; - Model *characterModels[characterCount]; - float anim; - float fade; - Vec3f aboutPosition; - - RainParticleSystem *rps; + Model *mainModel; + + // water + bool water; + float waterHeight; + Texture2D *waterTexture; + + // fog + bool fog; + float fogDensity; + + // rain + bool rain; + Vec2f raindropPos[raindropCount]; + float raindropStates[raindropCount]; + + // camera + Camera camera; + Camera lastCamera; + const Camera *targetCamera; + float t; + + // misc + RandomGen random; + Model *characterModels[characterCount]; + float anim; + float fade; + Vec3f aboutPosition; + + RainParticleSystem *rps; public: - MenuBackground(); - ~MenuBackground(); - - bool getWater() const {return water;} - float getWaterHeight() const {return waterHeight;} - bool getFog() const {return fog;} - float getFogDensity() const {return fogDensity;} - bool getRain() const {return rain;} - Texture2D *getWaterTexture() const {return waterTexture;} - const Camera *getCamera() const {return &camera;} - const Model *getCharacterModel(int i) const {return characterModels[i];} - Model *getCharacterModelPtr(int i) const {return characterModels[i];} - const Model *getMainModel() const {return mainModel;} - Model *getMainModelPtr() const {return mainModel;} - float getFade() const {return fade;} - Vec2f getRaindropPos(int i) const {return raindropPos[i];} - float getRaindropState(int i) const {return raindropStates[i];} - float getAnim() const {return anim;} - const Vec3f &getAboutPosition() const {return aboutPosition;} - - void setTargetCamera(const Camera *targetCamera); - void update(); + MenuBackground(); + ~MenuBackground(); + + bool getWater() const { return water; } + float getWaterHeight() const { return waterHeight; } + bool getFog() const { return fog; } + float getFogDensity() const { return fogDensity; } + bool getRain() const { return rain; } + Texture2D *getWaterTexture() const { return waterTexture; } + const Camera *getCamera() const { return &camera; } + const Model *getCharacterModel(int i) const { return characterModels[i]; } + Model *getCharacterModelPtr(int i) const { return characterModels[i]; } + const Model *getMainModel() const { return mainModel; } + Model *getMainModelPtr() const { return mainModel; } + float getFade() const { return fade; } + Vec2f getRaindropPos(int i) const { return raindropPos[i]; } + float getRaindropState(int i) const { return raindropStates[i]; } + float getAnim() const { return anim; } + const Vec3f &getAboutPosition() const { return aboutPosition; } + + void setTargetCamera(const Camera *targetCamera); + void update(); private: - Vec2f computeRaindropPos(); - void createRainParticleSystem(); - void cleanup(); + Vec2f computeRaindropPos(); + void createRainParticleSystem(); + void cleanup(); }; -}} //end namespace +} // namespace Game +} // namespace Glest #endif - diff --git a/source/glest_game/menu/menu_state_about.cpp b/source/glest_game/menu/menu_state_about.cpp index db3e2c23e..79944cb97 100644 --- a/source/glest_game/menu/menu_state_about.cpp +++ b/source/glest_game/menu/menu_state_about.cpp @@ -3,23 +3,23 @@ // // Copyright (C) 2001-2005 MartiC1o Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== #include "menu_state_about.h" -#include "renderer.h" -#include "menu_state_root.h" -#include "sound_renderer.h" -#include "core_data.h" +#include "cache_manager.h" #include "config.h" +#include "core_data.h" #include "menu_state_options.h" -#include +#include "menu_state_root.h" #include "metrics.h" -#include "cache_manager.h" +#include "renderer.h" +#include "sound_renderer.h" +#include #include "leak_dumper.h" @@ -32,280 +32,306 @@ namespace Game { // class MenuStateAbout // ===================================================== -MenuStateAbout::MenuStateAbout(Program *program, MainMenu *mainMenu) : - MenuState(program, mainMenu, "about") { - - containerName= "About"; - Lang &lang= Lang::getInstance(); - - adjustModelText = true; - - customModTextureX = 0; - customModTextureY = 0; - customModTextureW = 0; - customModTextureH = 0; - customModTextureAlpha = 0.f; - - string additionalCredits= loadAdditionalCredits(); - - //init - buttonReturn.registerGraphicComponent(containerName, "buttonReturn"); - buttonReturn.init(438, 100, 125); - buttonReturn.setText(lang.getString("Return")); - - labelAdditionalCredits.registerGraphicComponent(containerName, "labelAdditionalCredits"); - labelAdditionalCredits.init(500, 700); - labelAdditionalCredits.setText(additionalCredits); - - if(additionalCredits == "") { - for(int i= 0; i < aboutStringCount1; ++i) { - labelAbout1[i].registerGraphicComponent(containerName, "labelAbout1" + intToStr(i)); - labelAbout1[i].init(100, 700 - i * 20); - labelAbout1[i].setText(getAboutString1(i)); - } - - for(int i= 0; i < aboutStringCount2; ++i) { - labelAbout2[i].registerGraphicComponent(containerName, "labelAbout2" + intToStr(i)); - labelAbout2[i].init(450, 620 - i * 20); - labelAbout2[i].setText(getAboutString2(i)); - } - } - else { - for(int i= 0; i < aboutStringCount1; ++i) { - labelAbout1[i].registerGraphicComponent(containerName, "labelAbout1" + intToStr(i)); - labelAbout1[i].init(100, 700 - i * 20); - labelAbout1[i].setText(getAboutString1(i)); - } - - for(int i= 0; i < aboutStringCount2; ++i) { - labelAbout2[i].registerGraphicComponent(containerName, "labelAbout2" + intToStr(i)); - labelAbout2[i].init(100, 620 - i * 20); - labelAbout2[i].setText(getAboutString2(i)); - } - } - - for(int i= 0; i < teammateCount; ++i) { - int xPos = (182 + i * 138); - labelTeammateName[i].registerGraphicComponent(containerName, "labelTeammateName" + intToStr(i)); - labelTeammateName[i].init(xPos, 500); - labelTeammateRole[i].registerGraphicComponent(containerName, "labelTeammateRole" + intToStr(i)); - labelTeammateRole[i].init(xPos, 520); - - labelTeammateName[i].setText(getTeammateName(i)); - labelTeammateRole[i].setText(getTeammateRole(i)); - } - - for(int i = teammateTopLineCount; i < teammateCount; ++i) { - labelTeammateName[i].init(202 + (i-5) * 138, 160); - labelTeammateRole[i].init(202 + (i-5) * 138, 180); - } - labelTeammateName[8].init(labelTeammateName[4].getX(), 160); - labelTeammateRole[8].init(labelTeammateRole[4].getX(), 180); - - customModTexture = NULL; - labelCustomModCredits.registerGraphicComponent(containerName, "labelCustomModCredits"); - labelCustomModCredits.init(-1, -1); - labelCustomModCredits.setText(""); - labelCustomModCredits.setVisible(false); - - enableCustomModCredits = Config::getInstance().getBool("EnabledCustomModCredits","false"); - if(enableCustomModCredits == true) { - string customModCreditsText = Config::getInstance().getString("CustomModCreditsText",""); - if(customModCreditsText != "") { - replaceAll(customModCreditsText, "\\n", "\n"); - int x = Config::getInstance().getInt("CustomModCreditsTextX","1"); - int y = Config::getInstance().getInt("CustomModCreditsTextY","1"); - int w = Config::getInstance().getInt("CustomModCreditsTextW",intToStr(GraphicLabel::defW).c_str()); - int h = Config::getInstance().getInt("CustomModCreditsTextH",intToStr(GraphicLabel::defH).c_str()); - - labelCustomModCredits.init(x, y, w, h); - labelCustomModCredits.setText(customModCreditsText); - labelCustomModCredits.setVisible(true); - } - - int buttonReturnX = Config::getInstance().getInt("CustomModCreditsReturnX",intToStr(buttonReturn.getX()).c_str()); - int buttonReturnY = Config::getInstance().getInt("CustomModCreditsReturnY",intToStr(buttonReturn.getY()).c_str()); - int buttonReturnW = Config::getInstance().getInt("CustomModCreditsReturnW",intToStr(buttonReturn.getW()).c_str()); - - buttonReturn.init(buttonReturnX, buttonReturnY, buttonReturnW); - } - - GraphicComponent::applyAllCustomProperties(containerName); +MenuStateAbout::MenuStateAbout(Program *program, MainMenu *mainMenu) + : MenuState(program, mainMenu, "about") { + + containerName = "About"; + Lang &lang = Lang::getInstance(); + + adjustModelText = true; + + customModTextureX = 0; + customModTextureY = 0; + customModTextureW = 0; + customModTextureH = 0; + customModTextureAlpha = 0.f; + + string additionalCredits = loadAdditionalCredits(); + + // init + buttonReturn.registerGraphicComponent(containerName, "buttonReturn"); + buttonReturn.init(438, 100, 125); + buttonReturn.setText(lang.getString("Return")); + + labelAdditionalCredits.registerGraphicComponent(containerName, + "labelAdditionalCredits"); + labelAdditionalCredits.init(500, 700); + labelAdditionalCredits.setText(additionalCredits); + + if (additionalCredits == "") { + for (int i = 0; i < aboutStringCount1; ++i) { + labelAbout1[i].registerGraphicComponent(containerName, + "labelAbout1" + intToStr(i)); + labelAbout1[i].init(100, 700 - i * 20); + labelAbout1[i].setText(getAboutString1(i)); + } + + for (int i = 0; i < aboutStringCount2; ++i) { + labelAbout2[i].registerGraphicComponent(containerName, + "labelAbout2" + intToStr(i)); + labelAbout2[i].init(450, 620 - i * 20); + labelAbout2[i].setText(getAboutString2(i)); + } + } else { + for (int i = 0; i < aboutStringCount1; ++i) { + labelAbout1[i].registerGraphicComponent(containerName, + "labelAbout1" + intToStr(i)); + labelAbout1[i].init(100, 700 - i * 20); + labelAbout1[i].setText(getAboutString1(i)); + } + + for (int i = 0; i < aboutStringCount2; ++i) { + labelAbout2[i].registerGraphicComponent(containerName, + "labelAbout2" + intToStr(i)); + labelAbout2[i].init(100, 620 - i * 20); + labelAbout2[i].setText(getAboutString2(i)); + } + } + + for (int i = 0; i < teammateCount; ++i) { + int xPos = (182 + i * 138); + labelTeammateName[i].registerGraphicComponent( + containerName, "labelTeammateName" + intToStr(i)); + labelTeammateName[i].init(xPos, 500); + labelTeammateRole[i].registerGraphicComponent( + containerName, "labelTeammateRole" + intToStr(i)); + labelTeammateRole[i].init(xPos, 520); + + labelTeammateName[i].setText(getTeammateName(i)); + labelTeammateRole[i].setText(getTeammateRole(i)); + } + + for (int i = teammateTopLineCount; i < teammateCount; ++i) { + labelTeammateName[i].init(202 + (i - 5) * 138, 160); + labelTeammateRole[i].init(202 + (i - 5) * 138, 180); + } + labelTeammateName[8].init(labelTeammateName[4].getX(), 160); + labelTeammateRole[8].init(labelTeammateRole[4].getX(), 180); + + customModTexture = NULL; + labelCustomModCredits.registerGraphicComponent(containerName, + "labelCustomModCredits"); + labelCustomModCredits.init(-1, -1); + labelCustomModCredits.setText(""); + labelCustomModCredits.setVisible(false); + + enableCustomModCredits = + Config::getInstance().getBool("EnabledCustomModCredits", "false"); + if (enableCustomModCredits == true) { + string customModCreditsText = + Config::getInstance().getString("CustomModCreditsText", ""); + if (customModCreditsText != "") { + replaceAll(customModCreditsText, "\\n", "\n"); + int x = Config::getInstance().getInt("CustomModCreditsTextX", "1"); + int y = Config::getInstance().getInt("CustomModCreditsTextY", "1"); + int w = Config::getInstance().getInt( + "CustomModCreditsTextW", intToStr(GraphicLabel::defW).c_str()); + int h = Config::getInstance().getInt( + "CustomModCreditsTextH", intToStr(GraphicLabel::defH).c_str()); + + labelCustomModCredits.init(x, y, w, h); + labelCustomModCredits.setText(customModCreditsText); + labelCustomModCredits.setVisible(true); + } + + int buttonReturnX = Config::getInstance().getInt( + "CustomModCreditsReturnX", intToStr(buttonReturn.getX()).c_str()); + int buttonReturnY = Config::getInstance().getInt( + "CustomModCreditsReturnY", intToStr(buttonReturn.getY()).c_str()); + int buttonReturnW = Config::getInstance().getInt( + "CustomModCreditsReturnW", intToStr(buttonReturn.getW()).c_str()); + + buttonReturn.init(buttonReturnX, buttonReturnY, buttonReturnW); + } + + GraphicComponent::applyAllCustomProperties(containerName); } MenuStateAbout::~MenuStateAbout() { - if(customModTexture != NULL) { - Renderer::getInstance().endTexture(rsGlobal, customModTexture, false); - customModTexture = NULL; - } + if (customModTexture != NULL) { + Renderer::getInstance().endTexture(rsGlobal, customModTexture, false); + customModTexture = NULL; + } } void MenuStateAbout::reloadUI() { - Lang &lang= Lang::getInstance(); - - adjustModelText = true; - string additionalCredits= loadAdditionalCredits(); - - buttonReturn.setText(lang.getString("Return")); - labelAdditionalCredits.setText(additionalCredits); - - //if(additionalCredits == "") { - for(int i= 0; i < aboutStringCount1; ++i){ - labelAbout1[i].setText(getAboutString1(i)); - } - - for(int i= 0; i < aboutStringCount2; ++i){ - labelAbout2[i].setText(getAboutString2(i)); - } - //} - //else { - // for(int i= 0; i < aboutStringCount1; ++i){ - // labelAbout1[i].setText(getAboutString1(i)); - // } - - // for(int i= 0; i < aboutStringCount2; ++i){ - // labelAbout2[i].setText(getAboutString2(i)); - // } - //} - - for(int i= 0; i < teammateCount; ++i) { - labelTeammateName[i].setText(getTeammateName(i)); - labelTeammateRole[i].setText(getTeammateRole(i)); - } - - GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); + Lang &lang = Lang::getInstance(); + + adjustModelText = true; + string additionalCredits = loadAdditionalCredits(); + + buttonReturn.setText(lang.getString("Return")); + labelAdditionalCredits.setText(additionalCredits); + + // if(additionalCredits == "") { + for (int i = 0; i < aboutStringCount1; ++i) { + labelAbout1[i].setText(getAboutString1(i)); + } + + for (int i = 0; i < aboutStringCount2; ++i) { + labelAbout2[i].setText(getAboutString2(i)); + } + //} + // else { + // for(int i= 0; i < aboutStringCount1; ++i){ + // labelAbout1[i].setText(getAboutString1(i)); + // } + + // for(int i= 0; i < aboutStringCount2; ++i){ + // labelAbout2[i].setText(getAboutString2(i)); + // } + //} + + for (int i = 0; i < teammateCount; ++i) { + labelTeammateName[i].setText(getTeammateName(i)); + labelTeammateRole[i].setText(getTeammateRole(i)); + } + + GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); } -string MenuStateAbout::loadAdditionalCredits(){ - string data_path= getGameReadWritePath(GameConstants::path_data_CacheLookupKey); - if(data_path != ""){ - endPathWithSlash(data_path); - } - string result= ""; - const string dir= getGameCustomCoreDataPath(data_path,"data/core/menu/credits.txt"); - //printf("dir [%s]\n",dir.c_str()); - - if(fileExists(dir) == true) { +string MenuStateAbout::loadAdditionalCredits() { + string data_path = + getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + if (data_path != "") { + endPathWithSlash(data_path); + } + string result = ""; + const string dir = + getGameCustomCoreDataPath(data_path, "data/core/menu/credits.txt"); + // printf("dir [%s]\n",dir.c_str()); + + if (fileExists(dir) == true) { #if defined(WIN32) && !defined(__MINGW32__) - FILE *fp = _wfopen(utf8_decode(dir).c_str(), L"r"); - ifstream file(fp); + FILE *fp = _wfopen(utf8_decode(dir).c_str(), L"r"); + ifstream file(fp); #else - ifstream file(dir.c_str()); + ifstream file(dir.c_str()); #endif - std::string buffer; - while(!file.eof()){ - getline(file, buffer); - result+= buffer + "\n"; - } - std::cout << buffer << std::endl; - file.close(); + std::string buffer; + while (!file.eof()) { + getline(file, buffer); + result += buffer + "\n"; + } + std::cout << buffer << std::endl; + file.close(); #if defined(WIN32) && !defined(__MINGW32__) - if(fp) fclose(fp); + if (fp) + fclose(fp); #endif - } - return result; + } + return result; } -void MenuStateAbout::mouseClick(int x, int y, MouseButton mouseButton){ - - CoreData &coreData= CoreData::getInstance(); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); +void MenuStateAbout::mouseClick(int x, int y, MouseButton mouseButton) { - if(buttonReturn.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - mainMenu->setState(new MenuStateRoot(program, mainMenu)); - } + CoreData &coreData = CoreData::getInstance(); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + if (buttonReturn.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + mainMenu->setState(new MenuStateRoot(program, mainMenu)); + } } -void MenuStateAbout::mouseMove(int x, int y, const MouseState *ms){ - buttonReturn.mouseMove(x, y); +void MenuStateAbout::mouseMove(int x, int y, const MouseState *ms) { + buttonReturn.mouseMove(x, y); } void MenuStateAbout::render() { - Renderer &renderer= Renderer::getInstance(); - - if(enableCustomModCredits == true) { - if(customModTexture == NULL) { - string customModCreditsTextureFile = Config::getInstance().getString("CustomModCreditsTextureFile",""); - if(customModCreditsTextureFile != "") { - string data_path= getGameReadWritePath(GameConstants::path_data_CacheLookupKey); - if(data_path != ""){ - endPathWithSlash(data_path); - } - customModTexture = Renderer::findTexture(data_path + customModCreditsTextureFile); - } - } - - renderer.renderBackground(customModTexture); - renderer.renderLabel(&labelCustomModCredits); - } - else { - renderer.renderLabel(&labelAdditionalCredits); - - for(int i= 0; i < aboutStringCount1; ++i) { - renderer.renderLabel(&labelAbout1[i]); - } - for(int i= 0; i < aboutStringCount2; ++i) { - renderer.renderLabel(&labelAbout2[i]); - } - - if(adjustModelText == true) { - std::vector &characterMenuScreenPositionListCache = - CacheManager::getCachedItem< std::vector >(GameConstants::characterMenuScreenPositionListCacheLookupKey); - - for(int i= 0; i < teammateCount; ++i) { - int characterPos = (i % teammateTopLineCount); - if(characterPos < (int)characterMenuScreenPositionListCache.size()) { - adjustModelText = false; - - int xPos = characterMenuScreenPositionListCache[characterPos].x; - if(i == 7 && characterPos+1 < (int)characterMenuScreenPositionListCache.size()) { - xPos += ((characterMenuScreenPositionListCache[characterPos+1].x - characterMenuScreenPositionListCache[characterPos].x) / 2); - } - else if(i == 8 && characterPos+1 < (int)characterMenuScreenPositionListCache.size()) { - xPos = characterMenuScreenPositionListCache[characterPos+1].x; - } - - FontMetrics *fontMetrics= NULL; - if(Renderer::renderText3DEnabled == false) { - fontMetrics= labelTeammateName[i].getFont()->getMetrics(); - } - else { - fontMetrics= labelTeammateName[i].getFont3D()->getMetrics(); - } - int newxPos = xPos - (fontMetrics->getTextWidth(labelTeammateName[i].getText()) / 2); - if(newxPos != labelTeammateName[i].getX()) { - labelTeammateName[i].init(newxPos, labelTeammateName[i].getY()); - } - - newxPos = xPos - (fontMetrics->getTextWidth(labelTeammateRole[i].getText()) / 2); - if(newxPos != labelTeammateRole[i].getX()) { - labelTeammateRole[i].init(newxPos, labelTeammateRole[i].getY()); - } - } - } - } - - for(int i= 0; i < teammateCount; ++i) { - renderer.renderLabel(&labelTeammateName[i]); - renderer.renderLabel(&labelTeammateRole[i]); - } - } - - renderer.renderButton(&buttonReturn); - - if(program != NULL) - program->renderProgramMsgBox(); - + Renderer &renderer = Renderer::getInstance(); + + if (enableCustomModCredits == true) { + if (customModTexture == NULL) { + string customModCreditsTextureFile = + Config::getInstance().getString("CustomModCreditsTextureFile", ""); + if (customModCreditsTextureFile != "") { + string data_path = + getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + if (data_path != "") { + endPathWithSlash(data_path); + } + customModTexture = + Renderer::findTexture(data_path + customModCreditsTextureFile); + } + } + + renderer.renderBackground(customModTexture); + renderer.renderLabel(&labelCustomModCredits); + } else { + renderer.renderLabel(&labelAdditionalCredits); + + for (int i = 0; i < aboutStringCount1; ++i) { + renderer.renderLabel(&labelAbout1[i]); + } + for (int i = 0; i < aboutStringCount2; ++i) { + renderer.renderLabel(&labelAbout2[i]); + } + + if (adjustModelText == true) { + std::vector &characterMenuScreenPositionListCache = + CacheManager::getCachedItem>( + GameConstants::characterMenuScreenPositionListCacheLookupKey); + + for (int i = 0; i < teammateCount; ++i) { + int characterPos = (i % teammateTopLineCount); + if (characterPos < (int)characterMenuScreenPositionListCache.size()) { + adjustModelText = false; + + int xPos = characterMenuScreenPositionListCache[characterPos].x; + if (i == 7 && characterPos + 1 < + (int)characterMenuScreenPositionListCache.size()) { + xPos += ((characterMenuScreenPositionListCache[characterPos + 1].x - + characterMenuScreenPositionListCache[characterPos].x) / + 2); + } else if (i == 8 && + characterPos + 1 < + (int)characterMenuScreenPositionListCache.size()) { + xPos = characterMenuScreenPositionListCache[characterPos + 1].x; + } + + FontMetrics *fontMetrics = NULL; + if (Renderer::renderText3DEnabled == false) { + fontMetrics = labelTeammateName[i].getFont()->getMetrics(); + } else { + fontMetrics = labelTeammateName[i].getFont3D()->getMetrics(); + } + int newxPos = + xPos - + (fontMetrics->getTextWidth(labelTeammateName[i].getText()) / 2); + if (newxPos != labelTeammateName[i].getX()) { + labelTeammateName[i].init(newxPos, labelTeammateName[i].getY()); + } + + newxPos = + xPos - + (fontMetrics->getTextWidth(labelTeammateRole[i].getText()) / 2); + if (newxPos != labelTeammateRole[i].getX()) { + labelTeammateRole[i].init(newxPos, labelTeammateRole[i].getY()); + } + } + } + } + + for (int i = 0; i < teammateCount; ++i) { + renderer.renderLabel(&labelTeammateName[i]); + renderer.renderLabel(&labelTeammateRole[i]); + } + } + + renderer.renderButton(&buttonReturn); + + if (program != NULL) + program->renderProgramMsgBox(); } -void MenuStateAbout::keyDown(SDL_KeyboardEvent key){ - Config &configKeys= Config::getInstance(std::pair(cfgMainKeys, cfgUserKeys)); - if(isKeyPressed(configKeys.getSDLKey("SaveGUILayout"),key) == true) { - GraphicComponent::saveAllCustomProperties(containerName); - } +void MenuStateAbout::keyDown(SDL_KeyboardEvent key) { + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + if (isKeyPressed(configKeys.getSDLKey("SaveGUILayout"), key) == true) { + GraphicComponent::saveAllCustomProperties(containerName); + } } -} -}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/menu/menu_state_about.h b/source/glest_game/menu/menu_state_about.h index 5a8207b4a..a4c8be9bb 100644 --- a/source/glest_game/menu/menu_state_about.h +++ b/source/glest_game/menu/menu_state_about.h @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,60 +13,62 @@ #define _GLEST_GAME_MENUSTATEABOUT_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include "main_menu.h" #include "leak_dumper.h" +#include "main_menu.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // =============================== -// class MenuStateAbout +// class MenuStateAbout // =============================== -class MenuStateAbout: public MenuState{ +class MenuStateAbout : public MenuState { public: - static const int aboutStringCount1= 4; - static const int aboutStringCount2= 3; - static const int teammateCount= 9; - static const int teammateTopLineCount= 5; + static const int aboutStringCount1 = 4; + static const int aboutStringCount2 = 3; + static const int teammateCount = 9; + static const int teammateTopLineCount = 5; private: - GraphicButton buttonReturn; - GraphicLabel labelAdditionalCredits; - GraphicLabel labelAbout1[aboutStringCount1]; - GraphicLabel labelAbout2[aboutStringCount2]; - GraphicLabel labelTeammateName[teammateCount]; - GraphicLabel labelTeammateRole[teammateCount]; + GraphicButton buttonReturn; + GraphicLabel labelAdditionalCredits; + GraphicLabel labelAbout1[aboutStringCount1]; + GraphicLabel labelAbout2[aboutStringCount2]; + GraphicLabel labelTeammateName[teammateCount]; + GraphicLabel labelTeammateRole[teammateCount]; - bool adjustModelText; - string loadAdditionalCredits(); + bool adjustModelText; + string loadAdditionalCredits(); - bool enableCustomModCredits; - Texture2D *customModTexture; - int customModTextureX; - int customModTextureY; - int customModTextureW; - int customModTextureH; - float customModTextureAlpha; + bool enableCustomModCredits; + Texture2D *customModTexture; + int customModTextureX; + int customModTextureY; + int customModTextureW; + int customModTextureH; + float customModTextureAlpha; - GraphicLabel labelCustomModCredits; + GraphicLabel labelCustomModCredits; public: - MenuStateAbout(Program *program, MainMenu *mainMenu); - virtual ~MenuStateAbout(); + MenuStateAbout(Program *program, MainMenu *mainMenu); + virtual ~MenuStateAbout(); - void mouseClick(int x, int y, MouseButton mouseButton); - void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; - void mouseMove(int x, int y, const MouseState *mouseState); - void render(); - virtual void keyDown(SDL_KeyboardEvent key); + void mouseClick(int x, int y, MouseButton mouseButton); + void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; + void mouseMove(int x, int y, const MouseState *mouseState); + void render(); + virtual void keyDown(SDL_KeyboardEvent key); - virtual void reloadUI(); + virtual void reloadUI(); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/menu/menu_state_connected_game.cpp b/source/glest_game/menu/menu_state_connected_game.cpp index 6aa32717e..11537a516 100644 --- a/source/glest_game/menu/menu_state_connected_game.cpp +++ b/source/glest_game/menu/menu_state_connected_game.cpp @@ -11,43 +11,46 @@ #include "menu_state_connected_game.h" +#include "cache_manager.h" +#include "client_interface.h" +#include "compression_utils.h" +#include "config.h" +#include "conversion.h" +#include "core_data.h" +#include "game.h" +#include "map_preview.h" #include "menu_state_join_game.h" #include "menu_state_masterserver.h" -#include "renderer.h" -#include "sound_renderer.h" -#include "core_data.h" -#include "config.h" #include "menu_state_new_game.h" #include "metrics.h" #include "network_manager.h" #include "network_message.h" -#include "client_interface.h" -#include "conversion.h" +#include "renderer.h" #include "socket.h" -#include "game.h" -#include -#include -#include "cache_manager.h" +#include "sound_renderer.h" #include "string_utils.h" -#include "map_preview.h" +#include #include -#include "compression_utils.h" +#include #include "leak_dumper.h" using namespace Shared::Util; using namespace Shared::CompressionUtil; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { -static const int MAX_PING_LAG_COUNT = 6; -static const double REPROMPT_DOWNLOAD_SECONDS = 7; -//static const string ITEM_MISSING = "***missing***"; -// above replaced with Lang::getInstance().getString("DataMissing","",true) -const int HEADLESSSERVER_BROADCAST_SETTINGS_SECONDS = 2; -static const char *HEADLESS_SAVED_SETUP_FILENAME = "lastHeadlessGameSettings.mgg"; -static const char *LAST_SETUP_STRING="LastSetup"; -static const char *SETUPS_DIR=GameConstants::folder_path_setups; +static const int MAX_PING_LAG_COUNT = 6; +static const double REPROMPT_DOWNLOAD_SECONDS = 7; +// static const string ITEM_MISSING = +// "***missing***"; +// above replaced with Lang::getInstance().getString("DataMissing","",true) +const int HEADLESSSERVER_BROADCAST_SETTINGS_SECONDS = 2; +static const char *HEADLESS_SAVED_SETUP_FILENAME = + "lastHeadlessGameSettings.mgg"; +static const char *LAST_SETUP_STRING = "LastSetup"; +static const char *SETUPS_DIR = GameConstants::folder_path_setups; const int mapPreviewTexture_X = 5; const int mapPreviewTexture_Y = 260; @@ -55,5613 +58,7315 @@ const int mapPreviewTexture_W = 150; const int mapPreviewTexture_H = 150; struct FormatString { - void operator()(string &s) { - s = formatString(s); - } + void operator()(string &s) { s = formatString(s); } }; // ===================================================== // class MenuStateConnectedGame // ===================================================== -MenuStateConnectedGame::MenuStateConnectedGame(Program *program, MainMenu *mainMenu,JoinMenu joinMenuInfo, bool openNetworkSlots) : - MenuState(program, mainMenu, "connected-game"), modHttpServerThread(NULL) -{ - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - containerName = "ClientConnectedGame"; - switchSetupRequestFlagType |= ssrft_NetworkPlayerName; - updateDataSynchDetailText = false; - launchingNewGame = false; - isfirstSwitchingMapMessage = true; - - this->zoomedMap = false; - this->render_mapPreviewTexture_X = mapPreviewTexture_X; - this->render_mapPreviewTexture_Y = mapPreviewTexture_Y; - this->render_mapPreviewTexture_W = mapPreviewTexture_W; - this->render_mapPreviewTexture_H = mapPreviewTexture_H; - - needToBroadcastServerSettings=false; - broadcastServerSettingsDelayTimer=0; - lastGameSettingsReceivedCount=0; - noReceiveTimer=time(NULL)-100; // old but inititialized ( must be an "old" time ) - - soundConnectionCount=0; - - this->factionVideo = NULL; - factionVideoSwitchedOffVolume=false; - currentTechName_factionPreview=""; - currentFactionName_factionPreview=""; - - ftpClientThread = NULL; - ftpMissingDataType = ftpmsg_MissingNone; - getMissingMapFromFTPServer = ""; - getMissingMapFromFTPServerLastPrompted = 0; - getMissingMapFromFTPServerInProgress = false; - getMissingTilesetFromFTPServer = ""; - getMissingTilesetFromFTPServerLastPrompted = 0; - getMissingTilesetFromFTPServerInProgress = false; - getMissingTechtreeFromFTPServer = ""; - getMissingTechtreeFromFTPServerLastPrompted = 0; - getMissingTechtreeFromFTPServerInProgress = false; - - getInProgressSavedGameFromFTPServer = ""; - getInProgressSavedGameFromFTPServerInProgress = false; - readyToJoinInProgressGame = false; - - lastCheckedCRCTilesetName = ""; - lastCheckedCRCTechtreeName = ""; - lastCheckedCRCMapName = ""; - lastCheckedCRCTilesetValue = 0; - lastCheckedCRCTechtreeValue = 0; - lastCheckedCRCMapValue = 0; - - mapPreviewTexture=NULL; - currentFactionLogo = ""; - factionTexture=NULL; - lastMissingMap=""; - lastMissingTechtree =""; - lastMissingTileSet = ""; - - activeInputLabel = NULL; - lastNetworkSendPing = 0; - pingCount = 0; - needToSetChangedGameSettings = false; - lastSetChangedGameSettings = time(NULL); - showFullConsole=false; - - - currentFactionName=""; - currentMap=""; - lastPreviewedMapFile=""; - settingsReceivedFromServer=false; - initialSettingsReceivedFromServer=false; - - validOriginalGameSettings=false; - validDisplayedGamesettings=false; - - returnMenuInfo=joinMenuInfo; - Lang &lang= Lang::getInstance(); - - mainMessageBox.registerGraphicComponent(containerName,"mainMessageBox"); - mainMessageBox.init(lang.getString("Ok")); - mainMessageBox.setEnabled(false); - - ftpMessageBox.registerGraphicComponent(containerName,"ftpMessageBox"); - ftpMessageBox.init(lang.getString("ModCenter"),lang.getString("GameHost")); - ftpMessageBox.addButton(lang.getString("NoDownload")); - ftpMessageBox.setEnabled(false); - - NetworkManager &networkManager= NetworkManager::getInstance(); - Config &config = Config::getInstance(); - defaultPlayerName = config.getString("NetPlayerName",Socket::getHostName().c_str()); - enableFactionTexturePreview = config.getBool("FactionPreview","true"); - enableMapPreview = config.getBool("MapPreview","true"); - - enableScenarioTexturePreview = Config::getInstance().getBool("EnableScenarioTexturePreview","true"); - scenarioLogoTexture=NULL; - previewLoadDelayTimer=time(NULL); - needToLoadTextures=true; - this->dirList = Config::getInstance().getPathListForType(ptScenarios); - - vector techtreesList = Config::getInstance().getPathListForType(ptTechs); - techTree.reset(new TechTree(techtreesList)); - - int labelOffset=22; - int setupPos=650; - int mapHeadPos=mapPreviewTexture_Y+mapPreviewTexture_H; - int mapPos=mapHeadPos-labelOffset; - int aHeadPos=280; - int aPos=aHeadPos-labelOffset; - int networkHeadPos=750-labelOffset; - int xoffset=10; - int currX=0; - int currY=750; - int currXLabel=currX+20; - int lineHeightSmall=18; - - int buttonx=195; - int buttony=180; - - // player status - listBoxPlayerStatus.registerGraphicComponent(containerName,"listBoxPlayerStatus"); - listBoxPlayerStatus.init(buttonx, buttony, 165); - vector playerStatuses; - playerStatuses.push_back(lang.getString("PlayerStatusSetup")); - playerStatuses.push_back(lang.getString("PlayerStatusBeRightBack")); - playerStatuses.push_back(lang.getString("PlayerStatusReady")); - listBoxPlayerStatus.setItems(playerStatuses); - listBoxPlayerStatus.setSelectedItemIndex(2,true); - listBoxPlayerStatus.setTextColor(Vec3f(0.0f,1.0f,0.0f)); - listBoxPlayerStatus.setLighted(false); - listBoxPlayerStatus.setVisible(true); - buttonx+=175; - - buttonDisconnect.registerGraphicComponent(containerName,"buttonDisconnect"); - buttonDisconnect.init(buttonx, buttony, 125); - buttonDisconnect.setText(lang.getString("Return")); - buttonx+=135; - - buttonPlayNow.registerGraphicComponent(containerName,"buttonPlayNow"); - buttonPlayNow.init(buttonx, buttony, 125); - buttonPlayNow.setText(lang.getString("PlayNow")); - buttonPlayNow.setVisible(false); - - // network options - currY=680; - currX=390; - currXLabel=currX+20; - - vector rMultiplier; - for(int i=0; i<45; ++i){ - rMultiplier.push_back(floatToStr(0.5f+0.1f*i,1)); - } - listBoxFallbackCpuMultiplier.registerGraphicComponent(containerName,"listBoxFallbackCpuMultiplier"); - listBoxFallbackCpuMultiplier.init(currX-44, currY+2, 60,16); - listBoxFallbackCpuMultiplier.setItems(rMultiplier); - listBoxFallbackCpuMultiplier.setSelectedItem("1.5"); - labelFallbackCpuMultiplier.registerGraphicComponent(containerName,"labelFallbackCpuMultiplier"); - labelFallbackCpuMultiplier.init(currXLabel, currY, 80); - labelFallbackCpuMultiplier.setText(lang.getString("FallbackCpuMultiplier")); - setSmallFont(labelAllowNativeLanguageTechtree); - currY = currY - lineHeightSmall; - - xoffset=65; - // MapFilter - labelMapFilter.registerGraphicComponent(containerName,"labelMapFilter"); - labelMapFilter.init(xoffset+525, mapHeadPos); - labelMapFilter.setText(lang.getString("MapFilter")); - labelMapFilter.setVisible(false); - - labelMap.registerGraphicComponent(containerName,"labelMap"); - labelMap.init(xoffset+100, mapPos+20); - labelMap.setText(lang.getString("Map")); - - //Map Filter - listBoxMapFilter.registerGraphicComponent(containerName,"listBoxMapFilter"); - listBoxMapFilter.init(xoffset+260, mapPos+labelOffset, 60); - listBoxMapFilter.pushBackItem("-"); - for(int i=1; i 0) { - listBoxTechTree.setSelectedItemIndex(initialTechSelection); - } - - labelTileset.registerGraphicComponent(containerName,"labelTileset"); - labelTileset.init(xoffset+325, mapHeadPos-44); - labelTileset.setText(lang.getString("Tileset")); - - //tileset listBox - listBoxTileset.registerGraphicComponent(containerName,"listBoxTileset"); - listBoxTileset.init(xoffset+325, mapPos-44, 180); - - setupTilesetList(""); - Chrono seed(true); - srand((unsigned int)seed.getCurTicks()); - - listBoxTileset.setSelectedItemIndex(rand() % listBoxTileset.getItemCount()); - - // Save Setup - currY=mapHeadPos-100; - currX=xoffset+325; - - comboBoxLoadSetup.registerGraphicComponent(containerName,"comboBoxLoadSetup"); - comboBoxLoadSetup.init(currX, currY, 220); - loadSavedSetupNames(); - comboBoxLoadSetup.setItems(savedSetupFilenames); - - currY = currY - labelOffset; - - buttonDeleteSetup.registerGraphicComponent(containerName,"buttonDeleteSetup"); - buttonDeleteSetup.init(currX, currY, 110); - buttonDeleteSetup.setText(lang.getString("Delete")); - buttonLoadSetup.registerGraphicComponent(containerName,"buttonLoadSetup"); - buttonLoadSetup.init(currX+110, currY, 110); - buttonLoadSetup.setText(lang.getString("Load")); - - currY = currY - labelOffset; - - labelSaveSetupName.registerGraphicComponent(containerName,"labelSaveSetupName"); - labelSaveSetupName.init(currX,currY, 110); - labelSaveSetupName.setText(""); - labelSaveSetupName.setEditable(true); - labelSaveSetupName.setMaxEditWidth(16); - labelSaveSetupName.setMaxEditRenderWidth(labelSaveSetupName.getW()); - labelSaveSetupName.setBackgroundColor(Vec4f(230,230,230,0.4)); - labelSaveSetupName.setRenderBackground(true); - - buttonSaveSetup.registerGraphicComponent(containerName,"buttonSaveSetup"); - buttonSaveSetup.init(currX+110, currY, 110); - buttonSaveSetup.setText(lang.getString("Save")); - - - // Toy Block - currY=mapHeadPos; - currX=750; - currXLabel=currX+20; - - checkBoxAllowTeamUnitSharing.registerGraphicComponent(containerName,"checkBoxAllowTeamUnitSharing"); - checkBoxAllowTeamUnitSharing.init(currX, currY+2,16,16); - checkBoxAllowTeamUnitSharing.setValue(false); - checkBoxAllowTeamUnitSharing.setVisible(true); - - labelAllowTeamUnitSharing.registerGraphicComponent(containerName,"labelAllowTeamUnitSharing"); - labelAllowTeamUnitSharing.init(currXLabel, currY, 80); - labelAllowTeamUnitSharing.setText(lang.getString("AllowTeamUnitSharing")); - labelAllowTeamUnitSharing.setVisible(true); - setSmallFont(labelAllowTeamUnitSharing); - currY = currY - lineHeightSmall; - - checkBoxAllowTeamResourceSharing.registerGraphicComponent(containerName,"checkBoxAllowTeamResourceSharing"); - checkBoxAllowTeamResourceSharing.init(currX, currY+2,16,16); - checkBoxAllowTeamResourceSharing.setValue(false); - checkBoxAllowTeamResourceSharing.setVisible(true); - labelAllowTeamResourceSharing.registerGraphicComponent(containerName,"labelAllowTeamResourceSharing"); - labelAllowTeamResourceSharing.init(currXLabel, currY, 80); - labelAllowTeamResourceSharing.setText(lang.getString("AllowTeamResourceSharing")); - labelAllowTeamResourceSharing.setVisible(true); - setSmallFont(labelAllowTeamResourceSharing); - currY = currY - lineHeightSmall; - - checkBoxAllowNativeLanguageTechtree.registerGraphicComponent(containerName,"checkBoxAllowNativeLanguageTechtree"); - checkBoxAllowNativeLanguageTechtree.init(currX, currY+2,16,16); - checkBoxAllowNativeLanguageTechtree.setValue(false); - - labelAllowNativeLanguageTechtree.registerGraphicComponent(containerName,"labelAllowNativeLanguageTechtree"); - labelAllowNativeLanguageTechtree.init(currXLabel, currY, 80); - labelAllowNativeLanguageTechtree.setText(lang.getString("AllowNativeLanguageTechtree")); - setSmallFont(labelAllowNativeLanguageTechtree); - currY = currY - lineHeightSmall; - - // Allow Observers - checkBoxAllowObservers.registerGraphicComponent(containerName,"checkBoxAllowObservers"); - checkBoxAllowObservers.init(currX, currY+2,16,16); - checkBoxAllowObservers.setValue(true); - - labelAllowObservers.registerGraphicComponent(containerName,"labelAllowObservers"); - labelAllowObservers.init(currXLabel, currY, 80); - labelAllowObservers.setText(lang.getString("AllowObservers")); - setSmallFont(labelAllowNativeLanguageTechtree); - currY = currY - lineHeightSmall; - - checkBoxEnableSwitchTeamMode.registerGraphicComponent(containerName,"checkBoxEnableSwitchTeamMode"); - checkBoxEnableSwitchTeamMode.init(currX, currY+2,16,16); - checkBoxEnableSwitchTeamMode.setValue(false); - labelEnableSwitchTeamMode.registerGraphicComponent(containerName,"labelEnableSwitchTeamMode"); - labelEnableSwitchTeamMode.init(currXLabel, currY); - labelEnableSwitchTeamMode.setText(lang.getString("EnableSwitchTeamMode")); - setSmallFont(labelEnableSwitchTeamMode); - currY=currY-lineHeightSmall; - - listBoxAISwitchTeamAcceptPercent.registerGraphicComponent(containerName,"listBoxAISwitchTeamAcceptPercent"); - listBoxAISwitchTeamAcceptPercent.init(currX-44, currY+2, 60,16); - for(int i = 0; i <= 100; i = i + 10) { - listBoxAISwitchTeamAcceptPercent.pushBackItem(intToStr(i)); - } - listBoxAISwitchTeamAcceptPercent.setSelectedItem(intToStr(30)); - listBoxAISwitchTeamAcceptPercent.setVisible(false); - labelAISwitchTeamAcceptPercent.registerGraphicComponent(containerName,"labelAISwitchTeamAcceptPercent"); - labelAISwitchTeamAcceptPercent.init(currXLabel, currY, 80); - labelAISwitchTeamAcceptPercent.setText(lang.getString("AISwitchTeamAcceptPercent")); - labelAISwitchTeamAcceptPercent.setVisible(false); - setSmallFont(labelEnableSwitchTeamMode); - currY=currY-lineHeightSmall; - - // Network Scenario - checkBoxScenario.registerGraphicComponent(containerName,"checkBoxScenario"); - checkBoxScenario.init(currX, currY+2,16,16); - checkBoxScenario.setValue(false); - labelScenario.registerGraphicComponent(containerName,"labelScenario"); - labelScenario.init(currXLabel, currY); - labelScenario.setText(lang.getString("NetworkScenarios")); - setSmallFont(labelAllowNativeLanguageTechtree); - currY = currY - lineHeightSmall; - listBoxScenario.registerGraphicComponent(containerName,"listBoxScenario"); - listBoxScenario.init(currX, currY,190,16); - - //scenario listbox - vector resultsScenarios; - findDirs(dirList, resultsScenarios); - // Filter out only scenarios with no network slots - for(int i= 0; i < (int)resultsScenarios.size(); ++i) { - string scenario = resultsScenarios[i]; - string file = Scenario::getScenarioPath(dirList, scenario); - - try { - if(file != "") { - bool isTutorial = Scenario::isGameTutorial(file); - Scenario::loadScenarioInfo(file, &scenarioInfo, isTutorial); - - bool isNetworkScenario = false; - for(unsigned int j = 0; isNetworkScenario == false && j < (unsigned int)GameConstants::maxPlayers; ++j) { - if(scenarioInfo.factionControls[j] == ctNetwork) { - isNetworkScenario = true; - } - } - if(isNetworkScenario == true) { - scenarioFiles.push_back(scenario); - } - } - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - 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()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - - showMessageBox( szBuf, "Error", false); - } - } - resultsScenarios.clear(); - for(int i = 0; i < (int)scenarioFiles.size(); ++i) { - resultsScenarios.push_back(formatString(scenarioFiles[i])); - } - listBoxScenario.setItems(resultsScenarios); - if(resultsScenarios.empty() == true) { - checkBoxScenario.setEnabled(false); - } - - //state - labelStatus.registerGraphicComponent(containerName,"labelStatus"); - labelStatus.init(30, networkHeadPos); - labelStatus.setText(""); - - labelInfo.registerGraphicComponent(containerName,"labelInfo"); - labelInfo.init(30, networkHeadPos+30); - labelInfo.setText(""); - labelInfo.setFont(CoreData::getInstance().getMenuFontBig()); - labelInfo.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - - labelWaitingForPlayers.registerGraphicComponent(containerName,"labelInfo"); - labelWaitingForPlayers.init(0, networkHeadPos-25); - labelWaitingForPlayers.setText(""); - labelWaitingForPlayers.setFont(CoreData::getInstance().getMenuFontBig()); - labelWaitingForPlayers.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - labelWaitingForPlayers.setTextColor(Vec3f(1.0f,1.0f,0.f)); - - timerLabelFlash = time(NULL); - labelDataSynchInfo.registerGraphicComponent(containerName,"labelDataSynchInfo"); - labelDataSynchInfo.init(30, networkHeadPos-60); - labelDataSynchInfo.setText(""); - labelDataSynchInfo.setFont(CoreData::getInstance().getMenuFontBig()); - labelDataSynchInfo.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - - for(int i=0; i<45; ++i){ - rMultiplier.push_back(floatToStr(0.5f+0.1f*i,1)); - } - - //create - buttonCancelDownloads.registerGraphicComponent(containerName,"buttonCancelDownloads"); - buttonCancelDownloads.init(xoffset+620, 180, 150); - buttonCancelDownloads.setText(lang.getString("CancelDownloads")); - - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - xoffset=5; - int rowHeight=22; - for(int i=0; izoomedMap = false; + this->render_mapPreviewTexture_X = mapPreviewTexture_X; + this->render_mapPreviewTexture_Y = mapPreviewTexture_Y; + this->render_mapPreviewTexture_W = mapPreviewTexture_W; + this->render_mapPreviewTexture_H = mapPreviewTexture_H; + + needToBroadcastServerSettings = false; + broadcastServerSettingsDelayTimer = 0; + lastGameSettingsReceivedCount = 0; + noReceiveTimer = + time(NULL) - 100; // old but inititialized ( must be an "old" time ) + + soundConnectionCount = 0; + + this->factionVideo = NULL; + factionVideoSwitchedOffVolume = false; + currentTechName_factionPreview = ""; + currentFactionName_factionPreview = ""; + + ftpClientThread = NULL; + ftpMissingDataType = ftpmsg_MissingNone; + getMissingMapFromFTPServer = ""; + getMissingMapFromFTPServerLastPrompted = 0; + getMissingMapFromFTPServerInProgress = false; + getMissingTilesetFromFTPServer = ""; + getMissingTilesetFromFTPServerLastPrompted = 0; + getMissingTilesetFromFTPServerInProgress = false; + getMissingTechtreeFromFTPServer = ""; + getMissingTechtreeFromFTPServerLastPrompted = 0; + getMissingTechtreeFromFTPServerInProgress = false; + + getInProgressSavedGameFromFTPServer = ""; + getInProgressSavedGameFromFTPServerInProgress = false; + readyToJoinInProgressGame = false; + + lastCheckedCRCTilesetName = ""; + lastCheckedCRCTechtreeName = ""; + lastCheckedCRCMapName = ""; + lastCheckedCRCTilesetValue = 0; + lastCheckedCRCTechtreeValue = 0; + lastCheckedCRCMapValue = 0; + + mapPreviewTexture = NULL; + currentFactionLogo = ""; + factionTexture = NULL; + lastMissingMap = ""; + lastMissingTechtree = ""; + lastMissingTileSet = ""; + + activeInputLabel = NULL; + lastNetworkSendPing = 0; + pingCount = 0; + needToSetChangedGameSettings = false; + lastSetChangedGameSettings = time(NULL); + showFullConsole = false; + + currentFactionName = ""; + currentMap = ""; + lastPreviewedMapFile = ""; + settingsReceivedFromServer = false; + initialSettingsReceivedFromServer = false; + + validOriginalGameSettings = false; + validDisplayedGamesettings = false; + + returnMenuInfo = joinMenuInfo; + Lang &lang = Lang::getInstance(); + + mainMessageBox.registerGraphicComponent(containerName, "mainMessageBox"); + mainMessageBox.init(lang.getString("Ok")); + mainMessageBox.setEnabled(false); + + ftpMessageBox.registerGraphicComponent(containerName, "ftpMessageBox"); + ftpMessageBox.init(lang.getString("ModCenter"), lang.getString("GameHost")); + ftpMessageBox.addButton(lang.getString("NoDownload")); + ftpMessageBox.setEnabled(false); + + NetworkManager &networkManager = NetworkManager::getInstance(); + Config &config = Config::getInstance(); + defaultPlayerName = + config.getString("NetPlayerName", Socket::getHostName().c_str()); + enableFactionTexturePreview = config.getBool("FactionPreview", "true"); + enableMapPreview = config.getBool("MapPreview", "true"); + + enableScenarioTexturePreview = + Config::getInstance().getBool("EnableScenarioTexturePreview", "true"); + scenarioLogoTexture = NULL; + previewLoadDelayTimer = time(NULL); + needToLoadTextures = true; + this->dirList = Config::getInstance().getPathListForType(ptScenarios); + + vector techtreesList = + Config::getInstance().getPathListForType(ptTechs); + techTree.reset(new TechTree(techtreesList)); + + int labelOffset = 22; + int setupPos = 650; + int mapHeadPos = mapPreviewTexture_Y + mapPreviewTexture_H; + int mapPos = mapHeadPos - labelOffset; + int aHeadPos = 280; + int aPos = aHeadPos - labelOffset; + int networkHeadPos = 750 - labelOffset; + int xoffset = 10; + int currX = 0; + int currY = 750; + int currXLabel = currX + 20; + int lineHeightSmall = 18; + + int buttonx = 195; + int buttony = 180; + + // player status + listBoxPlayerStatus.registerGraphicComponent(containerName, + "listBoxPlayerStatus"); + listBoxPlayerStatus.init(buttonx, buttony, 165); + vector playerStatuses; + playerStatuses.push_back(lang.getString("PlayerStatusSetup")); + playerStatuses.push_back(lang.getString("PlayerStatusBeRightBack")); + playerStatuses.push_back(lang.getString("PlayerStatusReady")); + listBoxPlayerStatus.setItems(playerStatuses); + listBoxPlayerStatus.setSelectedItemIndex(2, true); + listBoxPlayerStatus.setTextColor(Vec3f(0.0f, 1.0f, 0.0f)); + listBoxPlayerStatus.setLighted(false); + listBoxPlayerStatus.setVisible(true); + buttonx += 175; + + buttonDisconnect.registerGraphicComponent(containerName, "buttonDisconnect"); + buttonDisconnect.init(buttonx, buttony, 125); + buttonDisconnect.setText(lang.getString("Return")); + buttonx += 135; + + buttonPlayNow.registerGraphicComponent(containerName, "buttonPlayNow"); + buttonPlayNow.init(buttonx, buttony, 125); + buttonPlayNow.setText(lang.getString("PlayNow")); + buttonPlayNow.setVisible(false); + + // network options + currY = 680; + currX = 390; + currXLabel = currX + 20; + + vector rMultiplier; + for (int i = 0; i < 45; ++i) { + rMultiplier.push_back(floatToStr(0.5f + 0.1f * i, 1)); + } + listBoxFallbackCpuMultiplier.registerGraphicComponent( + containerName, "listBoxFallbackCpuMultiplier"); + listBoxFallbackCpuMultiplier.init(currX - 44, currY + 2, 60, 16); + listBoxFallbackCpuMultiplier.setItems(rMultiplier); + listBoxFallbackCpuMultiplier.setSelectedItem("1.5"); + labelFallbackCpuMultiplier.registerGraphicComponent( + containerName, "labelFallbackCpuMultiplier"); + labelFallbackCpuMultiplier.init(currXLabel, currY, 80); + labelFallbackCpuMultiplier.setText(lang.getString("FallbackCpuMultiplier")); + setSmallFont(labelAllowNativeLanguageTechtree); + currY = currY - lineHeightSmall; + + xoffset = 65; + // MapFilter + labelMapFilter.registerGraphicComponent(containerName, "labelMapFilter"); + labelMapFilter.init(xoffset + 525, mapHeadPos); + labelMapFilter.setText(lang.getString("MapFilter")); + labelMapFilter.setVisible(false); + + labelMap.registerGraphicComponent(containerName, "labelMap"); + labelMap.init(xoffset + 100, mapPos + 20); + labelMap.setText(lang.getString("Map")); + + // Map Filter + listBoxMapFilter.registerGraphicComponent(containerName, "listBoxMapFilter"); + listBoxMapFilter.init(xoffset + 260, mapPos + labelOffset, 60); + listBoxMapFilter.pushBackItem("-"); + for (int i = 1; i < GameConstants::maxPlayers + 1; ++i) { + listBoxMapFilter.pushBackItem(intToStr(i)); + } + listBoxMapFilter.setSelectedItemIndex(0); + + // map listBox + comboBoxMap.registerGraphicComponent(containerName, "listBoxMap"); + comboBoxMap.init(xoffset + 100, mapPos, 220); + // put them all in a set, to weed out duplicates (gbm & mgm with same name) + // will also ensure they are alphabetically listed (rather than how the OS + // provides them) + int initialMapSelection = setupMapList(""); + comboBoxMap.setItems(formattedPlayerSortedMaps[0]); + comboBoxMap.setSelectedItemIndex(initialMapSelection); + + labelMapInfo.registerGraphicComponent(containerName, "labelMapInfo"); + labelMapInfo.init(xoffset + 100, mapPos - labelOffset - 10, 200, + 40); // position is set by update() ! + setSmallFont(labelMapInfo); + + // fog - o - war + // @350 ? 300 ? + labelFogOfWar.registerGraphicComponent(containerName, "labelFogOfWar"); + labelFogOfWar.init(xoffset + 100, aHeadPos, 165); + labelFogOfWar.setText(lang.getString("FogOfWar")); + + listBoxFogOfWar.registerGraphicComponent(containerName, "listBoxFogOfWar"); + listBoxFogOfWar.init(xoffset + 100, aPos, 165); + listBoxFogOfWar.pushBackItem(lang.getString("Enabled")); + listBoxFogOfWar.pushBackItem(lang.getString("Explored")); + listBoxFogOfWar.pushBackItem(lang.getString("Disabled")); + listBoxFogOfWar.setSelectedItemIndex(0); + + // tech Tree listBox + labelTechTree.registerGraphicComponent(containerName, "labelTechTree"); + labelTechTree.init(xoffset + 325, mapHeadPos); + labelTechTree.setText(lang.getString("TechTree")); + + int initialTechSelection = setupTechList("", true); + listBoxTechTree.registerGraphicComponent(containerName, "listBoxTechTree"); + listBoxTechTree.init(xoffset + 325, mapPos, 180); + if (listBoxTechTree.getItemCount() > 0) { + listBoxTechTree.setSelectedItemIndex(initialTechSelection); + } + + labelTileset.registerGraphicComponent(containerName, "labelTileset"); + labelTileset.init(xoffset + 325, mapHeadPos - 44); + labelTileset.setText(lang.getString("Tileset")); + + // tileset listBox + listBoxTileset.registerGraphicComponent(containerName, "listBoxTileset"); + listBoxTileset.init(xoffset + 325, mapPos - 44, 180); + + setupTilesetList(""); + Chrono seed(true); + srand((unsigned int)seed.getCurTicks()); + + listBoxTileset.setSelectedItemIndex(rand() % listBoxTileset.getItemCount()); + + // Save Setup + currY = mapHeadPos - 100; + currX = xoffset + 325; + + comboBoxLoadSetup.registerGraphicComponent(containerName, + "comboBoxLoadSetup"); + comboBoxLoadSetup.init(currX, currY, 220); + loadSavedSetupNames(); + comboBoxLoadSetup.setItems(savedSetupFilenames); + + currY = currY - labelOffset; + + buttonDeleteSetup.registerGraphicComponent(containerName, + "buttonDeleteSetup"); + buttonDeleteSetup.init(currX, currY, 110); + buttonDeleteSetup.setText(lang.getString("Delete")); + buttonLoadSetup.registerGraphicComponent(containerName, "buttonLoadSetup"); + buttonLoadSetup.init(currX + 110, currY, 110); + buttonLoadSetup.setText(lang.getString("Load")); + + currY = currY - labelOffset; + + labelSaveSetupName.registerGraphicComponent(containerName, + "labelSaveSetupName"); + labelSaveSetupName.init(currX, currY, 110); + labelSaveSetupName.setText(""); + labelSaveSetupName.setEditable(true); + labelSaveSetupName.setMaxEditWidth(16); + labelSaveSetupName.setMaxEditRenderWidth(labelSaveSetupName.getW()); + labelSaveSetupName.setBackgroundColor(Vec4f(230, 230, 230, 0.4)); + labelSaveSetupName.setRenderBackground(true); + + buttonSaveSetup.registerGraphicComponent(containerName, "buttonSaveSetup"); + buttonSaveSetup.init(currX + 110, currY, 110); + buttonSaveSetup.setText(lang.getString("Save")); + + // Toy Block + currY = mapHeadPos; + currX = 750; + currXLabel = currX + 20; + + checkBoxAllowTeamUnitSharing.registerGraphicComponent( + containerName, "checkBoxAllowTeamUnitSharing"); + checkBoxAllowTeamUnitSharing.init(currX, currY + 2, 16, 16); + checkBoxAllowTeamUnitSharing.setValue(false); + checkBoxAllowTeamUnitSharing.setVisible(true); + + labelAllowTeamUnitSharing.registerGraphicComponent( + containerName, "labelAllowTeamUnitSharing"); + labelAllowTeamUnitSharing.init(currXLabel, currY, 80); + labelAllowTeamUnitSharing.setText(lang.getString("AllowTeamUnitSharing")); + labelAllowTeamUnitSharing.setVisible(true); + setSmallFont(labelAllowTeamUnitSharing); + currY = currY - lineHeightSmall; + + checkBoxAllowTeamResourceSharing.registerGraphicComponent( + containerName, "checkBoxAllowTeamResourceSharing"); + checkBoxAllowTeamResourceSharing.init(currX, currY + 2, 16, 16); + checkBoxAllowTeamResourceSharing.setValue(false); + checkBoxAllowTeamResourceSharing.setVisible(true); + labelAllowTeamResourceSharing.registerGraphicComponent( + containerName, "labelAllowTeamResourceSharing"); + labelAllowTeamResourceSharing.init(currXLabel, currY, 80); + labelAllowTeamResourceSharing.setText( + lang.getString("AllowTeamResourceSharing")); + labelAllowTeamResourceSharing.setVisible(true); + setSmallFont(labelAllowTeamResourceSharing); + currY = currY - lineHeightSmall; + + checkBoxAllowNativeLanguageTechtree.registerGraphicComponent( + containerName, "checkBoxAllowNativeLanguageTechtree"); + checkBoxAllowNativeLanguageTechtree.init(currX, currY + 2, 16, 16); + checkBoxAllowNativeLanguageTechtree.setValue(false); + + labelAllowNativeLanguageTechtree.registerGraphicComponent( + containerName, "labelAllowNativeLanguageTechtree"); + labelAllowNativeLanguageTechtree.init(currXLabel, currY, 80); + labelAllowNativeLanguageTechtree.setText( + lang.getString("AllowNativeLanguageTechtree")); + setSmallFont(labelAllowNativeLanguageTechtree); + currY = currY - lineHeightSmall; + + // Allow Observers + checkBoxAllowObservers.registerGraphicComponent(containerName, + "checkBoxAllowObservers"); + checkBoxAllowObservers.init(currX, currY + 2, 16, 16); + checkBoxAllowObservers.setValue(true); + + labelAllowObservers.registerGraphicComponent(containerName, + "labelAllowObservers"); + labelAllowObservers.init(currXLabel, currY, 80); + labelAllowObservers.setText(lang.getString("AllowObservers")); + setSmallFont(labelAllowNativeLanguageTechtree); + currY = currY - lineHeightSmall; + + checkBoxEnableSwitchTeamMode.registerGraphicComponent( + containerName, "checkBoxEnableSwitchTeamMode"); + checkBoxEnableSwitchTeamMode.init(currX, currY + 2, 16, 16); + checkBoxEnableSwitchTeamMode.setValue(false); + labelEnableSwitchTeamMode.registerGraphicComponent( + containerName, "labelEnableSwitchTeamMode"); + labelEnableSwitchTeamMode.init(currXLabel, currY); + labelEnableSwitchTeamMode.setText(lang.getString("EnableSwitchTeamMode")); + setSmallFont(labelEnableSwitchTeamMode); + currY = currY - lineHeightSmall; + + listBoxAISwitchTeamAcceptPercent.registerGraphicComponent( + containerName, "listBoxAISwitchTeamAcceptPercent"); + listBoxAISwitchTeamAcceptPercent.init(currX - 44, currY + 2, 60, 16); + for (int i = 0; i <= 100; i = i + 10) { + listBoxAISwitchTeamAcceptPercent.pushBackItem(intToStr(i)); + } + listBoxAISwitchTeamAcceptPercent.setSelectedItem(intToStr(30)); + listBoxAISwitchTeamAcceptPercent.setVisible(false); + labelAISwitchTeamAcceptPercent.registerGraphicComponent( + containerName, "labelAISwitchTeamAcceptPercent"); + labelAISwitchTeamAcceptPercent.init(currXLabel, currY, 80); + labelAISwitchTeamAcceptPercent.setText( + lang.getString("AISwitchTeamAcceptPercent")); + labelAISwitchTeamAcceptPercent.setVisible(false); + setSmallFont(labelEnableSwitchTeamMode); + currY = currY - lineHeightSmall; + + // Network Scenario + checkBoxScenario.registerGraphicComponent(containerName, "checkBoxScenario"); + checkBoxScenario.init(currX, currY + 2, 16, 16); + checkBoxScenario.setValue(false); + labelScenario.registerGraphicComponent(containerName, "labelScenario"); + labelScenario.init(currXLabel, currY); + labelScenario.setText(lang.getString("NetworkScenarios")); + setSmallFont(labelAllowNativeLanguageTechtree); + currY = currY - lineHeightSmall; + listBoxScenario.registerGraphicComponent(containerName, "listBoxScenario"); + listBoxScenario.init(currX, currY, 190, 16); + + // scenario listbox + vector resultsScenarios; + findDirs(dirList, resultsScenarios); + // Filter out only scenarios with no network slots + for (int i = 0; i < (int)resultsScenarios.size(); ++i) { + string scenario = resultsScenarios[i]; + string file = Scenario::getScenarioPath(dirList, scenario); - labelNetStatus[i].registerGraphicComponent(containerName,"labelNetStatus" + intToStr(i)); - labelNetStatus[i].init(xoffset+623, setupPos-30-i*rowHeight, 60); - labelNetStatus[i].setFont(CoreData::getInstance().getDisplayFontSmall()); - labelNetStatus[i].setFont3D(CoreData::getInstance().getDisplayFontSmall3D()); - - grabSlotButton[i].registerGraphicComponent(containerName,"grabSlotButton" + intToStr(i)); - grabSlotButton[i].init(xoffset+626, setupPos-30-i*rowHeight, 35, rowHeight-5); - grabSlotButton[i].setText(">"); + try { + if (file != "") { + bool isTutorial = Scenario::isGameTutorial(file); + Scenario::loadScenarioInfo(file, &scenarioInfo, isTutorial); + + bool isNetworkScenario = false; + for (unsigned int j = 0; isNetworkScenario == false && + j < (unsigned int)GameConstants::maxPlayers; + ++j) { + if (scenarioInfo.factionControls[j] == ctNetwork) { + isNetworkScenario = true; + } + } + if (isNetworkScenario == true) { + scenarioFiles.push_back(scenario); + } + } + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + 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()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + showMessageBox(szBuf, "Error", false); } - - labelControl.registerGraphicComponent(containerName,"labelControl"); - labelControl.init(xoffset+160, setupPos, 50, GraphicListBox::defH, true); - labelControl.setText(lang.getString("Control")); - - labelRMultiplier.registerGraphicComponent(containerName,"labelRMultiplier"); - labelRMultiplier.init(xoffset+310, setupPos, 50, GraphicListBox::defH, true); - - labelFaction.registerGraphicComponent(containerName,"labelFaction"); - labelFaction.init(xoffset+411, setupPos, 50, GraphicListBox::defH, true); - labelFaction.setText(lang.getString("Faction")); - - labelTeam.registerGraphicComponent(containerName,"labelTeam"); - labelTeam.init(xoffset+560, setupPos, 50, GraphicListBox::defH, true); - labelTeam.setText(lang.getString("Team")); - - labelControl.setFont(CoreData::getInstance().getMenuFontBig()); - labelControl.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - labelFaction.setFont(CoreData::getInstance().getMenuFontBig()); - labelFaction.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - labelTeam.setFont(CoreData::getInstance().getMenuFontBig()); - labelTeam.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - - //texts - buttonDisconnect.setText(lang.getString("Return")); - - vector controlItems; - controlItems.push_back(lang.getString("Closed")); - controlItems.push_back(lang.getString("CpuEasy")); - controlItems.push_back(lang.getString("Cpu")); - controlItems.push_back(lang.getString("CpuUltra")); - controlItems.push_back(lang.getString("CpuMega")); - controlItems.push_back(lang.getString("Network")); - controlItems.push_back(lang.getString("NetworkUnassigned")); - controlItems.push_back(lang.getString("Human")); - - - if(config.getBool("EnableNetworkCpu","false") == true) { - controlItems.push_back(lang.getString("NetworkCpuEasy")); - controlItems.push_back(lang.getString("NetworkCpu")); - controlItems.push_back(lang.getString("NetworkCpuUltra")); - controlItems.push_back(lang.getString("NetworkCpuMega")); - } - - vector teamItems; - for(int i = 1; i <= GameConstants::maxPlayers; ++i) { - teamItems.push_back(intToStr(i)); - } - for(int i = GameConstants::maxPlayers + 1; i <= GameConstants::maxPlayers + GameConstants::specialFactions; ++i) { - teamItems.push_back(intToStr(i)); - } - - for(int i=0; i"); + } + + labelControl.registerGraphicComponent(containerName, "labelControl"); + labelControl.init(xoffset + 160, setupPos, 50, GraphicListBox::defH, true); + labelControl.setText(lang.getString("Control")); + + labelRMultiplier.registerGraphicComponent(containerName, "labelRMultiplier"); + labelRMultiplier.init(xoffset + 310, setupPos, 50, GraphicListBox::defH, + true); + + labelFaction.registerGraphicComponent(containerName, "labelFaction"); + labelFaction.init(xoffset + 411, setupPos, 50, GraphicListBox::defH, true); + labelFaction.setText(lang.getString("Faction")); + + labelTeam.registerGraphicComponent(containerName, "labelTeam"); + labelTeam.init(xoffset + 560, setupPos, 50, GraphicListBox::defH, true); + labelTeam.setText(lang.getString("Team")); + + labelControl.setFont(CoreData::getInstance().getMenuFontBig()); + labelControl.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + labelFaction.setFont(CoreData::getInstance().getMenuFontBig()); + labelFaction.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + labelTeam.setFont(CoreData::getInstance().getMenuFontBig()); + labelTeam.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + + // texts + buttonDisconnect.setText(lang.getString("Return")); + + vector controlItems; + controlItems.push_back(lang.getString("Closed")); + controlItems.push_back(lang.getString("CpuEasy")); + controlItems.push_back(lang.getString("Cpu")); + controlItems.push_back(lang.getString("CpuUltra")); + controlItems.push_back(lang.getString("CpuMega")); + controlItems.push_back(lang.getString("Network")); + controlItems.push_back(lang.getString("NetworkUnassigned")); + controlItems.push_back(lang.getString("Human")); + + if (config.getBool("EnableNetworkCpu", "false") == true) { + controlItems.push_back(lang.getString("NetworkCpuEasy")); + controlItems.push_back(lang.getString("NetworkCpu")); + controlItems.push_back(lang.getString("NetworkCpuUltra")); + controlItems.push_back(lang.getString("NetworkCpuMega")); + } + + vector teamItems; + for (int i = 1; i <= GameConstants::maxPlayers; ++i) { + teamItems.push_back(intToStr(i)); + } + for (int i = GameConstants::maxPlayers + 1; + i <= GameConstants::maxPlayers + GameConstants::specialFactions; ++i) { + teamItems.push_back(intToStr(i)); + } + + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + labelPlayerStatus[i].setText(""); + labelPlayerStatus[i].setTexture(NULL); + labelPlayerStatus[i].setH(16); + labelPlayerStatus[i].setW(12); + + labelPlayers[i].setText(intToStr(i + 1)); + labelPlayerNames[i].setText(""); + labelPlayerNames[i].setMaxEditWidth(16); + labelPlayerNames[i].setMaxEditRenderWidth(127); + + listBoxTeams[i].setItems(teamItems); + listBoxTeams[i].setSelectedItemIndex(i); + listBoxControls[i].setItems(controlItems); + listBoxRMultiplier[i].setItems(rMultiplier); + listBoxRMultiplier[i].setSelectedItem("1.0"); + + labelNetStatus[i].setText("V"); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // init controllers + listBoxControls[0].setSelectedItemIndex(ctHuman); + + // map listBox + // put them all in a set, to weed out duplicates (gbm & mgm with same name) + // will also ensure they are alphabetically listed (rather than how the OS + // provides them) + setupMapList(""); + comboBoxMap.setItems(formattedPlayerSortedMaps[0]); + + // write hint to console: + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + + console.addLine(lang.getString("ToSwitchOffMusicPress") + " - \"" + + configKeys.getString("ToggleMusic") + "\""); + chatManager.init(&console, -1, true); + + GraphicComponent::applyAllCustomProperties(containerName); + + if (config.getBool("EnableFTPXfer", "true") == true) { + ClientInterface *clientInterface = networkManager.getClientInterface(); + string serverUrl = clientInterface->getServerIpAddress(); + int portNumber = clientInterface->getServerFTPPort(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d] Using FTP port #: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, portNumber); + + vector mapPathList = config.getPathListForType(ptMaps); + std::pair mapsPath; + if (mapPathList.empty() == false) { + mapsPath.first = mapPathList[0]; + } + if (mapPathList.size() > 1) { + mapsPath.second = mapPathList[1]; + } + std::pair tilesetsPath; + vector tilesetsList = + Config::getInstance().getPathListForType(ptTilesets); + if (tilesetsList.empty() == false) { + tilesetsPath.first = tilesetsList[0]; + if (tilesetsList.size() > 1) { + tilesetsPath.second = tilesetsList[1]; + } } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //init controllers - listBoxControls[0].setSelectedItemIndex(ctHuman); - - - //map listBox - // put them all in a set, to weed out duplicates (gbm & mgm with same name) - // will also ensure they are alphabetically listed (rather than how the OS provides them) - setupMapList(""); - comboBoxMap.setItems(formattedPlayerSortedMaps[0]); - - - // write hint to console: - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - - console.addLine(lang.getString("ToSwitchOffMusicPress") + " - \"" + configKeys.getString("ToggleMusic") + "\""); - chatManager.init(&console, -1,true); - - GraphicComponent::applyAllCustomProperties(containerName); - - if(config.getBool("EnableFTPXfer","true") == true) { - ClientInterface *clientInterface = networkManager.getClientInterface(); - string serverUrl = clientInterface->getServerIpAddress(); - int portNumber = clientInterface->getServerFTPPort(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] Using FTP port #: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,portNumber); + std::pair techtreesPath; + if (techtreesList.empty() == false) { + techtreesPath.first = techtreesList[0]; + if (techtreesList.size() > 1) { + techtreesPath.second = techtreesList[1]; + } + } - vector mapPathList = config.getPathListForType(ptMaps); - std::pair mapsPath; - if(mapPathList.empty() == false) { - mapsPath.first = mapPathList[0]; - } - if(mapPathList.size() > 1) { - mapsPath.second = mapPathList[1]; - } - std::pair tilesetsPath; - vector tilesetsList = Config::getInstance().getPathListForType(ptTilesets); - if(tilesetsList.empty() == false) { - tilesetsPath.first = tilesetsList[0]; - if(tilesetsList.size() > 1) { - tilesetsPath.second = tilesetsList[1]; - } - } + std::pair scenariosPath; + vector scenariosList = + Config::getInstance().getPathListForType(ptScenarios); + if (scenariosList.empty() == false) { + scenariosPath.first = scenariosList[0]; + if (scenariosList.size() > 1) { + scenariosPath.second = scenariosList[1]; + } + } - std::pair techtreesPath; - if(techtreesList.empty() == false) { - techtreesPath.first = techtreesList[0]; - if(techtreesList.size() > 1) { - techtreesPath.second = techtreesList[1]; - } - } + string fileArchiveExtension = config.getString("FileArchiveExtension", ""); + string fileArchiveExtractCommand = + config.getString("FileArchiveExtractCommand", ""); + string fileArchiveExtractCommandParameters = + config.getString("FileArchiveExtractCommandParameters", ""); + int32 fileArchiveExtractCommandSuccessResult = + config.getInt("FileArchiveExtractCommandSuccessResult", "0"); + + // Get path to temp files + string tempFilePath = "temp/"; + if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { + tempFilePath = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + + tempFilePath; + } else { + string userData = config.getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + tempFilePath = userData + tempFilePath; + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Temp files path [%s]\n", tempFilePath.c_str()); + + ftpClientThread = new FTPClientThread( + portNumber, serverUrl, mapsPath, tilesetsPath, techtreesPath, + scenariosPath, this, fileArchiveExtension, fileArchiveExtractCommand, + fileArchiveExtractCommandParameters, + fileArchiveExtractCommandSuccessResult, tempFilePath); + ftpClientThread->start(); + } + // Start http meta data thread + static string mutexOwnerId = + string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + + intToStr(__LINE__); + modHttpServerThread = new SimpleTaskThread(this, 0, 200); + modHttpServerThread->setUniqueID(mutexOwnerId); + modHttpServerThread->start(); + + ClientInterface *clientInterface = networkManager.getClientInterface(); + if (clientInterface != NULL && + clientInterface->getJoinGameInProgress() == true) { + listBoxPlayerStatus.setVisible(false); + Lang &lang = Lang::getInstance(); + const vector languageList = + clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + char szMsg[8096] = ""; + if (lang.hasString("JoinPlayerToCurrentGameWelcome", languageList[i]) == + true) { + snprintf( + szMsg, 8096, + lang.getString("JoinPlayerToCurrentGameWelcome", languageList[i]) + .c_str(), + getHumanPlayerName().c_str()); + } else { + snprintf(szMsg, 8096, + "Player: %s has connected to the game and would like to join.", + getHumanPlayerName().c_str()); + } + bool localEcho = lang.isLanguageLocal(languageList[i]); + clientInterface->sendTextMessage(szMsg, -1, localEcho, languageList[i]); + } + sleep(1); + } - std::pair scenariosPath; - vector scenariosList = Config::getInstance().getPathListForType(ptScenarios); - if(scenariosList.empty() == false) { - scenariosPath.first = scenariosList[0]; - if(scenariosList.size() > 1) { - scenariosPath.second = scenariosList[1]; - } - } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); - string fileArchiveExtension = config.getString("FileArchiveExtension",""); - string fileArchiveExtractCommand = config.getString("FileArchiveExtractCommand",""); - string fileArchiveExtractCommandParameters = config.getString("FileArchiveExtractCommandParameters",""); - int32 fileArchiveExtractCommandSuccessResult = config.getInt("FileArchiveExtractCommandSuccessResult","0"); - - // Get path to temp files - string tempFilePath = "temp/"; - if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - tempFilePath = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + tempFilePath; - } - else { - string userData = config.getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - tempFilePath = userData + tempFilePath; - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Temp files path [%s]\n",tempFilePath.c_str()); - - ftpClientThread = new FTPClientThread(portNumber,serverUrl, - mapsPath,tilesetsPath,techtreesPath,scenariosPath, - this,fileArchiveExtension,fileArchiveExtractCommand, - fileArchiveExtractCommandParameters, - fileArchiveExtractCommandSuccessResult, - tempFilePath); - ftpClientThread->start(); - } - // Start http meta data thread - static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); - modHttpServerThread = new SimpleTaskThread(this,0,200); - modHttpServerThread->setUniqueID(mutexOwnerId); - modHttpServerThread->start(); - - ClientInterface *clientInterface = networkManager.getClientInterface(); - if(clientInterface != NULL && clientInterface->getJoinGameInProgress() == true) { - listBoxPlayerStatus.setVisible(false); - Lang &lang= Lang::getInstance(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - char szMsg[8096]=""; - if(lang.hasString("JoinPlayerToCurrentGameWelcome",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("JoinPlayerToCurrentGameWelcome",languageList[i]).c_str(),getHumanPlayerName().c_str()); - } - else { - snprintf(szMsg,8096,"Player: %s has connected to the game and would like to join.",getHumanPlayerName().c_str()); - } - bool localEcho = lang.isLanguageLocal(languageList[i]); - clientInterface->sendTextMessage(szMsg,-1, localEcho,languageList[i]); - } - sleep(1); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); } void MenuStateConnectedGame::reloadUI() { - Config &config = Config::getInstance(); - Lang &lang= Lang::getInstance(); + Config &config = Config::getInstance(); + Lang &lang = Lang::getInstance(); - console.resetFonts(); - mainMessageBox.init(lang.getString("Ok")); - ftpMessageBox.init(lang.getString("ModCenter"),lang.getString("GameHost")); - ftpMessageBox.addButton(lang.getString("NoDownload")); + console.resetFonts(); + mainMessageBox.init(lang.getString("Ok")); + ftpMessageBox.init(lang.getString("ModCenter"), lang.getString("GameHost")); + ftpMessageBox.addButton(lang.getString("NoDownload")); - labelInfo.setFont(CoreData::getInstance().getMenuFontBig()); - labelInfo.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + labelInfo.setFont(CoreData::getInstance().getMenuFontBig()); + labelInfo.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - labelWaitingForPlayers.setFont(CoreData::getInstance().getMenuFontBig()); - labelWaitingForPlayers.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + labelWaitingForPlayers.setFont(CoreData::getInstance().getMenuFontBig()); + labelWaitingForPlayers.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - labelDataSynchInfo.setFont(CoreData::getInstance().getMenuFontBig()); - labelDataSynchInfo.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + labelDataSynchInfo.setFont(CoreData::getInstance().getMenuFontBig()); + labelDataSynchInfo.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - buttonCancelDownloads.setText(lang.getString("CancelDownloads")); + buttonCancelDownloads.setText(lang.getString("CancelDownloads")); - labelAllowObservers.setText(lang.getString("AllowObservers")); - labelFallbackCpuMultiplier.setText(lang.getString("FallbackCpuMultiplier")); + labelAllowObservers.setText(lang.getString("AllowObservers")); + labelFallbackCpuMultiplier.setText(lang.getString("FallbackCpuMultiplier")); - labelEnableSwitchTeamMode.setText(lang.getString("EnableSwitchTeamMode")); + labelEnableSwitchTeamMode.setText(lang.getString("EnableSwitchTeamMode")); - labelAllowTeamUnitSharing.setText(lang.getString("AllowTeamUnitSharing")); - labelAllowTeamResourceSharing.setText(lang.getString("AllowTeamResourceSharing")); + labelAllowTeamUnitSharing.setText(lang.getString("AllowTeamUnitSharing")); + labelAllowTeamResourceSharing.setText( + lang.getString("AllowTeamResourceSharing")); - labelAISwitchTeamAcceptPercent.setText(lang.getString("AISwitchTeamAcceptPercent")); + labelAISwitchTeamAcceptPercent.setText( + lang.getString("AISwitchTeamAcceptPercent")); - vector aiswitchteamModeItems; - for(int i = 0; i <= 100; i = i + 10) { - aiswitchteamModeItems.push_back(intToStr(i)); - } - listBoxAISwitchTeamAcceptPercent.setItems(aiswitchteamModeItems); + vector aiswitchteamModeItems; + for (int i = 0; i <= 100; i = i + 10) { + aiswitchteamModeItems.push_back(intToStr(i)); + } + listBoxAISwitchTeamAcceptPercent.setItems(aiswitchteamModeItems); - vector rMultiplier; - for(int i=0; i<45; ++i){ - rMultiplier.push_back(floatToStr(0.5f+0.1f*i,1)); - } - listBoxFallbackCpuMultiplier.setItems(rMultiplier); + vector rMultiplier; + for (int i = 0; i < 45; ++i) { + rMultiplier.push_back(floatToStr(0.5f + 0.1f * i, 1)); + } + listBoxFallbackCpuMultiplier.setItems(rMultiplier); - labelMap.setText(lang.getString("Map")); + labelMap.setText(lang.getString("Map")); - labelMapFilter.setText(lang.getString("MapFilter")); + labelMapFilter.setText(lang.getString("MapFilter")); - labelTileset.setText(lang.getString("Tileset")); + labelTileset.setText(lang.getString("Tileset")); - labelTechTree.setText(lang.getString("TechTree")); + labelTechTree.setText(lang.getString("TechTree")); - vector playerstatusItems; - playerstatusItems.push_back(lang.getString("PlayerStatusSetup")); - playerstatusItems.push_back(lang.getString("PlayerStatusBeRightBack")); - playerstatusItems.push_back(lang.getString("PlayerStatusReady")); - listBoxPlayerStatus.setItems(playerstatusItems); + vector playerstatusItems; + playerstatusItems.push_back(lang.getString("PlayerStatusSetup")); + playerstatusItems.push_back(lang.getString("PlayerStatusBeRightBack")); + playerstatusItems.push_back(lang.getString("PlayerStatusReady")); + listBoxPlayerStatus.setItems(playerstatusItems); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - labelControl.setText(lang.getString("Control")); + labelControl.setText(lang.getString("Control")); - labelFaction.setText(lang.getString("Faction")); + labelFaction.setText(lang.getString("Faction")); - labelTeam.setText(lang.getString("Team")); + labelTeam.setText(lang.getString("Team")); - labelControl.setFont(CoreData::getInstance().getMenuFontBig()); - labelControl.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - labelFaction.setFont(CoreData::getInstance().getMenuFontBig()); - labelFaction.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - labelTeam.setFont(CoreData::getInstance().getMenuFontBig()); - labelTeam.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + labelControl.setFont(CoreData::getInstance().getMenuFontBig()); + labelControl.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + labelFaction.setFont(CoreData::getInstance().getMenuFontBig()); + labelFaction.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + labelTeam.setFont(CoreData::getInstance().getMenuFontBig()); + labelTeam.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - vector controlItems; - controlItems.push_back(lang.getString("Closed")); - controlItems.push_back(lang.getString("CpuEasy")); - controlItems.push_back(lang.getString("Cpu")); - controlItems.push_back(lang.getString("CpuUltra")); - controlItems.push_back(lang.getString("CpuMega")); - controlItems.push_back(lang.getString("Network")); - controlItems.push_back(lang.getString("NetworkUnassigned")); - controlItems.push_back(lang.getString("Human")); + vector controlItems; + controlItems.push_back(lang.getString("Closed")); + controlItems.push_back(lang.getString("CpuEasy")); + controlItems.push_back(lang.getString("Cpu")); + controlItems.push_back(lang.getString("CpuUltra")); + controlItems.push_back(lang.getString("CpuMega")); + controlItems.push_back(lang.getString("Network")); + controlItems.push_back(lang.getString("NetworkUnassigned")); + controlItems.push_back(lang.getString("Human")); - if(config.getBool("EnableNetworkCpu","false") == true) { - controlItems.push_back(lang.getString("NetworkCpuEasy")); - controlItems.push_back(lang.getString("NetworkCpu")); - controlItems.push_back(lang.getString("NetworkCpuUltra")); - controlItems.push_back(lang.getString("NetworkCpuMega")); - } + if (config.getBool("EnableNetworkCpu", "false") == true) { + controlItems.push_back(lang.getString("NetworkCpuEasy")); + controlItems.push_back(lang.getString("NetworkCpu")); + controlItems.push_back(lang.getString("NetworkCpuUltra")); + controlItems.push_back(lang.getString("NetworkCpuMega")); + } - for(int i=0; i < GameConstants::maxPlayers; ++i) { - labelPlayers[i].setText(intToStr(i+1)); - listBoxControls[i].setItems(controlItems); - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + labelPlayers[i].setText(intToStr(i + 1)); + listBoxControls[i].setItems(controlItems); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - labelScenario.setText(lang.getString("Scenario")); + labelScenario.setText(lang.getString("Scenario")); - labelAllowNativeLanguageTechtree.setText(lang.getString("AllowNativeLanguageTechtree")); + labelAllowNativeLanguageTechtree.setText( + lang.getString("AllowNativeLanguageTechtree")); - buttonPlayNow.setText(lang.getString("PlayNow")); + buttonPlayNow.setText(lang.getString("PlayNow")); - chatManager.init(&console, -1,true); + chatManager.init(&console, -1, true); - GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); + GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); } void MenuStateConnectedGame::disconnectFromServer() { - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface* clientInterface= networkManager.getClientInterface(false); - if(clientInterface != NULL) { - CoreData &coreData= CoreData::getInstance(); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - - soundRenderer.playFx(coreData.getClickSoundA()); - if(clientInterface->getSocket() != NULL) { - if(clientInterface->isConnected() == true) { - Lang &lang= Lang::getInstance(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - string sQuitText = lang.getString("QuitGame",languageList[i]); - clientInterface->sendTextMessage(sQuitText,-1,false,languageList[i]); - } - sleep(1); - - } - clientInterface->close(); - } - clientInterface->reset(); - } - currentFactionName=""; - currentMap=""; + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(false); + if (clientInterface != NULL) { + CoreData &coreData = CoreData::getInstance(); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + + soundRenderer.playFx(coreData.getClickSoundA()); + if (clientInterface->getSocket() != NULL) { + if (clientInterface->isConnected() == true) { + Lang &lang = Lang::getInstance(); + const vector languageList = + clientInterface->getGameSettings() + ->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + string sQuitText = lang.getString("QuitGame", languageList[i]); + clientInterface->sendTextMessage(sQuitText, -1, false, + languageList[i]); + } + sleep(1); + } + clientInterface->close(); + } + clientInterface->reset(); + } + currentFactionName = ""; + currentMap = ""; } MenuStateConnectedGame::~MenuStateConnectedGame() { - if(launchingNewGame == false) { - disconnectFromServer(); - NetworkManager &networkManager= NetworkManager::getInstance(); - networkManager.end(); - } - - if(modHttpServerThread != NULL) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - modHttpServerThread->setSimpleTaskInterfaceValid(false); - modHttpServerThread->signalQuit(); - modHttpServerThread->setThreadOwnerValid(false); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - if( modHttpServerThread->canShutdown(true) == true && - modHttpServerThread->shutdownAndWait() == true) { - delete modHttpServerThread; - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - modHttpServerThread = NULL; - } - - if(ftpClientThread != NULL) { - ftpClientThread->setCallBackObject(NULL); - ftpClientThread->signalQuit(); - sleep(0); - if(ftpClientThread->canShutdown(true) == true && - ftpClientThread->shutdownAndWait() == true) { - delete ftpClientThread; - } - else { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] Error cannot shutdown ftpClientThread\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s",szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - } - - ftpClientThread = NULL; - } - - cleanupMapPreviewTexture(); - - if(factionVideo != NULL) { - factionVideo->closePlayer(); - delete factionVideo; - factionVideo = NULL; - } + if (launchingNewGame == false) { + disconnectFromServer(); + NetworkManager &networkManager = NetworkManager::getInstance(); + networkManager.end(); + } + + if (modHttpServerThread != NULL) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + modHttpServerThread->setSimpleTaskInterfaceValid(false); + modHttpServerThread->signalQuit(); + modHttpServerThread->setThreadOwnerValid(false); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, + __LINE__); + if (modHttpServerThread->canShutdown(true) == true && + modHttpServerThread->shutdownAndWait() == true) { + delete modHttpServerThread; + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + modHttpServerThread = NULL; + } + + if (ftpClientThread != NULL) { + ftpClientThread->setCallBackObject(NULL); + ftpClientThread->signalQuit(); + sleep(0); + if (ftpClientThread->canShutdown(true) == true && + ftpClientThread->shutdownAndWait() == true) { + delete ftpClientThread; + } else { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s %d] Error cannot shutdown ftpClientThread\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("%s", szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + } + + ftpClientThread = NULL; + } + + cleanupMapPreviewTexture(); + + if (factionVideo != NULL) { + factionVideo->closePlayer(); + delete factionVideo; + factionVideo = NULL; + } } string MenuStateConnectedGame::refreshTilesetModInfo(string tilesetInfo) { - std::vector tilesetInfoList; - Tokenize(tilesetInfo,tilesetInfoList,"|"); - if(tilesetInfoList.size() >= 5) { - Config &config = Config::getInstance(); - ModInfo modinfo; - modinfo.name = tilesetInfoList[0]; - modinfo.crc = tilesetInfoList[1]; - modinfo.description = tilesetInfoList[2]; - modinfo.url = tilesetInfoList[3]; - modinfo.imageUrl = tilesetInfoList[4]; - modinfo.type = mt_Tileset; - - string itemPath = config.getPathListForType(ptTilesets,"")[1] + "/" + modinfo.name + string("/*"); - if(itemPath.empty() == false) { - bool forceRefresh = (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); - uint32 crc = getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", NULL,forceRefresh); - if(crc == 0) { - itemPath = config.getPathListForType(ptTilesets,"")[0] + "/" + modinfo.name + string("/*"); - if(itemPath.empty() == false) { - forceRefresh = (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); - crc=getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", NULL,forceRefresh); - } - } - modinfo.localCRC=uIntToStr(crc); - //printf("itemPath='%s' remote crc:'%s' local crc:'%s' crc='%d' \n",itemPath.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str(),crc); - - //printf("#1 refreshTilesetModInfo name [%s] modInfo.crc [%s] modInfo.localCRC [%s]\n",modinfo.name.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str()); - } - else { - modinfo.localCRC=""; - - //printf("#2 refreshTilesetModInfo name [%s] modInfo.crc [%s] modInfo.localCRC [%s]\n",modinfo.name.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str()); - } - - tilesetCacheList[modinfo.name] = modinfo; - return modinfo.name; - } - return ""; + std::vector tilesetInfoList; + Tokenize(tilesetInfo, tilesetInfoList, "|"); + if (tilesetInfoList.size() >= 5) { + Config &config = Config::getInstance(); + ModInfo modinfo; + modinfo.name = tilesetInfoList[0]; + modinfo.crc = tilesetInfoList[1]; + modinfo.description = tilesetInfoList[2]; + modinfo.url = tilesetInfoList[3]; + modinfo.imageUrl = tilesetInfoList[4]; + modinfo.type = mt_Tileset; + + string itemPath = config.getPathListForType(ptTilesets, "")[1] + "/" + + modinfo.name + string("/*"); + if (itemPath.empty() == false) { + bool forceRefresh = + (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); + uint32 crc = getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", + NULL, forceRefresh); + if (crc == 0) { + itemPath = config.getPathListForType(ptTilesets, "")[0] + "/" + + modinfo.name + string("/*"); + if (itemPath.empty() == false) { + forceRefresh = + (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); + crc = getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", NULL, + forceRefresh); + } + } + modinfo.localCRC = uIntToStr(crc); + // printf("itemPath='%s' remote crc:'%s' local crc:'%s' crc='%d' + // \n",itemPath.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str(),crc); + + // printf("#1 refreshTilesetModInfo name [%s] modInfo.crc [%s] + // modInfo.localCRC + // [%s]\n",modinfo.name.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str()); + } else { + modinfo.localCRC = ""; + + // printf("#2 refreshTilesetModInfo name [%s] modInfo.crc [%s] + // modInfo.localCRC + // [%s]\n",modinfo.name.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str()); + } + + tilesetCacheList[modinfo.name] = modinfo; + return modinfo.name; + } + return ""; } string MenuStateConnectedGame::refreshTechModInfo(string techInfo) { - std::vector techInfoList; - Tokenize(techInfo,techInfoList,"|"); - if(techInfoList.size() >= 6) { - Config &config = Config::getInstance(); - ModInfo modinfo; - modinfo.name = techInfoList[0]; - modinfo.count = techInfoList[1]; - modinfo.crc = techInfoList[2]; - modinfo.description = techInfoList[3]; - modinfo.url = techInfoList[4]; - modinfo.imageUrl = techInfoList[5]; - modinfo.type = mt_Techtree; - - string itemPath = config.getPathListForType(ptTechs,"")[1] + "/" + modinfo.name + string("/*"); - if(itemPath.empty() == false) { - bool forceRefresh = (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); - uint32 crc = getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", NULL,forceRefresh); - if(crc == 0) { - itemPath = config.getPathListForType(ptTechs,"")[0] + "/" + modinfo.name + string("/*"); - if(itemPath.empty() == false) { - forceRefresh = (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); - crc = getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", NULL,forceRefresh); - } - } - modinfo.localCRC=uIntToStr(crc); - //printf("itemPath='%s' remote crc:'%s' local crc:'%s' crc='%d' \n",itemPath.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str(),crc); - } - else { - modinfo.localCRC=""; - } - techCacheList[modinfo.name] = modinfo; - return modinfo.name; - } - return ""; + std::vector techInfoList; + Tokenize(techInfo, techInfoList, "|"); + if (techInfoList.size() >= 6) { + Config &config = Config::getInstance(); + ModInfo modinfo; + modinfo.name = techInfoList[0]; + modinfo.count = techInfoList[1]; + modinfo.crc = techInfoList[2]; + modinfo.description = techInfoList[3]; + modinfo.url = techInfoList[4]; + modinfo.imageUrl = techInfoList[5]; + modinfo.type = mt_Techtree; + + string itemPath = config.getPathListForType(ptTechs, "")[1] + "/" + + modinfo.name + string("/*"); + if (itemPath.empty() == false) { + bool forceRefresh = + (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); + uint32 crc = getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", + NULL, forceRefresh); + if (crc == 0) { + itemPath = config.getPathListForType(ptTechs, "")[0] + "/" + + modinfo.name + string("/*"); + if (itemPath.empty() == false) { + forceRefresh = + (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); + crc = getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", NULL, + forceRefresh); + } + } + modinfo.localCRC = uIntToStr(crc); + // printf("itemPath='%s' remote crc:'%s' local crc:'%s' crc='%d' + // \n",itemPath.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str(),crc); + } else { + modinfo.localCRC = ""; + } + techCacheList[modinfo.name] = modinfo; + return modinfo.name; + } + return ""; } string MenuStateConnectedGame::getMapCRC(string mapName) { - Config &config = Config::getInstance(); - vector mappaths=config.getPathListForType(ptMaps,""); - string result=""; - if(mappaths.empty() == false) { - Checksum checksum; - string itemPath = mappaths[1] + "/" + mapName; - if (fileExists(itemPath)){ - checksum.addFile(itemPath); - uint32 crc=checksum.getSum(); - result=uIntToStr(crc); - //printf("itemPath='%s' modinfo.name='%s' remote crc:'%s' local crc:'%s' crc='%d' \n",itemPath.c_str(),modinfo.name.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str(),crc); - } - else { - itemPath = mappaths[0] + "/" + mapName; - if (fileExists(itemPath)){ - checksum.addFile(itemPath); - uint32 crc=checksum.getSum(); - result=uIntToStr(crc); - //printf("itemPath='%s' modinfo.name='%s' remote crc:'%s' local crc:'%s' crc='%d' \n",itemPath.c_str(),modinfo.name.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str(),crc); - } - else { - result=""; - } - } - } - else { - result=""; - } - return result; + Config &config = Config::getInstance(); + vector mappaths = config.getPathListForType(ptMaps, ""); + string result = ""; + if (mappaths.empty() == false) { + Checksum checksum; + string itemPath = mappaths[1] + "/" + mapName; + if (fileExists(itemPath)) { + checksum.addFile(itemPath); + uint32 crc = checksum.getSum(); + result = uIntToStr(crc); + // printf("itemPath='%s' modinfo.name='%s' remote crc:'%s' local crc:'%s' + // crc='%d' + // \n",itemPath.c_str(),modinfo.name.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str(),crc); + } else { + itemPath = mappaths[0] + "/" + mapName; + if (fileExists(itemPath)) { + checksum.addFile(itemPath); + uint32 crc = checksum.getSum(); + result = uIntToStr(crc); + // printf("itemPath='%s' modinfo.name='%s' remote crc:'%s' local + // crc:'%s' crc='%d' + // \n",itemPath.c_str(),modinfo.name.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str(),crc); + } else { + result = ""; + } + } + } else { + result = ""; + } + return result; } string MenuStateConnectedGame::refreshMapModInfo(string mapInfo) { - std::vector mapInfoList; - Tokenize(mapInfo,mapInfoList,"|"); - if(mapInfoList.size() >= 6) { - //Config &config = Config::getInstance(); - ModInfo modinfo; - modinfo.name = mapInfoList[0]; - modinfo.count = mapInfoList[1]; - modinfo.crc = mapInfoList[2]; - modinfo.description = mapInfoList[3]; - modinfo.url = mapInfoList[4]; - modinfo.imageUrl = mapInfoList[5]; - modinfo.type = mt_Map; - modinfo.localCRC=getMapCRC(modinfo.name); - mapCacheList[modinfo.name] = modinfo; - return modinfo.name; - } - return ""; + std::vector mapInfoList; + Tokenize(mapInfo, mapInfoList, "|"); + if (mapInfoList.size() >= 6) { + // Config &config = Config::getInstance(); + ModInfo modinfo; + modinfo.name = mapInfoList[0]; + modinfo.count = mapInfoList[1]; + modinfo.crc = mapInfoList[2]; + modinfo.description = mapInfoList[3]; + modinfo.url = mapInfoList[4]; + modinfo.imageUrl = mapInfoList[5]; + modinfo.type = mt_Map; + modinfo.localCRC = getMapCRC(modinfo.name); + mapCacheList[modinfo.name] = modinfo; + return modinfo.name; + } + return ""; } -void MenuStateConnectedGame::simpleTask(BaseThread *callingThread,void *userdata) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexThreadOwner(callingThread->getMutexThreadOwnerValid(),mutexOwnerId); - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; +void MenuStateConnectedGame::simpleTask(BaseThread *callingThread, + void *userdata) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexThreadOwner( + callingThread->getMutexThreadOwnerValid(), mutexOwnerId); + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; + } + + callingThread->getMutexThreadOwnerValid()->setOwnerId(mutexOwnerId); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + Lang &lang = Lang::getInstance(); + Config &config = Config::getInstance(); + + std::string techsMetaData = ""; + std::string tilesetsMetaData = ""; + std::string mapsMetaData = ""; + std::string scenariosMetaData = ""; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + if (config.getString("Masterserver", "") != "") { + string baseURL = config.getString("Masterserver"); + if (baseURL != "") { + endPathWithSlash(baseURL, false); } - - callingThread->getMutexThreadOwnerValid()->setOwnerId(mutexOwnerId); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - Lang &lang= Lang::getInstance(); - Config &config = Config::getInstance(); - - std::string techsMetaData = ""; - std::string tilesetsMetaData = ""; - std::string mapsMetaData = ""; - std::string scenariosMetaData = ""; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(config.getString("Masterserver","") != "") { - string baseURL = config.getString("Masterserver"); - if(baseURL != "") { - endPathWithSlash(baseURL,false); - } - string phpVersionParam = config.getString("phpVersionParam","?version=0.1"); - string gameVersion = "&glestVersion=" + SystemFlags::escapeURL(glestVersionString); - string playerUUID = "&uuid=" + SystemFlags::escapeURL(config.getString("PlayerId","")); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d] About to call first http url, base [%s]..\n",__FILE__,__FUNCTION__,__LINE__,baseURL.c_str()); - - CURL *handle = SystemFlags::initHTTP(); - CURLcode curlResult = CURLE_OK; - techsMetaData = SystemFlags::getHTTP(baseURL + "showTechsForGlest.php"+phpVersionParam+gameVersion+playerUUID,handle,-1,&curlResult); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("techsMetaData [%s] curlResult = %d\n",techsMetaData.c_str(),curlResult); - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; - } - - if(curlResult != CURLE_OK) { - string curlError = curl_easy_strerror(curlResult); - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModErrorGettingServerData").c_str(),curlError.c_str()); - console.addLine(string("#1 ") + szBuf,true); - } - - if(curlResult == CURLE_OK || - (curlResult != CURLE_COULDNT_RESOLVE_HOST && - curlResult != CURLE_COULDNT_CONNECT)) { - - tilesetsMetaData = SystemFlags::getHTTP(baseURL + "showTilesetsForGlest.php"+phpVersionParam+gameVersion,handle,-1,&curlResult); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("tilesetsMetaData [%s]\n",tilesetsMetaData.c_str()); - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; - } - - if(curlResult != CURLE_OK) { - string curlError = curl_easy_strerror(curlResult); - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModErrorGettingServerData").c_str(),curlError.c_str()); - console.addLine(string("#2 ") + szBuf,true); - } - - mapsMetaData = SystemFlags::getHTTP(baseURL + "showMapsForGlest.php"+phpVersionParam+gameVersion,handle,-1,&curlResult); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("mapsMetaData [%s]\n",mapsMetaData.c_str()); - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; - } - - if(curlResult != CURLE_OK) { - string curlError = curl_easy_strerror(curlResult); - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModErrorGettingServerData").c_str(),curlError.c_str()); - console.addLine(string("#3 ") + szBuf,true); - } - - scenariosMetaData = SystemFlags::getHTTP(baseURL + "showScenariosForGlest.php"+phpVersionParam+gameVersion,handle,-1,&curlResult); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("scenariosMetaData [%s]\n",scenariosMetaData.c_str()); - - if(curlResult != CURLE_OK) { - string curlError = curl_easy_strerror(curlResult); - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModErrorGettingServerData").c_str(),curlError.c_str()); - console.addLine(string("#4 ") + szBuf,true); - } - } - SystemFlags::cleanupHTTP(&handle); - } - else { - console.addLine(lang.getString("MasterServerMissing"),true); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; + string phpVersionParam = + config.getString("phpVersionParam", "?version=0.1"); + string gameVersion = + "&glestVersion=" + SystemFlags::escapeURL(glestVersionString); + string playerUUID = + "&uuid=" + SystemFlags::escapeURL(config.getString("PlayerId", "")); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d] About to call first http url, base [%s]..\n", + __FILE__, __FUNCTION__, __LINE__, baseURL.c_str()); + + CURL *handle = SystemFlags::initHTTP(); + CURLcode curlResult = CURLE_OK; + techsMetaData = + SystemFlags::getHTTP(baseURL + "showTechsForGlest.php" + + phpVersionParam + gameVersion + playerUUID, + handle, -1, &curlResult); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("techsMetaData [%s] curlResult = %d\n", techsMetaData.c_str(), + curlResult); + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - MutexSafeWrapper safeMutex(callingThread->getMutexThreadObjectAccessor(),string(__FILE__) + "_" + intToStr(__LINE__)); - tilesetListRemote.clear(); - Tokenize(tilesetsMetaData,tilesetListRemote,"\n"); - safeMutex.ReleaseLock(true); - - for(unsigned int i=0; i < tilesetListRemote.size(); i++) { + if (curlResult != CURLE_OK) { + string curlError = curl_easy_strerror(curlResult); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, lang.getString("ModErrorGettingServerData").c_str(), + curlError.c_str()); + console.addLine(string("#1 ") + szBuf, true); + } - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; - } + if (curlResult == CURLE_OK || (curlResult != CURLE_COULDNT_RESOLVE_HOST && + curlResult != CURLE_COULDNT_CONNECT)) { - safeMutex.Lock(); - string result=refreshTilesetModInfo(tilesetListRemote[i]); - safeMutex.ReleaseLock(true); - } + tilesetsMetaData = SystemFlags::getHTTP( + baseURL + "showTilesetsForGlest.php" + phpVersionParam + gameVersion, + handle, -1, &curlResult); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("tilesetsMetaData [%s]\n", tilesetsMetaData.c_str()); - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); return; - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); + } + + if (curlResult != CURLE_OK) { + string curlError = curl_easy_strerror(curlResult); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("ModErrorGettingServerData").c_str(), + curlError.c_str()); + console.addLine(string("#2 ") + szBuf, true); + } + + mapsMetaData = SystemFlags::getHTTP(baseURL + "showMapsForGlest.php" + + phpVersionParam + gameVersion, + handle, -1, &curlResult); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("mapsMetaData [%s]\n", mapsMetaData.c_str()); + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); return; + } + + if (curlResult != CURLE_OK) { + string curlError = curl_easy_strerror(curlResult); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("ModErrorGettingServerData").c_str(), + curlError.c_str()); + console.addLine(string("#3 ") + szBuf, true); + } + + scenariosMetaData = SystemFlags::getHTTP( + baseURL + "showScenariosForGlest.php" + phpVersionParam + gameVersion, + handle, -1, &curlResult); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("scenariosMetaData [%s]\n", scenariosMetaData.c_str()); + + if (curlResult != CURLE_OK) { + string curlError = curl_easy_strerror(curlResult); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("ModErrorGettingServerData").c_str(), + curlError.c_str()); + console.addLine(string("#4 ") + szBuf, true); + } } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - safeMutex.Lock(); - techListRemote.clear(); - Tokenize(techsMetaData,techListRemote,"\n"); - safeMutex.ReleaseLock(true); - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; + SystemFlags::cleanupHTTP(&handle); + } else { + console.addLine(lang.getString("MasterServerMissing"), true); + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + MutexSafeWrapper safeMutex(callingThread->getMutexThreadObjectAccessor(), + string(__FILE__) + "_" + intToStr(__LINE__)); + tilesetListRemote.clear(); + Tokenize(tilesetsMetaData, tilesetListRemote, "\n"); + safeMutex.ReleaseLock(true); + + for (unsigned int i = 0; i < tilesetListRemote.size(); i++) { + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; } - for(unsigned int i=0; i < techListRemote.size(); i++) { - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; - } - - safeMutex.Lock(); - string result=refreshTechModInfo(techListRemote[i]); - safeMutex.ReleaseLock(true); - } - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; + safeMutex.Lock(); + string result = refreshTilesetModInfo(tilesetListRemote[i]); + safeMutex.ReleaseLock(true); + } + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + safeMutex.Lock(); + techListRemote.clear(); + Tokenize(techsMetaData, techListRemote, "\n"); + safeMutex.ReleaseLock(true); + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; + } + + for (unsigned int i = 0; i < techListRemote.size(); i++) { + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; + safeMutex.Lock(); + string result = refreshTechModInfo(techListRemote[i]); + safeMutex.ReleaseLock(true); + } + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + safeMutex.Lock(); + mapListRemote.clear(); + Tokenize(mapsMetaData, mapListRemote, "\n"); + safeMutex.ReleaseLock(true); + + for (unsigned int i = 0; i < mapListRemote.size(); i++) { + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - safeMutex.Lock(); - mapListRemote.clear(); - Tokenize(mapsMetaData,mapListRemote,"\n"); - safeMutex.ReleaseLock(true); - - for(unsigned int i=0; i < mapListRemote.size(); i++) { + string result = refreshMapModInfo(mapListRemote[i]); + safeMutex.ReleaseLock(true); + } + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; + } + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + if (modHttpServerThread != NULL) { + modHttpServerThread->signalQuit(); + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); +} - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; - } +void MenuStateConnectedGame::mouseClick(int x, int y, MouseButton mouseButton) { - safeMutex.Lock(); - string result=refreshMapModInfo(mapListRemote[i]); - safeMutex.ReleaseLock(true); - } + CoreData &coreData = CoreData::getInstance(); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + Lang &lang = Lang::getInstance(); - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; + string advanceToItemStartingWith = ""; + if (mainMessageBox.getEnabled() == false) { + if (::Shared::Platform::Window::isKeyStateModPressed(KMOD_SHIFT) == true) { + wchar_t lastKey = ::Shared::Platform::Window::extractLastKeyPressed(); + // printf("lastKey = %d [%c]\n",lastKey,lastKey); + advanceToItemStartingWith = lastKey; } - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; + } + + if (mapPreviewTexture != NULL) { + // printf("X: %d Y: %d [%d, %d, %d, %d]\n", + // x, y, + // this->render_mapPreviewTexture_X, + // this->render_mapPreviewTexture_X + + // this->render_mapPreviewTexture_W, + // this->render_mapPreviewTexture_Y, + // this->render_mapPreviewTexture_Y + + // this->render_mapPreviewTexture_H); + + if (x >= this->render_mapPreviewTexture_X && + x <= this->render_mapPreviewTexture_X + + this->render_mapPreviewTexture_W && + y >= this->render_mapPreviewTexture_Y && + y <= this->render_mapPreviewTexture_Y + + this->render_mapPreviewTexture_H) { + + if (this->render_mapPreviewTexture_X == mapPreviewTexture_X && + this->render_mapPreviewTexture_Y == mapPreviewTexture_Y && + this->render_mapPreviewTexture_W == mapPreviewTexture_W && + this->render_mapPreviewTexture_H == mapPreviewTexture_H) { + + const Metrics &metrics = Metrics::getInstance(); + + this->render_mapPreviewTexture_X = 0; + this->render_mapPreviewTexture_Y = 0; + this->render_mapPreviewTexture_W = metrics.getVirtualW(); + this->render_mapPreviewTexture_H = metrics.getVirtualH(); + this->zoomedMap = true; + + cleanupMapPreviewTexture(); + } else { + this->render_mapPreviewTexture_X = mapPreviewTexture_X; + this->render_mapPreviewTexture_Y = mapPreviewTexture_Y; + this->render_mapPreviewTexture_W = mapPreviewTexture_W; + this->render_mapPreviewTexture_H = mapPreviewTexture_H; + this->zoomedMap = false; + + cleanupMapPreviewTexture(); + } + return; } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(modHttpServerThread != NULL) { - modHttpServerThread->signalQuit(); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); -} - -void MenuStateConnectedGame::mouseClick(int x, int y, MouseButton mouseButton){ - - CoreData &coreData= CoreData::getInstance(); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface* clientInterface= networkManager.getClientInterface(); - Lang &lang= Lang::getInstance(); - - string advanceToItemStartingWith = ""; - if(mainMessageBox.getEnabled() == false) { - if(::Shared::Platform::Window::isKeyStateModPressed(KMOD_SHIFT) == true) { - wchar_t lastKey = ::Shared::Platform::Window::extractLastKeyPressed(); - //printf("lastKey = %d [%c]\n",lastKey,lastKey); - advanceToItemStartingWith = lastKey; - } - } - - if(mapPreviewTexture != NULL) { -// printf("X: %d Y: %d [%d, %d, %d, %d]\n", -// x, y, -// this->render_mapPreviewTexture_X, this->render_mapPreviewTexture_X + this->render_mapPreviewTexture_W, -// this->render_mapPreviewTexture_Y, this->render_mapPreviewTexture_Y + this->render_mapPreviewTexture_H); - - if( x >= this->render_mapPreviewTexture_X && x <= this->render_mapPreviewTexture_X + this->render_mapPreviewTexture_W && - y >= this->render_mapPreviewTexture_Y && y <= this->render_mapPreviewTexture_Y + this->render_mapPreviewTexture_H) { - - if( this->render_mapPreviewTexture_X == mapPreviewTexture_X && - this->render_mapPreviewTexture_Y == mapPreviewTexture_Y && - this->render_mapPreviewTexture_W == mapPreviewTexture_W && - this->render_mapPreviewTexture_H == mapPreviewTexture_H) { - - const Metrics &metrics= Metrics::getInstance(); - - this->render_mapPreviewTexture_X = 0; - this->render_mapPreviewTexture_Y = 0; - this->render_mapPreviewTexture_W = metrics.getVirtualW(); - this->render_mapPreviewTexture_H = metrics.getVirtualH(); - this->zoomedMap = true; - - cleanupMapPreviewTexture(); - } - else { - this->render_mapPreviewTexture_X = mapPreviewTexture_X; - this->render_mapPreviewTexture_Y = mapPreviewTexture_Y; - this->render_mapPreviewTexture_W = mapPreviewTexture_W; - this->render_mapPreviewTexture_H = mapPreviewTexture_H; - this->zoomedMap = false; - - cleanupMapPreviewTexture(); - } - return; - } - if(this->zoomedMap==true){ - return; - } - } - - if(mainMessageBox.getEnabled()) { - int button= 0; - if(mainMessageBox.mouseClick(x, y, button)) { - soundRenderer.playFx(coreData.getClickSoundA()); - if(button == 0) { - mainMessageBox.setEnabled(false); - } - } - } - else if(ftpMessageBox.getEnabled()) { - int button= 0; - if(ftpMessageBox.mouseClick(x, y, button)) { - soundRenderer.playFx(coreData.getClickSoundA()); - ftpMessageBox.setEnabled(false); - - if(button == 0 || (button == 1 && ftpMessageBox.getButtonCount() == 3)) { - if(ftpMissingDataType == ftpmsg_MissingMap) { - getMissingMapFromFTPServerInProgress = true; - - Lang &lang= Lang::getInstance(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - char szMsg[8096]=""; - if(lang.hasString("DataMissingMapNowDownloading",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("DataMissingMapNowDownloading",languageList[i]).c_str(),getHumanPlayerName().c_str(),getMissingMapFromFTPServer.c_str()); - } - else { - snprintf(szMsg,8096,"Player: %s is attempting to download the map: %s",getHumanPlayerName().c_str(),getMissingMapFromFTPServer.c_str()); - } - bool localEcho = lang.isLanguageLocal(languageList[i]); - clientInterface->sendTextMessage(szMsg,-1, localEcho,languageList[i]); - } - - if(ftpClientThread != NULL) { - if(button == 0 && ftpMessageBox.getButtonCount() == 3) { - string mapName = getMissingMapFromFTPServer; - - MutexSafeWrapper safeMutexThread((modHttpServerThread != NULL ? modHttpServerThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - string mapURL = mapCacheList[mapName].url; - safeMutexThread.ReleaseLock(); - - if(ftpClientThread != NULL) ftpClientThread->addMapToRequests(mapName,mapURL); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - fileFTPProgressList[getMissingMapFromFTPServer] = pair(0,""); - safeMutexFTPProgress.ReleaseLock(); - } - else { - ftpClientThread->addMapToRequests(getMissingMapFromFTPServer); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - fileFTPProgressList[getMissingMapFromFTPServer] = pair(0,""); - safeMutexFTPProgress.ReleaseLock(); - } - } - } - else if(ftpMissingDataType == ftpmsg_MissingTileset) { - getMissingTilesetFromFTPServerInProgress = true; - - Lang &lang= Lang::getInstance(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - char szMsg[8096]=""; - if(lang.hasString("DataMissingTilesetNowDownloading",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("DataMissingTilesetNowDownloading",languageList[i]).c_str(),getHumanPlayerName().c_str(),getMissingTilesetFromFTPServer.c_str()); - } - else { - snprintf(szMsg,8096,"Player: %s is attempting to download the tileset: %s",getHumanPlayerName().c_str(),getMissingTilesetFromFTPServer.c_str()); - } - bool localEcho = lang.isLanguageLocal(languageList[i]); - clientInterface->sendTextMessage(szMsg,-1, localEcho,languageList[i]); - } - - if(ftpClientThread != NULL) { - if(button == 0 && ftpMessageBox.getButtonCount() == 3) { - string tilesetName = getMissingTilesetFromFTPServer; - - MutexSafeWrapper safeMutexThread((modHttpServerThread != NULL ? modHttpServerThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - string tilesetURL = tilesetCacheList[tilesetName].url; - safeMutexThread.ReleaseLock(); - - if(ftpClientThread != NULL) ftpClientThread->addTilesetToRequests(tilesetName,tilesetURL); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - fileFTPProgressList[getMissingTilesetFromFTPServer] = pair(0,""); - safeMutexFTPProgress.ReleaseLock(); - } - else { - ftpClientThread->addTilesetToRequests(getMissingTilesetFromFTPServer); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - fileFTPProgressList[getMissingTilesetFromFTPServer] = pair(0,""); - safeMutexFTPProgress.ReleaseLock(); - } - } - } - else if(ftpMissingDataType == ftpmsg_MissingTechtree) { - getMissingTechtreeFromFTPServerInProgress = true; - - Lang &lang= Lang::getInstance(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - char szMsg[8096]=""; - if(lang.hasString("DataMissingTechtreeNowDownloading",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("DataMissingTechtreeNowDownloading",languageList[i]).c_str(),getHumanPlayerName().c_str(),getMissingTechtreeFromFTPServer.c_str()); - } - else { - snprintf(szMsg,8096,"Player: %s is attempting to download the techtree: %s",getHumanPlayerName().c_str(),getMissingTechtreeFromFTPServer.c_str()); - } - bool localEcho = lang.isLanguageLocal(languageList[i]); - clientInterface->sendTextMessage(szMsg,-1, localEcho,languageList[i]); - } - - if(ftpClientThread != NULL) { - if(button == 0 && ftpMessageBox.getButtonCount() == 3) { - string techName = getMissingTechtreeFromFTPServer; - - MutexSafeWrapper safeMutexThread((modHttpServerThread != NULL ? modHttpServerThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - string techURL = techCacheList[techName].url; - safeMutexThread.ReleaseLock(); - - if(ftpClientThread != NULL) ftpClientThread->addTechtreeToRequests(techName,techURL); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - fileFTPProgressList[getMissingTechtreeFromFTPServer] = pair(0,""); - safeMutexFTPProgress.ReleaseLock(); - } - else { - ftpClientThread->addTechtreeToRequests(getMissingTechtreeFromFTPServer); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - fileFTPProgressList[getMissingTechtreeFromFTPServer] = pair(0,""); - safeMutexFTPProgress.ReleaseLock(); - } - } - } - } - } - } - else if(buttonCancelDownloads.mouseClick(x,y)) { - soundRenderer.playFx(coreData.getClickSoundA()); - - if(ftpClientThread != NULL && fileFTPProgressList.empty() == false) { - - ftpClientThread->setCallBackObject(NULL); - ftpClientThread->signalQuit(); - sleep(0); - if(ftpClientThread->canShutdown(true) == true && - ftpClientThread->shutdownAndWait() == true) { - delete ftpClientThread; - } - else { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] Error cannot shutdown ftpClientThread\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s",szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - } - ftpClientThread = NULL; - - fileFTPProgressList.clear(); - getMissingMapFromFTPServerInProgress = false; - getMissingTilesetFromFTPServerInProgress = false; - getMissingTechtreeFromFTPServerInProgress = false; - getMissingMapFromFTPServer = ""; - getMissingTilesetFromFTPServer = ""; - getMissingTechtreeFromFTPServer = ""; - getMissingMapFromFTPServerLastPrompted = 0; - getMissingTilesetFromFTPServerLastPrompted = 0; - getMissingTechtreeFromFTPServerLastPrompted = 0; - - ClientInterface *clientInterface = networkManager.getClientInterface(); - if(clientInterface == NULL) { - throw megaglest_runtime_error("clientInterface == NULL"); + if (this->zoomedMap == true) { + return; + } + } + + if (mainMessageBox.getEnabled()) { + int button = 0; + if (mainMessageBox.mouseClick(x, y, button)) { + soundRenderer.playFx(coreData.getClickSoundA()); + if (button == 0) { + mainMessageBox.setEnabled(false); + } + } + } else if (ftpMessageBox.getEnabled()) { + int button = 0; + if (ftpMessageBox.mouseClick(x, y, button)) { + soundRenderer.playFx(coreData.getClickSoundA()); + ftpMessageBox.setEnabled(false); + + if (button == 0 || (button == 1 && ftpMessageBox.getButtonCount() == 3)) { + if (ftpMissingDataType == ftpmsg_MissingMap) { + getMissingMapFromFTPServerInProgress = true; + + Lang &lang = Lang::getInstance(); + const vector languageList = + clientInterface->getGameSettings() + ->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + char szMsg[8096] = ""; + if (lang.hasString("DataMissingMapNowDownloading", + languageList[i]) == true) { + snprintf(szMsg, 8096, + lang.getString("DataMissingMapNowDownloading", + languageList[i]) + .c_str(), + getHumanPlayerName().c_str(), + getMissingMapFromFTPServer.c_str()); + } else { + snprintf(szMsg, 8096, + "Player: %s is attempting to download the map: %s", + getHumanPlayerName().c_str(), + getMissingMapFromFTPServer.c_str()); } - if(getInProgressSavedGameFromFTPServerInProgress == true) { - if(clientInterface != NULL) { - clientInterface->close(); - return; - } + bool localEcho = lang.isLanguageLocal(languageList[i]); + clientInterface->sendTextMessage(szMsg, -1, localEcho, + languageList[i]); + } + + if (ftpClientThread != NULL) { + if (button == 0 && ftpMessageBox.getButtonCount() == 3) { + string mapName = getMissingMapFromFTPServer; + + MutexSafeWrapper safeMutexThread( + (modHttpServerThread != NULL + ? modHttpServerThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + string mapURL = mapCacheList[mapName].url; + safeMutexThread.ReleaseLock(); + + if (ftpClientThread != NULL) + ftpClientThread->addMapToRequests(mapName, mapURL); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + fileFTPProgressList[getMissingMapFromFTPServer] = + pair(0, ""); + safeMutexFTPProgress.ReleaseLock(); + } else { + ftpClientThread->addMapToRequests(getMissingMapFromFTPServer); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + fileFTPProgressList[getMissingMapFromFTPServer] = + pair(0, ""); + safeMutexFTPProgress.ReleaseLock(); } - - getInProgressSavedGameFromFTPServer = ""; - getInProgressSavedGameFromFTPServerInProgress = false; - - string serverUrl = clientInterface->getServerIpAddress(); - int portNumber = clientInterface->getServerFTPPort(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] Using FTP port #: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,portNumber); - - Config &config = Config::getInstance(); - vector mapPathList = config.getPathListForType(ptMaps); - std::pair mapsPath; - if(mapPathList.empty() == false) { - mapsPath.first = mapPathList[0]; + } + } else if (ftpMissingDataType == ftpmsg_MissingTileset) { + getMissingTilesetFromFTPServerInProgress = true; + + Lang &lang = Lang::getInstance(); + const vector languageList = + clientInterface->getGameSettings() + ->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + char szMsg[8096] = ""; + if (lang.hasString("DataMissingTilesetNowDownloading", + languageList[i]) == true) { + snprintf(szMsg, 8096, + lang.getString("DataMissingTilesetNowDownloading", + languageList[i]) + .c_str(), + getHumanPlayerName().c_str(), + getMissingTilesetFromFTPServer.c_str()); + } else { + snprintf(szMsg, 8096, + "Player: %s is attempting to download the tileset: %s", + getHumanPlayerName().c_str(), + getMissingTilesetFromFTPServer.c_str()); } - if(mapPathList.size() > 1) { - mapsPath.second = mapPathList[1]; + bool localEcho = lang.isLanguageLocal(languageList[i]); + clientInterface->sendTextMessage(szMsg, -1, localEcho, + languageList[i]); + } + + if (ftpClientThread != NULL) { + if (button == 0 && ftpMessageBox.getButtonCount() == 3) { + string tilesetName = getMissingTilesetFromFTPServer; + + MutexSafeWrapper safeMutexThread( + (modHttpServerThread != NULL + ? modHttpServerThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + string tilesetURL = tilesetCacheList[tilesetName].url; + safeMutexThread.ReleaseLock(); + + if (ftpClientThread != NULL) + ftpClientThread->addTilesetToRequests(tilesetName, tilesetURL); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + fileFTPProgressList[getMissingTilesetFromFTPServer] = + pair(0, ""); + safeMutexFTPProgress.ReleaseLock(); + } else { + ftpClientThread->addTilesetToRequests( + getMissingTilesetFromFTPServer); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + fileFTPProgressList[getMissingTilesetFromFTPServer] = + pair(0, ""); + safeMutexFTPProgress.ReleaseLock(); } - std::pair tilesetsPath; - vector tilesetsList = Config::getInstance().getPathListForType(ptTilesets); - if(tilesetsList.empty() == false) { - tilesetsPath.first = tilesetsList[0]; - if(tilesetsList.size() > 1) { - tilesetsPath.second = tilesetsList[1]; - } + } + } else if (ftpMissingDataType == ftpmsg_MissingTechtree) { + getMissingTechtreeFromFTPServerInProgress = true; + + Lang &lang = Lang::getInstance(); + const vector languageList = + clientInterface->getGameSettings() + ->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + char szMsg[8096] = ""; + if (lang.hasString("DataMissingTechtreeNowDownloading", + languageList[i]) == true) { + snprintf(szMsg, 8096, + lang.getString("DataMissingTechtreeNowDownloading", + languageList[i]) + .c_str(), + getHumanPlayerName().c_str(), + getMissingTechtreeFromFTPServer.c_str()); + } else { + snprintf(szMsg, 8096, + "Player: %s is attempting to download the techtree: %s", + getHumanPlayerName().c_str(), + getMissingTechtreeFromFTPServer.c_str()); } - - std::pair techtreesPath; - vector techtreesList = Config::getInstance().getPathListForType(ptTechs); - if(techtreesList.empty() == false) { - techtreesPath.first = techtreesList[0]; - if(techtreesList.size() > 1) { - techtreesPath.second = techtreesList[1]; - } + bool localEcho = lang.isLanguageLocal(languageList[i]); + clientInterface->sendTextMessage(szMsg, -1, localEcho, + languageList[i]); + } + + if (ftpClientThread != NULL) { + if (button == 0 && ftpMessageBox.getButtonCount() == 3) { + string techName = getMissingTechtreeFromFTPServer; + + MutexSafeWrapper safeMutexThread( + (modHttpServerThread != NULL + ? modHttpServerThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + string techURL = techCacheList[techName].url; + safeMutexThread.ReleaseLock(); + + if (ftpClientThread != NULL) + ftpClientThread->addTechtreeToRequests(techName, techURL); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + fileFTPProgressList[getMissingTechtreeFromFTPServer] = + pair(0, ""); + safeMutexFTPProgress.ReleaseLock(); + } else { + ftpClientThread->addTechtreeToRequests( + getMissingTechtreeFromFTPServer); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + fileFTPProgressList[getMissingTechtreeFromFTPServer] = + pair(0, ""); + safeMutexFTPProgress.ReleaseLock(); } + } + } + } + } + } else if (buttonCancelDownloads.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + + if (ftpClientThread != NULL && fileFTPProgressList.empty() == false) { + + ftpClientThread->setCallBackObject(NULL); + ftpClientThread->signalQuit(); + sleep(0); + if (ftpClientThread->canShutdown(true) == true && + ftpClientThread->shutdownAndWait() == true) { + delete ftpClientThread; + } else { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s %d] Error cannot shutdown ftpClientThread\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("%s", szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + } + ftpClientThread = NULL; + + fileFTPProgressList.clear(); + getMissingMapFromFTPServerInProgress = false; + getMissingTilesetFromFTPServerInProgress = false; + getMissingTechtreeFromFTPServerInProgress = false; + getMissingMapFromFTPServer = ""; + getMissingTilesetFromFTPServer = ""; + getMissingTechtreeFromFTPServer = ""; + getMissingMapFromFTPServerLastPrompted = 0; + getMissingTilesetFromFTPServerLastPrompted = 0; + getMissingTechtreeFromFTPServerLastPrompted = 0; + + ClientInterface *clientInterface = networkManager.getClientInterface(); + if (clientInterface == NULL) { + throw megaglest_runtime_error("clientInterface == NULL"); + } + if (getInProgressSavedGameFromFTPServerInProgress == true) { + if (clientInterface != NULL) { + clientInterface->close(); + return; + } + } + + getInProgressSavedGameFromFTPServer = ""; + getInProgressSavedGameFromFTPServerInProgress = false; + + string serverUrl = clientInterface->getServerIpAddress(); + int portNumber = clientInterface->getServerFTPPort(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d] Using FTP port #: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, portNumber); + + Config &config = Config::getInstance(); + vector mapPathList = config.getPathListForType(ptMaps); + std::pair mapsPath; + if (mapPathList.empty() == false) { + mapsPath.first = mapPathList[0]; + } + if (mapPathList.size() > 1) { + mapsPath.second = mapPathList[1]; + } + std::pair tilesetsPath; + vector tilesetsList = + Config::getInstance().getPathListForType(ptTilesets); + if (tilesetsList.empty() == false) { + tilesetsPath.first = tilesetsList[0]; + if (tilesetsList.size() > 1) { + tilesetsPath.second = tilesetsList[1]; + } + } + + std::pair techtreesPath; + vector techtreesList = + Config::getInstance().getPathListForType(ptTechs); + if (techtreesList.empty() == false) { + techtreesPath.first = techtreesList[0]; + if (techtreesList.size() > 1) { + techtreesPath.second = techtreesList[1]; + } + } + + std::pair scenariosPath; + vector scenariosList = + Config::getInstance().getPathListForType(ptScenarios); + if (scenariosList.empty() == false) { + scenariosPath.first = scenariosList[0]; + if (scenariosList.size() > 1) { + scenariosPath.second = scenariosList[1]; + } + } + + string fileArchiveExtension = + config.getString("FileArchiveExtension", ""); + string fileArchiveExtractCommand = + config.getString("FileArchiveExtractCommand", ""); + string fileArchiveExtractCommandParameters = + config.getString("FileArchiveExtractCommandParameters", ""); + int32 fileArchiveExtractCommandSuccessResult = + config.getInt("FileArchiveExtractCommandSuccessResult", "0"); + + // Get path to temp files + string tempFilePath = "temp/"; + if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { + tempFilePath = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + + tempFilePath; + } else { + string userData = config.getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + tempFilePath = userData + tempFilePath; + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Temp files path [%s]\n", tempFilePath.c_str()); + + ftpClientThread = new FTPClientThread( + portNumber, serverUrl, mapsPath, tilesetsPath, techtreesPath, + scenariosPath, this, fileArchiveExtension, fileArchiveExtractCommand, + fileArchiveExtractCommandParameters, + fileArchiveExtractCommandSuccessResult, tempFilePath); + ftpClientThread->start(); + + Lang &lang = Lang::getInstance(); + const vector languageList = + clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + char szMsg[8096] = ""; + if (lang.hasString("CancelDownloadsMsg", languageList[i]) == true) { + snprintf( + szMsg, 8096, + lang.getString("CancelDownloadsMsg", languageList[i]).c_str(), + getHumanPlayerName().c_str()); + } else { + snprintf(szMsg, 8096, "Player: %s cancelled all file downloads.", + getHumanPlayerName().c_str()); + } + clientInterface->sendTextMessage( + szMsg, -1, lang.isLanguageLocal(languageList[i]), languageList[i]); + } + } + } else if (buttonDisconnect.mouseClick(x, y)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + disconnectFromServer(); + networkManager.end(); + returnToJoinMenu(); + return; + } + + if (initialSettingsReceivedFromServer == false) { + return; + } + + if (activeInputLabel != NULL && activeInputLabel->mouseClick(x, y) == false) { + setActiveInputLabel(NULL); + } + + // Only allow changes after we get game settings from the server + if (clientInterface != NULL && clientInterface->isConnected() == true) { + int myCurrentIndex = -1; + for (int i = 0; i < GameConstants::maxPlayers; + ++i) { // find my current index by looking at editable listBoxes + if ( // listBoxFactions[i].getEditable() && + clientInterface->getGameSettings()->getStartLocationIndex( + clientInterface->getGameSettings()->getThisFactionIndex()) == i) { + myCurrentIndex = i; + } + } - std::pair scenariosPath; - vector scenariosList = Config::getInstance().getPathListForType(ptScenarios); - if(scenariosList.empty() == false) { - scenariosPath.first = scenariosList[0]; - if(scenariosList.size() > 1) { - scenariosPath.second = scenariosList[1]; - } + // printf("myCurrentIndex = %d thisFactionIndex = + // %d\n",myCurrentIndex,clientInterface->getGameSettings()->getThisFactionIndex()); + + if (myCurrentIndex != -1) + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + if (listBoxFactions[i].getEditable() && + clientInterface->getGameSettings()->getStartLocationIndex( + clientInterface->getGameSettings()->getThisFactionIndex()) == + i) { + if (listBoxFactions[i].mouseClick(x, y, advanceToItemStartingWith)) { + soundRenderer.playFx(coreData.getClickSoundA()); + ClientInterface *clientInterface = + NetworkManager::getInstance().getClientInterface(); + if (clientInterface->isConnected()) { + clientInterface->setGameSettingsReceived(false); + clientInterface->sendSwitchSetupRequest( + listBoxFactions[i].getSelectedItem(), i, -1, + listBoxTeams[i].getSelectedItemIndex(), getHumanPlayerName(), + getNetworkPlayerStatus(), switchSetupRequestFlagType, + lang.getLanguage()); + switchSetupRequestFlagType = ssrft_None; + noReceiveTimer = time(NULL); } - - string fileArchiveExtension = config.getString("FileArchiveExtension",""); - string fileArchiveExtractCommand = config.getString("FileArchiveExtractCommand",""); - string fileArchiveExtractCommandParameters = config.getString("FileArchiveExtractCommandParameters",""); - int32 fileArchiveExtractCommandSuccessResult = config.getInt("FileArchiveExtractCommandSuccessResult","0"); - - // Get path to temp files - string tempFilePath = "temp/"; - if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - tempFilePath = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + tempFilePath; - } - else { - string userData = config.getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - tempFilePath = userData + tempFilePath; - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Temp files path [%s]\n",tempFilePath.c_str()); - - ftpClientThread = new FTPClientThread(portNumber,serverUrl, - mapsPath,tilesetsPath,techtreesPath,scenariosPath, - this,fileArchiveExtension,fileArchiveExtractCommand, - fileArchiveExtractCommandParameters, - fileArchiveExtractCommandSuccessResult, - tempFilePath); - ftpClientThread->start(); - - Lang &lang= Lang::getInstance(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - char szMsg[8096]=""; - if(lang.hasString("CancelDownloadsMsg",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("CancelDownloadsMsg",languageList[i]).c_str(),getHumanPlayerName().c_str()); - } - else { - snprintf(szMsg,8096,"Player: %s cancelled all file downloads.",getHumanPlayerName().c_str()); - } - clientInterface->sendTextMessage(szMsg,-1, lang.isLanguageLocal(languageList[i]),languageList[i]); - } + break; + } + } + if (listBoxTeams[i].getEditable() && + clientInterface->getGameSettings()->getStartLocationIndex( + clientInterface->getGameSettings()->getThisFactionIndex()) == + i) { + if (listBoxTeams[i].mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + if (clientInterface->isConnected()) { + clientInterface->setGameSettingsReceived(false); + clientInterface->sendSwitchSetupRequest( + listBoxFactions[i].getSelectedItem(), i, -1, + listBoxTeams[i].getSelectedItemIndex(), getHumanPlayerName(), + getNetworkPlayerStatus(), switchSetupRequestFlagType, + lang.getLanguage()); + switchSetupRequestFlagType = ssrft_None; + } + break; + } } - } - else if(buttonDisconnect.mouseClick(x,y)){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - disconnectFromServer(); - networkManager.end(); - returnToJoinMenu(); - return; - } - - if (initialSettingsReceivedFromServer == false) { - return; - } - - if(activeInputLabel != NULL && activeInputLabel->mouseClick(x,y) == false){ - setActiveInputLabel(NULL); - } - - // Only allow changes after we get game settings from the server - if(clientInterface != NULL && clientInterface->isConnected() == true) { - int myCurrentIndex= -1; - for(int i= 0; i < GameConstants::maxPlayers; ++i) {// find my current index by looking at editable listBoxes - if(//listBoxFactions[i].getEditable() && - clientInterface->getGameSettings()->getStartLocationIndex(clientInterface->getGameSettings()->getThisFactionIndex()) == i) { - myCurrentIndex= i; - } - } - - //printf("myCurrentIndex = %d thisFactionIndex = %d\n",myCurrentIndex,clientInterface->getGameSettings()->getThisFactionIndex()); - - if(myCurrentIndex != -1) - for(int i= 0; i < GameConstants::maxPlayers; ++i) { - if(listBoxFactions[i].getEditable() && - clientInterface->getGameSettings()->getStartLocationIndex(clientInterface->getGameSettings()->getThisFactionIndex()) == i) { - if(listBoxFactions[i].mouseClick(x, y,advanceToItemStartingWith)) { - soundRenderer.playFx(coreData.getClickSoundA()); - ClientInterface* clientInterface= NetworkManager::getInstance().getClientInterface(); - if(clientInterface->isConnected()) { - clientInterface->setGameSettingsReceived(false); - clientInterface->sendSwitchSetupRequest( - listBoxFactions[i].getSelectedItem(), - i, - -1, - listBoxTeams[i].getSelectedItemIndex(), - getHumanPlayerName(), - getNetworkPlayerStatus(), - switchSetupRequestFlagType, - lang.getLanguage()); - switchSetupRequestFlagType= ssrft_None; - noReceiveTimer=time(NULL); - } - break; - } - } - if(listBoxTeams[i].getEditable() && - clientInterface->getGameSettings()->getStartLocationIndex(clientInterface->getGameSettings()->getThisFactionIndex()) == i) { - if(listBoxTeams[i].mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - if(clientInterface->isConnected()){ - clientInterface->setGameSettingsReceived(false); - clientInterface->sendSwitchSetupRequest( - listBoxFactions[i].getSelectedItem(), - i, - -1, - listBoxTeams[i].getSelectedItemIndex(), - getHumanPlayerName(), - getNetworkPlayerStatus(), - switchSetupRequestFlagType, - lang.getLanguage()); - switchSetupRequestFlagType= ssrft_None; - } - break; - } - } - - bool canGrabSlot = false; - ClientInterface *clientInterface = networkManager.getClientInterface(); - if(clientInterface != NULL && clientInterface->getJoinGameInProgress() == true) { - canGrabSlot = ((listBoxControls[i].getSelectedItemIndex() == ctNetwork && - labelNetStatus[i].getText() == GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME) || - (listBoxControls[i].getSelectedItemIndex() != ctHuman && - listBoxControls[i].getSelectedItemIndex() != ctClosed && - listBoxControls[i].getSelectedItemIndex() != ctNetwork)); - } - else { - canGrabSlot = (listBoxControls[i].getSelectedItemIndex() == ctNetwork && - labelNetStatus[i].getText() == GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME); - } - - if(canGrabSlot == true) { - if(clientInterface != NULL && i < mapInfo.players && grabSlotButton[i].mouseClick(x, y)) { - //printf("Send slot switch request for slot = %d, myCurrentIndex = %d\n",i,myCurrentIndex); - - soundRenderer.playFx(coreData.getClickSoundB()); - clientInterface->setGameSettingsReceived(false); - settingsReceivedFromServer= false; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] sending a switchSlot request from %d to %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,clientInterface->getGameSettings()->getThisFactionIndex(),i); - - //printf("Switch slot from %d to %d\n",myCurrentIndex,i); - - string desiredFactionName = listBoxFactions[myCurrentIndex].getSelectedItem(); - int desiredTeamIndex = listBoxTeams[myCurrentIndex].getSelectedItemIndex(); - if(checkBoxScenario.getValue() == true) { - desiredFactionName = listBoxFactions[i].getSelectedItem(); - desiredTeamIndex = listBoxTeams[i].getSelectedItemIndex(); - } - - //printf("Sending switch slot request to server...\n"); - - clientInterface->sendSwitchSetupRequest( - desiredFactionName, - myCurrentIndex, - i, - desiredTeamIndex, - getHumanPlayerName(), - getNetworkPlayerStatus(), - switchSetupRequestFlagType, - lang.getLanguage()); - labelPlayerNames[myCurrentIndex].setText(""); - labelPlayerNames[i].setText(""); - switchSetupRequestFlagType= ssrft_None; - break; - } - } - - if(labelPlayerNames[i].mouseClick(x, y) && (activeInputLabel != &labelPlayerNames[i])){ - if(clientInterface != NULL && i == clientInterface->getPlayerIndex()){ - setActiveInputLabel(&labelPlayerNames[i]); - } - } - } - - if(listBoxPlayerStatus.mouseClick(x,y)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - soundRenderer.playFx(coreData.getClickSoundC()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(getNetworkPlayerStatus()==npst_PickSettings) - { - listBoxPlayerStatus.setTextColor(Vec3f(1.0f,0.0f,0.0f)); - listBoxPlayerStatus.setLighted(true); - } - else if(getNetworkPlayerStatus()==npst_BeRightBack) - { - listBoxPlayerStatus.setTextColor(Vec3f(1.0f,1.0f,0.0f)); - listBoxPlayerStatus.setLighted(true); - } - else if(getNetworkPlayerStatus()==npst_Ready) - { - listBoxPlayerStatus.setTextColor(Vec3f(0.0f,1.0f,0.0f)); - listBoxPlayerStatus.setLighted(false); - } - - ClientInterface* clientInterface= NetworkManager::getInstance().getClientInterface(); - if(clientInterface != NULL && clientInterface->isConnected()) { - clientInterface->setGameSettingsReceived(false); - clientInterface->sendSwitchSetupRequest( - listBoxFactions[clientInterface->getPlayerIndex()].getSelectedItem(), - clientInterface->getPlayerIndex(),-1, - listBoxTeams[clientInterface->getPlayerIndex()].getSelectedItemIndex(), - getHumanPlayerName(), - getNetworkPlayerStatus(), - switchSetupRequestFlagType, - lang.getLanguage()); - switchSetupRequestFlagType=ssrft_None; - } - } - - if(isHeadlessAdmin() == true) { - //printf("#1 admin key [%d] client key [%d]\n",settings->getMasterserver_admin(),clientInterface->getSessionKey()); - mouseClickAdmin(x, y, mouseButton,advanceToItemStartingWith); - } - else if(clientInterface != NULL && clientInterface->getJoinGameInProgress() == true) { - if(buttonPlayNow.mouseClick(x,y) && buttonPlayNow.getEnabled()) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - uint32 tilesetCRC = lastCheckedCRCTilesetValue; - uint32 techCRC = lastCheckedCRCTechtreeValue; - uint32 mapCRC = lastCheckedCRCMapValue; - const GameSettings *gameSettings = clientInterface->getGameSettings(); - - bool dataSynchMismatch = ((mapCRC != 0 && mapCRC != gameSettings->getMapCRC()) || - (tilesetCRC != 0 && tilesetCRC != gameSettings->getTilesetCRC()) || - (techCRC != 0 && techCRC != gameSettings->getTechCRC())); - if(dataSynchMismatch == false) { - PlayNow(true); - return; - } - else { - showMessageBox("You cannot start the game because\none or more clients do not have the same game data!", "Data Mismatch Error", false); - } - } - } - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); -} -bool MenuStateConnectedGame::isHeadlessAdmin() { - bool result = false; + bool canGrabSlot = false; + ClientInterface *clientInterface = networkManager.getClientInterface(); + if (clientInterface != NULL && + clientInterface->getJoinGameInProgress() == true) { + canGrabSlot = + ((listBoxControls[i].getSelectedItemIndex() == ctNetwork && + labelNetStatus[i].getText() == + GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME) || + (listBoxControls[i].getSelectedItemIndex() != ctHuman && + listBoxControls[i].getSelectedItemIndex() != ctClosed && + listBoxControls[i].getSelectedItemIndex() != ctNetwork)); + } else { + canGrabSlot = + (listBoxControls[i].getSelectedItemIndex() == ctNetwork && + labelNetStatus[i].getText() == + GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME); + } - ClientInterface* clientInterface= NetworkManager::getInstance().getClientInterface(); - if(clientInterface != NULL && clientInterface->isConnected()) { - const GameSettings *settings = clientInterface->getGameSettings(); - if(settings != NULL) { - //printf("#1 admin key [%d] client key [%d]\n",settings->getMasterserver_admin(),clientInterface->getSessionKey()); + if (canGrabSlot == true) { + if (clientInterface != NULL && i < mapInfo.players && + grabSlotButton[i].mouseClick(x, y)) { + // printf("Send slot switch request for slot = %d, myCurrentIndex = + // %d\n",i,myCurrentIndex); + + soundRenderer.playFx(coreData.getClickSoundB()); + clientInterface->setGameSettingsReceived(false); + settingsReceivedFromServer = false; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line %d] sending a switchSlot request from %d to " + "%d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, + clientInterface->getGameSettings()->getThisFactionIndex(), i); + + // printf("Switch slot from %d to %d\n",myCurrentIndex,i); + + string desiredFactionName = + listBoxFactions[myCurrentIndex].getSelectedItem(); + int desiredTeamIndex = + listBoxTeams[myCurrentIndex].getSelectedItemIndex(); + if (checkBoxScenario.getValue() == true) { + desiredFactionName = listBoxFactions[i].getSelectedItem(); + desiredTeamIndex = listBoxTeams[i].getSelectedItemIndex(); + } - if(settings->getMasterserver_admin() == clientInterface->getSessionKey()) { - result = true; - } - } - } + // printf("Sending switch slot request to server...\n"); - return result; -} + clientInterface->sendSwitchSetupRequest( + desiredFactionName, myCurrentIndex, i, desiredTeamIndex, + getHumanPlayerName(), getNetworkPlayerStatus(), + switchSetupRequestFlagType, lang.getLanguage()); + labelPlayerNames[myCurrentIndex].setText(""); + labelPlayerNames[i].setText(""); + switchSetupRequestFlagType = ssrft_None; + break; + } + } -void MenuStateConnectedGame::broadCastGameSettingsToHeadlessServer(bool forceNow) { - if(isHeadlessAdmin() == false) { - return; - } + if (labelPlayerNames[i].mouseClick(x, y) && + (activeInputLabel != &labelPlayerNames[i])) { + if (clientInterface != NULL && + i == clientInterface->getPlayerIndex()) { + setActiveInputLabel(&labelPlayerNames[i]); + } + } + } + + if (listBoxPlayerStatus.mouseClick(x, y)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + soundRenderer.playFx(coreData.getClickSoundC()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (getNetworkPlayerStatus() == npst_PickSettings) { + listBoxPlayerStatus.setTextColor(Vec3f(1.0f, 0.0f, 0.0f)); + listBoxPlayerStatus.setLighted(true); + } else if (getNetworkPlayerStatus() == npst_BeRightBack) { + listBoxPlayerStatus.setTextColor(Vec3f(1.0f, 1.0f, 0.0f)); + listBoxPlayerStatus.setLighted(true); + } else if (getNetworkPlayerStatus() == npst_Ready) { + listBoxPlayerStatus.setTextColor(Vec3f(0.0f, 1.0f, 0.0f)); + listBoxPlayerStatus.setLighted(false); + } + + ClientInterface *clientInterface = + NetworkManager::getInstance().getClientInterface(); + if (clientInterface != NULL && clientInterface->isConnected()) { + clientInterface->setGameSettingsReceived(false); + clientInterface->sendSwitchSetupRequest( + listBoxFactions[clientInterface->getPlayerIndex()] + .getSelectedItem(), + clientInterface->getPlayerIndex(), -1, + listBoxTeams[clientInterface->getPlayerIndex()] + .getSelectedItemIndex(), + getHumanPlayerName(), getNetworkPlayerStatus(), + switchSetupRequestFlagType, lang.getLanguage()); + switchSetupRequestFlagType = ssrft_None; + } + } - if(forceNow == true || - ((needToBroadcastServerSettings == true ) && ( difftime((long int)time(NULL),broadcastServerSettingsDelayTimer) >= HEADLESSSERVER_BROADCAST_SETTINGS_SECONDS))) { - //printf("In [%s:%s] Line: %d forceNow = %d broadcastServerSettingsDelayTimer = " MG_SIZE_T_SPECIFIER ", now =" MG_SIZE_T_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,forceNow,broadcastServerSettingsDelayTimer,time(NULL)); + if (isHeadlessAdmin() == true) { + // printf("#1 admin key [%d] client key + // [%d]\n",settings->getMasterserver_admin(),clientInterface->getSessionKey()); + mouseClickAdmin(x, y, mouseButton, advanceToItemStartingWith); + } else if (clientInterface != NULL && + clientInterface->getJoinGameInProgress() == true) { + if (buttonPlayNow.mouseClick(x, y) && buttonPlayNow.getEnabled()) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + uint32 tilesetCRC = lastCheckedCRCTilesetValue; + uint32 techCRC = lastCheckedCRCTechtreeValue; + uint32 mapCRC = lastCheckedCRCMapValue; + const GameSettings *gameSettings = clientInterface->getGameSettings(); - needToBroadcastServerSettings = false; - broadcastServerSettingsDelayTimer = time(NULL); + bool dataSynchMismatch = + ((mapCRC != 0 && mapCRC != gameSettings->getMapCRC()) || + (tilesetCRC != 0 && tilesetCRC != gameSettings->getTilesetCRC()) || + (techCRC != 0 && techCRC != gameSettings->getTechCRC())); + if (dataSynchMismatch == false) { + PlayNow(true); + return; + } else { + showMessageBox("You cannot start the game because\none or more " + "clients do not have the same game data!", + "Data Mismatch Error", false); + } + } + } + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); +} - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface *clientInterface = networkManager.getClientInterface(); +bool MenuStateConnectedGame::isHeadlessAdmin() { + bool result = false; + + ClientInterface *clientInterface = + NetworkManager::getInstance().getClientInterface(); + if (clientInterface != NULL && clientInterface->isConnected()) { + const GameSettings *settings = clientInterface->getGameSettings(); + if (settings != NULL) { + // printf("#1 admin key [%d] client key + // [%d]\n",settings->getMasterserver_admin(),clientInterface->getSessionKey()); + + if (settings->getMasterserver_admin() == + clientInterface->getSessionKey()) { + result = true; + } + } + } - for(int i = 0; i < mapInfo.players; ++i) { - if(listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) { - listBoxControls[i].setSelectedItemIndex(ctNetwork); - } - } - for(int i = mapInfo.players; i < GameConstants::maxPlayers; ++i) { - if(listBoxControls[i].getSelectedItemIndex() == ctNetwork) { - listBoxControls[i].setSelectedItemIndex(ctNetworkUnassigned); - } - } + return result; +} - if(validDisplayedGamesettings){ - copyToGameSettings(&displayedGamesettings); +void MenuStateConnectedGame::broadCastGameSettingsToHeadlessServer( + bool forceNow) { + if (isHeadlessAdmin() == false) { + return; + } + + if (forceNow == true || + ((needToBroadcastServerSettings == true) && + (difftime((long int)time(NULL), broadcastServerSettingsDelayTimer) >= + HEADLESSSERVER_BROADCAST_SETTINGS_SECONDS))) { + // printf("In [%s:%s] Line: %d forceNow = %d + // broadcastServerSettingsDelayTimer = " MG_SIZE_T_SPECIFIER ", now =" + // MG_SIZE_T_SPECIFIER + // "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,forceNow,broadcastServerSettingsDelayTimer,time(NULL)); + + needToBroadcastServerSettings = false; + broadcastServerSettingsDelayTimer = time(NULL); + + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + + for (int i = 0; i < mapInfo.players; ++i) { + if (listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) { + listBoxControls[i].setSelectedItemIndex(ctNetwork); + } + } + for (int i = mapInfo.players; i < GameConstants::maxPlayers; ++i) { + if (listBoxControls[i].getSelectedItemIndex() == ctNetwork) { + listBoxControls[i].setSelectedItemIndex(ctNetworkUnassigned); + } + } + if (validDisplayedGamesettings) { + copyToGameSettings(&displayedGamesettings); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("broadcast settings:\n%s\n",displayedGamesettings.toString().c_str()); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("broadcast settings:\n%s\n", + displayedGamesettings.toString().c_str()); - //printf("Client sending map [%s] admin key [%d]\n",gameSettings.getMap().c_str(),gameSettings.getMasterserver_admin()); - //printf("sending Settings map filter=%d\n",displayedGamesettings.getMapFilter()); - clientInterface->broadcastGameSetup(&displayedGamesettings); - noReceiveTimer=time(NULL); - } - } + // printf("Client sending map [%s] admin key + // [%d]\n",gameSettings.getMap().c_str(),gameSettings.getMasterserver_admin()); + // printf("sending Settings map + // filter=%d\n",displayedGamesettings.getMapFilter()); + clientInterface->broadcastGameSetup(&displayedGamesettings); + noReceiveTimer = time(NULL); + } + } } void MenuStateConnectedGame::updateResourceMultiplier(const int index) { - ControlType ct= static_cast(listBoxControls[index].getSelectedItemIndex()); - if(ct == ctCpuEasy || ct == ctNetworkCpuEasy) - { - listBoxRMultiplier[index].setSelectedItem(floatToStr(GameConstants::easyMultiplier,1)); - listBoxRMultiplier[index].setEnabled(true); - } - else if(ct == ctCpu || ct == ctNetworkCpu) { - listBoxRMultiplier[index].setSelectedItem(floatToStr(GameConstants::normalMultiplier,1)); - listBoxRMultiplier[index].setEnabled(true); - } - else if(ct == ctCpuUltra || ct == ctNetworkCpuUltra) - { - listBoxRMultiplier[index].setSelectedItem(floatToStr(GameConstants::ultraMultiplier,1)); - listBoxRMultiplier[index].setEnabled(true); - } - else if(ct == ctCpuMega || ct == ctNetworkCpuMega) - { - listBoxRMultiplier[index].setSelectedItem(floatToStr(GameConstants::megaMultiplier,1)); - listBoxRMultiplier[index].setEnabled(true); - } - else { - listBoxRMultiplier[index].setSelectedItem(floatToStr(GameConstants::normalMultiplier,1)); - listBoxRMultiplier[index].setEnabled(false); - } - - listBoxRMultiplier[index].setEditable(listBoxRMultiplier[index].getEnabled()); - listBoxRMultiplier[index].setVisible(listBoxRMultiplier[index].getEnabled()); + ControlType ct = + static_cast(listBoxControls[index].getSelectedItemIndex()); + if (ct == ctCpuEasy || ct == ctNetworkCpuEasy) { + listBoxRMultiplier[index].setSelectedItem( + floatToStr(GameConstants::easyMultiplier, 1)); + listBoxRMultiplier[index].setEnabled(true); + } else if (ct == ctCpu || ct == ctNetworkCpu) { + listBoxRMultiplier[index].setSelectedItem( + floatToStr(GameConstants::normalMultiplier, 1)); + listBoxRMultiplier[index].setEnabled(true); + } else if (ct == ctCpuUltra || ct == ctNetworkCpuUltra) { + listBoxRMultiplier[index].setSelectedItem( + floatToStr(GameConstants::ultraMultiplier, 1)); + listBoxRMultiplier[index].setEnabled(true); + } else if (ct == ctCpuMega || ct == ctNetworkCpuMega) { + listBoxRMultiplier[index].setSelectedItem( + floatToStr(GameConstants::megaMultiplier, 1)); + listBoxRMultiplier[index].setEnabled(true); + } else { + listBoxRMultiplier[index].setSelectedItem( + floatToStr(GameConstants::normalMultiplier, 1)); + listBoxRMultiplier[index].setEnabled(false); + } + + listBoxRMultiplier[index].setEditable(listBoxRMultiplier[index].getEnabled()); + listBoxRMultiplier[index].setVisible(listBoxRMultiplier[index].getEnabled()); } -void MenuStateConnectedGame::mouseClickAdmin(int x, int y, MouseButton mouseButton,string advanceToItemStartingWith) { - - try { - Lang &lang= Lang::getInstance(); - - int oldListBoxMapfilterIndex=listBoxMapFilter.getSelectedItemIndex(); - if(buttonPlayNow.mouseClick(x,y) && buttonPlayNow.getEnabled()) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - PlayNow(true); - return; +void MenuStateConnectedGame::mouseClickAdmin(int x, int y, + MouseButton mouseButton, + string advanceToItemStartingWith) { + + try { + Lang &lang = Lang::getInstance(); + + int oldListBoxMapfilterIndex = listBoxMapFilter.getSelectedItemIndex(); + if (buttonPlayNow.mouseClick(x, y) && buttonPlayNow.getEnabled()) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + PlayNow(true); + return; + } else if (checkBoxAllowNativeLanguageTechtree.mouseClick(x, y)) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + needToBroadcastServerSettings = true; + broadcastServerSettingsDelayTimer = time(NULL); + } else if (comboBoxMap.mouseClick(x, y)) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s\n", + getCurrentMapFile().c_str()); + + if (loadMapInfo(Config::getMapPath(getCurrentMapFile(), "", false), + &mapInfo, true, true) == true) { + labelMapInfo.setText(mapInfo.desc); + } else { + labelMapInfo.setText("???"); + } + + needToBroadcastServerSettings = true; + broadcastServerSettingsDelayTimer = time(NULL); + } else if (comboBoxMap.isDropDownShowing()) { + // do nothing + } else if (comboBoxLoadSetup.mouseClick(x, y)) { + } else if (comboBoxLoadSetup.isDropDownShowing()) { + // do nothing + } else if (listBoxFogOfWar.mouseClick(x, y)) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + needToBroadcastServerSettings = true; + broadcastServerSettingsDelayTimer = time(NULL); + } else if (labelSaveSetupName.mouseClick(x, y)) { + setActiveInputLabel(&labelSaveSetupName); + } else if (buttonSaveSetup.mouseClick(x, y)) { + GameSettings gameSettings; + copyToGameSettings(&gameSettings); + int humanSlots = 0; + for (int i = 0; i < gameSettings.getFactionCount(); i++) { + switch (gameSettings.getFactionControl(i)) { + case ctNetwork: + case ctHuman: + case ctNetworkUnassigned: + humanSlots++; + break; + default: + // do nothing + break; } - else if (checkBoxAllowNativeLanguageTechtree.mouseClick(x, y)) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - needToBroadcastServerSettings=true; - broadcastServerSettingsDelayTimer=time(NULL); + } + string setupName = intToStr(humanSlots) + "_" + gameSettings.getMap(); + labelSaveSetupName.setText(trim(labelSaveSetupName.getText())); + if (labelSaveSetupName.getText() != "") { + setupName = labelSaveSetupName.getText(); + setupName = replaceAll(setupName, "/", "_"); + setupName = replaceAll(setupName, "\\", "_"); + if (StartsWith(setupName, ".")) { + setupName[0] = '_'; } - else if(comboBoxMap.mouseClick(x, y)) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s\n", getCurrentMapFile().c_str()); - - if(loadMapInfo(Config::getMapPath(getCurrentMapFile(),"",false), &mapInfo, true,true) == true) { - labelMapInfo.setText(mapInfo.desc); - } - else { - labelMapInfo.setText("???"); - } - - needToBroadcastServerSettings=true; - broadcastServerSettingsDelayTimer=time(NULL); - } - else if(comboBoxMap.isDropDownShowing()){ - //do nothing - } - else if(comboBoxLoadSetup.mouseClick(x,y)){ - } - else if(comboBoxLoadSetup.isDropDownShowing()){ - //do nothing - } - else if(listBoxFogOfWar.mouseClick(x, y)) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - needToBroadcastServerSettings=true; - broadcastServerSettingsDelayTimer=time(NULL); - } - else if(labelSaveSetupName.mouseClick(x, y) ){ - setActiveInputLabel(&labelSaveSetupName); - } - else if ( buttonSaveSetup.mouseClick(x, y)){ - GameSettings gameSettings; - copyToGameSettings(&gameSettings); - int humanSlots=0; - for( int i=0; i " +filename); - loadSavedSetupNames(); - comboBoxLoadSetup.setItems(savedSetupFilenames); - comboBoxLoadSetup.setSelectedItem(setupName); - } - } - else if ( buttonLoadSetup.mouseClick(x, y)){ - string setupName=comboBoxLoadSetup.getSelectedItem(); - if( setupName!=""){ - string fileNameToLoad=SETUPS_DIR+setupName+".mgg"; - if( setupName== lang.getString(LAST_SETUP_STRING)){ - fileNameToLoad=HEADLESS_SAVED_SETUP_FILENAME; - } - if(loadGameSettings(fileNameToLoad)){ - console.addLine("<-- " +fileNameToLoad); - needToBroadcastServerSettings=true; - broadcastServerSettingsDelayTimer=time(NULL); - } - } - } - else if ( buttonDeleteSetup.mouseClick(x, y)){ - string setupName=comboBoxLoadSetup.getSelectedItem(); - if( setupName!=""&& setupName!= lang.getString(LAST_SETUP_STRING)) { - int index=comboBoxLoadSetup.getSelectedItemIndex(); - removeFile(savedSetupsDir+setupName+".mgg"); - loadSavedSetupNames(); - comboBoxLoadSetup.setItems(savedSetupFilenames); - if(comboBoxLoadSetup.getItemCount()>index){ - comboBoxLoadSetup.setSelectedItemIndex(index,false); - } - else{ - comboBoxLoadSetup.setSelectedItem( lang.getString(LAST_SETUP_STRING),false); - } - console.addLine("X " +setupName+".mgg"); - } - } - else if(checkBoxAllowObservers.mouseClick(x, y)) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - needToBroadcastServerSettings=true; - broadcastServerSettingsDelayTimer=time(NULL); - } - else if (checkBoxEnableSwitchTeamMode.mouseClick(x, y)) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - needToBroadcastServerSettings=true; - broadcastServerSettingsDelayTimer=time(NULL); + } + if (setupName != lang.getString(LAST_SETUP_STRING)) { + string filename = SETUPS_DIR + setupName + ".mgg"; + saveGameSettings(filename); + console.addLine("--> " + filename); + loadSavedSetupNames(); + comboBoxLoadSetup.setItems(savedSetupFilenames); + comboBoxLoadSetup.setSelectedItem(setupName); + } + } else if (buttonLoadSetup.mouseClick(x, y)) { + string setupName = comboBoxLoadSetup.getSelectedItem(); + if (setupName != "") { + string fileNameToLoad = SETUPS_DIR + setupName + ".mgg"; + if (setupName == lang.getString(LAST_SETUP_STRING)) { + fileNameToLoad = HEADLESS_SAVED_SETUP_FILENAME; } - else if(listBoxAISwitchTeamAcceptPercent.getEnabled() && listBoxAISwitchTeamAcceptPercent.mouseClick(x, y)) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - needToBroadcastServerSettings=true; - broadcastServerSettingsDelayTimer=time(NULL); + if (loadGameSettings(fileNameToLoad)) { + console.addLine("<-- " + fileNameToLoad); + needToBroadcastServerSettings = true; + broadcastServerSettingsDelayTimer = time(NULL); } - else if(listBoxFallbackCpuMultiplier.getEnabled() && listBoxFallbackCpuMultiplier.mouseClick(x, y)) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - needToBroadcastServerSettings=true; - broadcastServerSettingsDelayTimer=time(NULL); - } - else if(listBoxTileset.mouseClick(x, y,advanceToItemStartingWith)) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - needToBroadcastServerSettings=true; - broadcastServerSettingsDelayTimer=time(NULL); + } + } else if (buttonDeleteSetup.mouseClick(x, y)) { + string setupName = comboBoxLoadSetup.getSelectedItem(); + if (setupName != "" && setupName != lang.getString(LAST_SETUP_STRING)) { + int index = comboBoxLoadSetup.getSelectedItemIndex(); + removeFile(savedSetupsDir + setupName + ".mgg"); + loadSavedSetupNames(); + comboBoxLoadSetup.setItems(savedSetupFilenames); + if (comboBoxLoadSetup.getItemCount() > index) { + comboBoxLoadSetup.setSelectedItemIndex(index, false); + } else { + comboBoxLoadSetup.setSelectedItem(lang.getString(LAST_SETUP_STRING), + false); } + console.addLine("X " + setupName + ".mgg"); + } + } else if (checkBoxAllowObservers.mouseClick(x, y)) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + needToBroadcastServerSettings = true; + broadcastServerSettingsDelayTimer = time(NULL); + } else if (checkBoxEnableSwitchTeamMode.mouseClick(x, y)) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + needToBroadcastServerSettings = true; + broadcastServerSettingsDelayTimer = time(NULL); + } else if (listBoxAISwitchTeamAcceptPercent.getEnabled() && + listBoxAISwitchTeamAcceptPercent.mouseClick(x, y)) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + needToBroadcastServerSettings = true; + broadcastServerSettingsDelayTimer = time(NULL); + } else if (listBoxFallbackCpuMultiplier.getEnabled() && + listBoxFallbackCpuMultiplier.mouseClick(x, y)) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + needToBroadcastServerSettings = true; + broadcastServerSettingsDelayTimer = time(NULL); + } else if (listBoxTileset.mouseClick(x, y, advanceToItemStartingWith)) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + needToBroadcastServerSettings = true; + broadcastServerSettingsDelayTimer = time(NULL); + } - else if(listBoxMapFilter.mouseClick(x, y)){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s\n", getCurrentMapFile().c_str()); - switchToNextMapGroup(listBoxMapFilter.getSelectedItemIndex()-oldListBoxMapfilterIndex); - if(loadMapInfo(Config::getMapPath(getCurrentMapFile(),"",false), &mapInfo, true,true) == true) { - labelMapInfo.setText(mapInfo.desc); - } - else { - labelMapInfo.setText("???"); - } - needToBroadcastServerSettings=true; - broadcastServerSettingsDelayTimer=time(NULL); - } - else if(listBoxTechTree.mouseClick(x, y,advanceToItemStartingWith)) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - reloadFactions(false,""); - needToBroadcastServerSettings=true; - broadcastServerSettingsDelayTimer=time(NULL); - } + else if (listBoxMapFilter.mouseClick(x, y)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s\n", + getCurrentMapFile().c_str()); + switchToNextMapGroup(listBoxMapFilter.getSelectedItemIndex() - + oldListBoxMapfilterIndex); + if (loadMapInfo(Config::getMapPath(getCurrentMapFile(), "", false), + &mapInfo, true, true) == true) { + labelMapInfo.setText(mapInfo.desc); + } else { + labelMapInfo.setText("???"); + } + needToBroadcastServerSettings = true; + broadcastServerSettingsDelayTimer = time(NULL); + } else if (listBoxTechTree.mouseClick(x, y, advanceToItemStartingWith)) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + reloadFactions(false, ""); + needToBroadcastServerSettings = true; + broadcastServerSettingsDelayTimer = time(NULL); + } - else if (checkBoxAllowTeamUnitSharing.mouseClick(x, y)) { - needToBroadcastServerSettings=true; - broadcastServerSettingsDelayTimer=time(NULL); - } - else if (checkBoxAllowTeamResourceSharing.mouseClick(x, y)) { - needToBroadcastServerSettings=true; - broadcastServerSettingsDelayTimer=time(NULL); - } - else { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface* clientInterface= networkManager.getClientInterface(); - - for(int i=0; igetGameSettings() != NULL && - clientInterface->getGameSettings()->getStartLocationIndex(clientInterface->getGameSettings()->getThisFactionIndex()) != i && - listBoxControls[i].mouseClick(x, y)) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //!! this must be done two times!"" - if(listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) { - listBoxControls[i].mouseClick(x, y); - } - if( (isHeadlessAdmin()==true) && (listBoxControls[i].getSelectedItemIndex() == ctHuman)){ - listBoxControls[i].mouseClick(x, y); - } - //!! this must be done two times!"" - if(listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) { - listBoxControls[i].mouseClick(x, y); - } - - updateResourceMultiplier(i); - - needToBroadcastServerSettings=true; - broadcastServerSettingsDelayTimer=time(NULL); - } - else if(clientInterface != NULL && clientInterface->getGameSettings()->getStartLocationIndex(clientInterface->getGameSettings()->getThisFactionIndex()) != i && - listBoxFactions[i].mouseClick(x, y,advanceToItemStartingWith)) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - // Disallow CPU players to be observers - if(factionFiles[listBoxFactions[i].getSelectedItemIndex()] == formatString(GameConstants::OBSERVER_SLOTNAME) && - (listBoxControls[i].getSelectedItemIndex() == ctCpuEasy || listBoxControls[i].getSelectedItemIndex() == ctCpu || - listBoxControls[i].getSelectedItemIndex() == ctCpuUltra || listBoxControls[i].getSelectedItemIndex() == ctCpuMega)) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - listBoxFactions[i].setSelectedItemIndex(0); - } - - needToBroadcastServerSettings=true; - broadcastServerSettingsDelayTimer=time(NULL); - } - else if(clientInterface != NULL && clientInterface->getGameSettings()->getStartLocationIndex(clientInterface->getGameSettings()->getThisFactionIndex()) != i && - listBoxTeams[i].mouseClick(x, y)) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(factionFiles[listBoxFactions[i].getSelectedItemIndex()] != formatString(GameConstants::OBSERVER_SLOTNAME)) { - if(listBoxTeams[i].getSelectedItemIndex() + 1 != (GameConstants::maxPlayers + fpt_Observer)) { - //lastSelectedTeamIndex[i] = listBoxTeams[i].getSelectedItemIndex(); - } - } + else if (checkBoxAllowTeamUnitSharing.mouseClick(x, y)) { + needToBroadcastServerSettings = true; + broadcastServerSettingsDelayTimer = time(NULL); + } else if (checkBoxAllowTeamResourceSharing.mouseClick(x, y)) { + needToBroadcastServerSettings = true; + broadcastServerSettingsDelayTimer = time(NULL); + } else { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + + for (int i = 0; i < mapInfo.players; ++i) { + // set multiplier + if (listBoxRMultiplier[i].mouseClick(x, y)) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + // broadCastGameSettingsToMasterserver(); + needToBroadcastServerSettings = true; + broadcastServerSettingsDelayTimer = time(NULL); + } - needToBroadcastServerSettings=true; - broadcastServerSettingsDelayTimer=time(NULL); - } + // ensure that only 1 human player is present + if (clientInterface != NULL && + clientInterface->getGameSettings() != NULL && + clientInterface->getGameSettings()->getStartLocationIndex( + clientInterface->getGameSettings()->getThisFactionIndex()) != + i && + listBoxControls[i].mouseClick(x, y)) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + //!! this must be done two times!"" + if (listBoxControls[i].getSelectedItemIndex() == + ctNetworkUnassigned) { + listBoxControls[i].mouseClick(x, y); + } + if ((isHeadlessAdmin() == true) && + (listBoxControls[i].getSelectedItemIndex() == ctHuman)) { + listBoxControls[i].mouseClick(x, y); + } + //!! this must be done two times!"" + if (listBoxControls[i].getSelectedItemIndex() == + ctNetworkUnassigned) { + listBoxControls[i].mouseClick(x, y); + } + + updateResourceMultiplier(i); + + needToBroadcastServerSettings = true; + broadcastServerSettingsDelayTimer = time(NULL); + } else if (clientInterface != NULL && + clientInterface->getGameSettings()->getStartLocationIndex( + clientInterface->getGameSettings() + ->getThisFactionIndex()) != i && + listBoxFactions[i].mouseClick(x, y, + advanceToItemStartingWith)) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + // Disallow CPU players to be observers + if (factionFiles[listBoxFactions[i].getSelectedItemIndex()] == + formatString(GameConstants::OBSERVER_SLOTNAME) && + (listBoxControls[i].getSelectedItemIndex() == ctCpuEasy || + listBoxControls[i].getSelectedItemIndex() == ctCpu || + listBoxControls[i].getSelectedItemIndex() == ctCpuUltra || + listBoxControls[i].getSelectedItemIndex() == ctCpuMega)) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + listBoxFactions[i].setSelectedItemIndex(0); + } + + needToBroadcastServerSettings = true; + broadcastServerSettingsDelayTimer = time(NULL); + } else if (clientInterface != NULL && + clientInterface->getGameSettings()->getStartLocationIndex( + clientInterface->getGameSettings() + ->getThisFactionIndex()) != i && + listBoxTeams[i].mouseClick(x, y)) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + if (factionFiles[listBoxFactions[i].getSelectedItemIndex()] != + formatString(GameConstants::OBSERVER_SLOTNAME)) { + if (listBoxTeams[i].getSelectedItemIndex() + 1 != + (GameConstants::maxPlayers + fpt_Observer)) { + // lastSelectedTeamIndex[i] = + // listBoxTeams[i].getSelectedItemIndex(); } + } + + needToBroadcastServerSettings = true; + broadcastServerSettingsDelayTimer = time(NULL); } + } } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - - showMessageBox( szBuf, "Error", false); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + showMessageBox(szBuf, "Error", false); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); } void MenuStateConnectedGame::PlayNow(bool saveGame) { - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface *clientInterface = networkManager.getClientInterface(); - - GameSettings gameSettings = *clientInterface->getGameSettings(); - copyToGameSettings(&gameSettings); - - if(saveGame == true) { - CoreData::getInstance().saveGameSettingsToFile(HEADLESS_SAVED_SETUP_FILENAME,&gameSettings,true); - } - - CoreData &coreData= CoreData::getInstance(); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - soundRenderer.playFx(coreData.getClickSoundC()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //printf("Client sending map [%s] admin key [%d]\n",gameSettings.getMap().c_str(),gameSettings.getMasterserver_admin()); - - if(clientInterface->getJoinGameInProgress() == true) { - if(readyToJoinInProgressGame == false && launchingNewGame == false) { - Lang &lang= Lang::getInstance(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - char szMsg[8096]=""; - if(lang.hasString("JoinPlayerToCurrentGameLaunch",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("JoinPlayerToCurrentGameLaunch",languageList[i]).c_str(),getHumanPlayerName().c_str()); - } - else { - snprintf(szMsg,8096,"Player: %s is about to join the game, please wait...",getHumanPlayerName().c_str()); - } - bool localEcho = lang.isLanguageLocal(languageList[i]); - clientInterface->sendTextMessage(szMsg,-1, localEcho,languageList[i]); - } - - sleep(1); - launchingNewGame = true; - clientInterface->broadcastGameStart(&gameSettings); - } - return; - } - else { - launchingNewGame = true; - broadCastGameSettingsToHeadlessServer(needToBroadcastServerSettings); - clientInterface->broadcastGameStart(&gameSettings); - } -} + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + + GameSettings gameSettings = *clientInterface->getGameSettings(); + copyToGameSettings(&gameSettings); + + if (saveGame == true) { + CoreData::getInstance().saveGameSettingsToFile( + HEADLESS_SAVED_SETUP_FILENAME, &gameSettings, true); + } + + CoreData &coreData = CoreData::getInstance(); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + soundRenderer.playFx(coreData.getClickSoundC()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // printf("Client sending map [%s] admin key + // [%d]\n",gameSettings.getMap().c_str(),gameSettings.getMasterserver_admin()); + + if (clientInterface->getJoinGameInProgress() == true) { + if (readyToJoinInProgressGame == false && launchingNewGame == false) { + Lang &lang = Lang::getInstance(); + const vector languageList = + clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + char szMsg[8096] = ""; + if (lang.hasString("JoinPlayerToCurrentGameLaunch", languageList[i]) == + true) { + snprintf( + szMsg, 8096, + lang.getString("JoinPlayerToCurrentGameLaunch", languageList[i]) + .c_str(), + getHumanPlayerName().c_str()); + } else { + snprintf(szMsg, 8096, + "Player: %s is about to join the game, please wait...", + getHumanPlayerName().c_str()); + } + bool localEcho = lang.isLanguageLocal(languageList[i]); + clientInterface->sendTextMessage(szMsg, -1, localEcho, languageList[i]); + } -void MenuStateConnectedGame::switchToNextMapGroup(const int direction){ - int i=listBoxMapFilter.getSelectedItemIndex(); - // if there are no maps for the current selection we switch to next selection - while(formattedPlayerSortedMaps[i].empty()){ - i=i+direction; - if(i>GameConstants::maxPlayers){ - i=0; - } - if(i<0){ - i=GameConstants::maxPlayers; - } - } - switchToMapGroup(i); + sleep(1); + launchingNewGame = true; + clientInterface->broadcastGameStart(&gameSettings); + } + return; + } else { + launchingNewGame = true; + broadCastGameSettingsToHeadlessServer(needToBroadcastServerSettings); + clientInterface->broadcastGameStart(&gameSettings); + } } -void MenuStateConnectedGame::switchToMapGroup(int filterIndex){ - int i = filterIndex; - listBoxMapFilter.setSelectedItemIndex(i); - comboBoxMap.setItems(formattedPlayerSortedMaps[i]); -// printf("switching map group to filter=%d mapgroup has %d maps. map=%s \n",i, -// (int)formattedPlayerSortedMaps[i].size(),formattedPlayerSortedMaps[i][0].c_str()); +void MenuStateConnectedGame::switchToNextMapGroup(const int direction) { + int i = listBoxMapFilter.getSelectedItemIndex(); + // if there are no maps for the current selection we switch to next selection + while (formattedPlayerSortedMaps[i].empty()) { + i = i + direction; + if (i > GameConstants::maxPlayers) { + i = 0; + } + if (i < 0) { + i = GameConstants::maxPlayers; + } + } + switchToMapGroup(i); } -string MenuStateConnectedGame::getCurrentMapFile(){ - int i=listBoxMapFilter.getSelectedItemIndex(); - int mapIndex=comboBoxMap.getSelectedItemIndex(); - if(playerSortedMaps[i].empty() == false) { - return playerSortedMaps[i].at(mapIndex); - } - return ""; +void MenuStateConnectedGame::switchToMapGroup(int filterIndex) { + int i = filterIndex; + listBoxMapFilter.setSelectedItemIndex(i); + comboBoxMap.setItems(formattedPlayerSortedMaps[i]); + // printf("switching map group to filter=%d mapgroup has %d maps. map=%s + //\n",i, + // (int)formattedPlayerSortedMaps[i].size(),formattedPlayerSortedMaps[i][0].c_str()); } -string MenuStateConnectedGame::getPreselectedMapFile(){ - int i=listBoxMapFilter.getSelectedItemIndex(); - int mapIndex=comboBoxMap.getPreselectedItemIndex(); - if(playerSortedMaps[i].empty() == false) { - return playerSortedMaps[i].at(mapIndex); - } - return ""; +string MenuStateConnectedGame::getCurrentMapFile() { + int i = listBoxMapFilter.getSelectedItemIndex(); + int mapIndex = comboBoxMap.getSelectedItemIndex(); + if (playerSortedMaps[i].empty() == false) { + return playerSortedMaps[i].at(mapIndex); + } + return ""; } -void MenuStateConnectedGame::reloadFactions(bool keepExistingSelectedItem, string scenario) { - vector results; - Config &config = Config::getInstance(); - Lang &lang= Lang::getInstance(); - - string scenarioDir = Scenario::getScenarioDir(dirList, scenario); - vector techPaths = config.getPathListForType(ptTechs,scenarioDir); - for(int idx = 0; idx < (int)techPaths.size(); idx++) { - string &techPath = techPaths[idx]; - endPathWithSlash(techPath); +string MenuStateConnectedGame::getPreselectedMapFile() { + int i = listBoxMapFilter.getSelectedItemIndex(); + int mapIndex = comboBoxMap.getPreselectedItemIndex(); + if (playerSortedMaps[i].empty() == false) { + return playerSortedMaps[i].at(mapIndex); + } + return ""; +} - if(listBoxTechTree.getSelectedItemIndex() >= 0 && listBoxTechTree.getSelectedItemIndex() < (int)techTreeFiles.size()) { - findDirs(techPath + techTreeFiles[listBoxTechTree.getSelectedItemIndex()] + "/factions/", results, false, false); - } - if(results.empty() == false) { - break; +void MenuStateConnectedGame::reloadFactions(bool keepExistingSelectedItem, + string scenario) { + vector results; + Config &config = Config::getInstance(); + Lang &lang = Lang::getInstance(); + + string scenarioDir = Scenario::getScenarioDir(dirList, scenario); + vector techPaths = config.getPathListForType(ptTechs, scenarioDir); + for (int idx = 0; idx < (int)techPaths.size(); idx++) { + string &techPath = techPaths[idx]; + endPathWithSlash(techPath); + + if (listBoxTechTree.getSelectedItemIndex() >= 0 && + listBoxTechTree.getSelectedItemIndex() < (int)techTreeFiles.size()) { + findDirs(techPath + + techTreeFiles[listBoxTechTree.getSelectedItemIndex()] + + "/factions/", + results, false, false); + } + if (results.empty() == false) { + break; + } + } + + if (results.empty() == true) { + // throw megaglest_runtime_error("(2)There are no factions for the tech tree + // [" + techTreeFiles[listBoxTechTree.getSelectedItemIndex()] + "]"); + // showGeneralError=true; + // generalErrorToShow = "[#2] There are no factions for the tech tree [" + + // techTreeFiles[listBoxTechTree.getSelectedItemIndex()] + "]"; + } + + vector translatedFactionNames; + factionFiles = results; + for (int i = 0; i < (int)results.size(); ++i) { + results[i] = formatString(results[i]); + string translatedString = techTree->getTranslatedFactionName( + techTreeFiles[listBoxTechTree.getSelectedItemIndex()], factionFiles[i]); + if (toLower(translatedString) == toLower(results[i])) { + translatedFactionNames.push_back(results[i]); + } else { + translatedFactionNames.push_back(results[i] + " (" + translatedString + + ")"); + } + // printf("FACTIONS i = %d results [%s]\n",i,results[i].c_str()); + + 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()); + } + + results.push_back(formatString(GameConstants::RANDOMFACTION_SLOTNAME)); + factionFiles.push_back(formatString(GameConstants::RANDOMFACTION_SLOTNAME)); + translatedFactionNames.push_back("*" + lang.getString("Random", "", true) + + "*"); + + // Add special Observer Faction + if (checkBoxAllowObservers.getValue() == 1) { + results.push_back(formatString(GameConstants::OBSERVER_SLOTNAME)); + factionFiles.push_back(formatString(GameConstants::OBSERVER_SLOTNAME)); + translatedFactionNames.push_back( + "*" + lang.getString("Observer", "", true) + "*"); + } + + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + int originalIndex = listBoxFactions[i].getSelectedItemIndex(); + string originalValue = (listBoxFactions[i].getItemCount() > 0 + ? listBoxFactions[i].getSelectedItem() + : ""); + + listBoxFactions[i].setItems(results, translatedFactionNames); + if (keepExistingSelectedItem == false || + (checkBoxAllowObservers.getValue() == true && + originalValue == formatString(GameConstants::OBSERVER_SLOTNAME))) { + listBoxFactions[i].setSelectedItemIndex(i % results.size()); + + if (originalValue == formatString(GameConstants::OBSERVER_SLOTNAME) && + listBoxFactions[i].getSelectedItem() != + formatString(GameConstants::OBSERVER_SLOTNAME)) { + if (listBoxTeams[i].getSelectedItem() == + intToStr(GameConstants::maxPlayers + fpt_Observer)) { + listBoxTeams[i].setSelectedItem(intToStr(1)); } + } + } else if (originalIndex < (int)results.size()) { + listBoxFactions[i].setSelectedItemIndex(originalIndex); } + } +} - if(results.empty() == true) { - //throw megaglest_runtime_error("(2)There are no factions for the tech tree [" + techTreeFiles[listBoxTechTree.getSelectedItemIndex()] + "]"); - //showGeneralError=true; - //generalErrorToShow = "[#2] There are no factions for the tech tree [" + techTreeFiles[listBoxTechTree.getSelectedItemIndex()] + "]"; - } - - vector translatedFactionNames; - factionFiles= results; - for(int i = 0; i < (int)results.size(); ++i) { - results[i]= formatString(results[i]); - string translatedString=techTree->getTranslatedFactionName(techTreeFiles[listBoxTechTree.getSelectedItemIndex()],factionFiles[i]); - if(toLower(translatedString)==toLower(results[i])){ - translatedFactionNames.push_back(results[i]); - } - else { - translatedFactionNames.push_back(results[i]+" ("+translatedString+")"); - } - //printf("FACTIONS i = %d results [%s]\n",i,results[i].c_str()); - - 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()); - } - - results.push_back(formatString(GameConstants::RANDOMFACTION_SLOTNAME)); - factionFiles.push_back(formatString(GameConstants::RANDOMFACTION_SLOTNAME)); - translatedFactionNames.push_back("*"+lang.getString("Random","",true)+"*"); - - // Add special Observer Faction - if(checkBoxAllowObservers.getValue() == 1) { - results.push_back(formatString(GameConstants::OBSERVER_SLOTNAME)); - factionFiles.push_back(formatString(GameConstants::OBSERVER_SLOTNAME)); - translatedFactionNames.push_back("*"+lang.getString("Observer","",true)+"*"); - } - - for(int i=0; i 0 ? listBoxFactions[i].getSelectedItem() : ""); - - listBoxFactions[i].setItems(results,translatedFactionNames); - if( keepExistingSelectedItem == false || - (checkBoxAllowObservers.getValue() == true && - originalValue == formatString(GameConstants::OBSERVER_SLOTNAME)) ) { - listBoxFactions[i].setSelectedItemIndex(i % results.size()); - - if( originalValue == formatString(GameConstants::OBSERVER_SLOTNAME) && - listBoxFactions[i].getSelectedItem() != formatString(GameConstants::OBSERVER_SLOTNAME)) { - if(listBoxTeams[i].getSelectedItem() == intToStr(GameConstants::maxPlayers + fpt_Observer)) { - listBoxTeams[i].setSelectedItem(intToStr(1)); - } - } +void MenuStateConnectedGame::copyToGameSettings(GameSettings *gameSettings) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + int factionCount = 0; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // Test flags values + // gameSettings->setFlagTypes1(ft1_show_map_resources); + // + + if (checkBoxScenario.getValue() == true) { + gameSettings->setScenario(scenarioInfo.name); + gameSettings->setScenarioDir( + Scenario::getScenarioPath(dirList, scenarioInfo.name)); + + gameSettings->setDefaultResources(scenarioInfo.defaultResources); + gameSettings->setDefaultUnits(scenarioInfo.defaultUnits); + gameSettings->setDefaultVictoryConditions( + scenarioInfo.defaultVictoryConditions); + } else { + gameSettings->setScenario(""); + gameSettings->setScenarioDir(""); + } + + gameSettings->setNetworkAllowNativeLanguageTechtree( + checkBoxAllowNativeLanguageTechtree.getValue()); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d] listBoxMap.getSelectedItemIndex() = %d, " + "mapFiles.size() = " MG_SIZE_T_SPECIFIER + ", getCurrentMapFile() [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, comboBoxMap.getSelectedItemIndex(), mapFiles.size(), + getCurrentMapFile().c_str()); + + if (comboBoxMap.getSelectedItemIndex() >= 0 && + comboBoxMap.getSelectedItemIndex() < (int)mapFiles.size()) { + gameSettings->setDescription(formatString(getCurrentMapFile())); + gameSettings->setMap(getCurrentMapFile()); + gameSettings->setMapFilter(listBoxMapFilter.getSelectedItemIndex()); + } else { + Lang &lang = Lang::getInstance(); + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + const vector languageList = + clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + char szMsg[8096] = ""; + if (lang.hasString("DataMissingMap=Player", languageList[i]) == true) { + snprintf( + szMsg, 8096, + lang.getString("DataMissingMap=Player", languageList[i]).c_str(), + getHumanPlayerName().c_str(), + comboBoxMap.getSelectedItem().c_str()); + } else { + snprintf(szMsg, 8096, "Player: %s is missing the map: %s", + getHumanPlayerName().c_str(), + comboBoxMap.getSelectedItem().c_str()); + } + bool localEcho = lang.isLanguageLocal(languageList[i]); + clientInterface->sendTextMessage(szMsg, -1, localEcho, languageList[i]); + } + } + + if (listBoxTileset.getSelectedItemIndex() >= 0 && + listBoxTileset.getSelectedItemIndex() < (int)tilesetFiles.size()) { + gameSettings->setTileset( + tilesetFiles[listBoxTileset.getSelectedItemIndex()]); + } else { + // printf("A loadGameSettings listBoxTileset.getSelectedItemIndex() = %d + // tilesetFiles.size() = + // %d\n",listBoxTileset.getSelectedItemIndex(),tilesetFiles.size()); + + Lang &lang = Lang::getInstance(); + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + const vector languageList = + clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + char szMsg[8096] = ""; + if (lang.hasString("DataMissingTileset=Player", languageList[i]) == + true) { + snprintf(szMsg, 8096, + lang.getString("DataMissingTileset=Player", languageList[i]) + .c_str(), + getHumanPlayerName().c_str(), + listBoxTileset.getSelectedItem().c_str()); + } else { + snprintf(szMsg, 8096, "Player: %s is missing the tileset: %s", + getHumanPlayerName().c_str(), + listBoxTileset.getSelectedItem().c_str()); + } + bool localEcho = lang.isLanguageLocal(languageList[i]); + clientInterface->sendTextMessage(szMsg, -1, localEcho, languageList[i]); + } + } + if (listBoxTechTree.getSelectedItemIndex() >= 0 && + listBoxTechTree.getSelectedItemIndex() < (int)techTreeFiles.size()) { + gameSettings->setTech( + techTreeFiles[listBoxTechTree.getSelectedItemIndex()]); + } else { + Lang &lang = Lang::getInstance(); + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + const vector languageList = + clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + char szMsg[8096] = ""; + if (lang.hasString("DataMissingTechtree=Player", languageList[i]) == + true) { + snprintf(szMsg, 8096, + lang.getString("DataMissingTechtree=Player", languageList[i]) + .c_str(), + getHumanPlayerName().c_str(), + listBoxTechTree.getSelectedItem().c_str()); + } else { + snprintf(szMsg, 8096, "Player: %s is missing the techtree: %s", + getHumanPlayerName().c_str(), + listBoxTechTree.getSelectedItem().c_str()); + } + bool localEcho = lang.isLanguageLocal(languageList[i]); + clientInterface->sendTextMessage(szMsg, -1, localEcho, languageList[i]); + } + } + + if (checkBoxScenario.getValue() == false) { + gameSettings->setDefaultUnits(true); + gameSettings->setDefaultResources(true); + gameSettings->setDefaultVictoryConditions(true); + } + + gameSettings->setFogOfWar(listBoxFogOfWar.getSelectedItemIndex() == 0 || + listBoxFogOfWar.getSelectedItemIndex() == 1); + + gameSettings->setAllowObservers(checkBoxAllowObservers.getValue() == true); + + uint32 valueFlags1 = gameSettings->getFlagTypes1(); + if (listBoxFogOfWar.getSelectedItemIndex() == 1 || + listBoxFogOfWar.getSelectedItemIndex() == 2) { + valueFlags1 |= ft1_show_map_resources; + gameSettings->setFlagTypes1(valueFlags1); + } else { + valueFlags1 &= ~ft1_show_map_resources; + gameSettings->setFlagTypes1(valueFlags1); + } + + // gameSettings->setEnableObserverModeAtEndGame(listBoxEnableObserverMode.getSelectedItemIndex() + // == 0); + gameSettings->setEnableObserverModeAtEndGame(true); + // gameSettings->setPathFinderType(static_cast(listBoxPathFinderType.getSelectedItemIndex())); + + valueFlags1 = gameSettings->getFlagTypes1(); + if (checkBoxEnableSwitchTeamMode.getValue() == true) { + valueFlags1 |= ft1_allow_team_switching; + gameSettings->setFlagTypes1(valueFlags1); + } else { + valueFlags1 &= ~ft1_allow_team_switching; + gameSettings->setFlagTypes1(valueFlags1); + } + gameSettings->setAiAcceptSwitchTeamPercentChance( + strToInt(listBoxAISwitchTeamAcceptPercent.getSelectedItem())); + gameSettings->setFallbackCpuMultiplier( + listBoxFallbackCpuMultiplier.getSelectedItemIndex()); + + valueFlags1 = gameSettings->getFlagTypes1(); + if (checkBoxAllowTeamUnitSharing.getValue() == true) { + valueFlags1 |= ft1_allow_shared_team_units; + gameSettings->setFlagTypes1(valueFlags1); + } else { + valueFlags1 &= ~ft1_allow_shared_team_units; + gameSettings->setFlagTypes1(valueFlags1); + } + + valueFlags1 = gameSettings->getFlagTypes1(); + if (checkBoxAllowTeamResourceSharing.getValue() == true) { + valueFlags1 |= ft1_allow_shared_team_resources; + gameSettings->setFlagTypes1(valueFlags1); + } else { + valueFlags1 &= ~ft1_allow_shared_team_resources; + gameSettings->setFlagTypes1(valueFlags1); + } + + // First save Used slots + // for(int i=0; i(listBoxControls[i].getSelectedItemIndex()); + + if (ct != ctClosed) { + int slotIndex = factionCount; + ControlType oldControlType = gameSettings->getFactionControl(slotIndex); + gameSettings->setFactionControl(slotIndex, ct); + if (ct == ctHuman) { + // 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()); + + gameSettings->setThisFactionIndex(slotIndex); + gameSettings->setNetworkPlayerName(slotIndex, getHumanPlayerName()); + gameSettings->setNetworkPlayerUUID( + slotIndex, Config::getInstance().getString("PlayerId", "")); + gameSettings->setNetworkPlayerPlatform(slotIndex, + getPlatformNameString()); + gameSettings->setNetworkPlayerStatuses(slotIndex, + getNetworkPlayerStatus()); + Lang &lang = Lang::getInstance(); + gameSettings->setNetworkPlayerLanguages(slotIndex, lang.getLanguage()); + + gameSettings->setResourceMultiplierIndex(slotIndex, 5); + } else { + gameSettings->setResourceMultiplierIndex( + slotIndex, listBoxRMultiplier[i].getSelectedItemIndex()); + } + + 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()); + + gameSettings->setFactionTypeName( + slotIndex, factionFiles[listBoxFactions[i].getSelectedItemIndex()]); + if (factionFiles[listBoxFactions[i].getSelectedItemIndex()] == + formatString(GameConstants::OBSERVER_SLOTNAME)) { + listBoxTeams[i].setSelectedItem( + intToStr(GameConstants::maxPlayers + fpt_Observer)); + } + + gameSettings->setTeam(slotIndex, listBoxTeams[i].getSelectedItemIndex()); + gameSettings->setStartLocationIndex(slotIndex, i); + // printf("!!! setStartLocationIndex #1 slotIndex = %d, i = + // %d\n",slotIndex, i); + + if (listBoxControls[i].getSelectedItemIndex() == ctNetwork || + listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) { + if (oldControlType != ctNetwork && + oldControlType != ctNetworkUnassigned) { + gameSettings->setNetworkPlayerName(slotIndex, ""); } - else if(originalIndex < (int)results.size()) { - listBoxFactions[i].setSelectedItemIndex(originalIndex); + } else if (listBoxControls[i].getSelectedItemIndex() != ctHuman) { + AIPlayerCount++; + 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); + + Lang &lang = Lang::getInstance(); + gameSettings->setNetworkPlayerName( + slotIndex, lang.getString("AI") + intToStr(AIPlayerCount)); + labelPlayerNames[i].setText(""); + } + + factionCount++; + } else { + labelPlayerNames[i].setText(""); + } + } + + // Next save closed slots + int closedCount = 0; + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + ControlType ct = + static_cast(listBoxControls[i].getSelectedItemIndex()); + if (ct == ctClosed) { + int slotIndex = factionCount + closedCount; + + gameSettings->setFactionControl(slotIndex, ct); + gameSettings->setTeam(slotIndex, listBoxTeams[i].getSelectedItemIndex()); + gameSettings->setStartLocationIndex(slotIndex, i); + // printf("!!! setStartLocationIndex #2 slotIndex = %d, i = + // %d\n",slotIndex, i); + + gameSettings->setResourceMultiplierIndex(slotIndex, 5); + + 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()); + + gameSettings->setFactionTypeName( + slotIndex, factionFiles[listBoxFactions[i].getSelectedItemIndex()]); + gameSettings->setNetworkPlayerStatuses(slotIndex, npst_None); + gameSettings->setNetworkPlayerName( + slotIndex, GameConstants::NETWORK_SLOT_CLOSED_SLOTNAME); + + closedCount++; + } + } + + gameSettings->setFactionCount(factionCount); + + Config &config = Config::getInstance(); + gameSettings->setEnableServerControlledAI( + config.getBool("ServerControlledAI", "true")); + gameSettings->setNetworkFramePeriod( + config.getInt("NetworkSendFrameCount", "20")); + + if (hasNetworkGameSettings() == true) { + if (gameSettings->getTileset() != "") { + if (lastCheckedCRCTilesetName != gameSettings->getTileset()) { + // console.addLine("Checking tileset CRC [" + gameSettings->getTileset() + // + "]"); + lastCheckedCRCTilesetValue = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTilesets, ""), + string("/") + gameSettings->getTileset() + string("/*"), ".xml", + NULL); + if (lastCheckedCRCTilesetValue == 0 || + lastCheckedCRCTilesetValue != gameSettings->getTilesetCRC()) { + lastCheckedCRCTilesetValue = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTilesets, ""), + string("/") + gameSettings->getTileset() + string("/*"), ".xml", + NULL, true); } + lastCheckedCRCTilesetName = gameSettings->getTileset(); + } + gameSettings->setTilesetCRC(lastCheckedCRCTilesetValue); } -} -void MenuStateConnectedGame::copyToGameSettings(GameSettings *gameSettings) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - int factionCount= 0; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - // Test flags values - //gameSettings->setFlagTypes1(ft1_show_map_resources); - // - - if(checkBoxScenario.getValue() == true) { - gameSettings->setScenario(scenarioInfo.name); - gameSettings->setScenarioDir(Scenario::getScenarioPath(dirList, scenarioInfo.name)); - - gameSettings->setDefaultResources(scenarioInfo.defaultResources); - gameSettings->setDefaultUnits(scenarioInfo.defaultUnits); - gameSettings->setDefaultVictoryConditions(scenarioInfo.defaultVictoryConditions); - } - else { - gameSettings->setScenario(""); - gameSettings->setScenarioDir(""); - } - - gameSettings->setNetworkAllowNativeLanguageTechtree(checkBoxAllowNativeLanguageTechtree.getValue()); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d] listBoxMap.getSelectedItemIndex() = %d, mapFiles.size() = " MG_SIZE_T_SPECIFIER ", getCurrentMapFile() [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,comboBoxMap.getSelectedItemIndex(),mapFiles.size(),getCurrentMapFile().c_str()); - - if(comboBoxMap.getSelectedItemIndex() >= 0 && comboBoxMap.getSelectedItemIndex() < (int)mapFiles.size()) { - gameSettings->setDescription(formatString(getCurrentMapFile())); - gameSettings->setMap(getCurrentMapFile()); - gameSettings->setMapFilter(listBoxMapFilter.getSelectedItemIndex()); - } - else { - Lang &lang= Lang::getInstance(); - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface *clientInterface = networkManager.getClientInterface(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - char szMsg[8096]=""; - if(lang.hasString("DataMissingMap=Player",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("DataMissingMap=Player",languageList[i]).c_str(),getHumanPlayerName().c_str(),comboBoxMap.getSelectedItem().c_str()); - } - else { - snprintf(szMsg,8096,"Player: %s is missing the map: %s",getHumanPlayerName().c_str(),comboBoxMap.getSelectedItem().c_str()); - } - bool localEcho = lang.isLanguageLocal(languageList[i]); - clientInterface->sendTextMessage(szMsg,-1, localEcho,languageList[i]); - } - } - - if(listBoxTileset.getSelectedItemIndex() >= 0 && listBoxTileset.getSelectedItemIndex() < (int)tilesetFiles.size()) { - gameSettings->setTileset(tilesetFiles[listBoxTileset.getSelectedItemIndex()]); - } - else { - //printf("A loadGameSettings listBoxTileset.getSelectedItemIndex() = %d tilesetFiles.size() = %d\n",listBoxTileset.getSelectedItemIndex(),tilesetFiles.size()); - - Lang &lang= Lang::getInstance(); - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface *clientInterface = networkManager.getClientInterface(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - char szMsg[8096]=""; - if(lang.hasString("DataMissingTileset=Player",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("DataMissingTileset=Player",languageList[i]).c_str(),getHumanPlayerName().c_str(),listBoxTileset.getSelectedItem().c_str()); - } - else { - snprintf(szMsg,8096,"Player: %s is missing the tileset: %s",getHumanPlayerName().c_str(),listBoxTileset.getSelectedItem().c_str()); - } - bool localEcho = lang.isLanguageLocal(languageList[i]); - clientInterface->sendTextMessage(szMsg,-1, localEcho,languageList[i]); - } - } - if(listBoxTechTree.getSelectedItemIndex() >= 0 && listBoxTechTree.getSelectedItemIndex() < (int)techTreeFiles.size()) { - gameSettings->setTech(techTreeFiles[listBoxTechTree.getSelectedItemIndex()]); - } - else { - Lang &lang= Lang::getInstance(); - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface *clientInterface = networkManager.getClientInterface(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - char szMsg[8096]=""; - if(lang.hasString("DataMissingTechtree=Player",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("DataMissingTechtree=Player",languageList[i]).c_str(),getHumanPlayerName().c_str(),listBoxTechTree.getSelectedItem().c_str()); - } - else { - snprintf(szMsg,8096,"Player: %s is missing the techtree: %s",getHumanPlayerName().c_str(),listBoxTechTree.getSelectedItem().c_str()); - } - bool localEcho = lang.isLanguageLocal(languageList[i]); - clientInterface->sendTextMessage(szMsg,-1, localEcho,languageList[i]); - } - } - - if(checkBoxScenario.getValue() == false) { - gameSettings->setDefaultUnits(true); - gameSettings->setDefaultResources(true); - gameSettings->setDefaultVictoryConditions(true); - } - - gameSettings->setFogOfWar(listBoxFogOfWar.getSelectedItemIndex() == 0 || - listBoxFogOfWar.getSelectedItemIndex() == 1 ); - - gameSettings->setAllowObservers(checkBoxAllowObservers.getValue() == true); - - uint32 valueFlags1 = gameSettings->getFlagTypes1(); - if(listBoxFogOfWar.getSelectedItemIndex() == 1 || - listBoxFogOfWar.getSelectedItemIndex() == 2 ) { - valueFlags1 |= ft1_show_map_resources; - gameSettings->setFlagTypes1(valueFlags1); - } - else { - valueFlags1 &= ~ft1_show_map_resources; - gameSettings->setFlagTypes1(valueFlags1); - } - - //gameSettings->setEnableObserverModeAtEndGame(listBoxEnableObserverMode.getSelectedItemIndex() == 0); - gameSettings->setEnableObserverModeAtEndGame(true); - //gameSettings->setPathFinderType(static_cast(listBoxPathFinderType.getSelectedItemIndex())); - - valueFlags1 = gameSettings->getFlagTypes1(); - if(checkBoxEnableSwitchTeamMode.getValue() == true) { - valueFlags1 |= ft1_allow_team_switching; - gameSettings->setFlagTypes1(valueFlags1); - } - else { - valueFlags1 &= ~ft1_allow_team_switching; - gameSettings->setFlagTypes1(valueFlags1); - } - gameSettings->setAiAcceptSwitchTeamPercentChance(strToInt(listBoxAISwitchTeamAcceptPercent.getSelectedItem())); - gameSettings->setFallbackCpuMultiplier(listBoxFallbackCpuMultiplier.getSelectedItemIndex()); - - valueFlags1 = gameSettings->getFlagTypes1(); - if(checkBoxAllowTeamUnitSharing.getValue() == true) { - valueFlags1 |= ft1_allow_shared_team_units; - gameSettings->setFlagTypes1(valueFlags1); - } - else { - valueFlags1 &= ~ft1_allow_shared_team_units; - gameSettings->setFlagTypes1(valueFlags1); - } - - valueFlags1 = gameSettings->getFlagTypes1(); - if(checkBoxAllowTeamResourceSharing.getValue() == true) { - valueFlags1 |= ft1_allow_shared_team_resources; - gameSettings->setFlagTypes1(valueFlags1); - } - else { - valueFlags1 &= ~ft1_allow_shared_team_resources; - gameSettings->setFlagTypes1(valueFlags1); - } - - // First save Used slots - //for(int i=0; i(listBoxControls[i].getSelectedItemIndex()); - - if(ct != ctClosed) { - int slotIndex = factionCount; - ControlType oldControlType=gameSettings->getFactionControl(slotIndex); - gameSettings->setFactionControl(slotIndex, ct); - if(ct == ctHuman) { - //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()); - - gameSettings->setThisFactionIndex(slotIndex); - gameSettings->setNetworkPlayerName(slotIndex, getHumanPlayerName()); - gameSettings->setNetworkPlayerUUID(slotIndex,Config::getInstance().getString("PlayerId","")); - gameSettings->setNetworkPlayerPlatform(slotIndex,getPlatformNameString()); - gameSettings->setNetworkPlayerStatuses(slotIndex, getNetworkPlayerStatus()); - Lang &lang= Lang::getInstance(); - gameSettings->setNetworkPlayerLanguages(slotIndex, lang.getLanguage()); - - gameSettings->setResourceMultiplierIndex(slotIndex, 5); - } - else { - gameSettings->setResourceMultiplierIndex(slotIndex, listBoxRMultiplier[i].getSelectedItemIndex()); - } - - 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()); - - gameSettings->setFactionTypeName(slotIndex, factionFiles[listBoxFactions[i].getSelectedItemIndex()]); - if(factionFiles[listBoxFactions[i].getSelectedItemIndex()] == formatString(GameConstants::OBSERVER_SLOTNAME)) { - listBoxTeams[i].setSelectedItem(intToStr(GameConstants::maxPlayers + fpt_Observer)); - } - - gameSettings->setTeam(slotIndex, listBoxTeams[i].getSelectedItemIndex()); - gameSettings->setStartLocationIndex(slotIndex, i); - //printf("!!! setStartLocationIndex #1 slotIndex = %d, i = %d\n",slotIndex, i); - - if(listBoxControls[i].getSelectedItemIndex() == ctNetwork || listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) { - if(oldControlType!=ctNetwork && oldControlType!=ctNetworkUnassigned ){ - gameSettings->setNetworkPlayerName(slotIndex,""); - } - } - else if (listBoxControls[i].getSelectedItemIndex() != ctHuman) { - AIPlayerCount++; - 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); - - Lang &lang= Lang::getInstance(); - gameSettings->setNetworkPlayerName(slotIndex, lang.getString("AI") + intToStr(AIPlayerCount)); - labelPlayerNames[i].setText(""); - } - - factionCount++; - } - else { - labelPlayerNames[i].setText(""); - } - } - - // Next save closed slots - int closedCount = 0; - for(int i = 0; i < GameConstants::maxPlayers; ++i) { - ControlType ct= static_cast(listBoxControls[i].getSelectedItemIndex()); - if(ct == ctClosed) { - int slotIndex = factionCount + closedCount; - - gameSettings->setFactionControl(slotIndex, ct); - gameSettings->setTeam(slotIndex, listBoxTeams[i].getSelectedItemIndex()); - gameSettings->setStartLocationIndex(slotIndex, i); - //printf("!!! setStartLocationIndex #2 slotIndex = %d, i = %d\n",slotIndex, i); - - gameSettings->setResourceMultiplierIndex(slotIndex, 5); - - 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()); - - gameSettings->setFactionTypeName(slotIndex, factionFiles[listBoxFactions[i].getSelectedItemIndex()]); - gameSettings->setNetworkPlayerStatuses(slotIndex, npst_None); - gameSettings->setNetworkPlayerName(slotIndex, GameConstants::NETWORK_SLOT_CLOSED_SLOTNAME); - - closedCount++; - } - } - - gameSettings->setFactionCount(factionCount); - - Config &config = Config::getInstance(); - gameSettings->setEnableServerControlledAI(config.getBool("ServerControlledAI","true")); - gameSettings->setNetworkFramePeriod(config.getInt("NetworkSendFrameCount","20")); - - if(hasNetworkGameSettings() == true) { - if( gameSettings->getTileset() != "") { - if(lastCheckedCRCTilesetName != gameSettings->getTileset()) { - //console.addLine("Checking tileset CRC [" + gameSettings->getTileset() + "]"); - lastCheckedCRCTilesetValue = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTilesets,""), string("/") + gameSettings->getTileset() + string("/*"), ".xml", NULL); - if(lastCheckedCRCTilesetValue == 0 || lastCheckedCRCTilesetValue != gameSettings->getTilesetCRC()) { - lastCheckedCRCTilesetValue = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTilesets,""), string("/") + gameSettings->getTileset() + string("/*"), ".xml", NULL, true); - } - lastCheckedCRCTilesetName = gameSettings->getTileset(); - } - gameSettings->setTilesetCRC(lastCheckedCRCTilesetValue); - } - - if(config.getBool("DisableServerLobbyTechtreeCRCCheck","false") == false) { - if(gameSettings->getTech() != "") { - if(lastCheckedCRCTechtreeName != gameSettings->getTech()) { - //console.addLine("Checking techtree CRC [" + gameSettings->getTech() + "]"); - lastCheckedCRCTechtreeValue = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), "/" + gameSettings->getTech() + "/*", ".xml", NULL); - if(lastCheckedCRCTechtreeValue == 0 || lastCheckedCRCTechtreeValue != gameSettings->getTechCRC()) { - lastCheckedCRCTechtreeValue = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), "/" + gameSettings->getTech() + "/*", ".xml", NULL, true); - } - - reloadFactions(true,gameSettings->getScenario()); - factionCRCList.clear(); - for(unsigned int factionIdx = 0; factionIdx < factionFiles.size(); ++factionIdx) { - string factionName = factionFiles[factionIdx]; - if(factionName != GameConstants::RANDOMFACTION_SLOTNAME && - factionName != GameConstants::OBSERVER_SLOTNAME) { - //factionCRC = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), "/" + gameSettings->getTech() + "/factions/" + factionName + "/*", ".xml", NULL, true); - uint32 factionCRC = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), "/" + gameSettings->getTech() + "/factions/" + factionName + "/*", ".xml", NULL); - if(factionCRC == 0) { - factionCRC = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), "/" + gameSettings->getTech() + "/factions/" + factionName + "/*", ".xml", NULL, true); - } - factionCRCList.push_back(make_pair(factionName,factionCRC)); - } - } - //console.addLine("Found factions: " + intToStr(factionCRCList.size())); - lastCheckedCRCTechtreeName = gameSettings->getTech(); - } - - gameSettings->setFactionCRCList(factionCRCList); - gameSettings->setTechCRC(lastCheckedCRCTechtreeValue); - } - } - - if(gameSettings->getMap() != "") { - if(lastCheckedCRCMapName != gameSettings->getMap()) { - Checksum checksum; - string file = Config::getMapPath(gameSettings->getMap(),"",false); - //console.addLine("Checking map CRC [" + file + "]"); - checksum.addFile(file); - lastCheckedCRCMapValue = checksum.getSum(); - lastCheckedCRCMapName = gameSettings->getMap(); - } - gameSettings->setMapCRC(lastCheckedCRCMapValue); - } - } - - //replace server player by network - for(int i= 0; i< gameSettings->getFactionCount(); ++i) { - //replace by network - if(gameSettings->getFactionControl(i)==ctHuman) { - gameSettings->setFactionControl(i, ctNetwork); + if (config.getBool("DisableServerLobbyTechtreeCRCCheck", "false") == + false) { + if (gameSettings->getTech() != "") { + if (lastCheckedCRCTechtreeName != gameSettings->getTech()) { + // console.addLine("Checking techtree CRC [" + gameSettings->getTech() + // + "]"); + lastCheckedCRCTechtreeValue = + getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTechs, ""), + "/" + gameSettings->getTech() + "/*", ".xml", NULL); + if (lastCheckedCRCTechtreeValue == 0 || + lastCheckedCRCTechtreeValue != gameSettings->getTechCRC()) { + lastCheckedCRCTechtreeValue = + getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTechs, ""), + "/" + gameSettings->getTech() + "/*", ".xml", NULL, true); + } + + reloadFactions(true, gameSettings->getScenario()); + factionCRCList.clear(); + for (unsigned int factionIdx = 0; factionIdx < factionFiles.size(); + ++factionIdx) { + string factionName = factionFiles[factionIdx]; + if (factionName != GameConstants::RANDOMFACTION_SLOTNAME && + factionName != GameConstants::OBSERVER_SLOTNAME) { + // factionCRC = + // getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), + // "/" + gameSettings->getTech() + "/factions/" + factionName + + // "/*", ".xml", NULL, true); + uint32 factionCRC = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTechs, ""), + "/" + gameSettings->getTech() + "/factions/" + factionName + + "/*", + ".xml", NULL); + if (factionCRC == 0) { + factionCRC = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTechs, ""), + "/" + gameSettings->getTech() + "/factions/" + factionName + + "/*", + ".xml", NULL, true); + } + factionCRCList.push_back(make_pair(factionName, factionCRC)); + } + } + // console.addLine("Found factions: " + + // intToStr(factionCRCList.size())); + lastCheckedCRCTechtreeName = gameSettings->getTech(); } + + gameSettings->setFactionCRCList(factionCRCList); + gameSettings->setTechCRC(lastCheckedCRCTechtreeValue); + } + } + + if (gameSettings->getMap() != "") { + if (lastCheckedCRCMapName != gameSettings->getMap()) { + Checksum checksum; + string file = Config::getMapPath(gameSettings->getMap(), "", false); + // console.addLine("Checking map CRC [" + file + "]"); + checksum.addFile(file); + lastCheckedCRCMapValue = checksum.getSum(); + lastCheckedCRCMapName = gameSettings->getMap(); + } + gameSettings->setMapCRC(lastCheckedCRCMapValue); } + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // replace server player by network + for (int i = 0; i < gameSettings->getFactionCount(); ++i) { + // replace by network + if (gameSettings->getFactionControl(i) == ctHuman) { + gameSettings->setFactionControl(i, ctNetwork); + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); } void MenuStateConnectedGame::returnToJoinMenu() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(modHttpServerThread != NULL) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - modHttpServerThread->setSimpleTaskInterfaceValid(false); - modHttpServerThread->signalQuit(); - //modHttpServerThread->setThreadOwnerValid(false); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - if( modHttpServerThread->canShutdown(true) == true && - modHttpServerThread->shutdownAndWait() == true) { - delete modHttpServerThread; - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - modHttpServerThread = NULL; - } - - if(ftpClientThread != NULL) { - - ftpClientThread->setCallBackObject(NULL); - ftpClientThread->signalQuit(); - sleep(0); - if(ftpClientThread->canShutdown(true) == true && - ftpClientThread->shutdownAndWait() == true) { - delete ftpClientThread; - } - else { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] Error cannot shutdown ftpClientThread\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s",szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - } - ftpClientThread = NULL; - } - - if(returnMenuInfo == jmSimple) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - launchingNewGame = true; - disconnectFromServer(); - mainMenu->setState(new MenuStateJoinGame(program, mainMenu)); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - launchingNewGame = true; - disconnectFromServer(); - mainMenu->setState(new MenuStateMasterserver(program, mainMenu)); - } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (modHttpServerThread != NULL) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + modHttpServerThread->setSimpleTaskInterfaceValid(false); + modHttpServerThread->signalQuit(); + // modHttpServerThread->setThreadOwnerValid(false); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, + __LINE__); + if (modHttpServerThread->canShutdown(true) == true && + modHttpServerThread->shutdownAndWait() == true) { + delete modHttpServerThread; + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + modHttpServerThread = NULL; + } + + if (ftpClientThread != NULL) { + + ftpClientThread->setCallBackObject(NULL); + ftpClientThread->signalQuit(); + sleep(0); + if (ftpClientThread->canShutdown(true) == true && + ftpClientThread->shutdownAndWait() == true) { + delete ftpClientThread; + } else { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s %d] Error cannot shutdown ftpClientThread\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("%s", szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + } + ftpClientThread = NULL; + } + + if (returnMenuInfo == jmSimple) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + launchingNewGame = true; + disconnectFromServer(); + mainMenu->setState(new MenuStateJoinGame(program, mainMenu)); + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + launchingNewGame = true; + disconnectFromServer(); + mainMenu->setState(new MenuStateMasterserver(program, mainMenu)); + } } -void MenuStateConnectedGame::eventMouseWheel(int x, int y,int zDelta) { - comboBoxMap.eventMouseWheel(x,y,zDelta); - comboBoxLoadSetup.eventMouseWheel(x,y,zDelta); +void MenuStateConnectedGame::eventMouseWheel(int x, int y, int zDelta) { + comboBoxMap.eventMouseWheel(x, y, zDelta); + comboBoxLoadSetup.eventMouseWheel(x, y, zDelta); } void MenuStateConnectedGame::mouseMove(int x, int y, const MouseState *ms) { - if (mainMessageBox.getEnabled()) { - mainMessageBox.mouseMove(x, y); - } - - if (ftpMessageBox.getEnabled()) { - ftpMessageBox.mouseMove(x, y); - } - - if (comboBoxMap.isDropDownShowing()) { - if (ms->get(mbLeft)) { - comboBoxMap.mouseDown(x, y); - } - comboBoxMap.mouseMove(x, y); - if (lastPreviewedMapFile != getPreselectedMapFile()) { - loadMapInfo(Config::getMapPath(getPreselectedMapFile(), "", false), &mapInfo, true, false); - labelMapInfo.setText(mapInfo.desc); - lastPreviewedMapFile = getPreselectedMapFile(); - } - } - - buttonCancelDownloads.mouseMove(x, y); - buttonDisconnect.mouseMove(x, y); - - for(int i = 0; i < GameConstants::maxPlayers; ++i) { - listBoxControls[i].mouseMove(x, y); - listBoxFactions[i].mouseMove(x, y); - listBoxTeams[i].mouseMove(x, y); - grabSlotButton[i].mouseMove(x, y); - } - - comboBoxMap.mouseMove(x, y); - comboBoxLoadSetup.mouseMove(x, y); - if (comboBoxLoadSetup.isDropDownShowing()) { - if (ms->get(mbLeft)) { - comboBoxLoadSetup.mouseDown(x, y); - } - } - buttonSaveSetup.mouseMove(x, y); - buttonLoadSetup.mouseMove(x, y); - buttonDeleteSetup.mouseMove(x, y); - - listBoxFogOfWar.mouseMove(x, y); - checkBoxAllowObservers.mouseMove(x, y); - listBoxTileset.mouseMove(x, y); - listBoxMapFilter.mouseMove(x, y); - listBoxTechTree.mouseMove(x, y); - listBoxPlayerStatus.mouseMove(x,y); - - labelAllowTeamUnitSharing.mouseMove(x,y); - checkBoxAllowTeamUnitSharing.mouseMove(x,y); - labelAllowTeamResourceSharing.mouseMove(x,y); - checkBoxAllowTeamResourceSharing.mouseMove(x,y); - - checkBoxAllowNativeLanguageTechtree.mouseMove(x, y); - - buttonPlayNow.mouseMove(x, y); + if (mainMessageBox.getEnabled()) { + mainMessageBox.mouseMove(x, y); + } + + if (ftpMessageBox.getEnabled()) { + ftpMessageBox.mouseMove(x, y); + } + + if (comboBoxMap.isDropDownShowing()) { + if (ms->get(mbLeft)) { + comboBoxMap.mouseDown(x, y); + } + comboBoxMap.mouseMove(x, y); + if (lastPreviewedMapFile != getPreselectedMapFile()) { + loadMapInfo(Config::getMapPath(getPreselectedMapFile(), "", false), + &mapInfo, true, false); + labelMapInfo.setText(mapInfo.desc); + lastPreviewedMapFile = getPreselectedMapFile(); + } + } + + buttonCancelDownloads.mouseMove(x, y); + buttonDisconnect.mouseMove(x, y); + + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + listBoxControls[i].mouseMove(x, y); + listBoxFactions[i].mouseMove(x, y); + listBoxTeams[i].mouseMove(x, y); + grabSlotButton[i].mouseMove(x, y); + } + + comboBoxMap.mouseMove(x, y); + comboBoxLoadSetup.mouseMove(x, y); + if (comboBoxLoadSetup.isDropDownShowing()) { + if (ms->get(mbLeft)) { + comboBoxLoadSetup.mouseDown(x, y); + } + } + buttonSaveSetup.mouseMove(x, y); + buttonLoadSetup.mouseMove(x, y); + buttonDeleteSetup.mouseMove(x, y); + + listBoxFogOfWar.mouseMove(x, y); + checkBoxAllowObservers.mouseMove(x, y); + listBoxTileset.mouseMove(x, y); + listBoxMapFilter.mouseMove(x, y); + listBoxTechTree.mouseMove(x, y); + listBoxPlayerStatus.mouseMove(x, y); + + labelAllowTeamUnitSharing.mouseMove(x, y); + checkBoxAllowTeamUnitSharing.mouseMove(x, y); + labelAllowTeamResourceSharing.mouseMove(x, y); + checkBoxAllowTeamResourceSharing.mouseMove(x, y); + + checkBoxAllowNativeLanguageTechtree.mouseMove(x, y); + + buttonPlayNow.mouseMove(x, y); } bool MenuStateConnectedGame::isVideoPlaying() { - bool result = false; - if(factionVideo != NULL) { - result = factionVideo->isPlaying(); - } - return result; + bool result = false; + if (factionVideo != NULL) { + result = factionVideo->isPlaying(); + } + return result; } void MenuStateConnectedGame::render() { - try { - Renderer &renderer= Renderer::getInstance(); - - if(mainMessageBox.getEnabled()) { - renderer.renderMessageBox(&mainMessageBox); - } - - renderer.renderButton(&buttonDisconnect); - - if (initialSettingsReceivedFromServer == false) { - return; - } - - if(factionTexture != NULL) { - if(factionVideo == NULL || factionVideo->isPlaying() == false) { - renderer.renderTextureQuad(800,600,200,150,factionTexture,1); - } - } - if(factionVideo != NULL) { - if(factionVideo->isPlaying() == true) { - factionVideo->playFrame(false); - } - else { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && - ::Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == true) { - if(factionVideo != NULL) { - factionVideo->closePlayer(); - delete factionVideo; - factionVideo = NULL; - - if(validDisplayedGamesettings) { - initFactionPreview(&displayedGamesettings); - } - } - } - } - } - - if(mapPreviewTexture != NULL) { - //renderer.renderTextureQuad(5,185,150,150,mapPreviewTexture,1.0f); - renderer.renderTextureQuad( this->render_mapPreviewTexture_X, - this->render_mapPreviewTexture_Y, - this->render_mapPreviewTexture_W, - this->render_mapPreviewTexture_H, - mapPreviewTexture,1.0f); - if(this->zoomedMap==true) { - return; - } - //printf("=================> Rendering map preview texture\n"); - } - - if(scenarioLogoTexture != NULL) { - renderer.renderTextureQuad(300,350,400,300,scenarioLogoTexture,1.0f); - //renderer.renderBackground(scenarioLogoTexture); - } - - renderer.renderButton(&buttonDisconnect); - - // Get a reference to the player texture cache - std::map &crcPlayerTextureCache = CacheManager::getCachedItem< std::map >(GameConstants::playerTextureCacheLookupKey); - - // START - this code ensure player title and player names don't overlap - int offsetPosition=0; - for(int i=0; i < GameConstants::maxPlayers; ++i) { - const Metrics &metrics= Metrics::getInstance(); - FontMetrics *fontMetrics= NULL; - if(Renderer::renderText3DEnabled == false) { - fontMetrics = CoreData::getInstance().getMenuFontNormal()->getMetrics(); - } - else { - fontMetrics = CoreData::getInstance().getMenuFontNormal3D()->getMetrics(); - } - - if(fontMetrics == NULL) { - throw megaglest_runtime_error("fontMetrics == NULL"); - } - int curWidth = (metrics.toVirtualX(fontMetrics->getTextWidth(labelPlayers[i].getText()))); - - if(labelPlayers[i].getX() + curWidth >= labelPlayerNames[i].getX()) { - int newOffsetPosition = labelPlayers[i].getX() + curWidth + 2; - if(offsetPosition < newOffsetPosition) { - offsetPosition = newOffsetPosition; - } - } - } - // END - - renderer.renderListBox(&listBoxPlayerStatus); - - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface *clientInterface = networkManager.getClientInterface(); - for(int i = 0; i < GameConstants::maxPlayers; ++i) { - if(listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) { - bool renderIt=true; - //printf("Player #%d [%s] control = %d\n",i,labelPlayerNames[i].getText().c_str(),listBoxControls[i].getSelectedItemIndex()); - if(labelNetStatus[i].getText() == GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME){ - renderIt=false; - } - labelPlayers[i].setVisible(renderIt); - labelPlayerNames[i].setVisible(renderIt); - listBoxControls[i].setVisible(renderIt); - listBoxRMultiplier[i].setVisible(renderIt); - listBoxFactions[i].setVisible(renderIt); - listBoxTeams[i].setVisible(renderIt); - labelNetStatus[i].setVisible(renderIt); - } - - if(listBoxControls[i].getSelectedItemIndex() != ctClosed) { - renderer.renderLabel(&labelPlayerStatus[i]); - } - - if(crcPlayerTextureCache[i] != NULL) { - // Render the player # label the player's color - - Vec3f playerColor = crcPlayerTextureCache[i]->getPixmap()->getPixel3f(0, 0); - if(clientInterface != NULL && - clientInterface->getGameSettings() != NULL && - clientInterface->getGameSettings()->getMasterserver_admin() > 0 && - clientInterface->getGameSettings()->getMasterserver_admin_faction_index() == i) { - - if(difftime((long int)time(NULL),timerLabelFlash) < 1) { - renderer.renderLabel(&labelPlayers[i],&playerColor); - } - else { - Vec4f flashColor=Vec4f(playerColor.x, playerColor.y, playerColor.z, 0.45f); - renderer.renderLabel(&labelPlayers[i],&flashColor); - } - - } - else { - renderer.renderLabel(&labelPlayers[i],&playerColor); - } - - // Blend the color with white so make it more readable - //Vec4f newColor(1.f, 1.f, 1.f, 0.57f); - //renderer.renderLabel(&labelPlayers[i],&newColor); - - //int quadWidth = labelPlayerNames[i].getX() - labelPlayers[i].getX() - 5; - //renderer.renderTextureQuad(labelPlayers[i].getX(), labelPlayers[i].getY(), quadWidth, labelPlayers[i].getH(), crcPlayerTextureCache[i],1.0f,&playerColor); - } - else { - renderer.renderLabel(&labelPlayers[i]); - } - - if(offsetPosition > 0) { - labelPlayerNames[i].setX(offsetPosition); - } - - renderer.renderListBox(&listBoxControls[i]); - if(listBoxControls[i].getSelectedItemIndex() != ctClosed) { - renderer.renderListBox(&listBoxRMultiplier[i]); - renderer.renderListBox(&listBoxFactions[i]); - int teamnumber=listBoxTeams[i].getSelectedItemIndex(); - Vec3f teamcolor=Vec3f(1.0f,1.0f,1.0f); - if(teamnumber>=0 && teamnumber<8){ - teamcolor=crcPlayerTextureCache[teamnumber]->getPixmap()->getPixel3f(0, 0); - } - listBoxTeams[i].setTextColor(teamcolor); - renderer.renderListBox(&listBoxTeams[i]); - - bool canGrabSlot = false; - ClientInterface *clientInterface = networkManager.getClientInterface(); - if(clientInterface != NULL && clientInterface->getJoinGameInProgress() == true) { - canGrabSlot = ((listBoxControls[i].getSelectedItemIndex() == ctNetwork && - labelNetStatus[i].getText() == GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME) || - (listBoxControls[i].getSelectedItemIndex() != ctHuman && - listBoxControls[i].getSelectedItemIndex() != ctClosed && - listBoxControls[i].getSelectedItemIndex() != ctNetwork)); - } - else { - canGrabSlot = (listBoxControls[i].getSelectedItemIndex() == ctNetwork && - labelNetStatus[i].getText() == GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME); - } - - if(canGrabSlot == true) { - if(i < mapInfo.players) { - renderer.renderButton(&grabSlotButton[i]); - } - } - else if(listBoxControls[i].getSelectedItemIndex() == ctNetwork || - listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned || - listBoxControls[i].getSelectedItemIndex() == ctHuman){ - renderer.renderLabel(&labelNetStatus[i]); - } - - if(listBoxControls[i].getSelectedItemIndex() == ctNetwork || - listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned || - listBoxControls[i].getSelectedItemIndex() == ctHuman){ - if(labelNetStatus[i].getText() != GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME) { - renderer.renderLabel(&labelPlayerNames[i]); - } - } - } - } - renderer.renderLabel(&labelStatus); - renderer.renderLabel(&labelInfo); - - if(difftime((long int)time(NULL),timerLabelFlash) < 1) { - renderer.renderLabel(&labelDataSynchInfo,&RED); - renderer.renderLabel(&labelWaitingForPlayers,&YELLOW); - } - else { - renderer.renderLabel(&labelDataSynchInfo,&WHITE); - renderer.renderLabel(&labelWaitingForPlayers,&WHITE); - } - - renderer.renderLabel(&labelMap); - renderer.renderLabel(&labelMapFilter); - renderer.renderLabel(&labelFogOfWar); - renderer.renderLabel(&labelAllowObservers); - renderer.renderLabel(&labelFallbackCpuMultiplier); - renderer.renderLabel(&labelTileset); - renderer.renderLabel(&labelTechTree); - renderer.renderLabel(&labelControl); - renderer.renderLabel(&labelFaction); - renderer.renderLabel(&labelTeam); - renderer.renderLabel(&labelMapInfo); - - renderer.renderListBox(&listBoxMapFilter); - renderer.renderListBox(&listBoxFogOfWar); - renderer.renderCheckBox(&checkBoxAllowObservers); - renderer.renderListBox(&listBoxTileset); - renderer.renderListBox(&listBoxTechTree); - - renderer.renderLabel(&labelEnableSwitchTeamMode); - renderer.renderLabel(&labelAISwitchTeamAcceptPercent); - - renderer.renderCheckBox(&checkBoxEnableSwitchTeamMode); - renderer.renderListBox(&listBoxAISwitchTeamAcceptPercent); - renderer.renderListBox(&listBoxFallbackCpuMultiplier); - - renderer.renderLabel(&labelAllowTeamUnitSharing); - renderer.renderCheckBox(&checkBoxAllowTeamUnitSharing); - - renderer.renderLabel(&labelAllowTeamResourceSharing); - renderer.renderCheckBox(&checkBoxAllowTeamResourceSharing); - - renderer.renderButton(&buttonPlayNow); - - renderer.renderLabel(&labelSaveSetupName); - renderer.renderButton(&buttonSaveSetup); - renderer.renderButton(&buttonLoadSetup); - renderer.renderButton(&buttonDeleteSetup); - - renderer.renderCheckBox(&checkBoxScenario); - renderer.renderLabel(&labelScenario); - if(checkBoxScenario.getValue() == true) { - renderer.renderListBox(&listBoxScenario); - } - - renderer.renderLabel(&labelAllowNativeLanguageTechtree); - renderer.renderCheckBox(&checkBoxAllowNativeLanguageTechtree); - - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - // !!! START TEMP MV - //renderer.renderButton(&buttonCancelDownloads); - //fileFTPProgressList.clear(); - //fileFTPProgressList["test1a dsa asd asda sdasd asd ad ad"] = make_pair(1,"testa"); - //fileFTPProgressList["test2 asdasdasdadas dasdasdasda"] = make_pair(1,"testb"); - //fileFTPProgressList["test3 asdasdad asd ada dasdadasdada"] = make_pair(1,"testc"); - // !!! END TEMP MV - - if(fileFTPProgressList.empty() == false) { - Lang &lang= Lang::getInstance(); - renderer.renderButton(&buttonCancelDownloads); - int xLocation = buttonCancelDownloads.getX(); - int yLocation = buttonCancelDownloads.getY() - 20; - for(std::map >::iterator iterMap = fileFTPProgressList.begin(); - iterMap != fileFTPProgressList.end(); ++iterMap) { - string progressLabelPrefix = lang.getString("ModDownloading") + " " + iterMap->first + " "; - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\nRendering file progress with the following prefix [%s]\n",progressLabelPrefix.c_str()); - - if(Renderer::renderText3DEnabled) { - renderer.renderProgressBar3D( - iterMap->second.first, - xLocation, - //10, - yLocation, - CoreData::getInstance().getDisplayFontSmall3D(), - //350,progressLabelPrefix); - 300,progressLabelPrefix); - } - else { - renderer.renderProgressBar( - iterMap->second.first, - //10, - xLocation, - yLocation, - CoreData::getInstance().getDisplayFontSmall(), - //350,progressLabelPrefix); - 300,progressLabelPrefix); - } - - yLocation -= 20; - } - } - safeMutexFTPProgress.ReleaseLock(); - - renderer.renderComboBox(&comboBoxMap); - renderer.renderComboBox(&comboBoxLoadSetup); + try { + Renderer &renderer = Renderer::getInstance(); - if(mainMessageBox.getEnabled()) { - renderer.renderMessageBox(&mainMessageBox); - } - if(ftpMessageBox.getEnabled()) { - renderer.renderMessageBox(&ftpMessageBox); - } - - if(program != NULL) program->renderProgramMsgBox(); - - if(enableMapPreview && (mapPreview.hasFileLoaded() == true)) { - - int mouseX = mainMenu->getMouseX(); - int mouseY = mainMenu->getMouseY(); - int mouse2dAnim = mainMenu->getMouse2dAnim(); + if (mainMessageBox.getEnabled()) { + renderer.renderMessageBox(&mainMessageBox); + } - if(mapPreviewTexture == NULL) { - renderer.renderMouse2d(mouseX, mouseY, mouse2dAnim); + renderer.renderButton(&buttonDisconnect); - bool renderAll = (listBoxFogOfWar.getSelectedItemIndex() == 2); - //renderer.renderMapPreview(&mapPreview, renderAll, 10, 350, &mapPreviewTexture); - renderer.renderMapPreview(&mapPreview, renderAll, - this->render_mapPreviewTexture_X, - this->render_mapPreviewTexture_Y, - &mapPreviewTexture); - } - } - renderer.renderChatManager(&chatManager); - renderer.renderConsole(&console,showFullConsole?consoleFull:consoleStoredAndNormal); + if (initialSettingsReceivedFromServer == false) { + return; + } - if(difftime((long int)time(NULL),timerLabelFlash) > 2) { - timerLabelFlash = time(NULL); + if (factionTexture != NULL) { + if (factionVideo == NULL || factionVideo->isPlaying() == false) { + renderer.renderTextureQuad(800, 600, 200, 150, factionTexture, 1); + } + } + if (factionVideo != NULL) { + if (factionVideo->isPlaying() == true) { + factionVideo->playFrame(false); + } else { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && + ::Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == true) { + if (factionVideo != NULL) { + factionVideo->closePlayer(); + delete factionVideo; + factionVideo = NULL; + + if (validDisplayedGamesettings) { + initFactionPreview(&displayedGamesettings); + } + } } - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - throw megaglest_runtime_error(szBuf); - } -} + } + } -void MenuStateConnectedGame::update() { - Chrono chrono; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); - - Lang &lang= Lang::getInstance(); - ClientInterface *clientInterface= NetworkManager::getInstance().getClientInterface(); - - if(comboBoxMap.isDropDownShowing()){ - labelMapInfo.setX(0); - labelMapInfo.setY(mapPreviewTexture_Y-40); - } - else{ - labelMapInfo.setX(165); - labelMapInfo.setY(mapPreviewTexture_Y+mapPreviewTexture_H-60); - } - - string newLabelConnectionInfo = lang.getString("WaitingHost"); - if(clientInterface != NULL && clientInterface->getJoinGameInProgress() == true) { - newLabelConnectionInfo = lang.getString("MGGameStatus2"); - } - // Test progress bar - //MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - //fileFTPProgressList["test"] = pair(difftime(time(NULL),lastNetworkSendPing) * 20,"test file 123"); - //safeMutexFTPProgress.ReleaseLock(); - // - - if(clientInterface != NULL && clientInterface->isConnected()) { - //printf("#2 admin key [%d] client key [%d]\n",settings->getMasterserver_admin(),clientInterface->getSessionKey()); - broadCastGameSettingsToHeadlessServer(false); - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - bool notCurrentlySwitching=(( difftime((long int) time(NULL), broadcastServerSettingsDelayTimer)) >= HEADLESSSERVER_BROADCAST_SETTINGS_SECONDS ); - bool receiveAllowedNow=difftime((long int) time(NULL), noReceiveTimer) > 2 ; - bool newMessage= lastGameSettingsReceivedCount < clientInterface->getGameSettingsReceivedCount(); - if (validDisplayedGamesettings == false - || ( notCurrentlySwitching - && newMessage - && receiveAllowedNow )) { - - //printf("I take the whole settings top broadcastDelay=%d noReceiveTimer=%d\n", (int)difftime((long int) time(NULL), broadcastServerSettingsDelayTimer),(int)difftime((long int) time(NULL), noReceiveTimer)); - - displayedGamesettings = *(clientInterface->getGameSettings()); - originalGamesettings = displayedGamesettings; - validDisplayedGamesettings = true; - } - - checkBoxAllowNativeLanguageTechtree.setEditable(isHeadlessAdmin()); - checkBoxAllowNativeLanguageTechtree.setEnabled(isHeadlessAdmin()); - buttonSaveSetup.setVisible(isHeadlessAdmin()); - labelSaveSetupName.setVisible(isHeadlessAdmin()); - buttonLoadSetup.setVisible(isHeadlessAdmin()); - buttonDeleteSetup.setVisible(isHeadlessAdmin()); - comboBoxLoadSetup.setVisible(isHeadlessAdmin()); - comboBoxMap.setEditable(isHeadlessAdmin()); - listBoxMapFilter.setEditable(isHeadlessAdmin()); - buttonPlayNow.setVisible(isHeadlessAdmin() || - clientInterface->getJoinGameInProgress() == true); - listBoxTechTree.setEditable(isHeadlessAdmin()); - listBoxTileset.setEditable(isHeadlessAdmin()); - checkBoxEnableSwitchTeamMode.setEditable(isHeadlessAdmin()); - listBoxAISwitchTeamAcceptPercent.setEditable(isHeadlessAdmin()); - listBoxFallbackCpuMultiplier.setEditable(isHeadlessAdmin()); - listBoxFogOfWar.setEditable(isHeadlessAdmin()); - checkBoxAllowObservers.setEditable(isHeadlessAdmin()); - - checkBoxAllowTeamUnitSharing.setEditable(isHeadlessAdmin()); - checkBoxAllowTeamResourceSharing.setEditable(isHeadlessAdmin()); - - if(isHeadlessAdmin() == true) { - bool hasOtherPlayer=false; - bool hasOpenSlot=false; - for(unsigned int i = 0; i < (unsigned int)GameConstants::maxPlayers; ++i) { - if(displayedGamesettings.getFactionControl(i)==ctNetwork && clientInterface->getPlayerIndex()!=(int)i){ - hasOpenSlot=true; - } - if(displayedGamesettings.getFactionControl(i)==ctNetwork && - displayedGamesettings.getNetworkPlayerNameByPlayerIndex(i)!= GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME && - displayedGamesettings.getNetworkPlayerNameByPlayerIndex(i)!= GameConstants::NETWORK_SLOT_CLOSED_SLOTNAME ){ - listBoxControls[i].setEditable(false); - if(clientInterface->getPlayerIndex()!=(int)i){ - hasOtherPlayer=true; - } - } - else if(clientInterface->getPlayerIndex()==(int)i){ - listBoxControls[i].setEditable(false); - } - else { - listBoxControls[i].setEditable(true); - } - listBoxRMultiplier[i].setEditable(isHeadlessAdmin()); - listBoxFactions[i].setEditable(isHeadlessAdmin()); - listBoxTeams[i].setEditable(isHeadlessAdmin()); - } - if (hasOtherPlayer) { - labelWaitingForPlayers.setText(""); - labelWaitingForPlayers.setVisible(false); - } else if (hasOpenSlot) { - labelWaitingForPlayers.setText(lang.getString("WaitingForPlayers")); - labelWaitingForPlayers.setVisible(true); - } else { - labelWaitingForPlayers.setText(lang.getString("OpenANetworkSLot")); - labelWaitingForPlayers.setVisible(true); - } - } - else { - labelWaitingForPlayers.setText(""); - labelWaitingForPlayers.setVisible(false); - } - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - if(difftime((long int)time(NULL),lastNetworkSendPing) >= GameConstants::networkPingInterval) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] about to sendPingMessage...\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - lastNetworkSendPing = time(NULL); - clientInterface->sendPingMessage(GameConstants::networkPingInterval, (int64)time(NULL)); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] pingCount = %d, clientInterface->getLastPingLag() = %f, GameConstants::networkPingInterval = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,pingCount, clientInterface->getLastPingLag(),GameConstants::networkPingInterval); - - // Starting checking timeout after sending at least 3 pings to server - if(clientInterface->isConnected() && - pingCount >= MAX_PING_LAG_COUNT && clientInterface->getLastPingLag() >= (GameConstants::networkPingInterval * MAX_PING_LAG_COUNT)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - clientInterface->updateLobby(); - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - if(clientInterface->isConnected() && clientInterface->getJoinGameInProgress() == false && - pingCount >= MAX_PING_LAG_COUNT && clientInterface->getLastPingLag() >= (GameConstants::networkPingInterval * MAX_PING_LAG_COUNT)) { - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - if(fileFTPProgressList.empty() == true) { - Lang &lang= Lang::getInstance(); - const vector languageList = displayedGamesettings.getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - clientInterface->sendTextMessage(lang.getString("ConnectionTimedOut",languageList[i]) + " : " + doubleToStr(clientInterface->getLastPingLag(),2),-1,false,languageList[i]); - sleep(1); - clientInterface->close(); - } - } - } - } - - pingCount++; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - buttonDisconnect.setText(lang.getString("Disconnect")); - - if(clientInterface->getAllowDownloadDataSynch() == false) { - string label = lang.getString("ConnectedToServer"); - - if(clientInterface->getServerName().empty() == false) { - label = label + " " + clientInterface->getServerName(); - } + if (mapPreviewTexture != NULL) { + // renderer.renderTextureQuad(5,185,150,150,mapPreviewTexture,1.0f); + renderer.renderTextureQuad( + this->render_mapPreviewTexture_X, this->render_mapPreviewTexture_Y, + this->render_mapPreviewTexture_W, this->render_mapPreviewTexture_H, + mapPreviewTexture, 1.0f); + if (this->zoomedMap == true) { + return; + } + // printf("=================> Rendering map preview texture\n"); + } - label = label + ", " + clientInterface->getVersionString(); + if (scenarioLogoTexture != NULL) { + renderer.renderTextureQuad(300, 350, 400, 300, scenarioLogoTexture, 1.0f); + // renderer.renderBackground(scenarioLogoTexture); + } - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); + renderer.renderButton(&buttonDisconnect); + + // Get a reference to the player texture cache + std::map &crcPlayerTextureCache = + CacheManager::getCachedItem>( + GameConstants::playerTextureCacheLookupKey); + + // START - this code ensure player title and player names don't overlap + int offsetPosition = 0; + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + const Metrics &metrics = Metrics::getInstance(); + FontMetrics *fontMetrics = NULL; + if (Renderer::renderText3DEnabled == false) { + fontMetrics = CoreData::getInstance().getMenuFontNormal()->getMetrics(); + } else { + fontMetrics = + CoreData::getInstance().getMenuFontNormal3D()->getMetrics(); + } + + if (fontMetrics == NULL) { + throw megaglest_runtime_error("fontMetrics == NULL"); + } + int curWidth = (metrics.toVirtualX( + fontMetrics->getTextWidth(labelPlayers[i].getText()))); + + if (labelPlayers[i].getX() + curWidth >= labelPlayerNames[i].getX()) { + int newOffsetPosition = labelPlayers[i].getX() + curWidth + 2; + if (offsetPosition < newOffsetPosition) { + offsetPosition = newOffsetPosition; + } + } + } + // END + + renderer.renderListBox(&listBoxPlayerStatus); + + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + if (listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) { + bool renderIt = true; + // printf("Player #%d [%s] control = + // %d\n",i,labelPlayerNames[i].getText().c_str(),listBoxControls[i].getSelectedItemIndex()); + if (labelNetStatus[i].getText() == + GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME) { + renderIt = false; + } + labelPlayers[i].setVisible(renderIt); + labelPlayerNames[i].setVisible(renderIt); + listBoxControls[i].setVisible(renderIt); + listBoxRMultiplier[i].setVisible(renderIt); + listBoxFactions[i].setVisible(renderIt); + listBoxTeams[i].setVisible(renderIt); + labelNetStatus[i].setVisible(renderIt); + } + + if (listBoxControls[i].getSelectedItemIndex() != ctClosed) { + renderer.renderLabel(&labelPlayerStatus[i]); + } + + if (crcPlayerTextureCache[i] != NULL) { + // Render the player # label the player's color + + Vec3f playerColor = + crcPlayerTextureCache[i]->getPixmap()->getPixel3f(0, 0); + if (clientInterface != NULL && + clientInterface->getGameSettings() != NULL && + clientInterface->getGameSettings()->getMasterserver_admin() > 0 && + clientInterface->getGameSettings() + ->getMasterserver_admin_faction_index() == i) { + + if (difftime((long int)time(NULL), timerLabelFlash) < 1) { + renderer.renderLabel(&labelPlayers[i], &playerColor); + } else { + Vec4f flashColor = + Vec4f(playerColor.x, playerColor.y, playerColor.z, 0.45f); + renderer.renderLabel(&labelPlayers[i], &flashColor); + } + + } else { + renderer.renderLabel(&labelPlayers[i], &playerColor); + } - if(clientInterface->getAllowGameDataSynchCheck() == false && - displayedGamesettings.getTileset() != "" && - displayedGamesettings.getTech() != "" && - displayedGamesettings.getMap() != "") { - Config &config = Config::getInstance(); + // Blend the color with white so make it more readable + // Vec4f newColor(1.f, 1.f, 1.f, 0.57f); + // renderer.renderLabel(&labelPlayers[i],&newColor); + + // int quadWidth = labelPlayerNames[i].getX() - labelPlayers[i].getX() - + // 5; renderer.renderTextureQuad(labelPlayers[i].getX(), + // labelPlayers[i].getY(), quadWidth, labelPlayers[i].getH(), + // crcPlayerTextureCache[i],1.0f,&playerColor); + } else { + renderer.renderLabel(&labelPlayers[i]); + } + + if (offsetPosition > 0) { + labelPlayerNames[i].setX(offsetPosition); + } + + renderer.renderListBox(&listBoxControls[i]); + if (listBoxControls[i].getSelectedItemIndex() != ctClosed) { + renderer.renderListBox(&listBoxRMultiplier[i]); + renderer.renderListBox(&listBoxFactions[i]); + int teamnumber = listBoxTeams[i].getSelectedItemIndex(); + Vec3f teamcolor = Vec3f(1.0f, 1.0f, 1.0f); + if (teamnumber >= 0 && teamnumber < 8) { + teamcolor = + crcPlayerTextureCache[teamnumber]->getPixmap()->getPixel3f(0, 0); + } + listBoxTeams[i].setTextColor(teamcolor); + renderer.renderListBox(&listBoxTeams[i]); - MutexSafeWrapper safeMutexFTPProgress(ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL,string(__FILE__) + "_" + intToStr(__LINE__)); + bool canGrabSlot = false; + ClientInterface *clientInterface = networkManager.getClientInterface(); + if (clientInterface != NULL && + clientInterface->getJoinGameInProgress() == true) { + canGrabSlot = + ((listBoxControls[i].getSelectedItemIndex() == ctNetwork && + labelNetStatus[i].getText() == + GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME) || + (listBoxControls[i].getSelectedItemIndex() != ctHuman && + listBoxControls[i].getSelectedItemIndex() != ctClosed && + listBoxControls[i].getSelectedItemIndex() != ctNetwork)); + } else { + canGrabSlot = + (listBoxControls[i].getSelectedItemIndex() == ctNetwork && + labelNetStatus[i].getText() == + GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME); + } - uint32 tilesetCRC = lastCheckedCRCTilesetValue; - if(lastCheckedCRCTilesetName != displayedGamesettings.getTileset() && - displayedGamesettings.getTileset() != "") { - //console.addLine("Checking tileset CRC [" + displayedGamesettings.getTileset() + "]"); - tilesetCRC = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTilesets,""), string("/") + displayedGamesettings.getTileset() + string("/*"), ".xml", NULL); - if(tilesetCRC == 0 || tilesetCRC != displayedGamesettings.getTilesetCRC()) { - tilesetCRC = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTilesets,""), string("/") + displayedGamesettings.getTileset() + string("/*"), ".xml", NULL, true); - } + if (canGrabSlot == true) { + if (i < mapInfo.players) { + renderer.renderButton(&grabSlotButton[i]); + } + } else if (listBoxControls[i].getSelectedItemIndex() == ctNetwork || + listBoxControls[i].getSelectedItemIndex() == + ctNetworkUnassigned || + listBoxControls[i].getSelectedItemIndex() == ctHuman) { + renderer.renderLabel(&labelNetStatus[i]); + } - // Test data synch - //tilesetCRC++; - lastCheckedCRCTilesetValue = tilesetCRC; - lastCheckedCRCTilesetName = displayedGamesettings.getTileset(); - } + if (listBoxControls[i].getSelectedItemIndex() == ctNetwork || + listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned || + listBoxControls[i].getSelectedItemIndex() == ctHuman) { + if (labelNetStatus[i].getText() != + GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME) { + renderer.renderLabel(&labelPlayerNames[i]); + } + } + } + } + renderer.renderLabel(&labelStatus); + renderer.renderLabel(&labelInfo); + + if (difftime((long int)time(NULL), timerLabelFlash) < 1) { + renderer.renderLabel(&labelDataSynchInfo, &RED); + renderer.renderLabel(&labelWaitingForPlayers, &YELLOW); + } else { + renderer.renderLabel(&labelDataSynchInfo, &WHITE); + renderer.renderLabel(&labelWaitingForPlayers, &WHITE); + } - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); + renderer.renderLabel(&labelMap); + renderer.renderLabel(&labelMapFilter); + renderer.renderLabel(&labelFogOfWar); + renderer.renderLabel(&labelAllowObservers); + renderer.renderLabel(&labelFallbackCpuMultiplier); + renderer.renderLabel(&labelTileset); + renderer.renderLabel(&labelTechTree); + renderer.renderLabel(&labelControl); + renderer.renderLabel(&labelFaction); + renderer.renderLabel(&labelTeam); + renderer.renderLabel(&labelMapInfo); + + renderer.renderListBox(&listBoxMapFilter); + renderer.renderListBox(&listBoxFogOfWar); + renderer.renderCheckBox(&checkBoxAllowObservers); + renderer.renderListBox(&listBoxTileset); + renderer.renderListBox(&listBoxTechTree); + + renderer.renderLabel(&labelEnableSwitchTeamMode); + renderer.renderLabel(&labelAISwitchTeamAcceptPercent); + + renderer.renderCheckBox(&checkBoxEnableSwitchTeamMode); + renderer.renderListBox(&listBoxAISwitchTeamAcceptPercent); + renderer.renderListBox(&listBoxFallbackCpuMultiplier); + + renderer.renderLabel(&labelAllowTeamUnitSharing); + renderer.renderCheckBox(&checkBoxAllowTeamUnitSharing); + + renderer.renderLabel(&labelAllowTeamResourceSharing); + renderer.renderCheckBox(&checkBoxAllowTeamResourceSharing); + + renderer.renderButton(&buttonPlayNow); + + renderer.renderLabel(&labelSaveSetupName); + renderer.renderButton(&buttonSaveSetup); + renderer.renderButton(&buttonLoadSetup); + renderer.renderButton(&buttonDeleteSetup); + + renderer.renderCheckBox(&checkBoxScenario); + renderer.renderLabel(&labelScenario); + if (checkBoxScenario.getValue() == true) { + renderer.renderListBox(&listBoxScenario); + } - uint32 techCRC = lastCheckedCRCTechtreeValue; - if(lastCheckedCRCTechtreeName != displayedGamesettings.getTech() && - displayedGamesettings.getTech() != "") { - //console.addLine("Checking techtree CRC [" + displayedGamesettings.getTech() + "]"); - techCRC = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), string("/") + displayedGamesettings.getTech() + string("/*"), ".xml", NULL); - //clientInterface->sendTextMessage("#1 TechCRC = " + intToStr(techCRC) + " remoteCRC = " + intToStr(displayedGamesettings.getTechCRC()),-1, true, ""); + renderer.renderLabel(&labelAllowNativeLanguageTechtree); + renderer.renderCheckBox(&checkBoxAllowNativeLanguageTechtree); + + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + // !!! START TEMP MV + // renderer.renderButton(&buttonCancelDownloads); + // fileFTPProgressList.clear(); + // fileFTPProgressList["test1a dsa asd asda sdasd asd ad ad"] = + // make_pair(1,"testa"); fileFTPProgressList["test2 asdasdasdadas + // dasdasdasda"] = make_pair(1,"testb"); fileFTPProgressList["test3 asdasdad + // asd ada dasdadasdada"] = make_pair(1,"testc"); + // !!! END TEMP MV + + if (fileFTPProgressList.empty() == false) { + Lang &lang = Lang::getInstance(); + renderer.renderButton(&buttonCancelDownloads); + int xLocation = buttonCancelDownloads.getX(); + int yLocation = buttonCancelDownloads.getY() - 20; + for (std::map>::iterator iterMap = + fileFTPProgressList.begin(); + iterMap != fileFTPProgressList.end(); ++iterMap) { + string progressLabelPrefix = + lang.getString("ModDownloading") + " " + iterMap->first + " "; + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\nRendering file + // progress with the following prefix + // [%s]\n",progressLabelPrefix.c_str()); + + if (Renderer::renderText3DEnabled) { + renderer.renderProgressBar3D( + iterMap->second.first, xLocation, + // 10, + yLocation, CoreData::getInstance().getDisplayFontSmall3D(), + // 350,progressLabelPrefix); + 300, progressLabelPrefix); + } else { + renderer.renderProgressBar( + iterMap->second.first, + // 10, + xLocation, yLocation, + CoreData::getInstance().getDisplayFontSmall(), + // 350,progressLabelPrefix); + 300, progressLabelPrefix); + } - if(techCRC == 0 || techCRC != displayedGamesettings.getTechCRC()) { - techCRC = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), string("/") + displayedGamesettings.getTech() + string("/*"), ".xml", NULL, true); - //clientInterface->sendTextMessage("#2 TechCRC = " + intToStr(techCRC) + " remoteCRC = " + intToStr(displayedGamesettings.getTechCRC()),-1, true, ""); - } + yLocation -= 20; + } + } + safeMutexFTPProgress.ReleaseLock(); + renderer.renderComboBox(&comboBoxMap); + renderer.renderComboBox(&comboBoxLoadSetup); - if(techCRC != 0 && techCRC != displayedGamesettings.getTechCRC() && - listBoxTechTree.getSelectedItemIndex() >= 0 && - listBoxTechTree.getSelectedItem() != Lang::getInstance().getString("DataMissing","",true)) { + if (mainMessageBox.getEnabled()) { + renderer.renderMessageBox(&mainMessageBox); + } + if (ftpMessageBox.getEnabled()) { + renderer.renderMessageBox(&ftpMessageBox); + } - //time_t now = time(NULL); - time_t lastUpdateDate = getFolderTreeContentsCheckSumRecursivelyLastGenerated(config.getPathListForType(ptTechs,""), string("/") + displayedGamesettings.getTech() + string("/*"), ".xml"); + if (program != NULL) + program->renderProgramMsgBox(); - const time_t REFRESH_CRC_DAY_SECONDS = 60 * 60 * 1; - if( lastUpdateDate <= 0 || - difftime((long int)time(NULL),lastUpdateDate) >= REFRESH_CRC_DAY_SECONDS) { - techCRC = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), string("/") + displayedGamesettings.getTech() + string("/*"), ".xml", NULL, true); - //clientInterface->sendTextMessage("#3 TechCRC = " + intToStr(techCRC) + " remoteCRC = " + intToStr(displayedGamesettings.getTechCRC()),-1, true, ""); - } - } + if (enableMapPreview && (mapPreview.hasFileLoaded() == true)) { - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - // Test data synch - //techCRC++; - lastCheckedCRCTechtreeValue = techCRC; - lastCheckedCRCTechtreeName = displayedGamesettings.getTech(); - - loadFactions(&displayedGamesettings,false); - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - factionCRCList.clear(); - for(unsigned int factionIdx = 0; factionIdx < factionFiles.size(); ++factionIdx) { - string factionName = factionFiles[factionIdx]; - if(factionName != GameConstants::RANDOMFACTION_SLOTNAME && - factionName != GameConstants::OBSERVER_SLOTNAME && - factionName != Lang::getInstance().getString("DataMissing","",true)) { - - uint32 factionCRC = 0; - //time_t now = time(NULL); - time_t lastUpdateDate = getFolderTreeContentsCheckSumRecursivelyLastGenerated(config.getPathListForType(ptTechs,""), "/" + displayedGamesettings.getTech() + "/factions/" + factionName + "/*", ".xml"); - - const time_t REFRESH_CRC_DAY_SECONDS = 60 * 60 * 24; - if( lastUpdateDate <= 0 || - difftime((long int)time(NULL),lastUpdateDate) >= REFRESH_CRC_DAY_SECONDS || - (techCRC != 0 && techCRC != displayedGamesettings.getTechCRC())) { - factionCRC = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), "/" + displayedGamesettings.getTech() + "/factions/" + factionName + "/*", ".xml", NULL, true); - } - else { - factionCRC = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), "/" + displayedGamesettings.getTech() + "/factions/" + factionName + "/*", ".xml", NULL); - } - if(factionCRC == 0) { - factionCRC = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), "/" + displayedGamesettings.getTech() + "/factions/" + factionName + "/*", ".xml", NULL, true); - } - - if(factionCRC != 0) { - vector > serverFactionCRCList = displayedGamesettings.getFactionCRCList(); - for(unsigned int factionIdx1 = 0; factionIdx1 < serverFactionCRCList.size(); ++factionIdx1) { - pair &serverFaction = serverFactionCRCList[factionIdx1]; - if(serverFaction.first == factionName) { - if(serverFaction.second != factionCRC) { - factionCRC = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), "/" + displayedGamesettings.getTech() + "/factions/" + factionName + "/*", ".xml", NULL, true); - } - break; - } - } - } - factionCRCList.push_back(make_pair(factionName,factionCRC)); - } - } - //console.addLine("Found factions: " + intToStr(factionCRCList.size())); - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); + int mouseX = mainMenu->getMouseX(); + int mouseY = mainMenu->getMouseY(); + int mouse2dAnim = mainMenu->getMouse2dAnim(); - } + if (mapPreviewTexture == NULL) { + renderer.renderMouse2d(mouseX, mouseY, mouse2dAnim); - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - uint32 mapCRC = lastCheckedCRCMapValue; - if(lastCheckedCRCMapName != displayedGamesettings.getMap() && - displayedGamesettings.getMap() != "") { - Checksum checksum; - string file = Config::getMapPath(displayedGamesettings.getMap(),"",false); - //console.addLine("Checking map CRC [" + file + "]"); - checksum.addFile(file); - mapCRC = checksum.getSum(); - // Test data synch - //mapCRC++; - - lastCheckedCRCMapValue = mapCRC; - lastCheckedCRCMapName = displayedGamesettings.getMap(); - } - safeMutexFTPProgress.ReleaseLock(); + bool renderAll = (listBoxFogOfWar.getSelectedItemIndex() == 2); + // renderer.renderMapPreview(&mapPreview, renderAll, 10, 350, + // &mapPreviewTexture); + renderer.renderMapPreview( + &mapPreview, renderAll, this->render_mapPreviewTexture_X, + this->render_mapPreviewTexture_Y, &mapPreviewTexture); + } + } + renderer.renderChatManager(&chatManager); + renderer.renderConsole(&console, showFullConsole ? consoleFull + : consoleStoredAndNormal); - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); + if (difftime((long int)time(NULL), timerLabelFlash) > 2) { + timerLabelFlash = time(NULL); + } + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + throw megaglest_runtime_error(szBuf); + } +} - bool dataSynchMismatch = ((mapCRC != 0 && mapCRC != displayedGamesettings.getMapCRC()) || - (tilesetCRC != 0 && tilesetCRC != displayedGamesettings.getTilesetCRC()) || - (techCRC != 0 && techCRC != displayedGamesettings.getTechCRC())); +void MenuStateConnectedGame::update() { + Chrono chrono; + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) + chrono.start(); + + Lang &lang = Lang::getInstance(); + ClientInterface *clientInterface = + NetworkManager::getInstance().getClientInterface(); + + if (comboBoxMap.isDropDownShowing()) { + labelMapInfo.setX(0); + labelMapInfo.setY(mapPreviewTexture_Y - 40); + } else { + labelMapInfo.setX(165); + labelMapInfo.setY(mapPreviewTexture_Y + mapPreviewTexture_H - 60); + } + + string newLabelConnectionInfo = lang.getString("WaitingHost"); + if (clientInterface != NULL && + clientInterface->getJoinGameInProgress() == true) { + newLabelConnectionInfo = lang.getString("MGGameStatus2"); + } + // Test progress bar + // MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? + // ftpClientThread->getProgressMutex() : NULL),string(__FILE__) + "_" + + // intToStr(__LINE__)); fileFTPProgressList["test"] = + // pair(difftime(time(NULL),lastNetworkSendPing) * 20,"test file + // 123"); safeMutexFTPProgress.ReleaseLock(); + // + + if (clientInterface != NULL && clientInterface->isConnected()) { + // printf("#2 admin key [%d] client key + // [%d]\n",settings->getMasterserver_admin(),clientInterface->getSessionKey()); + broadCastGameSettingsToHeadlessServer(false); + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + bool notCurrentlySwitching = + ((difftime((long int)time(NULL), broadcastServerSettingsDelayTimer)) >= + HEADLESSSERVER_BROADCAST_SETTINGS_SECONDS); + bool receiveAllowedNow = difftime((long int)time(NULL), noReceiveTimer) > 2; + bool newMessage = lastGameSettingsReceivedCount < + clientInterface->getGameSettingsReceivedCount(); + if (validDisplayedGamesettings == false || + (notCurrentlySwitching && newMessage && receiveAllowedNow)) { + + // printf("I take the whole settings top broadcastDelay=%d + // noReceiveTimer=%d\n", (int)difftime((long int) time(NULL), + // broadcastServerSettingsDelayTimer),(int)difftime((long int) time(NULL), + // noReceiveTimer)); + + displayedGamesettings = *(clientInterface->getGameSettings()); + originalGamesettings = displayedGamesettings; + validDisplayedGamesettings = true; + } - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\nmapCRC [%d] displayedGamesettings.getMapCRC() [%d]\ntilesetCRC [%d] displayedGamesettings.getTilesetCRC() [%d]\ntechCRC [%d] displayedGamesettings.getTechCRC() [%d]\n",mapCRC,displayedGamesettings.getMapCRC(),tilesetCRC,displayedGamesettings.getTilesetCRC(),techCRC,displayedGamesettings.getTechCRC()); + checkBoxAllowNativeLanguageTechtree.setEditable(isHeadlessAdmin()); + checkBoxAllowNativeLanguageTechtree.setEnabled(isHeadlessAdmin()); + buttonSaveSetup.setVisible(isHeadlessAdmin()); + labelSaveSetupName.setVisible(isHeadlessAdmin()); + buttonLoadSetup.setVisible(isHeadlessAdmin()); + buttonDeleteSetup.setVisible(isHeadlessAdmin()); + comboBoxLoadSetup.setVisible(isHeadlessAdmin()); + comboBoxMap.setEditable(isHeadlessAdmin()); + listBoxMapFilter.setEditable(isHeadlessAdmin()); + buttonPlayNow.setVisible(isHeadlessAdmin() || + clientInterface->getJoinGameInProgress() == true); + listBoxTechTree.setEditable(isHeadlessAdmin()); + listBoxTileset.setEditable(isHeadlessAdmin()); + checkBoxEnableSwitchTeamMode.setEditable(isHeadlessAdmin()); + listBoxAISwitchTeamAcceptPercent.setEditable(isHeadlessAdmin()); + listBoxFallbackCpuMultiplier.setEditable(isHeadlessAdmin()); + listBoxFogOfWar.setEditable(isHeadlessAdmin()); + checkBoxAllowObservers.setEditable(isHeadlessAdmin()); + + checkBoxAllowTeamUnitSharing.setEditable(isHeadlessAdmin()); + checkBoxAllowTeamResourceSharing.setEditable(isHeadlessAdmin()); + + if (isHeadlessAdmin() == true) { + bool hasOtherPlayer = false; + bool hasOpenSlot = false; + for (unsigned int i = 0; i < (unsigned int)GameConstants::maxPlayers; + ++i) { + if (displayedGamesettings.getFactionControl(i) == ctNetwork && + clientInterface->getPlayerIndex() != (int)i) { + hasOpenSlot = true; + } + if (displayedGamesettings.getFactionControl(i) == ctNetwork && + displayedGamesettings.getNetworkPlayerNameByPlayerIndex(i) != + GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME && + displayedGamesettings.getNetworkPlayerNameByPlayerIndex(i) != + GameConstants::NETWORK_SLOT_CLOSED_SLOTNAME) { + listBoxControls[i].setEditable(false); + if (clientInterface->getPlayerIndex() != (int)i) { + hasOtherPlayer = true; + } + } else if (clientInterface->getPlayerIndex() == (int)i) { + listBoxControls[i].setEditable(false); + } else { + listBoxControls[i].setEditable(true); + } + listBoxRMultiplier[i].setEditable(isHeadlessAdmin()); + listBoxFactions[i].setEditable(isHeadlessAdmin()); + listBoxTeams[i].setEditable(isHeadlessAdmin()); + } + if (hasOtherPlayer) { + labelWaitingForPlayers.setText(""); + labelWaitingForPlayers.setVisible(false); + } else if (hasOpenSlot) { + labelWaitingForPlayers.setText(lang.getString("WaitingForPlayers")); + labelWaitingForPlayers.setVisible(true); + } else { + labelWaitingForPlayers.setText(lang.getString("OpenANetworkSLot")); + labelWaitingForPlayers.setVisible(true); + } + } else { + labelWaitingForPlayers.setText(""); + labelWaitingForPlayers.setVisible(false); + } - if(dataSynchMismatch == true && - ( difftime((long int)time(NULL),broadcastServerSettingsDelayTimer) >= HEADLESSSERVER_BROADCAST_SETTINGS_SECONDS)) { - //printf("Data not synched: lmap %u rmap: %u ltile: %d rtile: %u ltech: %u rtech: %u\n",mapCRC,displayedGamesettings.getMapCRC(),tilesetCRC,displayedGamesettings.getTilesetCRC(),techCRC,displayedGamesettings.getTechCRC()); + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (difftime((long int)time(NULL), lastNetworkSendPing) >= + GameConstants::networkPingInterval) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] about to sendPingMessage...\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + lastNetworkSendPing = time(NULL); + clientInterface->sendPingMessage(GameConstants::networkPingInterval, + (int64)time(NULL)); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] pingCount = %d, " + "clientInterface->getLastPingLag() = %f, " + "GameConstants::networkPingInterval = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, pingCount, + clientInterface->getLastPingLag(), + GameConstants::networkPingInterval); + + // Starting checking timeout after sending at least 3 pings to server + if (clientInterface->isConnected() && pingCount >= MAX_PING_LAG_COUNT && + clientInterface->getLastPingLag() >= + (GameConstants::networkPingInterval * MAX_PING_LAG_COUNT)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + clientInterface->updateLobby(); + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (clientInterface->isConnected() && + clientInterface->getJoinGameInProgress() == false && + pingCount >= MAX_PING_LAG_COUNT && + clientInterface->getLastPingLag() >= + (GameConstants::networkPingInterval * MAX_PING_LAG_COUNT)) { + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + if (fileFTPProgressList.empty() == true) { + Lang &lang = Lang::getInstance(); + const vector languageList = + displayedGamesettings.getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + clientInterface->sendTextMessage( + lang.getString("ConnectionTimedOut", languageList[i]) + + " : " + doubleToStr(clientInterface->getLastPingLag(), 2), + -1, false, languageList[i]); + sleep(1); + clientInterface->close(); + } + } + } + } + + pingCount++; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + } - string labelSynch = lang.getString("DataNotSynchedTitle"); + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + buttonDisconnect.setText(lang.getString("Disconnect")); + + if (clientInterface->getAllowDownloadDataSynch() == false) { + string label = lang.getString("ConnectedToServer"); + + if (clientInterface->getServerName().empty() == false) { + label = label + " " + clientInterface->getServerName(); + } + + label = label + ", " + clientInterface->getVersionString(); + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (clientInterface->getAllowGameDataSynchCheck() == false && + displayedGamesettings.getTileset() != "" && + displayedGamesettings.getTech() != "" && + displayedGamesettings.getMap() != "") { + Config &config = Config::getInstance(); + + MutexSafeWrapper safeMutexFTPProgress( + ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL, + string(__FILE__) + "_" + intToStr(__LINE__)); + + uint32 tilesetCRC = lastCheckedCRCTilesetValue; + if (lastCheckedCRCTilesetName != displayedGamesettings.getTileset() && + displayedGamesettings.getTileset() != "") { + // console.addLine("Checking tileset CRC [" + + // displayedGamesettings.getTileset() + "]"); + tilesetCRC = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTilesets, ""), + string("/") + displayedGamesettings.getTileset() + string("/*"), + ".xml", NULL); + if (tilesetCRC == 0 || + tilesetCRC != displayedGamesettings.getTilesetCRC()) { + tilesetCRC = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTilesets, ""), + string("/") + displayedGamesettings.getTileset() + string("/*"), + ".xml", NULL, true); + } + + // Test data synch + // tilesetCRC++; + lastCheckedCRCTilesetValue = tilesetCRC; + lastCheckedCRCTilesetName = displayedGamesettings.getTileset(); + } - if(mapCRC != 0 && mapCRC != displayedGamesettings.getMapCRC() && - comboBoxMap.getSelectedItemIndex() >= 0 && - comboBoxMap.getSelectedItem() != Lang::getInstance().getString("DataMissing","",true)) { - labelSynch = labelSynch + " " + lang.getString("Map"); + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + uint32 techCRC = lastCheckedCRCTechtreeValue; + if (lastCheckedCRCTechtreeName != displayedGamesettings.getTech() && + displayedGamesettings.getTech() != "") { + // console.addLine("Checking techtree CRC [" + + // displayedGamesettings.getTech() + "]"); + techCRC = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTechs, ""), + string("/") + displayedGamesettings.getTech() + string("/*"), + ".xml", NULL); + // clientInterface->sendTextMessage("#1 TechCRC = " + + // intToStr(techCRC) + " remoteCRC = " + + // intToStr(displayedGamesettings.getTechCRC()),-1, true, ""); + + if (techCRC == 0 || techCRC != displayedGamesettings.getTechCRC()) { + techCRC = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTechs, ""), + string("/") + displayedGamesettings.getTech() + string("/*"), + ".xml", NULL, true); + // clientInterface->sendTextMessage("#2 TechCRC = " + + // intToStr(techCRC) + " remoteCRC = " + + // intToStr(displayedGamesettings.getTechCRC()),-1, true, ""); + } + + if (techCRC != 0 && techCRC != displayedGamesettings.getTechCRC() && + listBoxTechTree.getSelectedItemIndex() >= 0 && + listBoxTechTree.getSelectedItem() != + Lang::getInstance().getString("DataMissing", "", true)) { + + // time_t now = time(NULL); + time_t lastUpdateDate = + getFolderTreeContentsCheckSumRecursivelyLastGenerated( + config.getPathListForType(ptTechs, ""), + string("/") + displayedGamesettings.getTech() + + string("/*"), + ".xml"); + + const time_t REFRESH_CRC_DAY_SECONDS = 60 * 60 * 1; + if (lastUpdateDate <= 0 || + difftime((long int)time(NULL), lastUpdateDate) >= + REFRESH_CRC_DAY_SECONDS) { + techCRC = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTechs, ""), + string("/") + displayedGamesettings.getTech() + string("/*"), + ".xml", NULL, true); + // clientInterface->sendTextMessage("#3 TechCRC = " + + // intToStr(techCRC) + " remoteCRC = " + + // intToStr(displayedGamesettings.getTechCRC()),-1, true, ""); + } + } + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // Test data synch + // techCRC++; + lastCheckedCRCTechtreeValue = techCRC; + lastCheckedCRCTechtreeName = displayedGamesettings.getTech(); + + loadFactions(&displayedGamesettings, false); + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + factionCRCList.clear(); + for (unsigned int factionIdx = 0; factionIdx < factionFiles.size(); + ++factionIdx) { + string factionName = factionFiles[factionIdx]; + if (factionName != GameConstants::RANDOMFACTION_SLOTNAME && + factionName != GameConstants::OBSERVER_SLOTNAME && + factionName != + Lang::getInstance().getString("DataMissing", "", true)) { + + uint32 factionCRC = 0; + // time_t now = time(NULL); + time_t lastUpdateDate = + getFolderTreeContentsCheckSumRecursivelyLastGenerated( + config.getPathListForType(ptTechs, ""), + "/" + displayedGamesettings.getTech() + "/factions/" + + factionName + "/*", + ".xml"); + + const time_t REFRESH_CRC_DAY_SECONDS = 60 * 60 * 24; + if (lastUpdateDate <= 0 || + difftime((long int)time(NULL), lastUpdateDate) >= + REFRESH_CRC_DAY_SECONDS || + (techCRC != 0 && + techCRC != displayedGamesettings.getTechCRC())) { + factionCRC = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTechs, ""), + "/" + displayedGamesettings.getTech() + "/factions/" + + factionName + "/*", + ".xml", NULL, true); + } else { + factionCRC = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTechs, ""), + "/" + displayedGamesettings.getTech() + "/factions/" + + factionName + "/*", + ".xml", NULL); + } + if (factionCRC == 0) { + factionCRC = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTechs, ""), + "/" + displayedGamesettings.getTech() + "/factions/" + + factionName + "/*", + ".xml", NULL, true); + } + + if (factionCRC != 0) { + vector> serverFactionCRCList = + displayedGamesettings.getFactionCRCList(); + for (unsigned int factionIdx1 = 0; + factionIdx1 < serverFactionCRCList.size(); ++factionIdx1) { + pair &serverFaction = + serverFactionCRCList[factionIdx1]; + if (serverFaction.first == factionName) { + if (serverFaction.second != factionCRC) { + factionCRC = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTechs, ""), + "/" + displayedGamesettings.getTech() + "/factions/" + + factionName + "/*", + ".xml", NULL, true); + } + break; + } + } + } + factionCRCList.push_back(make_pair(factionName, factionCRC)); + } + } + // console.addLine("Found factions: " + + // intToStr(factionCRCList.size())); + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + } - if(updateDataSynchDetailText == true && - lastMapDataSynchError != lang.getString("DataNotSynchedMap") + " " + comboBoxMap.getSelectedItem()) { - lastMapDataSynchError = lang.getString("DataNotSynchedMap") + " " + comboBoxMap.getSelectedItem(); + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + uint32 mapCRC = lastCheckedCRCMapValue; + if (lastCheckedCRCMapName != displayedGamesettings.getMap() && + displayedGamesettings.getMap() != "") { + Checksum checksum; + string file = + Config::getMapPath(displayedGamesettings.getMap(), "", false); + // console.addLine("Checking map CRC [" + file + "]"); + checksum.addFile(file); + mapCRC = checksum.getSum(); + // Test data synch + // mapCRC++; + + lastCheckedCRCMapValue = mapCRC; + lastCheckedCRCMapName = displayedGamesettings.getMap(); + } + safeMutexFTPProgress.ReleaseLock(); - Lang &lang= Lang::getInstance(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - string msg = lang.getString("DataNotSynchedMap",languageList[i]) + " " + comboBoxMap.getSelectedItem(); - bool localEcho = lang.isLanguageLocal(languageList[i]); - clientInterface->sendTextMessage(msg,-1,localEcho,languageList[i]); - } + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + bool dataSynchMismatch = + ((mapCRC != 0 && mapCRC != displayedGamesettings.getMapCRC()) || + (tilesetCRC != 0 && + tilesetCRC != displayedGamesettings.getTilesetCRC()) || + (techCRC != 0 && techCRC != displayedGamesettings.getTechCRC())); + + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\nmapCRC [%d] + // displayedGamesettings.getMapCRC() [%d]\ntilesetCRC [%d] + // displayedGamesettings.getTilesetCRC() [%d]\ntechCRC [%d] + // displayedGamesettings.getTechCRC() + // [%d]\n",mapCRC,displayedGamesettings.getMapCRC(),tilesetCRC,displayedGamesettings.getTilesetCRC(),techCRC,displayedGamesettings.getTechCRC()); + + if (dataSynchMismatch == true && + (difftime((long int)time(NULL), + broadcastServerSettingsDelayTimer) >= + HEADLESSSERVER_BROADCAST_SETTINGS_SECONDS)) { + // printf("Data not synched: lmap %u rmap: %u ltile: %d rtile: %u + // ltech: %u rtech: + // %u\n",mapCRC,displayedGamesettings.getMapCRC(),tilesetCRC,displayedGamesettings.getTilesetCRC(),techCRC,displayedGamesettings.getTechCRC()); + + string labelSynch = lang.getString("DataNotSynchedTitle"); + + if (mapCRC != 0 && mapCRC != displayedGamesettings.getMapCRC() && + comboBoxMap.getSelectedItemIndex() >= 0 && + comboBoxMap.getSelectedItem() != + Lang::getInstance().getString("DataMissing", "", true)) { + labelSynch = labelSynch + " " + lang.getString("Map"); + + if (updateDataSynchDetailText == true && + lastMapDataSynchError != lang.getString("DataNotSynchedMap") + + " " + + comboBoxMap.getSelectedItem()) { + lastMapDataSynchError = lang.getString("DataNotSynchedMap") + + " " + comboBoxMap.getSelectedItem(); + + Lang &lang = Lang::getInstance(); + const vector languageList = + clientInterface->getGameSettings() + ->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + string msg = + lang.getString("DataNotSynchedMap", languageList[i]) + " " + + comboBoxMap.getSelectedItem(); + bool localEcho = lang.isLanguageLocal(languageList[i]); + clientInterface->sendTextMessage(msg, -1, localEcho, + languageList[i]); + } + } + } + + if (tilesetCRC != 0 && + tilesetCRC != displayedGamesettings.getTilesetCRC() && + listBoxTileset.getSelectedItemIndex() >= 0 && + listBoxTileset.getSelectedItem() != + Lang::getInstance().getString("DataMissing", "", true)) { + labelSynch = labelSynch + " " + lang.getString("Tileset"); + if (updateDataSynchDetailText == true && + lastTileDataSynchError != + lang.getString("DataNotSynchedTileset") + " " + + listBoxTileset.getSelectedItem()) { + lastTileDataSynchError = lang.getString("DataNotSynchedTileset") + + " " + listBoxTileset.getSelectedItem(); + + Lang &lang = Lang::getInstance(); + const vector languageList = + clientInterface->getGameSettings() + ->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + string msg = + lang.getString("DataNotSynchedTileset", languageList[i]) + + " " + listBoxTileset.getSelectedItem(); + bool localEcho = lang.isLanguageLocal(languageList[i]); + clientInterface->sendTextMessage(msg, -1, localEcho, + languageList[i]); + } + } + } + + if (techCRC != 0 && techCRC != displayedGamesettings.getTechCRC() && + listBoxTechTree.getSelectedItemIndex() >= 0 && + listBoxTechTree.getSelectedItem() != + Lang::getInstance().getString("DataMissing", "", true)) { + labelSynch = labelSynch + " " + lang.getString("TechTree"); + if (updateDataSynchDetailText == true && + lastTechtreeDataSynchError != + lang.getString("DataNotSynchedTechtree") + " " + + listBoxTechTree.getSelectedItem()) { + lastTechtreeDataSynchError = + lang.getString("DataNotSynchedTechtree") + " " + + listBoxTechTree.getSelectedItem(); + + Lang &lang = Lang::getInstance(); + const vector languageList = + clientInterface->getGameSettings() + ->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + string msg = + lang.getString("DataNotSynchedTechtree", languageList[i]) + + " " + listBoxTechTree.getSelectedItem(); + bool localEcho = lang.isLanguageLocal(languageList[i]); + clientInterface->sendTextMessage(msg, -1, localEcho, + languageList[i]); + } + + 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()); + if (SystemFlags::getSystemSettingType( + SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + const int MAX_CHAT_TEXT_LINE_LENGTH = 110; + // const vector languageList = + // clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + bool localEcho = lang.isLanguageLocal(languageList[i]); + + string mismatchedFactionText = ""; + vector mismatchedFactionTextList; + vector> serverFactionCRCList = + displayedGamesettings.getFactionCRCList(); + + for (unsigned int factionIdx = 0; + factionIdx < serverFactionCRCList.size(); ++factionIdx) { + pair &serverFaction = + serverFactionCRCList[factionIdx]; + + bool foundFaction = false; + for (unsigned int clientFactionIdx = 0; + clientFactionIdx < factionCRCList.size(); + ++clientFactionIdx) { + pair &clientFaction = + factionCRCList[clientFactionIdx]; + + if (serverFaction.first == clientFaction.first) { + foundFaction = true; + if (serverFaction.second != clientFaction.second) { + if (mismatchedFactionText.length() >= 10) { + mismatchedFactionTextList.push_back( + mismatchedFactionText); + mismatchedFactionText = ""; } - } - - if(tilesetCRC != 0 && tilesetCRC != displayedGamesettings.getTilesetCRC() && - listBoxTileset.getSelectedItemIndex() >= 0 && - listBoxTileset.getSelectedItem() != Lang::getInstance().getString("DataMissing","",true)) { - labelSynch = labelSynch + " " + lang.getString("Tileset"); - if(updateDataSynchDetailText == true && - lastTileDataSynchError != lang.getString("DataNotSynchedTileset") + " " + listBoxTileset.getSelectedItem()) { - lastTileDataSynchError = lang.getString("DataNotSynchedTileset") + " " + listBoxTileset.getSelectedItem(); - - Lang &lang= Lang::getInstance(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - string msg = lang.getString("DataNotSynchedTileset",languageList[i]) + " " + listBoxTileset.getSelectedItem(); - bool localEcho = lang.isLanguageLocal(languageList[i]); - clientInterface->sendTextMessage(msg,-1,localEcho,languageList[i]); - } + if (mismatchedFactionText == "") { + mismatchedFactionText = + "The following factions are mismatched: "; + if (lang.hasString("MismatchedFactions", + languageList[i]) == true) { + mismatchedFactionText = lang.getString( + "MismatchedFactions", languageList[i]); + } + + mismatchedFactionText += + " [" + intToStr(factionCRCList.size()) + "][" + + intToStr(serverFactionCRCList.size()) + "] - "; + } else { + mismatchedFactionText += ", "; } + mismatchedFactionText += serverFaction.first; + } + break; + } + } + + if (foundFaction == false) { + if ((int)mismatchedFactionText.length() > + MAX_CHAT_TEXT_LINE_LENGTH) { + mismatchedFactionTextList.push_back( + mismatchedFactionText); + mismatchedFactionText = ""; } - if(techCRC != 0 && techCRC != displayedGamesettings.getTechCRC() && - listBoxTechTree.getSelectedItemIndex() >= 0 && - listBoxTechTree.getSelectedItem() != Lang::getInstance().getString("DataMissing","",true)) { - labelSynch = labelSynch + " " + lang.getString("TechTree"); - if(updateDataSynchDetailText == true && - lastTechtreeDataSynchError != lang.getString("DataNotSynchedTechtree") + " " + listBoxTechTree.getSelectedItem()) { - lastTechtreeDataSynchError = lang.getString("DataNotSynchedTechtree") + " " + listBoxTechTree.getSelectedItem(); - - Lang &lang= Lang::getInstance(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - string msg = lang.getString("DataNotSynchedTechtree",languageList[i]) + " " + listBoxTechTree.getSelectedItem(); - bool localEcho = lang.isLanguageLocal(languageList[i]); - clientInterface->sendTextMessage(msg,-1,localEcho,languageList[i]); - } - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - const int MAX_CHAT_TEXT_LINE_LENGTH = 110; - //const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - bool localEcho = lang.isLanguageLocal(languageList[i]); - - string mismatchedFactionText = ""; - vector mismatchedFactionTextList; - vector > serverFactionCRCList = displayedGamesettings.getFactionCRCList(); - - for(unsigned int factionIdx = 0; factionIdx < serverFactionCRCList.size(); ++factionIdx) { - pair &serverFaction = serverFactionCRCList[factionIdx]; - - bool foundFaction = false; - for(unsigned int clientFactionIdx = 0; clientFactionIdx < factionCRCList.size(); ++clientFactionIdx) { - pair &clientFaction = factionCRCList[clientFactionIdx]; - - if(serverFaction.first == clientFaction.first) { - foundFaction = true; - if(serverFaction.second != clientFaction.second) { - if(mismatchedFactionText.length() >= 10) { - mismatchedFactionTextList.push_back(mismatchedFactionText); - mismatchedFactionText = ""; - } - if(mismatchedFactionText == "") { - mismatchedFactionText = "The following factions are mismatched: "; - if(lang.hasString("MismatchedFactions",languageList[i]) == true) { - mismatchedFactionText = lang.getString("MismatchedFactions",languageList[i]); - } - - mismatchedFactionText += " ["+ intToStr(factionCRCList.size()) + "][" + intToStr(serverFactionCRCList.size()) + "] - "; - } - else { - mismatchedFactionText += ", "; - } - mismatchedFactionText += serverFaction.first; - } - break; - } - } - - if(foundFaction == false) { - if((int)mismatchedFactionText.length() > MAX_CHAT_TEXT_LINE_LENGTH) { - mismatchedFactionTextList.push_back(mismatchedFactionText); - mismatchedFactionText = ""; - } - - if(mismatchedFactionText == "") { - mismatchedFactionText = "The following factions are mismatched: "; - if(lang.hasString("MismatchedFactions",languageList[i]) == true) { - mismatchedFactionText = lang.getString("MismatchedFactions",languageList[i]); - } - - mismatchedFactionText += " ["+ intToStr(factionCRCList.size()) + "][" + intToStr(serverFactionCRCList.size()) + "] - "; - } - else { - mismatchedFactionText += ", "; - } - - if(lang.hasString("MismatchedFactionsMissing",languageList[i]) == true) { - mismatchedFactionText += serverFaction.first + " " + lang.getString("MismatchedFactionsMissing",languageList[i]); - } - else { - mismatchedFactionText += serverFaction.first + " (missing)"; - } - } - } - - for(unsigned int clientFactionIdx = 0; clientFactionIdx < factionCRCList.size(); ++clientFactionIdx) { - pair &clientFaction = factionCRCList[clientFactionIdx]; - - bool foundFaction = false; - for(unsigned int factionIdx = 0; factionIdx < serverFactionCRCList.size(); ++factionIdx) { - pair &serverFaction = serverFactionCRCList[factionIdx]; - - if(serverFaction.first == clientFaction.first) { - foundFaction = true; - break; - } - } - - if(foundFaction == false) { - if((int)mismatchedFactionText.length() > MAX_CHAT_TEXT_LINE_LENGTH) { - mismatchedFactionTextList.push_back(mismatchedFactionText); - mismatchedFactionText = ""; - } - - if(mismatchedFactionText == "") { - mismatchedFactionText = "The following factions are mismatched: "; - if(lang.hasString("MismatchedFactions",languageList[i]) == true) { - mismatchedFactionText = lang.getString("MismatchedFactions",languageList[i]); - } - - mismatchedFactionText += " ["+ intToStr(factionCRCList.size()) + "][" + intToStr(serverFactionCRCList.size()) + "] - "; - } - else { - mismatchedFactionText += ", "; - } - - if(lang.hasString("MismatchedFactionsExtra",languageList[i]) == true) { - mismatchedFactionText += clientFaction.first + " " + lang.getString("MismatchedFactionsExtra",languageList[i]); - } - else { - mismatchedFactionText += clientFaction.first + " (extra)"; - } - } - } - - if(mismatchedFactionText != "") { - if(mismatchedFactionTextList.empty() == false) { - if(mismatchedFactionText != "") { - mismatchedFactionText += "."; - mismatchedFactionTextList.push_back(mismatchedFactionText); - } - for(unsigned int splitIdx = 0; splitIdx < mismatchedFactionTextList.size(); ++splitIdx) { - clientInterface->sendTextMessage(mismatchedFactionTextList[splitIdx],-1,localEcho,languageList[i]); - } - } - else { - mismatchedFactionText += "."; - clientInterface->sendTextMessage(mismatchedFactionText,-1,localEcho,languageList[i]); - } - } - } - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - } + if (mismatchedFactionText == "") { + mismatchedFactionText = + "The following factions are mismatched: "; + if (lang.hasString("MismatchedFactions", + languageList[i]) == true) { + mismatchedFactionText = lang.getString( + "MismatchedFactions", languageList[i]); + } + + mismatchedFactionText += + " [" + intToStr(factionCRCList.size()) + "][" + + intToStr(serverFactionCRCList.size()) + "] - "; + } else { + mismatchedFactionText += ", "; } - updateDataSynchDetailText = false; - labelDataSynchInfo.setText(labelSynch); - } - else { - labelDataSynchInfo.setText(""); + if (lang.hasString("MismatchedFactionsMissing", + languageList[i]) == true) { + mismatchedFactionText += + serverFaction.first + " " + + lang.getString("MismatchedFactionsMissing", + languageList[i]); + } else { + mismatchedFactionText += + serverFaction.first + " (missing)"; + } + } } - } - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - if(clientInterface->getAllowGameDataSynchCheck() == true && - clientInterface->getNetworkGameDataSynchCheckOk() == false) { - label = label + " -synch mismatch for:"; + for (unsigned int clientFactionIdx = 0; + clientFactionIdx < factionCRCList.size(); + ++clientFactionIdx) { + pair &clientFaction = + factionCRCList[clientFactionIdx]; + + bool foundFaction = false; + for (unsigned int factionIdx = 0; + factionIdx < serverFactionCRCList.size(); ++factionIdx) { + pair &serverFaction = + serverFactionCRCList[factionIdx]; + + if (serverFaction.first == clientFaction.first) { + foundFaction = true; + break; + } + } + + if (foundFaction == false) { + if ((int)mismatchedFactionText.length() > + MAX_CHAT_TEXT_LINE_LENGTH) { + mismatchedFactionTextList.push_back( + mismatchedFactionText); + mismatchedFactionText = ""; + } - if(clientInterface->getNetworkGameDataSynchCheckOkMap() == false) { - label = label + " map"; + if (mismatchedFactionText == "") { + mismatchedFactionText = + "The following factions are mismatched: "; + if (lang.hasString("MismatchedFactions", + languageList[i]) == true) { + mismatchedFactionText = lang.getString( + "MismatchedFactions", languageList[i]); + } + + mismatchedFactionText += + " [" + intToStr(factionCRCList.size()) + "][" + + intToStr(serverFactionCRCList.size()) + "] - "; + } else { + mismatchedFactionText += ", "; + } - if(updateDataSynchDetailText == true && - clientInterface->getReceivedDataSynchCheck() && - lastMapDataSynchError != "map CRC mismatch, " + comboBoxMap.getSelectedItem()) { - lastMapDataSynchError = "map CRC mismatch, " + comboBoxMap.getSelectedItem(); - clientInterface->sendTextMessage(lastMapDataSynchError,-1,true, ""); + if (lang.hasString("MismatchedFactionsExtra", + languageList[i]) == true) { + mismatchedFactionText += + clientFaction.first + " " + + lang.getString("MismatchedFactionsExtra", + languageList[i]); + } else { + mismatchedFactionText += clientFaction.first + " (extra)"; } + } } - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - if(clientInterface->getNetworkGameDataSynchCheckOkTile() == false) { - label = label + " tile"; - if(updateDataSynchDetailText == true && - clientInterface->getReceivedDataSynchCheck() && - lastTileDataSynchError != "tile CRC mismatch, " + listBoxTileset.getSelectedItem()) { - lastTileDataSynchError = "tile CRC mismatch, " + listBoxTileset.getSelectedItem(); - clientInterface->sendTextMessage(lastTileDataSynchError,-1,true,""); + if (mismatchedFactionText != "") { + if (mismatchedFactionTextList.empty() == false) { + if (mismatchedFactionText != "") { + mismatchedFactionText += "."; + mismatchedFactionTextList.push_back( + mismatchedFactionText); + } + for (unsigned int splitIdx = 0; + splitIdx < mismatchedFactionTextList.size(); + ++splitIdx) { + clientInterface->sendTextMessage( + mismatchedFactionTextList[splitIdx], -1, localEcho, + languageList[i]); } + } else { + mismatchedFactionText += "."; + clientInterface->sendTextMessage( + mismatchedFactionText, -1, localEcho, languageList[i]); + } } + } + + 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()); + if (SystemFlags::getSystemSettingType( + SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + } + } - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); + updateDataSynchDetailText = false; + labelDataSynchInfo.setText(labelSynch); + } else { + labelDataSynchInfo.setText(""); + } + } + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (clientInterface->getAllowGameDataSynchCheck() == true && + clientInterface->getNetworkGameDataSynchCheckOk() == false) { + label = label + " -synch mismatch for:"; + + if (clientInterface->getNetworkGameDataSynchCheckOkMap() == false) { + label = label + " map"; + + if (updateDataSynchDetailText == true && + clientInterface->getReceivedDataSynchCheck() && + lastMapDataSynchError != + "map CRC mismatch, " + comboBoxMap.getSelectedItem()) { + lastMapDataSynchError = + "map CRC mismatch, " + comboBoxMap.getSelectedItem(); + clientInterface->sendTextMessage(lastMapDataSynchError, -1, true, + ""); + } + } - if(clientInterface->getNetworkGameDataSynchCheckOkTech() == false) { - label = label + " techtree"; + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (clientInterface->getNetworkGameDataSynchCheckOkTile() == false) { + label = label + " tile"; + if (updateDataSynchDetailText == true && + clientInterface->getReceivedDataSynchCheck() && + lastTileDataSynchError != + "tile CRC mismatch, " + listBoxTileset.getSelectedItem()) { + lastTileDataSynchError = + "tile CRC mismatch, " + listBoxTileset.getSelectedItem(); + clientInterface->sendTextMessage(lastTileDataSynchError, -1, true, + ""); + } + } - if(updateDataSynchDetailText == true && - clientInterface->getReceivedDataSynchCheck()) { + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (clientInterface->getNetworkGameDataSynchCheckOkTech() == false) { + label = label + " techtree"; + + if (updateDataSynchDetailText == true && + clientInterface->getReceivedDataSynchCheck()) { + + string report = + clientInterface + ->getNetworkGameDataSynchCheckTechMismatchReport(); + if (lastTechtreeDataSynchError != + "techtree CRC mismatch" + report) { + lastTechtreeDataSynchError = "techtree CRC mismatch" + report; + + 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()); + + clientInterface->sendTextMessage("techtree CRC mismatch", -1, + true, ""); + vector reportLineTokens; + Tokenize(report, reportLineTokens, "\n"); + for (int reportLine = 0; + reportLine < (int)reportLineTokens.size(); ++reportLine) { + clientInterface->sendTextMessage(reportLineTokens[reportLine], + -1, true, ""); + } + } + } + } - string report = clientInterface->getNetworkGameDataSynchCheckTechMismatchReport(); - if(lastTechtreeDataSynchError != "techtree CRC mismatch" + report) { - lastTechtreeDataSynchError = "techtree CRC mismatch" + report; + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (clientInterface->getReceivedDataSynchCheck() == true) { + updateDataSynchDetailText = false; + } + } else if (clientInterface->getAllowGameDataSynchCheck() == true) { + label += " - data synch is ok"; + } + + labelStatus.setText(label); + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + } else { + string label = lang.getString("ConnectedToServer"); + + if (!clientInterface->getServerName().empty()) { + label = label + " " + clientInterface->getServerName(); + } + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (clientInterface->getAllowGameDataSynchCheck() == true && + clientInterface->getNetworkGameDataSynchCheckOk() == false) { + label = label + " -waiting to synch:"; + if (clientInterface->getNetworkGameDataSynchCheckOkMap() == false) { + label = label + " map"; + } + if (clientInterface->getNetworkGameDataSynchCheckOkTile() == false) { + label = label + " tile"; + } + if (clientInterface->getNetworkGameDataSynchCheckOkTech() == false) { + label = label + " techtree"; + } + } else if (clientInterface->getAllowGameDataSynchCheck() == true) { + label += " - data synch is ok"; + } - 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()); + labelStatus.setText(label); + } - clientInterface->sendTextMessage("techtree CRC mismatch",-1,true,""); - vector reportLineTokens; - Tokenize(report,reportLineTokens,"\n"); - for(int reportLine = 0; reportLine < (int)reportLineTokens.size(); ++reportLine) { - clientInterface->sendTextMessage(reportLineTokens[reportLine],-1,true,""); - } - } - } - } + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (clientInterface != NULL && clientInterface->isConnected() == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + clientInterface->close(); + } - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + returnToJoinMenu(); + return; + } + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // process network messages + if (clientInterface != NULL && clientInterface->isConnected()) { + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); - if(clientInterface->getReceivedDataSynchCheck() == true) { - updateDataSynchDetailText = false; + try { + if (clientInterface->getGameSettingsReceived() && + validDisplayedGamesettings && + lastGameSettingsReceivedCount != + clientInterface->getGameSettingsReceivedCount()) { + lastGameSettingsReceivedCount = + clientInterface->getGameSettingsReceivedCount(); + bool errorOnMissingData = + (clientInterface->getAllowGameDataSynchCheck() == false); + + const GameSettings *receivedGameSettings = + clientInterface->getGameSettings(); + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // printf("Menu got new settings thisfactionindex = %d startlocation: %d + // control = + // %d\n",displayedGamesettings.getThisFactionIndex(),clientInterface->getGameSettings()->getStartLocationIndex(clientInterface->getGameSettings()->getThisFactionIndex()),displayedGamesettings.getFactionControl(clientInterface->getGameSettings()->getThisFactionIndex())); + if (difftime((long int)time(NULL), noReceiveTimer) < 3 || + difftime((long int)time(NULL), broadcastServerSettingsDelayTimer) < + HEADLESSSERVER_BROADCAST_SETTINGS_SECONDS) { + // copy my current settings in UI to displayedSettings; + copyToGameSettings(&displayedGamesettings); + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // check if there are any changed fields from others clients + if (isHeadlessAdmin()) { + // printf("I am headless admin and will restore only some parts\n"); + // only copy those parts which are editable by normal clients + for (int i = 0; i < receivedGameSettings->getFactionCount(); i++) { + if (displayedGamesettings.getFactionControl(i) == ctNetwork) { + if (originalGamesettings.getTeam(i) == + displayedGamesettings.getTeam(i)) { + displayedGamesettings.setTeam( + i, receivedGameSettings->getTeam(i)); + originalGamesettings.setTeam( + i, receivedGameSettings->getTeam(i)); } + if (originalGamesettings.getFactionTypeName(i) == + displayedGamesettings.getFactionTypeName(i)) { + displayedGamesettings.setFactionTypeName( + i, receivedGameSettings->getFactionTypeName(i)); + originalGamesettings.setFactionTypeName( + i, receivedGameSettings->getFactionTypeName(i)); + } + displayedGamesettings.setNetworkPlayerGameStatus( + i, receivedGameSettings->getNetworkPlayerGameStatus(i)); + originalGamesettings.setNetworkPlayerGameStatus( + i, receivedGameSettings->getNetworkPlayerGameStatus(i)); + displayedGamesettings.setNetworkPlayerName( + i, receivedGameSettings->getNetworkPlayerName(i)); + originalGamesettings.setNetworkPlayerName( + i, receivedGameSettings->getNetworkPlayerName(i)); + } } - else if(clientInterface->getAllowGameDataSynchCheck() == true) { - label += " - data synch is ok"; - } - - labelStatus.setText(label); - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - } - else { - string label = lang.getString("ConnectedToServer"); + } else { + // printf("I am client and restore everything but not my line\n"); + // copy all received fields just not those which are editable for + // normal client + // store my changes + int i = clientInterface->getPlayerIndex(); + int team = displayedGamesettings.getTeam(i); + string faction = displayedGamesettings.getFactionTypeName(i); + int status = displayedGamesettings.getNetworkPlayerGameStatus(i); + string networkPlayerName = + displayedGamesettings.getNetworkPlayerName(i); + displayedGamesettings = *receivedGameSettings; + originalGamesettings = *receivedGameSettings; + + displayedGamesettings.setTeam(i, team); + originalGamesettings.setTeam(i, team); + displayedGamesettings.setFactionTypeName(i, faction); + originalGamesettings.setFactionTypeName(i, faction); + displayedGamesettings.setNetworkPlayerGameStatus(i, status); + originalGamesettings.setNetworkPlayerGameStatus(i, status); + displayedGamesettings.setNetworkPlayerName(i, networkPlayerName); + originalGamesettings.setNetworkPlayerName(i, networkPlayerName); + } + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + setupUIFromGameSettings(&displayedGamesettings, errorOnMissingData); + } else { + // do nothing + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + setupUIFromGameSettings(&displayedGamesettings, errorOnMissingData); + } - if(!clientInterface->getServerName().empty()) { - label = label + " " + clientInterface->getServerName(); + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + broadCastGameSettingsToHeadlessServer(needToBroadcastServerSettings); + } + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // check if we are joining an in progress game + if (clientInterface->getJoinGameInProgress() == true && + clientInterface->getJoinGameInProgressLaunch() == true && + clientInterface->getReadyForInGameJoin() == true && + ftpClientThread != NULL) { + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + if (readyToJoinInProgressGame == false) { + if (getInProgressSavedGameFromFTPServer == "") { + + getInProgressSavedGameFromFTPServerInProgress = true; + ftpClientThread->addTempFileToRequests( + GameConstants::saveNetworkGameFileClientCompressed, + GameConstants::saveNetworkGameFileServerCompressed); + + getInProgressSavedGameFromFTPServer = + GameConstants::saveNetworkGameFileServerCompressed; + fileFTPProgressList[getInProgressSavedGameFromFTPServer] = + pair(0, ""); + } + safeMutexFTPProgress.ReleaseLock(); + } else { + safeMutexFTPProgress.ReleaseLock(); + + string saveGameFile = + "temp/" + string(GameConstants::saveNetworkGameFileClient); + if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != + "") { + saveGameFile = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + + saveGameFile; + } else { + string userData = + Config::getInstance().getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); } + saveGameFile = userData + saveGameFile; + } + + // printf("Loading saved game file [%s]\n",saveGameFile.c_str()); + + GameSettings gameSettings = *clientInterface->getGameSettings(); + copyToGameSettings(&gameSettings); + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + Game::loadGame(saveGameFile, program, false, &gameSettings); + return; + } + } + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // update lobby + clientInterface = NetworkManager::getInstance().getClientInterface(); + if (clientInterface != NULL && clientInterface->isConnected()) { + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + clientInterface->updateLobby(); + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + } + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + clientInterface = NetworkManager::getInstance().getClientInterface(); + if (clientInterface != NULL && clientInterface->isConnected()) { + if (initialSettingsReceivedFromServer == true && + clientInterface->getIntroDone() == true && + (switchSetupRequestFlagType & ssrft_NetworkPlayerName) == + ssrft_NetworkPlayerName) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] getHumanPlayerName() = [%s], " + "clientInterface->getGameSettings()->getThisFactionIndex() = " + "%d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, getHumanPlayerName().c_str(), + clientInterface->getGameSettings()->getThisFactionIndex()); + clientInterface->sendSwitchSetupRequest( + "", clientInterface->getPlayerIndex(), -1, -1, + getHumanPlayerName(), getNetworkPlayerStatus(), + switchSetupRequestFlagType, lang.getLanguage()); + + switchSetupRequestFlagType = ssrft_None; + } - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // intro + if (clientInterface->getIntroDone()) { + if (newLabelConnectionInfo != labelInfo.getText()) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + labelInfo.setText(newLabelConnectionInfo); + } + } - if(clientInterface->getAllowGameDataSynchCheck() == true && - clientInterface->getNetworkGameDataSynchCheckOk() == false) { - label = label + " -waiting to synch:"; - if(clientInterface->getNetworkGameDataSynchCheckOkMap() == false) { - label = label + " map"; - } - if(clientInterface->getNetworkGameDataSynchCheckOkTile() == false) { - label = label + " tile"; - } - if(clientInterface->getNetworkGameDataSynchCheckOkTech() == false) { - label = label + " techtree"; - } + // launch + if (clientInterface->getLaunchGame()) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + assert(clientInterface != NULL); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + if (modHttpServerThread != NULL) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", __FILE__, + __FUNCTION__, __LINE__); + modHttpServerThread->setSimpleTaskInterfaceValid(false); + modHttpServerThread->signalQuit(); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", __FILE__, + __FUNCTION__, __LINE__); + if (modHttpServerThread->canShutdown(true) == true && + modHttpServerThread->shutdownAndWait() == true) { + delete modHttpServerThread; } - else if(clientInterface->getAllowGameDataSynchCheck() == true) - { - label += " - data synch is ok"; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + modHttpServerThread = NULL; + } + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (ftpClientThread != NULL) { + ftpClientThread->setCallBackObject(NULL); + ftpClientThread->signalQuit(); + sleep(0); + if (ftpClientThread->canShutdown(true) == true && + ftpClientThread->shutdownAndWait() == true) { + delete ftpClientThread; + } else { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s %d] Error cannot shutdown ftpClientThread\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("%s", szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); } + ftpClientThread = NULL; + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + launchingNewGame = true; + + GameSettings gameSettings = *clientInterface->getGameSettings(); + // complete game settings with local stuff + if (gameSettings.getScenario() != "") { + string scenario = gameSettings.getScenario(); + listBoxScenario.setSelectedItem(formatString(scenario)); + string file = Scenario::getScenarioPath(dirList, scenario); + + bool isTutorial = Scenario::isGameTutorial(file); + Scenario::loadScenarioInfo(file, &scenarioInfo, isTutorial); + + gameSettings.setScenarioDir( + Scenario::getScenarioPath(dirList, scenarioInfo.name)); + + gameSettings.setDefaultResources(scenarioInfo.defaultResources); + gameSettings.setDefaultUnits(scenarioInfo.defaultUnits); + gameSettings.setDefaultVictoryConditions( + scenarioInfo.defaultVictoryConditions); + } + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + program->setState(new Game(program, &gameSettings, false)); + return; + } + } + + // call the chat manager + chatManager.updateNetwork(); + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // console732 + console.update(); + + // check for need to switch music on again + if (clientInterface != NULL) { + int currentConnectionCount = 0; + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + if (displayedGamesettings.getFactionControl(i) == ctNetwork && + displayedGamesettings.getNetworkPlayerName(i) != "" && + displayedGamesettings.getNetworkPlayerName(i) != + GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME) { + currentConnectionCount++; + } + } + if (currentConnectionCount > soundConnectionCount) { + soundConnectionCount = currentConnectionCount; + SoundRenderer::getInstance().playFx( + CoreData::getInstance().getAttentionSound()); + // switch on music again!! + Config &config = Config::getInstance(); + float configVolume = (config.getInt("SoundVolumeMusic") / 100.f); + CoreData::getInstance().getMenuMusic()->setVolume(configVolume); + } + soundConnectionCount = currentConnectionCount; + } + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + } catch (const runtime_error &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d] %s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, szBuf); + showMessageBox(szBuf, "Error", false); + } - labelStatus.setText(label); - } - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(clientInterface != NULL && clientInterface->isConnected() == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - clientInterface->close(); - } - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - returnToJoinMenu(); - return; - } - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - //process network messages - if(clientInterface != NULL && clientInterface->isConnected()) { - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - try { - if(clientInterface->getGameSettingsReceived() && validDisplayedGamesettings && - lastGameSettingsReceivedCount != clientInterface->getGameSettingsReceivedCount()) { - lastGameSettingsReceivedCount = clientInterface->getGameSettingsReceivedCount(); - bool errorOnMissingData = (clientInterface->getAllowGameDataSynchCheck() == false); - - const GameSettings *receivedGameSettings= clientInterface->getGameSettings(); - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - //printf("Menu got new settings thisfactionindex = %d startlocation: %d control = %d\n",displayedGamesettings.getThisFactionIndex(),clientInterface->getGameSettings()->getStartLocationIndex(clientInterface->getGameSettings()->getThisFactionIndex()),displayedGamesettings.getFactionControl(clientInterface->getGameSettings()->getThisFactionIndex())); - if ( difftime((long int)time(NULL),noReceiveTimer) < 3 || difftime((long int)time(NULL),broadcastServerSettingsDelayTimer) < HEADLESSSERVER_BROADCAST_SETTINGS_SECONDS){ - // copy my current settings in UI to displayedSettings; - copyToGameSettings(&displayedGamesettings); - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - // check if there are any changed fields from others clients - if(isHeadlessAdmin()){ - //printf("I am headless admin and will restore only some parts\n"); - // only copy those parts which are editable by normal clients - for (int i=0;igetFactionCount();i++){ - if(displayedGamesettings.getFactionControl(i)==ctNetwork){ - if(originalGamesettings.getTeam(i)==displayedGamesettings.getTeam(i)){ - displayedGamesettings.setTeam(i,receivedGameSettings->getTeam(i)); - originalGamesettings.setTeam(i,receivedGameSettings->getTeam(i)); - } - if(originalGamesettings.getFactionTypeName(i)==displayedGamesettings.getFactionTypeName(i)){ - displayedGamesettings.setFactionTypeName(i,receivedGameSettings->getFactionTypeName(i)); - originalGamesettings.setFactionTypeName(i,receivedGameSettings->getFactionTypeName(i)); - } - displayedGamesettings.setNetworkPlayerGameStatus(i,receivedGameSettings->getNetworkPlayerGameStatus(i)); - originalGamesettings.setNetworkPlayerGameStatus(i,receivedGameSettings->getNetworkPlayerGameStatus(i)); - displayedGamesettings.setNetworkPlayerName(i,receivedGameSettings->getNetworkPlayerName(i)); - originalGamesettings.setNetworkPlayerName(i,receivedGameSettings->getNetworkPlayerName(i)); - } - } - } - else{ - //printf("I am client and restore everything but not my line\n"); - // copy all received fields just not those which are editable for normal client - //store my changes - int i=clientInterface->getPlayerIndex(); - int team=displayedGamesettings.getTeam(i); - string faction=displayedGamesettings.getFactionTypeName(i); - int status=displayedGamesettings.getNetworkPlayerGameStatus(i); - string networkPlayerName=displayedGamesettings.getNetworkPlayerName(i); - displayedGamesettings=*receivedGameSettings; - originalGamesettings=*receivedGameSettings; - - displayedGamesettings.setTeam(i,team); - originalGamesettings.setTeam(i,team); - displayedGamesettings.setFactionTypeName(i,faction); - originalGamesettings.setFactionTypeName(i,faction); - displayedGamesettings.setNetworkPlayerGameStatus(i,status); - originalGamesettings.setNetworkPlayerGameStatus(i,status); - displayedGamesettings.setNetworkPlayerName(i,networkPlayerName); - originalGamesettings.setNetworkPlayerName(i,networkPlayerName); - - } - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - setupUIFromGameSettings(&displayedGamesettings, errorOnMissingData); - } - else { - // do nothing - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - setupUIFromGameSettings(&displayedGamesettings, errorOnMissingData); - } - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - broadCastGameSettingsToHeadlessServer(needToBroadcastServerSettings); - } - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - // check if we are joining an in progress game - if( clientInterface->getJoinGameInProgress() == true && - clientInterface->getJoinGameInProgressLaunch() == true && - clientInterface->getReadyForInGameJoin() == true && - ftpClientThread != NULL) { - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - if(readyToJoinInProgressGame == false) { - if(getInProgressSavedGameFromFTPServer == "") { - - getInProgressSavedGameFromFTPServerInProgress = true; - ftpClientThread->addTempFileToRequests( - GameConstants::saveNetworkGameFileClientCompressed, - GameConstants::saveNetworkGameFileServerCompressed); - - getInProgressSavedGameFromFTPServer = GameConstants::saveNetworkGameFileServerCompressed; - fileFTPProgressList[getInProgressSavedGameFromFTPServer] = pair(0,""); - } - safeMutexFTPProgress.ReleaseLock(); - } - else { - safeMutexFTPProgress.ReleaseLock(); - - string saveGameFile = "temp/" + string(GameConstants::saveNetworkGameFileClient); - if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - saveGameFile = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + saveGameFile; - } - else { - string userData = Config::getInstance().getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - saveGameFile = userData + saveGameFile; - } - - //printf("Loading saved game file [%s]\n",saveGameFile.c_str()); - - GameSettings gameSettings = *clientInterface->getGameSettings(); - copyToGameSettings(&gameSettings); - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - Game::loadGame(saveGameFile,program,false,&gameSettings); - return; - } - } - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - //update lobby - clientInterface= NetworkManager::getInstance().getClientInterface(); - if(clientInterface != NULL && clientInterface->isConnected()) { - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - clientInterface->updateLobby(); - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - } - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - clientInterface= NetworkManager::getInstance().getClientInterface(); - if(clientInterface != NULL && clientInterface->isConnected()) { - if( initialSettingsReceivedFromServer == true && - clientInterface->getIntroDone() == true && - (switchSetupRequestFlagType & ssrft_NetworkPlayerName) == ssrft_NetworkPlayerName) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] getHumanPlayerName() = [%s], clientInterface->getGameSettings()->getThisFactionIndex() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,getHumanPlayerName().c_str(),clientInterface->getGameSettings()->getThisFactionIndex()); - clientInterface->sendSwitchSetupRequest( - "", - clientInterface->getPlayerIndex(), - -1, - -1, - getHumanPlayerName(), - getNetworkPlayerStatus(), - switchSetupRequestFlagType, - lang.getLanguage()); - - switchSetupRequestFlagType=ssrft_None; - } - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - //intro - if(clientInterface->getIntroDone()) { - if(newLabelConnectionInfo != labelInfo.getText()) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - labelInfo.setText(newLabelConnectionInfo); - } - } - - //launch - if(clientInterface->getLaunchGame()) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - assert(clientInterface != NULL); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(modHttpServerThread != NULL) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - modHttpServerThread->setSimpleTaskInterfaceValid(false); - modHttpServerThread->signalQuit(); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - if( modHttpServerThread->canShutdown(true) == true && - modHttpServerThread->shutdownAndWait() == true) { - delete modHttpServerThread; - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - modHttpServerThread = NULL; - } - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - if(ftpClientThread != NULL) { - ftpClientThread->setCallBackObject(NULL); - ftpClientThread->signalQuit(); - sleep(0); - if(ftpClientThread->canShutdown(true) == true && - ftpClientThread->shutdownAndWait() == true) { - delete ftpClientThread; - } - else { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] Error cannot shutdown ftpClientThread\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s",szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - } - ftpClientThread = NULL; - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - launchingNewGame = true; - - GameSettings gameSettings = *clientInterface->getGameSettings(); - // complete game settings with local stuff - if(gameSettings.getScenario()!="") - { - string scenario = gameSettings.getScenario(); - listBoxScenario.setSelectedItem(formatString(scenario)); - string file = Scenario::getScenarioPath(dirList, scenario); + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + } +} - bool isTutorial = Scenario::isGameTutorial(file); - Scenario::loadScenarioInfo(file, &scenarioInfo, isTutorial); +bool MenuStateConnectedGame::loadFactions(const GameSettings *gameSettings, + bool errorOnNoFactions) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - gameSettings.setScenarioDir(Scenario::getScenarioPath(dirList, scenarioInfo.name)); + Lang &lang = Lang::getInstance(); + bool foundFactions = false; + vector results; - gameSettings.setDefaultResources(scenarioInfo.defaultResources); - gameSettings.setDefaultUnits(scenarioInfo.defaultUnits); - gameSettings.setDefaultVictoryConditions(scenarioInfo.defaultVictoryConditions); - } + string scenarioDir = + Scenario::getScenarioDir(dirList, gameSettings->getScenario()); + if (gameSettings->getTech() != "") { + Config &config = Config::getInstance(); - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - program->setState(new Game(program, &gameSettings,false)); - return; - } - } - - //call the chat manager - chatManager.updateNetwork(); - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - //console732 - console.update(); - - // check for need to switch music on again - if(clientInterface != NULL) { - int currentConnectionCount=0; - for(int i=0; i < GameConstants::maxPlayers; ++i) { - if(displayedGamesettings.getFactionControl(i)==ctNetwork && - displayedGamesettings.getNetworkPlayerName(i) != "" && - displayedGamesettings.getNetworkPlayerName(i) != GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME) - { - currentConnectionCount++; - } - } - if(currentConnectionCount > soundConnectionCount){ - soundConnectionCount = currentConnectionCount; - SoundRenderer::getInstance().playFx(CoreData::getInstance().getAttentionSound()); - //switch on music again!! - Config &config = Config::getInstance(); - float configVolume = (config.getInt("SoundVolumeMusic") / 100.f); - CoreData::getInstance().getMenuMusic()->setVolume(configVolume); - } - soundConnectionCount = currentConnectionCount; - } - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - } - catch(const runtime_error &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] %s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,szBuf); - showMessageBox( szBuf, "Error", false); - } - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - } -} + vector techPaths = config.getPathListForType(ptTechs, scenarioDir); + for (int idx = 0; idx < (int)techPaths.size(); idx++) { + string &techPath = techPaths[idx]; + endPathWithSlash(techPath); + // findAll(techPath + gameSettings->getTech() + "/factions/*.", results, + // false, false); + findDirs(techPath + gameSettings->getTech() + "/factions/", results, + false, false); + if (results.empty() == false) { + break; + } + } -bool MenuStateConnectedGame::loadFactions(const GameSettings *gameSettings, bool errorOnNoFactions) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - Lang &lang= Lang::getInstance(); - bool foundFactions = false; - vector results; - - string scenarioDir = Scenario::getScenarioDir(dirList, gameSettings->getScenario()); - if(gameSettings->getTech() != "") { - Config &config = Config::getInstance(); - - vector techPaths = config.getPathListForType(ptTechs,scenarioDir); - for(int idx = 0; idx < (int)techPaths.size(); idx++) { - string &techPath = techPaths[idx]; - endPathWithSlash(techPath); - //findAll(techPath + gameSettings->getTech() + "/factions/*.", results, false, false); - findDirs(techPath + gameSettings->getTech() + "/factions/", results, false, false); - if(results.empty() == false) { - break; - } - } - - if(results.empty() == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface* clientInterface= networkManager.getClientInterface(); - if(clientInterface->getAllowGameDataSynchCheck() == false) { - if(errorOnNoFactions == true) { - throw megaglest_runtime_error("(2)There are no factions for the tech tree [" + gameSettings->getTech() + "]"); - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] (2)There are no factions for the tech tree [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,gameSettings->getTech().c_str()); - } - results.push_back(Lang::getInstance().getString("DataMissing","",true)); - factionFiles = results; - vector translatedFactionNames; - for(int i= 0; i < (int)factionFiles.size(); ++i) { - results[i]= formatString(results[i]); - string translatedString=techTree->getTranslatedFactionName(gameSettings->getTech(),factionFiles[i]); - if(toLower(translatedString)==toLower(results[i])){ - translatedFactionNames.push_back(results[i]); - } - else { - translatedFactionNames.push_back(results[i]+" ("+translatedString+")"); - } - } - - for(int i=0; igetTech() && - gameSettings->getTech() != "") { - lastMissingTechtree = gameSettings->getTech(); - - Lang &lang= Lang::getInstance(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - - char szMsg[8096]=""; - if(lang.hasString("DataMissingTechtree",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("DataMissingTechtree",languageList[i]).c_str(),getHumanPlayerName().c_str(),gameSettings->getTech().c_str()); - } - else { - snprintf(szMsg,8096,"Player: %s is missing the techtree: %s",getHumanPlayerName().c_str(),gameSettings->getTech().c_str()); - } - clientInterface->sendTextMessage(szMsg,-1, lang.isLanguageLocal(languageList[i]),languageList[i]); - } - } - - foundFactions = false; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - else { - lastMissingTechtree = ""; - getMissingTechtreeFromFTPServer = ""; - - factionFiles= results; - vector translatedFactionNames; - for(int i= 0; i < (int)factionFiles.size(); ++i) { - results[i]= formatString(results[i]); - string translatedString=techTree->getTranslatedFactionName(gameSettings->getTech(),factionFiles[i]); - if(toLower(translatedString)==toLower(results[i])){ - translatedFactionNames.push_back(results[i]); - } - else { - translatedFactionNames.push_back(results[i]+" ("+translatedString+")"); - } - } - - results.push_back(formatString(GameConstants::RANDOMFACTION_SLOTNAME)); - factionFiles.push_back(formatString(GameConstants::RANDOMFACTION_SLOTNAME)); - translatedFactionNames.push_back("*"+lang.getString("Random","",true)+"*"); - - // Add special Observer Faction - if(checkBoxAllowObservers.getValue() == 1) { - results.push_back(formatString(GameConstants::OBSERVER_SLOTNAME)); - factionFiles.push_back(formatString(GameConstants::OBSERVER_SLOTNAME)); - translatedFactionNames.push_back("*"+lang.getString("Observer","",true)+"*"); - } - - - for(int i=0; igetAllowGameDataSynchCheck() == false) { + if (errorOnNoFactions == true) { + throw megaglest_runtime_error( + "(2)There are no factions for the tech tree [" + + gameSettings->getTech() + "]"); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] (2)There are no factions for the tech tree " + "[%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, gameSettings->getTech().c_str()); + } + results.push_back(Lang::getInstance().getString("DataMissing", "", true)); + factionFiles = results; + vector translatedFactionNames; + for (int i = 0; i < (int)factionFiles.size(); ++i) { + results[i] = formatString(results[i]); + string translatedString = techTree->getTranslatedFactionName( + gameSettings->getTech(), factionFiles[i]); + if (toLower(translatedString) == toLower(results[i])) { + translatedFactionNames.push_back(results[i]); + } else { + translatedFactionNames.push_back(results[i] + " (" + + translatedString + ")"); + } + } + + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + listBoxFactions[i].setItems(results, translatedFactionNames); + } + + if (lastMissingTechtree != gameSettings->getTech() && + gameSettings->getTech() != "") { + lastMissingTechtree = gameSettings->getTech(); + + Lang &lang = Lang::getInstance(); + const vector languageList = + clientInterface->getGameSettings() + ->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + + char szMsg[8096] = ""; + if (lang.hasString("DataMissingTechtree", languageList[i]) == true) { + snprintf( + szMsg, 8096, + lang.getString("DataMissingTechtree", languageList[i]).c_str(), + getHumanPlayerName().c_str(), gameSettings->getTech().c_str()); + } else { + snprintf(szMsg, 8096, "Player: %s is missing the techtree: %s", + getHumanPlayerName().c_str(), + gameSettings->getTech().c_str()); + } + clientInterface->sendTextMessage( + szMsg, -1, lang.isLanguageLocal(languageList[i]), + languageList[i]); + } + } + + foundFactions = false; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + } else { + lastMissingTechtree = ""; + getMissingTechtreeFromFTPServer = ""; + + factionFiles = results; + vector translatedFactionNames; + for (int i = 0; i < (int)factionFiles.size(); ++i) { + results[i] = formatString(results[i]); + string translatedString = techTree->getTranslatedFactionName( + gameSettings->getTech(), factionFiles[i]); + if (toLower(translatedString) == toLower(results[i])) { + translatedFactionNames.push_back(results[i]); + } else { + translatedFactionNames.push_back(results[i] + " (" + + translatedString + ")"); + } + } + + results.push_back(formatString(GameConstants::RANDOMFACTION_SLOTNAME)); + factionFiles.push_back( + formatString(GameConstants::RANDOMFACTION_SLOTNAME)); + translatedFactionNames.push_back( + "*" + lang.getString("Random", "", true) + "*"); + + // Add special Observer Faction + if (checkBoxAllowObservers.getValue() == 1) { + results.push_back(formatString(GameConstants::OBSERVER_SLOTNAME)); + factionFiles.push_back(formatString(GameConstants::OBSERVER_SLOTNAME)); + translatedFactionNames.push_back( + "*" + lang.getString("Observer", "", true) + "*"); + } + + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + listBoxFactions[i].setItems(results, translatedFactionNames); + } + + foundFactions = (results.empty() == false); + } + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + return foundFactions; } // ============ PRIVATE =========================== -void MenuStateConnectedGame::setSmallFont(GraphicLabel l){ - l.setFont(CoreData::getInstance().getDisplayFontSmall()); - l.setFont3D(CoreData::getInstance().getDisplayFontSmall3D()); +void MenuStateConnectedGame::setSmallFont(GraphicLabel l) { + l.setFont(CoreData::getInstance().getDisplayFontSmall()); + l.setFont3D(CoreData::getInstance().getDisplayFontSmall3D()); } bool MenuStateConnectedGame::hasNetworkGameSettings() { - bool hasNetworkSlot = false; - - try { - for(int i=0; i(listBoxControls[i].getSelectedItemIndex()); - if(ct != ctClosed) { - if(ct == ctNetwork || ct == ctNetworkUnassigned) { - hasNetworkSlot = true; - break; - } - } - } - if(hasNetworkSlot == false) { - for(int i=0; i < GameConstants::maxPlayers; ++i) { - ControlType ct= static_cast(listBoxControls[i].getSelectedItemIndex()); - if(ct != ctClosed) { - if(ct == ctNetworkUnassigned) { - hasNetworkSlot = true; - break; - } - } - } - } - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] %s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,szBuf); - showMessageBox( szBuf, "Error", false); - } - - return hasNetworkSlot; + bool hasNetworkSlot = false; + + try { + for (int i = 0; i < mapInfo.players; ++i) { + ControlType ct = + static_cast(listBoxControls[i].getSelectedItemIndex()); + if (ct != ctClosed) { + if (ct == ctNetwork || ct == ctNetworkUnassigned) { + hasNetworkSlot = true; + break; + } + } + } + if (hasNetworkSlot == false) { + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + ControlType ct = + static_cast(listBoxControls[i].getSelectedItemIndex()); + if (ct != ctClosed) { + if (ct == ctNetworkUnassigned) { + hasNetworkSlot = true; + break; + } + } + } + } + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d] %s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, szBuf); + showMessageBox(szBuf, "Error", false); + } + + return hasNetworkSlot; } void MenuStateConnectedGame::keyDown(SDL_KeyboardEvent key) { - if(activeInputLabel != NULL) { - bool handled = keyDownEditLabel(key, &activeInputLabel); - if(handled == true) { - switchSetupRequestFlagType |= ssrft_NetworkPlayerName; - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); - } - } - else { - //send key to the chat manager - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface *clientInterface = networkManager.getClientInterface(); - if(clientInterface != NULL && - clientInterface->isConnected() == true && - clientInterface->getIntroDone() == true) { - chatManager.keyDown(key); - } - if(chatManager.getEditEnabled() == false && - (::Shared::Platform::Window::isKeyStateModPressed(KMOD_SHIFT) == false)) { - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - - if(isKeyPressed(configKeys.getSDLKey("ShowFullConsole"),key) == true) { - showFullConsole= true; - } - else if(isKeyPressed(configKeys.getSDLKey("ToggleMusic"),key) == true) { - Config &config = Config::getInstance(); - Lang &lang= Lang::getInstance(); - - float configVolume = (config.getInt("SoundVolumeMusic") / 100.f); - float currentVolume = CoreData::getInstance().getMenuMusic()->getVolume(); - if(currentVolume > 0) { - CoreData::getInstance().getMenuMusic()->setVolume(0.f); - console.addLine(lang.getString("GameMusic") + " " + lang.getString("Off")); - } - else { - CoreData::getInstance().getMenuMusic()->setVolume(configVolume); - //If the config says zero, use the default music volume - //gameMusic->setVolume(configVolume ? configVolume : 0.9); - console.addLine(lang.getString("GameMusic")); - } - } - //else if(key == configKeys.getCharKey("SaveGUILayout")) { - else if(isKeyPressed(configKeys.getSDLKey("SaveGUILayout"),key) == true) { - bool saved = GraphicComponent::saveAllCustomProperties(containerName); - Lang &lang= Lang::getInstance(); - console.addLine(lang.getString("GUILayoutSaved") + " [" + (saved ? lang.getString("Yes") : lang.getString("No"))+ "]"); - } - } - } + if (activeInputLabel != NULL) { + bool handled = keyDownEditLabel(key, &activeInputLabel); + if (handled == true) { + switchSetupRequestFlagType |= ssrft_NetworkPlayerName; + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + } + } else { + // send key to the chat manager + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + if (clientInterface != NULL && clientInterface->isConnected() == true && + clientInterface->getIntroDone() == true) { + chatManager.keyDown(key); + } + if (chatManager.getEditEnabled() == false && + (::Shared::Platform::Window::isKeyStateModPressed(KMOD_SHIFT) == + false)) { + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + + if (isKeyPressed(configKeys.getSDLKey("ShowFullConsole"), key) == true) { + showFullConsole = true; + } else if (isKeyPressed(configKeys.getSDLKey("ToggleMusic"), key) == + true) { + Config &config = Config::getInstance(); + Lang &lang = Lang::getInstance(); + + float configVolume = (config.getInt("SoundVolumeMusic") / 100.f); + float currentVolume = + CoreData::getInstance().getMenuMusic()->getVolume(); + if (currentVolume > 0) { + CoreData::getInstance().getMenuMusic()->setVolume(0.f); + console.addLine(lang.getString("GameMusic") + " " + + lang.getString("Off")); + } else { + CoreData::getInstance().getMenuMusic()->setVolume(configVolume); + // If the config says zero, use the default music volume + // gameMusic->setVolume(configVolume ? configVolume : 0.9); + console.addLine(lang.getString("GameMusic")); + } + } + // else if(key == configKeys.getCharKey("SaveGUILayout")) { + else if (isKeyPressed(configKeys.getSDLKey("SaveGUILayout"), key) == + true) { + bool saved = GraphicComponent::saveAllCustomProperties(containerName); + Lang &lang = Lang::getInstance(); + console.addLine(lang.getString("GUILayoutSaved") + " [" + + (saved ? lang.getString("Yes") : lang.getString("No")) + + "]"); + } + } + } } bool MenuStateConnectedGame::textInput(std::string text) { - if (activeInputLabel != NULL) { - bool handled = textInputEditLabel(text, &activeInputLabel); - if (handled == true) { - switchSetupRequestFlagType |= ssrft_NetworkPlayerName; - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); - } - return handled; - } else { - NetworkManager &networkManager = NetworkManager::getInstance(); - ClientInterface *clientInterface = networkManager.getClientInterface(); - if (clientInterface != NULL && clientInterface->isConnected() == true - && clientInterface->getIntroDone() == true) { - return chatManager.textInput(text); - } - } - return false; + if (activeInputLabel != NULL) { + bool handled = textInputEditLabel(text, &activeInputLabel); + if (handled == true) { + switchSetupRequestFlagType |= ssrft_NetworkPlayerName; + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + } + return handled; + } else { + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + if (clientInterface != NULL && clientInterface->isConnected() == true && + clientInterface->getIntroDone() == true) { + return chatManager.textInput(text); + } + } + return false; } void MenuStateConnectedGame::keyPress(SDL_KeyboardEvent c) { - if(activeInputLabel!=NULL) { - keyPressEditLabel( c, &activeInputLabel); - } else { - NetworkManager &networkManager = NetworkManager::getInstance(); - ClientInterface *clientInterface = networkManager.getClientInterface(); - if (clientInterface != NULL && clientInterface->isConnected() == true - && clientInterface->getIntroDone() == true) { - chatManager.keyPress(c); - } - } + if (activeInputLabel != NULL) { + keyPressEditLabel(c, &activeInputLabel); + } else { + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + if (clientInterface != NULL && clientInterface->isConnected() == true && + clientInterface->getIntroDone() == true) { + chatManager.keyPress(c); + } + } } void MenuStateConnectedGame::keyUp(SDL_KeyboardEvent key) { - if(activeInputLabel==NULL) { - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface *clientInterface = networkManager.getClientInterface(); - if(clientInterface != NULL && - clientInterface->isConnected() == true && - clientInterface->getIntroDone() == true) { - chatManager.keyUp(key); - } - - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - - if(chatManager.getEditEnabled()) { - //send key to the chat manager - chatManager.keyUp(key); - } - else if(isKeyPressed(configKeys.getSDLKey("ShowFullConsole"),key) == true) { - showFullConsole= false; - } - } + if (activeInputLabel == NULL) { + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + if (clientInterface != NULL && clientInterface->isConnected() == true && + clientInterface->getIntroDone() == true) { + chatManager.keyUp(key); + } + + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + + if (chatManager.getEditEnabled()) { + // send key to the chat manager + chatManager.keyUp(key); + } else if (isKeyPressed(configKeys.getSDLKey("ShowFullConsole"), key) == + true) { + showFullConsole = false; + } + } } void MenuStateConnectedGame::setActiveInputLabel(GraphicLabel *newLable) { - MenuState::setActiveInputLabel(newLable,&activeInputLabel); + MenuState::setActiveInputLabel(newLable, &activeInputLabel); } string MenuStateConnectedGame::getHumanPlayerName() { - string result = defaultPlayerName; - - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface* clientInterface= networkManager.getClientInterface(); - for(int j=0; jgetPlayerIndex() && - labelPlayerNames[j].getText() != "") { - result = labelPlayerNames[j].getText(); - - if(activeInputLabel != NULL) { - size_t found = result.find_last_of("_"); - if (found != string::npos) { - result = result.substr(0,found); - } - } - - break; - } - } - - return result; + string result = defaultPlayerName; + + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + for (int j = 0; j < GameConstants::maxPlayers; ++j) { + if (clientInterface != NULL && j == clientInterface->getPlayerIndex() && + labelPlayerNames[j].getText() != "") { + result = labelPlayerNames[j].getText(); + + if (activeInputLabel != NULL) { + size_t found = result.find_last_of("_"); + if (found != string::npos) { + result = result.substr(0, found); + } + } + + break; + } + } + + return result; } void MenuStateConnectedGame::loadFactionTexture(string filepath) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(enableFactionTexturePreview == true) { - if(filepath == "") { - factionTexture=NULL; - } - else { - 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()); - factionTexture = Renderer::findTexture(filepath); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (enableFactionTexturePreview == true) { + if (filepath == "") { + factionTexture = NULL; + } else { + 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()); + factionTexture = Renderer::findTexture(filepath); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + } + } } -bool MenuStateConnectedGame::loadMapInfo(string file, MapInfo *mapInfo, bool loadMapPreview, bool doPlayerSetup) { - bool mapLoaded = false; - try { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] map [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,file.c_str()); - - if(file != "") { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - lastMissingMap = file; - - Lang &lang= Lang::getInstance(); - if(MapPreview::loadMapInfo(file, mapInfo, lang.getString("MaxPlayers"),lang.getString("Size"),true) == true) { - for(int i = 0; i < GameConstants::maxPlayers; ++i) { - bool visible=i+1 <= mapInfo->players; - labelPlayers[i].setVisible(visible); - labelPlayerNames[i].setVisible(visible); - listBoxControls[i].setVisible(visible); - listBoxRMultiplier[i].setVisible(visible); - listBoxFactions[i].setVisible(visible); - listBoxTeams[i].setVisible(visible); - labelNetStatus[i].setVisible(visible); - } - - // Not painting properly so this is on hold - if(loadMapPreview == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(mapPreview.getMapFileLoaded() != file) { - mapPreview.loadFromFile(file.c_str()); - cleanupMapPreviewTexture(); - } - } - - mapLoaded = true; - } - } - else { - cleanupMapPreviewTexture(); - mapInfo->desc = Lang::getInstance().getString("DataMissing","",true); - - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface* clientInterface= networkManager.getClientInterface(); - const GameSettings *gameSettings = clientInterface->getGameSettings(); - - if(lastMissingMap != gameSettings->getMap()) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - lastMissingMap = gameSettings->getMap(); - - Lang &lang= Lang::getInstance(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - - char szMsg[8096]=""; - if(lang.hasString("DataMissingMap",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("DataMissingMap",languageList[i]).c_str(),getHumanPlayerName().c_str(),gameSettings->getMap().c_str()); - } - else { - snprintf(szMsg,8096,"Player: %s is missing the map: %s",getHumanPlayerName().c_str(),gameSettings->getMap().c_str()); - } - clientInterface->sendTextMessage(szMsg,-1, lang.isLanguageLocal(languageList[i]),languageList[i]); - } - } - } - } - catch(exception &e){ - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what()); - - showMessageBox( "Error loading map file: "+file+'\n'+e.what(), "Error", false); - } - return mapLoaded; +bool MenuStateConnectedGame::loadMapInfo(string file, MapInfo *mapInfo, + bool loadMapPreview, + bool doPlayerSetup) { + bool mapLoaded = false; + try { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] map [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, file.c_str()); + + if (file != "") { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + lastMissingMap = file; + + Lang &lang = Lang::getInstance(); + if (MapPreview::loadMapInfo(file, mapInfo, lang.getString("MaxPlayers"), + lang.getString("Size"), true) == true) { + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + bool visible = i + 1 <= mapInfo->players; + labelPlayers[i].setVisible(visible); + labelPlayerNames[i].setVisible(visible); + listBoxControls[i].setVisible(visible); + listBoxRMultiplier[i].setVisible(visible); + listBoxFactions[i].setVisible(visible); + listBoxTeams[i].setVisible(visible); + labelNetStatus[i].setVisible(visible); + } + + // Not painting properly so this is on hold + if (loadMapPreview == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + if (mapPreview.getMapFileLoaded() != file) { + mapPreview.loadFromFile(file.c_str()); + cleanupMapPreviewTexture(); + } + } + + mapLoaded = true; + } + } else { + cleanupMapPreviewTexture(); + mapInfo->desc = Lang::getInstance().getString("DataMissing", "", true); + + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + const GameSettings *gameSettings = clientInterface->getGameSettings(); + + if (lastMissingMap != gameSettings->getMap()) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + lastMissingMap = gameSettings->getMap(); + + Lang &lang = Lang::getInstance(); + const vector languageList = + clientInterface->getGameSettings() + ->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + + char szMsg[8096] = ""; + if (lang.hasString("DataMissingMap", languageList[i]) == true) { + snprintf(szMsg, 8096, + lang.getString("DataMissingMap", languageList[i]).c_str(), + getHumanPlayerName().c_str(), + gameSettings->getMap().c_str()); + } else { + snprintf(szMsg, 8096, "Player: %s is missing the map: %s", + getHumanPlayerName().c_str(), + gameSettings->getMap().c_str()); + } + clientInterface->sendTextMessage( + szMsg, -1, lang.isLanguageLocal(languageList[i]), + languageList[i]); + } + } + } + } catch (exception &e) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, e.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, e.what()); + + showMessageBox("Error loading map file: " + file + '\n' + e.what(), "Error", + false); + } + return mapLoaded; } -void MenuStateConnectedGame::showMessageBox(const string &text, const string &header, bool toggle){ - if(!toggle){ - mainMessageBox.setEnabled(false); - } - - if(!mainMessageBox.getEnabled()){ - mainMessageBox.setText(text); - mainMessageBox.setHeader(header); - mainMessageBox.setEnabled(true); - } - else{ - mainMessageBox.setEnabled(false); - } +void MenuStateConnectedGame::showMessageBox(const string &text, + const string &header, bool toggle) { + if (!toggle) { + mainMessageBox.setEnabled(false); + } + + if (!mainMessageBox.getEnabled()) { + mainMessageBox.setText(text); + mainMessageBox.setHeader(header); + mainMessageBox.setEnabled(true); + } else { + mainMessageBox.setEnabled(false); + } } -void MenuStateConnectedGame::showFTPMessageBox(const string &text, const string &header, bool toggle) { - if(!toggle) { - ftpMessageBox.setEnabled(false); - } - - if(!ftpMessageBox.getEnabled()) { - ftpMessageBox.setText(text); - ftpMessageBox.setHeader(header); - ftpMessageBox.setEnabled(true); - } - else { - ftpMessageBox.setEnabled(false); - } +void MenuStateConnectedGame::showFTPMessageBox(const string &text, + const string &header, + bool toggle) { + if (!toggle) { + ftpMessageBox.setEnabled(false); + } + + if (!ftpMessageBox.getEnabled()) { + ftpMessageBox.setText(text); + ftpMessageBox.setHeader(header); + ftpMessageBox.setEnabled(true); + } else { + ftpMessageBox.setEnabled(false); + } } int32 MenuStateConnectedGame::getNetworkPlayerStatus() { - int32 result = npst_None; - switch(listBoxPlayerStatus.getSelectedItemIndex()) { - case 2: - result = npst_Ready; - break; - case 1: - result = npst_BeRightBack; - break; - case 0: - result = npst_PickSettings; - break; - } - - return result; + int32 result = npst_None; + switch (listBoxPlayerStatus.getSelectedItemIndex()) { + case 2: + result = npst_Ready; + break; + case 1: + result = npst_BeRightBack; + break; + case 0: + result = npst_PickSettings; + break; + } + + return result; } void MenuStateConnectedGame::cleanupMapPreviewTexture() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(mapPreviewTexture != NULL) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - mapPreviewTexture->end(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - delete mapPreviewTexture; - mapPreviewTexture = NULL; - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (mapPreviewTexture != NULL) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + mapPreviewTexture->end(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + delete mapPreviewTexture; + mapPreviewTexture = NULL; + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); } bool MenuStateConnectedGame::isInSpecialKeyCaptureEvent() { - bool result = (chatManager.getEditEnabled() || activeInputLabel != NULL); - return result; + bool result = (chatManager.getEditEnabled() || activeInputLabel != NULL); + return result; } -void MenuStateConnectedGame::FTPClient_CallbackEvent(string itemName, - FTP_Client_CallbackType type, pair result, void *userdata) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void MenuStateConnectedGame::FTPClient_CallbackEvent( + string itemName, FTP_Client_CallbackType type, + pair result, void *userdata) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (type == ftp_cct_DownloadProgress) { + FTPClientCallbackInterface::FtpProgressStats *stats = + (FTPClientCallbackInterface::FtpProgressStats *)userdata; + if (stats != NULL) { + int fileProgress = 0; + if (stats->download_total > 0) { + fileProgress = ((stats->download_now / stats->download_total) * 100.0); + } + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Got FTP Callback for [%s] + // current file [%s] fileProgress = %d [now = %f, total = + // %f]\n",itemName.c_str(),stats->currentFilename.c_str(), + // fileProgress,stats->download_now,stats->download_total); + + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + pair lastProgress; + std::map>::iterator iterFind = + fileFTPProgressList.find(itemName); + if (iterFind == fileFTPProgressList.end()) { + iterFind = fileFTPProgressList.find( + GameConstants::saveNetworkGameFileServerCompressed); + if (iterFind == fileFTPProgressList.end()) { + iterFind = fileFTPProgressList.find( + GameConstants::saveNetworkGameFileClientCompressed); + } + } + if (iterFind != fileFTPProgressList.end()) { + lastProgress = iterFind->second; + fileFTPProgressList[iterFind->first] = + pair(fileProgress, stats->currentFilename); + } + safeMutexFTPProgress.ReleaseLock(); + + if (itemName != "" && (lastProgress.first / 25) < (fileProgress / 25)) { + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); - if(type == ftp_cct_DownloadProgress) { - FTPClientCallbackInterface::FtpProgressStats *stats = (FTPClientCallbackInterface::FtpProgressStats *)userdata; - if(stats != NULL) { - int fileProgress = 0; - if(stats->download_total > 0) { - fileProgress = ((stats->download_now / stats->download_total) * 100.0); - } - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Got FTP Callback for [%s] current file [%s] fileProgress = %d [now = %f, total = %f]\n",itemName.c_str(),stats->currentFilename.c_str(), fileProgress,stats->download_now,stats->download_total); - - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - pair lastProgress; - std::map >::iterator iterFind = fileFTPProgressList.find(itemName); - if(iterFind == fileFTPProgressList.end()) { - iterFind = fileFTPProgressList.find(GameConstants::saveNetworkGameFileServerCompressed); - if(iterFind == fileFTPProgressList.end()) { - iterFind = fileFTPProgressList.find(GameConstants::saveNetworkGameFileClientCompressed); - } - } - if(iterFind != fileFTPProgressList.end()) { - lastProgress = iterFind->second; - fileFTPProgressList[iterFind->first] = pair(fileProgress,stats->currentFilename); - } - safeMutexFTPProgress.ReleaseLock(); - - if(itemName != "" && (lastProgress.first / 25) < (fileProgress / 25)) { - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface* clientInterface= networkManager.getClientInterface(); - - Lang &lang= Lang::getInstance(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - char szMsg[8096]=""; - if(lang.hasString("FileDownloadProgress",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("FileDownloadProgress",languageList[i]).c_str(),getHumanPlayerName().c_str(),itemName.c_str(),fileProgress); - } - else { - snprintf(szMsg,8096,"Player: %s download progress for [%s] is %d %%",getHumanPlayerName().c_str(),itemName.c_str(),fileProgress); - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] szMsg [%s] lastProgress.first = %d, fileProgress = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,szMsg,lastProgress.first,fileProgress); - clientInterface->sendTextMessage(szMsg,-1, lang.isLanguageLocal(languageList[i]),languageList[i]); - } - sleep(1); - } + Lang &lang = Lang::getInstance(); + const vector languageList = + clientInterface->getGameSettings() + ->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + char szMsg[8096] = ""; + if (lang.hasString("FileDownloadProgress", languageList[i]) == true) { + snprintf( + szMsg, 8096, + lang.getString("FileDownloadProgress", languageList[i]).c_str(), + getHumanPlayerName().c_str(), itemName.c_str(), fileProgress); + } else { + snprintf( + szMsg, 8096, "Player: %s download progress for [%s] is %d %%", + getHumanPlayerName().c_str(), itemName.c_str(), fileProgress); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line %d] szMsg [%s] lastProgress.first = %d, " + "fileProgress = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, szMsg, lastProgress.first, fileProgress); + clientInterface->sendTextMessage( + szMsg, -1, lang.isLanguageLocal(languageList[i]), + languageList[i]); } + sleep(1); + } } - else if(type == ftp_cct_ExtractProgress) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Got FTP extract Callback for [%s] result = %d [%s]\n",itemName.c_str(),result.first,result.second.c_str()); - - if(userdata == NULL) { - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface* clientInterface= networkManager.getClientInterface(); - - Lang &lang= Lang::getInstance(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - char szMsg[8096]=""; - if(lang.hasString("DataMissingExtractDownload",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("DataMissingExtractDownload",languageList[i]).c_str(),getHumanPlayerName().c_str(),itemName.c_str()); - } - else { - snprintf(szMsg,8096,"Please wait, player: %s is extracting: %s",getHumanPlayerName().c_str(),itemName.c_str()); - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] szMsg [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,szMsg); - clientInterface->sendTextMessage(szMsg,-1, lang.isLanguageLocal(languageList[i]),languageList[i]); - } - sleep(1); - } - else { - char *szBuf = (char *)userdata; - //printf("%s\n",szBuf); - //console.addLine(szBuf); - console.addLine(szBuf, false,""); - } - } - else if(type == ftp_cct_Map) { - getMissingMapFromFTPServerInProgress = false; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Got FTP Callback for [%s] result = %d [%s]\n",itemName.c_str(),result.first,result.second.c_str()); - - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - fileFTPProgressList.erase(itemName); - safeMutexFTPProgress.ReleaseLock(); - - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface* clientInterface= networkManager.getClientInterface(); - const GameSettings *gameSettings = clientInterface->getGameSettings(); - - if(result.first == ftp_crt_SUCCESS) { - // Clear the CRC file Cache - string file = Config::getMapPath(itemName,"",false); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Got map itemName [%s] file [%s] lastCheckedCRCMapName [%s] gameSettings->getMap() [%s]\n", - itemName.c_str(),file.c_str(),lastCheckedCRCMapName.c_str(),gameSettings->getMap().c_str()); - - if(gameSettings != NULL && itemName == gameSettings->getMap() && - lastCheckedCRCMapName == gameSettings->getMap() && - gameSettings->getMap() != "") { - Checksum::clearFileCache(); - Checksum checksum; - - checksum.addFile(file); - lastCheckedCRCMapValue = checksum.getSum(); - } - - Lang &lang= Lang::getInstance(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - char szMsg[8096]=""; - if(lang.hasString("DataMissingMapSuccessDownload",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("DataMissingMapSuccessDownload",languageList[i]).c_str(),getHumanPlayerName().c_str(),itemName.c_str()); - } - else { - snprintf(szMsg,8096,"Player: %s SUCCESSFULLY downloaded the map: %s",getHumanPlayerName().c_str(),itemName.c_str()); - } - clientInterface->sendTextMessage(szMsg,-1, lang.isLanguageLocal(languageList[i]),languageList[i]); - } - sleep(1); + } else if (type == ftp_cct_ExtractProgress) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Got FTP extract Callback for [%s] result = %d [%s]\n", + itemName.c_str(), result.first, result.second.c_str()); + + if (userdata == NULL) { + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + + Lang &lang = Lang::getInstance(); + const vector languageList = + clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + char szMsg[8096] = ""; + if (lang.hasString("DataMissingExtractDownload", languageList[i]) == + true) { + snprintf(szMsg, 8096, + lang.getString("DataMissingExtractDownload", languageList[i]) + .c_str(), + getHumanPlayerName().c_str(), itemName.c_str()); + } else { + snprintf(szMsg, 8096, "Please wait, player: %s is extracting: %s", + getHumanPlayerName().c_str(), itemName.c_str()); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line %d] szMsg [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, szMsg); + clientInterface->sendTextMessage( + szMsg, -1, lang.isLanguageLocal(languageList[i]), languageList[i]); + } + sleep(1); + } else { + char *szBuf = (char *)userdata; + // printf("%s\n",szBuf); + // console.addLine(szBuf); + console.addLine(szBuf, false, ""); + } + } else if (type == ftp_cct_Map) { + getMissingMapFromFTPServerInProgress = false; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Got FTP Callback for [%s] result = %d [%s]\n", itemName.c_str(), + result.first, result.second.c_str()); + + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + fileFTPProgressList.erase(itemName); + safeMutexFTPProgress.ReleaseLock(); + + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + const GameSettings *gameSettings = clientInterface->getGameSettings(); + + if (result.first == ftp_crt_SUCCESS) { + // Clear the CRC file Cache + string file = Config::getMapPath(itemName, "", false); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Got map itemName [%s] file [%s] lastCheckedCRCMapName [%s] " + "gameSettings->getMap() [%s]\n", + itemName.c_str(), file.c_str(), lastCheckedCRCMapName.c_str(), + gameSettings->getMap().c_str()); + + if (gameSettings != NULL && itemName == gameSettings->getMap() && + lastCheckedCRCMapName == gameSettings->getMap() && + gameSettings->getMap() != "") { + Checksum::clearFileCache(); + Checksum checksum; + + checksum.addFile(file); + lastCheckedCRCMapValue = checksum.getSum(); + } + + Lang &lang = Lang::getInstance(); + const vector languageList = + clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + char szMsg[8096] = ""; + if (lang.hasString("DataMissingMapSuccessDownload", languageList[i]) == + true) { + snprintf( + szMsg, 8096, + lang.getString("DataMissingMapSuccessDownload", languageList[i]) + .c_str(), + getHumanPlayerName().c_str(), itemName.c_str()); + } else { + snprintf(szMsg, 8096, + "Player: %s SUCCESSFULLY downloaded the map: %s", + getHumanPlayerName().c_str(), itemName.c_str()); } - else { - printf("FAILED map itemName [%s] lastCheckedCRCMapName [%s] gameSettings->getMap() [%s]\n", - itemName.c_str(),lastCheckedCRCMapName.c_str(),gameSettings->getMap().c_str()); - - curl_version_info_data *curlVersion= curl_version_info(CURLVERSION_NOW); - - Lang &lang= Lang::getInstance(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - char szMsg[8096]=""; - if(lang.hasString("DataMissingMapFailDownload",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("DataMissingMapFailDownload",languageList[i]).c_str(),getHumanPlayerName().c_str(),itemName.c_str(),curlVersion->version); - } - else { - snprintf(szMsg,8096,"Player: %s FAILED to download the map: [%s] using CURL version [%s]",getHumanPlayerName().c_str(),itemName.c_str(),curlVersion->version); - } - clientInterface->sendTextMessage(szMsg,-1, lang.isLanguageLocal(languageList[i]),languageList[i]); - - if(result.first == ftp_crt_HOST_NOT_ACCEPTING) { - if(lang.hasString("HostNotAcceptingDataConnections",languageList[i]) == true) { - clientInterface->sendTextMessage(lang.getString("HostNotAcceptingDataConnections",languageList[i]),-1, lang.isLanguageLocal(languageList[i]),languageList[i]); - } - else { - clientInterface->sendTextMessage("*Warning* the host is not accepting data connections.",-1, lang.isLanguageLocal(languageList[i]),languageList[i]); - } - } - } - sleep(1); - - console.addLine(result.second,true); + clientInterface->sendTextMessage( + szMsg, -1, lang.isLanguageLocal(languageList[i]), languageList[i]); + } + sleep(1); + } else { + printf("FAILED map itemName [%s] lastCheckedCRCMapName [%s] " + "gameSettings->getMap() [%s]\n", + itemName.c_str(), lastCheckedCRCMapName.c_str(), + gameSettings->getMap().c_str()); + + curl_version_info_data *curlVersion = curl_version_info(CURLVERSION_NOW); + + Lang &lang = Lang::getInstance(); + const vector languageList = + clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + char szMsg[8096] = ""; + if (lang.hasString("DataMissingMapFailDownload", languageList[i]) == + true) { + snprintf(szMsg, 8096, + lang.getString("DataMissingMapFailDownload", languageList[i]) + .c_str(), + getHumanPlayerName().c_str(), itemName.c_str(), + curlVersion->version); + } else { + snprintf(szMsg, 8096, + "Player: %s FAILED to download the map: [%s] using CURL " + "version [%s]", + getHumanPlayerName().c_str(), itemName.c_str(), + curlVersion->version); } + clientInterface->sendTextMessage( + szMsg, -1, lang.isLanguageLocal(languageList[i]), languageList[i]); + + if (result.first == ftp_crt_HOST_NOT_ACCEPTING) { + if (lang.hasString("HostNotAcceptingDataConnections", + languageList[i]) == true) { + clientInterface->sendTextMessage( + lang.getString("HostNotAcceptingDataConnections", + languageList[i]), + -1, lang.isLanguageLocal(languageList[i]), languageList[i]); + } else { + clientInterface->sendTextMessage( + "*Warning* the host is not accepting data connections.", -1, + lang.isLanguageLocal(languageList[i]), languageList[i]); + } + } + } + sleep(1); + + console.addLine(result.second, true); } - else if(type == ftp_cct_Tileset) { - getMissingTilesetFromFTPServerInProgress = false; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Got FTP Callback for [%s] result = %d [%s]\n",itemName.c_str(),result.first,result.second.c_str()); + } else if (type == ftp_cct_Tileset) { + getMissingTilesetFromFTPServerInProgress = false; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Got FTP Callback for [%s] result = %d [%s]\n", itemName.c_str(), + result.first, result.second.c_str()); + + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + fileFTPProgressList.erase(itemName); + safeMutexFTPProgress.ReleaseLock(true); + + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + const GameSettings *gameSettings = clientInterface->getGameSettings(); + + if (result.first == ftp_crt_SUCCESS) { + + Lang &lang = Lang::getInstance(); + const vector languageList = + clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + char szMsg[8096] = ""; + if (lang.hasString("DataMissingTilesetSuccessDownload", + languageList[i]) == true) { + snprintf(szMsg, 8096, + lang.getString("DataMissingTilesetSuccessDownload", + languageList[i]) + .c_str(), + getHumanPlayerName().c_str(), itemName.c_str()); + } else { + snprintf(szMsg, 8096, + "Player: %s SUCCESSFULLY downloaded the tileset: %s", + getHumanPlayerName().c_str(), itemName.c_str()); + } + clientInterface->sendTextMessage( + szMsg, -1, lang.isLanguageLocal(languageList[i]), languageList[i]); + } + sleep(1); + + // START + // Clear the CRC Cache if it is populated + // + // Clear the CRC file Cache + safeMutexFTPProgress.Lock(); + Checksum::clearFileCache(); + + vector paths = + Config::getInstance().getPathListForType(ptTilesets); + string pathSearchString = string("/") + itemName + string("/*"); + const string filterFileExt = ".xml"; + clearFolderTreeContentsCheckSum(paths, pathSearchString, filterFileExt); + clearFolderTreeContentsCheckSumList(paths, pathSearchString, + filterFileExt); + + // Refresh CRC + + // printf("Got map itemName [%s] file [%s] lastCheckedCRCMapName [%s] + // gameSettings->getMap() [%s]\n", + // itemName.c_str(),file.c_str(),lastCheckedCRCMapName.c_str(),gameSettings->getMap().c_str()); + + if (gameSettings != NULL && itemName == gameSettings->getTileset() && + lastCheckedCRCTilesetName == gameSettings->getTileset() && + gameSettings->getTileset() != "") { + Config &config = Config::getInstance(); + lastCheckedCRCTilesetValue = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTilesets, ""), + string("/") + itemName + string("/*"), ".xml", NULL, true); + } + + safeMutexFTPProgress.ReleaseLock(); + // END + + // Reload tilesets for the UI + string scenarioDir = + Scenario::getScenarioDir(dirList, gameSettings->getScenario()); + findDirs( + Config::getInstance().getPathListForType(ptTilesets, scenarioDir), + tilesetFiles); + + std::vector tilesetsFormatted = tilesetFiles; + std::for_each(tilesetsFormatted.begin(), tilesetsFormatted.end(), + FormatString()); + listBoxTileset.setItems(tilesetsFormatted); + } else { + curl_version_info_data *curlVersion = curl_version_info(CURLVERSION_NOW); + + Lang &lang = Lang::getInstance(); + const vector languageList = + clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + char szMsg[8096] = ""; + if (lang.hasString("DataMissingTilesetFailDownload", languageList[i]) == + true) { + snprintf( + szMsg, 8096, + lang.getString("DataMissingTilesetFailDownload", languageList[i]) + .c_str(), + getHumanPlayerName().c_str(), (itemName + "(.7z)").c_str(), + curlVersion->version); + } else { + snprintf(szMsg, 8096, + "Player: %s FAILED to download the tileset: [%s] using CURL " + "version [%s]", + getHumanPlayerName().c_str(), (itemName + "(.7z)").c_str(), + curlVersion->version); + } + clientInterface->sendTextMessage( + szMsg, -1, lang.isLanguageLocal(languageList[i]), languageList[i]); + + if (result.first == ftp_crt_HOST_NOT_ACCEPTING) { + if (lang.hasString("HostNotAcceptingDataConnections", + languageList[i]) == true) { + clientInterface->sendTextMessage( + lang.getString("HostNotAcceptingDataConnections", + languageList[i]), + -1, lang.isLanguageLocal(languageList[i]), languageList[i]); + } else { + clientInterface->sendTextMessage( + "*Warning* the host is not accepting data connections.", -1, + lang.isLanguageLocal(languageList[i]), languageList[i]); + } + } + } + sleep(1); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - fileFTPProgressList.erase(itemName); - safeMutexFTPProgress.ReleaseLock(true); + console.addLine(result.second, true); + } + } else if (type == ftp_cct_Techtree) { + getMissingTechtreeFromFTPServerInProgress = false; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Got FTP Callback for [%s] result = %d [%s]\n", itemName.c_str(), + result.first, result.second.c_str()); + + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + fileFTPProgressList.erase(itemName); + safeMutexFTPProgress.ReleaseLock(true); + + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + const GameSettings *gameSettings = clientInterface->getGameSettings(); + + if (result.first == ftp_crt_SUCCESS) { + + Lang &lang = Lang::getInstance(); + const vector languageList = + clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + char szMsg[8096] = ""; + if (lang.hasString("DataMissingTechtreeSuccessDownload", + languageList[i]) == true) { + snprintf(szMsg, 8096, + lang.getString("DataMissingTechtreeSuccessDownload", + languageList[i]) + .c_str(), + getHumanPlayerName().c_str(), itemName.c_str()); + } else { + snprintf(szMsg, 8096, + "Player: %s SUCCESSFULLY downloaded the techtree: %s", + getHumanPlayerName().c_str(), itemName.c_str()); + } + clientInterface->sendTextMessage( + szMsg, -1, lang.isLanguageLocal(languageList[i]), languageList[i]); + } + sleep(1); + + // START + // Clear the CRC Cache if it is populated + // + // Clear the CRC file Cache + safeMutexFTPProgress.Lock(); + Checksum::clearFileCache(); + + vector paths = Config::getInstance().getPathListForType(ptTechs); + string pathSearchString = string("/") + itemName + string("/*"); + const string filterFileExt = ".xml"; + clearFolderTreeContentsCheckSum(paths, pathSearchString, filterFileExt); + clearFolderTreeContentsCheckSumList(paths, pathSearchString, + filterFileExt); + + // Refresh CRC + if (gameSettings != NULL && itemName == gameSettings->getTech() && + lastCheckedCRCTechtreeName == gameSettings->getTech() && + gameSettings->getTech() != "") { + Config &config = Config::getInstance(); + lastCheckedCRCTechtreeValue = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTechs, ""), + string("/") + itemName + string("/*"), ".xml", NULL, true); + } + safeMutexFTPProgress.ReleaseLock(); + // END + + // Reload techs for the UI + string scenarioDir = + Scenario::getScenarioDir(dirList, gameSettings->getScenario()); + findDirs(Config::getInstance().getPathListForType(ptTechs, scenarioDir), + techTreeFiles); + + vector translatedTechs; + std::vector techsFormatted = techTreeFiles; + for (int i = 0; i < (int)techsFormatted.size(); i++) { + techsFormatted.at(i) = formatString(techsFormatted.at(i)); + + string txTech = techTree->getTranslatedName(techTreeFiles.at(i), true); + translatedTechs.push_back(formatString(txTech)); + } + listBoxTechTree.setItems(techsFormatted, translatedTechs); + } else { + curl_version_info_data *curlVersion = curl_version_info(CURLVERSION_NOW); + + Lang &lang = Lang::getInstance(); + const vector languageList = + clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < (unsigned int)languageList.size(); ++i) { + char szMsg[8096] = ""; + if (lang.hasString("DataMissingTechtreeFailDownload", + languageList[i]) == true) { + snprintf( + szMsg, 8096, + lang.getString("DataMissingTechtreeFailDownload", languageList[i]) + .c_str(), + getHumanPlayerName().c_str(), (itemName + "(.7z)").c_str(), + curlVersion->version); + } else { + snprintf(szMsg, 8096, + "Player: %s FAILED to download the techtree: [%s] using " + "CURL version [%s]", + getHumanPlayerName().c_str(), (itemName + "(.7z)").c_str(), + curlVersion->version); + } + clientInterface->sendTextMessage( + szMsg, -1, lang.isLanguageLocal(languageList[i]), languageList[i]); + + if (result.first == ftp_crt_HOST_NOT_ACCEPTING) { + if (lang.hasString("HostNotAcceptingDataConnections", + languageList[i]) == true) { + clientInterface->sendTextMessage( + lang.getString("HostNotAcceptingDataConnections", + languageList[i]), + -1, lang.isLanguageLocal(languageList[i]), languageList[i]); + } else { + clientInterface->sendTextMessage( + "*Warning* the host is not accepting data connections.", -1, + lang.isLanguageLocal(languageList[i]), languageList[i]); + } + } + } + sleep(1); - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface* clientInterface= networkManager.getClientInterface(); - const GameSettings *gameSettings = clientInterface->getGameSettings(); + console.addLine(result.second, true); + } + } else if (type == ftp_cct_TempFile) { + getInProgressSavedGameFromFTPServerInProgress = false; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Got FTP Callback for [%s] result = %d [%s]\n", itemName.c_str(), + result.first, result.second.c_str()); + + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + // fileFTPProgressList.erase(itemName); + std::map>::iterator iterFind = + fileFTPProgressList.find(itemName); + if (iterFind == fileFTPProgressList.end()) { + iterFind = fileFTPProgressList.find( + GameConstants::saveNetworkGameFileServerCompressed); + if (iterFind == fileFTPProgressList.end()) { + iterFind = fileFTPProgressList.find( + GameConstants::saveNetworkGameFileClientCompressed); + } + } + if (iterFind != fileFTPProgressList.end()) { + fileFTPProgressList.erase(iterFind->first); + } + safeMutexFTPProgress.ReleaseLock(); + + // printf("Status update downloading saved game file: + // [%s]\n",itemName.c_str()); + + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + // const GameSettings *gameSettings = clientInterface->getGameSettings(); + + if (result.first == ftp_crt_SUCCESS) { + Lang &lang = Lang::getInstance(); + const vector languageList = + clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + char szMsg[8096] = ""; + if (lang.hasString("JoinPlayerToCurrentGameSuccessDownload", + languageList[i]) == true) { + snprintf(szMsg, 8096, + lang.getString("JoinPlayerToCurrentGameSuccessDownload", + languageList[i]) + .c_str(), + getHumanPlayerName().c_str(), itemName.c_str()); + } else { + snprintf(szMsg, 8096, + "Player: %s SUCCESSFULLY downloaded the saved game: %s", + getHumanPlayerName().c_str(), itemName.c_str()); + } + clientInterface->sendTextMessage( + szMsg, -1, lang.isLanguageLocal(languageList[i]), languageList[i]); + } + sleep(1); + + if (itemName == GameConstants::saveNetworkGameFileClientCompressed) { + string saveGameFilePath = "temp/"; + string saveGameFile = + saveGameFilePath + + string(GameConstants::saveNetworkGameFileClientCompressed); + if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != + "") { + saveGameFilePath = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + + saveGameFilePath; + saveGameFile = + saveGameFilePath + + string(GameConstants::saveNetworkGameFileClientCompressed); + } else { + string userData = + Config::getInstance().getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + saveGameFilePath = userData + saveGameFilePath; + saveGameFile = + saveGameFilePath + + string(GameConstants::saveNetworkGameFileClientCompressed); + } - if(result.first == ftp_crt_SUCCESS) { - - Lang &lang= Lang::getInstance(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - char szMsg[8096]=""; - if(lang.hasString("DataMissingTilesetSuccessDownload",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("DataMissingTilesetSuccessDownload",languageList[i]).c_str(),getHumanPlayerName().c_str(),itemName.c_str()); - } - else { - snprintf(szMsg,8096,"Player: %s SUCCESSFULLY downloaded the tileset: %s",getHumanPlayerName().c_str(),itemName.c_str()); - } - clientInterface->sendTextMessage(szMsg,-1, lang.isLanguageLocal(languageList[i]),languageList[i]); - } - sleep(1); - - // START - // Clear the CRC Cache if it is populated - // - // Clear the CRC file Cache - safeMutexFTPProgress.Lock(); - Checksum::clearFileCache(); - - vector paths = Config::getInstance().getPathListForType(ptTilesets); - string pathSearchString = string("/") + itemName + string("/*"); - const string filterFileExt = ".xml"; - clearFolderTreeContentsCheckSum(paths, pathSearchString, filterFileExt); - clearFolderTreeContentsCheckSumList(paths, pathSearchString, filterFileExt); - - // Refresh CRC - - //printf("Got map itemName [%s] file [%s] lastCheckedCRCMapName [%s] gameSettings->getMap() [%s]\n", - // itemName.c_str(),file.c_str(),lastCheckedCRCMapName.c_str(),gameSettings->getMap().c_str()); - - if(gameSettings != NULL && itemName == gameSettings->getTileset() && - lastCheckedCRCTilesetName == gameSettings->getTileset() && - gameSettings->getTileset() != "") { - Config &config = Config::getInstance(); - lastCheckedCRCTilesetValue = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTilesets,""), string("/") + itemName + string("/*"), ".xml", NULL, true); - } - - safeMutexFTPProgress.ReleaseLock(); - // END - - // Reload tilesets for the UI - string scenarioDir = Scenario::getScenarioDir(dirList, gameSettings->getScenario()); - findDirs(Config::getInstance().getPathListForType(ptTilesets,scenarioDir), tilesetFiles); - - std::vector tilesetsFormatted = tilesetFiles; - std::for_each(tilesetsFormatted.begin(), tilesetsFormatted.end(), FormatString()); - listBoxTileset.setItems(tilesetsFormatted); + string extractedFileName = + saveGameFilePath + string(GameConstants::saveNetworkGameFileClient); + bool extract_result = + extractFileFromZIPFile(saveGameFile, extractedFileName); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Saved game [%s] compressed to [%s] returned: %d\n", + saveGameFile.c_str(), extractedFileName.c_str(), + extract_result); + } + readyToJoinInProgressGame = true; + + // printf("Success downloading saved game file: [%s]\n",itemName.c_str()); + } else { + curl_version_info_data *curlVersion = curl_version_info(CURLVERSION_NOW); + + Lang &lang = Lang::getInstance(); + const vector languageList = + clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + char szMsg[8096] = ""; + if (lang.hasString("JoinPlayerToCurrentGameFailDownload", + languageList[i]) == true) { + snprintf(szMsg, 8096, + lang.getString("JoinPlayerToCurrentGameFailDownload", + languageList[i]) + .c_str(), + getHumanPlayerName().c_str(), itemName.c_str(), + curlVersion->version); + } else { + snprintf(szMsg, 8096, + "Player: %s FAILED to download the saved game: [%s] using " + "CURL version [%s]", + getHumanPlayerName().c_str(), itemName.c_str(), + curlVersion->version); } - else { - curl_version_info_data *curlVersion= curl_version_info(CURLVERSION_NOW); - - Lang &lang= Lang::getInstance(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - char szMsg[8096]=""; - if(lang.hasString("DataMissingTilesetFailDownload",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("DataMissingTilesetFailDownload",languageList[i]).c_str(),getHumanPlayerName().c_str(),(itemName+"(.7z)").c_str(),curlVersion->version); - } - else { - snprintf(szMsg,8096,"Player: %s FAILED to download the tileset: [%s] using CURL version [%s]",getHumanPlayerName().c_str(),(itemName+"(.7z)").c_str(),curlVersion->version); - } - clientInterface->sendTextMessage(szMsg,-1, lang.isLanguageLocal(languageList[i]),languageList[i]); - - if(result.first == ftp_crt_HOST_NOT_ACCEPTING) { - if(lang.hasString("HostNotAcceptingDataConnections",languageList[i]) == true) { - clientInterface->sendTextMessage(lang.getString("HostNotAcceptingDataConnections",languageList[i]),-1, lang.isLanguageLocal(languageList[i]),languageList[i]); - } - else { - clientInterface->sendTextMessage("*Warning* the host is not accepting data connections.",-1, lang.isLanguageLocal(languageList[i]),languageList[i]); - } - } - } - sleep(1); - - console.addLine(result.second,true); + clientInterface->sendTextMessage( + szMsg, -1, lang.isLanguageLocal(languageList[i]), languageList[i]); + + if (result.first == ftp_crt_HOST_NOT_ACCEPTING) { + if (lang.hasString("HostNotAcceptingDataConnections", + languageList[i]) == true) { + clientInterface->sendTextMessage( + lang.getString("HostNotAcceptingDataConnections", + languageList[i]), + -1, lang.isLanguageLocal(languageList[i]), languageList[i]); + } else { + clientInterface->sendTextMessage( + "*Warning* the host is not accepting data connections.", -1, + lang.isLanguageLocal(languageList[i]), languageList[i]); + } } + } + sleep(1); + + console.addLine(result.second, true); } - else if(type == ftp_cct_Techtree) { - getMissingTechtreeFromFTPServerInProgress = false; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Got FTP Callback for [%s] result = %d [%s]\n",itemName.c_str(),result.first,result.second.c_str()); + } +} - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - fileFTPProgressList.erase(itemName); - safeMutexFTPProgress.ReleaseLock(true); +void MenuStateConnectedGame::setupUIFromGameSettings(GameSettings *gameSettings, + bool errorOnMissingData) { + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface* clientInterface= networkManager.getClientInterface(); - const GameSettings *gameSettings = clientInterface->getGameSettings(); + updateDataSynchDetailText = true; + vector tilesets, techtree; - if(result.first == ftp_crt_SUCCESS) { - - Lang &lang= Lang::getInstance(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - char szMsg[8096]=""; - if(lang.hasString("DataMissingTechtreeSuccessDownload",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("DataMissingTechtreeSuccessDownload",languageList[i]).c_str(),getHumanPlayerName().c_str(),itemName.c_str()); - } - else { - snprintf(szMsg,8096,"Player: %s SUCCESSFULLY downloaded the techtree: %s",getHumanPlayerName().c_str(),itemName.c_str()); - } - clientInterface->sendTextMessage(szMsg,-1, lang.isLanguageLocal(languageList[i]),languageList[i]); - } - sleep(1); - - // START - // Clear the CRC Cache if it is populated - // - // Clear the CRC file Cache - safeMutexFTPProgress.Lock(); - Checksum::clearFileCache(); - - vector paths = Config::getInstance().getPathListForType(ptTechs); - string pathSearchString = string("/") + itemName + string("/*"); - const string filterFileExt = ".xml"; - clearFolderTreeContentsCheckSum(paths, pathSearchString, filterFileExt); - clearFolderTreeContentsCheckSumList(paths, pathSearchString, filterFileExt); - - // Refresh CRC - if(gameSettings != NULL && itemName == gameSettings->getTech() && - lastCheckedCRCTechtreeName == gameSettings->getTech() && - gameSettings->getTech() != "") { - Config &config = Config::getInstance(); - lastCheckedCRCTechtreeValue = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), string("/") + itemName + string("/*"), ".xml", NULL, true); - } - safeMutexFTPProgress.ReleaseLock(); - // END - - // Reload techs for the UI - string scenarioDir = Scenario::getScenarioDir(dirList, gameSettings->getScenario()); - findDirs(Config::getInstance().getPathListForType(ptTechs,scenarioDir), techTreeFiles); - - vector translatedTechs; - std::vector techsFormatted = techTreeFiles; - for(int i= 0; i < (int)techsFormatted.size(); i++){ - techsFormatted.at(i)= formatString(techsFormatted.at(i)); - - string txTech = techTree->getTranslatedName(techTreeFiles.at(i), true); - translatedTechs.push_back(formatString(txTech)); - } - listBoxTechTree.setItems(techsFormatted,translatedTechs); + if (gameSettings == NULL) { + throw megaglest_runtime_error("gameSettings == NULL"); + } + + checkBoxScenario.setValue((gameSettings->getScenario() != "")); + if (checkBoxScenario.getValue() == true) { + int originalFOWValue = listBoxFogOfWar.getSelectedItemIndex(); + + string scenario = gameSettings->getScenario(); + listBoxScenario.setSelectedItem(formatString(scenario)); + string file = Scenario::getScenarioPath(dirList, scenario); + + bool isTutorial = Scenario::isGameTutorial(file); + Scenario::loadScenarioInfo(file, &scenarioInfo, isTutorial); + + gameSettings->setScenarioDir( + Scenario::getScenarioPath(dirList, scenarioInfo.name)); + + gameSettings->setDefaultResources(scenarioInfo.defaultResources); + gameSettings->setDefaultUnits(scenarioInfo.defaultUnits); + gameSettings->setDefaultVictoryConditions( + scenarioInfo.defaultVictoryConditions); + + if (scenarioInfo.fogOfWar == false && + scenarioInfo.fogOfWar_exploredFlag == false) { + listBoxFogOfWar.setSelectedItemIndex(2); + } else if (scenarioInfo.fogOfWar_exploredFlag == true) { + listBoxFogOfWar.setSelectedItemIndex(1); + } else { + listBoxFogOfWar.setSelectedItemIndex(0); + } + + checkBoxAllowTeamUnitSharing.setValue(scenarioInfo.allowTeamUnitSharing); + checkBoxAllowTeamResourceSharing.setValue( + scenarioInfo.allowTeamResourceSharing); + + if (originalFOWValue != listBoxFogOfWar.getSelectedItemIndex()) { + cleanupMapPreviewTexture(); + } + } + + if (listBoxMapFilter.getSelectedItemIndex() != gameSettings->getMapFilter()) { + switchToMapGroup(gameSettings->getMapFilter()); + // printf("Switching to Map filter group %d + //\n",gameSettings->getMapFilter()); + } + + string scenarioDir = + Scenario::getScenarioDir(dirList, gameSettings->getScenario()); + setupMapList(gameSettings->getScenario()); + setupTechList(gameSettings->getScenario()); + setupTilesetList(gameSettings->getScenario()); + + // printf("A gameSettings->getTileset() + // [%s]\n",gameSettings->getTileset().c_str()); + + if (getMissingTilesetFromFTPServerInProgress == false && + gameSettings->getTileset() != "") { + // tileset + tilesets = tilesetFiles; + std::for_each(tilesets.begin(), tilesets.end(), FormatString()); + + if (std::find(tilesetFiles.begin(), tilesetFiles.end(), + gameSettings->getTileset()) != tilesetFiles.end()) { + lastMissingTileSet = ""; + getMissingTilesetFromFTPServer = ""; + listBoxTileset.setSelectedItem(formatString(gameSettings->getTileset())); + } else { + // try to get the tileset via ftp + if (ftpClientThread != NULL && + (getMissingTilesetFromFTPServer != gameSettings->getTileset() || + difftime(time(NULL), getMissingTilesetFromFTPServerLastPrompted) > + REPROMPT_DOWNLOAD_SECONDS)) { + if (ftpMessageBox.getEnabled() == false) { + getMissingTilesetFromFTPServerLastPrompted = time(NULL); + getMissingTilesetFromFTPServer = gameSettings->getTileset(); + Lang &lang = Lang::getInstance(); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "%s %s ?", + lang.getString("DownloadMissingTilesetQuestion").c_str(), + gameSettings->getTileset().c_str()); + + // Is the item in the mod center? + MutexSafeWrapper safeMutexThread( + (modHttpServerThread != NULL + ? modHttpServerThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + if (tilesetCacheList.find(getMissingTilesetFromFTPServer) == + tilesetCacheList.end()) { + ftpMessageBox.init(lang.getString("Yes"), + lang.getString("NoDownload")); + } else { + ftpMessageBox.init(lang.getString("ModCenter"), + lang.getString("GameHost")); + ftpMessageBox.addButton(lang.getString("NoDownload")); + } + safeMutexThread.ReleaseLock(); + + ftpMissingDataType = ftpmsg_MissingTileset; + showFTPMessageBox(szBuf, lang.getString("Question"), false); } - else { - curl_version_info_data *curlVersion= curl_version_info(CURLVERSION_NOW); - - Lang &lang= Lang::getInstance(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < (unsigned int)languageList.size(); ++i) { - char szMsg[8096]=""; - if(lang.hasString("DataMissingTechtreeFailDownload",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("DataMissingTechtreeFailDownload",languageList[i]).c_str(),getHumanPlayerName().c_str(),(itemName+"(.7z)").c_str(),curlVersion->version); - } - else { - snprintf(szMsg,8096,"Player: %s FAILED to download the techtree: [%s] using CURL version [%s]",getHumanPlayerName().c_str(),(itemName+"(.7z)").c_str(),curlVersion->version); - } - clientInterface->sendTextMessage(szMsg,-1, lang.isLanguageLocal(languageList[i]),languageList[i]); - - if(result.first == ftp_crt_HOST_NOT_ACCEPTING) { - if(lang.hasString("HostNotAcceptingDataConnections",languageList[i]) == true) { - clientInterface->sendTextMessage(lang.getString("HostNotAcceptingDataConnections",languageList[i]),-1, lang.isLanguageLocal(languageList[i]),languageList[i]); - } - else { - clientInterface->sendTextMessage("*Warning* the host is not accepting data connections.",-1, lang.isLanguageLocal(languageList[i]),languageList[i]); - } - } - } - sleep(1); - - console.addLine(result.second,true); + } + + tilesets.push_back( + Lang::getInstance().getString("DataMissing", "", true)); + + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + const GameSettings *gameSettings = clientInterface->getGameSettings(); + + if (lastMissingTileSet != gameSettings->getTileset()) { + lastMissingTileSet = gameSettings->getTileset(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + Lang &lang = Lang::getInstance(); + const vector languageList = + clientInterface->getGameSettings() + ->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + + char szMsg[8096] = ""; + if (lang.hasString("DataMissingTileset", languageList[i]) == true) { + snprintf( + szMsg, 8096, + lang.getString("DataMissingTileset", languageList[i]).c_str(), + getHumanPlayerName().c_str(), + gameSettings->getTileset().c_str()); + } else { + snprintf(szMsg, 8096, "Player: %s is missing the tileset: %s", + getHumanPlayerName().c_str(), + gameSettings->getTileset().c_str()); + } + clientInterface->sendTextMessage( + szMsg, -1, lang.isLanguageLocal(languageList[i]), + languageList[i]); } + } + + listBoxTileset.setItems(tilesets); + listBoxTileset.setSelectedItem( + Lang::getInstance().getString("DataMissing", "", true)); } - else if(type == ftp_cct_TempFile) { - getInProgressSavedGameFromFTPServerInProgress = false; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Got FTP Callback for [%s] result = %d [%s]\n",itemName.c_str(),result.first,result.second.c_str()); - - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - //fileFTPProgressList.erase(itemName); - std::map >::iterator iterFind = fileFTPProgressList.find(itemName); - if(iterFind == fileFTPProgressList.end()) { - iterFind = fileFTPProgressList.find(GameConstants::saveNetworkGameFileServerCompressed); - if(iterFind == fileFTPProgressList.end()) { - iterFind = fileFTPProgressList.find(GameConstants::saveNetworkGameFileClientCompressed); - } + } + + if (getMissingTechtreeFromFTPServerInProgress == false && + gameSettings->getTech() != "") { + // techtree + techtree = techTreeFiles; + std::for_each(techtree.begin(), techtree.end(), FormatString()); + + if (std::find(techTreeFiles.begin(), techTreeFiles.end(), + gameSettings->getTech()) != techTreeFiles.end()) { + + lastMissingTechtree = ""; + getMissingTechtreeFromFTPServer = ""; + reloadFactions(true, gameSettings->getScenario()); + listBoxTechTree.setSelectedItem(formatString(gameSettings->getTech())); + } else { + // try to get the tileset via ftp + if (ftpClientThread != NULL && + (getMissingTechtreeFromFTPServer != gameSettings->getTech() || + difftime(time(NULL), getMissingTechtreeFromFTPServerLastPrompted) > + REPROMPT_DOWNLOAD_SECONDS)) { + if (ftpMessageBox.getEnabled() == false) { + getMissingTechtreeFromFTPServerLastPrompted = time(NULL); + getMissingTechtreeFromFTPServer = gameSettings->getTech(); + Lang &lang = Lang::getInstance(); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "%s %s ?", + lang.getString("DownloadMissingTechtreeQuestion").c_str(), + gameSettings->getTech().c_str()); + + // Is the item in the mod center? + MutexSafeWrapper safeMutexThread( + (modHttpServerThread != NULL + ? modHttpServerThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + if (techCacheList.find(getMissingTechtreeFromFTPServer) == + techCacheList.end()) { + ftpMessageBox.init(lang.getString("Yes"), + lang.getString("NoDownload")); + } else { + ftpMessageBox.init(lang.getString("ModCenter"), + lang.getString("GameHost")); + ftpMessageBox.addButton(lang.getString("NoDownload")); + } + safeMutexThread.ReleaseLock(); + + ftpMissingDataType = ftpmsg_MissingTechtree; + showFTPMessageBox(szBuf, lang.getString("Question"), false); } - if(iterFind != fileFTPProgressList.end()) { - fileFTPProgressList.erase(iterFind->first); + } + + techtree.push_back( + Lang::getInstance().getString("DataMissing", "", true)); + + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + const GameSettings *gameSettings = clientInterface->getGameSettings(); + + if (lastMissingTechtree != gameSettings->getTech()) { + lastMissingTechtree = gameSettings->getTech(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + Lang &lang = Lang::getInstance(); + const vector languageList = + clientInterface->getGameSettings() + ->getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + + char szMsg[8096] = ""; + if (lang.hasString("DataMissingTechtree", languageList[i]) == true) { + snprintf( + szMsg, 8096, + lang.getString("DataMissingTechtree", languageList[i]).c_str(), + getHumanPlayerName().c_str(), gameSettings->getTech().c_str()); + } else { + snprintf(szMsg, 8096, "Player: %s is missing the techtree: %s", + getHumanPlayerName().c_str(), + gameSettings->getTech().c_str()); + } + clientInterface->sendTextMessage( + szMsg, -1, lang.isLanguageLocal(languageList[i]), + languageList[i]); } - safeMutexFTPProgress.ReleaseLock(); + } + + vector translatedTechs; + for (unsigned int i = 0; i < techTreeFiles.size(); i++) { + string txTech = techTree->getTranslatedName(techTreeFiles.at(i)); + translatedTechs.push_back(txTech); + } + listBoxTechTree.setItems(techtree, translatedTechs); + listBoxTechTree.setSelectedItem( + Lang::getInstance().getString("DataMissing", "", true)); + } + } + + // factions + bool hasFactions = true; + if (currentFactionName != gameSettings->getTech() && + gameSettings->getTech() != "") { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] hasFactions = %d, currentFactionName [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, hasFactions, currentFactionName.c_str()); + currentFactionName = gameSettings->getTech(); + hasFactions = loadFactions(gameSettings, false); + } else { + // do this to process special faction types like observers + loadFactions(gameSettings, false); + } + + if (getMissingMapFromFTPServerInProgress == false && + gameSettings->getMap() != "" && + gameSettings->getMapFilter() == listBoxMapFilter.getSelectedItemIndex()) { + // map + bool missingMap = false; + string mapFile = gameSettings->getMap(); + mapFile = formatString(mapFile); + + if (currentMap != gameSettings->getMap()) { // load the setup again + currentMap = gameSettings->getMap(); + } + bool mapLoaded = + loadMapInfo(Config::getMapPath(currentMap, scenarioDir, false), + &mapInfo, true, true); + if (mapLoaded == false) { + // try to get the map via ftp + if (ftpClientThread != NULL && + (getMissingMapFromFTPServer != currentMap || + difftime(time(NULL), getMissingMapFromFTPServerLastPrompted) > + REPROMPT_DOWNLOAD_SECONDS)) { + if (ftpMessageBox.getEnabled() == false) { + getMissingMapFromFTPServerLastPrompted = time(NULL); + getMissingMapFromFTPServer = currentMap; + Lang &lang = Lang::getInstance(); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "%s %s ?", + lang.getString("DownloadMissingMapQuestion").c_str(), + currentMap.c_str()); + + // Is the item in the mod center? + MutexSafeWrapper safeMutexThread( + (modHttpServerThread != NULL + ? modHttpServerThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + if (mapCacheList.find(getMissingMapFromFTPServer) == + mapCacheList.end()) { + ftpMessageBox.init(lang.getString("Yes"), + lang.getString("NoDownload")); + } else { + ftpMessageBox.init(lang.getString("ModCenter"), + lang.getString("GameHost")); + ftpMessageBox.addButton(lang.getString("NoDownload")); + } + safeMutexThread.ReleaseLock(); + + ftpMissingDataType = ftpmsg_MissingMap; + showFTPMessageBox(szBuf, lang.getString("Question"), false); + } + } + + formattedPlayerSortedMaps[gameSettings->getMapFilter()].push_back( + Lang::getInstance().getString("DataMissing", "", true)); + mapFile = Lang::getInstance().getString("DataMissing", "", true); + missingMap = true; + } + + if (isHeadlessAdmin() && !missingMap && + mapFile != comboBoxMap.getSelectedItem()) { + // console.addLine("Headless server does not have map, switching to next + // one"); + if (isfirstSwitchingMapMessage) { + isfirstSwitchingMapMessage = false; + } else { + console.addLine(Lang::getInstance().getString( + "HeadlessServerDoesNotHaveMap", "", true)); + } + } + comboBoxMap.setItems( + formattedPlayerSortedMaps[gameSettings->getMapFilter()]); + + // printf("Setting map from game settings map:%s , settingsfilter=%d , + // boxfilter=%d + // \n",gameSettings->getMap().c_str(),gameSettings->getMapFilter(),listBoxMapFilter.getSelectedItemIndex()); + comboBoxMap.setSelectedItem(mapFile); + labelMapInfo.setText(mapInfo.desc); + } + + // FogOfWar + if (checkBoxScenario.getValue() == false) { + int originalFOWValue = listBoxFogOfWar.getSelectedItemIndex(); + listBoxFogOfWar.setSelectedItemIndex(0); // default is 0! + if (gameSettings->getFogOfWar() == false) { + listBoxFogOfWar.setSelectedItemIndex(2); + } + if ((gameSettings->getFlagTypes1() & ft1_show_map_resources) == + ft1_show_map_resources) { + if (gameSettings->getFogOfWar() == true) { + listBoxFogOfWar.setSelectedItemIndex(1); + } + } + if (originalFOWValue != listBoxFogOfWar.getSelectedItemIndex()) { + cleanupMapPreviewTexture(); + } + } + + // Allow Observers + if (gameSettings->getAllowObservers()) { + checkBoxAllowObservers.setValue(true); + } else { + checkBoxAllowObservers.setValue(false); + } + + if ((gameSettings->getFlagTypes1() & ft1_allow_team_switching) == + ft1_allow_team_switching) { + checkBoxEnableSwitchTeamMode.setValue(true); + } else { + checkBoxEnableSwitchTeamMode.setValue(false); + } + listBoxAISwitchTeamAcceptPercent.setSelectedItem( + intToStr(gameSettings->getAiAcceptSwitchTeamPercentChance())); + listBoxFallbackCpuMultiplier.setSelectedItemIndex( + gameSettings->getFallbackCpuMultiplier()); + + if ((gameSettings->getFlagTypes1() & ft1_allow_shared_team_units) == + ft1_allow_shared_team_units) { + checkBoxAllowTeamUnitSharing.setValue(true); + } else { + checkBoxAllowTeamUnitSharing.setValue(false); + } + + if ((gameSettings->getFlagTypes1() & ft1_allow_shared_team_resources) == + ft1_allow_shared_team_resources) { + checkBoxAllowTeamResourceSharing.setValue(true); + } else { + checkBoxAllowTeamResourceSharing.setValue(false); + } + + checkBoxAllowNativeLanguageTechtree.setValue( + gameSettings->getNetworkAllowNativeLanguageTechtree()); + + // Control + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + listBoxControls[i].setSelectedItemIndex(ctClosed); + + if (isHeadlessAdmin() == false) { + if (clientInterface->getJoinGameInProgress() == false) { + listBoxFactions[i].setEditable(false); + listBoxTeams[i].setEditable(false); + } + } - //printf("Status update downloading saved game file: [%s]\n",itemName.c_str()); - - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface* clientInterface= networkManager.getClientInterface(); - //const GameSettings *gameSettings = clientInterface->getGameSettings(); - - if(result.first == ftp_crt_SUCCESS) { - Lang &lang= Lang::getInstance(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - char szMsg[8096]=""; - if(lang.hasString("JoinPlayerToCurrentGameSuccessDownload",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("JoinPlayerToCurrentGameSuccessDownload",languageList[i]).c_str(),getHumanPlayerName().c_str(),itemName.c_str()); - } - else { - snprintf(szMsg,8096,"Player: %s SUCCESSFULLY downloaded the saved game: %s",getHumanPlayerName().c_str(),itemName.c_str()); - } - clientInterface->sendTextMessage(szMsg,-1, lang.isLanguageLocal(languageList[i]),languageList[i]); - } - sleep(1); - - if(itemName == GameConstants::saveNetworkGameFileClientCompressed) { - string saveGameFilePath = "temp/"; - string saveGameFile = saveGameFilePath + string(GameConstants::saveNetworkGameFileClientCompressed); - if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - saveGameFilePath = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + saveGameFilePath; - saveGameFile = saveGameFilePath + string(GameConstants::saveNetworkGameFileClientCompressed); - } - else { - string userData = Config::getInstance().getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - saveGameFilePath = userData + saveGameFilePath; - saveGameFile = saveGameFilePath + string(GameConstants::saveNetworkGameFileClientCompressed); - } - - string extractedFileName = saveGameFilePath + string(GameConstants::saveNetworkGameFileClient); - bool extract_result = extractFileFromZIPFile(saveGameFile,extractedFileName); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Saved game [%s] compressed to [%s] returned: %d\n",saveGameFile.c_str(),extractedFileName.c_str(), extract_result); - } - readyToJoinInProgressGame = true; - - //printf("Success downloading saved game file: [%s]\n",itemName.c_str()); + labelPlayerStatus[i].setTexture(NULL); + ; + } + + if (hasFactions == true && gameSettings != NULL) { + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + + // for(int i=0; i < gameSettings->getFactionCount(); ++i){ + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + int slot = gameSettings->getStartLocationIndex(i); + + if (slot == clientInterface->getPlayerIndex()) { + labelPlayerNames[slot].setEditable(true); + } else { + labelPlayerNames[slot].setEditable(false); + } + + if (i >= mapInfo.players) { + if (gameSettings->getFactionControl(i) != ctNetworkUnassigned) { + continue; + } else if (clientInterface->getPlayerIndex() != slot) { + continue; + } + } + + if (gameSettings->getFactionControl(i) == ctNetwork || + gameSettings->getFactionControl(i) == ctNetworkUnassigned || + gameSettings->getFactionControl(i) == ctHuman) { + switch (gameSettings->getNetworkPlayerStatuses(i)) { + case npst_BeRightBack: + labelPlayerStatus[slot].setTexture( + CoreData::getInstance().getStatusBRBTexture()); + break; + case npst_Ready: + labelPlayerStatus[slot].setTexture( + CoreData::getInstance().getStatusReadyTexture()); + break; + case npst_PickSettings: + labelPlayerStatus[slot].setTexture( + CoreData::getInstance().getStatusNotReadyTexture()); + break; + case npst_Disconnected: + labelPlayerStatus[slot].setTexture(NULL); + break; + + default: + labelPlayerStatus[slot].setTexture(NULL); + break; + } + } + + listBoxControls[slot].setSelectedItemIndex( + gameSettings->getFactionControl(i), errorOnMissingData); + listBoxRMultiplier[slot].setSelectedItemIndex( + gameSettings->getResourceMultiplierIndex(i), errorOnMissingData); + listBoxTeams[slot].setSelectedItemIndex(gameSettings->getTeam(i), + errorOnMissingData); + listBoxFactions[slot].setSelectedItem( + formatString(gameSettings->getFactionTypeName(i)), false); + + if (gameSettings->getFactionControl(i) == ctNetwork || + gameSettings->getFactionControl(i) == ctNetworkUnassigned) { + labelNetStatus[slot].setText(gameSettings->getNetworkPlayerName(i)); + if (gameSettings->getThisFactionIndex() != i && + gameSettings->getNetworkPlayerName(i) != "" && + gameSettings->getNetworkPlayerName(i) != + GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME) { + labelPlayerNames[slot].setText(gameSettings->getNetworkPlayerName(i)); } - else { - curl_version_info_data *curlVersion= curl_version_info(CURLVERSION_NOW); - - Lang &lang= Lang::getInstance(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - char szMsg[8096]=""; - if(lang.hasString("JoinPlayerToCurrentGameFailDownload",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("JoinPlayerToCurrentGameFailDownload",languageList[i]).c_str(),getHumanPlayerName().c_str(),itemName.c_str(),curlVersion->version); - } - else { - snprintf(szMsg,8096,"Player: %s FAILED to download the saved game: [%s] using CURL version [%s]",getHumanPlayerName().c_str(),itemName.c_str(),curlVersion->version); - } - clientInterface->sendTextMessage(szMsg,-1, lang.isLanguageLocal(languageList[i]),languageList[i]); - - if(result.first == ftp_crt_HOST_NOT_ACCEPTING) { - if(lang.hasString("HostNotAcceptingDataConnections",languageList[i]) == true) { - clientInterface->sendTextMessage(lang.getString("HostNotAcceptingDataConnections",languageList[i]),-1, lang.isLanguageLocal(languageList[i]),languageList[i]); - } - else { - clientInterface->sendTextMessage("*Warning* the host is not accepting data connections.",-1, lang.isLanguageLocal(languageList[i]),languageList[i]); - } - } - } - sleep(1); - - console.addLine(result.second,true); + } + + ControlType ct = gameSettings->getFactionControl(i); + if (ct == ctHuman || ct == ctNetwork || ct == ctClosed) { + listBoxRMultiplier[slot].setEnabled(false); + listBoxRMultiplier[slot].setVisible(false); + } else { + listBoxRMultiplier[slot].setEnabled(true); + listBoxRMultiplier[slot].setVisible(true); + } + + if ((gameSettings->getFactionControl(i) == ctNetwork || + gameSettings->getFactionControl(i) == ctNetworkUnassigned) && + gameSettings->getThisFactionIndex() == i) { + + // set my current slot to ctHuman + if (gameSettings->getFactionControl(i) != ctNetworkUnassigned) { + listBoxControls[slot].setSelectedItemIndex(ctHuman); } + if (checkBoxScenario.getValue() == false) { + if (clientInterface->getJoinGameInProgress() == false) { + listBoxFactions[slot].setEditable(true); + listBoxTeams[slot].setEditable(true); + } + } + + if (labelPlayerNames[slot].getText() == "" && + gameSettings->getNetworkPlayerName(i) != "" && + gameSettings->getNetworkPlayerName(i) != + GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME) { + labelPlayerNames[slot].setText(gameSettings->getNetworkPlayerName(i)); + } + } } -} + settingsReceivedFromServer = true; + initialSettingsReceivedFromServer = true; -void MenuStateConnectedGame::setupUIFromGameSettings(GameSettings *gameSettings, bool errorOnMissingData) { - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface *clientInterface = networkManager.getClientInterface(); - - updateDataSynchDetailText = true; - vector tilesets,techtree; - - if(gameSettings == NULL) { - throw megaglest_runtime_error("gameSettings == NULL"); - } - - - checkBoxScenario.setValue((gameSettings->getScenario() != "")); - if(checkBoxScenario.getValue() == true) { - int originalFOWValue = listBoxFogOfWar.getSelectedItemIndex(); - - string scenario = gameSettings->getScenario(); - listBoxScenario.setSelectedItem(formatString(scenario)); - string file = Scenario::getScenarioPath(dirList, scenario); - - bool isTutorial = Scenario::isGameTutorial(file); - Scenario::loadScenarioInfo(file, &scenarioInfo, isTutorial); - - gameSettings->setScenarioDir(Scenario::getScenarioPath(dirList, scenarioInfo.name)); - - gameSettings->setDefaultResources(scenarioInfo.defaultResources); - gameSettings->setDefaultUnits(scenarioInfo.defaultUnits); - gameSettings->setDefaultVictoryConditions(scenarioInfo.defaultVictoryConditions); - - if(scenarioInfo.fogOfWar == false && scenarioInfo.fogOfWar_exploredFlag == false) { - listBoxFogOfWar.setSelectedItemIndex(2); - } - else if(scenarioInfo.fogOfWar_exploredFlag == true) { - listBoxFogOfWar.setSelectedItemIndex(1); - } - else { - listBoxFogOfWar.setSelectedItemIndex(0); - } - - checkBoxAllowTeamUnitSharing.setValue(scenarioInfo.allowTeamUnitSharing); - checkBoxAllowTeamResourceSharing.setValue(scenarioInfo.allowTeamResourceSharing); - - if(originalFOWValue != listBoxFogOfWar.getSelectedItemIndex()) { - cleanupMapPreviewTexture(); - } - } - - if( listBoxMapFilter.getSelectedItemIndex()!=gameSettings->getMapFilter()){ - switchToMapGroup(gameSettings->getMapFilter()); -// printf("Switching to Map filter group %d \n",gameSettings->getMapFilter()); - } - - string scenarioDir = Scenario::getScenarioDir(dirList, gameSettings->getScenario()); - setupMapList(gameSettings->getScenario()); - setupTechList(gameSettings->getScenario()); - setupTilesetList(gameSettings->getScenario()); - - - //printf("A gameSettings->getTileset() [%s]\n",gameSettings->getTileset().c_str()); - - if ( getMissingTilesetFromFTPServerInProgress == false - && gameSettings->getTileset() != "") { - // tileset - tilesets = tilesetFiles; - std::for_each(tilesets.begin(), tilesets.end(), FormatString()); - - if(std::find(tilesetFiles.begin(),tilesetFiles.end(),gameSettings->getTileset()) != tilesetFiles.end()) { - lastMissingTileSet = ""; - getMissingTilesetFromFTPServer = ""; - listBoxTileset.setSelectedItem(formatString(gameSettings->getTileset())); - } - else { - // try to get the tileset via ftp - if(ftpClientThread != NULL && - (getMissingTilesetFromFTPServer != gameSettings->getTileset() || - difftime(time(NULL),getMissingTilesetFromFTPServerLastPrompted) > REPROMPT_DOWNLOAD_SECONDS)) { - if(ftpMessageBox.getEnabled() == false) { - getMissingTilesetFromFTPServerLastPrompted = time(NULL); - getMissingTilesetFromFTPServer = gameSettings->getTileset(); - Lang &lang= Lang::getInstance(); - - char szBuf[8096]=""; - snprintf(szBuf,8096,"%s %s ?",lang.getString("DownloadMissingTilesetQuestion").c_str(),gameSettings->getTileset().c_str()); - - // Is the item in the mod center? - MutexSafeWrapper safeMutexThread((modHttpServerThread != NULL ? modHttpServerThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - if(tilesetCacheList.find(getMissingTilesetFromFTPServer) == tilesetCacheList.end()) { - ftpMessageBox.init(lang.getString("Yes"),lang.getString("NoDownload")); - } - else { - ftpMessageBox.init(lang.getString("ModCenter"),lang.getString("GameHost")); - ftpMessageBox.addButton(lang.getString("NoDownload")); - } - safeMutexThread.ReleaseLock(); - - ftpMissingDataType = ftpmsg_MissingTileset; - showFTPMessageBox(szBuf, lang.getString("Question"), false); - } - } - - tilesets.push_back(Lang::getInstance().getString("DataMissing","",true)); - - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface* clientInterface= networkManager.getClientInterface(); - const GameSettings *gameSettings = clientInterface->getGameSettings(); - - if(lastMissingTileSet != gameSettings->getTileset()) { - lastMissingTileSet = gameSettings->getTileset(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - Lang &lang= Lang::getInstance(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - - char szMsg[8096]=""; - if(lang.hasString("DataMissingTileset",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("DataMissingTileset",languageList[i]).c_str(),getHumanPlayerName().c_str(),gameSettings->getTileset().c_str()); - } - else { - snprintf(szMsg,8096,"Player: %s is missing the tileset: %s",getHumanPlayerName().c_str(),gameSettings->getTileset().c_str()); - } - clientInterface->sendTextMessage(szMsg,-1, lang.isLanguageLocal(languageList[i]),languageList[i]); - } - } - - listBoxTileset.setItems(tilesets); - listBoxTileset.setSelectedItem(Lang::getInstance().getString("DataMissing","",true)); - } - - } - - if(getMissingTechtreeFromFTPServerInProgress == false && - gameSettings->getTech() != "") { - // techtree - techtree = techTreeFiles; - std::for_each(techtree.begin(), techtree.end(), FormatString()); - - if(std::find(techTreeFiles.begin(),techTreeFiles.end(),gameSettings->getTech()) != techTreeFiles.end()) { - - lastMissingTechtree = ""; - getMissingTechtreeFromFTPServer = ""; - reloadFactions(true,gameSettings->getScenario()); - listBoxTechTree.setSelectedItem(formatString(gameSettings->getTech())); - } - else { - // try to get the tileset via ftp - if(ftpClientThread != NULL && (getMissingTechtreeFromFTPServer != gameSettings->getTech() || - difftime(time(NULL),getMissingTechtreeFromFTPServerLastPrompted) > REPROMPT_DOWNLOAD_SECONDS)) { - if(ftpMessageBox.getEnabled() == false) { - getMissingTechtreeFromFTPServerLastPrompted = time(NULL); - getMissingTechtreeFromFTPServer = gameSettings->getTech(); - Lang &lang= Lang::getInstance(); - - char szBuf[8096]=""; - snprintf(szBuf,8096,"%s %s ?",lang.getString("DownloadMissingTechtreeQuestion").c_str(),gameSettings->getTech().c_str()); - - // Is the item in the mod center? - MutexSafeWrapper safeMutexThread((modHttpServerThread != NULL ? modHttpServerThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - if(techCacheList.find(getMissingTechtreeFromFTPServer) == techCacheList.end()) { - ftpMessageBox.init(lang.getString("Yes"),lang.getString("NoDownload")); - } - else { - ftpMessageBox.init(lang.getString("ModCenter"),lang.getString("GameHost")); - ftpMessageBox.addButton(lang.getString("NoDownload")); - } - safeMutexThread.ReleaseLock(); - - ftpMissingDataType = ftpmsg_MissingTechtree; - showFTPMessageBox(szBuf, lang.getString("Question"), false); - } - } - - techtree.push_back(Lang::getInstance().getString("DataMissing","",true)); - - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface* clientInterface= networkManager.getClientInterface(); - const GameSettings *gameSettings = clientInterface->getGameSettings(); - - if(lastMissingTechtree != gameSettings->getTech()) { - lastMissingTechtree = gameSettings->getTech(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - Lang &lang= Lang::getInstance(); - const vector languageList = clientInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - - char szMsg[8096]=""; - if(lang.hasString("DataMissingTechtree",languageList[i]) == true) { - snprintf(szMsg,8096,lang.getString("DataMissingTechtree",languageList[i]).c_str(),getHumanPlayerName().c_str(),gameSettings->getTech().c_str()); - } - else { - snprintf(szMsg,8096,"Player: %s is missing the techtree: %s",getHumanPlayerName().c_str(),gameSettings->getTech().c_str()); - } - clientInterface->sendTextMessage(szMsg,-1, lang.isLanguageLocal(languageList[i]),languageList[i]); - } - } - - vector translatedTechs; - for(unsigned int i= 0; i < techTreeFiles.size(); i++) { - string txTech = techTree->getTranslatedName(techTreeFiles.at(i)); - translatedTechs.push_back(txTech); - } - listBoxTechTree.setItems(techtree,translatedTechs); - listBoxTechTree.setSelectedItem(Lang::getInstance().getString("DataMissing","",true)); - } - } - - // factions - bool hasFactions = true; - if(currentFactionName != gameSettings->getTech() && gameSettings->getTech() != "") { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] hasFactions = %d, currentFactionName [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,hasFactions,currentFactionName.c_str()); - currentFactionName = gameSettings->getTech(); - hasFactions = loadFactions(gameSettings,false); - } - else { - // do this to process special faction types like observers - loadFactions(gameSettings,false); - } - - - if(getMissingMapFromFTPServerInProgress == false && - gameSettings->getMap() != "" && gameSettings->getMapFilter()==listBoxMapFilter.getSelectedItemIndex()) - { - // map - bool missingMap=false; - string mapFile = gameSettings->getMap(); - mapFile = formatString(mapFile); - - if(currentMap != gameSettings->getMap()) {// load the setup again - currentMap = gameSettings->getMap(); - } - bool mapLoaded = loadMapInfo(Config::getMapPath(currentMap,scenarioDir,false), &mapInfo, true,true); - if(mapLoaded == false) { - // try to get the map via ftp - if(ftpClientThread != NULL && (getMissingMapFromFTPServer != currentMap || - difftime(time(NULL),getMissingMapFromFTPServerLastPrompted) > REPROMPT_DOWNLOAD_SECONDS)) { - if(ftpMessageBox.getEnabled() == false) { - getMissingMapFromFTPServerLastPrompted = time(NULL); - getMissingMapFromFTPServer = currentMap; - Lang &lang= Lang::getInstance(); - - char szBuf[8096]=""; - snprintf(szBuf,8096,"%s %s ?",lang.getString("DownloadMissingMapQuestion").c_str(),currentMap.c_str()); - - // Is the item in the mod center? - MutexSafeWrapper safeMutexThread((modHttpServerThread != NULL ? modHttpServerThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - if(mapCacheList.find(getMissingMapFromFTPServer) == mapCacheList.end()) { - ftpMessageBox.init(lang.getString("Yes"),lang.getString("NoDownload")); - } - else { - ftpMessageBox.init(lang.getString("ModCenter"),lang.getString("GameHost")); - ftpMessageBox.addButton(lang.getString("NoDownload")); - } - safeMutexThread.ReleaseLock(); - - ftpMissingDataType = ftpmsg_MissingMap; - showFTPMessageBox(szBuf, lang.getString("Question"), false); - } - } - - formattedPlayerSortedMaps[gameSettings->getMapFilter()].push_back(Lang::getInstance().getString("DataMissing","",true)); - mapFile = Lang::getInstance().getString("DataMissing","",true); - missingMap=true; - } - - if( isHeadlessAdmin() && !missingMap && mapFile!=comboBoxMap.getSelectedItem()){ - //console.addLine("Headless server does not have map, switching to next one"); - if(isfirstSwitchingMapMessage){ - isfirstSwitchingMapMessage=false; - }else{ - console.addLine(Lang::getInstance().getString("HeadlessServerDoesNotHaveMap","",true)); - } - } - comboBoxMap.setItems(formattedPlayerSortedMaps[gameSettings->getMapFilter()]); - - //printf("Setting map from game settings map:%s , settingsfilter=%d , boxfilter=%d \n",gameSettings->getMap().c_str(),gameSettings->getMapFilter(),listBoxMapFilter.getSelectedItemIndex()); - comboBoxMap.setSelectedItem(mapFile); - labelMapInfo.setText(mapInfo.desc); - } - - // FogOfWar - if(checkBoxScenario.getValue() == false) { - int originalFOWValue = listBoxFogOfWar.getSelectedItemIndex(); - listBoxFogOfWar.setSelectedItemIndex(0); // default is 0! - if(gameSettings->getFogOfWar() == false){ - listBoxFogOfWar.setSelectedItemIndex(2); - } - if((gameSettings->getFlagTypes1() & ft1_show_map_resources) == ft1_show_map_resources){ - if(gameSettings->getFogOfWar() == true){ - listBoxFogOfWar.setSelectedItemIndex(1); - } - } - if(originalFOWValue != listBoxFogOfWar.getSelectedItemIndex()) { - cleanupMapPreviewTexture(); - } - } - - // Allow Observers - if(gameSettings->getAllowObservers()) { - checkBoxAllowObservers.setValue(true); - } - else - { - checkBoxAllowObservers.setValue(false); - } - - if((gameSettings->getFlagTypes1() & ft1_allow_team_switching) == ft1_allow_team_switching){ - checkBoxEnableSwitchTeamMode.setValue(true); - } - else { - checkBoxEnableSwitchTeamMode.setValue(false); - } - listBoxAISwitchTeamAcceptPercent.setSelectedItem(intToStr(gameSettings->getAiAcceptSwitchTeamPercentChance())); - listBoxFallbackCpuMultiplier.setSelectedItemIndex(gameSettings->getFallbackCpuMultiplier()); - - if((gameSettings->getFlagTypes1() & ft1_allow_shared_team_units) == ft1_allow_shared_team_units) { - checkBoxAllowTeamUnitSharing.setValue(true); - } - else { - checkBoxAllowTeamUnitSharing.setValue(false); - } - - if((gameSettings->getFlagTypes1() & ft1_allow_shared_team_resources) == ft1_allow_shared_team_resources) { - checkBoxAllowTeamResourceSharing.setValue(true); - } - else { - checkBoxAllowTeamResourceSharing.setValue(false); - } - - checkBoxAllowNativeLanguageTechtree.setValue(gameSettings->getNetworkAllowNativeLanguageTechtree()); - - // Control - for(int i=0; igetJoinGameInProgress() == false) { - listBoxFactions[i].setEditable(false); - listBoxTeams[i].setEditable(false); - } - } - - labelPlayerStatus[i].setTexture(NULL);; - } - - if(hasFactions == true && gameSettings != NULL) { - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface *clientInterface = networkManager.getClientInterface(); - - //for(int i=0; i < gameSettings->getFactionCount(); ++i){ - for(int i=0; i < GameConstants::maxPlayers; ++i) { - int slot = gameSettings->getStartLocationIndex(i); - - if(slot == clientInterface->getPlayerIndex()){ - labelPlayerNames[slot].setEditable(true); - } - else { - labelPlayerNames[slot].setEditable(false); - } - - if(i >= mapInfo.players) { - if( gameSettings->getFactionControl(i) != ctNetworkUnassigned) { - continue; - } - else if(clientInterface->getPlayerIndex() != slot) { - continue; - } - } - - if( gameSettings->getFactionControl(i) == ctNetwork || - gameSettings->getFactionControl(i) == ctNetworkUnassigned || - gameSettings->getFactionControl(i) == ctHuman) { - switch(gameSettings->getNetworkPlayerStatuses(i)) { - case npst_BeRightBack: - labelPlayerStatus[slot].setTexture(CoreData::getInstance().getStatusBRBTexture()); - break; - case npst_Ready: - labelPlayerStatus[slot].setTexture(CoreData::getInstance().getStatusReadyTexture()); - break; - case npst_PickSettings: - labelPlayerStatus[slot].setTexture(CoreData::getInstance().getStatusNotReadyTexture()); - break; - case npst_Disconnected: - labelPlayerStatus[slot].setTexture(NULL); - break; - - default: - labelPlayerStatus[slot].setTexture(NULL); - break; - } - } - - listBoxControls[slot].setSelectedItemIndex(gameSettings->getFactionControl(i),errorOnMissingData); - listBoxRMultiplier[slot].setSelectedItemIndex(gameSettings->getResourceMultiplierIndex(i),errorOnMissingData); - listBoxTeams[slot].setSelectedItemIndex(gameSettings->getTeam(i),errorOnMissingData); - listBoxFactions[slot].setSelectedItem(formatString(gameSettings->getFactionTypeName(i)),false); - - if( gameSettings->getFactionControl(i) == ctNetwork || - gameSettings->getFactionControl(i) == ctNetworkUnassigned) { - labelNetStatus[slot].setText(gameSettings->getNetworkPlayerName(i)); - if( gameSettings->getThisFactionIndex() != i && - gameSettings->getNetworkPlayerName(i) != "" && - gameSettings->getNetworkPlayerName(i) != GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME) { - labelPlayerNames[slot].setText(gameSettings->getNetworkPlayerName(i)); - } - } - - ControlType ct= gameSettings->getFactionControl(i); - if (ct == ctHuman || ct == ctNetwork || ct == ctClosed) { - listBoxRMultiplier[slot].setEnabled(false); - listBoxRMultiplier[slot].setVisible(false); - } - else { - listBoxRMultiplier[slot].setEnabled(true); - listBoxRMultiplier[slot].setVisible(true); - } - - if((gameSettings->getFactionControl(i) == ctNetwork || - gameSettings->getFactionControl(i) == ctNetworkUnassigned) && - gameSettings->getThisFactionIndex() == i) { - - // set my current slot to ctHuman - if(gameSettings->getFactionControl(i) != ctNetworkUnassigned) { - listBoxControls[slot].setSelectedItemIndex(ctHuman); - } - if(checkBoxScenario.getValue() == false) { - if(clientInterface->getJoinGameInProgress() == false) { - listBoxFactions[slot].setEditable(true); - listBoxTeams[slot].setEditable(true); - } - } - - if(labelPlayerNames[slot].getText() == "" && - gameSettings->getNetworkPlayerName(i) != "" && - gameSettings->getNetworkPlayerName(i) != GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME) { - labelPlayerNames[slot].setText(gameSettings->getNetworkPlayerName(i)); - } - } - } - settingsReceivedFromServer=true; - initialSettingsReceivedFromServer=true; - - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); - } - - if(enableFactionTexturePreview == true) { - if( clientInterface != NULL && clientInterface->isConnected() && - gameSettings != NULL) { - - if( currentTechName_factionPreview != gameSettings->getTech() || - currentFactionName_factionPreview != gameSettings->getFactionTypeName(gameSettings->getThisFactionIndex())) { - - currentTechName_factionPreview=gameSettings->getTech(); - currentFactionName_factionPreview=gameSettings->getFactionTypeName(gameSettings->getThisFactionIndex()); - - initFactionPreview(gameSettings); - } - } - } + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + } + if (enableFactionTexturePreview == true) { + if (clientInterface != NULL && clientInterface->isConnected() && + gameSettings != NULL) { + + if (currentTechName_factionPreview != gameSettings->getTech() || + currentFactionName_factionPreview != + gameSettings->getFactionTypeName( + gameSettings->getThisFactionIndex())) { + + currentTechName_factionPreview = gameSettings->getTech(); + currentFactionName_factionPreview = gameSettings->getFactionTypeName( + gameSettings->getThisFactionIndex()); + + initFactionPreview(gameSettings); + } + } + } } -void MenuStateConnectedGame::initFactionPreview(const GameSettings *gameSettings) { - string factionVideoUrl = ""; - string factionVideoUrlFallback = ""; - - string factionDefinitionXML = Game::findFactionLogoFile(gameSettings, NULL,currentFactionName_factionPreview + ".xml"); - if(factionDefinitionXML != "" && currentFactionName_factionPreview != GameConstants::RANDOMFACTION_SLOTNAME && - currentFactionName_factionPreview != GameConstants::OBSERVER_SLOTNAME && fileExists(factionDefinitionXML) == true) { - XmlTree xmlTree; - std::map mapExtraTagReplacementValues; - xmlTree.load(factionDefinitionXML, Properties::getTagReplacementValues(&mapExtraTagReplacementValues)); - const XmlNode *factionNode= xmlTree.getRootNode(); - if(factionNode->hasAttribute("faction-preview-video") == true) { - factionVideoUrl = factionNode->getAttribute("faction-preview-video")->getValue(); - } - - factionVideoUrlFallback = Game::findFactionLogoFile(gameSettings, NULL,"preview_video.*"); - if(factionVideoUrl == "") { - factionVideoUrl = factionVideoUrlFallback; - factionVideoUrlFallback = ""; - } - } - - if(factionVideoUrl != "") { - if(CoreData::getInstance().getMenuMusic()->getVolume() != 0) { - CoreData::getInstance().getMenuMusic()->setVolume(0); - factionVideoSwitchedOffVolume=true; - } - - if(currentFactionLogo != factionVideoUrl) { - currentFactionLogo = factionVideoUrl; - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && - ::Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == true) { - - if(factionVideo != NULL) { - factionVideo->closePlayer(); - delete factionVideo; - factionVideo = NULL; - } - string introVideoFile = factionVideoUrl; - string introVideoFileFallback = factionVideoUrlFallback; - - Context *c= GraphicsInterface::getInstance().getCurrentContext(); - PlatformContextGl *glCtx = static_cast(c)->getPlatformContextGlPtr(); - SDL_Window *window = glCtx->getScreenWindow(); - SDL_Surface *screen = glCtx->getScreenSurface(); - - string vlcPluginsPath = Config::getInstance().getString("VideoPlayerPluginsPath",""); - //printf("screen->w = %d screen->h = %d screen->format->BitsPerPixel = %d\n",screen->w,screen->h,screen->format->BitsPerPixel); - factionVideo = new VideoPlayer( - &Renderer::getInstance(), - introVideoFile, - introVideoFileFallback, - window, - 0,0, - screen->w, - screen->h, - screen->format->BitsPerPixel, - true, - vlcPluginsPath, - SystemFlags::VERBOSE_MODE_ENABLED); - factionVideo->initPlayer(); - } - } - } - else { - //switch on music again!! - Config &config = Config::getInstance(); - float configVolume = (config.getInt("SoundVolumeMusic") / 100.f); - if(factionVideoSwitchedOffVolume){ - if(CoreData::getInstance().getMenuMusic()->getVolume() != configVolume) { - CoreData::getInstance().getMenuMusic()->setVolume(configVolume); - } - factionVideoSwitchedOffVolume=false; - } - - if(factionVideo != NULL) { - factionVideo->closePlayer(); - delete factionVideo; - factionVideo = NULL; - } - } - - if(factionVideo == NULL) { - string factionLogo = Game::findFactionLogoFile(gameSettings, NULL,GameConstants::PREVIEW_SCREEN_FILE_FILTER); - if(factionLogo == "") { - factionLogo = Game::findFactionLogoFile(gameSettings, NULL); - } - if(currentFactionLogo != factionLogo) { - currentFactionLogo = factionLogo; - loadFactionTexture(currentFactionLogo); - } - } +void MenuStateConnectedGame::initFactionPreview( + const GameSettings *gameSettings) { + string factionVideoUrl = ""; + string factionVideoUrlFallback = ""; + + string factionDefinitionXML = Game::findFactionLogoFile( + gameSettings, NULL, currentFactionName_factionPreview + ".xml"); + if (factionDefinitionXML != "" && + currentFactionName_factionPreview != + GameConstants::RANDOMFACTION_SLOTNAME && + currentFactionName_factionPreview != GameConstants::OBSERVER_SLOTNAME && + fileExists(factionDefinitionXML) == true) { + XmlTree xmlTree; + std::map mapExtraTagReplacementValues; + xmlTree.load(factionDefinitionXML, Properties::getTagReplacementValues( + &mapExtraTagReplacementValues)); + const XmlNode *factionNode = xmlTree.getRootNode(); + if (factionNode->hasAttribute("faction-preview-video") == true) { + factionVideoUrl = + factionNode->getAttribute("faction-preview-video")->getValue(); + } + + factionVideoUrlFallback = + Game::findFactionLogoFile(gameSettings, NULL, "preview_video.*"); + if (factionVideoUrl == "") { + factionVideoUrl = factionVideoUrlFallback; + factionVideoUrlFallback = ""; + } + } + + if (factionVideoUrl != "") { + if (CoreData::getInstance().getMenuMusic()->getVolume() != 0) { + CoreData::getInstance().getMenuMusic()->setVolume(0); + factionVideoSwitchedOffVolume = true; + } + + if (currentFactionLogo != factionVideoUrl) { + currentFactionLogo = factionVideoUrl; + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && + ::Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == true) { + + if (factionVideo != NULL) { + factionVideo->closePlayer(); + delete factionVideo; + factionVideo = NULL; + } + string introVideoFile = factionVideoUrl; + string introVideoFileFallback = factionVideoUrlFallback; + + Context *c = GraphicsInterface::getInstance().getCurrentContext(); + PlatformContextGl *glCtx = + static_cast(c)->getPlatformContextGlPtr(); + SDL_Window *window = glCtx->getScreenWindow(); + SDL_Surface *screen = glCtx->getScreenSurface(); + + string vlcPluginsPath = + Config::getInstance().getString("VideoPlayerPluginsPath", ""); + // printf("screen->w = %d screen->h = %d screen->format->BitsPerPixel = + // %d\n",screen->w,screen->h,screen->format->BitsPerPixel); + factionVideo = new VideoPlayer( + &Renderer::getInstance(), introVideoFile, introVideoFileFallback, + window, 0, 0, screen->w, screen->h, screen->format->BitsPerPixel, + true, vlcPluginsPath, SystemFlags::VERBOSE_MODE_ENABLED); + factionVideo->initPlayer(); + } + } + } else { + // switch on music again!! + Config &config = Config::getInstance(); + float configVolume = (config.getInt("SoundVolumeMusic") / 100.f); + if (factionVideoSwitchedOffVolume) { + if (CoreData::getInstance().getMenuMusic()->getVolume() != configVolume) { + CoreData::getInstance().getMenuMusic()->setVolume(configVolume); + } + factionVideoSwitchedOffVolume = false; + } + + if (factionVideo != NULL) { + factionVideo->closePlayer(); + delete factionVideo; + factionVideo = NULL; + } + } + + if (factionVideo == NULL) { + string factionLogo = Game::findFactionLogoFile( + gameSettings, NULL, GameConstants::PREVIEW_SCREEN_FILE_FILTER); + if (factionLogo == "") { + factionLogo = Game::findFactionLogoFile(gameSettings, NULL); + } + if (currentFactionLogo != factionLogo) { + currentFactionLogo = factionLogo; + loadFactionTexture(currentFactionLogo); + } + } } void MenuStateConnectedGame::RestoreLastGameSettings() { - loadGameSettings(HEADLESS_SAVED_SETUP_FILENAME); + loadGameSettings(HEADLESS_SAVED_SETUP_FILENAME); } - -bool MenuStateConnectedGame::loadGameSettings(const std::string &fileName) { - // Ensure we have set the gamesettings at least once - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface* clientInterface= networkManager.getClientInterface(); - GameSettings gameSettings = *clientInterface->getGameSettings(); - bool result=CoreData::getInstance().loadGameSettingsFromFile(fileName,&gameSettings); - if(result==false){ - console.addLine("Cannot load '"+fileName+"'"); - return false; - } - if(gameSettings.getMap() == "") { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - copyToGameSettings(&gameSettings); - } - - vector mapsV=playerSortedMaps[0]; - if(std::find(mapsV.begin(), mapsV.end(), gameSettings.getMap()) == mapsV.end()) { - console.addLine("Cannot load '"+fileName+"', map unknown ('"+gameSettings.getMap()+"')"); - return false;// map unknown - } - if(std::find(tilesetFiles.begin(), tilesetFiles.end(), gameSettings.getTileset()) == tilesetFiles.end()) { - console.addLine("Cannot load '"+fileName+"', tileset unknown ('"+gameSettings.getTileset()+"')"); - return false;// tileset unknown - } - if(std::find(techTreeFiles.begin(), techTreeFiles.end(), gameSettings.getTech()) == techTreeFiles.end()) { - console.addLine("Cannot load '"+fileName+"', techtree unknown ('"+gameSettings.getTech()+"')"); - return false;// techtree unknown - } - - setupUIFromGameSettings(&gameSettings, false); - - needToBroadcastServerSettings=true; - broadcastServerSettingsDelayTimer=time(NULL); - noReceiveTimer=time(NULL); - return true; +bool MenuStateConnectedGame::loadGameSettings(const std::string &fileName) { + // Ensure we have set the gamesettings at least once + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + GameSettings gameSettings = *clientInterface->getGameSettings(); + bool result = + CoreData::getInstance().loadGameSettingsFromFile(fileName, &gameSettings); + if (result == false) { + console.addLine("Cannot load '" + fileName + "'"); + return false; + } + if (gameSettings.getMap() == "") { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + copyToGameSettings(&gameSettings); + } + + vector mapsV = playerSortedMaps[0]; + if (std::find(mapsV.begin(), mapsV.end(), gameSettings.getMap()) == + mapsV.end()) { + console.addLine("Cannot load '" + fileName + "', map unknown ('" + + gameSettings.getMap() + "')"); + return false; // map unknown + } + if (std::find(tilesetFiles.begin(), tilesetFiles.end(), + gameSettings.getTileset()) == tilesetFiles.end()) { + console.addLine("Cannot load '" + fileName + "', tileset unknown ('" + + gameSettings.getTileset() + "')"); + return false; // tileset unknown + } + if (std::find(techTreeFiles.begin(), techTreeFiles.end(), + gameSettings.getTech()) == techTreeFiles.end()) { + console.addLine("Cannot load '" + fileName + "', techtree unknown ('" + + gameSettings.getTech() + "')"); + return false; // techtree unknown + } + + setupUIFromGameSettings(&gameSettings, false); + + needToBroadcastServerSettings = true; + broadcastServerSettingsDelayTimer = time(NULL); + noReceiveTimer = time(NULL); + return true; } void MenuStateConnectedGame::saveGameSettings(std::string fileName) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - GameSettings gameSettings; - copyToGameSettings(&gameSettings); - CoreData::getInstance().saveGameSettingsToFile(fileName, &gameSettings,true); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + GameSettings gameSettings; + copyToGameSettings(&gameSettings); + CoreData::getInstance().saveGameSettingsToFile(fileName, &gameSettings, true); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); } void MenuStateConnectedGame::loadSavedSetupNames() { - Config &config = Config::getInstance(); - Lang &lang= Lang::getInstance(); - vector paths; - string userData = config.getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - string saveSetupDir ; - saveSetupDir = userData +"setups"; - paths.push_back(saveSetupDir); - savedSetupFilenames.clear(); - findAll(paths, "*.mgg", savedSetupFilenames, true, false, true); - sort(savedSetupFilenames.begin(),savedSetupFilenames.end()); - savedSetupFilenames.insert(savedSetupFilenames.begin(),1,lang.getString(LAST_SETUP_STRING)); + Config &config = Config::getInstance(); + Lang &lang = Lang::getInstance(); + vector paths; + string userData = config.getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + string saveSetupDir; + saveSetupDir = userData + "setups"; + paths.push_back(saveSetupDir); + savedSetupFilenames.clear(); + findAll(paths, "*.mgg", savedSetupFilenames, true, false, true); + sort(savedSetupFilenames.begin(), savedSetupFilenames.end()); + savedSetupFilenames.insert(savedSetupFilenames.begin(), 1, + lang.getString(LAST_SETUP_STRING)); } int MenuStateConnectedGame::setupMapList(string scenario) { - int initialMapSelection = 0; - - try { - Config &config = Config::getInstance(); - vector invalidMapList; - string scenarioDir = Scenario::getScenarioDir(dirList, scenario); - vector pathList = config.getPathListForType(ptMaps,scenarioDir); - vector allMaps = MapPreview::findAllValidMaps(pathList,scenarioDir,false,true,&invalidMapList); - // sort map list non case sensitive - std::sort(allMaps.begin(),allMaps.end(),compareNonCaseSensitive); - if(scenario != "") { - vector allMaps2 = MapPreview::findAllValidMaps(config.getPathListForType(ptMaps,""),"",false,true,&invalidMapList); - copy(allMaps2.begin(), allMaps2.end(), std::inserter(allMaps, allMaps.begin())); - std::sort(allMaps.begin(),allMaps.end(),compareNonCaseSensitive); - } - - if (allMaps.empty()) { - throw megaglest_runtime_error("No maps were found!"); - } - vector results; - copy(allMaps.begin(), allMaps.end(), std::back_inserter(results)); - mapFiles = results; - - for(unsigned int i = 0; i < GameConstants::maxPlayers+1; ++i) { - playerSortedMaps[i].clear(); - formattedPlayerSortedMaps[i].clear(); - } - - copy(mapFiles.begin(), mapFiles.end(), std::back_inserter(playerSortedMaps[0])); - copy(playerSortedMaps[0].begin(), playerSortedMaps[0].end(), std::back_inserter(formattedPlayerSortedMaps[0])); - std::for_each(formattedPlayerSortedMaps[0].begin(), formattedPlayerSortedMaps[0].end(), FormatString()); - - formattedMapFiles.clear(); - for(int i= 0; i < (int)mapFiles.size(); i++){// fetch info and put map in right list - loadMapInfo(Config::getMapPath(mapFiles.at(i), scenarioDir, false), &mapInfo, false,true); - - if(GameConstants::maxPlayers+1 <= mapInfo.players) { - char szBuf[8096]=""; - 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()); - throw megaglest_runtime_error(szBuf); - } - playerSortedMaps[mapInfo.players].push_back(mapFiles.at(i)); - formattedPlayerSortedMaps[mapInfo.players].push_back(formatString(mapFiles.at(i))); - if(config.getString("InitialMap", "Conflict") == formattedPlayerSortedMaps[mapInfo.players].back()){ - initialMapSelection= i; - } - formattedMapFiles.push_back(formatString(mapFiles.at(i))); - } - - if(scenario != "") { - string file = Scenario::getScenarioPath(dirList, scenario); - loadScenarioInfo(file, &scenarioInfo); - - loadMapInfo(Config::getMapPath(scenarioInfo.mapName, scenarioDir, true), &mapInfo, false,true); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d] listBoxMap.getSelectedItemIndex() = %d, mapFiles.size() = " MG_SIZE_T_SPECIFIER ", mapInfo.players = %d, formattedPlayerSortedMaps[mapInfo.players].size() = " MG_SIZE_T_SPECIFIER ", scenarioInfo.mapName [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,comboBoxMap.getSelectedItemIndex(),mapFiles.size(),mapInfo.players,formattedPlayerSortedMaps[mapInfo.players].size(),scenarioInfo.mapName.c_str()); - comboBoxMap.setItems(formattedPlayerSortedMaps[mapInfo.players]); - } - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - - throw megaglest_runtime_error(szBuf); - //abort(); - } - - return initialMapSelection; + int initialMapSelection = 0; + + try { + Config &config = Config::getInstance(); + vector invalidMapList; + string scenarioDir = Scenario::getScenarioDir(dirList, scenario); + vector pathList = config.getPathListForType(ptMaps, scenarioDir); + vector allMaps = MapPreview::findAllValidMaps( + pathList, scenarioDir, false, true, &invalidMapList); + // sort map list non case sensitive + std::sort(allMaps.begin(), allMaps.end(), compareNonCaseSensitive); + if (scenario != "") { + vector allMaps2 = + MapPreview::findAllValidMaps(config.getPathListForType(ptMaps, ""), + "", false, true, &invalidMapList); + copy(allMaps2.begin(), allMaps2.end(), + std::inserter(allMaps, allMaps.begin())); + std::sort(allMaps.begin(), allMaps.end(), compareNonCaseSensitive); + } + + if (allMaps.empty()) { + throw megaglest_runtime_error("No maps were found!"); + } + vector results; + copy(allMaps.begin(), allMaps.end(), std::back_inserter(results)); + mapFiles = results; + + for (unsigned int i = 0; i < GameConstants::maxPlayers + 1; ++i) { + playerSortedMaps[i].clear(); + formattedPlayerSortedMaps[i].clear(); + } + + copy(mapFiles.begin(), mapFiles.end(), + std::back_inserter(playerSortedMaps[0])); + copy(playerSortedMaps[0].begin(), playerSortedMaps[0].end(), + std::back_inserter(formattedPlayerSortedMaps[0])); + std::for_each(formattedPlayerSortedMaps[0].begin(), + formattedPlayerSortedMaps[0].end(), FormatString()); + + formattedMapFiles.clear(); + for (int i = 0; i < (int)mapFiles.size(); + i++) { // fetch info and put map in right list + loadMapInfo(Config::getMapPath(mapFiles.at(i), scenarioDir, false), + &mapInfo, false, true); + + if (GameConstants::maxPlayers + 1 <= mapInfo.players) { + char szBuf[8096] = ""; + 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()); + throw megaglest_runtime_error(szBuf); + } + playerSortedMaps[mapInfo.players].push_back(mapFiles.at(i)); + formattedPlayerSortedMaps[mapInfo.players].push_back( + formatString(mapFiles.at(i))); + if (config.getString("InitialMap", "Conflict") == + formattedPlayerSortedMaps[mapInfo.players].back()) { + initialMapSelection = i; + } + formattedMapFiles.push_back(formatString(mapFiles.at(i))); + } + + if (scenario != "") { + string file = Scenario::getScenarioPath(dirList, scenario); + loadScenarioInfo(file, &scenarioInfo); + + loadMapInfo(Config::getMapPath(scenarioInfo.mapName, scenarioDir, true), + &mapInfo, false, true); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf( + "In [%s::%s Line %d] listBoxMap.getSelectedItemIndex() = %d, " + "mapFiles.size() = " MG_SIZE_T_SPECIFIER ", mapInfo.players = %d, " + "formattedPlayerSortedMaps[mapInfo.players].size() " + "= " MG_SIZE_T_SPECIFIER ", scenarioInfo.mapName [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, comboBoxMap.getSelectedItemIndex(), mapFiles.size(), + mapInfo.players, formattedPlayerSortedMaps[mapInfo.players].size(), + scenarioInfo.mapName.c_str()); + comboBoxMap.setItems(formattedPlayerSortedMaps[mapInfo.players]); + } + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + throw megaglest_runtime_error(szBuf); + // abort(); + } + + return initialMapSelection; } int MenuStateConnectedGame::setupTechList(string scenario, bool forceLoad) { - int initialTechSelection = 0; - try { - Config &config = Config::getInstance(); - - string scenarioDir = Scenario::getScenarioDir(dirList, scenario); - vector results; - vector techPaths = config.getPathListForType(ptTechs,scenarioDir); - findDirs(techPaths, results); + int initialTechSelection = 0; + try { + Config &config = Config::getInstance(); - if(results.empty()) { - throw megaglest_runtime_error("No tech-trees were found!"); - } + string scenarioDir = Scenario::getScenarioDir(dirList, scenario); + vector results; + vector techPaths = config.getPathListForType(ptTechs, scenarioDir); + findDirs(techPaths, results); - techTreeFiles= results; + if (results.empty()) { + throw megaglest_runtime_error("No tech-trees were found!"); + } - vector translatedTechs; + techTreeFiles = results; - for(unsigned int i= 0; i < results.size(); i++) { - //printf("TECHS i = %d results [%s] scenario [%s]\n",i,results[i].c_str(),scenario.c_str()); + vector translatedTechs; - results.at(i)= formatString(results.at(i)); - if(config.getString("InitialTechTree", "Megapack") == results.at(i)) { - initialTechSelection= i; - } - string txTech = techTree->getTranslatedName(techTreeFiles.at(i), forceLoad); - translatedTechs.push_back(formatString(txTech)); - } + for (unsigned int i = 0; i < results.size(); i++) { + // printf("TECHS i = %d results [%s] scenario + // [%s]\n",i,results[i].c_str(),scenario.c_str()); + results.at(i) = formatString(results.at(i)); + if (config.getString("InitialTechTree", "Megapack") == results.at(i)) { + initialTechSelection = i; + } + string txTech = + techTree->getTranslatedName(techTreeFiles.at(i), forceLoad); + translatedTechs.push_back(formatString(txTech)); + } - listBoxTechTree.setItems(results,translatedTechs); - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); + listBoxTechTree.setItems(results, translatedTechs); + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); - throw megaglest_runtime_error(szBuf); - } + throw megaglest_runtime_error(szBuf); + } - return initialTechSelection; + return initialTechSelection; } void MenuStateConnectedGame::setupTilesetList(string scenario) { - try { - Config &config = Config::getInstance(); - - string scenarioDir = Scenario::getScenarioDir(dirList, scenario); - - vector results; - findDirs(config.getPathListForType(ptTilesets,scenarioDir), results); - if (results.empty()) { - //throw megaglest_runtime_error("No tile-sets were found!"); - showMessageBox( "No tile-sets were found!", "Error", false); - } - else { - tilesetFiles= results; - std::for_each(results.begin(), results.end(), FormatString()); - - listBoxTileset.setItems(results); - } - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - - throw megaglest_runtime_error(szBuf); - } + try { + Config &config = Config::getInstance(); + + string scenarioDir = Scenario::getScenarioDir(dirList, scenario); + + vector results; + findDirs(config.getPathListForType(ptTilesets, scenarioDir), results); + if (results.empty()) { + // throw megaglest_runtime_error("No tile-sets were found!"); + showMessageBox("No tile-sets were found!", "Error", false); + } else { + tilesetFiles = results; + std::for_each(results.begin(), results.end(), FormatString()); + + listBoxTileset.setItems(results); + } + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + throw megaglest_runtime_error(szBuf); + } } -void MenuStateConnectedGame::loadScenarioInfo(string file, ScenarioInfo *scenarioInfo) { - bool isTutorial = Scenario::isGameTutorial(file); - Scenario::loadScenarioInfo(file, scenarioInfo, isTutorial); +void MenuStateConnectedGame::loadScenarioInfo(string file, + ScenarioInfo *scenarioInfo) { + bool isTutorial = Scenario::isGameTutorial(file); + Scenario::loadScenarioInfo(file, scenarioInfo, isTutorial); - previewLoadDelayTimer=time(NULL); - needToLoadTextures=true; + previewLoadDelayTimer = time(NULL); + needToLoadTextures = true; } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/menu/menu_state_connected_game.h b/source/glest_game/menu/menu_state_connected_game.h index f4971cf05..da5c4cf53 100644 --- a/source/glest_game/menu/menu_state_connected_game.h +++ b/source/glest_game/menu/menu_state_connected_game.h @@ -13,331 +13,341 @@ #define _GLEST_GAME_MENUSTATECONNECTEDGAME_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include "main_menu.h" #include "chat_manager.h" -#include "map_preview.h" -#include "miniftpclient.h" #include "common_scoped_ptr.h" #include "leak_dumper.h" +#include "main_menu.h" +#include "map_preview.h" +#include "miniftpclient.h" -namespace Shared { namespace Graphics { - class VideoPlayer; -}} +namespace Shared { +namespace Graphics { +class VideoPlayer; +} +} // namespace Shared -namespace Glest { namespace Game { +namespace Glest { +namespace Game { class TechTree; enum JoinMenu { - jmSimple, - jmMasterserver, + jmSimple, + jmMasterserver, - jmCount + jmCount }; enum FTPMessageType { - ftpmsg_MissingNone, - ftpmsg_MissingMap, - ftpmsg_MissingTileset, - ftpmsg_MissingTechtree + ftpmsg_MissingNone, + ftpmsg_MissingMap, + ftpmsg_MissingTileset, + ftpmsg_MissingTechtree }; // =============================== // class MenuStateConnectedGame // =============================== -class MenuStateConnectedGame: public MenuState, public FTPClientCallbackInterface, public SimpleTaskCallbackInterface { +class MenuStateConnectedGame : public MenuState, + public FTPClientCallbackInterface, + public SimpleTaskCallbackInterface { private: - GraphicButton buttonDisconnect; - GraphicLabel labelControl; - GraphicLabel labelRMultiplier; - GraphicLabel labelFaction; - GraphicLabel labelTeam; - GraphicLabel labelMap; - GraphicLabel labelFogOfWar; - GraphicLabel labelTechTree; - GraphicLabel labelTileset; - GraphicLabel labelMapInfo; - GraphicLabel labelStatus; - GraphicLabel labelInfo; - GraphicLabel labelWaitingForPlayers; - - - //GraphicLabel labelPathFinderType; - //GraphicListBox listBoxPathFinderType; - - GraphicLabel labelMapPlayerCount; - GraphicListBox listBoxMapPlayerCount; - - GraphicLabel labelAdvanced; - GraphicListBox listBoxAdvanced; - - GraphicComboBox comboBoxMap; - GraphicListBox listBoxFogOfWar; - GraphicListBox listBoxTechTree; - GraphicListBox listBoxTileset; - GraphicLabel labelPlayers[GameConstants::maxPlayers]; - GraphicLabel labelPlayerNames[GameConstants::maxPlayers]; - GraphicListBox listBoxControls[GameConstants::maxPlayers]; - GraphicListBox listBoxRMultiplier[GameConstants::maxPlayers]; - GraphicListBox listBoxFactions[GameConstants::maxPlayers]; - GraphicListBox listBoxTeams[GameConstants::maxPlayers]; - GraphicLabel labelNetStatus[GameConstants::maxPlayers]; - GraphicButton grabSlotButton[GameConstants::maxPlayers]; - - GraphicListBox listBoxPlayerStatus; - GraphicLabel labelPlayerStatus[GameConstants::maxPlayers]; - - GraphicLabel labelMapFilter; - GraphicListBox listBoxMapFilter; - - GraphicLabel labelAllowObservers; - GraphicCheckBox checkBoxAllowObservers; - - GraphicButton buttonSaveSetup; - GraphicLabel labelSaveSetupName; - GraphicButton buttonLoadSetup; - GraphicButton buttonDeleteSetup; - GraphicComboBox comboBoxLoadSetup; - string savedSetupsDir; - vector savedSetupFilenames; - - GraphicLabel labelAllowNativeLanguageTechtree; - GraphicCheckBox checkBoxAllowNativeLanguageTechtree; - - GraphicLabel *activeInputLabel; - - time_t timerLabelFlash; - GraphicLabel labelDataSynchInfo; - - MapInfo mapInfo; - Texture2D *mapPreviewTexture; - bool zoomedMap; - int render_mapPreviewTexture_X; - int render_mapPreviewTexture_Y; - int render_mapPreviewTexture_W; - int render_mapPreviewTexture_H; - - bool needToSetChangedGameSettings; - time_t lastSetChangedGameSettings; - bool updateDataSynchDetailText; - - int soundConnectionCount; - - //Console console; - ChatManager chatManager; - bool showFullConsole; - - string currentFactionName; - string currentMap; - JoinMenu returnMenuInfo; - bool settingsReceivedFromServer; - time_t lastNetworkSendPing; - int pingCount; - bool initialSettingsReceivedFromServer; - - string lastMapDataSynchError; - string lastTileDataSynchError; - string lastTechtreeDataSynchError; - - int8 switchSetupRequestFlagType; - string defaultPlayerName; - - bool enableFactionTexturePreview; - bool enableMapPreview; - - string currentTechName_factionPreview; - string currentFactionName_factionPreview; - string currentFactionLogo; - Texture2D *factionTexture; - ::Shared::Graphics::VideoPlayer *factionVideo; - bool factionVideoSwitchedOffVolume; - - MapPreview mapPreview; - - GraphicMessageBox mainMessageBox; - - std::string lastMissingMap; - std::string lastMissingTechtree; - std::string lastMissingTileSet; - - vector mapFiles; - vector techTreeFiles; - vector tilesetFiles; - vector factionFiles; - - vector playerSortedMaps[GameConstants::maxPlayers+1]; - vector formattedPlayerSortedMaps[GameConstants::maxPlayers+1]; - vector formattedMapFiles; - - GraphicMessageBox ftpMessageBox; - FTPClientThread *ftpClientThread; - FTPMessageType ftpMissingDataType; - - SimpleTaskThread *modHttpServerThread; - std::vector tilesetListRemote; - std::map tilesetCacheList; - std::vector techListRemote; - std::map techCacheList; - std::vector mapListRemote; - std::map mapCacheList; - - std::map mapCRCUpdateList; - - string getMissingMapFromFTPServer; - bool getMissingMapFromFTPServerInProgress; - time_t getMissingMapFromFTPServerLastPrompted; - - string getMissingTilesetFromFTPServer; - bool getMissingTilesetFromFTPServerInProgress; - time_t getMissingTilesetFromFTPServerLastPrompted; - - string getMissingTechtreeFromFTPServer; - bool getMissingTechtreeFromFTPServerInProgress; - time_t getMissingTechtreeFromFTPServerLastPrompted; - - string getInProgressSavedGameFromFTPServer; - bool getInProgressSavedGameFromFTPServerInProgress; - bool readyToJoinInProgressGame; - - string lastCheckedCRCTilesetName; - string lastCheckedCRCTechtreeName; - string lastCheckedCRCMapName; - uint32 lastCheckedCRCTilesetValue; - uint32 lastCheckedCRCTechtreeValue; - uint32 lastCheckedCRCMapValue; - vector > factionCRCList; - - std::map > fileFTPProgressList; - GraphicButton buttonCancelDownloads; - - GraphicLabel labelEnableSwitchTeamMode; - GraphicCheckBox checkBoxEnableSwitchTeamMode; - - GraphicLabel labelAllowTeamUnitSharing; - GraphicCheckBox checkBoxAllowTeamUnitSharing; - - GraphicLabel labelAllowTeamResourceSharing; - GraphicCheckBox checkBoxAllowTeamResourceSharing; - - GraphicLabel labelAISwitchTeamAcceptPercent; - GraphicListBox listBoxAISwitchTeamAcceptPercent; - GraphicLabel labelFallbackCpuMultiplier; - GraphicListBox listBoxFallbackCpuMultiplier; - - GraphicButton buttonPlayNow; - - GraphicCheckBox checkBoxScenario; - GraphicLabel labelScenario; - GraphicListBox listBoxScenario; - vector scenarioFiles; - ScenarioInfo scenarioInfo; - vector dirList; - string autoloadScenarioName; - time_t previewLoadDelayTimer; - bool needToLoadTextures; - bool enableScenarioTexturePreview; - Texture2D *scenarioLogoTexture; + GraphicButton buttonDisconnect; + GraphicLabel labelControl; + GraphicLabel labelRMultiplier; + GraphicLabel labelFaction; + GraphicLabel labelTeam; + GraphicLabel labelMap; + GraphicLabel labelFogOfWar; + GraphicLabel labelTechTree; + GraphicLabel labelTileset; + GraphicLabel labelMapInfo; + GraphicLabel labelStatus; + GraphicLabel labelInfo; + GraphicLabel labelWaitingForPlayers; + + // GraphicLabel labelPathFinderType; + // GraphicListBox listBoxPathFinderType; + + GraphicLabel labelMapPlayerCount; + GraphicListBox listBoxMapPlayerCount; + + GraphicLabel labelAdvanced; + GraphicListBox listBoxAdvanced; + + GraphicComboBox comboBoxMap; + GraphicListBox listBoxFogOfWar; + GraphicListBox listBoxTechTree; + GraphicListBox listBoxTileset; + GraphicLabel labelPlayers[GameConstants::maxPlayers]; + GraphicLabel labelPlayerNames[GameConstants::maxPlayers]; + GraphicListBox listBoxControls[GameConstants::maxPlayers]; + GraphicListBox listBoxRMultiplier[GameConstants::maxPlayers]; + GraphicListBox listBoxFactions[GameConstants::maxPlayers]; + GraphicListBox listBoxTeams[GameConstants::maxPlayers]; + GraphicLabel labelNetStatus[GameConstants::maxPlayers]; + GraphicButton grabSlotButton[GameConstants::maxPlayers]; + + GraphicListBox listBoxPlayerStatus; + GraphicLabel labelPlayerStatus[GameConstants::maxPlayers]; + + GraphicLabel labelMapFilter; + GraphicListBox listBoxMapFilter; + + GraphicLabel labelAllowObservers; + GraphicCheckBox checkBoxAllowObservers; + + GraphicButton buttonSaveSetup; + GraphicLabel labelSaveSetupName; + GraphicButton buttonLoadSetup; + GraphicButton buttonDeleteSetup; + GraphicComboBox comboBoxLoadSetup; + string savedSetupsDir; + vector savedSetupFilenames; + + GraphicLabel labelAllowNativeLanguageTechtree; + GraphicCheckBox checkBoxAllowNativeLanguageTechtree; + + GraphicLabel *activeInputLabel; + + time_t timerLabelFlash; + GraphicLabel labelDataSynchInfo; + + MapInfo mapInfo; + Texture2D *mapPreviewTexture; + bool zoomedMap; + int render_mapPreviewTexture_X; + int render_mapPreviewTexture_Y; + int render_mapPreviewTexture_W; + int render_mapPreviewTexture_H; + + bool needToSetChangedGameSettings; + time_t lastSetChangedGameSettings; + bool updateDataSynchDetailText; + + int soundConnectionCount; + + // Console console; + ChatManager chatManager; + bool showFullConsole; + + string currentFactionName; + string currentMap; + JoinMenu returnMenuInfo; + bool settingsReceivedFromServer; + time_t lastNetworkSendPing; + int pingCount; + bool initialSettingsReceivedFromServer; + + string lastMapDataSynchError; + string lastTileDataSynchError; + string lastTechtreeDataSynchError; + + int8 switchSetupRequestFlagType; + string defaultPlayerName; + + bool enableFactionTexturePreview; + bool enableMapPreview; + + string currentTechName_factionPreview; + string currentFactionName_factionPreview; + string currentFactionLogo; + Texture2D *factionTexture; + ::Shared::Graphics::VideoPlayer *factionVideo; + bool factionVideoSwitchedOffVolume; + + MapPreview mapPreview; + + GraphicMessageBox mainMessageBox; + + std::string lastMissingMap; + std::string lastMissingTechtree; + std::string lastMissingTileSet; + + vector mapFiles; + vector techTreeFiles; + vector tilesetFiles; + vector factionFiles; + + vector playerSortedMaps[GameConstants::maxPlayers + 1]; + vector formattedPlayerSortedMaps[GameConstants::maxPlayers + 1]; + vector formattedMapFiles; + + GraphicMessageBox ftpMessageBox; + FTPClientThread *ftpClientThread; + FTPMessageType ftpMissingDataType; + + SimpleTaskThread *modHttpServerThread; + std::vector tilesetListRemote; + std::map tilesetCacheList; + std::vector techListRemote; + std::map techCacheList; + std::vector mapListRemote; + std::map mapCacheList; + + std::map mapCRCUpdateList; + + string getMissingMapFromFTPServer; + bool getMissingMapFromFTPServerInProgress; + time_t getMissingMapFromFTPServerLastPrompted; + + string getMissingTilesetFromFTPServer; + bool getMissingTilesetFromFTPServerInProgress; + time_t getMissingTilesetFromFTPServerLastPrompted; + + string getMissingTechtreeFromFTPServer; + bool getMissingTechtreeFromFTPServerInProgress; + time_t getMissingTechtreeFromFTPServerLastPrompted; + + string getInProgressSavedGameFromFTPServer; + bool getInProgressSavedGameFromFTPServerInProgress; + bool readyToJoinInProgressGame; + + string lastCheckedCRCTilesetName; + string lastCheckedCRCTechtreeName; + string lastCheckedCRCMapName; + uint32 lastCheckedCRCTilesetValue; + uint32 lastCheckedCRCTechtreeValue; + uint32 lastCheckedCRCMapValue; + vector> factionCRCList; + + std::map> fileFTPProgressList; + GraphicButton buttonCancelDownloads; + + GraphicLabel labelEnableSwitchTeamMode; + GraphicCheckBox checkBoxEnableSwitchTeamMode; + + GraphicLabel labelAllowTeamUnitSharing; + GraphicCheckBox checkBoxAllowTeamUnitSharing; + + GraphicLabel labelAllowTeamResourceSharing; + GraphicCheckBox checkBoxAllowTeamResourceSharing; + + GraphicLabel labelAISwitchTeamAcceptPercent; + GraphicListBox listBoxAISwitchTeamAcceptPercent; + GraphicLabel labelFallbackCpuMultiplier; + GraphicListBox listBoxFallbackCpuMultiplier; + + GraphicButton buttonPlayNow; + + GraphicCheckBox checkBoxScenario; + GraphicLabel labelScenario; + GraphicListBox listBoxScenario; + vector scenarioFiles; + ScenarioInfo scenarioInfo; + vector dirList; + string autoloadScenarioName; + time_t previewLoadDelayTimer; + bool needToLoadTextures; + bool enableScenarioTexturePreview; + Texture2D *scenarioLogoTexture; - bool needToBroadcastServerSettings; - time_t broadcastServerSettingsDelayTimer; - int lastGameSettingsReceivedCount; + bool needToBroadcastServerSettings; + time_t broadcastServerSettingsDelayTimer; + int lastGameSettingsReceivedCount; - time_t noReceiveTimer; - - bool launchingNewGame; - bool isfirstSwitchingMapMessage; - auto_ptr techTree; - - GameSettings originalGamesettings; - bool validOriginalGameSettings; - GameSettings displayedGamesettings; - bool validDisplayedGamesettings; + time_t noReceiveTimer; + + bool launchingNewGame; + bool isfirstSwitchingMapMessage; + auto_ptr techTree; + + GameSettings originalGamesettings; + bool validOriginalGameSettings; + GameSettings displayedGamesettings; + bool validDisplayedGamesettings; - string lastPreviewedMapFile; + string lastPreviewedMapFile; public: + MenuStateConnectedGame(Program *program, MainMenu *mainMenu, + JoinMenu joinMenuInfo = jmSimple, + bool openNetworkSlots = false); + virtual ~MenuStateConnectedGame(); - MenuStateConnectedGame(Program *program, MainMenu *mainMenu, JoinMenu joinMenuInfo=jmSimple, bool openNetworkSlots= false); - virtual ~MenuStateConnectedGame(); + void mouseClick(int x, int y, MouseButton mouseButton); + void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; + void mouseMove(int x, int y, const MouseState *mouseState); + void eventMouseWheel(int x, int y, int zDelta); + void render(); + void update(); - void mouseClick(int x, int y, MouseButton mouseButton); - void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; - void mouseMove(int x, int y, const MouseState *mouseState); - void eventMouseWheel(int x, int y,int zDelta); - void render(); - void update(); + virtual bool textInput(std::string text); + virtual void keyDown(SDL_KeyboardEvent key); + virtual void keyPress(SDL_KeyboardEvent c); + virtual void keyUp(SDL_KeyboardEvent key); - virtual bool textInput(std::string text); - virtual void keyDown(SDL_KeyboardEvent key); - virtual void keyPress(SDL_KeyboardEvent c); - virtual void keyUp(SDL_KeyboardEvent key); + virtual bool isInSpecialKeyCaptureEvent(); - virtual bool isInSpecialKeyCaptureEvent(); + virtual void reloadUI(); - virtual void reloadUI(); - - virtual bool isVideoPlaying(); + virtual bool isVideoPlaying(); private: - - void setSmallFont(GraphicLabel l); - bool hasNetworkGameSettings(); - bool loadFactions(const GameSettings *gameSettings,bool errorOnNoFactions); - void returnToJoinMenu(); - string getHumanPlayerName(); - void setActiveInputLabel(GraphicLabel *newLable); - - void loadFactionTexture(string filepath); - bool loadMapInfo(string file, MapInfo *mapInfo, bool loadMapPreview, bool doPlayerSetup); - void showMessageBox(const string &text, const string &header, bool toggle); - - void showFTPMessageBox(const string &text, const string &header, bool toggle); - virtual void FTPClient_CallbackEvent(string itemName, - FTP_Client_CallbackType type, pair result,void *userdata); - - int32 getNetworkPlayerStatus(); - void cleanupMapPreviewTexture(); - - void mouseClickAdmin(int x, int y, MouseButton mouseButton,string advanceToItemStartingWith); - void switchToNextMapGroup(const int direction); - void switchToMapGroup(int filterIndex); - string getCurrentMapFile(); - string getPreselectedMapFile(); - - void copyToGameSettings(GameSettings *gameSettings); - void reloadFactions(bool keepExistingSelectedItem,string scenario); - void PlayNow(bool saveGame); - bool isHeadlessAdmin(); - void broadCastGameSettingsToHeadlessServer(bool forceNow); - void updateResourceMultiplier(const int index); - - void saveGameSettings(std::string fileName); - bool loadGameSettings(const std::string &fileName); - void RestoreLastGameSettings(); - void setupUIFromGameSettings(GameSettings *gameSettings, bool errorOnMissingData); - - int setupMapList(string scenario); - void loadSavedSetupNames(); - int setupTechList(string scenario, bool forceLoad=false); - void setupTilesetList(string scenario); - - void loadScenarioInfo(string file, ScenarioInfo *scenarioInfo); - void initFactionPreview(const GameSettings *gameSettings); - - virtual void simpleTask(BaseThread *callingThread,void *userdata); - string refreshTilesetModInfo(string tilesetInfo); - string refreshTechModInfo(string techInfo); - string refreshMapModInfo(string mapInfo); - string getMapCRC(string mapName); - - void disconnectFromServer(); + void setSmallFont(GraphicLabel l); + bool hasNetworkGameSettings(); + bool loadFactions(const GameSettings *gameSettings, bool errorOnNoFactions); + void returnToJoinMenu(); + string getHumanPlayerName(); + void setActiveInputLabel(GraphicLabel *newLable); + + void loadFactionTexture(string filepath); + bool loadMapInfo(string file, MapInfo *mapInfo, bool loadMapPreview, + bool doPlayerSetup); + void showMessageBox(const string &text, const string &header, bool toggle); + + void showFTPMessageBox(const string &text, const string &header, bool toggle); + virtual void + FTPClient_CallbackEvent(string itemName, FTP_Client_CallbackType type, + pair result, + void *userdata); + + int32 getNetworkPlayerStatus(); + void cleanupMapPreviewTexture(); + + void mouseClickAdmin(int x, int y, MouseButton mouseButton, + string advanceToItemStartingWith); + void switchToNextMapGroup(const int direction); + void switchToMapGroup(int filterIndex); + string getCurrentMapFile(); + string getPreselectedMapFile(); + + void copyToGameSettings(GameSettings *gameSettings); + void reloadFactions(bool keepExistingSelectedItem, string scenario); + void PlayNow(bool saveGame); + bool isHeadlessAdmin(); + void broadCastGameSettingsToHeadlessServer(bool forceNow); + void updateResourceMultiplier(const int index); + + void saveGameSettings(std::string fileName); + bool loadGameSettings(const std::string &fileName); + void RestoreLastGameSettings(); + void setupUIFromGameSettings(GameSettings *gameSettings, + bool errorOnMissingData); + + int setupMapList(string scenario); + void loadSavedSetupNames(); + int setupTechList(string scenario, bool forceLoad = false); + void setupTilesetList(string scenario); + + void loadScenarioInfo(string file, ScenarioInfo *scenarioInfo); + void initFactionPreview(const GameSettings *gameSettings); + + virtual void simpleTask(BaseThread *callingThread, void *userdata); + string refreshTilesetModInfo(string tilesetInfo); + string refreshTechModInfo(string techInfo); + string refreshMapModInfo(string mapInfo); + string getMapCRC(string mapName); + + void disconnectFromServer(); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/menu/menu_state_custom_game.cpp b/source/glest_game/menu/menu_state_custom_game.cpp index 3350dee04..ce9bb6d9b 100644 --- a/source/glest_game/menu/menu_state_custom_game.cpp +++ b/source/glest_game/menu/menu_state_custom_game.cpp @@ -9,43 +9,45 @@ // ============================================================== #include "menu_state_custom_game.h" -#include "renderer.h" -#include "sound_renderer.h" -#include "core_data.h" +#include "cache_manager.h" +#include "client_interface.h" #include "config.h" -#include "menu_state_new_game.h" -#include "menu_state_masterserver.h" +#include "conversion.h" +#include "core_data.h" +#include "game.h" +#include "gen_uuid.h" +#include "leak_dumper.h" +#include "map_preview.h" #include "menu_state_join_game.h" +#include "menu_state_masterserver.h" +#include "menu_state_new_game.h" #include "metrics.h" #include "network_manager.h" #include "network_message.h" -#include "client_interface.h" -#include "conversion.h" +#include "renderer.h" #include "socket.h" -#include "game.h" +#include "sound_renderer.h" #include "util.h" #include -#include #include -#include "cache_manager.h" #include -#include "map_preview.h" -#include "gen_uuid.h" -#include "leak_dumper.h" +#include -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { using namespace ::Shared::Util; -const int MASTERSERVER_BROADCAST_MAX_WAIT_RESPONSE_SECONDS = 15; -const int MASTERSERVER_BROADCAST_PUBLISH_SECONDS = 6; -const int BROADCAST_MAP_DELAY_SECONDS = 5; -const int BROADCAST_SETTINGS_SECONDS = 4; -static const char *SAVED_SETUP_FILENAME = "lastCustomGameSettings.mgg"; -static const char *DEFAULT_SETUP_FILENAME = "data/defaultGameSetup.mgg"; -static const char *DEFAULT_NETWORK_SETUP_FILENAME = "data/defaultNetworkGameSetup.mgg"; -static const char *LAST_SETUP_STRING="LastSetup"; -static const char *SETUPS_DIR=GameConstants::folder_path_setups; +const int MASTERSERVER_BROADCAST_MAX_WAIT_RESPONSE_SECONDS = 15; +const int MASTERSERVER_BROADCAST_PUBLISH_SECONDS = 6; +const int BROADCAST_MAP_DELAY_SECONDS = 5; +const int BROADCAST_SETTINGS_SECONDS = 4; +static const char *SAVED_SETUP_FILENAME = "lastCustomGameSettings.mgg"; +static const char *DEFAULT_SETUP_FILENAME = "data/defaultGameSetup.mgg"; +static const char *DEFAULT_NETWORK_SETUP_FILENAME = + "data/defaultNetworkGameSetup.mgg"; +static const char *LAST_SETUP_STRING = "LastSetup"; +static const char *SETUPS_DIR = GameConstants::folder_path_setups; const int mapPreviewTexture_X = 5; const int mapPreviewTexture_Y = 260; @@ -53,5468 +55,6949 @@ const int mapPreviewTexture_W = 150; const int mapPreviewTexture_H = 150; struct FormatString { - void operator()(string &s) { - s = formatString(s); - } + void operator()(string &s) { s = formatString(s); } }; // ===================================================== // class MenuStateCustomGame // ===================================================== -enum THREAD_NOTIFIER_TYPE { - tnt_MASTERSERVER = 1, - tnt_CLIENTS = 2 -}; +enum THREAD_NOTIFIER_TYPE { tnt_MASTERSERVER = 1, tnt_CLIENTS = 2 }; MenuStateCustomGame::MenuStateCustomGame(Program *program, MainMenu *mainMenu, - bool openNetworkSlots,ParentMenuState parentMenuState, bool autostart, - GameSettings *settings, bool masterserverMode, - string autoloadScenarioName) : - MenuState(program, mainMenu, "new-game") { - try { - - this->headlessServerMode = masterserverMode; - if(this->headlessServerMode == true) { - printf("Waiting for players to join and start a game...\n"); - } - - this->gameUUID = getUUIDAsString(); - - this->zoomedMap=false; - this->render_mapPreviewTexture_X = mapPreviewTexture_X; - this->render_mapPreviewTexture_Y = mapPreviewTexture_Y; - this->render_mapPreviewTexture_W = mapPreviewTexture_W; - this->render_mapPreviewTexture_H = mapPreviewTexture_H; - - this->lastMasterServerSettingsUpdateCount = 0; - this->masterserverModeMinimalResources = true; - this->parentMenuState=parentMenuState; - this->factionVideo = NULL; - factionVideoSwitchedOffVolume=false; - - //printf("this->masterserverMode = %d [%d]\n",this->masterserverMode,masterserverMode); - - forceWaitForShutdown = true; - this->autostart = autostart; - this->autoStartSettings = settings; - - 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); - - containerName = "CustomGame"; - activeInputLabel=NULL; - showGeneralError = false; - generalErrorToShow = "---"; - currentFactionLogo = ""; - factionTexture=NULL; - currentTechName_factionPreview=""; - currentFactionName_factionPreview=""; - mapPreviewTexture=NULL; - hasCheckedForUPNP = false; - needToPublishDelayed=false; - mapPublishingDelayTimer=time(NULL); - headlessHasConnectedPlayer=false; - lastPreviewedMapFile=""; - - lastCheckedCRCTilesetName = ""; - lastCheckedCRCTechtreeName = ""; - lastCheckedCRCMapName = ""; - - lastRecalculatedCRCTilesetName = ""; - lastRecalculatedCRCTechtreeName = ""; - - initTime= time(NULL); // now - lastTechtreeChange= time(NULL); // now - - lastCheckedCRCTilesetValue = 0; - lastCheckedCRCTechtreeValue = 0; - lastCheckedCRCMapValue = 0; - - publishToMasterserverThread = NULL; - publishToClientsThread = NULL; - - Lang &lang= Lang::getInstance(); - NetworkManager &networkManager= NetworkManager::getInstance(); + bool openNetworkSlots, + ParentMenuState parentMenuState, + bool autostart, GameSettings *settings, + bool masterserverMode, + string autoloadScenarioName) + : MenuState(program, mainMenu, "new-game") { + try { + + this->headlessServerMode = masterserverMode; + if (this->headlessServerMode == true) { + printf("Waiting for players to join and start a game...\n"); + } + + this->gameUUID = getUUIDAsString(); + + this->zoomedMap = false; + this->render_mapPreviewTexture_X = mapPreviewTexture_X; + this->render_mapPreviewTexture_Y = mapPreviewTexture_Y; + this->render_mapPreviewTexture_W = mapPreviewTexture_W; + this->render_mapPreviewTexture_H = mapPreviewTexture_H; + + this->lastMasterServerSettingsUpdateCount = 0; + this->masterserverModeMinimalResources = true; + this->parentMenuState = parentMenuState; + this->factionVideo = NULL; + factionVideoSwitchedOffVolume = false; + + // printf("this->masterserverMode = %d + // [%d]\n",this->masterserverMode,masterserverMode); + + forceWaitForShutdown = true; + this->autostart = autostart; + this->autoStartSettings = settings; + + 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); + + containerName = "CustomGame"; + activeInputLabel = NULL; + showGeneralError = false; + generalErrorToShow = "---"; + currentFactionLogo = ""; + factionTexture = NULL; + currentTechName_factionPreview = ""; + currentFactionName_factionPreview = ""; + mapPreviewTexture = NULL; + hasCheckedForUPNP = false; + needToPublishDelayed = false; + mapPublishingDelayTimer = time(NULL); + headlessHasConnectedPlayer = false; + lastPreviewedMapFile = ""; + + lastCheckedCRCTilesetName = ""; + lastCheckedCRCTechtreeName = ""; + lastCheckedCRCMapName = ""; + + lastRecalculatedCRCTilesetName = ""; + lastRecalculatedCRCTechtreeName = ""; + + initTime = time(NULL); // now + lastTechtreeChange = time(NULL); // now + + lastCheckedCRCTilesetValue = 0; + lastCheckedCRCTechtreeValue = 0; + lastCheckedCRCMapValue = 0; + + publishToMasterserverThread = NULL; + publishToClientsThread = NULL; + + Lang &lang = Lang::getInstance(); + NetworkManager &networkManager = NetworkManager::getInstance(); Config &config = Config::getInstance(); - defaultPlayerName = config.getString("NetPlayerName",Socket::getHostName().c_str()); - enableFactionTexturePreview = config.getBool("FactionPreview","true"); - enableMapPreview = config.getBool("MapPreview","true"); - - showFullConsole=false; - - enableScenarioTexturePreview = Config::getInstance().getBool("EnableScenarioTexturePreview","true"); - scenarioLogoTexture=NULL; - previewLoadDelayTimer=time(NULL); - needToLoadTextures=true; - this->autoloadScenarioName = autoloadScenarioName; - this->dirList = Config::getInstance().getPathListForType(ptScenarios); - - - string userData = Config::getInstance().getString("UserData_Root",""); - if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - userData = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey); - } - if(userData != "") { - endPathWithSlash(userData); - } - savedSetupsDir = userData +SETUPS_DIR; - - mainMessageBox.registerGraphicComponent(containerName,"mainMessageBox"); - mainMessageBox.init(lang.getString("Ok"),500,300); - mainMessageBox.setEnabled(false); - mainMessageBoxState=0; - - //initialize network interface - NetworkManager::getInstance().end(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - serverInitError = false; - try { - networkManager.init(nrServer,openNetworkSlots); - } - catch(const std::exception &ex) { - serverInitError = true; - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nNetwork init error:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - - showGeneralError=true; - generalErrorToShow = szBuf; - } - - string serverPort=config.getString("PortServer", intToStr(GameConstants::serverPort).c_str()); - string externalPort=config.getString("PortExternal", serverPort.c_str()); - ServerSocket::setExternalPort(strToInt(externalPort)); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - needToSetChangedGameSettings = false; - needToRepublishToMasterserver = false; - needToBroadcastServerSettings = false; - lastGameSettingsreceivedCount = -1; - showMasterserverError = false; - tMasterserverErrorElapsed = 0; - masterServererErrorToShow = "---"; - lastSetChangedGameSettings = 0; - lastMasterserverPublishing = 0; - lastNetworkPing = 0; - soundConnectionCount=0; - - techTree.reset(new TechTree(config.getPathListForType(ptTechs))); - - int labelOffset=22; - int setupPos=650; - int mapHeadPos=mapPreviewTexture_Y+mapPreviewTexture_H; - int mapPos=mapHeadPos-labelOffset; - int aHeadPos=280; - int aPos=aHeadPos-labelOffset; - int networkHeadPos=750-labelOffset; - int xoffset=10; - int currX=0; - int currY=750; - int currXLabel=currX+20; - int lineHeightSmall=18; - - int buttonx=195; - int buttony=180; + defaultPlayerName = + config.getString("NetPlayerName", Socket::getHostName().c_str()); + enableFactionTexturePreview = config.getBool("FactionPreview", "true"); + enableMapPreview = config.getBool("MapPreview", "true"); + + showFullConsole = false; + + enableScenarioTexturePreview = + Config::getInstance().getBool("EnableScenarioTexturePreview", "true"); + scenarioLogoTexture = NULL; + previewLoadDelayTimer = time(NULL); + needToLoadTextures = true; + this->autoloadScenarioName = autoloadScenarioName; + this->dirList = Config::getInstance().getPathListForType(ptScenarios); + + string userData = Config::getInstance().getString("UserData_Root", ""); + if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { + userData = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey); + } + if (userData != "") { + endPathWithSlash(userData); + } + savedSetupsDir = userData + SETUPS_DIR; - // player status - listBoxPlayerStatus.registerGraphicComponent(containerName,"listBoxPlayerStatus"); - listBoxPlayerStatus.init(buttonx, buttony, 165); - vector playerStatuses; - playerStatuses.push_back(lang.getString("PlayerStatusSetup")); - playerStatuses.push_back(lang.getString("PlayerStatusBeRightBack")); - playerStatuses.push_back(lang.getString("PlayerStatusReady")); - listBoxPlayerStatus.setItems(playerStatuses); - listBoxPlayerStatus.setSelectedItemIndex(2,true); - listBoxPlayerStatus.setTextColor(Vec3f(0.0f,1.0f,0.0f)); - listBoxPlayerStatus.setLighted(false); - listBoxPlayerStatus.setVisible(true); - buttonx+=175; - - buttonReturn.registerGraphicComponent(containerName,"buttonReturn"); - buttonReturn.init(buttonx, buttony, 125); - buttonReturn.setText(lang.getString("Return")); - buttonx+=135; - - buttonPlayNow.registerGraphicComponent(containerName,"buttonPlayNow"); - buttonPlayNow.init(buttonx, buttony, 125); - buttonPlayNow.setText(lang.getString("PlayNow")); - - // network options - currY=networkHeadPos; - currX=10; - currXLabel=currX+20; - - labelPublishServer.registerGraphicComponent(containerName,"labelPublishServer"); - labelPublishServer.init(currX, currY, 100); - labelPublishServer.setText(lang.getString("PublishServer")); - - currY=currY-labelOffset; - - checkBoxPublishServer.registerGraphicComponent(containerName,"checkBoxPublishServer"); - checkBoxPublishServer.init(currX, currY); - checkBoxPublishServer.setValue(false); - if((this->headlessServerMode == true || - (openNetworkSlots == true && parentMenuState != pLanGame)) && - GlobalStaticFlags::isFlagSet(gsft_lan_mode) == false) { - checkBoxPublishServer.setValue(true); - } - - labelGameName.registerGraphicComponent(containerName,"labelGameName"); - labelGameName.init(currX+checkBoxPublishServer.getW()+5, currY,200); - //labelGameName.setFont(CoreData::getInstance().getMenuFontBig()); - //labelGameName.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - labelGameName.setText(createGameName()); - labelGameName.setEditable(true); - labelGameName.setMaxEditWidth(20); - labelGameName.setMaxEditRenderWidth(200); - - currY=730; - currX=390; - currXLabel=currX+20; - - checkBoxNetworkPauseGameForLaggedClients.registerGraphicComponent(containerName,"checkBoxNetworkPauseGameForLaggedClients"); - checkBoxNetworkPauseGameForLaggedClients.init(currX, currY+2,16,16); - checkBoxNetworkPauseGameForLaggedClients.setValue(true); - - labelNetworkPauseGameForLaggedClients.registerGraphicComponent(containerName,"labelNetworkPauseGameForLaggedClients"); - labelNetworkPauseGameForLaggedClients.init(currXLabel, currY, 80); - labelNetworkPauseGameForLaggedClients.setText(lang.getString("NetworkPauseGameForLaggedClients")); - currY = currY - lineHeightSmall; - - bool allowInProgressJoin = Config::getInstance().getBool("EnableJoinInProgressGame","false"); - labelAllowInGameJoinPlayer.registerGraphicComponent(containerName,"labelAllowInGameJoinPlayer"); - labelAllowInGameJoinPlayer.init(currXLabel, currY, 80); - labelAllowInGameJoinPlayer.setText(lang.getString("AllowInGameJoinPlayer")); - labelAllowInGameJoinPlayer.setVisible(allowInProgressJoin); - - checkBoxAllowInGameJoinPlayer.registerGraphicComponent(containerName,"checkBoxAllowInGameJoinPlayer"); - checkBoxAllowInGameJoinPlayer.init(currX, currX,16,16); - checkBoxAllowInGameJoinPlayer.setValue(false); - checkBoxAllowInGameJoinPlayer.setVisible(allowInProgressJoin); - - currY=680; - vector rMultiplier; - for(int i=0; i<45; ++i){ - rMultiplier.push_back(floatToStr(0.5f+0.1f*i,1)); - } - listBoxFallbackCpuMultiplier.registerGraphicComponent(containerName,"listBoxFallbackCpuMultiplier"); - listBoxFallbackCpuMultiplier.init(currX-44, currY+2, 60,16); - listBoxFallbackCpuMultiplier.setItems(rMultiplier); - listBoxFallbackCpuMultiplier.setSelectedItem("1.5"); - labelFallbackCpuMultiplier.registerGraphicComponent(containerName,"labelFallbackCpuMultiplier"); - labelFallbackCpuMultiplier.init(currXLabel, currY, 80); - labelFallbackCpuMultiplier.setText(lang.getString("FallbackCpuMultiplier")); - setSmallFont(labelAllowNativeLanguageTechtree); - currY = currY - lineHeightSmall; - - - xoffset=65; - // MapFilter - labelMapFilter.registerGraphicComponent(containerName,"labelMapFilter"); - labelMapFilter.init(xoffset+525, mapHeadPos); - labelMapFilter.setText(lang.getString("MapFilter")); - labelMapFilter.setVisible(false); - - labelMap.registerGraphicComponent(containerName,"labelMap"); - labelMap.init(xoffset+100, mapPos+20); - labelMap.setText(lang.getString("Map")); - - //Map Filter - listBoxMapFilter.registerGraphicComponent(containerName,"listBoxMapFilter"); - listBoxMapFilter.init(xoffset+260, mapPos+labelOffset, 60); - listBoxMapFilter.pushBackItem("-"); - for(int i=1; i playerStatuses; + playerStatuses.push_back(lang.getString("PlayerStatusSetup")); + playerStatuses.push_back(lang.getString("PlayerStatusBeRightBack")); + playerStatuses.push_back(lang.getString("PlayerStatusReady")); + listBoxPlayerStatus.setItems(playerStatuses); + listBoxPlayerStatus.setSelectedItemIndex(2, true); + listBoxPlayerStatus.setTextColor(Vec3f(0.0f, 1.0f, 0.0f)); + listBoxPlayerStatus.setLighted(false); + listBoxPlayerStatus.setVisible(true); + buttonx += 175; + + buttonReturn.registerGraphicComponent(containerName, "buttonReturn"); + buttonReturn.init(buttonx, buttony, 125); + buttonReturn.setText(lang.getString("Return")); + buttonx += 135; + + buttonPlayNow.registerGraphicComponent(containerName, "buttonPlayNow"); + buttonPlayNow.init(buttonx, buttony, 125); + buttonPlayNow.setText(lang.getString("PlayNow")); + + // network options + currY = networkHeadPos; + currX = 10; + currXLabel = currX + 20; + + labelPublishServer.registerGraphicComponent(containerName, + "labelPublishServer"); + labelPublishServer.init(currX, currY, 100); + labelPublishServer.setText(lang.getString("PublishServer")); + + currY = currY - labelOffset; + + checkBoxPublishServer.registerGraphicComponent(containerName, + "checkBoxPublishServer"); + checkBoxPublishServer.init(currX, currY); + checkBoxPublishServer.setValue(false); + if ((this->headlessServerMode == true || + (openNetworkSlots == true && parentMenuState != pLanGame)) && + GlobalStaticFlags::isFlagSet(gsft_lan_mode) == false) { + checkBoxPublishServer.setValue(true); + } - listBoxFogOfWar.registerGraphicComponent(containerName,"listBoxFogOfWar"); - listBoxFogOfWar.init(xoffset+100, aPos, 165); - listBoxFogOfWar.pushBackItem(lang.getString("Enabled")); - listBoxFogOfWar.pushBackItem(lang.getString("Explored")); - listBoxFogOfWar.pushBackItem(lang.getString("Disabled")); - listBoxFogOfWar.setSelectedItemIndex(0); + labelGameName.registerGraphicComponent(containerName, "labelGameName"); + labelGameName.init(currX + checkBoxPublishServer.getW() + 5, currY, 200); + // labelGameName.setFont(CoreData::getInstance().getMenuFontBig()); + // labelGameName.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + labelGameName.setText(createGameName()); + labelGameName.setEditable(true); + labelGameName.setMaxEditWidth(20); + labelGameName.setMaxEditRenderWidth(200); + + currY = 730; + currX = 390; + currXLabel = currX + 20; + + checkBoxNetworkPauseGameForLaggedClients.registerGraphicComponent( + containerName, "checkBoxNetworkPauseGameForLaggedClients"); + checkBoxNetworkPauseGameForLaggedClients.init(currX, currY + 2, 16, 16); + checkBoxNetworkPauseGameForLaggedClients.setValue(true); + + labelNetworkPauseGameForLaggedClients.registerGraphicComponent( + containerName, "labelNetworkPauseGameForLaggedClients"); + labelNetworkPauseGameForLaggedClients.init(currXLabel, currY, 80); + labelNetworkPauseGameForLaggedClients.setText( + lang.getString("NetworkPauseGameForLaggedClients")); + currY = currY - lineHeightSmall; + + bool allowInProgressJoin = + Config::getInstance().getBool("EnableJoinInProgressGame", "false"); + labelAllowInGameJoinPlayer.registerGraphicComponent( + containerName, "labelAllowInGameJoinPlayer"); + labelAllowInGameJoinPlayer.init(currXLabel, currY, 80); + labelAllowInGameJoinPlayer.setText(lang.getString("AllowInGameJoinPlayer")); + labelAllowInGameJoinPlayer.setVisible(allowInProgressJoin); + + checkBoxAllowInGameJoinPlayer.registerGraphicComponent( + containerName, "checkBoxAllowInGameJoinPlayer"); + checkBoxAllowInGameJoinPlayer.init(currX, currX, 16, 16); + checkBoxAllowInGameJoinPlayer.setValue(false); + checkBoxAllowInGameJoinPlayer.setVisible(allowInProgressJoin); + + currY = 680; + vector rMultiplier; + for (int i = 0; i < 45; ++i) { + rMultiplier.push_back(floatToStr(0.5f + 0.1f * i, 1)); + } + listBoxFallbackCpuMultiplier.registerGraphicComponent( + containerName, "listBoxFallbackCpuMultiplier"); + listBoxFallbackCpuMultiplier.init(currX - 44, currY + 2, 60, 16); + listBoxFallbackCpuMultiplier.setItems(rMultiplier); + listBoxFallbackCpuMultiplier.setSelectedItem("1.5"); + labelFallbackCpuMultiplier.registerGraphicComponent( + containerName, "labelFallbackCpuMultiplier"); + labelFallbackCpuMultiplier.init(currXLabel, currY, 80); + labelFallbackCpuMultiplier.setText(lang.getString("FallbackCpuMultiplier")); + setSmallFont(labelAllowNativeLanguageTechtree); + currY = currY - lineHeightSmall; + + xoffset = 65; + // MapFilter + labelMapFilter.registerGraphicComponent(containerName, "labelMapFilter"); + labelMapFilter.init(xoffset + 525, mapHeadPos); + labelMapFilter.setText(lang.getString("MapFilter")); + labelMapFilter.setVisible(false); + + labelMap.registerGraphicComponent(containerName, "labelMap"); + labelMap.init(xoffset + 100, mapPos + 20); + labelMap.setText(lang.getString("Map")); + + // Map Filter + listBoxMapFilter.registerGraphicComponent(containerName, + "listBoxMapFilter"); + listBoxMapFilter.init(xoffset + 260, mapPos + labelOffset, 60); + listBoxMapFilter.pushBackItem("-"); + for (int i = 1; i < GameConstants::maxPlayers + 1; ++i) { + listBoxMapFilter.pushBackItem(intToStr(i)); + } + listBoxMapFilter.setSelectedItemIndex(0); + + // map listBox + comboBoxMap.registerGraphicComponent(containerName, "comboBoxMap"); + comboBoxMap.init(xoffset + 100, mapPos, 220); + // put them all in a set, to weed out duplicates (gbm & mgm with same name) + // will also ensure they are alphabetically listed (rather than how the OS + // provides them) + int initialMapSelection = setupMapList(""); + comboBoxMap.setItems(formattedPlayerSortedMaps[0]); + comboBoxMap.setSelectedItemIndex(initialMapSelection); - //tech Tree listBox - labelTechTree.registerGraphicComponent(containerName,"labelTechTree"); - labelTechTree.init(xoffset+325, mapHeadPos); - labelTechTree.setText(lang.getString("TechTree")); + labelMapInfo.registerGraphicComponent(containerName, "labelMapInfo"); + labelMapInfo.init(xoffset + 100, mapPos - labelOffset - 10, 200, + 40); // position is set by update() ! + setSmallFont(labelMapInfo); + + // fog - o - war + // @350 ? 300 ? + labelFogOfWar.registerGraphicComponent(containerName, "labelFogOfWar"); + labelFogOfWar.init(xoffset + 100, aHeadPos, 165); + labelFogOfWar.setText(lang.getString("FogOfWar")); + + listBoxFogOfWar.registerGraphicComponent(containerName, "listBoxFogOfWar"); + listBoxFogOfWar.init(xoffset + 100, aPos, 165); + listBoxFogOfWar.pushBackItem(lang.getString("Enabled")); + listBoxFogOfWar.pushBackItem(lang.getString("Explored")); + listBoxFogOfWar.pushBackItem(lang.getString("Disabled")); + listBoxFogOfWar.setSelectedItemIndex(0); + + // tech Tree listBox + labelTechTree.registerGraphicComponent(containerName, "labelTechTree"); + labelTechTree.init(xoffset + 325, mapHeadPos); + labelTechTree.setText(lang.getString("TechTree")); int initialTechSelection = setupTechList("", true); - listBoxTechTree.registerGraphicComponent(containerName,"listBoxTechTree"); - listBoxTechTree.init(xoffset+325, mapPos, 180); - if(listBoxTechTree.getItemCount() > 0) { - listBoxTechTree.setSelectedItemIndex(initialTechSelection); - } + listBoxTechTree.registerGraphicComponent(containerName, "listBoxTechTree"); + listBoxTechTree.init(xoffset + 325, mapPos, 180); + if (listBoxTechTree.getItemCount() > 0) { + listBoxTechTree.setSelectedItemIndex(initialTechSelection); + } - labelTileset.registerGraphicComponent(containerName,"labelTileset"); - labelTileset.init(xoffset+325, mapHeadPos-44); - labelTileset.setText(lang.getString("Tileset")); + labelTileset.registerGraphicComponent(containerName, "labelTileset"); + labelTileset.init(xoffset + 325, mapHeadPos - 44); + labelTileset.setText(lang.getString("Tileset")); - //tileset listBox - listBoxTileset.registerGraphicComponent(containerName,"listBoxTileset"); - listBoxTileset.init(xoffset+325, mapPos-44, 180); + // tileset listBox + listBoxTileset.registerGraphicComponent(containerName, "listBoxTileset"); + listBoxTileset.init(xoffset + 325, mapPos - 44, 180); - setupTilesetList(""); - Chrono seed(true); - srand((unsigned int)seed.getCurTicks()); + setupTilesetList(""); + Chrono seed(true); + srand((unsigned int)seed.getCurTicks()); - listBoxTileset.setSelectedItemIndex(rand() % listBoxTileset.getItemCount()); + listBoxTileset.setSelectedItemIndex(rand() % listBoxTileset.getItemCount()); - // Save Setup - currY=mapHeadPos-100; - currX=xoffset+325; + // Save Setup + currY = mapHeadPos - 100; + currX = xoffset + 325; - comboBoxLoadSetup.registerGraphicComponent(containerName,"comboBoxLoadSetup"); + comboBoxLoadSetup.registerGraphicComponent(containerName, + "comboBoxLoadSetup"); comboBoxLoadSetup.init(currX, currY, 220); - loadSavedSetupNames(); - comboBoxLoadSetup.setItems(savedSetupFilenames); - - currY = currY - labelOffset; - - buttonDeleteSetup.registerGraphicComponent(containerName,"buttonDeleteSetup"); - buttonDeleteSetup.init(currX, currY, 110); - buttonDeleteSetup.setText(lang.getString("Delete")); - buttonLoadSetup.registerGraphicComponent(containerName,"buttonLoadSetup"); - buttonLoadSetup.init(currX+110, currY, 110); - buttonLoadSetup.setText(lang.getString("Load")); - - currY = currY - labelOffset; - - labelSaveSetupName.registerGraphicComponent(containerName,"labelSaveSetupName"); - labelSaveSetupName.init(currX,currY, 110); - labelSaveSetupName.setText(""); - labelSaveSetupName.setEditable(true); - labelSaveSetupName.setMaxEditWidth(16); - labelSaveSetupName.setMaxEditRenderWidth(labelSaveSetupName.getW()); - labelSaveSetupName.setBackgroundColor(Vec4f(230,230,230,0.4)); - labelSaveSetupName.setRenderBackground(true); - - buttonSaveSetup.registerGraphicComponent(containerName,"buttonSaveSetup"); - buttonSaveSetup.init(currX+110, currY, 110); - buttonSaveSetup.setText(lang.getString("Save")); - - // Toy Block - currY=mapHeadPos; - currX=750; - currXLabel=currX+20; - - checkBoxAllowTeamUnitSharing.registerGraphicComponent(containerName,"checkBoxAllowTeamUnitSharing"); - checkBoxAllowTeamUnitSharing.init(currX, currY+2,16,16); - checkBoxAllowTeamUnitSharing.setValue(false); - checkBoxAllowTeamUnitSharing.setVisible(true); - - labelAllowTeamUnitSharing.registerGraphicComponent(containerName,"labelAllowTeamUnitSharing"); - labelAllowTeamUnitSharing.init(currXLabel, currY, 80); - labelAllowTeamUnitSharing.setText(lang.getString("AllowTeamUnitSharing")); - labelAllowTeamUnitSharing.setVisible(true); - setSmallFont(labelAllowTeamUnitSharing); - currY = currY - lineHeightSmall; - - checkBoxAllowTeamResourceSharing.registerGraphicComponent(containerName,"checkBoxAllowTeamResourceSharing"); - checkBoxAllowTeamResourceSharing.init(currX, currY+2,16,16); - checkBoxAllowTeamResourceSharing.setValue(false); - checkBoxAllowTeamResourceSharing.setVisible(true); - labelAllowTeamResourceSharing.registerGraphicComponent(containerName,"labelAllowTeamResourceSharing"); - labelAllowTeamResourceSharing.init(currXLabel, currY, 80); - labelAllowTeamResourceSharing.setText(lang.getString("AllowTeamResourceSharing")); - labelAllowTeamResourceSharing.setVisible(true); - setSmallFont(labelAllowTeamResourceSharing); - currY = currY - lineHeightSmall; - - checkBoxAllowNativeLanguageTechtree.registerGraphicComponent(containerName,"checkBoxAllowNativeLanguageTechtree"); - checkBoxAllowNativeLanguageTechtree.init(currX, currY+2,16,16); - checkBoxAllowNativeLanguageTechtree.setValue(false); - - labelAllowNativeLanguageTechtree.registerGraphicComponent(containerName,"labelAllowNativeLanguageTechtree"); - labelAllowNativeLanguageTechtree.init(currXLabel, currY, 80); - labelAllowNativeLanguageTechtree.setText(lang.getString("AllowNativeLanguageTechtree")); - setSmallFont(labelAllowNativeLanguageTechtree); - currY = currY - lineHeightSmall; - - // Allow Observers - checkBoxAllowObservers.registerGraphicComponent(containerName,"checkBoxAllowObservers"); - checkBoxAllowObservers.init(currX, currY+2,16,16); - checkBoxAllowObservers.setValue(true); - - labelAllowObservers.registerGraphicComponent(containerName,"labelAllowObservers"); - labelAllowObservers.init(currXLabel, currY, 80); - labelAllowObservers.setText(lang.getString("AllowObservers")); - setSmallFont(labelAllowNativeLanguageTechtree); - currY = currY - lineHeightSmall; - - checkBoxEnableSwitchTeamMode.registerGraphicComponent(containerName,"checkBoxEnableSwitchTeamMode"); - checkBoxEnableSwitchTeamMode.init(currX, currY+2,16,16); - checkBoxEnableSwitchTeamMode.setValue(false); - labelEnableSwitchTeamMode.registerGraphicComponent(containerName,"labelEnableSwitchTeamMode"); - labelEnableSwitchTeamMode.init(currXLabel, currY); - labelEnableSwitchTeamMode.setText(lang.getString("EnableSwitchTeamMode")); - setSmallFont(labelEnableSwitchTeamMode); - currY=currY-lineHeightSmall; - - listBoxAISwitchTeamAcceptPercent.registerGraphicComponent(containerName,"listBoxAISwitchTeamAcceptPercent"); - listBoxAISwitchTeamAcceptPercent.init(currX-44, currY+2, 60,16); - for(int i = 0; i <= 100; i = i + 10) { - listBoxAISwitchTeamAcceptPercent.pushBackItem(intToStr(i)); - } - listBoxAISwitchTeamAcceptPercent.setSelectedItem(intToStr(30)); - listBoxAISwitchTeamAcceptPercent.setVisible(false); - labelAISwitchTeamAcceptPercent.registerGraphicComponent(containerName,"labelAISwitchTeamAcceptPercent"); - labelAISwitchTeamAcceptPercent.init(currXLabel, currY, 80); - labelAISwitchTeamAcceptPercent.setText(lang.getString("AISwitchTeamAcceptPercent")); - labelAISwitchTeamAcceptPercent.setVisible(false); - setSmallFont(labelEnableSwitchTeamMode); - currY=currY-lineHeightSmall; - - // Network Scenario - checkBoxScenario.registerGraphicComponent(containerName,"checkBoxScenario"); - checkBoxScenario.init(currX, currY+2,16,16); + loadSavedSetupNames(); + comboBoxLoadSetup.setItems(savedSetupFilenames); + + currY = currY - labelOffset; + + buttonDeleteSetup.registerGraphicComponent(containerName, + "buttonDeleteSetup"); + buttonDeleteSetup.init(currX, currY, 110); + buttonDeleteSetup.setText(lang.getString("Delete")); + buttonLoadSetup.registerGraphicComponent(containerName, "buttonLoadSetup"); + buttonLoadSetup.init(currX + 110, currY, 110); + buttonLoadSetup.setText(lang.getString("Load")); + + currY = currY - labelOffset; + + labelSaveSetupName.registerGraphicComponent(containerName, + "labelSaveSetupName"); + labelSaveSetupName.init(currX, currY, 110); + labelSaveSetupName.setText(""); + labelSaveSetupName.setEditable(true); + labelSaveSetupName.setMaxEditWidth(16); + labelSaveSetupName.setMaxEditRenderWidth(labelSaveSetupName.getW()); + labelSaveSetupName.setBackgroundColor(Vec4f(230, 230, 230, 0.4)); + labelSaveSetupName.setRenderBackground(true); + + buttonSaveSetup.registerGraphicComponent(containerName, "buttonSaveSetup"); + buttonSaveSetup.init(currX + 110, currY, 110); + buttonSaveSetup.setText(lang.getString("Save")); + + // Toy Block + currY = mapHeadPos; + currX = 750; + currXLabel = currX + 20; + + checkBoxAllowTeamUnitSharing.registerGraphicComponent( + containerName, "checkBoxAllowTeamUnitSharing"); + checkBoxAllowTeamUnitSharing.init(currX, currY + 2, 16, 16); + checkBoxAllowTeamUnitSharing.setValue(false); + checkBoxAllowTeamUnitSharing.setVisible(true); + + labelAllowTeamUnitSharing.registerGraphicComponent( + containerName, "labelAllowTeamUnitSharing"); + labelAllowTeamUnitSharing.init(currXLabel, currY, 80); + labelAllowTeamUnitSharing.setText(lang.getString("AllowTeamUnitSharing")); + labelAllowTeamUnitSharing.setVisible(true); + setSmallFont(labelAllowTeamUnitSharing); + currY = currY - lineHeightSmall; + + checkBoxAllowTeamResourceSharing.registerGraphicComponent( + containerName, "checkBoxAllowTeamResourceSharing"); + checkBoxAllowTeamResourceSharing.init(currX, currY + 2, 16, 16); + checkBoxAllowTeamResourceSharing.setValue(false); + checkBoxAllowTeamResourceSharing.setVisible(true); + labelAllowTeamResourceSharing.registerGraphicComponent( + containerName, "labelAllowTeamResourceSharing"); + labelAllowTeamResourceSharing.init(currXLabel, currY, 80); + labelAllowTeamResourceSharing.setText( + lang.getString("AllowTeamResourceSharing")); + labelAllowTeamResourceSharing.setVisible(true); + setSmallFont(labelAllowTeamResourceSharing); + currY = currY - lineHeightSmall; + + checkBoxAllowNativeLanguageTechtree.registerGraphicComponent( + containerName, "checkBoxAllowNativeLanguageTechtree"); + checkBoxAllowNativeLanguageTechtree.init(currX, currY + 2, 16, 16); + checkBoxAllowNativeLanguageTechtree.setValue(false); + + labelAllowNativeLanguageTechtree.registerGraphicComponent( + containerName, "labelAllowNativeLanguageTechtree"); + labelAllowNativeLanguageTechtree.init(currXLabel, currY, 80); + labelAllowNativeLanguageTechtree.setText( + lang.getString("AllowNativeLanguageTechtree")); + setSmallFont(labelAllowNativeLanguageTechtree); + currY = currY - lineHeightSmall; + + // Allow Observers + checkBoxAllowObservers.registerGraphicComponent(containerName, + "checkBoxAllowObservers"); + checkBoxAllowObservers.init(currX, currY + 2, 16, 16); + checkBoxAllowObservers.setValue(true); + + labelAllowObservers.registerGraphicComponent(containerName, + "labelAllowObservers"); + labelAllowObservers.init(currXLabel, currY, 80); + labelAllowObservers.setText(lang.getString("AllowObservers")); + setSmallFont(labelAllowNativeLanguageTechtree); + currY = currY - lineHeightSmall; + + checkBoxEnableSwitchTeamMode.registerGraphicComponent( + containerName, "checkBoxEnableSwitchTeamMode"); + checkBoxEnableSwitchTeamMode.init(currX, currY + 2, 16, 16); + checkBoxEnableSwitchTeamMode.setValue(false); + labelEnableSwitchTeamMode.registerGraphicComponent( + containerName, "labelEnableSwitchTeamMode"); + labelEnableSwitchTeamMode.init(currXLabel, currY); + labelEnableSwitchTeamMode.setText(lang.getString("EnableSwitchTeamMode")); + setSmallFont(labelEnableSwitchTeamMode); + currY = currY - lineHeightSmall; + + listBoxAISwitchTeamAcceptPercent.registerGraphicComponent( + containerName, "listBoxAISwitchTeamAcceptPercent"); + listBoxAISwitchTeamAcceptPercent.init(currX - 44, currY + 2, 60, 16); + for (int i = 0; i <= 100; i = i + 10) { + listBoxAISwitchTeamAcceptPercent.pushBackItem(intToStr(i)); + } + listBoxAISwitchTeamAcceptPercent.setSelectedItem(intToStr(30)); + listBoxAISwitchTeamAcceptPercent.setVisible(false); + labelAISwitchTeamAcceptPercent.registerGraphicComponent( + containerName, "labelAISwitchTeamAcceptPercent"); + labelAISwitchTeamAcceptPercent.init(currXLabel, currY, 80); + labelAISwitchTeamAcceptPercent.setText( + lang.getString("AISwitchTeamAcceptPercent")); + labelAISwitchTeamAcceptPercent.setVisible(false); + setSmallFont(labelEnableSwitchTeamMode); + currY = currY - lineHeightSmall; + + // Network Scenario + checkBoxScenario.registerGraphicComponent(containerName, + "checkBoxScenario"); + checkBoxScenario.init(currX, currY + 2, 16, 16); checkBoxScenario.setValue(false); - labelScenario.registerGraphicComponent(containerName,"labelScenario"); + labelScenario.registerGraphicComponent(containerName, "labelScenario"); labelScenario.init(currXLabel, currY); labelScenario.setText(lang.getString("NetworkScenarios")); - setSmallFont(labelAllowNativeLanguageTechtree); - currY = currY - lineHeightSmall; - listBoxScenario.registerGraphicComponent(containerName,"listBoxScenario"); - listBoxScenario.init(currX, currY,190,16); + setSmallFont(labelAllowNativeLanguageTechtree); + currY = currY - lineHeightSmall; + listBoxScenario.registerGraphicComponent(containerName, "listBoxScenario"); + listBoxScenario.init(currX, currY, 190, 16); - //scenario listbox + // scenario listbox vector resultsScenarios; - findDirs(dirList, resultsScenarios); - // Filter out only scenarios with no network slots - for(int i= 0; i < (int)resultsScenarios.size(); ++i) { - string scenario = resultsScenarios[i]; - string file = Scenario::getScenarioPath(dirList, scenario); - - try { - if(file != "") { - bool isTutorial = Scenario::isGameTutorial(file); - Scenario::loadScenarioInfo(file, &scenarioInfo, isTutorial); - - bool isNetworkScenario = false; - for(unsigned int j = 0; isNetworkScenario == false && j < (unsigned int)GameConstants::maxPlayers; ++j) { - if(scenarioInfo.factionControls[j] == ctNetwork) { - isNetworkScenario = true; - } - } - if(isNetworkScenario == true) { - scenarioFiles.push_back(scenario); - } - } - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - 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()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - - showGeneralError=true; - generalErrorToShow = szBuf; - //throw megaglest_runtime_error(szBuf); - } - } - resultsScenarios.clear(); - for(int i = 0; i < (int)scenarioFiles.size(); ++i) { - resultsScenarios.push_back(formatString(scenarioFiles[i])); - } + findDirs(dirList, resultsScenarios); + // Filter out only scenarios with no network slots + for (int i = 0; i < (int)resultsScenarios.size(); ++i) { + string scenario = resultsScenarios[i]; + string file = Scenario::getScenarioPath(dirList, scenario); + + try { + if (file != "") { + bool isTutorial = Scenario::isGameTutorial(file); + Scenario::loadScenarioInfo(file, &scenarioInfo, isTutorial); + + bool isNetworkScenario = false; + for (unsigned int j = 0; isNetworkScenario == false && + j < (unsigned int)GameConstants::maxPlayers; + ++j) { + if (scenarioInfo.factionControls[j] == ctNetwork) { + isNetworkScenario = true; + } + } + if (isNetworkScenario == true) { + scenarioFiles.push_back(scenario); + } + } + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + 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()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + showGeneralError = true; + generalErrorToShow = szBuf; + // throw megaglest_runtime_error(szBuf); + } + } + resultsScenarios.clear(); + for (int i = 0; i < (int)scenarioFiles.size(); ++i) { + resultsScenarios.push_back(formatString(scenarioFiles[i])); + } listBoxScenario.setItems(resultsScenarios); - if(resultsScenarios.empty() == true) { - checkBoxScenario.setEnabled(false); + if (resultsScenarios.empty() == true) { + checkBoxScenario.setEnabled(false); } - currY = currY - lineHeightSmall; - buttonShowLanInfo .registerGraphicComponent(containerName,"buttonShowLanInfo"); - buttonShowLanInfo.init(currX, currY, 200,16); - buttonShowLanInfo.setText(lang.getString("ShowIP")); - currY = currY - lineHeightSmall; - - // Advanced Options - labelAdvanced.registerGraphicComponent(containerName,"labelAdvanced"); - labelAdvanced.init(750, 80, 80); - labelAdvanced.setText(lang.getString("AdvancedGameOptions")); - - checkBoxAdvanced.registerGraphicComponent(containerName,"checkBoxAdvanced"); - checkBoxAdvanced.init(750, 80-labelOffset); - checkBoxAdvanced.setValue(false); - - - //list boxes - xoffset=5; - int rowHeight=22; - for(int i=0; i controlItems; + vector controlItems; controlItems.push_back(lang.getString("Closed")); - controlItems.push_back(lang.getString("CpuEasy")); - controlItems.push_back(lang.getString("Cpu")); + controlItems.push_back(lang.getString("CpuEasy")); + controlItems.push_back(lang.getString("Cpu")); controlItems.push_back(lang.getString("CpuUltra")); controlItems.push_back(lang.getString("CpuMega")); - controlItems.push_back(lang.getString("Network")); - controlItems.push_back(lang.getString("NetworkUnassigned")); - controlItems.push_back(lang.getString("Human")); - - if(config.getBool("EnableNetworkCpu","false") == true) { - controlItems.push_back(lang.getString("NetworkCpuEasy")); - controlItems.push_back(lang.getString("NetworkCpu")); - controlItems.push_back(lang.getString("NetworkCpuUltra")); - controlItems.push_back(lang.getString("NetworkCpuMega")); - } - - vector teamItems; - for(int i = 1; i <= GameConstants::maxPlayers; ++i) { - teamItems.push_back(intToStr(i)); - } - for(int i = GameConstants::maxPlayers + 1; i <= GameConstants::maxPlayers + GameConstants::specialFactions; ++i) { - teamItems.push_back(intToStr(i)); - } - - reloadFactions(false,""); - - if(factionFiles.empty() == true) { - showGeneralError=true; - generalErrorToShow = "[#1] There are no factions for the tech tree [" + techTreeFiles[listBoxTechTree.getSelectedItemIndex()] + "]"; - } - - for(int i=0; i < GameConstants::maxPlayers; ++i) { - labelPlayerStatus[i].setText(" "); - labelPlayerStatus[i].setTexture(CoreData::getInstance().getStatusReadyTexture()); - labelPlayerStatus[i].setH(16); - labelPlayerStatus[i].setW(12); - - //labelPlayers[i].setText(lang.getString("Player")+" "+intToStr(i)); - labelPlayers[i].setText(intToStr(i+1)); - labelPlayerNames[i].setText("*"); - labelPlayerNames[i].setMaxEditWidth(16); - labelPlayerNames[i].setMaxEditRenderWidth(127); - - listBoxTeams[i].setItems(teamItems); - listBoxTeams[i].setSelectedItemIndex(i); - lastSelectedTeamIndex[i] = listBoxTeams[i].getSelectedItemIndex(); - - listBoxControls[i].setItems(controlItems); - listBoxRMultiplier[i].setItems(rMultiplier); - listBoxRMultiplier[i].setSelectedItem("1.0"); - labelNetStatus[i].setText(""); - } - - loadMapInfo(Config::getMapPath(getCurrentMapFile()), &mapInfo, true,true); - labelMapInfo.setText(mapInfo.desc); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //init controllers - if(serverInitError == false) { - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - if(serverInterface == NULL) { - throw megaglest_runtime_error("serverInterface == NULL"); - } - if(this->headlessServerMode == true) { - listBoxControls[0].setSelectedItemIndex(ctNetwork); - updateResourceMultiplier(0); - } - else { - setSlotHuman(0); - updateResourceMultiplier(0); - } - labelPlayerNames[0].setText(""); - labelPlayerNames[0].setText(getHumanPlayerName()); - - if(openNetworkSlots == true) { - for(int i= 1; i< mapInfo.players; ++i){ - listBoxControls[i].setSelectedItemIndex(ctNetwork); - } - } - else{ - listBoxControls[1].setSelectedItemIndex(ctCpu); - } - updateControlers(); - updateNetworkSlots(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - // Ensure we have set the gamesettings at least once - GameSettings gameSettings; - copyToGameSettings(&gameSettings); - - serverInterface->setGameSettings(&gameSettings,false); - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - updateAllResourceMultiplier(); - - // write hint to console: - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - - console.addLine(lang.getString("ToSwitchOffMusicPress") + " - \"" + configKeys.getString("ToggleMusic") + "\""); - - chatManager.init(&console, -1,true); - - GraphicComponent::applyAllCustomProperties(containerName); - - static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); - publishToMasterserverThread = new SimpleTaskThread(this,0,300,false,(void *)tnt_MASTERSERVER); - publishToMasterserverThread->setUniqueID(mutexOwnerId); - - static string mutexOwnerId2 = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); - publishToClientsThread = new SimpleTaskThread(this,0,200,false,(void *)tnt_CLIENTS,false); - publishToClientsThread->setUniqueID(mutexOwnerId2); - - publishToMasterserverThread->start(); - publishToClientsThread->start(); - - if(openNetworkSlots == true) { - string data_path = getGameReadWritePath(GameConstants::path_data_CacheLookupKey); - - if(fileExists(data_path + DEFAULT_NETWORK_SETUP_FILENAME) == true) - loadGameSettings(data_path + DEFAULT_NETWORK_SETUP_FILENAME); - } - else { - string data_path = getGameReadWritePath(GameConstants::path_data_CacheLookupKey); - - if(fileExists(data_path + DEFAULT_SETUP_FILENAME) == true) - loadGameSettings(data_path + DEFAULT_SETUP_FILENAME); - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - - throw megaglest_runtime_error(szBuf); - } -} + controlItems.push_back(lang.getString("Network")); + controlItems.push_back(lang.getString("NetworkUnassigned")); + controlItems.push_back(lang.getString("Human")); + + if (config.getBool("EnableNetworkCpu", "false") == true) { + controlItems.push_back(lang.getString("NetworkCpuEasy")); + controlItems.push_back(lang.getString("NetworkCpu")); + controlItems.push_back(lang.getString("NetworkCpuUltra")); + controlItems.push_back(lang.getString("NetworkCpuMega")); + } + + vector teamItems; + for (int i = 1; i <= GameConstants::maxPlayers; ++i) { + teamItems.push_back(intToStr(i)); + } + for (int i = GameConstants::maxPlayers + 1; + i <= GameConstants::maxPlayers + GameConstants::specialFactions; ++i) { + teamItems.push_back(intToStr(i)); + } + + reloadFactions(false, ""); + + if (factionFiles.empty() == true) { + showGeneralError = true; + generalErrorToShow = + "[#1] There are no factions for the tech tree [" + + techTreeFiles[listBoxTechTree.getSelectedItemIndex()] + "]"; + } + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + labelPlayerStatus[i].setText(" "); + labelPlayerStatus[i].setTexture( + CoreData::getInstance().getStatusReadyTexture()); + labelPlayerStatus[i].setH(16); + labelPlayerStatus[i].setW(12); + + // labelPlayers[i].setText(lang.getString("Player")+" "+intToStr(i)); + labelPlayers[i].setText(intToStr(i + 1)); + labelPlayerNames[i].setText("*"); + labelPlayerNames[i].setMaxEditWidth(16); + labelPlayerNames[i].setMaxEditRenderWidth(127); + + listBoxTeams[i].setItems(teamItems); + listBoxTeams[i].setSelectedItemIndex(i); + lastSelectedTeamIndex[i] = listBoxTeams[i].getSelectedItemIndex(); + + listBoxControls[i].setItems(controlItems); + listBoxRMultiplier[i].setItems(rMultiplier); + listBoxRMultiplier[i].setSelectedItem("1.0"); + labelNetStatus[i].setText(""); + } + loadMapInfo(Config::getMapPath(getCurrentMapFile()), &mapInfo, true, true); + labelMapInfo.setText(mapInfo.desc); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // init controllers + if (serverInitError == false) { + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + if (serverInterface == NULL) { + throw megaglest_runtime_error("serverInterface == NULL"); + } + if (this->headlessServerMode == true) { + listBoxControls[0].setSelectedItemIndex(ctNetwork); + updateResourceMultiplier(0); + } else { + setSlotHuman(0); + updateResourceMultiplier(0); + } + labelPlayerNames[0].setText(""); + labelPlayerNames[0].setText(getHumanPlayerName()); + + if (openNetworkSlots == true) { + for (int i = 1; i < mapInfo.players; ++i) { + listBoxControls[i].setSelectedItemIndex(ctNetwork); + } + } else { + listBoxControls[1].setSelectedItemIndex(ctCpu); + } + updateControlers(); + updateNetworkSlots(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // Ensure we have set the gamesettings at least once + GameSettings gameSettings; + copyToGameSettings(&gameSettings); + + serverInterface->setGameSettings(&gameSettings, false); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + updateAllResourceMultiplier(); + + // write hint to console: + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + + console.addLine(lang.getString("ToSwitchOffMusicPress") + " - \"" + + configKeys.getString("ToggleMusic") + "\""); + + chatManager.init(&console, -1, true); + + GraphicComponent::applyAllCustomProperties(containerName); + + static string mutexOwnerId = + string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + + intToStr(__LINE__); + publishToMasterserverThread = + new SimpleTaskThread(this, 0, 300, false, (void *)tnt_MASTERSERVER); + publishToMasterserverThread->setUniqueID(mutexOwnerId); + + static string mutexOwnerId2 = + string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + + intToStr(__LINE__); + publishToClientsThread = + new SimpleTaskThread(this, 0, 200, false, (void *)tnt_CLIENTS, false); + publishToClientsThread->setUniqueID(mutexOwnerId2); + + publishToMasterserverThread->start(); + publishToClientsThread->start(); + + if (openNetworkSlots == true) { + string data_path = + getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + + if (fileExists(data_path + DEFAULT_NETWORK_SETUP_FILENAME) == true) + loadGameSettings(data_path + DEFAULT_NETWORK_SETUP_FILENAME); + } else { + string data_path = + getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + + if (fileExists(data_path + DEFAULT_SETUP_FILENAME) == true) + loadGameSettings(data_path + DEFAULT_SETUP_FILENAME); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + throw megaglest_runtime_error(szBuf); + } +} -string MenuStateCustomGame::createGameName(string controllingPlayer){ - Config &config = Config::getInstance(); - string serverTitle=config.getString("ServerTitle",""); - - if(serverTitle!="" && controllingPlayer == ""){ - return serverTitle; - } - else if (this->headlessServerMode == true) { - if (controllingPlayer != "") { - return controllingPlayer + " controls"; - } else { - return "[H] " + defaultPlayerName; - } - } else { - string defaultPlayerNameEnd = defaultPlayerName.substr(defaultPlayerName.size()-1, 1); - if(defaultPlayerNameEnd == "s") { - return defaultPlayerName+"' game"; - } else { - return defaultPlayerName+"'s game"; - } - } +string MenuStateCustomGame::createGameName(string controllingPlayer) { + Config &config = Config::getInstance(); + string serverTitle = config.getString("ServerTitle", ""); + + if (serverTitle != "" && controllingPlayer == "") { + return serverTitle; + } else if (this->headlessServerMode == true) { + if (controllingPlayer != "") { + return controllingPlayer + " controls"; + } else { + return "[H] " + defaultPlayerName; + } + } else { + string defaultPlayerNameEnd = + defaultPlayerName.substr(defaultPlayerName.size() - 1, 1); + if (defaultPlayerNameEnd == "s") { + return defaultPlayerName + "' game"; + } else { + return defaultPlayerName + "'s game"; + } + } } void MenuStateCustomGame::reloadUI() { - Lang &lang= Lang::getInstance(); - Config &config = Config::getInstance(); + Lang &lang = Lang::getInstance(); + Config &config = Config::getInstance(); - console.resetFonts(); - mainMessageBox.init(lang.getString("Ok"),500,300); + console.resetFonts(); + mainMessageBox.init(lang.getString("Ok"), 500, 300); - labelMap.setText(lang.getString("Map")); + labelMap.setText(lang.getString("Map")); - labelMapFilter.setText(lang.getString("MapFilter")); + labelMapFilter.setText(lang.getString("MapFilter")); - labelTileset.setText(lang.getString("Tileset")); + labelTileset.setText(lang.getString("Tileset")); - labelTechTree.setText(lang.getString("TechTree")); + labelTechTree.setText(lang.getString("TechTree")); - labelAllowNativeLanguageTechtree.setText(lang.getString("AllowNativeLanguageTechtree")); + labelAllowNativeLanguageTechtree.setText( + lang.getString("AllowNativeLanguageTechtree")); - labelFogOfWar.setText(lang.getString("FogOfWar")); + labelFogOfWar.setText(lang.getString("FogOfWar")); - buttonSaveSetup.setText(lang.getString("Save")); - buttonLoadSetup.setText(lang.getString("Load")); - buttonDeleteSetup.setText(lang.getString("Delete")); + buttonSaveSetup.setText(lang.getString("Save")); + buttonLoadSetup.setText(lang.getString("Load")); + buttonDeleteSetup.setText(lang.getString("Delete")); - std::vector listBoxData; - listBoxData.push_back(lang.getString("Enabled")); - listBoxData.push_back(lang.getString("Explored")); - listBoxData.push_back(lang.getString("Disabled")); - listBoxFogOfWar.setItems(listBoxData); + std::vector listBoxData; + listBoxData.push_back(lang.getString("Enabled")); + listBoxData.push_back(lang.getString("Explored")); + listBoxData.push_back(lang.getString("Disabled")); + listBoxFogOfWar.setItems(listBoxData); - // Allow Observers - labelAllowObservers.setText(lang.getString("AllowObservers")); + // Allow Observers + labelAllowObservers.setText(lang.getString("AllowObservers")); - // Allow Switch Team Mode - labelEnableSwitchTeamMode.setText(lang.getString("EnableSwitchTeamMode")); + // Allow Switch Team Mode + labelEnableSwitchTeamMode.setText(lang.getString("EnableSwitchTeamMode")); - labelAllowInGameJoinPlayer.setText(lang.getString("AllowInGameJoinPlayer")); + labelAllowInGameJoinPlayer.setText(lang.getString("AllowInGameJoinPlayer")); - labelAllowTeamUnitSharing.setText(lang.getString("AllowTeamUnitSharing")); - labelAllowTeamResourceSharing.setText(lang.getString("AllowTeamResourceSharing")); + labelAllowTeamUnitSharing.setText(lang.getString("AllowTeamUnitSharing")); + labelAllowTeamResourceSharing.setText( + lang.getString("AllowTeamResourceSharing")); - labelAISwitchTeamAcceptPercent.setText(lang.getString("AISwitchTeamAcceptPercent")); + labelAISwitchTeamAcceptPercent.setText( + lang.getString("AISwitchTeamAcceptPercent")); - listBoxData.clear(); + listBoxData.clear(); - // Advanced Options - labelAdvanced.setText(lang.getString("AdvancedGameOptions")); + // Advanced Options + labelAdvanced.setText(lang.getString("AdvancedGameOptions")); - labelPublishServer.setText(lang.getString("PublishServer")); + labelPublishServer.setText(lang.getString("PublishServer")); - labelGameName.setFont(CoreData::getInstance().getMenuFontBig()); - labelGameName.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + labelGameName.setFont(CoreData::getInstance().getMenuFontBig()); + labelGameName.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - labelGameName.setText(createGameName()); + labelGameName.setText(createGameName()); - labelNetworkPauseGameForLaggedClients.setText(lang.getString("NetworkPauseGameForLaggedClients")); + labelNetworkPauseGameForLaggedClients.setText( + lang.getString("NetworkPauseGameForLaggedClients")); - for(int i=0; i < GameConstants::maxPlayers; ++i) { - buttonBlockPlayers[i].setText(lang.getString("BlockPlayer")); - } + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + buttonBlockPlayers[i].setText(lang.getString("BlockPlayer")); + } - labelControl.setText(lang.getString("Control")); + labelControl.setText(lang.getString("Control")); - labelFaction.setText(lang.getString("Faction")); + labelFaction.setText(lang.getString("Faction")); - labelTeam.setText(lang.getString("Team")); + labelTeam.setText(lang.getString("Team")); - labelControl.setFont(CoreData::getInstance().getMenuFontBig()); - labelControl.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - labelRMultiplier.setFont(CoreData::getInstance().getMenuFontBig()); - labelRMultiplier.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - labelFaction.setFont(CoreData::getInstance().getMenuFontBig()); - labelFaction.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - labelTeam.setFont(CoreData::getInstance().getMenuFontBig()); - labelTeam.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + labelControl.setFont(CoreData::getInstance().getMenuFontBig()); + labelControl.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + labelRMultiplier.setFont(CoreData::getInstance().getMenuFontBig()); + labelRMultiplier.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + labelFaction.setFont(CoreData::getInstance().getMenuFontBig()); + labelFaction.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + labelTeam.setFont(CoreData::getInstance().getMenuFontBig()); + labelTeam.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - //texts - buttonClearBlockedPlayers.setText(lang.getString("BlockPlayerClear")); - buttonReturn.setText(lang.getString("Return")); - buttonPlayNow.setText(lang.getString("PlayNow")); + // texts + buttonClearBlockedPlayers.setText(lang.getString("BlockPlayerClear")); + buttonReturn.setText(lang.getString("Return")); + buttonPlayNow.setText(lang.getString("PlayNow")); - vector controlItems; - controlItems.push_back(lang.getString("Closed")); - controlItems.push_back(lang.getString("CpuEasy")); - controlItems.push_back(lang.getString("Cpu")); - controlItems.push_back(lang.getString("CpuUltra")); - controlItems.push_back(lang.getString("CpuMega")); - controlItems.push_back(lang.getString("Network")); - controlItems.push_back(lang.getString("NetworkUnassigned")); - controlItems.push_back(lang.getString("Human")); + vector controlItems; + controlItems.push_back(lang.getString("Closed")); + controlItems.push_back(lang.getString("CpuEasy")); + controlItems.push_back(lang.getString("Cpu")); + controlItems.push_back(lang.getString("CpuUltra")); + controlItems.push_back(lang.getString("CpuMega")); + controlItems.push_back(lang.getString("Network")); + controlItems.push_back(lang.getString("NetworkUnassigned")); + controlItems.push_back(lang.getString("Human")); - if(config.getBool("EnableNetworkCpu","false") == true) { - controlItems.push_back(lang.getString("NetworkCpuEasy")); - controlItems.push_back(lang.getString("NetworkCpu")); - controlItems.push_back(lang.getString("NetworkCpuUltra")); - controlItems.push_back(lang.getString("NetworkCpuMega")); - } + if (config.getBool("EnableNetworkCpu", "false") == true) { + controlItems.push_back(lang.getString("NetworkCpuEasy")); + controlItems.push_back(lang.getString("NetworkCpu")); + controlItems.push_back(lang.getString("NetworkCpuUltra")); + controlItems.push_back(lang.getString("NetworkCpuMega")); + } - for(int i=0; i < GameConstants::maxPlayers; ++i) { - labelPlayers[i].setText(intToStr(i+1)); + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + labelPlayers[i].setText(intToStr(i + 1)); - listBoxControls[i].setItems(controlItems); - } + listBoxControls[i].setItems(controlItems); + } - labelFallbackCpuMultiplier.setText(lang.getString("FallbackCpuMultiplier")); + labelFallbackCpuMultiplier.setText(lang.getString("FallbackCpuMultiplier")); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - vector playerStatuses; - playerStatuses.push_back(lang.getString("PlayerStatusSetup")); - playerStatuses.push_back(lang.getString("PlayerStatusBeRightBack")); - playerStatuses.push_back(lang.getString("PlayerStatusReady")); - listBoxPlayerStatus.setItems(playerStatuses); + vector playerStatuses; + playerStatuses.push_back(lang.getString("PlayerStatusSetup")); + playerStatuses.push_back(lang.getString("PlayerStatusBeRightBack")); + playerStatuses.push_back(lang.getString("PlayerStatusReady")); + listBoxPlayerStatus.setItems(playerStatuses); - labelScenario.setText(lang.getString("NetworkScenarios")); - buttonShowLanInfo.setText(lang.getString("LanIP")); + labelScenario.setText(lang.getString("NetworkScenarios")); + buttonShowLanInfo.setText(lang.getString("LanIP")); - reloadFactions(true,(checkBoxScenario.getValue() == true ? scenarioFiles[listBoxScenario.getSelectedItemIndex()] : "")); + reloadFactions(true, + (checkBoxScenario.getValue() == true + ? scenarioFiles[listBoxScenario.getSelectedItemIndex()] + : "")); - // write hint to console: - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); + // write hint to console: + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); - console.addLine(lang.getString("ToSwitchOffMusicPress") + " - \"" + configKeys.getString("ToggleMusic") + "\""); + console.addLine(lang.getString("ToSwitchOffMusicPress") + " - \"" + + configKeys.getString("ToggleMusic") + "\""); - chatManager.init(&console, -1,true); + chatManager.init(&console, -1, true); - GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); + GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); } void MenuStateCustomGame::cleanupThread(SimpleTaskThread **thread) { - //printf("LINE: %d *thread = %p\n",__LINE__,*thread); + // printf("LINE: %d *thread = %p\n",__LINE__,*thread); + + if (thread != NULL && *thread != NULL) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\n\n#1 cleanupThread callingThread [%p]\n", *thread); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + SimpleTaskThread *threadPtr = *thread; + int value = threadPtr->getUserdataAsInt(); + THREAD_NOTIFIER_TYPE threadType = (THREAD_NOTIFIER_TYPE)value; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\n\n#1. cleanupThread callingThread [%p] value = %d\n", *thread, + value); + + needToBroadcastServerSettings = false; + needToRepublishToMasterserver = false; + lastNetworkPing = time(NULL); + threadPtr->setThreadOwnerValid(false); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\n\n#1.. cleanupThread callingThread [%p] value = %d\n", *thread, + value); + + if (forceWaitForShutdown == true) { + time_t elapsed = time(NULL); + threadPtr->signalQuit(); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\n\n#1a cleanupThread callingThread [%p]\n", *thread); + + for (; (threadPtr->canShutdown(false) == false || + threadPtr->getRunningStatus() == true) && + difftime((long int)time(NULL), elapsed) <= 15;) { + // sleep(150); + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\n\n#1b cleanupThread callingThread [%p]\n", *thread); + + if (threadPtr->canShutdown(true) == true && + threadPtr->getRunningStatus() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\n\n#1c cleanupThread callingThread [%p]\n", *thread); + + delete threadPtr; + // printf("LINE: %d *thread = %p\n",__LINE__,*thread); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } else { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\n\n#1d cleanupThread callingThread [%p]\n", *thread); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] Error cannot shutdown thread\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + // SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("%s", szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + if (threadType == tnt_MASTERSERVER) { + threadPtr->setOverrideShutdownTask(shutdownTaskStatic); + } + threadPtr->setDeleteSelfOnExecutionDone(true); + threadPtr->setDeleteAfterExecute(true); + // printf("LINE: %d *thread = %p\n",__LINE__,*thread); + } + threadPtr = NULL; + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1e cleanupThread + // callingThread [%p]\n",*thread); + } else { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\n\n#1f cleanupThread callingThread [%p]\n", *thread); + threadPtr->signalQuit(); + sleep(0); + if (threadPtr->canShutdown(true) == true && + threadPtr->getRunningStatus() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\n\n#1g cleanupThread callingThread [%p]\n", *thread); + delete threadPtr; + // printf("LINE: %d *thread = %p\n",__LINE__,*thread); + } else { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\n\n#1h cleanupThread callingThread [%p]\n", *thread); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] Error cannot shutdown thread\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + // SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("%s", szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + if (threadType == tnt_MASTERSERVER) { + threadPtr->setOverrideShutdownTask(shutdownTaskStatic); + } + threadPtr->setDeleteSelfOnExecutionDone(true); + threadPtr->setDeleteAfterExecute(true); + // printf("LINE: %d *thread = %p\n",__LINE__,*thread); + } + } - if(thread != NULL && *thread != NULL) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1 cleanupThread callingThread [%p]\n",*thread); + *thread = NULL; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\n\n#2 cleanupThread callingThread [%p]\n", *thread); + } + // printf("LINE: %d *thread = %p\n",__LINE__,*thread); +} + +void MenuStateCustomGame::cleanup() { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (publishToMasterserverThread) { + // printf("LINE: %d\n",__LINE__); + cleanupThread(&publishToMasterserverThread); + } + if (publishToClientsThread) { + // printf("LINE: %d\n",__LINE__); + cleanupThread(&publishToClientsThread); + } + + // printf("LINE: %d\n",__LINE__); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + cleanupMapPreviewTexture(); + + if (factionVideo != NULL) { + factionVideo->closePlayer(); + delete factionVideo; + factionVideo = NULL; + } + + if (forceWaitForShutdown == true) { + NetworkManager::getInstance().end(); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); +} - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +MenuStateCustomGame::~MenuStateCustomGame() { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + cleanup(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); +} - SimpleTaskThread *threadPtr = *thread; - int value = threadPtr->getUserdataAsInt(); - THREAD_NOTIFIER_TYPE threadType = (THREAD_NOTIFIER_TYPE)value; +void MenuStateCustomGame::returnToParentMenu() { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + needToBroadcastServerSettings = false; + needToRepublishToMasterserver = false; + lastNetworkPing = time(NULL); + ParentMenuState parentMenuState = this->parentMenuState; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + forceWaitForShutdown = false; + if (parentMenuState == pMasterServer) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + cleanup(); + mainMenu->setState(new MenuStateMasterserver(program, mainMenu)); + } else if (parentMenuState == pLanGame) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + cleanup(); + mainMenu->setState(new MenuStateJoinGame(program, mainMenu)); + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + cleanup(); + mainMenu->setState(new MenuStateNewGame(program, mainMenu)); + } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1. cleanupThread callingThread [%p] value = %d\n",*thread,value); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); +} +void MenuStateCustomGame::mouseClick(int x, int y, MouseButton mouseButton) { + if (isMasterserverMode() == true) { + return; + } + Config &config = Config::getInstance(); + Lang &lang = Lang::getInstance(); + try { + CoreData &coreData = CoreData::getInstance(); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + int oldListBoxMapfilterIndex = listBoxMapFilter.getSelectedItemIndex(); + + if (mainMessageBox.getEnabled()) { + int button = 0; + if (mainMessageBox.mouseClick(x, y, button)) { + soundRenderer.playFx(coreData.getClickSoundA()); + if (button == 0) { + mainMessageBox.setEnabled(false); + } + } + } else if (comboBoxMap.mouseClick(x, y)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s\n", + getCurrentMapFile().c_str()); + + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + MutexSafeWrapper safeMutexCLI( + (publishToClientsThread != NULL + ? publishToClientsThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + loadMapInfo(Config::getMapPath(getCurrentMapFile(), "", false), &mapInfo, + true, true); + labelMapInfo.setText(mapInfo.desc); + updateControlers(); + updateNetworkSlots(); + + if (checkBoxPublishServer.getValue() == true) { + needToRepublishToMasterserver = true; + } + + if (hasNetworkGameSettings() == true) { + // delay publishing for 5 seconds + needToPublishDelayed = true; + mapPublishingDelayTimer = time(NULL); + } + } else if (comboBoxMap.isDropDownShowing()) { + // do nothing + } else if (comboBoxLoadSetup.mouseClick(x, y)) { + } else if (comboBoxLoadSetup.isDropDownShowing()) { + // do nothing + } else { + string advanceToItemStartingWith = ""; + if (::Shared::Platform::Window::isKeyStateModPressed(KMOD_SHIFT) == + true) { + const wchar_t lastKey = + ::Shared::Platform::Window::extractLastKeyPressed(); + // string helpString = ""; + // helpString = lastKey; + // printf("lastKey = + //'%s'\n",helpString.c_str()); + advanceToItemStartingWith = lastKey; + } + + if (mapPreviewTexture != NULL) { + // printf("X: %d Y: %d [%d, %d, %d, %d]\n", + // x, y, + // this->render_mapPreviewTexture_X, + // this->render_mapPreviewTexture_X + + // this->render_mapPreviewTexture_W, + // this->render_mapPreviewTexture_Y, + // this->render_mapPreviewTexture_Y + + // this->render_mapPreviewTexture_H); + + if (x >= this->render_mapPreviewTexture_X && + x <= this->render_mapPreviewTexture_X + + this->render_mapPreviewTexture_W && + y >= this->render_mapPreviewTexture_Y && + y <= this->render_mapPreviewTexture_Y + + this->render_mapPreviewTexture_H) { + + if (this->render_mapPreviewTexture_X == mapPreviewTexture_X && + this->render_mapPreviewTexture_Y == mapPreviewTexture_Y && + this->render_mapPreviewTexture_W == mapPreviewTexture_W && + this->render_mapPreviewTexture_H == mapPreviewTexture_H) { + + const Metrics &metrics = Metrics::getInstance(); + + this->render_mapPreviewTexture_X = 0; + this->render_mapPreviewTexture_Y = 0; + this->render_mapPreviewTexture_W = metrics.getVirtualW(); + this->render_mapPreviewTexture_H = metrics.getVirtualH(); + this->zoomedMap = true; + + cleanupMapPreviewTexture(); + } else { + this->render_mapPreviewTexture_X = mapPreviewTexture_X; + this->render_mapPreviewTexture_Y = mapPreviewTexture_Y; + this->render_mapPreviewTexture_W = mapPreviewTexture_W; + this->render_mapPreviewTexture_H = mapPreviewTexture_H; + this->zoomedMap = false; + + cleanupMapPreviewTexture(); + } + return; + } + if (this->zoomedMap == true) { + return; + } + } + + if (activeInputLabel != NULL && !(activeInputLabel->mouseClick(x, y))) { + setActiveInputLabel(NULL); + } + if (buttonReturn.mouseClick(x, y) || serverInitError == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + soundRenderer.playFx(coreData.getClickSoundA()); + + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + MutexSafeWrapper safeMutexCLI( + (publishToClientsThread != NULL + ? publishToClientsThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); needToBroadcastServerSettings = false; needToRepublishToMasterserver = false; - lastNetworkPing = time(NULL); - threadPtr->setThreadOwnerValid(false); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1.. cleanupThread callingThread [%p] value = %d\n",*thread,value); - - if(forceWaitForShutdown == true) { - time_t elapsed = time(NULL); - threadPtr->signalQuit(); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1a cleanupThread callingThread [%p]\n",*thread); - - for(;(threadPtr->canShutdown(false) == false || - threadPtr->getRunningStatus() == true) && - difftime((long int)time(NULL),elapsed) <= 15;) { - //sleep(150); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1b cleanupThread callingThread [%p]\n",*thread); - - if(threadPtr->canShutdown(true) == true && - threadPtr->getRunningStatus() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1c cleanupThread callingThread [%p]\n",*thread); - - delete threadPtr; - //printf("LINE: %d *thread = %p\n",__LINE__,*thread); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - else { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1d cleanupThread callingThread [%p]\n",*thread); - - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] Error cannot shutdown thread\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s",szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - - if(threadType == tnt_MASTERSERVER) { - threadPtr->setOverrideShutdownTask(shutdownTaskStatic); - } - threadPtr->setDeleteSelfOnExecutionDone(true); - threadPtr->setDeleteAfterExecute(true); - //printf("LINE: %d *thread = %p\n",__LINE__,*thread); - } - threadPtr = NULL; - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1e cleanupThread callingThread [%p]\n",*thread); + lastNetworkPing = time(NULL); + safeMutex.ReleaseLock(); + safeMutexCLI.ReleaseLock(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + returnToParentMenu(); + return; + } else if (buttonPlayNow.mouseClick(x, y) && buttonPlayNow.getEnabled()) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + PlayNow(true); + return; + } else if (checkBoxAdvanced.getValue() == 1 && + listBoxFogOfWar.mouseClick(x, y)) { + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + MutexSafeWrapper safeMutexCLI( + (publishToClientsThread != NULL + ? publishToClientsThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + cleanupMapPreviewTexture(); + if (checkBoxPublishServer.getValue() == true) { + needToRepublishToMasterserver = true; } - else { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1f cleanupThread callingThread [%p]\n",*thread); - threadPtr->signalQuit(); - sleep(0); - if(threadPtr->canShutdown(true) == true && - threadPtr->getRunningStatus() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1g cleanupThread callingThread [%p]\n",*thread); - delete threadPtr; - //printf("LINE: %d *thread = %p\n",__LINE__,*thread); - } - else { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1h cleanupThread callingThread [%p]\n",*thread); - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] Error cannot shutdown thread\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s",szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - - if(threadType == tnt_MASTERSERVER) { - threadPtr->setOverrideShutdownTask(shutdownTaskStatic); - } - threadPtr->setDeleteSelfOnExecutionDone(true); - threadPtr->setDeleteAfterExecute(true); - //printf("LINE: %d *thread = %p\n",__LINE__,*thread); - } + + if (hasNetworkGameSettings() == true) { + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + } + } else if (labelSaveSetupName.mouseClick(x, y)) { + setActiveInputLabel(&labelSaveSetupName); + } else if (buttonSaveSetup.mouseClick(x, y)) { + GameSettings gameSettings; + copyToGameSettings(&gameSettings); + int humanSlots = 0; + for (int i = 0; i < gameSettings.getFactionCount(); i++) { + switch (gameSettings.getFactionControl(i)) { + case ctNetwork: + case ctHuman: + case ctNetworkUnassigned: + humanSlots++; + break; + default: + // do nothing + break; + } + } + string setupName = intToStr(humanSlots) + "_" + gameSettings.getMap(); + labelSaveSetupName.setText(trim(labelSaveSetupName.getText())); + if (labelSaveSetupName.getText() != "") { + setupName = labelSaveSetupName.getText(); + setupName = replaceAll(setupName, "/", "_"); + setupName = replaceAll(setupName, "\\", "_"); + if (StartsWith(setupName, ".")) { + setupName[0] = '_'; + } + } + if (setupName != lang.getString(LAST_SETUP_STRING)) { + string filename = SETUPS_DIR + setupName + ".mgg"; + saveGameSettings(filename); + console.addLine("--> " + filename); + loadSavedSetupNames(); + comboBoxLoadSetup.setItems(savedSetupFilenames); + comboBoxLoadSetup.setSelectedItem(setupName); + } + } else if (buttonLoadSetup.mouseClick(x, y)) { + string setupName = comboBoxLoadSetup.getSelectedItem(); + if (setupName != "") { + string fileNameToLoad = SETUPS_DIR + setupName + ".mgg"; + if (setupName == lang.getString(LAST_SETUP_STRING)) { + fileNameToLoad = SAVED_SETUP_FILENAME; + } + if (loadGameSettings(fileNameToLoad)) + console.addLine("<-- " + fileNameToLoad); + } + } else if (buttonDeleteSetup.mouseClick(x, y)) { + string setupName = comboBoxLoadSetup.getSelectedItem(); + if (setupName != "" && setupName != lang.getString(LAST_SETUP_STRING)) { + int index = comboBoxLoadSetup.getSelectedItemIndex(); + removeFile(savedSetupsDir + setupName + ".mgg"); + loadSavedSetupNames(); + comboBoxLoadSetup.setItems(savedSetupFilenames); + if (comboBoxLoadSetup.getItemCount() > index) { + comboBoxLoadSetup.setSelectedItemIndex(index, false); + } else { + comboBoxLoadSetup.setSelectedItem(lang.getString(LAST_SETUP_STRING), + false); + } + console.addLine("X " + setupName + ".mgg"); + } + } else if (checkBoxAdvanced.getValue() == 1 && + buttonShowLanInfo.mouseClick(x, y)) { + // show to console + string ipText = "none"; + std::vector ipList = Socket::getLocalIPAddressList(); + if (ipList.empty() == false) { + ipText = ""; + for (int idx = 0; idx < (int)ipList.size(); idx++) { + string ip = ipList[idx]; + if (ipText != "") { + ipText += ", "; + } + ipText += ip; + } } - *thread = NULL; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#2 cleanupThread callingThread [%p]\n",*thread); - } - //printf("LINE: %d *thread = %p\n",__LINE__,*thread); -} + string serverPort = config.getString( + "PortServer", intToStr(GameConstants::serverPort).c_str()); + string externalPort = + config.getString("PortExternal", serverPort.c_str()); + console.addLine(lang.getString("LanIP") + ipText + " ( " + serverPort + + " / " + externalPort + " )"); + } else if (checkBoxAdvanced.getValue() == 1 && + checkBoxAllowObservers.mouseClick(x, y)) { + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + MutexSafeWrapper safeMutexCLI( + (publishToClientsThread != NULL + ? publishToClientsThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + if (checkBoxPublishServer.getValue() == true) { + needToRepublishToMasterserver = true; + } -void MenuStateCustomGame::cleanup() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + reloadFactions( + true, (checkBoxScenario.getValue() == true + ? scenarioFiles[listBoxScenario.getSelectedItemIndex()] + : "")); - if(publishToMasterserverThread) { - //printf("LINE: %d\n",__LINE__); - cleanupThread(&publishToMasterserverThread); - } - if(publishToClientsThread) { - //printf("LINE: %d\n",__LINE__); - cleanupThread(&publishToClientsThread); - } + if (hasNetworkGameSettings() == true) { + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + } + } else if (checkBoxAllowInGameJoinPlayer.mouseClick(x, y)) { + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + MutexSafeWrapper safeMutexCLI( + (publishToClientsThread != NULL + ? publishToClientsThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + if (checkBoxPublishServer.getValue() == true) { + needToRepublishToMasterserver = true; + } - //printf("LINE: %d\n",__LINE__); + if (hasNetworkGameSettings() == true) { + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + serverInterface->setAllowInGameConnections( + checkBoxAllowInGameJoinPlayer.getValue() == true); + } else if (checkBoxAdvanced.getValue() == 1 && + checkBoxAllowTeamUnitSharing.mouseClick(x, y)) { + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + MutexSafeWrapper safeMutexCLI( + (publishToClientsThread != NULL + ? publishToClientsThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + if (checkBoxPublishServer.getValue() == true) { + needToRepublishToMasterserver = true; + } - cleanupMapPreviewTexture(); + if (hasNetworkGameSettings() == true) { + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + } + } else if (checkBoxAdvanced.getValue() == 1 && + checkBoxAllowTeamResourceSharing.mouseClick(x, y)) { + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + MutexSafeWrapper safeMutexCLI( + (publishToClientsThread != NULL + ? publishToClientsThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + if (checkBoxPublishServer.getValue() == true) { + needToRepublishToMasterserver = true; + } - if(factionVideo != NULL) { - factionVideo->closePlayer(); - delete factionVideo; - factionVideo = NULL; - } + if (hasNetworkGameSettings() == true) { + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + } + } else if (checkBoxAllowNativeLanguageTechtree.mouseClick(x, y)) { + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + MutexSafeWrapper safeMutexCLI( + (publishToClientsThread != NULL + ? publishToClientsThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + if (checkBoxPublishServer.getValue() == true) { + needToRepublishToMasterserver = true; + } - if(forceWaitForShutdown == true) { - NetworkManager::getInstance().end(); - } + if (hasNetworkGameSettings() == true) { + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + } + } else if (checkBoxAdvanced.getValue() == 1 && + checkBoxEnableSwitchTeamMode.mouseClick(x, y)) { + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + MutexSafeWrapper safeMutexCLI( + (publishToClientsThread != NULL + ? publishToClientsThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + if (checkBoxPublishServer.getValue() == true) { + needToRepublishToMasterserver = true; + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); -} + if (hasNetworkGameSettings() == true) { + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + } + } else if (checkBoxAdvanced.getValue() == 1 && + listBoxAISwitchTeamAcceptPercent.getEnabled() && + listBoxAISwitchTeamAcceptPercent.mouseClick(x, y)) { + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + MutexSafeWrapper safeMutexCLI( + (publishToClientsThread != NULL + ? publishToClientsThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + if (checkBoxPublishServer.getValue() == true) { + needToRepublishToMasterserver = true; + } -MenuStateCustomGame::~MenuStateCustomGame() { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (hasNetworkGameSettings() == true) { + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + } + } else if (checkBoxAdvanced.getValue() == 1 && + listBoxFallbackCpuMultiplier.getEditable() == true && + listBoxFallbackCpuMultiplier.mouseClick(x, y)) { + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + MutexSafeWrapper safeMutexCLI( + (publishToClientsThread != NULL + ? publishToClientsThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + if (checkBoxPublishServer.getValue() == true) { + needToRepublishToMasterserver = true; + } - cleanup(); + if (hasNetworkGameSettings() == true) { + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + } + } else if (checkBoxAdvanced.mouseClick(x, y)) { + } else if (listBoxTileset.mouseClick(x, y, advanceToItemStartingWith)) { + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + MutexSafeWrapper safeMutexCLI( + (publishToClientsThread != NULL + ? publishToClientsThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + if (checkBoxPublishServer.getValue() == true) { + needToRepublishToMasterserver = true; + } + if (hasNetworkGameSettings() == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); -} + // delay publishing for 5 seconds + needToPublishDelayed = true; + mapPublishingDelayTimer = time(NULL); + } + } else if (listBoxMapFilter.mouseClick(x, y)) { + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + MutexSafeWrapper safeMutexCLI( + (publishToClientsThread != NULL + ? publishToClientsThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + switchToNextMapGroup(listBoxMapFilter.getSelectedItemIndex() - + oldListBoxMapfilterIndex); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s\n", + getCurrentMapFile().c_str()); + + loadMapInfo(Config::getMapPath(getCurrentMapFile()), &mapInfo, true, + true); + labelMapInfo.setText(mapInfo.desc); + updateControlers(); + updateNetworkSlots(); + + if (checkBoxPublishServer.getValue() == true) { + needToRepublishToMasterserver = true; + } -void MenuStateCustomGame::returnToParentMenu() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - needToBroadcastServerSettings = false; - needToRepublishToMasterserver = false; - lastNetworkPing = time(NULL); - ParentMenuState parentMenuState = this->parentMenuState; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - forceWaitForShutdown = false; - if(parentMenuState==pMasterServer) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - cleanup(); - mainMenu->setState(new MenuStateMasterserver(program, mainMenu)); - } - else if(parentMenuState==pLanGame) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - cleanup(); - mainMenu->setState(new MenuStateJoinGame(program, mainMenu)); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - cleanup(); - mainMenu->setState(new MenuStateNewGame(program, mainMenu)); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); -} + if (hasNetworkGameSettings() == true) { + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + } + } else if (listBoxTechTree.mouseClick(x, y, advanceToItemStartingWith)) { + reloadFactions( + listBoxTechTree.getItemCount() <= 1, + (checkBoxScenario.getValue() == true + ? scenarioFiles[listBoxScenario.getSelectedItemIndex()] + : "")); + + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + MutexSafeWrapper safeMutexCLI( + (publishToClientsThread != NULL + ? publishToClientsThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + if (checkBoxPublishServer.getValue() == true) { + needToRepublishToMasterserver = true; + } -void MenuStateCustomGame::mouseClick(int x, int y, MouseButton mouseButton) { - if(isMasterserverMode() == true) { - return; - } - Config &config = Config::getInstance(); - Lang &lang= Lang::getInstance(); - try { - CoreData &coreData= CoreData::getInstance(); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - int oldListBoxMapfilterIndex=listBoxMapFilter.getSelectedItemIndex(); - - if(mainMessageBox.getEnabled()){ - int button= 0; - if(mainMessageBox.mouseClick(x, y, button)) { - soundRenderer.playFx(coreData.getClickSoundA()); - if(button == 0) { - mainMessageBox.setEnabled(false); - } - } + if (hasNetworkGameSettings() == true) { + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + } + } else if (checkBoxPublishServer.mouseClick(x, y) && + checkBoxPublishServer.getEditable()) { + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + MutexSafeWrapper safeMutexCLI( + (publishToClientsThread != NULL + ? publishToClientsThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + needToRepublishToMasterserver = true; + soundRenderer.playFx(coreData.getClickSoundC()); + + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + serverInterface->setPublishEnabled(checkBoxPublishServer.getValue() == + true); + } else if (labelGameName.mouseClick(x, y) && + checkBoxPublishServer.getEditable()) { + setActiveInputLabel(&labelGameName); + } else if (checkBoxAdvanced.getValue() == 1 && + checkBoxNetworkPauseGameForLaggedClients.mouseClick(x, y)) { + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + MutexSafeWrapper safeMutexCLI( + (publishToClientsThread != NULL + ? publishToClientsThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + if (checkBoxPublishServer.getValue() == true) { + needToRepublishToMasterserver = true; } - else if(comboBoxMap.mouseClick(x, y)){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s\n", getCurrentMapFile().c_str()); - - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - loadMapInfo(Config::getMapPath(getCurrentMapFile(),"",false), &mapInfo, true,true); - labelMapInfo.setText(mapInfo.desc); - updateControlers(); - updateNetworkSlots(); - - if(checkBoxPublishServer.getValue() == true) { - needToRepublishToMasterserver = true; - } - - if(hasNetworkGameSettings() == true) { - //delay publishing for 5 seconds - needToPublishDelayed=true; - mapPublishingDelayTimer=time(NULL); - } - } - else if(comboBoxMap.isDropDownShowing()){ - //do nothing - } - else if(comboBoxLoadSetup.mouseClick(x,y)){ - } - else if(comboBoxLoadSetup.isDropDownShowing()){ - //do nothing - } - else { - string advanceToItemStartingWith = ""; - if(::Shared::Platform::Window::isKeyStateModPressed(KMOD_SHIFT) == true) { - const wchar_t lastKey = ::Shared::Platform::Window::extractLastKeyPressed(); -// string helpString = ""; -// helpString = lastKey; -// printf("lastKey = '%s'\n",helpString.c_str()); - advanceToItemStartingWith = lastKey; - } - - if(mapPreviewTexture != NULL) { -// printf("X: %d Y: %d [%d, %d, %d, %d]\n", -// x, y, -// this->render_mapPreviewTexture_X, this->render_mapPreviewTexture_X + this->render_mapPreviewTexture_W, -// this->render_mapPreviewTexture_Y, this->render_mapPreviewTexture_Y + this->render_mapPreviewTexture_H); - - if( x >= this->render_mapPreviewTexture_X && x <= this->render_mapPreviewTexture_X + this->render_mapPreviewTexture_W && - y >= this->render_mapPreviewTexture_Y && y <= this->render_mapPreviewTexture_Y + this->render_mapPreviewTexture_H) { - - if( this->render_mapPreviewTexture_X == mapPreviewTexture_X && - this->render_mapPreviewTexture_Y == mapPreviewTexture_Y && - this->render_mapPreviewTexture_W == mapPreviewTexture_W && - this->render_mapPreviewTexture_H == mapPreviewTexture_H) { - - const Metrics &metrics= Metrics::getInstance(); - - this->render_mapPreviewTexture_X = 0; - this->render_mapPreviewTexture_Y = 0; - this->render_mapPreviewTexture_W = metrics.getVirtualW(); - this->render_mapPreviewTexture_H = metrics.getVirtualH(); - this->zoomedMap = true; - - cleanupMapPreviewTexture(); - } - else { - this->render_mapPreviewTexture_X = mapPreviewTexture_X; - this->render_mapPreviewTexture_Y = mapPreviewTexture_Y; - this->render_mapPreviewTexture_W = mapPreviewTexture_W; - this->render_mapPreviewTexture_H = mapPreviewTexture_H; - this->zoomedMap = false; - - cleanupMapPreviewTexture(); - } - return; - } - if(this->zoomedMap == true){ - return; - } - } - - if(activeInputLabel!=NULL && !(activeInputLabel->mouseClick(x,y))){ - setActiveInputLabel(NULL); - } - if(buttonReturn.mouseClick(x,y) || serverInitError == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - soundRenderer.playFx(coreData.getClickSoundA()); - - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - needToBroadcastServerSettings = false; - needToRepublishToMasterserver = false; - lastNetworkPing = time(NULL); - safeMutex.ReleaseLock(); - safeMutexCLI.ReleaseLock(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - returnToParentMenu(); - return; - } - else if(buttonPlayNow.mouseClick(x,y) && buttonPlayNow.getEnabled()) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - PlayNow(true); - return; - } - else if (checkBoxAdvanced.getValue() == 1 && listBoxFogOfWar.mouseClick(x, y)) { - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - cleanupMapPreviewTexture(); - if(checkBoxPublishServer.getValue() == true) { - needToRepublishToMasterserver = true; - } - - if(hasNetworkGameSettings() == true) { - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); - } - } - else if(labelSaveSetupName.mouseClick(x, y) ){ - setActiveInputLabel(&labelSaveSetupName); - } - else if ( buttonSaveSetup.mouseClick(x, y)){ - GameSettings gameSettings; - copyToGameSettings(&gameSettings); - int humanSlots=0; - for( int i=0; i " +filename); - loadSavedSetupNames(); - comboBoxLoadSetup.setItems(savedSetupFilenames); - comboBoxLoadSetup.setSelectedItem(setupName); - } - } - else if ( buttonLoadSetup.mouseClick(x, y)){ - string setupName=comboBoxLoadSetup.getSelectedItem(); - if( setupName!=""){ - string fileNameToLoad=SETUPS_DIR+setupName+".mgg"; - if( setupName== lang.getString(LAST_SETUP_STRING)){ - fileNameToLoad=SAVED_SETUP_FILENAME; - } - if(loadGameSettings(fileNameToLoad)) - console.addLine("<-- " +fileNameToLoad); - } - } - else if ( buttonDeleteSetup.mouseClick(x, y)){ - string setupName=comboBoxLoadSetup.getSelectedItem(); - if( setupName!=""&& setupName!= lang.getString(LAST_SETUP_STRING)) { - int index=comboBoxLoadSetup.getSelectedItemIndex(); - removeFile(savedSetupsDir+setupName+".mgg"); - loadSavedSetupNames(); - comboBoxLoadSetup.setItems(savedSetupFilenames); - if(comboBoxLoadSetup.getItemCount()>index){ - comboBoxLoadSetup.setSelectedItemIndex(index,false); - } - else{ - comboBoxLoadSetup.setSelectedItem( lang.getString(LAST_SETUP_STRING),false); - } - console.addLine("X " +setupName+".mgg"); - } - } - else if (checkBoxAdvanced.getValue() == 1 && buttonShowLanInfo.mouseClick(x, y)) { - // show to console - string ipText = "none"; - std::vector ipList = Socket::getLocalIPAddressList(); - if(ipList.empty() == false) { - ipText = ""; - for(int idx = 0; idx < (int)ipList.size(); idx++) { - string ip = ipList[idx]; - if(ipText != "") { - ipText += ", "; - } - ipText += ip; - } - } - - string serverPort=config.getString("PortServer", intToStr(GameConstants::serverPort).c_str()); - string externalPort=config.getString("PortExternal", serverPort.c_str()); - console.addLine(lang.getString("LanIP") + ipText + " ( "+serverPort+" / "+externalPort+" )"); - } - else if (checkBoxAdvanced.getValue() == 1 && checkBoxAllowObservers.mouseClick(x, y)) { - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - if(checkBoxPublishServer.getValue() == true) { - needToRepublishToMasterserver = true; - } - - reloadFactions(true,(checkBoxScenario.getValue() == true ? scenarioFiles[listBoxScenario.getSelectedItemIndex()] : "")); - - if(hasNetworkGameSettings() == true) { - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); - } - } - else if (checkBoxAllowInGameJoinPlayer.mouseClick(x, y)) { - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - if(checkBoxPublishServer.getValue() == true) { - needToRepublishToMasterserver = true; - } - - if(hasNetworkGameSettings() == true) { - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); - } - - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - serverInterface->setAllowInGameConnections(checkBoxAllowInGameJoinPlayer.getValue() == true); - } - else if (checkBoxAdvanced.getValue() == 1 && checkBoxAllowTeamUnitSharing.mouseClick(x, y)) { - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - - if(checkBoxPublishServer.getValue() == true) { - needToRepublishToMasterserver = true; - } - - if(hasNetworkGameSettings() == true) { - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); - } - } - else if (checkBoxAdvanced.getValue() == 1 && checkBoxAllowTeamResourceSharing.mouseClick(x, y)) { - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - - if(checkBoxPublishServer.getValue() == true) { - needToRepublishToMasterserver = true; - } - - if(hasNetworkGameSettings() == true) { - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); - } - } - else if (checkBoxAllowNativeLanguageTechtree.mouseClick(x, y)) { - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - if(checkBoxPublishServer.getValue() == true) { - needToRepublishToMasterserver = true; - } - - if(hasNetworkGameSettings() == true) - { - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); - } - } - else if (checkBoxAdvanced.getValue() == 1 && checkBoxEnableSwitchTeamMode.mouseClick(x, y)) { - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - if(checkBoxPublishServer.getValue() == true) { - needToRepublishToMasterserver = true; - } - - if(hasNetworkGameSettings() == true) - { - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); - } - } - else if (checkBoxAdvanced.getValue() == 1 && listBoxAISwitchTeamAcceptPercent.getEnabled() && listBoxAISwitchTeamAcceptPercent.mouseClick(x, y)) { - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - if(checkBoxPublishServer.getValue() == true) { - needToRepublishToMasterserver = true; - } - - if(hasNetworkGameSettings() == true) - { - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); - } - } - else if (checkBoxAdvanced.getValue() == 1 && listBoxFallbackCpuMultiplier.getEditable() == true && listBoxFallbackCpuMultiplier.mouseClick(x, y)) { - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - if(checkBoxPublishServer.getValue() == true) { - needToRepublishToMasterserver = true; - } - - if(hasNetworkGameSettings() == true) - { - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); - } - } - else if (checkBoxAdvanced.mouseClick(x, y)) { - } - else if(listBoxTileset.mouseClick(x, y,advanceToItemStartingWith)) { - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - if(checkBoxPublishServer.getValue() == true) { - needToRepublishToMasterserver = true; - } - if(hasNetworkGameSettings() == true) - { - - //delay publishing for 5 seconds - needToPublishDelayed=true; - mapPublishingDelayTimer=time(NULL); - } - } - else if(listBoxMapFilter.mouseClick(x, y)){ - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - switchToNextMapGroup(listBoxMapFilter.getSelectedItemIndex()-oldListBoxMapfilterIndex); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s\n", getCurrentMapFile().c_str()); - - loadMapInfo(Config::getMapPath(getCurrentMapFile()), &mapInfo, true,true); - labelMapInfo.setText(mapInfo.desc); - updateControlers(); - updateNetworkSlots(); - - if(checkBoxPublishServer.getValue() == true) { - needToRepublishToMasterserver = true; - } - - if(hasNetworkGameSettings() == true) - { - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); - } - } - else if(listBoxTechTree.mouseClick(x, y,advanceToItemStartingWith)){ - reloadFactions(listBoxTechTree.getItemCount() <= 1,(checkBoxScenario.getValue() == true ? scenarioFiles[listBoxScenario.getSelectedItemIndex()] : "")); - - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - if(checkBoxPublishServer.getValue() == true) { - needToRepublishToMasterserver = true; - } - - if(hasNetworkGameSettings() == true) - { - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); - } - } - else if(checkBoxPublishServer.mouseClick(x, y) && checkBoxPublishServer.getEditable()) { - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - needToRepublishToMasterserver = true; - soundRenderer.playFx(coreData.getClickSoundC()); - - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - serverInterface->setPublishEnabled(checkBoxPublishServer.getValue() == true); - } - else if(labelGameName.mouseClick(x, y) && checkBoxPublishServer.getEditable()){ - setActiveInputLabel(&labelGameName); - } - else if(checkBoxAdvanced.getValue() == 1 && checkBoxNetworkPauseGameForLaggedClients.mouseClick(x, y)) { - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - if(checkBoxPublishServer.getValue() == true) { - needToRepublishToMasterserver = true; - } - if(hasNetworkGameSettings() == true) - { - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); - } - - soundRenderer.playFx(coreData.getClickSoundC()); - } - else if(listBoxScenario.mouseClick(x, y) || checkBoxScenario.mouseClick(x,y)) { - processScenario(); - } - else { - for(int i = 0; i < mapInfo.players; ++i) { - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - // set multiplier - if(listBoxRMultiplier[i].mouseClick(x, y)) { - //printf("Line: %d multiplier index: %d i: %d itemcount: %d\n",__LINE__,listBoxRMultiplier[i].getSelectedItemIndex(),i,listBoxRMultiplier[i].getItemCount()); - - //for(int indexData = 0; indexData < listBoxRMultiplier[i].getItemCount(); ++indexData) { - //string item = listBoxRMultiplier[i].getItem(indexData); - - //printf("Item index: %d value: %s\n",indexData,item.c_str()); - //} - } - - //ensure thet only 1 human player is present - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - ConnectionSlot *slot = serverInterface->getSlot(i,true); - - bool checkControTypeClicked = false; - int selectedControlItemIndex = listBoxControls[i].getSelectedItemIndex(); - if(selectedControlItemIndex != ctNetwork || - (selectedControlItemIndex == ctNetwork && (slot == NULL || slot->isConnected() == false))) { - checkControTypeClicked = true; - } - - //printf("checkControTypeClicked = %d selectedControlItemIndex = %d i = %d\n",checkControTypeClicked,selectedControlItemIndex,i); - - if(selectedControlItemIndex != ctHuman && - checkControTypeClicked == true && - listBoxControls[i].mouseClick(x, y)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - ControlType currentControlType = static_cast( - listBoxControls[i].getSelectedItemIndex()); - int slotsToChangeStart = i; - int slotsToChangeEnd = i; - // If control is pressed while changing player types then change all other slots to same type - if(::Shared::Platform::Window::isKeyStateModPressed(KMOD_CTRL) == true && - currentControlType != ctHuman) { - slotsToChangeStart = 0; - slotsToChangeEnd = mapInfo.players-1; - } - - for(int index = slotsToChangeStart; index <= slotsToChangeEnd; ++index) { - if(index != i && static_cast( - listBoxControls[index].getSelectedItemIndex()) != ctHuman) { - listBoxControls[index].setSelectedItemIndex(listBoxControls[i].getSelectedItemIndex()); - } - // Skip over networkunassigned - if(listBoxControls[index].getSelectedItemIndex() == ctNetworkUnassigned && - selectedControlItemIndex != ctNetworkUnassigned) { - listBoxControls[index].mouseClick(x, y); - } - - //look for human players - int humanIndex1= -1; - int humanIndex2= -1; - for(int j = 0; j < GameConstants::maxPlayers; ++j) { - ControlType ct= static_cast(listBoxControls[j].getSelectedItemIndex()); - if(ct == ctHuman) { - if(humanIndex1 == -1) { - humanIndex1= j; - } - else { - humanIndex2= j; - } - } - } - - 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); - - //no human - if(humanIndex1 == -1 && humanIndex2 == -1) { - setSlotHuman(index); - 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()); - - //printf("humanIndex1 = %d humanIndex2 = %d i = %d listBoxControls[i].getSelectedItemIndex() = %d\n",humanIndex1,humanIndex2,i,listBoxControls[i].getSelectedItemIndex()); - } - //2 humans - else if(humanIndex1 != -1 && humanIndex2 != -1) { - int closeSlotIndex = (humanIndex1 == index ? humanIndex2: humanIndex1); - int humanSlotIndex = (closeSlotIndex == humanIndex1 ? humanIndex2 : humanIndex1); - - string origPlayName = labelPlayerNames[closeSlotIndex].getText(); - - 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()); - - listBoxControls[closeSlotIndex].setSelectedItemIndex(ctClosed); - setSlotHuman(humanSlotIndex); - labelPlayerNames[humanSlotIndex].setText((origPlayName != "" ? origPlayName : getHumanPlayerName())); - } - updateNetworkSlots(); - - if(checkBoxPublishServer.getValue() == true) { - needToRepublishToMasterserver = true; - } - - if(hasNetworkGameSettings() == true) { - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); - } - updateResourceMultiplier(index); - } - } - else if(buttonClearBlockedPlayers.mouseClick(x, y)) { - soundRenderer.playFx(coreData.getClickSoundB()); - - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - if(serverInterface != NULL) { - ServerSocket *serverSocket = serverInterface->getServerSocket(); - if(serverSocket != NULL) { - serverSocket->clearBlockedIPAddress(); - } - } - } - else if(buttonBlockPlayers[i].mouseClick(x, y)) { - soundRenderer.playFx(coreData.getClickSoundB()); - - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - if(serverInterface != NULL) { - if(serverInterface->getSlot(i,true) != NULL && - serverInterface->getSlot(i,true)->isConnected()) { - - ServerSocket *serverSocket = serverInterface->getServerSocket(); - if(serverSocket != NULL) { - serverSocket->addIPAddressToBlockedList(serverInterface->getSlot(i,true)->getIpAddress()); - - const vector languageList = serverInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int j = 0; j < languageList.size(); ++j) { - char szMsg[8096]=""; - if(lang.hasString("BlockPlayerServerMsg",languageList[j]) == true) { - snprintf(szMsg,8096,lang.getString("BlockPlayerServerMsg",languageList[j]).c_str(),serverInterface->getSlot(i,true)->getIpAddress().c_str()); - } - else { - snprintf(szMsg,8096,"The server has temporarily blocked IP Address [%s] from this game.",serverInterface->getSlot(i,true)->getIpAddress().c_str()); - } - - serverInterface->sendTextMessage(szMsg,-1, true,languageList[j]); - } - sleep(1); - serverInterface->getSlot(i,true)->close(); - } - } - } - } - else if(listBoxFactions[i].mouseClick(x, y,advanceToItemStartingWith)) { - // Disallow CPU players to be observers - if(factionFiles[listBoxFactions[i].getSelectedItemIndex()] == formatString(GameConstants::OBSERVER_SLOTNAME) && - (listBoxControls[i].getSelectedItemIndex() == ctCpuEasy || listBoxControls[i].getSelectedItemIndex() == ctCpu || - listBoxControls[i].getSelectedItemIndex() == ctCpuUltra || listBoxControls[i].getSelectedItemIndex() == ctCpuMega)) { - listBoxFactions[i].setSelectedItemIndex(0); - } - // - - if(checkBoxPublishServer.getValue() == true) { - needToRepublishToMasterserver = true; - } - - if(hasNetworkGameSettings() == true) - { - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); - } - } - else if(listBoxTeams[i].mouseClick(x, y)) - { - if(factionFiles[listBoxFactions[i].getSelectedItemIndex()] != formatString(GameConstants::OBSERVER_SLOTNAME)) { - if(listBoxTeams[i].getSelectedItemIndex() + 1 != (GameConstants::maxPlayers + fpt_Observer)) { - lastSelectedTeamIndex[i] = listBoxTeams[i].getSelectedItemIndex(); - } - } - else { - lastSelectedTeamIndex[i] = -1; - } - - if(checkBoxPublishServer.getValue() == true) { - needToRepublishToMasterserver = true; - } - - if(hasNetworkGameSettings() == true) - { - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL);; - } - } - else if(labelPlayerNames[i].mouseClick(x, y)) { - ControlType ct= static_cast(listBoxControls[i].getSelectedItemIndex()); - if(ct == ctHuman) { - setActiveInputLabel(&labelPlayerNames[i]); - break; - } - } - } - } + if (hasNetworkGameSettings() == true) { + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); } - if(hasNetworkGameSettings() == true && listBoxPlayerStatus.mouseClick(x,y)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - soundRenderer.playFx(coreData.getClickSoundC()); - if(getNetworkPlayerStatus()==npst_PickSettings) - { - listBoxPlayerStatus.setTextColor(Vec3f(1.0f,0.0f,0.0f)); - listBoxPlayerStatus.setLighted(true); - } - else if(getNetworkPlayerStatus()==npst_BeRightBack) - { - listBoxPlayerStatus.setTextColor(Vec3f(1.0f,1.0f,0.0f)); - listBoxPlayerStatus.setLighted(true); - } - else if(getNetworkPlayerStatus()==npst_Ready) - { - listBoxPlayerStatus.setTextColor(Vec3f(0.0f,1.0f,0.0f)); - listBoxPlayerStatus.setLighted(false); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(checkBoxPublishServer.getValue() == true) { - needToRepublishToMasterserver = true; + soundRenderer.playFx(coreData.getClickSoundC()); + } else if (listBoxScenario.mouseClick(x, y) || + checkBoxScenario.mouseClick(x, y)) { + processScenario(); + } else { + for (int i = 0; i < mapInfo.players; ++i) { + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + MutexSafeWrapper safeMutexCLI( + (publishToClientsThread != NULL + ? publishToClientsThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + // set multiplier + if (listBoxRMultiplier[i].mouseClick(x, y)) { + // printf("Line: %d multiplier index: %d i: %d itemcount: + // %d\n",__LINE__,listBoxRMultiplier[i].getSelectedItemIndex(),i,listBoxRMultiplier[i].getItemCount()); + + // for(int indexData = 0; indexData < + // listBoxRMultiplier[i].getItemCount(); ++indexData) { string item + // = listBoxRMultiplier[i].getItem(indexData); + + // printf("Item index: %d value: %s\n",indexData,item.c_str()); + //} + } + + // ensure thet only 1 human player is present + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + ConnectionSlot *slot = serverInterface->getSlot(i, true); + + bool checkControTypeClicked = false; + int selectedControlItemIndex = + listBoxControls[i].getSelectedItemIndex(); + if (selectedControlItemIndex != ctNetwork || + (selectedControlItemIndex == ctNetwork && + (slot == NULL || slot->isConnected() == false))) { + checkControTypeClicked = true; + } + + // printf("checkControTypeClicked = %d selectedControlItemIndex = %d i + // = %d\n",checkControTypeClicked,selectedControlItemIndex,i); + + if (selectedControlItemIndex != ctHuman && + checkControTypeClicked == true && + listBoxControls[i].mouseClick(x, y)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + ControlType currentControlType = static_cast( + listBoxControls[i].getSelectedItemIndex()); + int slotsToChangeStart = i; + int slotsToChangeEnd = i; + // If control is pressed while changing player types then change all + // other slots to same type + if (::Shared::Platform::Window::isKeyStateModPressed(KMOD_CTRL) == + true && + currentControlType != ctHuman) { + slotsToChangeStart = 0; + slotsToChangeEnd = mapInfo.players - 1; } - if(hasNetworkGameSettings() == true) { + for (int index = slotsToChangeStart; index <= slotsToChangeEnd; + ++index) { + if (index != i && + static_cast( + listBoxControls[index].getSelectedItemIndex()) != + ctHuman) { + listBoxControls[index].setSelectedItemIndex( + listBoxControls[i].getSelectedItemIndex()); + } + // Skip over networkunassigned + if (listBoxControls[index].getSelectedItemIndex() == + ctNetworkUnassigned && + selectedControlItemIndex != ctNetworkUnassigned) { + listBoxControls[index].mouseClick(x, y); + } + + // look for human players + int humanIndex1 = -1; + int humanIndex2 = -1; + for (int j = 0; j < GameConstants::maxPlayers; ++j) { + ControlType ct = static_cast( + listBoxControls[j].getSelectedItemIndex()); + if (ct == ctHuman) { + if (humanIndex1 == -1) { + humanIndex1 = j; + } else { + humanIndex2 = j; + } + } + } + + 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); + + // no human + if (humanIndex1 == -1 && humanIndex2 == -1) { + setSlotHuman(index); + 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()); + + // printf("humanIndex1 = %d humanIndex2 = %d i = %d + // listBoxControls[i].getSelectedItemIndex() = + // %d\n",humanIndex1,humanIndex2,i,listBoxControls[i].getSelectedItemIndex()); + } + // 2 humans + else if (humanIndex1 != -1 && humanIndex2 != -1) { + int closeSlotIndex = + (humanIndex1 == index ? humanIndex2 : humanIndex1); + int humanSlotIndex = + (closeSlotIndex == humanIndex1 ? humanIndex2 : humanIndex1); + + string origPlayName = + labelPlayerNames[closeSlotIndex].getText(); + + 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()); + + listBoxControls[closeSlotIndex].setSelectedItemIndex(ctClosed); + setSlotHuman(humanSlotIndex); + labelPlayerNames[humanSlotIndex].setText( + (origPlayName != "" ? origPlayName : getHumanPlayerName())); + } + updateNetworkSlots(); + + if (checkBoxPublishServer.getValue() == true) { + needToRepublishToMasterserver = true; + } + + if (hasNetworkGameSettings() == true) { needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); + lastSetChangedGameSettings = time(NULL); + } + updateResourceMultiplier(index); + } + } else if (buttonClearBlockedPlayers.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundB()); + + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + if (serverInterface != NULL) { + ServerSocket *serverSocket = serverInterface->getServerSocket(); + if (serverSocket != NULL) { + serverSocket->clearBlockedIPAddress(); + } + } + } else if (buttonBlockPlayers[i].mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundB()); + + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + if (serverInterface != NULL) { + if (serverInterface->getSlot(i, true) != NULL && + serverInterface->getSlot(i, true)->isConnected()) { + + ServerSocket *serverSocket = serverInterface->getServerSocket(); + if (serverSocket != NULL) { + serverSocket->addIPAddressToBlockedList( + serverInterface->getSlot(i, true)->getIpAddress()); + + const vector languageList = + serverInterface->getGameSettings() + ->getUniqueNetworkPlayerLanguages(); + for (unsigned int j = 0; j < languageList.size(); ++j) { + char szMsg[8096] = ""; + if (lang.hasString("BlockPlayerServerMsg", + languageList[j]) == true) { + snprintf(szMsg, 8096, + lang.getString("BlockPlayerServerMsg", + languageList[j]) + .c_str(), + serverInterface->getSlot(i, true) + ->getIpAddress() + .c_str()); + } else { + snprintf(szMsg, 8096, + "The server has temporarily blocked IP Address " + "[%s] from this game.", + serverInterface->getSlot(i, true) + ->getIpAddress() + .c_str()); + } + + serverInterface->sendTextMessage(szMsg, -1, true, + languageList[j]); + } + sleep(1); + serverInterface->getSlot(i, true)->close(); + } + } + } + } else if (listBoxFactions[i].mouseClick(x, y, + advanceToItemStartingWith)) { + // Disallow CPU players to be observers + if (factionFiles[listBoxFactions[i].getSelectedItemIndex()] == + formatString(GameConstants::OBSERVER_SLOTNAME) && + (listBoxControls[i].getSelectedItemIndex() == ctCpuEasy || + listBoxControls[i].getSelectedItemIndex() == ctCpu || + listBoxControls[i].getSelectedItemIndex() == ctCpuUltra || + listBoxControls[i].getSelectedItemIndex() == ctCpuMega)) { + listBoxFactions[i].setSelectedItemIndex(0); + } + // + + if (checkBoxPublishServer.getValue() == true) { + needToRepublishToMasterserver = true; + } + + if (hasNetworkGameSettings() == true) { + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + } + } else if (listBoxTeams[i].mouseClick(x, y)) { + if (factionFiles[listBoxFactions[i].getSelectedItemIndex()] != + formatString(GameConstants::OBSERVER_SLOTNAME)) { + if (listBoxTeams[i].getSelectedItemIndex() + 1 != + (GameConstants::maxPlayers + fpt_Observer)) { + lastSelectedTeamIndex[i] = + listBoxTeams[i].getSelectedItemIndex(); + } + } else { + lastSelectedTeamIndex[i] = -1; } - } - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - showGeneralError=true; - generalErrorToShow = szBuf; - } + if (checkBoxPublishServer.getValue() == true) { + needToRepublishToMasterserver = true; + } + + if (hasNetworkGameSettings() == true) { + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + ; + } + } else if (labelPlayerNames[i].mouseClick(x, y)) { + ControlType ct = static_cast( + listBoxControls[i].getSelectedItemIndex()); + if (ct == ctHuman) { + setActiveInputLabel(&labelPlayerNames[i]); + break; + } + } + } + } + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (hasNetworkGameSettings() == true && + listBoxPlayerStatus.mouseClick(x, y)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + soundRenderer.playFx(coreData.getClickSoundC()); + if (getNetworkPlayerStatus() == npst_PickSettings) { + listBoxPlayerStatus.setTextColor(Vec3f(1.0f, 0.0f, 0.0f)); + listBoxPlayerStatus.setLighted(true); + } else if (getNetworkPlayerStatus() == npst_BeRightBack) { + listBoxPlayerStatus.setTextColor(Vec3f(1.0f, 1.0f, 0.0f)); + listBoxPlayerStatus.setLighted(true); + } else if (getNetworkPlayerStatus() == npst_Ready) { + listBoxPlayerStatus.setTextColor(Vec3f(0.0f, 1.0f, 0.0f)); + listBoxPlayerStatus.setLighted(false); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (checkBoxPublishServer.getValue() == true) { + needToRepublishToMasterserver = true; + } + + if (hasNetworkGameSettings() == true) { + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + } + } + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + showGeneralError = true; + generalErrorToShow = szBuf; + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); } void MenuStateCustomGame::updateAllResourceMultiplier() { - for(int j=0; j(listBoxControls[index].getSelectedItemIndex()); - if(ct == ctCpuEasy || ct == ctNetworkCpuEasy) - { - listBoxRMultiplier[index].setSelectedItem(floatToStr(GameConstants::easyMultiplier,1)); - listBoxRMultiplier[index].setEnabled(checkBoxScenario.getValue() == false); - } - else if(ct == ctCpu || ct == ctNetworkCpu) { - listBoxRMultiplier[index].setSelectedItem(floatToStr(GameConstants::normalMultiplier,1)); - listBoxRMultiplier[index].setEnabled(checkBoxScenario.getValue() == false); - } - else if(ct == ctCpuUltra || ct == ctNetworkCpuUltra) - { - listBoxRMultiplier[index].setSelectedItem(floatToStr(GameConstants::ultraMultiplier,1)); - listBoxRMultiplier[index].setEnabled(checkBoxScenario.getValue() == false); - } - else if(ct == ctCpuMega || ct == ctNetworkCpuMega) - { - listBoxRMultiplier[index].setSelectedItem(floatToStr(GameConstants::megaMultiplier,1)); - listBoxRMultiplier[index].setEnabled(checkBoxScenario.getValue() == false); - } - //if(ct == ctHuman || ct == ctNetwork || ct == ctClosed) { - else { - listBoxRMultiplier[index].setSelectedItem(floatToStr(GameConstants::normalMultiplier,1)); - listBoxRMultiplier[index].setEnabled(false); - //!!!listBoxRMultiplier[index].setEnabled(checkBoxScenario.getValue() == false); - } - - listBoxRMultiplier[index].setEditable(listBoxRMultiplier[index].getEnabled()); - listBoxRMultiplier[index].setVisible(ct != ctHuman && ct != ctNetwork && ct != ctClosed); - //listBoxRMultiplier[index].setVisible(ct != ctClosed); - - //printf("Line: %d multiplier index: %d index: %d\n",__LINE__,listBoxRMultiplier[index].getSelectedItemIndex(),index); + // printf("Line: %d multiplier index: %d index: + // %d\n",__LINE__,listBoxRMultiplier[index].getSelectedItemIndex(),index); + + ControlType ct = + static_cast(listBoxControls[index].getSelectedItemIndex()); + if (ct == ctCpuEasy || ct == ctNetworkCpuEasy) { + listBoxRMultiplier[index].setSelectedItem( + floatToStr(GameConstants::easyMultiplier, 1)); + listBoxRMultiplier[index].setEnabled(checkBoxScenario.getValue() == false); + } else if (ct == ctCpu || ct == ctNetworkCpu) { + listBoxRMultiplier[index].setSelectedItem( + floatToStr(GameConstants::normalMultiplier, 1)); + listBoxRMultiplier[index].setEnabled(checkBoxScenario.getValue() == false); + } else if (ct == ctCpuUltra || ct == ctNetworkCpuUltra) { + listBoxRMultiplier[index].setSelectedItem( + floatToStr(GameConstants::ultraMultiplier, 1)); + listBoxRMultiplier[index].setEnabled(checkBoxScenario.getValue() == false); + } else if (ct == ctCpuMega || ct == ctNetworkCpuMega) { + listBoxRMultiplier[index].setSelectedItem( + floatToStr(GameConstants::megaMultiplier, 1)); + listBoxRMultiplier[index].setEnabled(checkBoxScenario.getValue() == false); + } + // if(ct == ctHuman || ct == ctNetwork || ct == ctClosed) { + else { + listBoxRMultiplier[index].setSelectedItem( + floatToStr(GameConstants::normalMultiplier, 1)); + listBoxRMultiplier[index].setEnabled(false); + //!!!listBoxRMultiplier[index].setEnabled(checkBoxScenario.getValue() == + //! false); + } + + listBoxRMultiplier[index].setEditable(listBoxRMultiplier[index].getEnabled()); + listBoxRMultiplier[index].setVisible(ct != ctHuman && ct != ctNetwork && + ct != ctClosed); + // listBoxRMultiplier[index].setVisible(ct != ctClosed); + + // printf("Line: %d multiplier index: %d index: + // %d\n",__LINE__,listBoxRMultiplier[index].getSelectedItemIndex(),index); } bool MenuStateCustomGame::loadGameSettings(const std::string &fileName) { - // Ensure we have set the gamesettings at least once - GameSettings gameSettings; - bool result=loadGameSettingsFromFile(&gameSettings,fileName); - if(result==false) return false; - if(gameSettings.getMap() == "") { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - copyToGameSettings(&gameSettings); - } - - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - serverInterface->setGameSettings(&gameSettings,false); - - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - if(checkBoxPublishServer.getValue() == true) { - needToRepublishToMasterserver = true; - } - - if(hasNetworkGameSettings() == true) { - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); - } - return true; + // Ensure we have set the gamesettings at least once + GameSettings gameSettings; + bool result = loadGameSettingsFromFile(&gameSettings, fileName); + if (result == false) + return false; + if (gameSettings.getMap() == "") { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + copyToGameSettings(&gameSettings); + } + + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + serverInterface->setGameSettings(&gameSettings, false); + + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + MutexSafeWrapper safeMutexCLI( + (publishToClientsThread != NULL + ? publishToClientsThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + if (checkBoxPublishServer.getValue() == true) { + needToRepublishToMasterserver = true; + } + + if (hasNetworkGameSettings() == true) { + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + } + return true; } void MenuStateCustomGame::RestoreLastGameSettings() { - loadGameSettings(SAVED_SETUP_FILENAME); + loadGameSettings(SAVED_SETUP_FILENAME); } bool MenuStateCustomGame::checkNetworkPlayerDataSynch(bool checkMapCRC, - bool checkTileSetCRC, bool checkTechTreeCRC) { - ServerInterface* serverInterface = NetworkManager::getInstance().getServerInterface(); - - bool dataSynchCheckOk = true; - for(int i= 0; i < mapInfo.players; ++i) { - if(listBoxControls[i].getSelectedItemIndex() == ctNetwork) { - - MutexSafeWrapper safeMutex(serverInterface->getSlotMutex(i),CODE_AT_LINE); - ConnectionSlot *slot = serverInterface->getSlot(i,false); - if( slot != NULL && slot->isConnected() && - (slot->getAllowDownloadDataSynch() == true || - slot->getAllowGameDataSynchCheck() == true)) { - - if(checkMapCRC == true && - slot->getNetworkGameDataSynchCheckOkMap() == false) { - dataSynchCheckOk = false; - break; - } - if(checkTileSetCRC == true && - slot->getNetworkGameDataSynchCheckOkTile() == false) { - dataSynchCheckOk = false; - break; - } - if(checkTechTreeCRC == true && - slot->getNetworkGameDataSynchCheckOkTech() == false) { - dataSynchCheckOk = false; - break; - } - } - } - } - - return dataSynchCheckOk; + bool checkTileSetCRC, + bool checkTechTreeCRC) { + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + + bool dataSynchCheckOk = true; + for (int i = 0; i < mapInfo.players; ++i) { + if (listBoxControls[i].getSelectedItemIndex() == ctNetwork) { + + MutexSafeWrapper safeMutex(serverInterface->getSlotMutex(i), + CODE_AT_LINE); + ConnectionSlot *slot = serverInterface->getSlot(i, false); + if (slot != NULL && slot->isConnected() && + (slot->getAllowDownloadDataSynch() == true || + slot->getAllowGameDataSynchCheck() == true)) { + + if (checkMapCRC == true && + slot->getNetworkGameDataSynchCheckOkMap() == false) { + dataSynchCheckOk = false; + break; + } + if (checkTileSetCRC == true && + slot->getNetworkGameDataSynchCheckOkTile() == false) { + dataSynchCheckOk = false; + break; + } + if (checkTechTreeCRC == true && + slot->getNetworkGameDataSynchCheckOkTech() == false) { + dataSynchCheckOk = false; + break; + } + } + } + } + + return dataSynchCheckOk; } void MenuStateCustomGame::PlayNow(bool saveGame) { - if(listBoxTechTree.getItemCount() <= 0) { - mainMessageBoxState=1; - - char szMsg[8096]=""; - strcpy(szMsg,"Cannot start game.\nThere are no tech-trees!\n"); - printf("%s",szMsg); - - showMessageBox(szMsg, "", false); - return; - } - - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - if(saveGame == true) { - saveGameSettings(SAVED_SETUP_FILENAME); - } - - forceWaitForShutdown = false; - closeUnusedSlots(); - CoreData &coreData= CoreData::getInstance(); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - soundRenderer.playFx(coreData.getClickSoundC()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - std::vector randomFactionSelectionList; - int RandomCount = 0; - for(int i= 0; i < mapInfo.players; ++i) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - // Check for random faction selection and choose the faction now - if(listBoxControls[i].getSelectedItemIndex() != ctClosed) { - if(listBoxFactions[i].getSelectedItem() == formatString(GameConstants::RANDOMFACTION_SLOTNAME) && - listBoxFactions[i].getItemCount() > 1) { - 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); - - // Max 1000 tries to get a random, unused faction - for(int findRandomFaction = 1; findRandomFaction < 1000; ++findRandomFaction) { - Chrono seed(true); - srand((unsigned int)seed.getCurTicks() + findRandomFaction); - - int selectedFactionIndex = rand() % listBoxFactions[i].getItemCount(); - string selectedFactionName = listBoxFactions[i].getItem(selectedFactionIndex); - - 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); - - if( selectedFactionName != formatString(GameConstants::RANDOMFACTION_SLOTNAME) && - selectedFactionName != formatString(GameConstants::OBSERVER_SLOTNAME) && - std::find(randomFactionSelectionList.begin(),randomFactionSelectionList.end(),selectedFactionName) == randomFactionSelectionList.end()) { - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - listBoxFactions[i].setSelectedItem(selectedFactionName); - randomFactionSelectionList.push_back(selectedFactionName); - break; - } - } - - if(listBoxFactions[i].getSelectedItem() == formatString(GameConstants::RANDOMFACTION_SLOTNAME)) { - 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); - - // Find first real faction and use it - int factionIndexToUse = RandomCount; - for(int useIdx = 0; useIdx < listBoxFactions[i].getItemCount(); useIdx++) { - string selectedFactionName = listBoxFactions[i].getItem(useIdx); - if( selectedFactionName != formatString(GameConstants::RANDOMFACTION_SLOTNAME) && - selectedFactionName != formatString(GameConstants::OBSERVER_SLOTNAME)) { - factionIndexToUse = useIdx; - break; - } - } - listBoxFactions[i].setSelectedItemIndex(factionIndexToUse); - randomFactionSelectionList.push_back(listBoxFactions[i].getItem(factionIndexToUse)); - } - - 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()); - - RandomCount++; - } - } - } - - if(RandomCount > 0) { - needToSetChangedGameSettings = true; - } - - safeMutex.ReleaseLock(true); - safeMutexCLI.ReleaseLock(true); - GameSettings gameSettings; - copyToGameSettings(&gameSettings, true); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - - // Send the game settings to each client if we have at least one networked client - safeMutex.Lock(); - safeMutexCLI.Lock(); - - bool dataSynchCheckOk = checkNetworkPlayerDataSynch(true, true, true); - - // Ensure we have no dangling network players - for(int i= 0; i < GameConstants::maxPlayers; ++i) { - if(listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) { - mainMessageBoxState=1; - - Lang &lang= Lang::getInstance(); - string sMsg = ""; - if(lang.hasString("NetworkSlotUnassignedErrorUI") == true) { - sMsg = lang.getString("NetworkSlotUnassignedErrorUI"); - } - else { - sMsg = "Cannot start game.\nSome player(s) are not in a network game slot!"; - } - - showMessageBox(sMsg, "", false); - - const vector languageList = serverInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int j = 0; j < languageList.size(); ++j) { - char szMsg[8096]=""; - if(lang.hasString("NetworkSlotUnassignedError",languageList[j]) == true) { - string msg_string = lang.getString("NetworkSlotUnassignedError"); + if (listBoxTechTree.getItemCount() <= 0) { + mainMessageBoxState = 1; + + char szMsg[8096] = ""; + strcpy(szMsg, "Cannot start game.\nThere are no tech-trees!\n"); + printf("%s", szMsg); + + showMessageBox(szMsg, "", false); + return; + } + + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + MutexSafeWrapper safeMutexCLI( + (publishToClientsThread != NULL + ? publishToClientsThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + if (saveGame == true) { + saveGameSettings(SAVED_SETUP_FILENAME); + } + + forceWaitForShutdown = false; + closeUnusedSlots(); + CoreData &coreData = CoreData::getInstance(); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + soundRenderer.playFx(coreData.getClickSoundC()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + std::vector randomFactionSelectionList; + int RandomCount = 0; + for (int i = 0; i < mapInfo.players; ++i) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // Check for random faction selection and choose the faction now + if (listBoxControls[i].getSelectedItemIndex() != ctClosed) { + if (listBoxFactions[i].getSelectedItem() == + formatString(GameConstants::RANDOMFACTION_SLOTNAME) && + listBoxFactions[i].getItemCount() > 1) { + 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); + + // Max 1000 tries to get a random, unused faction + for (int findRandomFaction = 1; findRandomFaction < 1000; + ++findRandomFaction) { + Chrono seed(true); + srand((unsigned int)seed.getCurTicks() + findRandomFaction); + + int selectedFactionIndex = rand() % listBoxFactions[i].getItemCount(); + string selectedFactionName = + listBoxFactions[i].getItem(selectedFactionIndex); + + 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); + + if (selectedFactionName != + formatString(GameConstants::RANDOMFACTION_SLOTNAME) && + selectedFactionName != + formatString(GameConstants::OBSERVER_SLOTNAME) && + std::find(randomFactionSelectionList.begin(), + randomFactionSelectionList.end(), + selectedFactionName) == + randomFactionSelectionList.end()) { + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + listBoxFactions[i].setSelectedItem(selectedFactionName); + randomFactionSelectionList.push_back(selectedFactionName); + break; + } + } + + if (listBoxFactions[i].getSelectedItem() == + formatString(GameConstants::RANDOMFACTION_SLOTNAME)) { + 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); + + // Find first real faction and use it + int factionIndexToUse = RandomCount; + for (int useIdx = 0; useIdx < listBoxFactions[i].getItemCount(); + useIdx++) { + string selectedFactionName = listBoxFactions[i].getItem(useIdx); + if (selectedFactionName != + formatString(GameConstants::RANDOMFACTION_SLOTNAME) && + selectedFactionName != + formatString(GameConstants::OBSERVER_SLOTNAME)) { + factionIndexToUse = useIdx; + break; + } + } + listBoxFactions[i].setSelectedItemIndex(factionIndexToUse); + randomFactionSelectionList.push_back( + listBoxFactions[i].getItem(factionIndexToUse)); + } + + 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()); + + RandomCount++; + } + } + } + + if (RandomCount > 0) { + needToSetChangedGameSettings = true; + } + + safeMutex.ReleaseLock(true); + safeMutexCLI.ReleaseLock(true); + GameSettings gameSettings; + copyToGameSettings(&gameSettings, true); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + + // Send the game settings to each client if we have at least one networked + // client + safeMutex.Lock(); + safeMutexCLI.Lock(); + + bool dataSynchCheckOk = checkNetworkPlayerDataSynch(true, true, true); + + // Ensure we have no dangling network players + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + if (listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) { + mainMessageBoxState = 1; + + Lang &lang = Lang::getInstance(); + string sMsg = ""; + if (lang.hasString("NetworkSlotUnassignedErrorUI") == true) { + sMsg = lang.getString("NetworkSlotUnassignedErrorUI"); + } else { + sMsg = "Cannot start game.\nSome player(s) are not in a network game " + "slot!"; + } + + showMessageBox(sMsg, "", false); + + const vector languageList = + serverInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); + for (unsigned int j = 0; j < languageList.size(); ++j) { + char szMsg[8096] = ""; + if (lang.hasString("NetworkSlotUnassignedError", languageList[j]) == + true) { + string msg_string = lang.getString("NetworkSlotUnassignedError"); #ifdef WIN32 - strncpy(szMsg,msg_string.c_str(),min((int)msg_string.length(),8095)); + strncpy(szMsg, msg_string.c_str(), + min((int)msg_string.length(), 8095)); #else - strncpy(szMsg,msg_string.c_str(),std::min((int)msg_string.length(),8095)); + strncpy(szMsg, msg_string.c_str(), + std::min((int)msg_string.length(), 8095)); #endif - } - else { - strcpy(szMsg,"Cannot start game, some player(s) are not in a network game slot!"); - } - - serverInterface->sendTextMessage(szMsg,-1, true,languageList[j]); - } - - safeMutex.ReleaseLock(); - safeMutexCLI.ReleaseLock(); - return; - } - } - - if(dataSynchCheckOk == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - mainMessageBoxState=1; - showMessageBox("You cannot start the game because\none or more clients do not have the same game data!", "Data Mismatch Error", false); - - safeMutex.ReleaseLock(); - safeMutexCLI.ReleaseLock(); - return; - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if( (hasNetworkGameSettings() == true && - needToSetChangedGameSettings == true) || (RandomCount > 0)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - serverInterface->setGameSettings(&gameSettings,true); - serverInterface->broadcastGameSetup(&gameSettings); - - needToSetChangedGameSettings = false; - lastSetChangedGameSettings = time(NULL); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - // Last check, stop human player from being in same slot as network - if(isMasterserverMode() == false) { - bool hasHuman = false; - for(int i= 0; i < mapInfo.players; ++i) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - // Check for random faction selection and choose the faction now - if(listBoxControls[i].getSelectedItemIndex() == ctHuman) { - hasHuman = true; - break; - } - } - if(hasHuman == false) { - mainMessageBoxState=1; - - Lang &lang= Lang::getInstance(); - string sMsg = lang.getString("NetworkSlotNoHumanErrorUI","",true); - showMessageBox(sMsg, "", false); - - const vector languageList = serverInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int j = 0; j < languageList.size(); ++j) { - sMsg = lang.getString("NetworkSlotNoHumanError","",true); - - serverInterface->sendTextMessage(sMsg,-1, true,languageList[j]); - } - - safeMutex.ReleaseLock(); - safeMutexCLI.ReleaseLock(); - return; - } - } - - // Tell the server Interface whether or not to publish game status updates to masterserver - serverInterface->setNeedToRepublishToMasterserver(checkBoxPublishServer.getValue() == true); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - bool bOkToStart = serverInterface->launchGame(&gameSettings); - if(bOkToStart == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if( checkBoxPublishServer.getEditable() && - checkBoxPublishServer.getValue() == true) { - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - needToRepublishToMasterserver = true; - lastMasterserverPublishing = 0; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - needToBroadcastServerSettings = false; - needToRepublishToMasterserver = false; - lastNetworkPing = time(NULL); - safeMutex.ReleaseLock(); - safeMutexCLI.ReleaseLock(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - assert(program != NULL); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - cleanup(); - Game *newGame = new Game(program, &gameSettings, this->headlessServerMode); - forceWaitForShutdown = false; - program->setState(newGame); - return; - } - else { - safeMutex.ReleaseLock(); - safeMutexCLI.ReleaseLock(); - } - } -} - - -void MenuStateCustomGame::eventMouseWheel(int x, int y,int zDelta) { - if(isMasterserverMode() == true) { - return; - } - comboBoxMap.eventMouseWheel(x,y,zDelta); - comboBoxLoadSetup.eventMouseWheel(x,y,zDelta); -} + } else { + strcpy(szMsg, "Cannot start game, some player(s) are not in a " + "network game slot!"); + } -void MenuStateCustomGame::mouseMove(int x, int y, const MouseState *ms) { - if(isMasterserverMode() == true) { - return; - } - - if (mainMessageBox.getEnabled()) { - mainMessageBox.mouseMove(x, y); - } - - - comboBoxMap.mouseMove(x, y); - if (comboBoxMap.isDropDownShowing()) { - if (ms->get(mbLeft)) { - comboBoxMap.mouseDown(x, y); - } - if(lastPreviewedMapFile!=getPreselectedMapFile()){ - loadMapInfo(Config::getMapPath(getPreselectedMapFile(), "", false), &mapInfo, true, false); - labelMapInfo.setText(mapInfo.desc); - lastPreviewedMapFile=getPreselectedMapFile(); - } - } - - comboBoxLoadSetup.mouseMove(x, y); - if (comboBoxLoadSetup.isDropDownShowing()) { - if (ms->get(mbLeft)) { - comboBoxLoadSetup.mouseDown(x, y); - } - } - buttonSaveSetup.mouseMove(x, y); - buttonLoadSetup.mouseMove(x, y); - buttonDeleteSetup.mouseMove(x, y); - - buttonReturn.mouseMove(x, y); - buttonPlayNow.mouseMove(x, y); - buttonClearBlockedPlayers.mouseMove(x, y); - - for(int i = 0; i < GameConstants::maxPlayers; ++i) { - listBoxRMultiplier[i].mouseMove(x, y); - listBoxControls[i].mouseMove(x, y); - buttonBlockPlayers[i].mouseMove(x, y); - listBoxFactions[i].mouseMove(x, y); - listBoxTeams[i].mouseMove(x, y); - } - - - if(checkBoxAdvanced.getValue() == 1) { - listBoxFogOfWar.mouseMove(x, y); - checkBoxAllowObservers.mouseMove(x, y); - - buttonShowLanInfo.mouseMove(x,y); - - checkBoxEnableSwitchTeamMode.mouseMove(x, y); - listBoxAISwitchTeamAcceptPercent.mouseMove(x, y); - listBoxFallbackCpuMultiplier.mouseMove(x, y); - - labelNetworkPauseGameForLaggedClients.mouseMove(x, y); - checkBoxNetworkPauseGameForLaggedClients.mouseMove(x, y); - - labelAllowTeamUnitSharing.mouseMove(x,y); - checkBoxAllowTeamUnitSharing.mouseMove(x,y); - labelAllowTeamResourceSharing.mouseMove(x,y); - checkBoxAllowTeamResourceSharing.mouseMove(x,y); - - } - checkBoxAllowInGameJoinPlayer.mouseMove(x, y); - - checkBoxAllowNativeLanguageTechtree.mouseMove(x, y); - - listBoxTileset.mouseMove(x, y); - listBoxMapFilter.mouseMove(x, y); - listBoxTechTree.mouseMove(x, y); - checkBoxPublishServer.mouseMove(x, y); - - checkBoxAdvanced.mouseMove(x, y); - - checkBoxScenario.mouseMove(x, y); - listBoxScenario.mouseMove(x, y); -} + serverInterface->sendTextMessage(szMsg, -1, true, languageList[j]); + } -bool MenuStateCustomGame::isMasterserverMode() const { - return (this->headlessServerMode == true && this->masterserverModeMinimalResources == true); - //return false; -} + safeMutex.ReleaseLock(); + safeMutexCLI.ReleaseLock(); + return; + } + } + + if (dataSynchCheckOk == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + mainMessageBoxState = 1; + showMessageBox("You cannot start the game because\none or more clients do " + "not have the same game data!", + "Data Mismatch Error", false); + + safeMutex.ReleaseLock(); + safeMutexCLI.ReleaseLock(); + return; + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + if ((hasNetworkGameSettings() == true && + needToSetChangedGameSettings == true) || + (RandomCount > 0)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + serverInterface->setGameSettings(&gameSettings, true); + serverInterface->broadcastGameSetup(&gameSettings); + + needToSetChangedGameSettings = false; + lastSetChangedGameSettings = time(NULL); + } -bool MenuStateCustomGame::isVideoPlaying() { - bool result = false; - if(factionVideo != NULL) { - result = factionVideo->isPlaying(); - } - return result; -} + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // Last check, stop human player from being in same slot as network + if (isMasterserverMode() == false) { + bool hasHuman = false; + for (int i = 0; i < mapInfo.players; ++i) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + // Check for random faction selection and choose the faction now + if (listBoxControls[i].getSelectedItemIndex() == ctHuman) { + hasHuman = true; + break; + } + } + if (hasHuman == false) { + mainMessageBoxState = 1; -void MenuStateCustomGame::render() { - try { - Renderer &renderer= Renderer::getInstance(); - - if(mainMessageBox.getEnabled() == false) { - if(factionTexture != NULL) { - if(factionVideo == NULL || factionVideo->isPlaying() == false) { - renderer.renderTextureQuad(800,600,200,150,factionTexture,1.0f); - } - } - } - if(factionVideo != NULL) { - if(factionVideo->isPlaying() == true) { - factionVideo->playFrame(false); - } - else { - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && - ::Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == true) { - if(factionVideo != NULL) { - factionVideo->closePlayer(); - delete factionVideo; - factionVideo = NULL; - - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - if(serverInterface != NULL) { - initFactionPreview(serverInterface->getGameSettings()); - } - } - } - } - } - - if(mainMessageBox.getEnabled()) { - renderer.renderMessageBox(&mainMessageBox); - - renderer.renderButton(&buttonReturn); - } - else { - if(mapPreviewTexture != NULL) { - //renderer.renderTextureQuad(5,185,150,150,mapPreviewTexture,1.0f); - renderer.renderTextureQuad( this->render_mapPreviewTexture_X, - this->render_mapPreviewTexture_Y, - this->render_mapPreviewTexture_W, - this->render_mapPreviewTexture_H, - mapPreviewTexture,1.0f); - if(this->zoomedMap==true) { - return; - } - //printf("=================> Rendering map preview texture\n"); - } - if(scenarioLogoTexture != NULL) { - renderer.renderTextureQuad(300,350,400,300,scenarioLogoTexture,1.0f); - //renderer.renderBackground(scenarioLogoTexture); - } - - renderer.renderButton(&buttonReturn); - renderer.renderButton(&buttonPlayNow); - - renderer.renderLabel(&labelSaveSetupName); - renderer.renderButton(&buttonSaveSetup); - renderer.renderButton(&buttonLoadSetup); - renderer.renderButton(&buttonDeleteSetup); - - - // Get a reference to the player texture cache - std::map &crcPlayerTextureCache = CacheManager::getCachedItem< std::map >(GameConstants::playerTextureCacheLookupKey); - - // START - this code ensure player title and player names don't overlap - int offsetPosition=0; - for(int i=0; i < GameConstants::maxPlayers; ++i) { - FontMetrics *fontMetrics= NULL; - if(Renderer::renderText3DEnabled == false) { - fontMetrics = labelPlayers[i].getFont()->getMetrics(); - } - else { - fontMetrics = labelPlayers[i].getFont3D()->getMetrics(); - } - if(fontMetrics == NULL) { - throw megaglest_runtime_error("fontMetrics == NULL"); - } - int curWidth = (fontMetrics->getTextWidth(labelPlayers[i].getText())); - int newOffsetPosition = labelPlayers[i].getX() + curWidth + 2; - - //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()); - - if(labelPlayers[i].getX() + curWidth >= labelPlayerNames[i].getX()) { - if(offsetPosition < newOffsetPosition) { - offsetPosition = newOffsetPosition; - } - } - } - // END - - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - if(hasNetworkGameSettings() == true) { - renderer.renderListBox(&listBoxPlayerStatus); - if( serverInterface != NULL && - buttonClearBlockedPlayers.getEditable() && - serverInterface->getServerSocket() != NULL ) { - renderer.renderButton(&buttonClearBlockedPlayers); - } - } - for(int i = 0; i < GameConstants::maxPlayers; ++i) { - if(listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) { - //printf("Player #%d [%s] control = %d\n",i,labelPlayerNames[i].getText().c_str(),listBoxControls[i].getSelectedItemIndex()); - - labelPlayers[i].setVisible(true); - labelPlayerNames[i].setVisible(true); - listBoxControls[i].setVisible(true); - listBoxFactions[i].setVisible(true); - listBoxTeams[i].setVisible(true); - labelNetStatus[i].setVisible(true); - } - - if( hasNetworkGameSettings() == true && - listBoxControls[i].getSelectedItemIndex() != ctClosed) { - - renderer.renderLabel(&labelPlayerStatus[i]); - } - - if(crcPlayerTextureCache[i] != NULL) { - // Render the player # label the player's color - Vec3f playerColor = crcPlayerTextureCache[i]->getPixmap()->getPixel3f(0, 0); - renderer.renderLabel(&labelPlayers[i],&playerColor); - } - else { - renderer.renderLabel(&labelPlayers[i]); - } - - if(offsetPosition > 0) { - labelPlayerNames[i].setX(offsetPosition); - } - renderer.renderLabel(&labelPlayerNames[i]); - - renderer.renderListBox(&listBoxControls[i]); - - if( hasNetworkGameSettings() == true && - listBoxControls[i].getSelectedItemIndex() != ctClosed) { - - renderer.renderLabel(&labelPlayerStatus[i]); - - if(listBoxControls[i].getSelectedItemIndex() == ctNetwork || listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) { - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - if( serverInterface != NULL && - serverInterface->getSlot(i,true) != NULL && - serverInterface->getSlot(i,true)->isConnected()) { - renderer.renderButton(&buttonBlockPlayers[i]); - } - } - } - - if(listBoxControls[i].getSelectedItemIndex()!=ctClosed){ - renderer.renderListBox(&listBoxRMultiplier[i]); - renderer.renderListBox(&listBoxFactions[i]); - - int teamnumber=listBoxTeams[i].getSelectedItemIndex(); - Vec3f teamcolor=Vec3f(1.0f,1.0f,1.0f); - if(teamnumber>=0 && teamnumber<8){ - teamcolor=crcPlayerTextureCache[teamnumber]->getPixmap()->getPixel3f(0, 0); - } - listBoxTeams[i].setTextColor(teamcolor); - - renderer.renderListBox(&listBoxTeams[i]); - renderer.renderLabel(&labelNetStatus[i]); - } - } - renderer.renderLabel(&labelMap); - - if(checkBoxAdvanced.getValue() == 1) { - renderer.renderLabel(&labelFogOfWar); - renderer.renderListBox(&listBoxFogOfWar); - - renderer.renderLabel(&labelAllowTeamUnitSharing); - renderer.renderCheckBox(&checkBoxAllowTeamUnitSharing); - - renderer.renderButton(&buttonShowLanInfo); - - renderer.renderLabel(&labelAllowTeamResourceSharing); - renderer.renderCheckBox(&checkBoxAllowTeamResourceSharing); - - renderer.renderLabel(&labelAllowNativeLanguageTechtree); - renderer.renderCheckBox(&checkBoxAllowNativeLanguageTechtree); - - renderer.renderLabel(&labelAllowObservers); - renderer.renderCheckBox(&checkBoxAllowObservers); - - renderer.renderCheckBox(&checkBoxEnableSwitchTeamMode); - renderer.renderLabel(&labelEnableSwitchTeamMode); - renderer.renderListBox(&listBoxAISwitchTeamAcceptPercent); - renderer.renderLabel(&labelAISwitchTeamAcceptPercent); - - renderer.renderCheckBox(&checkBoxScenario); - renderer.renderLabel(&labelScenario); - if(checkBoxScenario.getValue() == true) { - renderer.renderListBox(&listBoxScenario); - } - } - renderer.renderLabel(&labelAllowInGameJoinPlayer); - renderer.renderCheckBox(&checkBoxAllowInGameJoinPlayer); - - renderer.renderLabel(&labelTileset); - renderer.renderLabel(&labelMapFilter); - renderer.renderLabel(&labelTechTree); - renderer.renderLabel(&labelControl); - renderer.renderLabel(&labelFaction); - renderer.renderLabel(&labelTeam); - renderer.renderLabel(&labelMapInfo); - renderer.renderLabel(&labelAdvanced); - - renderer.renderListBox(&listBoxTileset); - renderer.renderListBox(&listBoxMapFilter); - renderer.renderListBox(&listBoxTechTree); - renderer.renderCheckBox(&checkBoxAdvanced); - - if(checkBoxPublishServer.getEditable()) - { - renderer.renderCheckBox(&checkBoxPublishServer); - renderer.renderLabel(&labelPublishServer); - renderer.renderLabel(&labelGameName); - if(checkBoxAdvanced.getValue() == 1) { - renderer.renderLabel(&labelNetworkPauseGameForLaggedClients); - renderer.renderCheckBox(&checkBoxNetworkPauseGameForLaggedClients); - renderer.renderListBox(&listBoxFallbackCpuMultiplier); - renderer.renderLabel(&labelFallbackCpuMultiplier); - } - } - } - - renderer.renderConsole(&console,showFullConsole?consoleFull:consoleStoredAndNormal); - - if(program != NULL) program->renderProgramMsgBox(); - - if(mainMessageBox.getEnabled() == false) { - if(hasNetworkGameSettings() == true) { - renderer.renderChatManager(&chatManager); - } - } - renderer.renderComboBox(&comboBoxMap); - renderer.renderComboBox(&comboBoxLoadSetup); - - if( enableMapPreview == true && - mapPreview.hasFileLoaded() == true) { - - if(mapPreviewTexture == NULL) { - bool renderAll = (listBoxFogOfWar.getSelectedItemIndex() == 2); - //printf("=================> Rendering map preview into a texture BEFORE (%p)\n", mapPreviewTexture); - - //renderer.renderMapPreview(&mapPreview, renderAll, 10, 350,&mapPreviewTexture); - renderer.renderMapPreview(&mapPreview, renderAll, - this->render_mapPreviewTexture_X, - this->render_mapPreviewTexture_Y, - &mapPreviewTexture); - - //printf("=================> Rendering map preview into a texture AFTER (%p)\n", mapPreviewTexture); - } - } - - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - //throw megaglest_runtime_error(szBuf); - - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - showGeneralError=true; - generalErrorToShow = szBuf; - } -} + Lang &lang = Lang::getInstance(); + string sMsg = lang.getString("NetworkSlotNoHumanErrorUI", "", true); + showMessageBox(sMsg, "", false); -void MenuStateCustomGame::switchSetupForSlots(SwitchSetupRequest **switchSetupRequests, - ServerInterface *& serverInterface, int startIndex, int endIndex, bool onlyNetworkUnassigned) { - for(int i= startIndex; i < endIndex; ++i) { - if(switchSetupRequests[i] != NULL) { - //printf("Switch slot = %d control = %d newIndex = %d currentindex = %d onlyNetworkUnassigned = %d\n",i,listBoxControls[i].getSelectedItemIndex(),switchSetupRequests[i]->getToFactionIndex(),switchSetupRequests[i]->getCurrentFactionIndex(),onlyNetworkUnassigned); - - 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()); - - if(onlyNetworkUnassigned == true && listBoxControls[i].getSelectedItemIndex() != ctNetworkUnassigned) { - if(i < mapInfo.players || (i >= mapInfo.players && listBoxControls[i].getSelectedItemIndex() != ctNetwork)) { - continue; - } - } - - if(listBoxControls[i].getSelectedItemIndex() == ctNetwork || listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) { - 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()); - - if(switchSetupRequests[i]->getToSlotIndex() != -1) { - int newFactionIdx = switchSetupRequests[i]->getToSlotIndex(); - - //printf("switchSlot request from %d to %d\n",switchSetupRequests[i]->getCurrentFactionIndex(),switchSetupRequests[i]->getToFactionIndex()); - int switchFactionIdx = switchSetupRequests[i]->getCurrentSlotIndex(); - if(serverInterface->switchSlot(switchFactionIdx,newFactionIdx)) { - try { - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - ConnectionSlot *slot = serverInterface->getSlot(newFactionIdx,true); - - if(switchSetupRequests[i]->getSelectedFactionName() != "" && - (slot != NULL && - switchSetupRequests[i]->getSelectedFactionName() != Lang::getInstance().getString("DataMissing",slot->getNetworkPlayerLanguage(),true) && - switchSetupRequests[i]->getSelectedFactionName() != "???DataMissing???")) { - listBoxFactions[newFactionIdx].setSelectedItem(switchSetupRequests[i]->getSelectedFactionName()); - } - if(switchSetupRequests[i]->getToTeam() != -1) { - listBoxTeams[newFactionIdx].setSelectedItemIndex(switchSetupRequests[i]->getToTeam()); - } - if(switchSetupRequests[i]->getNetworkPlayerName() != "") { - 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()); - labelPlayerNames[newFactionIdx].setText(switchSetupRequests[i]->getNetworkPlayerName()); - } - - if(listBoxControls[switchFactionIdx].getSelectedItemIndex() == ctNetworkUnassigned) { - serverInterface->removeSlot(switchFactionIdx); - listBoxControls[switchFactionIdx].setSelectedItemIndex(ctClosed); - - labelPlayers[switchFactionIdx].setVisible(switchFactionIdx+1 <= mapInfo.players); - labelPlayerNames[switchFactionIdx].setVisible(switchFactionIdx+1 <= mapInfo.players); - listBoxControls[switchFactionIdx].setVisible(switchFactionIdx+1 <= mapInfo.players); - listBoxFactions[switchFactionIdx].setVisible(switchFactionIdx+1 <= mapInfo.players); - listBoxTeams[switchFactionIdx].setVisible(switchFactionIdx+1 <= mapInfo.players); - labelNetStatus[switchFactionIdx].setVisible(switchFactionIdx+1 <= mapInfo.players); - } - } - catch(const runtime_error &e) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what()); - 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()); - } - } - } - else { - try { - int factionIdx = switchSetupRequests[i]->getCurrentSlotIndex(); - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - ConnectionSlot *slot = serverInterface->getSlot(factionIdx,true); - - if(switchSetupRequests[i]->getSelectedFactionName() != "" && - (slot != NULL && - switchSetupRequests[i]->getSelectedFactionName() != Lang::getInstance().getString("DataMissing",slot->getNetworkPlayerLanguage(),true) && - switchSetupRequests[i]->getSelectedFactionName() != "???DataMissing???")) { - listBoxFactions[i].setSelectedItem(switchSetupRequests[i]->getSelectedFactionName()); - } - if(switchSetupRequests[i]->getToTeam() != -1) { - listBoxTeams[i].setSelectedItemIndex(switchSetupRequests[i]->getToTeam()); - } - - if((switchSetupRequests[i]->getSwitchFlags() & ssrft_NetworkPlayerName) == ssrft_NetworkPlayerName) { - 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()); - - if(switchSetupRequests[i]->getNetworkPlayerName() != GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME) { - labelPlayerNames[i].setText(switchSetupRequests[i]->getNetworkPlayerName()); - } - else { - labelPlayerNames[i].setText(""); - } - } - } - catch(const runtime_error &e) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what()); - 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()); - } - } - } - - delete switchSetupRequests[i]; - switchSetupRequests[i]=NULL; - } - } -} + const vector languageList = + serverInterface->getGameSettings() + ->getUniqueNetworkPlayerLanguages(); + for (unsigned int j = 0; j < languageList.size(); ++j) { + sMsg = lang.getString("NetworkSlotNoHumanError", "", true); -void MenuStateCustomGame::update() { - Chrono chrono; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); - - // Test openal buffer underrun issue - //sleep(200); - // END - - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - try { - if(serverInitError == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(showGeneralError) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - - showGeneralError=false; - mainMessageBoxState=1; - showMessageBox( generalErrorToShow, "Error", false); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(this->headlessServerMode == false) { - return; - } - } - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - Lang& lang= Lang::getInstance(); - - if( serverInterface != NULL && serverInterface->getServerSocket() != NULL ){ - buttonClearBlockedPlayers.setEditable( serverInterface->getServerSocket()->hasBlockedIPAddresses()); - } - - if(comboBoxMap.isDropDownShowing()){ - labelMapInfo.setX(0); - labelMapInfo.setY(mapPreviewTexture_Y-40); - } - else{ - labelMapInfo.setX(165); - labelMapInfo.setY(mapPreviewTexture_Y+mapPreviewTexture_H-60); - } - if(this->autoloadScenarioName != "") { - listBoxScenario.setSelectedItem(formatString(this->autoloadScenarioName),false); - lastSetChangedGameSettings = time(NULL); - if(serverInterface != NULL){ - lastGameSettingsreceivedCount=serverInterface->getGameSettingsUpdateCount(); - } - if(listBoxScenario.getSelectedItem() != formatString(this->autoloadScenarioName)) { - mainMessageBoxState=1; - showMessageBox( "Could not find scenario name: " + formatString(this->autoloadScenarioName), "Scenario Missing", false); - this->autoloadScenarioName = ""; - } - else { - loadScenarioInfo(Scenario::getScenarioPath(dirList, scenarioFiles[listBoxScenario.getSelectedItemIndex()]), &scenarioInfo); - //labelInfo.setText(scenarioInfo.desc); - - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - CoreData &coreData= CoreData::getInstance(); - soundRenderer.playFx(coreData.getClickSoundC()); - //launchGame(); - PlayNow(true); - return; - } - } - - if(needToLoadTextures) { - // this delay is done to make it possible to switch faster - if(difftime((long int)time(NULL), previewLoadDelayTimer) >= 2){ - //loadScenarioPreviewTexture(); - needToLoadTextures= false; - } - } - - //bool haveAtLeastOneNetworkClientConnected = false; - bool hasOneNetworkSlotOpen = false; - int currentConnectionCount=0; - Config &config = Config::getInstance(); - - bool masterServerErr = showMasterserverError; - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - if(masterServerErr) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(EndsWith(masterServererErrorToShow, "wrong router setup") == true) { - masterServererErrorToShow=lang.getString("WrongRouterSetup"); - } - - Lang &lang= Lang::getInstance(); - string publishText = " (disabling publish)"; - if(lang.hasString("PublishDisabled") == true) { - publishText = lang.getString("PublishDisabled"); - } - - masterServererErrorToShow += "\n\n"+ publishText; - showMasterserverError=false; - mainMessageBoxState=1; - showMessageBox( masterServererErrorToShow, lang.getString("ErrorFromMasterserver"), false); - - if(this->headlessServerMode == false) { - checkBoxPublishServer.setValue(false); - } - - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - serverInterface->setPublishEnabled(checkBoxPublishServer.getValue() == true); - } - else if(showGeneralError) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - showGeneralError=false; - mainMessageBoxState=1; - showMessageBox( generalErrorToShow, "Error", false); - } - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - if(this->headlessServerMode == true && serverInterface == NULL) { - throw megaglest_runtime_error("serverInterface == NULL"); - } - if(this->headlessServerMode == true && serverInterface->getGameSettingsUpdateCount() > lastMasterServerSettingsUpdateCount && - serverInterface->getGameSettings() != NULL) { - const GameSettings *settings = serverInterface->getGameSettings(); - //printf("\n\n\n\n=====#1 got settings [%d] [%d]:\n%s\n",lastMasterServerSettingsUpdateCount,serverInterface->getGameSettingsUpdateCount(),settings->toString().c_str()); - - lastMasterServerSettingsUpdateCount = serverInterface->getGameSettingsUpdateCount(); - //printf("#2 custom menu got map [%s]\n",settings->getMap().c_str()); - - setupUIFromGameSettings(*settings); - printf("received Settings map filter=%d\n",settings->getMapFilter()); - - GameSettings gameSettings; - copyToGameSettings(&gameSettings); - - //printf("\n\n\n\n=====#1.1 got settings [%d] [%d]:\n%s\n",lastMasterServerSettingsUpdateCount,serverInterface->getGameSettingsUpdateCount(),gameSettings.toString().c_str()); - - } - if(this->headlessServerMode == true && serverInterface->getMasterserverAdminRequestLaunch() == true) { - serverInterface->setMasterserverAdminRequestLaunch(false); - safeMutex.ReleaseLock(); - safeMutexCLI.ReleaseLock(); - - PlayNow(false); - return; - } - - // handle setting changes from clients - SwitchSetupRequest ** switchSetupRequests = serverInterface->getSwitchSetupRequests(); - //!!! - switchSetupForSlots(switchSetupRequests, serverInterface, 0, mapInfo.players, false); - switchSetupForSlots(switchSetupRequests, serverInterface, mapInfo.players, GameConstants::maxPlayers, true); - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - GameSettings gameSettings; - copyToGameSettings(&gameSettings); - - listBoxAISwitchTeamAcceptPercent.setVisible(checkBoxEnableSwitchTeamMode.getValue()); - labelAISwitchTeamAcceptPercent.setVisible(checkBoxEnableSwitchTeamMode.getValue()); - - int factionCount = 0; - for(int i= 0; i< mapInfo.players; ++i) { - if(hasNetworkGameSettings() == true) { - if(listBoxControls[i].getSelectedItemIndex() != ctClosed) { - int slotIndex = factionCount; - if(listBoxControls[i].getSelectedItemIndex() == ctHuman) { - switch(gameSettings.getNetworkPlayerStatuses(slotIndex)) { - case npst_BeRightBack: - labelPlayerStatus[i].setTexture(CoreData::getInstance().getStatusBRBTexture()); - break; - case npst_Ready: - labelPlayerStatus[i].setTexture(CoreData::getInstance().getStatusReadyTexture()); - break; - case npst_PickSettings: - labelPlayerStatus[i].setTexture(CoreData::getInstance().getStatusNotReadyTexture()); - break; - case npst_Disconnected: - labelPlayerStatus[i].setTexture(NULL); - break; - - default: - labelPlayerStatus[i].setTexture(NULL); - break; - } - } - else { - labelPlayerStatus[i].setTexture(NULL); - } - - factionCount++; - } - else { - labelPlayerStatus[i].setTexture(NULL); - } - } - - if(listBoxControls[i].getSelectedItemIndex() == ctNetwork || - listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) { - hasOneNetworkSlotOpen=true; - - if(serverInterface->getSlot(i,true) != NULL && - serverInterface->getSlot(i,true)->isConnected()) { - - if(hasNetworkGameSettings() == true) { - switch(serverInterface->getSlot(i,true)->getNetworkPlayerStatus()) { - case npst_BeRightBack: - labelPlayerStatus[i].setTexture(CoreData::getInstance().getStatusBRBTexture()); - break; - case npst_Ready: - labelPlayerStatus[i].setTexture(CoreData::getInstance().getStatusReadyTexture()); - break; - case npst_PickSettings: - default: - labelPlayerStatus[i].setTexture(CoreData::getInstance().getStatusNotReadyTexture()); - break; - } - } - - serverInterface->getSlot(i,true)->setName(labelPlayerNames[i].getText()); - - //printf("FYI we have at least 1 client connected, slot = %d'\n",i); - - //haveAtLeastOneNetworkClientConnected = true; - if(serverInterface->getSlot(i,true) != NULL && - serverInterface->getSlot(i,true)->getConnectHasHandshaked()) { - currentConnectionCount++; - } - string label = (serverInterface->getSlot(i,true) != NULL ? serverInterface->getSlot(i,true)->getVersionString() : ""); - - if(serverInterface->getSlot(i,true) != NULL && - serverInterface->getSlot(i,true)->getAllowDownloadDataSynch() == true && - serverInterface->getSlot(i,true)->getAllowGameDataSynchCheck() == true) { - if(serverInterface->getSlot(i,true)->getNetworkGameDataSynchCheckOk() == false) { - label += " -waiting to synch:"; - if(serverInterface->getSlot(i,true)->getNetworkGameDataSynchCheckOkMap() == false) { - label = label + " map"; - } - if(serverInterface->getSlot(i,true)->getNetworkGameDataSynchCheckOkTile() == false) { - label = label + " tile"; - } - if(serverInterface->getSlot(i,true)->getNetworkGameDataSynchCheckOkTech() == false) { - label = label + " techtree"; - } - } - else { - label += " - data synch is ok"; - } - } - else { - if(serverInterface->getSlot(i,true) != NULL && - serverInterface->getSlot(i,true)->getAllowGameDataSynchCheck() == true && - serverInterface->getSlot(i,true)->getNetworkGameDataSynchCheckOk() == false) { - label += " -synch mismatch:"; - - if(serverInterface->getSlot(i,true) != NULL && serverInterface->getSlot(i,true)->getNetworkGameDataSynchCheckOkMap() == false) { - label = label + " map"; - - if(serverInterface->getSlot(i,true)->getReceivedDataSynchCheck() == true && - lastMapDataSynchError != "map CRC mismatch, " + comboBoxMap.getSelectedItem()) { - lastMapDataSynchError = "map CRC mismatch, " + comboBoxMap.getSelectedItem(); - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - serverInterface->sendTextMessage(lastMapDataSynchError,-1, true,""); - } - } - - if(serverInterface->getSlot(i,true) != NULL && - serverInterface->getSlot(i,true)->getNetworkGameDataSynchCheckOkTile() == false) { - label = label + " tile"; - - if(serverInterface->getSlot(i,true)->getReceivedDataSynchCheck() == true && - lastTileDataSynchError != "tile CRC mismatch, " + listBoxTileset.getSelectedItem()) { - lastTileDataSynchError = "tile CRC mismatch, " + listBoxTileset.getSelectedItem(); - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - serverInterface->sendTextMessage(lastTileDataSynchError,-1,true,""); - } - } - - if(serverInterface->getSlot(i,true) != NULL && - serverInterface->getSlot(i,true)->getNetworkGameDataSynchCheckOkTech() == false) { - { - // Ensure local CRC cache is correct - setRefreshedCrcToGameSettings(serverInterface->getGameSettingsPtr()); - } - label = label + " techtree"; - - if(serverInterface->getSlot(i,true)->getReceivedDataSynchCheck() == true) { - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - string report = serverInterface->getSlot(i,true)->getNetworkGameDataSynchCheckTechMismatchReport(); - - if(lastTechtreeDataSynchError != "techtree CRC mismatch" + report) { - lastTechtreeDataSynchError = "techtree CRC mismatch" + report; - - 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()); - - serverInterface->sendTextMessage("techtree CRC mismatch",-1,true,""); - vector reportLineTokens; - Tokenize(report,reportLineTokens,"\n"); - for(int reportLine = 0; reportLine < (int)reportLineTokens.size(); ++reportLine) { - serverInterface->sendTextMessage(reportLineTokens[reportLine],-1,true,""); - } - } - } - } - - if(serverInterface->getSlot(i,true) != NULL) { - serverInterface->getSlot(i,true)->setReceivedDataSynchCheck(false); - } - } - } - - //float pingTime = serverInterface->getSlot(i)->getThreadedPingMS(serverInterface->getSlot(i)->getIpAddress().c_str()); - char szBuf[8096]=""; - snprintf(szBuf,8096,"%s",label.c_str()); - - labelNetStatus[i].setText(szBuf); - } - else { - string port = "("+intToStr(config.getInt("PortServer"))+")"; - labelNetStatus[i].setText("--- " + port); - } - } - else if(listBoxControls[i].getSelectedItemIndex() == ctHuman) - { - if(EndsWith(glestVersionString, "-dev") == false) { - labelNetStatus[i].setText(glestVersionString); - } - else { - //labelLocalGameVersion.setText(glestVersionString + " [" + getCompileDateTime() + ", " + getGITRevisionString() + "]"); - labelNetStatus[i].setText(glestVersionString + " [" + getGITRevisionString() + "]"); - } - } - else { - labelNetStatus[i].setText(""); - } - } - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - //ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - - if(checkBoxScenario.getValue() == false) { - for(int i= 0; i< GameConstants::maxPlayers; ++i) { - if(i >= mapInfo.players) { - listBoxControls[i].setEditable(false); - listBoxControls[i].setEnabled(false); - - //printf("In [%s::%s] Line: %d i = %d mapInfo.players = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,mapInfo.players); - } - else if(listBoxControls[i].getSelectedItemIndex() != ctNetworkUnassigned) { - ConnectionSlot *slot = serverInterface->getSlot(i,true); - if((listBoxControls[i].getSelectedItemIndex() != ctNetwork) || - (listBoxControls[i].getSelectedItemIndex() == ctNetwork && (slot == NULL || slot->isConnected() == false))) { - listBoxControls[i].setEditable(true); - listBoxControls[i].setEnabled(true); - } - else { - listBoxControls[i].setEditable(false); - listBoxControls[i].setEnabled(false); - - //printf("In [%s::%s] Line: %d i = %d mapInfo.players = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,mapInfo.players); - } - } - else { - listBoxControls[i].setEditable(false); - listBoxControls[i].setEnabled(false); - - //printf("In [%s::%s] Line: %d i = %d mapInfo.players = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,mapInfo.players); - } - } - } - - bool checkDataSynch = (serverInterface->getAllowGameDataSynchCheck() == true && - needToSetChangedGameSettings == true && - (( difftime((long int)time(NULL),lastSetChangedGameSettings) >= BROADCAST_SETTINGS_SECONDS)|| - (this->headlessServerMode == true))); - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - // Send the game settings to each client if we have at least one networked client - if(checkDataSynch == true) { - serverInterface->setGameSettings(&gameSettings,false); - needToSetChangedGameSettings = false; - } - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - if(this->headlessServerMode == true || hasOneNetworkSlotOpen == true || - checkBoxAllowInGameJoinPlayer.getValue() == true) { - if(this->headlessServerMode == true && - GlobalStaticFlags::isFlagSet(gsft_lan_mode) == false) { - checkBoxPublishServer.setValue(true); - } - listBoxFallbackCpuMultiplier.setEditable(true); - checkBoxPublishServer.setEditable(true); - - // Masterserver always needs one network slot - if(this->headlessServerMode == true && hasOneNetworkSlotOpen == false) { - bool anyoneConnected = false; - for(int i= 0; i < mapInfo.players; ++i) { - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - ConnectionSlot *slot = serverInterface->getSlot(i,true); - if(slot != NULL && slot->isConnected() == true) { - anyoneConnected = true; - break; - } - } - - for(int i= 0; i < mapInfo.players; ++i) { - if(anyoneConnected == false && listBoxControls[i].getSelectedItemIndex() != ctNetwork) { - listBoxControls[i].setSelectedItemIndex(ctNetwork); - } - } - - updateNetworkSlots(); - } - } - else { - checkBoxPublishServer.setValue(false); - checkBoxPublishServer.setEditable(false); - listBoxFallbackCpuMultiplier.setEditable(false); - - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - serverInterface->setPublishEnabled(checkBoxPublishServer.getValue() == true); - } - - bool republishToMaster = (difftime((long int)time(NULL),lastMasterserverPublishing) >= MASTERSERVER_BROADCAST_PUBLISH_SECONDS); - - if(republishToMaster == true) { - if(checkBoxPublishServer.getValue() == true) { - needToRepublishToMasterserver = true; - lastMasterserverPublishing = time(NULL); - } - } - - bool callPublishNow = (checkBoxPublishServer.getEditable() && - checkBoxPublishServer.getValue() == true && - needToRepublishToMasterserver == true); - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - if(callPublishNow == true) { - // give it to me baby, aha aha ... - publishToMasterserver(); - } - if(needToPublishDelayed) { - // this delay is done to make it possible to switch over maps which are not meant to be distributed - if((difftime((long int)time(NULL), mapPublishingDelayTimer) >= BROADCAST_MAP_DELAY_SECONDS) || - (this->headlessServerMode == true) ){ - // after 5 seconds we are allowed to publish again! - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); - // set to normal.... - needToPublishDelayed=false; - } - } - if(needToPublishDelayed == false || headlessServerMode == true) { - bool broadCastSettings = (difftime((long int)time(NULL),lastSetChangedGameSettings) >= BROADCAST_SETTINGS_SECONDS); - - if(headlessServerMode==true){ - // publish settings directly when we receive them - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - if(lastGameSettingsreceivedCountgetGameSettingsUpdateCount()){ - needToBroadcastServerSettings=true; - lastSetChangedGameSettings = time(NULL); - lastGameSettingsreceivedCount=serverInterface->getGameSettingsUpdateCount(); - } - } - - if(broadCastSettings == true) { - needToBroadcastServerSettings=true; - lastSetChangedGameSettings = time(NULL); - } - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - //broadCastSettings = (difftime(time(NULL),lastSetChangedGameSettings) >= 2); - //if (broadCastSettings == true) {// reset timer here on bottom becasue used for different things - // lastSetChangedGameSettings = time(NULL); - //} - } - - if(this->headlessServerMode == true) { - lastPlayerDisconnected(); - } - - //call the chat manager - chatManager.updateNetwork(); - - //console - console.update(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - if(currentConnectionCount > soundConnectionCount){ - soundConnectionCount = currentConnectionCount; - SoundRenderer::getInstance().playFx(CoreData::getInstance().getAttentionSound()); - //switch on music again!! - Config &config = Config::getInstance(); - float configVolume = (config.getInt("SoundVolumeMusic") / 100.f); - CoreData::getInstance().getMenuMusic()->setVolume(configVolume); - } - soundConnectionCount = currentConnectionCount; - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - if(enableFactionTexturePreview == true) { - if( currentTechName_factionPreview != gameSettings.getTech() || - currentFactionName_factionPreview != gameSettings.getFactionTypeName(gameSettings.getThisFactionIndex())) { - - currentTechName_factionPreview=gameSettings.getTech(); - currentFactionName_factionPreview=gameSettings.getFactionTypeName(gameSettings.getThisFactionIndex()); - - initFactionPreview(&gameSettings); - } - } - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - if(autostart == true) { - autostart = false; - safeMutex.ReleaseLock(); - safeMutexCLI.ReleaseLock(); - if(autoStartSettings != NULL) { - - setupUIFromGameSettings(*autoStartSettings); - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - serverInterface->setGameSettings(autoStartSettings,false); - } - else { - RestoreLastGameSettings(); - } - PlayNow((autoStartSettings == NULL)); - return; - } - } - catch(megaglest_runtime_error& ex) { - //abort(); - //printf("1111111bbbb ex.wantStackTrace() = %d\n",ex.wantStackTrace()); - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - - //printf("2222222bbbb ex.wantStackTrace() = %d\n",ex.wantStackTrace()); - - showGeneralError=true; - generalErrorToShow = szBuf; - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - - showGeneralError=true; - generalErrorToShow = szBuf; - } -} + serverInterface->sendTextMessage(sMsg, -1, true, languageList[j]); + } -void MenuStateCustomGame::initFactionPreview(const GameSettings *gameSettings) { - string factionVideoUrl = ""; - string factionVideoUrlFallback = ""; - - string factionDefinitionXML = Game::findFactionLogoFile(gameSettings, NULL,currentFactionName_factionPreview + ".xml"); - if(factionDefinitionXML != "" && currentFactionName_factionPreview != GameConstants::RANDOMFACTION_SLOTNAME && - currentFactionName_factionPreview != GameConstants::OBSERVER_SLOTNAME && fileExists(factionDefinitionXML) == true) { - XmlTree xmlTree; - std::map mapExtraTagReplacementValues; - xmlTree.load(factionDefinitionXML, Properties::getTagReplacementValues(&mapExtraTagReplacementValues)); - const XmlNode *factionNode= xmlTree.getRootNode(); - if(factionNode->hasAttribute("faction-preview-video") == true) { - factionVideoUrl = factionNode->getAttribute("faction-preview-video")->getValue(); - } - - factionVideoUrlFallback = Game::findFactionLogoFile(gameSettings, NULL,"preview_video.*"); - if(factionVideoUrl == "") { - factionVideoUrl = factionVideoUrlFallback; - factionVideoUrlFallback = ""; - } - } - //printf("currentFactionName_factionPreview [%s] random [%s] observer [%s] factionVideoUrl [%s]\n",currentFactionName_factionPreview.c_str(),GameConstants::RANDOMFACTION_SLOTNAME,GameConstants::OBSERVER_SLOTNAME,factionVideoUrl.c_str()); - - - if(factionVideoUrl != "") { - //SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - if(CoreData::getInstance().getMenuMusic()->getVolume() != 0) { - CoreData::getInstance().getMenuMusic()->setVolume(0); - factionVideoSwitchedOffVolume=true; - } - - if(currentFactionLogo != factionVideoUrl) { - currentFactionLogo = factionVideoUrl; - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && - ::Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == true) { - - if(factionVideo != NULL) { - factionVideo->closePlayer(); - delete factionVideo; - factionVideo = NULL; - } - string introVideoFile = factionVideoUrl; - string introVideoFileFallback = factionVideoUrlFallback; - - Context *c= GraphicsInterface::getInstance().getCurrentContext(); - SDL_Window *window = static_cast(c)->getPlatformContextGlPtr()->getScreenWindow(); - SDL_Surface *screen = static_cast(c)->getPlatformContextGlPtr()->getScreenSurface(); - - string vlcPluginsPath = Config::getInstance().getString("VideoPlayerPluginsPath",""); - //printf("screen->w = %d screen->h = %d screen->format->BitsPerPixel = %d\n",screen->w,screen->h,screen->format->BitsPerPixel); - factionVideo = new VideoPlayer( - &Renderer::getInstance(), - introVideoFile, - introVideoFileFallback, - window, - 0,0, - screen->w, - screen->h, - screen->format->BitsPerPixel, - true, - vlcPluginsPath, - SystemFlags::VERBOSE_MODE_ENABLED); - factionVideo->initPlayer(); - } - } - } - else { - //SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - //switch on music again!! - Config &config = Config::getInstance(); - float configVolume = (config.getInt("SoundVolumeMusic") / 100.f); - if(factionVideoSwitchedOffVolume){ - if(CoreData::getInstance().getMenuMusic()->getVolume() != configVolume) { - CoreData::getInstance().getMenuMusic()->setVolume(configVolume); - } - factionVideoSwitchedOffVolume=false; - } - - if(factionVideo != NULL) { - factionVideo->closePlayer(); - delete factionVideo; - factionVideo = NULL; - } - } - - if(factionVideo == NULL) { - string factionLogo = Game::findFactionLogoFile(gameSettings, NULL,GameConstants::PREVIEW_SCREEN_FILE_FILTER); - if(factionLogo == "") { - factionLogo = Game::findFactionLogoFile(gameSettings, NULL); - } - if(currentFactionLogo != factionLogo) { - currentFactionLogo = factionLogo; - loadFactionTexture(currentFactionLogo); - } - } -} + safeMutex.ReleaseLock(); + safeMutexCLI.ReleaseLock(); + return; + } + } -void MenuStateCustomGame::publishToMasterserver() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - int slotCountUsed=0; - int slotCountHumans=0; - int slotCountConnectedPlayers=0; - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - GameSettings gameSettings; - copyToGameSettings(&gameSettings); - Config &config= Config::getInstance(); - //string serverinfo=""; - - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - publishToServerInfo.clear(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - for(int i= 0; i < mapInfo.players; ++i) { - if(listBoxControls[i].getSelectedItemIndex() != ctClosed) { - slotCountUsed++; - } - - if(listBoxControls[i].getSelectedItemIndex() == ctNetwork || listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) - { - slotCountHumans++; - if(serverInterface->getSlot(i,true) != NULL && - serverInterface->getSlot(i,true)->isConnected()) { - slotCountConnectedPlayers++; - } - } - else if(listBoxControls[i].getSelectedItemIndex() == ctHuman) { - slotCountHumans++; - slotCountConnectedPlayers++; - } - } - - publishToServerInfo["uuid"] = Config::getInstance().getString("PlayerId",""); - - //?status=waiting&system=linux&info=titus - publishToServerInfo["glestVersion"] = glestVersionString; - publishToServerInfo["platform"] = getPlatformNameString() + "-" + getGITRevisionString(); - publishToServerInfo["binaryCompileDate"] = getCompileDateTime(); - - //game info: - publishToServerInfo["serverTitle"] = gameSettings.getGameName(); - //ip is automatically set - - //game setup info: - - //publishToServerInfo["tech"] = listBoxTechTree.getSelectedItem(); - publishToServerInfo["tech"] = techTreeFiles[listBoxTechTree.getSelectedItemIndex()]; - //publishToServerInfo["map"] = listBoxMap.getSelectedItem(); - publishToServerInfo["map"] = getCurrentMapFile(); - //publishToServerInfo["tileset"] = listBoxTileset.getSelectedItem(); - publishToServerInfo["tileset"] = tilesetFiles[listBoxTileset.getSelectedItemIndex()]; - - publishToServerInfo["activeSlots"] = intToStr(slotCountUsed); - publishToServerInfo["networkSlots"] = intToStr(slotCountHumans); - publishToServerInfo["connectedClients"] = intToStr(slotCountConnectedPlayers); - - string serverPort=config.getString("PortServer", intToStr(GameConstants::serverPort).c_str()); - string externalPort=config.getString("PortExternal", serverPort.c_str()); - publishToServerInfo["externalconnectport"] = externalPort; - publishToServerInfo["privacyPlease"] = intToStr(config.getBool("PrivacyPlease","false")); - - publishToServerInfo["gameStatus"] = intToStr(game_status_waiting_for_players); - if(slotCountHumans <= slotCountConnectedPlayers) { - publishToServerInfo["gameStatus"] = intToStr(game_status_waiting_for_start); - } - - publishToServerInfo["gameUUID"] = gameSettings.getGameUUID(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // Tell the server Interface whether or not to publish game status updates + // to masterserver + serverInterface->setNeedToRepublishToMasterserver( + checkBoxPublishServer.getValue() == true); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + bool bOkToStart = serverInterface->launchGame(&gameSettings); + if (bOkToStart == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (checkBoxPublishServer.getEditable() && + checkBoxPublishServer.getValue() == true) { + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + needToRepublishToMasterserver = true; + lastMasterserverPublishing = 0; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } + needToBroadcastServerSettings = false; + needToRepublishToMasterserver = false; + lastNetworkPing = time(NULL); + safeMutex.ReleaseLock(); + safeMutexCLI.ReleaseLock(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + assert(program != NULL); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + cleanup(); + Game *newGame = + new Game(program, &gameSettings, this->headlessServerMode); + forceWaitForShutdown = false; + program->setState(newGame); + return; + } else { + safeMutex.ReleaseLock(); + safeMutexCLI.ReleaseLock(); + } + } } -void MenuStateCustomGame::setupTask(BaseThread *callingThread,void *userdata) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\nsetupTask callingThread [%p] userdata [%p]\n",callingThread,userdata); - if(userdata != NULL) { - int value = *((int*)&userdata); - THREAD_NOTIFIER_TYPE threadType = (THREAD_NOTIFIER_TYPE)value; - //printf("\n\nsetupTask callingThread [%p] userdata [%p]\n",callingThread,userdata); - if(threadType == tnt_MASTERSERVER) { - MenuStateCustomGame::setupTaskStatic(callingThread); - } - } -} -void MenuStateCustomGame::shutdownTask(BaseThread *callingThread,void *userdata) { - //printf("\n\nshutdownTask callingThread [%p] userdata [%p]\n",callingThread,userdata); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\nshutdownTask callingThread [%p] userdata [%p]\n",callingThread,userdata); - if(userdata != NULL) { - int value = *((int*)&userdata); - THREAD_NOTIFIER_TYPE threadType = (THREAD_NOTIFIER_TYPE)value; - //printf("\n\nshutdownTask callingThread [%p] userdata [%p]\n",callingThread,userdata); - if(threadType == tnt_MASTERSERVER) { - MenuStateCustomGame::shutdownTaskStatic(callingThread); - } - } +void MenuStateCustomGame::eventMouseWheel(int x, int y, int zDelta) { + if (isMasterserverMode() == true) { + return; + } + comboBoxMap.eventMouseWheel(x, y, zDelta); + comboBoxLoadSetup.eventMouseWheel(x, y, zDelta); } -void MenuStateCustomGame::setupTaskStatic(BaseThread *callingThread) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - CURL *handle = SystemFlags::initHTTP(); - callingThread->setGenericData(handle); +void MenuStateCustomGame::mouseMove(int x, int y, const MouseState *ms) { + if (isMasterserverMode() == true) { + return; + } + + if (mainMessageBox.getEnabled()) { + mainMessageBox.mouseMove(x, y); + } + + comboBoxMap.mouseMove(x, y); + if (comboBoxMap.isDropDownShowing()) { + if (ms->get(mbLeft)) { + comboBoxMap.mouseDown(x, y); + } + if (lastPreviewedMapFile != getPreselectedMapFile()) { + loadMapInfo(Config::getMapPath(getPreselectedMapFile(), "", false), + &mapInfo, true, false); + labelMapInfo.setText(mapInfo.desc); + lastPreviewedMapFile = getPreselectedMapFile(); + } + } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + comboBoxLoadSetup.mouseMove(x, y); + if (comboBoxLoadSetup.isDropDownShowing()) { + if (ms->get(mbLeft)) { + comboBoxLoadSetup.mouseDown(x, y); + } + } + buttonSaveSetup.mouseMove(x, y); + buttonLoadSetup.mouseMove(x, y); + buttonDeleteSetup.mouseMove(x, y); + + buttonReturn.mouseMove(x, y); + buttonPlayNow.mouseMove(x, y); + buttonClearBlockedPlayers.mouseMove(x, y); + + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + listBoxRMultiplier[i].mouseMove(x, y); + listBoxControls[i].mouseMove(x, y); + buttonBlockPlayers[i].mouseMove(x, y); + listBoxFactions[i].mouseMove(x, y); + listBoxTeams[i].mouseMove(x, y); + } + + if (checkBoxAdvanced.getValue() == 1) { + listBoxFogOfWar.mouseMove(x, y); + checkBoxAllowObservers.mouseMove(x, y); + + buttonShowLanInfo.mouseMove(x, y); + + checkBoxEnableSwitchTeamMode.mouseMove(x, y); + listBoxAISwitchTeamAcceptPercent.mouseMove(x, y); + listBoxFallbackCpuMultiplier.mouseMove(x, y); + + labelNetworkPauseGameForLaggedClients.mouseMove(x, y); + checkBoxNetworkPauseGameForLaggedClients.mouseMove(x, y); + + labelAllowTeamUnitSharing.mouseMove(x, y); + checkBoxAllowTeamUnitSharing.mouseMove(x, y); + labelAllowTeamResourceSharing.mouseMove(x, y); + checkBoxAllowTeamResourceSharing.mouseMove(x, y); + } + checkBoxAllowInGameJoinPlayer.mouseMove(x, y); + + checkBoxAllowNativeLanguageTechtree.mouseMove(x, y); + + listBoxTileset.mouseMove(x, y); + listBoxMapFilter.mouseMove(x, y); + listBoxTechTree.mouseMove(x, y); + checkBoxPublishServer.mouseMove(x, y); + + checkBoxAdvanced.mouseMove(x, y); + + checkBoxScenario.mouseMove(x, y); + listBoxScenario.mouseMove(x, y); } -void MenuStateCustomGame::shutdownTaskStatic(BaseThread *callingThread) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //printf("LINE: %d\n",__LINE__); - CURL *handle = callingThread->getGenericData(); - SystemFlags::cleanupHTTP(&handle); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +bool MenuStateCustomGame::isMasterserverMode() const { + return (this->headlessServerMode == true && + this->masterserverModeMinimalResources == true); + // return false; } -void MenuStateCustomGame::simpleTask(BaseThread *callingThread,void *userdata) { - //printf("\n\nSimple Task callingThread [%p] userdata [%p]\n",callingThread,userdata); - int value = *((int*)&userdata); - //printf("\n\nSimple Task callingThread [%p] userdata [%p] value = %d\n",callingThread,userdata,value); - - THREAD_NOTIFIER_TYPE threadType = (THREAD_NOTIFIER_TYPE)value; - if(threadType == tnt_MASTERSERVER) { - simpleTaskForMasterServer(callingThread); - } - else if(threadType == tnt_CLIENTS) { - simpleTaskForClients(callingThread); - } +bool MenuStateCustomGame::isVideoPlaying() { + bool result = false; + if (factionVideo != NULL) { + result = factionVideo->isPlaying(); + } + return result; } -void MenuStateCustomGame::simpleTaskForMasterServer(BaseThread *callingThread) { - try { - //printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - A\n"); +void MenuStateCustomGame::render() { + try { + Renderer &renderer = Renderer::getInstance(); - MutexSafeWrapper safeMutexThreadOwner(callingThread->getMutexThreadOwnerValid(),string(__FILE__) + "_" + intToStr(__LINE__)); - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - return; + if (mainMessageBox.getEnabled() == false) { + if (factionTexture != NULL) { + if (factionVideo == NULL || factionVideo->isPlaying() == false) { + renderer.renderTextureQuad(800, 600, 200, 150, factionTexture, 1.0f); } + } + } + if (factionVideo != NULL) { + if (factionVideo->isPlaying() == true) { + factionVideo->playFrame(false); + } else { + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && + ::Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == true) { + if (factionVideo != NULL) { + factionVideo->closePlayer(); + delete factionVideo; + factionVideo = NULL; + + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + if (serverInterface != NULL) { + initFactionPreview(serverInterface->getGameSettings()); + } + } + } + } + } - //printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - B\n"); - - MutexSafeWrapper safeMutex(callingThread->getMutexThreadObjectAccessor(),string(__FILE__) + "_" + intToStr(__LINE__)); - bool republish = (needToRepublishToMasterserver == true && publishToServerInfo.empty() == false); - needToRepublishToMasterserver = false; - std::map newPublishToServerInfo = publishToServerInfo; - publishToServerInfo.clear(); + if (mainMessageBox.getEnabled()) { + renderer.renderMessageBox(&mainMessageBox); + + renderer.renderButton(&buttonReturn); + } else { + if (mapPreviewTexture != NULL) { + // renderer.renderTextureQuad(5,185,150,150,mapPreviewTexture,1.0f); + renderer.renderTextureQuad( + this->render_mapPreviewTexture_X, this->render_mapPreviewTexture_Y, + this->render_mapPreviewTexture_W, this->render_mapPreviewTexture_H, + mapPreviewTexture, 1.0f); + if (this->zoomedMap == true) { + return; + } + // printf("=================> Rendering map preview texture\n"); + } + if (scenarioLogoTexture != NULL) { + renderer.renderTextureQuad(300, 350, 400, 300, scenarioLogoTexture, + 1.0f); + // renderer.renderBackground(scenarioLogoTexture); + } + + renderer.renderButton(&buttonReturn); + renderer.renderButton(&buttonPlayNow); + + renderer.renderLabel(&labelSaveSetupName); + renderer.renderButton(&buttonSaveSetup); + renderer.renderButton(&buttonLoadSetup); + renderer.renderButton(&buttonDeleteSetup); + + // Get a reference to the player texture cache + std::map &crcPlayerTextureCache = + CacheManager::getCachedItem>( + GameConstants::playerTextureCacheLookupKey); + + // START - this code ensure player title and player names don't overlap + int offsetPosition = 0; + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + FontMetrics *fontMetrics = NULL; + if (Renderer::renderText3DEnabled == false) { + fontMetrics = labelPlayers[i].getFont()->getMetrics(); + } else { + fontMetrics = labelPlayers[i].getFont3D()->getMetrics(); + } + if (fontMetrics == NULL) { + throw megaglest_runtime_error("fontMetrics == NULL"); + } + int curWidth = (fontMetrics->getTextWidth(labelPlayers[i].getText())); + int newOffsetPosition = labelPlayers[i].getX() + curWidth + 2; + + // 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()); + + if (labelPlayers[i].getX() + curWidth >= labelPlayerNames[i].getX()) { + if (offsetPosition < newOffsetPosition) { + offsetPosition = newOffsetPosition; + } + } + } + // END + + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + if (hasNetworkGameSettings() == true) { + renderer.renderListBox(&listBoxPlayerStatus); + if (serverInterface != NULL && + buttonClearBlockedPlayers.getEditable() && + serverInterface->getServerSocket() != NULL) { + renderer.renderButton(&buttonClearBlockedPlayers); + } + } + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + if (listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) { + // printf("Player #%d [%s] control = + // %d\n",i,labelPlayerNames[i].getText().c_str(),listBoxControls[i].getSelectedItemIndex()); + + labelPlayers[i].setVisible(true); + labelPlayerNames[i].setVisible(true); + listBoxControls[i].setVisible(true); + listBoxFactions[i].setVisible(true); + listBoxTeams[i].setVisible(true); + labelNetStatus[i].setVisible(true); + } - //printf("simpleTask broadCastSettings = %d\n",broadCastSettings); + if (hasNetworkGameSettings() == true && + listBoxControls[i].getSelectedItemIndex() != ctClosed) { - if(callingThread->getQuitStatus() == true) { - return; + renderer.renderLabel(&labelPlayerStatus[i]); } - //printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - C\n"); - - if(republish == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (crcPlayerTextureCache[i] != NULL) { + // Render the player # label the player's color + Vec3f playerColor = + crcPlayerTextureCache[i]->getPixmap()->getPixel3f(0, 0); + renderer.renderLabel(&labelPlayers[i], &playerColor); + } else { + renderer.renderLabel(&labelPlayers[i]); + } - string request = Config::getInstance().getString("Masterserver"); - if(request != "") { - endPathWithSlash(request,false); - } - request += "addServerInfo.php?"; + if (offsetPosition > 0) { + labelPlayerNames[i].setX(offsetPosition); + } + renderer.renderLabel(&labelPlayerNames[i]); - //CURL *handle = SystemFlags::initHTTP(); - CURL *handle = callingThread->getGenericData(); + renderer.renderListBox(&listBoxControls[i]); - int paramIndex = 0; - for(std::map::const_iterator iterMap = newPublishToServerInfo.begin(); - iterMap != newPublishToServerInfo.end(); ++iterMap) { + if (hasNetworkGameSettings() == true && + listBoxControls[i].getSelectedItemIndex() != ctClosed) { - request += iterMap->first; - request += "="; - request += SystemFlags::escapeURL(iterMap->second,handle); + renderer.renderLabel(&labelPlayerStatus[i]); - paramIndex++; - if(paramIndex < (int)newPublishToServerInfo.size()) { - request += "&"; - } + if (listBoxControls[i].getSelectedItemIndex() == ctNetwork || + listBoxControls[i].getSelectedItemIndex() == + ctNetworkUnassigned) { + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + if (serverInterface != NULL && + serverInterface->getSlot(i, true) != NULL && + serverInterface->getSlot(i, true)->isConnected()) { + renderer.renderButton(&buttonBlockPlayers[i]); } + } + } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("The Lobby request is:\n%s\n",request.c_str()); + if (listBoxControls[i].getSelectedItemIndex() != ctClosed) { + renderer.renderListBox(&listBoxRMultiplier[i]); + renderer.renderListBox(&listBoxFactions[i]); + + int teamnumber = listBoxTeams[i].getSelectedItemIndex(); + Vec3f teamcolor = Vec3f(1.0f, 1.0f, 1.0f); + if (teamnumber >= 0 && teamnumber < 8) { + teamcolor = + crcPlayerTextureCache[teamnumber]->getPixmap()->getPixel3f(0, + 0); + } + listBoxTeams[i].setTextColor(teamcolor); + + renderer.renderListBox(&listBoxTeams[i]); + renderer.renderLabel(&labelNetStatus[i]); + } + } + renderer.renderLabel(&labelMap); - 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()); - safeMutex.ReleaseLock(true); - safeMutexThreadOwner.ReleaseLock(); + if (checkBoxAdvanced.getValue() == 1) { + renderer.renderLabel(&labelFogOfWar); + renderer.renderListBox(&listBoxFogOfWar); - std::string serverInfo = SystemFlags::getHTTP(request,handle); - //SystemFlags::cleanupHTTP(&handle); + renderer.renderLabel(&labelAllowTeamUnitSharing); + renderer.renderCheckBox(&checkBoxAllowTeamUnitSharing); - MutexSafeWrapper safeMutexThreadOwner2(callingThread->getMutexThreadOwnerValid(),string(__FILE__) + "_" + intToStr(__LINE__)); - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner2.isValidMutex() == false) { - return; - } - safeMutex.Lock(); + renderer.renderButton(&buttonShowLanInfo); - //printf("the result is:\n'%s'\n",serverInfo.c_str()); - 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()); + renderer.renderLabel(&labelAllowTeamResourceSharing); + renderer.renderCheckBox(&checkBoxAllowTeamResourceSharing); - // uncomment to enable router setup check of this server - if(EndsWith(serverInfo, "OK") == false) { - if(callingThread->getQuitStatus() == true) { - return; - } + renderer.renderLabel(&labelAllowNativeLanguageTechtree); + renderer.renderCheckBox(&checkBoxAllowNativeLanguageTechtree); - // Give things another chance to see if we can get a connection from the master server - if(tMasterserverErrorElapsed > 0 && - difftime((long int)time(NULL),tMasterserverErrorElapsed) > MASTERSERVER_BROADCAST_MAX_WAIT_RESPONSE_SECONDS) { - showMasterserverError=true; - masterServererErrorToShow = (serverInfo != "" ? serverInfo : "No Reply"); - } - else { - if(tMasterserverErrorElapsed == 0) { - tMasterserverErrorElapsed = time(NULL); - } + renderer.renderLabel(&labelAllowObservers); + renderer.renderCheckBox(&checkBoxAllowObservers); - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line %d] error checking response from masterserver elapsed seconds = %.2f / %d\nResponse:\n%s\n", - extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,difftime((long int)time(NULL),tMasterserverErrorElapsed),MASTERSERVER_BROADCAST_MAX_WAIT_RESPONSE_SECONDS,serverInfo.c_str()); + renderer.renderCheckBox(&checkBoxEnableSwitchTeamMode); + renderer.renderLabel(&labelEnableSwitchTeamMode); + renderer.renderListBox(&listBoxAISwitchTeamAcceptPercent); + renderer.renderLabel(&labelAISwitchTeamAcceptPercent); - needToRepublishToMasterserver = true; - } - } + renderer.renderCheckBox(&checkBoxScenario); + renderer.renderLabel(&labelScenario); + if (checkBoxScenario.getValue() == true) { + renderer.renderListBox(&listBoxScenario); } - else { - safeMutexThreadOwner.ReleaseLock(); + } + renderer.renderLabel(&labelAllowInGameJoinPlayer); + renderer.renderCheckBox(&checkBoxAllowInGameJoinPlayer); + + renderer.renderLabel(&labelTileset); + renderer.renderLabel(&labelMapFilter); + renderer.renderLabel(&labelTechTree); + renderer.renderLabel(&labelControl); + renderer.renderLabel(&labelFaction); + renderer.renderLabel(&labelTeam); + renderer.renderLabel(&labelMapInfo); + renderer.renderLabel(&labelAdvanced); + + renderer.renderListBox(&listBoxTileset); + renderer.renderListBox(&listBoxMapFilter); + renderer.renderListBox(&listBoxTechTree); + renderer.renderCheckBox(&checkBoxAdvanced); + + if (checkBoxPublishServer.getEditable()) { + renderer.renderCheckBox(&checkBoxPublishServer); + renderer.renderLabel(&labelPublishServer); + renderer.renderLabel(&labelGameName); + if (checkBoxAdvanced.getValue() == 1) { + renderer.renderLabel(&labelNetworkPauseGameForLaggedClients); + renderer.renderCheckBox(&checkBoxNetworkPauseGameForLaggedClients); + renderer.renderListBox(&listBoxFallbackCpuMultiplier); + renderer.renderLabel(&labelFallbackCpuMultiplier); } + } + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + renderer.renderConsole(&console, showFullConsole ? consoleFull + : consoleStoredAndNormal); - //printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - D\n"); + if (program != NULL) + program->renderProgramMsgBox(); - safeMutex.ReleaseLock(); - - //printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - F\n"); + if (mainMessageBox.getEnabled() == false) { + if (hasNetworkGameSettings() == true) { + renderer.renderChatManager(&chatManager); + } } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); + renderer.renderComboBox(&comboBoxMap); + renderer.renderComboBox(&comboBoxLoadSetup); - if(callingThread->getQuitStatus() == false) { - //throw megaglest_runtime_error(szBuf); - showGeneralError=true; - generalErrorToShow = ex.what(); - } - } + if (enableMapPreview == true && mapPreview.hasFileLoaded() == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); -} + if (mapPreviewTexture == NULL) { + bool renderAll = (listBoxFogOfWar.getSelectedItemIndex() == 2); + // printf("=================> Rendering map preview into a texture + // BEFORE (%p)\n", mapPreviewTexture); -void MenuStateCustomGame::simpleTaskForClients(BaseThread *callingThread) { - try { - //printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - A\n"); + // renderer.renderMapPreview(&mapPreview, renderAll, 10, + // 350,&mapPreviewTexture); + renderer.renderMapPreview( + &mapPreview, renderAll, this->render_mapPreviewTexture_X, + this->render_mapPreviewTexture_Y, &mapPreviewTexture); - MutexSafeWrapper safeMutexThreadOwner(callingThread->getMutexThreadOwnerValid(),string(__FILE__) + "_" + intToStr(__LINE__)); - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - return; - } - - //printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - B\n"); - - MutexSafeWrapper safeMutex(callingThread->getMutexThreadObjectAccessor(),string(__FILE__) + "_" + intToStr(__LINE__)); - bool broadCastSettings = needToBroadcastServerSettings; + // printf("=================> Rendering map preview into a texture AFTER + // (%p)\n", mapPreviewTexture); + } + } - //printf("simpleTask broadCastSettings = %d\n",broadCastSettings); + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + // throw megaglest_runtime_error(szBuf); + + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + showGeneralError = true; + generalErrorToShow = szBuf; + } +} - needToBroadcastServerSettings = false; - bool hasClientConnection = false; +void MenuStateCustomGame::switchSetupForSlots( + SwitchSetupRequest **switchSetupRequests, ServerInterface *&serverInterface, + int startIndex, int endIndex, bool onlyNetworkUnassigned) { + for (int i = startIndex; i < endIndex; ++i) { + if (switchSetupRequests[i] != NULL) { + // printf("Switch slot = %d control = %d newIndex = %d currentindex = %d + // onlyNetworkUnassigned = + // %d\n",i,listBoxControls[i].getSelectedItemIndex(),switchSetupRequests[i]->getToFactionIndex(),switchSetupRequests[i]->getCurrentFactionIndex(),onlyNetworkUnassigned); + + 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()); + + if (onlyNetworkUnassigned == true && + listBoxControls[i].getSelectedItemIndex() != ctNetworkUnassigned) { + if (i < mapInfo.players || + (i >= mapInfo.players && + listBoxControls[i].getSelectedItemIndex() != ctNetwork)) { + continue; + } + } + + if (listBoxControls[i].getSelectedItemIndex() == ctNetwork || + listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) { + 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()); + + if (switchSetupRequests[i]->getToSlotIndex() != -1) { + int newFactionIdx = switchSetupRequests[i]->getToSlotIndex(); + + // printf("switchSlot request from %d to + // %d\n",switchSetupRequests[i]->getCurrentFactionIndex(),switchSetupRequests[i]->getToFactionIndex()); + int switchFactionIdx = switchSetupRequests[i]->getCurrentSlotIndex(); + if (serverInterface->switchSlot(switchFactionIdx, newFactionIdx)) { + try { + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + ConnectionSlot *slot = + serverInterface->getSlot(newFactionIdx, true); + + if (switchSetupRequests[i]->getSelectedFactionName() != "" && + (slot != NULL && + switchSetupRequests[i]->getSelectedFactionName() != + Lang::getInstance().getString( + "DataMissing", slot->getNetworkPlayerLanguage(), + true) && + switchSetupRequests[i]->getSelectedFactionName() != + "???DataMissing???")) { + listBoxFactions[newFactionIdx].setSelectedItem( + switchSetupRequests[i]->getSelectedFactionName()); + } + if (switchSetupRequests[i]->getToTeam() != -1) { + listBoxTeams[newFactionIdx].setSelectedItemIndex( + switchSetupRequests[i]->getToTeam()); + } + if (switchSetupRequests[i]->getNetworkPlayerName() != "") { + 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()); + labelPlayerNames[newFactionIdx].setText( + switchSetupRequests[i]->getNetworkPlayerName()); + } + + if (listBoxControls[switchFactionIdx].getSelectedItemIndex() == + ctNetworkUnassigned) { + serverInterface->removeSlot(switchFactionIdx); + listBoxControls[switchFactionIdx].setSelectedItemIndex( + ctClosed); + + labelPlayers[switchFactionIdx].setVisible( + switchFactionIdx + 1 <= mapInfo.players); + labelPlayerNames[switchFactionIdx].setVisible( + switchFactionIdx + 1 <= mapInfo.players); + listBoxControls[switchFactionIdx].setVisible( + switchFactionIdx + 1 <= mapInfo.players); + listBoxFactions[switchFactionIdx].setVisible( + switchFactionIdx + 1 <= mapInfo.players); + listBoxTeams[switchFactionIdx].setVisible( + switchFactionIdx + 1 <= mapInfo.players); + labelNetStatus[switchFactionIdx].setVisible( + switchFactionIdx + 1 <= mapInfo.players); + } + } catch (const runtime_error &e) { + SystemFlags::OutputDebug( + SystemFlags::debugError, "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, e.what()); + 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()); + } + } + } else { + try { + int factionIdx = switchSetupRequests[i]->getCurrentSlotIndex(); + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + ConnectionSlot *slot = serverInterface->getSlot(factionIdx, true); + + if (switchSetupRequests[i]->getSelectedFactionName() != "" && + (slot != NULL && + switchSetupRequests[i]->getSelectedFactionName() != + Lang::getInstance().getString( + "DataMissing", slot->getNetworkPlayerLanguage(), + true) && + switchSetupRequests[i]->getSelectedFactionName() != + "???DataMissing???")) { + listBoxFactions[i].setSelectedItem( + switchSetupRequests[i]->getSelectedFactionName()); + } + if (switchSetupRequests[i]->getToTeam() != -1) { + listBoxTeams[i].setSelectedItemIndex( + switchSetupRequests[i]->getToTeam()); + } - if(broadCastSettings == true) { - ServerInterface *serverInterface = NetworkManager::getInstance().getServerInterface(false); - if(serverInterface != NULL) { - hasClientConnection = serverInterface->hasClientConnection(); + if ((switchSetupRequests[i]->getSwitchFlags() & + ssrft_NetworkPlayerName) == ssrft_NetworkPlayerName) { + 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()); + + if (switchSetupRequests[i]->getNetworkPlayerName() != + GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME) { + labelPlayerNames[i].setText( + switchSetupRequests[i]->getNetworkPlayerName()); + } else { + labelPlayerNames[i].setText(""); + } } + } catch (const runtime_error &e) { + SystemFlags::OutputDebug( + SystemFlags::debugError, "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, e.what()); + 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()); + } } - bool needPing = (difftime((long int)time(NULL),lastNetworkPing) >= GameConstants::networkPingInterval); + } - if(callingThread->getQuitStatus() == true) { - return; - } + delete switchSetupRequests[i]; + switchSetupRequests[i] = NULL; + } + } +} - //printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - C\n"); +void MenuStateCustomGame::update() { + Chrono chrono; + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) + chrono.start(); + + // Test openal buffer underrun issue + // sleep(200); + // END + + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + MutexSafeWrapper safeMutexCLI( + (publishToClientsThread != NULL + ? publishToClientsThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + try { + if (serverInitError == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (showGeneralError) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + showGeneralError = false; + mainMessageBoxState = 1; + showMessageBox(generalErrorToShow, "Error", false); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (this->headlessServerMode == false) { + return; + } + } + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + Lang &lang = Lang::getInstance(); - safeMutexThreadOwner.ReleaseLock(); + if (serverInterface != NULL && serverInterface->getServerSocket() != NULL) { + buttonClearBlockedPlayers.setEditable( + serverInterface->getServerSocket()->hasBlockedIPAddresses()); + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (comboBoxMap.isDropDownShowing()) { + labelMapInfo.setX(0); + labelMapInfo.setY(mapPreviewTexture_Y - 40); + } else { + labelMapInfo.setX(165); + labelMapInfo.setY(mapPreviewTexture_Y + mapPreviewTexture_H - 60); + } + if (this->autoloadScenarioName != "") { + listBoxScenario.setSelectedItem(formatString(this->autoloadScenarioName), + false); + lastSetChangedGameSettings = time(NULL); + if (serverInterface != NULL) { + lastGameSettingsreceivedCount = + serverInterface->getGameSettingsUpdateCount(); + } + if (listBoxScenario.getSelectedItem() != + formatString(this->autoloadScenarioName)) { + mainMessageBoxState = 1; + showMessageBox("Could not find scenario name: " + + formatString(this->autoloadScenarioName), + "Scenario Missing", false); + this->autoloadScenarioName = ""; + } else { + loadScenarioInfo( + Scenario::getScenarioPath( + dirList, scenarioFiles[listBoxScenario.getSelectedItemIndex()]), + &scenarioInfo); + // labelInfo.setText(scenarioInfo.desc); + + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + CoreData &coreData = CoreData::getInstance(); + soundRenderer.playFx(coreData.getClickSoundC()); + // launchGame(); + PlayNow(true); + return; + } + } - //printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - D\n"); + if (needToLoadTextures) { + // this delay is done to make it possible to switch faster + if (difftime((long int)time(NULL), previewLoadDelayTimer) >= 2) { + // loadScenarioPreviewTexture(); + needToLoadTextures = false; + } + } - if(broadCastSettings == true) { - MutexSafeWrapper safeMutexThreadOwner2(callingThread->getMutexThreadOwnerValid(),string(__FILE__) + "_" + intToStr(__LINE__)); - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner2.isValidMutex() == false) { - return; - } + // bool haveAtLeastOneNetworkClientConnected = false; + bool hasOneNetworkSlotOpen = false; + int currentConnectionCount = 0; + Config &config = Config::getInstance(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + bool masterServerErr = showMasterserverError; + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (masterServerErr) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (EndsWith(masterServererErrorToShow, "wrong router setup") == true) { + masterServererErrorToShow = lang.getString("WrongRouterSetup"); + } + + Lang &lang = Lang::getInstance(); + string publishText = " (disabling publish)"; + if (lang.hasString("PublishDisabled") == true) { + publishText = lang.getString("PublishDisabled"); + } + + masterServererErrorToShow += "\n\n" + publishText; + showMasterserverError = false; + mainMessageBoxState = 1; + showMessageBox(masterServererErrorToShow, + lang.getString("ErrorFromMasterserver"), false); + + if (this->headlessServerMode == false) { + checkBoxPublishServer.setValue(false); + } + + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + serverInterface->setPublishEnabled(checkBoxPublishServer.getValue() == + true); + } else if (showGeneralError) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + showGeneralError = false; + mainMessageBoxState = 1; + showMessageBox(generalErrorToShow, "Error", false); + } + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (this->headlessServerMode == true && serverInterface == NULL) { + throw megaglest_runtime_error("serverInterface == NULL"); + } + if (this->headlessServerMode == true && + serverInterface->getGameSettingsUpdateCount() > + lastMasterServerSettingsUpdateCount && + serverInterface->getGameSettings() != NULL) { + const GameSettings *settings = serverInterface->getGameSettings(); + // printf("\n\n\n\n=====#1 got settings [%d] + // [%d]:\n%s\n",lastMasterServerSettingsUpdateCount,serverInterface->getGameSettingsUpdateCount(),settings->toString().c_str()); + + lastMasterServerSettingsUpdateCount = + serverInterface->getGameSettingsUpdateCount(); + // printf("#2 custom menu got map [%s]\n",settings->getMap().c_str()); + + setupUIFromGameSettings(*settings); + printf("received Settings map filter=%d\n", settings->getMapFilter()); + + GameSettings gameSettings; + copyToGameSettings(&gameSettings); + + // printf("\n\n\n\n=====#1.1 got settings [%d] + // [%d]:\n%s\n",lastMasterServerSettingsUpdateCount,serverInterface->getGameSettingsUpdateCount(),gameSettings.toString().c_str()); + } + if (this->headlessServerMode == true && + serverInterface->getMasterserverAdminRequestLaunch() == true) { + serverInterface->setMasterserverAdminRequestLaunch(false); + safeMutex.ReleaseLock(); + safeMutexCLI.ReleaseLock(); + + PlayNow(false); + return; + } + + // handle setting changes from clients + SwitchSetupRequest **switchSetupRequests = + serverInterface->getSwitchSetupRequests(); + //!!! + switchSetupForSlots(switchSetupRequests, serverInterface, 0, + mapInfo.players, false); + switchSetupForSlots(switchSetupRequests, serverInterface, mapInfo.players, + GameConstants::maxPlayers, true); + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + GameSettings gameSettings; + copyToGameSettings(&gameSettings); + + listBoxAISwitchTeamAcceptPercent.setVisible( + checkBoxEnableSwitchTeamMode.getValue()); + labelAISwitchTeamAcceptPercent.setVisible( + checkBoxEnableSwitchTeamMode.getValue()); + + int factionCount = 0; + for (int i = 0; i < mapInfo.players; ++i) { + if (hasNetworkGameSettings() == true) { + if (listBoxControls[i].getSelectedItemIndex() != ctClosed) { + int slotIndex = factionCount; + if (listBoxControls[i].getSelectedItemIndex() == ctHuman) { + switch (gameSettings.getNetworkPlayerStatuses(slotIndex)) { + case npst_BeRightBack: + labelPlayerStatus[i].setTexture( + CoreData::getInstance().getStatusBRBTexture()); + break; + case npst_Ready: + labelPlayerStatus[i].setTexture( + CoreData::getInstance().getStatusReadyTexture()); + break; + case npst_PickSettings: + labelPlayerStatus[i].setTexture( + CoreData::getInstance().getStatusNotReadyTexture()); + break; + case npst_Disconnected: + labelPlayerStatus[i].setTexture(NULL); + break; + + default: + labelPlayerStatus[i].setTexture(NULL); + break; + } + } else { + labelPlayerStatus[i].setTexture(NULL); + } - //printf("simpleTask broadCastSettings = %d hasClientConnection = %d\n",broadCastSettings,hasClientConnection); + factionCount++; + } else { + labelPlayerStatus[i].setTexture(NULL); + } + } + + if (listBoxControls[i].getSelectedItemIndex() == ctNetwork || + listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) { + hasOneNetworkSlotOpen = true; + + if (serverInterface->getSlot(i, true) != NULL && + serverInterface->getSlot(i, true)->isConnected()) { + + if (hasNetworkGameSettings() == true) { + switch ( + serverInterface->getSlot(i, true)->getNetworkPlayerStatus()) { + case npst_BeRightBack: + labelPlayerStatus[i].setTexture( + CoreData::getInstance().getStatusBRBTexture()); + break; + case npst_Ready: + labelPlayerStatus[i].setTexture( + CoreData::getInstance().getStatusReadyTexture()); + break; + case npst_PickSettings: + default: + labelPlayerStatus[i].setTexture( + CoreData::getInstance().getStatusNotReadyTexture()); + break; + } + } + + serverInterface->getSlot(i, true)->setName( + labelPlayerNames[i].getText()); + + // printf("FYI we have at least 1 client connected, slot = %d'\n",i); + + // haveAtLeastOneNetworkClientConnected = true; + if (serverInterface->getSlot(i, true) != NULL && + serverInterface->getSlot(i, true)->getConnectHasHandshaked()) { + currentConnectionCount++; + } + string label = + (serverInterface->getSlot(i, true) != NULL + ? serverInterface->getSlot(i, true)->getVersionString() + : ""); + + if (serverInterface->getSlot(i, true) != NULL && + serverInterface->getSlot(i, true)->getAllowDownloadDataSynch() == + true && + serverInterface->getSlot(i, true)->getAllowGameDataSynchCheck() == + true) { + if (serverInterface->getSlot(i, true) + ->getNetworkGameDataSynchCheckOk() == false) { + label += " -waiting to synch:"; + if (serverInterface->getSlot(i, true) + ->getNetworkGameDataSynchCheckOkMap() == false) { + label = label + " map"; + } + if (serverInterface->getSlot(i, true) + ->getNetworkGameDataSynchCheckOkTile() == false) { + label = label + " tile"; + } + if (serverInterface->getSlot(i, true) + ->getNetworkGameDataSynchCheckOkTech() == false) { + label = label + " techtree"; + } + } else { + label += " - data synch is ok"; + } + } else { + if (serverInterface->getSlot(i, true) != NULL && + serverInterface->getSlot(i, true) + ->getAllowGameDataSynchCheck() == true && + serverInterface->getSlot(i, true) + ->getNetworkGameDataSynchCheckOk() == false) { + label += " -synch mismatch:"; + + if (serverInterface->getSlot(i, true) != NULL && + serverInterface->getSlot(i, true) + ->getNetworkGameDataSynchCheckOkMap() == false) { + label = label + " map"; + + if (serverInterface->getSlot(i, true) + ->getReceivedDataSynchCheck() == true && + lastMapDataSynchError != + "map CRC mismatch, " + comboBoxMap.getSelectedItem()) { + lastMapDataSynchError = + "map CRC mismatch, " + comboBoxMap.getSelectedItem(); + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + serverInterface->sendTextMessage(lastMapDataSynchError, -1, + true, ""); + } + } + + if (serverInterface->getSlot(i, true) != NULL && + serverInterface->getSlot(i, true) + ->getNetworkGameDataSynchCheckOkTile() == false) { + label = label + " tile"; + + if (serverInterface->getSlot(i, true) + ->getReceivedDataSynchCheck() == true && + lastTileDataSynchError != + "tile CRC mismatch, " + + listBoxTileset.getSelectedItem()) { + lastTileDataSynchError = + "tile CRC mismatch, " + listBoxTileset.getSelectedItem(); + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + serverInterface->sendTextMessage(lastTileDataSynchError, -1, + true, ""); + } + } + + if (serverInterface->getSlot(i, true) != NULL && + serverInterface->getSlot(i, true) + ->getNetworkGameDataSynchCheckOkTech() == false) { + { + // Ensure local CRC cache is correct + setRefreshedCrcToGameSettings( + serverInterface->getGameSettingsPtr()); + } + label = label + " techtree"; + + if (serverInterface->getSlot(i, true) + ->getReceivedDataSynchCheck() == true) { + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + string report = + serverInterface->getSlot(i, true) + ->getNetworkGameDataSynchCheckTechMismatchReport(); + + if (lastTechtreeDataSynchError != + "techtree CRC mismatch" + report) { + lastTechtreeDataSynchError = + "techtree CRC mismatch" + report; + + 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()); + + serverInterface->sendTextMessage("techtree CRC mismatch", + -1, true, ""); + vector reportLineTokens; + Tokenize(report, reportLineTokens, "\n"); + for (int reportLine = 0; + reportLine < (int)reportLineTokens.size(); + ++reportLine) { + serverInterface->sendTextMessage( + reportLineTokens[reportLine], -1, true, ""); + } + } + } + } - if(callingThread->getQuitStatus() == true) { - return; + if (serverInterface->getSlot(i, true) != NULL) { + serverInterface->getSlot(i, true)->setReceivedDataSynchCheck( + false); + } } - ServerInterface *serverInterface= NetworkManager::getInstance().getServerInterface(false); - if(serverInterface != NULL) { - lastGameSettingsreceivedCount++; - if(this->headlessServerMode == false || (serverInterface->getGameSettingsUpdateCount() <= lastMasterServerSettingsUpdateCount)) { - GameSettings gameSettings; - copyToGameSettings(&gameSettings); + } - //printf("\n\n\n\n=====#2 got settings [%d] [%d]:\n%s\n",lastMasterServerSettingsUpdateCount,serverInterface->getGameSettingsUpdateCount(),gameSettings.toString().c_str()); + // float pingTime = + // serverInterface->getSlot(i)->getThreadedPingMS(serverInterface->getSlot(i)->getIpAddress().c_str()); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "%s", label.c_str()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + labelNetStatus[i].setText(szBuf); + } else { + string port = "(" + intToStr(config.getInt("PortServer")) + ")"; + labelNetStatus[i].setText("--- " + port); + } + } else if (listBoxControls[i].getSelectedItemIndex() == ctHuman) { + if (EndsWith(glestVersionString, "-dev") == false) { + labelNetStatus[i].setText(glestVersionString); + } else { + // labelLocalGameVersion.setText(glestVersionString + " [" + + // getCompileDateTime() + ", " + getGITRevisionString() + "]"); + labelNetStatus[i].setText(glestVersionString + " [" + + getGITRevisionString() + "]"); + } + } else { + labelNetStatus[i].setText(""); + } + } - serverInterface->setGameSettings(&gameSettings,false); - lastMasterServerSettingsUpdateCount = serverInterface->getGameSettingsUpdateCount(); + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // ServerInterface* serverInterface= + // NetworkManager::getInstance().getServerInterface(); + + if (checkBoxScenario.getValue() == false) { + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + if (i >= mapInfo.players) { + listBoxControls[i].setEditable(false); + listBoxControls[i].setEnabled(false); + + // printf("In [%s::%s] Line: %d i = %d mapInfo.players = + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,mapInfo.players); + } else if (listBoxControls[i].getSelectedItemIndex() != + ctNetworkUnassigned) { + ConnectionSlot *slot = serverInterface->getSlot(i, true); + if ((listBoxControls[i].getSelectedItemIndex() != ctNetwork) || + (listBoxControls[i].getSelectedItemIndex() == ctNetwork && + (slot == NULL || slot->isConnected() == false))) { + listBoxControls[i].setEditable(true); + listBoxControls[i].setEnabled(true); + } else { + listBoxControls[i].setEditable(false); + listBoxControls[i].setEnabled(false); + + // printf("In [%s::%s] Line: %d i = %d mapInfo.players = + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,mapInfo.players); + } + } else { + listBoxControls[i].setEditable(false); + listBoxControls[i].setEnabled(false); + + // printf("In [%s::%s] Line: %d i = %d mapInfo.players = + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,mapInfo.players); + } + } + } - if(hasClientConnection == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - serverInterface->broadcastGameSetup(&gameSettings); - } - } - } + bool checkDataSynch = + (serverInterface->getAllowGameDataSynchCheck() == true && + needToSetChangedGameSettings == true && + ((difftime((long int)time(NULL), lastSetChangedGameSettings) >= + BROADCAST_SETTINGS_SECONDS) || + (this->headlessServerMode == true))); + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // Send the game settings to each client if we have at least one networked + // client + if (checkDataSynch == true) { + serverInterface->setGameSettings(&gameSettings, false); + needToSetChangedGameSettings = false; + } + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (this->headlessServerMode == true || hasOneNetworkSlotOpen == true || + checkBoxAllowInGameJoinPlayer.getValue() == true) { + if (this->headlessServerMode == true && + GlobalStaticFlags::isFlagSet(gsft_lan_mode) == false) { + checkBoxPublishServer.setValue(true); + } + listBoxFallbackCpuMultiplier.setEditable(true); + checkBoxPublishServer.setEditable(true); + + // Masterserver always needs one network slot + if (this->headlessServerMode == true && hasOneNetworkSlotOpen == false) { + bool anyoneConnected = false; + for (int i = 0; i < mapInfo.players; ++i) { + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + ConnectionSlot *slot = serverInterface->getSlot(i, true); + if (slot != NULL && slot->isConnected() == true) { + anyoneConnected = true; + break; + } } - //printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - E\n"); + for (int i = 0; i < mapInfo.players; ++i) { + if (anyoneConnected == false && + listBoxControls[i].getSelectedItemIndex() != ctNetwork) { + listBoxControls[i].setSelectedItemIndex(ctNetwork); + } + } - if(needPing == true) { - MutexSafeWrapper safeMutexThreadOwner2(callingThread->getMutexThreadOwnerValid(),string(__FILE__) + "_" + intToStr(__LINE__)); - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner2.isValidMutex() == false) { - return; - } + updateNetworkSlots(); + } + } else { + checkBoxPublishServer.setValue(false); + checkBoxPublishServer.setEditable(false); + listBoxFallbackCpuMultiplier.setEditable(false); + + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + serverInterface->setPublishEnabled(checkBoxPublishServer.getValue() == + true); + } - lastNetworkPing = time(NULL); + bool republishToMaster = + (difftime((long int)time(NULL), lastMasterserverPublishing) >= + MASTERSERVER_BROADCAST_PUBLISH_SECONDS); - 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__); + if (republishToMaster == true) { + if (checkBoxPublishServer.getValue() == true) { + needToRepublishToMasterserver = true; + lastMasterserverPublishing = time(NULL); + } + } - ServerInterface *serverInterface= NetworkManager::getInstance().getServerInterface(false); - if(serverInterface != NULL) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - NetworkMessagePing *msg = new NetworkMessagePing(GameConstants::networkPingInterval,time(NULL)); - //serverInterface->broadcastPing(&msg); - serverInterface->queueBroadcastMessage(msg); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } + bool callPublishNow = (checkBoxPublishServer.getEditable() && + checkBoxPublishServer.getValue() == true && + needToRepublishToMasterserver == true); + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (callPublishNow == true) { + // give it to me baby, aha aha ... + publishToMasterserver(); + } + if (needToPublishDelayed) { + // this delay is done to make it possible to switch over maps which are + // not meant to be distributed + if ((difftime((long int)time(NULL), mapPublishingDelayTimer) >= + BROADCAST_MAP_DELAY_SECONDS) || + (this->headlessServerMode == true)) { + // after 5 seconds we are allowed to publish again! + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + // set to normal.... + needToPublishDelayed = false; + } + } + if (needToPublishDelayed == false || headlessServerMode == true) { + bool broadCastSettings = + (difftime((long int)time(NULL), lastSetChangedGameSettings) >= + BROADCAST_SETTINGS_SECONDS); + + if (headlessServerMode == true) { + // publish settings directly when we receive them + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + if (lastGameSettingsreceivedCount < + serverInterface->getGameSettingsUpdateCount()) { + needToBroadcastServerSettings = true; + lastSetChangedGameSettings = time(NULL); + lastGameSettingsreceivedCount = + serverInterface->getGameSettingsUpdateCount(); } - safeMutex.ReleaseLock(); + } + + if (broadCastSettings == true) { + needToBroadcastServerSettings = true; + lastSetChangedGameSettings = time(NULL); + } + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // broadCastSettings = (difftime(time(NULL),lastSetChangedGameSettings) >= + // 2); if (broadCastSettings == true) {// reset timer here on bottom + // becasue used for different things lastSetChangedGameSettings = + // time(NULL); + // } + } - //printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - F\n"); + if (this->headlessServerMode == true) { + lastPlayerDisconnected(); } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - if(callingThread->getQuitStatus() == false) { - //throw megaglest_runtime_error(szBuf); - showGeneralError=true; - generalErrorToShow = ex.what(); - } - } + // call the chat manager + chatManager.updateNetwork(); + + // console + console.update(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (currentConnectionCount > soundConnectionCount) { + soundConnectionCount = currentConnectionCount; + SoundRenderer::getInstance().playFx( + CoreData::getInstance().getAttentionSound()); + // switch on music again!! + Config &config = Config::getInstance(); + float configVolume = (config.getInt("SoundVolumeMusic") / 100.f); + CoreData::getInstance().getMenuMusic()->setVolume(configVolume); + } + soundConnectionCount = currentConnectionCount; + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (enableFactionTexturePreview == true) { + if (currentTechName_factionPreview != gameSettings.getTech() || + currentFactionName_factionPreview != + gameSettings.getFactionTypeName( + gameSettings.getThisFactionIndex())) { + + currentTechName_factionPreview = gameSettings.getTech(); + currentFactionName_factionPreview = + gameSettings.getFactionTypeName(gameSettings.getThisFactionIndex()); + + initFactionPreview(&gameSettings); + } + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (autostart == true) { + autostart = false; + safeMutex.ReleaseLock(); + safeMutexCLI.ReleaseLock(); + if (autoStartSettings != NULL) { + + setupUIFromGameSettings(*autoStartSettings); + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + serverInterface->setGameSettings(autoStartSettings, false); + } else { + RestoreLastGameSettings(); + } + PlayNow((autoStartSettings == NULL)); + return; + } + } catch (megaglest_runtime_error &ex) { + // abort(); + // printf("1111111bbbb ex.wantStackTrace() = %d\n",ex.wantStackTrace()); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + // printf("2222222bbbb ex.wantStackTrace() = %d\n",ex.wantStackTrace()); + + showGeneralError = true; + generalErrorToShow = szBuf; + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + showGeneralError = true; + generalErrorToShow = szBuf; + } } -void MenuStateCustomGame::copyToGameSettings(GameSettings *gameSettings,bool forceCloseUnusedSlots) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void MenuStateCustomGame::initFactionPreview(const GameSettings *gameSettings) { + string factionVideoUrl = ""; + string factionVideoUrlFallback = ""; + + string factionDefinitionXML = Game::findFactionLogoFile( + gameSettings, NULL, currentFactionName_factionPreview + ".xml"); + if (factionDefinitionXML != "" && + currentFactionName_factionPreview != + GameConstants::RANDOMFACTION_SLOTNAME && + currentFactionName_factionPreview != GameConstants::OBSERVER_SLOTNAME && + fileExists(factionDefinitionXML) == true) { + XmlTree xmlTree; + std::map mapExtraTagReplacementValues; + xmlTree.load(factionDefinitionXML, Properties::getTagReplacementValues( + &mapExtraTagReplacementValues)); + const XmlNode *factionNode = xmlTree.getRootNode(); + if (factionNode->hasAttribute("faction-preview-video") == true) { + factionVideoUrl = + factionNode->getAttribute("faction-preview-video")->getValue(); + } - int factionCount= 0; - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); + factionVideoUrlFallback = + Game::findFactionLogoFile(gameSettings, NULL, "preview_video.*"); + if (factionVideoUrl == "") { + factionVideoUrl = factionVideoUrlFallback; + factionVideoUrlFallback = ""; + } + } + // printf("currentFactionName_factionPreview [%s] random [%s] observer [%s] + // factionVideoUrl + // [%s]\n",currentFactionName_factionPreview.c_str(),GameConstants::RANDOMFACTION_SLOTNAME,GameConstants::OBSERVER_SLOTNAME,factionVideoUrl.c_str()); + + if (factionVideoUrl != "") { + // SoundRenderer &soundRenderer= SoundRenderer::getInstance(); + if (CoreData::getInstance().getMenuMusic()->getVolume() != 0) { + CoreData::getInstance().getMenuMusic()->setVolume(0); + factionVideoSwitchedOffVolume = true; + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (currentFactionLogo != factionVideoUrl) { + currentFactionLogo = factionVideoUrl; + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && + ::Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == true) { - if(this->headlessServerMode == true && serverInterface->getGameSettingsUpdateCount() > lastMasterServerSettingsUpdateCount && - serverInterface->getGameSettings() != NULL) { - const GameSettings *settings = serverInterface->getGameSettings(); - //printf("\n\n\n\n=====#3 got settings [%d] [%d]:\n%s\n",lastMasterServerSettingsUpdateCount,serverInterface->getGameSettingsUpdateCount(),settings->toString().c_str()); + if (factionVideo != NULL) { + factionVideo->closePlayer(); + delete factionVideo; + factionVideo = NULL; + } + string introVideoFile = factionVideoUrl; + string introVideoFileFallback = factionVideoUrlFallback; + + Context *c = GraphicsInterface::getInstance().getCurrentContext(); + SDL_Window *window = static_cast(c) + ->getPlatformContextGlPtr() + ->getScreenWindow(); + SDL_Surface *screen = static_cast(c) + ->getPlatformContextGlPtr() + ->getScreenSurface(); + + string vlcPluginsPath = + Config::getInstance().getString("VideoPlayerPluginsPath", ""); + // printf("screen->w = %d screen->h = %d screen->format->BitsPerPixel = + // %d\n",screen->w,screen->h,screen->format->BitsPerPixel); + factionVideo = new VideoPlayer( + &Renderer::getInstance(), introVideoFile, introVideoFileFallback, + window, 0, 0, screen->w, screen->h, screen->format->BitsPerPixel, + true, vlcPluginsPath, SystemFlags::VERBOSE_MODE_ENABLED); + factionVideo->initPlayer(); + } + } + } else { + // SoundRenderer &soundRenderer= SoundRenderer::getInstance(); + // switch on music again!! + Config &config = Config::getInstance(); + float configVolume = (config.getInt("SoundVolumeMusic") / 100.f); + if (factionVideoSwitchedOffVolume) { + if (CoreData::getInstance().getMenuMusic()->getVolume() != configVolume) { + CoreData::getInstance().getMenuMusic()->setVolume(configVolume); + } + factionVideoSwitchedOffVolume = false; + } - lastMasterServerSettingsUpdateCount = serverInterface->getGameSettingsUpdateCount(); - //printf("#1 custom menu got map [%s]\n",settings->getMap().c_str()); + if (factionVideo != NULL) { + factionVideo->closePlayer(); + delete factionVideo; + factionVideo = NULL; + } + } - setupUIFromGameSettings(*settings); - } + if (factionVideo == NULL) { + string factionLogo = Game::findFactionLogoFile( + gameSettings, NULL, GameConstants::PREVIEW_SCREEN_FILE_FILTER); + if (factionLogo == "") { + factionLogo = Game::findFactionLogoFile(gameSettings, NULL); + } + if (currentFactionLogo != factionLogo) { + currentFactionLogo = factionLogo; + loadFactionTexture(currentFactionLogo); + } + } +} - gameSettings->setGameName(labelGameName.getText()); +void MenuStateCustomGame::publishToMasterserver() { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + int slotCountUsed = 0; + int slotCountHumans = 0; + int slotCountConnectedPlayers = 0; + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + GameSettings gameSettings; + copyToGameSettings(&gameSettings); + Config &config = Config::getInstance(); + // string serverinfo=""; + + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + publishToServerInfo.clear(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + for (int i = 0; i < mapInfo.players; ++i) { + if (listBoxControls[i].getSelectedItemIndex() != ctClosed) { + slotCountUsed++; + } - // Test flags values - //gameSettings->setFlagTypes1(ft1_show_map_resources); - // + if (listBoxControls[i].getSelectedItemIndex() == ctNetwork || + listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) { + slotCountHumans++; + if (serverInterface->getSlot(i, true) != NULL && + serverInterface->getSlot(i, true)->isConnected()) { + slotCountConnectedPlayers++; + } + } else if (listBoxControls[i].getSelectedItemIndex() == ctHuman) { + slotCountHumans++; + slotCountConnectedPlayers++; + } + } + + publishToServerInfo["uuid"] = Config::getInstance().getString("PlayerId", ""); + + //?status=waiting&system=linux&info=titus + publishToServerInfo["glestVersion"] = glestVersionString; + publishToServerInfo["platform"] = + getPlatformNameString() + "-" + getGITRevisionString(); + publishToServerInfo["binaryCompileDate"] = getCompileDateTime(); + + // game info: + publishToServerInfo["serverTitle"] = gameSettings.getGameName(); + // ip is automatically set + + // game setup info: + + // publishToServerInfo["tech"] = listBoxTechTree.getSelectedItem(); + publishToServerInfo["tech"] = + techTreeFiles[listBoxTechTree.getSelectedItemIndex()]; + // publishToServerInfo["map"] = listBoxMap.getSelectedItem(); + publishToServerInfo["map"] = getCurrentMapFile(); + // publishToServerInfo["tileset"] = listBoxTileset.getSelectedItem(); + publishToServerInfo["tileset"] = + tilesetFiles[listBoxTileset.getSelectedItemIndex()]; + + publishToServerInfo["activeSlots"] = intToStr(slotCountUsed); + publishToServerInfo["networkSlots"] = intToStr(slotCountHumans); + publishToServerInfo["connectedClients"] = intToStr(slotCountConnectedPlayers); + + string serverPort = config.getString( + "PortServer", intToStr(GameConstants::serverPort).c_str()); + string externalPort = config.getString("PortExternal", serverPort.c_str()); + publishToServerInfo["externalconnectport"] = externalPort; + publishToServerInfo["privacyPlease"] = + intToStr(config.getBool("PrivacyPlease", "false")); + + publishToServerInfo["gameStatus"] = intToStr(game_status_waiting_for_players); + if (slotCountHumans <= slotCountConnectedPlayers) { + publishToServerInfo["gameStatus"] = intToStr(game_status_waiting_for_start); + } + + publishToServerInfo["gameUUID"] = gameSettings.getGameUUID(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); +} - if(checkBoxScenario.getValue() == true) { - gameSettings->setScenario(scenarioInfo.name); - gameSettings->setScenarioDir(Scenario::getScenarioPath(dirList, scenarioInfo.name)); - - gameSettings->setDefaultResources(scenarioInfo.defaultResources); - gameSettings->setDefaultUnits(scenarioInfo.defaultUnits); - gameSettings->setDefaultVictoryConditions(scenarioInfo.defaultVictoryConditions); - } - else { - gameSettings->setScenario(""); - gameSettings->setScenarioDir(""); - } - - gameSettings->setGameUUID(this->gameUUID); - - //printf("scenarioInfo.name [%s] [%s] [%s]\n",scenarioInfo.name.c_str(),listBoxMap.getSelectedItem().c_str(),getCurrentMapFile().c_str()); - - gameSettings->setMapFilter(listBoxMapFilter.getSelectedItemIndex()); - gameSettings->setDescription(formatString(getCurrentMapFile())); - gameSettings->setMap(getCurrentMapFile()); - if(tilesetFiles.empty() == false) { - gameSettings->setTileset(tilesetFiles[listBoxTileset.getSelectedItemIndex()]); - } - if(techTreeFiles.empty() == false) { - gameSettings->setTech(techTreeFiles[listBoxTechTree.getSelectedItemIndex()]); - } - - if(autoStartSettings != NULL) { - gameSettings->setDefaultUnits(autoStartSettings->getDefaultUnits()); - gameSettings->setDefaultResources(autoStartSettings->getDefaultResources()); - gameSettings->setDefaultVictoryConditions(autoStartSettings->getDefaultVictoryConditions()); - } - else if(checkBoxScenario.getValue() == false) { - gameSettings->setDefaultUnits(true); - gameSettings->setDefaultResources(true); - gameSettings->setDefaultVictoryConditions(true); - } - - gameSettings->setFogOfWar(listBoxFogOfWar.getSelectedItemIndex() == 0 || - listBoxFogOfWar.getSelectedItemIndex() == 1 ); - - gameSettings->setAllowObservers(checkBoxAllowObservers.getValue() == 1); - - uint32 valueFlags1 = gameSettings->getFlagTypes1(); - if(listBoxFogOfWar.getSelectedItemIndex() == 1 || - listBoxFogOfWar.getSelectedItemIndex() == 2 ) { - valueFlags1 |= ft1_show_map_resources; - gameSettings->setFlagTypes1(valueFlags1); - } - else { - valueFlags1 &= ~ft1_show_map_resources; - gameSettings->setFlagTypes1(valueFlags1); - } - - //gameSettings->setEnableObserverModeAtEndGame(listBoxEnableObserverMode.getSelectedItemIndex() == 0); - gameSettings->setEnableObserverModeAtEndGame(true); - //gameSettings->setPathFinderType(static_cast(listBoxPathFinderType.getSelectedItemIndex())); - - valueFlags1 = gameSettings->getFlagTypes1(); - if(checkBoxEnableSwitchTeamMode.getValue() == true) { - valueFlags1 |= ft1_allow_team_switching; - gameSettings->setFlagTypes1(valueFlags1); - } - else { - valueFlags1 &= ~ft1_allow_team_switching; - gameSettings->setFlagTypes1(valueFlags1); - } - gameSettings->setAiAcceptSwitchTeamPercentChance(strToInt(listBoxAISwitchTeamAcceptPercent.getSelectedItem())); - gameSettings->setFallbackCpuMultiplier(listBoxFallbackCpuMultiplier.getSelectedItemIndex()); - - if(checkBoxAllowInGameJoinPlayer.getValue() == true) { - valueFlags1 |= ft1_allow_in_game_joining; - gameSettings->setFlagTypes1(valueFlags1); - } - else { - valueFlags1 &= ~ft1_allow_in_game_joining; - gameSettings->setFlagTypes1(valueFlags1); - } - - if(checkBoxAllowTeamUnitSharing.getValue() == true) { - valueFlags1 |= ft1_allow_shared_team_units; - gameSettings->setFlagTypes1(valueFlags1); - } - else { - valueFlags1 &= ~ft1_allow_shared_team_units; - gameSettings->setFlagTypes1(valueFlags1); - } - - if(checkBoxAllowTeamResourceSharing.getValue() == true) { - valueFlags1 |= ft1_allow_shared_team_resources; - gameSettings->setFlagTypes1(valueFlags1); - } - else { - valueFlags1 &= ~ft1_allow_shared_team_resources; - gameSettings->setFlagTypes1(valueFlags1); - } - - if(Config::getInstance().getBool("EnableNetworkGameSynchChecks","false") == true) { - //printf("*WARNING* - EnableNetworkGameSynchChecks is enabled\n"); - - valueFlags1 |= ft1_network_synch_checks_verbose; - gameSettings->setFlagTypes1(valueFlags1); - - } - else { - valueFlags1 &= ~ft1_network_synch_checks_verbose; - gameSettings->setFlagTypes1(valueFlags1); - - } - if(Config::getInstance().getBool("EnableNetworkGameSynchMonitor","false") == true) { - //printf("*WARNING* - EnableNetworkGameSynchChecks is enabled\n"); - - valueFlags1 |= ft1_network_synch_checks; - gameSettings->setFlagTypes1(valueFlags1); - - } - else { - valueFlags1 &= ~ft1_network_synch_checks; - gameSettings->setFlagTypes1(valueFlags1); - - } - - gameSettings->setNetworkAllowNativeLanguageTechtree(checkBoxAllowNativeLanguageTechtree.getValue()); - - // First save Used slots - //for(int i=0; iheadlessServerMode == true) { - // switch slot to network, because no human in headless mode - listBoxControls[i].setSelectedItemIndex(ctNetwork) ; - updateResourceMultiplier(i); - } - - ControlType ct= static_cast(listBoxControls[i].getSelectedItemIndex()); - - if(forceCloseUnusedSlots == true && (ct == ctNetworkUnassigned || ct == ctNetwork)) { - if(serverInterface != NULL && - (serverInterface->getSlot(i,true) == NULL || - serverInterface->getSlot(i,true)->isConnected() == false)) { - if(checkBoxScenario.getValue() == false) { - //printf("Closed A [%d] [%s]\n",i,labelPlayerNames[i].getText().c_str()); - - listBoxControls[i].setSelectedItemIndex(ctClosed); - ct = ctClosed; - } - } - } - else if(ct == ctNetworkUnassigned && i < mapInfo.players) { - listBoxControls[i].setSelectedItemIndex(ctNetwork); - ct = ctNetwork; - } - - if(ct != ctClosed) { - int slotIndex = factionCount; - gameSettings->setFactionControl(slotIndex, ct); - if(ct == ctHuman) { - 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()); - - gameSettings->setThisFactionIndex(slotIndex); - gameSettings->setNetworkPlayerName(slotIndex, getHumanPlayerName(i)); - gameSettings->setNetworkPlayerUUID(slotIndex,Config::getInstance().getString("PlayerId","")); - gameSettings->setNetworkPlayerPlatform(slotIndex,getPlatformNameString()); - gameSettings->setNetworkPlayerStatuses(slotIndex, getNetworkPlayerStatus()); - Lang &lang= Lang::getInstance(); - gameSettings->setNetworkPlayerLanguages(slotIndex, lang.getLanguage()); - } - else if(serverInterface != NULL && serverInterface->getSlot(i,true) != NULL) { - gameSettings->setNetworkPlayerLanguages(slotIndex, serverInterface->getSlot(i,true)->getNetworkPlayerLanguage()); - } - - //if(slotIndex == 0) printf("slotIndex = %d, i = %d, multiplier = %d\n",slotIndex,i,listBoxRMultiplier[i].getSelectedItemIndex()); - - //printf("Line: %d multiplier index: %d slotIndex: %d\n",__LINE__,listBoxRMultiplier[i].getSelectedItemIndex(),slotIndex); - gameSettings->setResourceMultiplierIndex(slotIndex, listBoxRMultiplier[i].getSelectedItemIndex()); - //printf("Line: %d multiplier index: %d slotIndex: %d\n",__LINE__,gameSettings->getResourceMultiplierIndex(slotIndex),slotIndex); - - 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()); - - gameSettings->setFactionTypeName(slotIndex, factionFiles[listBoxFactions[i].getSelectedItemIndex()]); - if(factionFiles[listBoxFactions[i].getSelectedItemIndex()] == formatString(GameConstants::OBSERVER_SLOTNAME)) { - listBoxTeams[i].setSelectedItem(intToStr(GameConstants::maxPlayers + fpt_Observer)); - } - else if(listBoxTeams[i].getSelectedItem() == intToStr(GameConstants::maxPlayers + fpt_Observer)) { - - //printf("Line: %d lastSelectedTeamIndex[i] = %d \n",__LINE__,lastSelectedTeamIndex[i]); - - if((listBoxControls[i].getSelectedItemIndex() == ctCpuEasy || listBoxControls[i].getSelectedItemIndex() == ctCpu || - listBoxControls[i].getSelectedItemIndex() == ctCpuUltra || listBoxControls[i].getSelectedItemIndex() == ctCpuMega) && - checkBoxScenario.getValue() == true) { - - } - else { - if(lastSelectedTeamIndex[i] >= 0 && lastSelectedTeamIndex[i] + 1 != (GameConstants::maxPlayers + fpt_Observer)) { - if(lastSelectedTeamIndex[i] == 0) { - lastSelectedTeamIndex[i] = GameConstants::maxPlayers-1; - } - else if(lastSelectedTeamIndex[i] == GameConstants::maxPlayers-1) { - lastSelectedTeamIndex[i] = 0; - } - - listBoxTeams[i].setSelectedItemIndex(lastSelectedTeamIndex[i]); - } - else { - listBoxTeams[i].setSelectedItem(intToStr(1)); - } - } - } - - gameSettings->setTeam(slotIndex, listBoxTeams[i].getSelectedItemIndex()); - gameSettings->setStartLocationIndex(slotIndex, i); - - if(listBoxControls[i].getSelectedItemIndex() == ctNetwork || - listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) { - if(serverInterface != NULL && - serverInterface->getSlot(i,true) != NULL && - serverInterface->getSlot(i,true)->isConnected()) { - - gameSettings->setNetworkPlayerStatuses(slotIndex,serverInterface->getSlot(i,true)->getNetworkPlayerStatus()); - - 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()); - - gameSettings->setNetworkPlayerName(slotIndex, serverInterface->getSlot(i,true)->getName()); - gameSettings->setNetworkPlayerUUID(i,serverInterface->getSlot(i,true)->getUUID()); - gameSettings->setNetworkPlayerPlatform(i,serverInterface->getSlot(i,true)->getPlatform()); - labelPlayerNames[i].setText(serverInterface->getSlot(i,true)->getName()); - } - else { - 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); - - gameSettings->setNetworkPlayerName(slotIndex, GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME); - labelPlayerNames[i].setText(""); - } - } - else if (listBoxControls[i].getSelectedItemIndex() != ctHuman) { - AIPlayerCount++; - 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); - - Lang &lang= Lang::getInstance(); - gameSettings->setNetworkPlayerName(slotIndex, lang.getString("AI") + intToStr(AIPlayerCount)); - labelPlayerNames[i].setText(""); - } - if (listBoxControls[i].getSelectedItemIndex() == ctHuman) { - setSlotHuman(i); - } - if(serverInterface != NULL && serverInterface->getSlot(i,true) != NULL) { - gameSettings->setNetworkPlayerUUID(slotIndex,serverInterface->getSlot(i,true)->getUUID()); - gameSettings->setNetworkPlayerPlatform(slotIndex,serverInterface->getSlot(i,true)->getPlatform()); - } - - factionCount++; - } - else { - //gameSettings->setNetworkPlayerName(""); - gameSettings->setNetworkPlayerStatuses(factionCount, npst_None); - labelPlayerNames[i].setText(""); - } - } - - // Next save closed slots - int closedCount = 0; - for(int i = 0; i < GameConstants::maxPlayers; ++i) { - ControlType ct= static_cast(listBoxControls[i].getSelectedItemIndex()); - if(ct == ctClosed) { - int slotIndex = factionCount + closedCount; - - gameSettings->setFactionControl(slotIndex, ct); - gameSettings->setTeam(slotIndex, listBoxTeams[i].getSelectedItemIndex()); - gameSettings->setStartLocationIndex(slotIndex, i); - //gameSettings->setResourceMultiplierIndex(slotIndex, 10); - listBoxRMultiplier[i].setSelectedItem("1.0"); - gameSettings->setResourceMultiplierIndex(slotIndex, listBoxRMultiplier[i].getSelectedItemIndex()); - //printf("Test multiplier = %s\n",listBoxRMultiplier[i].getSelectedItem().c_str()); - - - 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()); - - gameSettings->setFactionTypeName(slotIndex, factionFiles[listBoxFactions[i].getSelectedItemIndex()]); - gameSettings->setNetworkPlayerName(slotIndex, GameConstants::NETWORK_SLOT_CLOSED_SLOTNAME); - gameSettings->setNetworkPlayerUUID(slotIndex,""); - gameSettings->setNetworkPlayerPlatform(slotIndex,""); - - closedCount++; - } - } - - gameSettings->setFactionCount(factionCount); - - Config &config = Config::getInstance(); - gameSettings->setEnableServerControlledAI(config.getBool("ServerControlledAI","true")); - gameSettings->setNetworkFramePeriod(config.getInt("NetworkSendFrameCount","20")); - gameSettings->setNetworkPauseGameForLaggedClients(((checkBoxNetworkPauseGameForLaggedClients.getValue() == true))); - - setCRCsToGameSettings(gameSettings); - - if(this->headlessServerMode == true) { - time_t clientConnectedTime = 0; - bool masterserver_admin_found=false; - //printf("mapInfo.players [%d]\n",mapInfo.players); - - for(int i= 0; i < mapInfo.players; ++i) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(listBoxControls[i].getSelectedItemIndex() == ctNetwork || listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if( serverInterface->getSlot(i,true) != NULL && serverInterface->getSlot(i,true)->isConnected()) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //printf("slot = %d serverInterface->getSlot(i)->getConnectedTime() = %d session key [%d]\n",i,serverInterface->getSlot(i)->getConnectedTime(),serverInterface->getSlot(i)->getSessionKey()); - - if(clientConnectedTime == 0 || - (serverInterface->getSlot(i,true)->getConnectedTime() > 0 && serverInterface->getSlot(i,true)->getConnectedTime() < clientConnectedTime)) { - clientConnectedTime = serverInterface->getSlot(i,true)->getConnectedTime(); - gameSettings->setMasterserver_admin(serverInterface->getSlot(i,true)->getSessionKey()); - gameSettings->setMasterserver_admin_faction_index(serverInterface->getSlot(i,true)->getPlayerIndex()); - labelGameName.setText(createGameName(serverInterface->getSlot(i,true)->getName())); - //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); - } - if(serverInterface->getSlot(i,true)->getSessionKey() == gameSettings->getMasterserver_admin()){ - masterserver_admin_found=true; - } - } - } - } - if(masterserver_admin_found == false ) { - for(int i=mapInfo.players; i < GameConstants::maxPlayers; ++i) { - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - //ConnectionSlot *slot = serverInterface->getSlot(i); - - if( serverInterface->getSlot(i,true) != NULL && serverInterface->getSlot(i,true)->isConnected()) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //printf("slot = %d serverInterface->getSlot(i)->getConnectedTime() = %d session key [%d]\n",i,serverInterface->getSlot(i)->getConnectedTime(),serverInterface->getSlot(i)->getSessionKey()); - - if(clientConnectedTime == 0 || - (serverInterface->getSlot(i,true)->getConnectedTime() > 0 && serverInterface->getSlot(i,true)->getConnectedTime() < clientConnectedTime)) { - clientConnectedTime = serverInterface->getSlot(i,true)->getConnectedTime(); - gameSettings->setMasterserver_admin(serverInterface->getSlot(i,true)->getSessionKey()); - gameSettings->setMasterserver_admin_faction_index(serverInterface->getSlot(i,true)->getPlayerIndex()); - labelGameName.setText(createGameName(serverInterface->getSlot(i,true)->getName())); - //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); - } - if(serverInterface->getSlot(i,true)->getSessionKey() == gameSettings->getMasterserver_admin()){ - masterserver_admin_found=true; - } - } - } - } - - if(masterserver_admin_found == false) - { - labelGameName.setText(createGameName()); - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void MenuStateCustomGame::setupTask(BaseThread *callingThread, void *userdata) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\n\nsetupTask callingThread [%p] userdata [%p]\n", callingThread, + userdata); + if (userdata != NULL) { + int value = *((int *)&userdata); + THREAD_NOTIFIER_TYPE threadType = (THREAD_NOTIFIER_TYPE)value; + // printf("\n\nsetupTask callingThread [%p] userdata + // [%p]\n",callingThread,userdata); + if (threadType == tnt_MASTERSERVER) { + MenuStateCustomGame::setupTaskStatic(callingThread); + } + } +} +void MenuStateCustomGame::shutdownTask(BaseThread *callingThread, + void *userdata) { + // printf("\n\nshutdownTask callingThread [%p] userdata + // [%p]\n",callingThread,userdata); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\n\nshutdownTask callingThread [%p] userdata [%p]\n", callingThread, + userdata); + if (userdata != NULL) { + int value = *((int *)&userdata); + THREAD_NOTIFIER_TYPE threadType = (THREAD_NOTIFIER_TYPE)value; + // printf("\n\nshutdownTask callingThread [%p] userdata + // [%p]\n",callingThread,userdata); + if (threadType == tnt_MASTERSERVER) { + MenuStateCustomGame::shutdownTaskStatic(callingThread); + } + } +} +void MenuStateCustomGame::setupTaskStatic(BaseThread *callingThread) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + CURL *handle = SystemFlags::initHTTP(); + callingThread->setGenericData(handle); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); +} +void MenuStateCustomGame::shutdownTaskStatic(BaseThread *callingThread) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + // printf("LINE: %d\n",__LINE__); + CURL *handle = callingThread->getGenericData(); + SystemFlags::cleanupHTTP(&handle); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); } -void MenuStateCustomGame::KeepCurrentHumanPlayerSlots(GameSettings &gameSettings) { - //look for human players - bool foundValidHumanControlTypeInFile = false; - for(int index2 = 0; index2 < GameConstants::maxPlayers; ++index2) { - ControlType ctFile = static_cast(gameSettings.getFactionControl(index2)); - if(ctFile == ctHuman) { - ControlType ctUI = static_cast(listBoxControls[index2].getSelectedItemIndex()); - if(ctUI != ctNetwork && ctUI != ctNetworkUnassigned) { - foundValidHumanControlTypeInFile = true; - //printf("Human found in file [%d]\n",index2); - } - else if(labelPlayerNames[index2].getText() == "") { - foundValidHumanControlTypeInFile = true; - } - } - } - - for(int index = 0; index < GameConstants::maxPlayers; ++index) { - ControlType ct= static_cast(listBoxControls[index].getSelectedItemIndex()); - if(ct == ctHuman) { - //printf("Human found in UI [%d] and file [%d]\n",index,foundControlType); - - if(foundValidHumanControlTypeInFile == false) { - gameSettings.setFactionControl(index,ctHuman); - gameSettings.setNetworkPlayerName(index,getHumanPlayerName()); - } - } - - ControlType ctFile = static_cast(gameSettings.getFactionControl(index)); - if(ctFile == ctHuman) { - gameSettings.setFactionControl(index,ctHuman); - } - } +void MenuStateCustomGame::simpleTask(BaseThread *callingThread, + void *userdata) { + // printf("\n\nSimple Task callingThread [%p] userdata + // [%p]\n",callingThread,userdata); + int value = *((int *)&userdata); + // printf("\n\nSimple Task callingThread [%p] userdata [%p] value = + // %d\n",callingThread,userdata,value); + + THREAD_NOTIFIER_TYPE threadType = (THREAD_NOTIFIER_TYPE)value; + if (threadType == tnt_MASTERSERVER) { + simpleTaskForMasterServer(callingThread); + } else if (threadType == tnt_CLIENTS) { + simpleTaskForClients(callingThread); + } } -void MenuStateCustomGame::saveGameSettings(std::string fileName) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void MenuStateCustomGame::simpleTaskForMasterServer(BaseThread *callingThread) { + try { + // printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - A\n"); + + MutexSafeWrapper safeMutexThreadOwner( + callingThread->getMutexThreadOwnerValid(), + string(__FILE__) + "_" + intToStr(__LINE__)); + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + return; + } - GameSettings gameSettings; - copyToGameSettings(&gameSettings); - CoreData::getInstance().saveGameSettingsToFile(fileName, &gameSettings,checkBoxAdvanced.getValue()); + // printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - B\n"); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); -} + MutexSafeWrapper safeMutex(callingThread->getMutexThreadObjectAccessor(), + string(__FILE__) + "_" + intToStr(__LINE__)); + bool republish = (needToRepublishToMasterserver == true && + publishToServerInfo.empty() == false); + needToRepublishToMasterserver = false; + std::map newPublishToServerInfo = publishToServerInfo; + publishToServerInfo.clear(); -bool MenuStateCustomGame::loadGameSettingsFromFile(GameSettings *gameSettings,std::string fileName) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // printf("simpleTask broadCastSettings = %d\n",broadCastSettings); - GameSettings originalGameSettings; - copyToGameSettings(&originalGameSettings); + if (callingThread->getQuitStatus() == true) { + return; + } - try { - bool loadSuccessful= CoreData::getInstance().loadGameSettingsFromFile(fileName, gameSettings); - if(!loadSuccessful){ - console.addLine("Cannot load '"+fileName+"'"); - // do nothing on failure - return false; - } - KeepCurrentHumanPlayerSlots(*gameSettings); - - // correct game settings for headless: - if(this->headlessServerMode == true) { - for(int i = 0; i < GameConstants::maxPlayers; ++i) { - if(gameSettings->getFactionControl(i)== ctHuman){ - gameSettings->setFactionControl(i,ctNetwork); - } - } - } - - vector mapsV=playerSortedMaps[0]; - if(std::find(mapsV.begin(), mapsV.end(), gameSettings->getMap()) == mapsV.end()) { - console.addLine("Cannot load '"+fileName+"', map unknown ('"+gameSettings->getMap()+"')"); - return false;// map unknown - } - if(std::find(tilesetFiles.begin(), tilesetFiles.end(), gameSettings->getTileset()) == tilesetFiles.end()) { - console.addLine("Cannot load '"+fileName+"', tileset unknown ('"+gameSettings->getTileset()+"')"); - return false;// tileset unknown - } - if(std::find(techTreeFiles.begin(), techTreeFiles.end(), gameSettings->getTech()) == techTreeFiles.end()) { - console.addLine("Cannot load '"+fileName+"', techtree unknown ('"+gameSettings->getTech()+"')"); - return false;// techtree unknown - } - - setupUIFromGameSettings(*gameSettings); - } - catch(const exception &ex) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - 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()); - - showMessageBox( ex.what(), "Error", false); - - setupUIFromGameSettings(originalGameSettings); - *gameSettings = originalGameSettings; - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - return true; -} + // printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - C\n"); + + if (republish == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + string request = Config::getInstance().getString("Masterserver"); + if (request != "") { + endPathWithSlash(request, false); + } + request += "addServerInfo.php?"; + + // CURL *handle = SystemFlags::initHTTP(); + CURL *handle = callingThread->getGenericData(); -void MenuStateCustomGame::setupUIFromGameSettings(const GameSettings &gameSettings) { - string humanPlayerName = getHumanPlayerName(); - - string scenarioDir = ""; - checkBoxScenario.setValue((gameSettings.getScenario() != "")); - if(checkBoxScenario.getValue() == true) { - listBoxScenario.setSelectedItem(formatString(gameSettings.getScenario())); - - loadScenarioInfo(Scenario::getScenarioPath(dirList, scenarioFiles[listBoxScenario.getSelectedItemIndex()]), &scenarioInfo); - scenarioDir = Scenario::getScenarioDir(dirList, gameSettings.getScenario()); - - //printf("scenarioInfo.fogOfWar = %d scenarioInfo.fogOfWar_exploredFlag = %d\n",scenarioInfo.fogOfWar,scenarioInfo.fogOfWar_exploredFlag); - if(scenarioInfo.fogOfWar == false && scenarioInfo.fogOfWar_exploredFlag == false) { - listBoxFogOfWar.setSelectedItemIndex(2); - } - else if(scenarioInfo.fogOfWar_exploredFlag == true) { - listBoxFogOfWar.setSelectedItemIndex(1); - } - else { - listBoxFogOfWar.setSelectedItemIndex(0); - } - checkBoxAllowTeamUnitSharing.setValue(scenarioInfo.allowTeamUnitSharing); - checkBoxAllowTeamResourceSharing.setValue(scenarioInfo.allowTeamResourceSharing); - } - setupMapList(gameSettings.getScenario()); - setupTechList(gameSettings.getScenario(),false); - setupTilesetList(gameSettings.getScenario()); - - if(checkBoxScenario.getValue() == true) { - //string file = Scenario::getScenarioPath(dirList, gameSettings.getScenario()); - //loadScenarioInfo(file, &scenarioInfo); - - //printf("#6.1 about to load map [%s]\n",scenarioInfo.mapName.c_str()); - //loadMapInfo(Config::getMapPath(scenarioInfo.mapName, scenarioDir, true), &mapInfo, false); - //printf("#6.2\n"); - - listBoxMapFilter.setSelectedItemIndex(0); - comboBoxMap.setItems(formattedPlayerSortedMaps[mapInfo.players]); - comboBoxMap.setSelectedItem(formatString(scenarioInfo.mapName)); - } - else { - //printf("gameSettings.getMapFilter()=%d \n",gameSettings.getMapFilter()); - if(gameSettings.getMapFilter() == 0) { - listBoxMapFilter.setSelectedItemIndex(0); - } - else { - listBoxMapFilter.setSelectedItem(intToStr(gameSettings.getMapFilter())); - } - comboBoxMap.setItems(formattedPlayerSortedMaps[gameSettings.getMapFilter()]); - } + int paramIndex = 0; + for (std::map::const_iterator iterMap = + newPublishToServerInfo.begin(); + iterMap != newPublishToServerInfo.end(); ++iterMap) { - //printf("gameSettings.getMap() [%s] [%s]\n",gameSettings.getMap().c_str(),listBoxMap.getSelectedItem().c_str()); + request += iterMap->first; + request += "="; + request += SystemFlags::escapeURL(iterMap->second, handle); - string mapFile = gameSettings.getMap(); - if(find(mapFiles.begin(),mapFiles.end(),mapFile) != mapFiles.end()) { - mapFile = formatString(mapFile); - comboBoxMap.setSelectedItem(mapFile); + paramIndex++; + if (paramIndex < (int)newPublishToServerInfo.size()) { + request += "&"; + } + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("The Lobby request is:\n%s\n", request.c_str()); + + 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()); + safeMutex.ReleaseLock(true); + safeMutexThreadOwner.ReleaseLock(); + + std::string serverInfo = SystemFlags::getHTTP(request, handle); + // SystemFlags::cleanupHTTP(&handle); + + MutexSafeWrapper safeMutexThreadOwner2( + callingThread->getMutexThreadOwnerValid(), + string(__FILE__) + "_" + intToStr(__LINE__)); + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner2.isValidMutex() == false) { + return; + } + safeMutex.Lock(); + + // printf("the result is:\n'%s'\n",serverInfo.c_str()); + 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()); + + // uncomment to enable router setup check of this server + if (EndsWith(serverInfo, "OK") == false) { + if (callingThread->getQuitStatus() == true) { + return; + } + + // Give things another chance to see if we can get a connection from the + // master server + if (tMasterserverErrorElapsed > 0 && + difftime((long int)time(NULL), tMasterserverErrorElapsed) > + MASTERSERVER_BROADCAST_MAX_WAIT_RESPONSE_SECONDS) { + showMasterserverError = true; + masterServererErrorToShow = + (serverInfo != "" ? serverInfo : "No Reply"); + } else { + if (tMasterserverErrorElapsed == 0) { + tMasterserverErrorElapsed = time(NULL); + } + + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line %d] error checking response from masterserver " + "elapsed seconds = %.2f / %d\nResponse:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, + difftime((long int)time(NULL), tMasterserverErrorElapsed), + MASTERSERVER_BROADCAST_MAX_WAIT_RESPONSE_SECONDS, + serverInfo.c_str()); + + needToRepublishToMasterserver = true; + } + } + } else { + safeMutexThreadOwner.ReleaseLock(); + } - loadMapInfo(Config::getMapPath(getCurrentMapFile(),scenarioDir,true), &mapInfo, true,true); - labelMapInfo.setText(mapInfo.desc); - } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - D\n"); + + safeMutex.ReleaseLock(); + + // printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - F\n"); + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + if (callingThread->getQuitStatus() == false) { + // throw megaglest_runtime_error(szBuf); + showGeneralError = true; + generalErrorToShow = ex.what(); + } + } - string tilesetFile = gameSettings.getTileset(); - if(find(tilesetFiles.begin(),tilesetFiles.end(),tilesetFile) != tilesetFiles.end()) { - tilesetFile = formatString(tilesetFile); - listBoxTileset.setSelectedItem(tilesetFile); - } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); +} - string techtreeFile = gameSettings.getTech(); - if(find(techTreeFiles.begin(),techTreeFiles.end(),techtreeFile) != techTreeFiles.end()) { - techtreeFile = formatString(techtreeFile); - listBoxTechTree.setSelectedItem(techtreeFile); - } +void MenuStateCustomGame::simpleTaskForClients(BaseThread *callingThread) { + try { + // printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - A\n"); + + MutexSafeWrapper safeMutexThreadOwner( + callingThread->getMutexThreadOwnerValid(), + string(__FILE__) + "_" + intToStr(__LINE__)); + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + return; + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - B\n"); - //gameSettings->setDefaultUnits(true); - //gameSettings->setDefaultResources(true); - //gameSettings->setDefaultVictoryConditions(true); + MutexSafeWrapper safeMutex(callingThread->getMutexThreadObjectAccessor(), + string(__FILE__) + "_" + intToStr(__LINE__)); + bool broadCastSettings = needToBroadcastServerSettings; - //FogOfWar - if(checkBoxScenario.getValue() == false) { - listBoxFogOfWar.setSelectedItemIndex(0); // default is 0! - if(gameSettings.getFogOfWar() == false){ - listBoxFogOfWar.setSelectedItemIndex(2); - } + // printf("simpleTask broadCastSettings = %d\n",broadCastSettings); - if((gameSettings.getFlagTypes1() & ft1_show_map_resources) == ft1_show_map_resources){ - if(gameSettings.getFogOfWar() == true){ - listBoxFogOfWar.setSelectedItemIndex(1); - } - } - } + needToBroadcastServerSettings = false; + bool hasClientConnection = false; - //printf("In [%s::%s line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (broadCastSettings == true) { + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(false); + if (serverInterface != NULL) { + hasClientConnection = serverInterface->hasClientConnection(); + } + } + bool needPing = (difftime((long int)time(NULL), lastNetworkPing) >= + GameConstants::networkPingInterval); - checkBoxAllowObservers.setValue(gameSettings.getAllowObservers() == true ? true : false); - //listBoxEnableObserverMode.setSelectedItem(gameSettings.getEnableObserverModeAtEndGame() == true ? lang.getString("Yes") : lang.getString("No")); + if (callingThread->getQuitStatus() == true) { + return; + } - checkBoxEnableSwitchTeamMode.setValue((gameSettings.getFlagTypes1() & ft1_allow_team_switching) == ft1_allow_team_switching ? true : false); - listBoxAISwitchTeamAcceptPercent.setSelectedItem(intToStr(gameSettings.getAiAcceptSwitchTeamPercentChance())); - listBoxFallbackCpuMultiplier.setSelectedItemIndex(gameSettings.getFallbackCpuMultiplier()); + // printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - C\n"); + + safeMutexThreadOwner.ReleaseLock(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - D\n"); + + if (broadCastSettings == true) { + MutexSafeWrapper safeMutexThreadOwner2( + callingThread->getMutexThreadOwnerValid(), + string(__FILE__) + "_" + intToStr(__LINE__)); + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner2.isValidMutex() == false) { + return; + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // printf("simpleTask broadCastSettings = %d hasClientConnection = + // %d\n",broadCastSettings,hasClientConnection); + + if (callingThread->getQuitStatus() == true) { + return; + } + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(false); + if (serverInterface != NULL) { + lastGameSettingsreceivedCount++; + if (this->headlessServerMode == false || + (serverInterface->getGameSettingsUpdateCount() <= + lastMasterServerSettingsUpdateCount)) { + GameSettings gameSettings; + copyToGameSettings(&gameSettings); + + // printf("\n\n\n\n=====#2 got settings [%d] + // [%d]:\n%s\n",lastMasterServerSettingsUpdateCount,serverInterface->getGameSettingsUpdateCount(),gameSettings.toString().c_str()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + serverInterface->setGameSettings(&gameSettings, false); + lastMasterServerSettingsUpdateCount = + serverInterface->getGameSettingsUpdateCount(); + + if (hasClientConnection == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + serverInterface->broadcastGameSetup(&gameSettings); + } + } + } + } - checkBoxAllowInGameJoinPlayer.setValue((gameSettings.getFlagTypes1() & ft1_allow_in_game_joining) == ft1_allow_in_game_joining ? true : false); + // printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - E\n"); + + if (needPing == true) { + MutexSafeWrapper safeMutexThreadOwner2( + callingThread->getMutexThreadOwnerValid(), + string(__FILE__) + "_" + intToStr(__LINE__)); + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner2.isValidMutex() == false) { + return; + } + + lastNetworkPing = time(NULL); + + 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__); + + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(false); + if (serverInterface != NULL) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + NetworkMessagePing *msg = new NetworkMessagePing( + GameConstants::networkPingInterval, time(NULL)); + // serverInterface->broadcastPing(&msg); + serverInterface->queueBroadcastMessage(msg); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } + } + safeMutex.ReleaseLock(); + + // printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - F\n"); + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + if (callingThread->getQuitStatus() == false) { + // throw megaglest_runtime_error(szBuf); + showGeneralError = true; + generalErrorToShow = ex.what(); + } + } - checkBoxAllowTeamUnitSharing.setValue((gameSettings.getFlagTypes1() & ft1_allow_shared_team_units) == ft1_allow_shared_team_units ? true : false); - checkBoxAllowTeamResourceSharing.setValue((gameSettings.getFlagTypes1() & ft1_allow_shared_team_resources) == ft1_allow_shared_team_resources ? true : false); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); +} - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - if(serverInterface != NULL) { - serverInterface->setAllowInGameConnections(checkBoxAllowInGameJoinPlayer.getValue() == true); - } +void MenuStateCustomGame::copyToGameSettings(GameSettings *gameSettings, + bool forceCloseUnusedSlots) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + int factionCount = 0; + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (this->headlessServerMode == true && + serverInterface->getGameSettingsUpdateCount() > + lastMasterServerSettingsUpdateCount && + serverInterface->getGameSettings() != NULL) { + const GameSettings *settings = serverInterface->getGameSettings(); + // printf("\n\n\n\n=====#3 got settings [%d] + // [%d]:\n%s\n",lastMasterServerSettingsUpdateCount,serverInterface->getGameSettingsUpdateCount(),settings->toString().c_str()); + + lastMasterServerSettingsUpdateCount = + serverInterface->getGameSettingsUpdateCount(); + // printf("#1 custom menu got map [%s]\n",settings->getMap().c_str()); + + setupUIFromGameSettings(*settings); + } + + gameSettings->setGameName(labelGameName.getText()); + + // Test flags values + // gameSettings->setFlagTypes1(ft1_show_map_resources); + // + + if (checkBoxScenario.getValue() == true) { + gameSettings->setScenario(scenarioInfo.name); + gameSettings->setScenarioDir( + Scenario::getScenarioPath(dirList, scenarioInfo.name)); + + gameSettings->setDefaultResources(scenarioInfo.defaultResources); + gameSettings->setDefaultUnits(scenarioInfo.defaultUnits); + gameSettings->setDefaultVictoryConditions( + scenarioInfo.defaultVictoryConditions); + } else { + gameSettings->setScenario(""); + gameSettings->setScenarioDir(""); + } + + gameSettings->setGameUUID(this->gameUUID); + + // printf("scenarioInfo.name [%s] [%s] + // [%s]\n",scenarioInfo.name.c_str(),listBoxMap.getSelectedItem().c_str(),getCurrentMapFile().c_str()); + + gameSettings->setMapFilter(listBoxMapFilter.getSelectedItemIndex()); + gameSettings->setDescription(formatString(getCurrentMapFile())); + gameSettings->setMap(getCurrentMapFile()); + if (tilesetFiles.empty() == false) { + gameSettings->setTileset( + tilesetFiles[listBoxTileset.getSelectedItemIndex()]); + } + if (techTreeFiles.empty() == false) { + gameSettings->setTech( + techTreeFiles[listBoxTechTree.getSelectedItemIndex()]); + } + + if (autoStartSettings != NULL) { + gameSettings->setDefaultUnits(autoStartSettings->getDefaultUnits()); + gameSettings->setDefaultResources(autoStartSettings->getDefaultResources()); + gameSettings->setDefaultVictoryConditions( + autoStartSettings->getDefaultVictoryConditions()); + } else if (checkBoxScenario.getValue() == false) { + gameSettings->setDefaultUnits(true); + gameSettings->setDefaultResources(true); + gameSettings->setDefaultVictoryConditions(true); + } + + gameSettings->setFogOfWar(listBoxFogOfWar.getSelectedItemIndex() == 0 || + listBoxFogOfWar.getSelectedItemIndex() == 1); + + gameSettings->setAllowObservers(checkBoxAllowObservers.getValue() == 1); + + uint32 valueFlags1 = gameSettings->getFlagTypes1(); + if (listBoxFogOfWar.getSelectedItemIndex() == 1 || + listBoxFogOfWar.getSelectedItemIndex() == 2) { + valueFlags1 |= ft1_show_map_resources; + gameSettings->setFlagTypes1(valueFlags1); + } else { + valueFlags1 &= ~ft1_show_map_resources; + gameSettings->setFlagTypes1(valueFlags1); + } + + // gameSettings->setEnableObserverModeAtEndGame(listBoxEnableObserverMode.getSelectedItemIndex() + // == 0); + gameSettings->setEnableObserverModeAtEndGame(true); + // gameSettings->setPathFinderType(static_cast(listBoxPathFinderType.getSelectedItemIndex())); + + valueFlags1 = gameSettings->getFlagTypes1(); + if (checkBoxEnableSwitchTeamMode.getValue() == true) { + valueFlags1 |= ft1_allow_team_switching; + gameSettings->setFlagTypes1(valueFlags1); + } else { + valueFlags1 &= ~ft1_allow_team_switching; + gameSettings->setFlagTypes1(valueFlags1); + } + gameSettings->setAiAcceptSwitchTeamPercentChance( + strToInt(listBoxAISwitchTeamAcceptPercent.getSelectedItem())); + gameSettings->setFallbackCpuMultiplier( + listBoxFallbackCpuMultiplier.getSelectedItemIndex()); + + if (checkBoxAllowInGameJoinPlayer.getValue() == true) { + valueFlags1 |= ft1_allow_in_game_joining; + gameSettings->setFlagTypes1(valueFlags1); + } else { + valueFlags1 &= ~ft1_allow_in_game_joining; + gameSettings->setFlagTypes1(valueFlags1); + } + + if (checkBoxAllowTeamUnitSharing.getValue() == true) { + valueFlags1 |= ft1_allow_shared_team_units; + gameSettings->setFlagTypes1(valueFlags1); + } else { + valueFlags1 &= ~ft1_allow_shared_team_units; + gameSettings->setFlagTypes1(valueFlags1); + } + + if (checkBoxAllowTeamResourceSharing.getValue() == true) { + valueFlags1 |= ft1_allow_shared_team_resources; + gameSettings->setFlagTypes1(valueFlags1); + } else { + valueFlags1 &= ~ft1_allow_shared_team_resources; + gameSettings->setFlagTypes1(valueFlags1); + } + + if (Config::getInstance().getBool("EnableNetworkGameSynchChecks", "false") == + true) { + // printf("*WARNING* - EnableNetworkGameSynchChecks is enabled\n"); + + valueFlags1 |= ft1_network_synch_checks_verbose; + gameSettings->setFlagTypes1(valueFlags1); + + } else { + valueFlags1 &= ~ft1_network_synch_checks_verbose; + gameSettings->setFlagTypes1(valueFlags1); + } + if (Config::getInstance().getBool("EnableNetworkGameSynchMonitor", "false") == + true) { + // printf("*WARNING* - EnableNetworkGameSynchChecks is enabled\n"); + + valueFlags1 |= ft1_network_synch_checks; + gameSettings->setFlagTypes1(valueFlags1); + + } else { + valueFlags1 &= ~ft1_network_synch_checks; + gameSettings->setFlagTypes1(valueFlags1); + } + + gameSettings->setNetworkAllowNativeLanguageTechtree( + checkBoxAllowNativeLanguageTechtree.getValue()); + + // First save Used slots + // for(int i=0; iheadlessServerMode == true) { + // switch slot to network, because no human in headless mode + listBoxControls[i].setSelectedItemIndex(ctNetwork); + updateResourceMultiplier(i); + } - checkBoxAllowNativeLanguageTechtree.setValue(gameSettings.getNetworkAllowNativeLanguageTechtree()); + ControlType ct = + static_cast(listBoxControls[i].getSelectedItemIndex()); - //listBoxPathFinderType.setSelectedItemIndex(gameSettings.getPathFinderType()); + if (forceCloseUnusedSlots == true && + (ct == ctNetworkUnassigned || ct == ctNetwork)) { + if (serverInterface != NULL && + (serverInterface->getSlot(i, true) == NULL || + serverInterface->getSlot(i, true)->isConnected() == false)) { + if (checkBoxScenario.getValue() == false) { + // printf("Closed A [%d] + // [%s]\n",i,labelPlayerNames[i].getText().c_str()); - //listBoxEnableServerControlledAI.setSelectedItem(gameSettings.getEnableServerControlledAI() == true ? lang.getString("Yes") : lang.getString("No")); + listBoxControls[i].setSelectedItemIndex(ctClosed); + ct = ctClosed; + } + } + } else if (ct == ctNetworkUnassigned && i < mapInfo.players) { + listBoxControls[i].setSelectedItemIndex(ctNetwork); + ct = ctNetwork; + } - //labelNetworkFramePeriod.setText(lang.getString("NetworkFramePeriod")); + if (ct != ctClosed) { + int slotIndex = factionCount; + gameSettings->setFactionControl(slotIndex, ct); + if (ct == ctHuman) { + 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()); + + gameSettings->setThisFactionIndex(slotIndex); + gameSettings->setNetworkPlayerName(slotIndex, getHumanPlayerName(i)); + gameSettings->setNetworkPlayerUUID( + slotIndex, Config::getInstance().getString("PlayerId", "")); + gameSettings->setNetworkPlayerPlatform(slotIndex, + getPlatformNameString()); + gameSettings->setNetworkPlayerStatuses(slotIndex, + getNetworkPlayerStatus()); + Lang &lang = Lang::getInstance(); + gameSettings->setNetworkPlayerLanguages(slotIndex, lang.getLanguage()); + } else if (serverInterface != NULL && + serverInterface->getSlot(i, true) != NULL) { + gameSettings->setNetworkPlayerLanguages( + slotIndex, + serverInterface->getSlot(i, true)->getNetworkPlayerLanguage()); + } + + // if(slotIndex == 0) printf("slotIndex = %d, i = %d, multiplier = + // %d\n",slotIndex,i,listBoxRMultiplier[i].getSelectedItemIndex()); + + // printf("Line: %d multiplier index: %d slotIndex: + // %d\n",__LINE__,listBoxRMultiplier[i].getSelectedItemIndex(),slotIndex); + gameSettings->setResourceMultiplierIndex( + slotIndex, listBoxRMultiplier[i].getSelectedItemIndex()); + // printf("Line: %d multiplier index: %d slotIndex: + // %d\n",__LINE__,gameSettings->getResourceMultiplierIndex(slotIndex),slotIndex); + + 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()); + + gameSettings->setFactionTypeName( + slotIndex, factionFiles[listBoxFactions[i].getSelectedItemIndex()]); + if (factionFiles[listBoxFactions[i].getSelectedItemIndex()] == + formatString(GameConstants::OBSERVER_SLOTNAME)) { + listBoxTeams[i].setSelectedItem( + intToStr(GameConstants::maxPlayers + fpt_Observer)); + } else if (listBoxTeams[i].getSelectedItem() == + intToStr(GameConstants::maxPlayers + fpt_Observer)) { + + // printf("Line: %d lastSelectedTeamIndex[i] = %d + // \n",__LINE__,lastSelectedTeamIndex[i]); + + if ((listBoxControls[i].getSelectedItemIndex() == ctCpuEasy || + listBoxControls[i].getSelectedItemIndex() == ctCpu || + listBoxControls[i].getSelectedItemIndex() == ctCpuUltra || + listBoxControls[i].getSelectedItemIndex() == ctCpuMega) && + checkBoxScenario.getValue() == true) { + + } else { + if (lastSelectedTeamIndex[i] >= 0 && + lastSelectedTeamIndex[i] + 1 != + (GameConstants::maxPlayers + fpt_Observer)) { + if (lastSelectedTeamIndex[i] == 0) { + lastSelectedTeamIndex[i] = GameConstants::maxPlayers - 1; + } else if (lastSelectedTeamIndex[i] == + GameConstants::maxPlayers - 1) { + lastSelectedTeamIndex[i] = 0; + } - //listBoxNetworkFramePeriod.setSelectedItem(intToStr(gameSettings.getNetworkFramePeriod()/10*10)); + listBoxTeams[i].setSelectedItemIndex(lastSelectedTeamIndex[i]); + } else { + listBoxTeams[i].setSelectedItem(intToStr(1)); + } + } + } + + gameSettings->setTeam(slotIndex, listBoxTeams[i].getSelectedItemIndex()); + gameSettings->setStartLocationIndex(slotIndex, i); + + if (listBoxControls[i].getSelectedItemIndex() == ctNetwork || + listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) { + if (serverInterface != NULL && + serverInterface->getSlot(i, true) != NULL && + serverInterface->getSlot(i, true)->isConnected()) { + + gameSettings->setNetworkPlayerStatuses( + slotIndex, + serverInterface->getSlot(i, true)->getNetworkPlayerStatus()); + + 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()); + + gameSettings->setNetworkPlayerName( + slotIndex, serverInterface->getSlot(i, true)->getName()); + gameSettings->setNetworkPlayerUUID( + i, serverInterface->getSlot(i, true)->getUUID()); + gameSettings->setNetworkPlayerPlatform( + i, serverInterface->getSlot(i, true)->getPlatform()); + labelPlayerNames[i].setText( + serverInterface->getSlot(i, true)->getName()); + } else { + 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); + + gameSettings->setNetworkPlayerName( + slotIndex, GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME); + labelPlayerNames[i].setText(""); + } + } else if (listBoxControls[i].getSelectedItemIndex() != ctHuman) { + AIPlayerCount++; + 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); + + Lang &lang = Lang::getInstance(); + gameSettings->setNetworkPlayerName( + slotIndex, lang.getString("AI") + intToStr(AIPlayerCount)); + labelPlayerNames[i].setText(""); + } + if (listBoxControls[i].getSelectedItemIndex() == ctHuman) { + setSlotHuman(i); + } + if (serverInterface != NULL && + serverInterface->getSlot(i, true) != NULL) { + gameSettings->setNetworkPlayerUUID( + slotIndex, serverInterface->getSlot(i, true)->getUUID()); + gameSettings->setNetworkPlayerPlatform( + slotIndex, serverInterface->getSlot(i, true)->getPlatform()); + } + + factionCount++; + } else { + // gameSettings->setNetworkPlayerName(""); + gameSettings->setNetworkPlayerStatuses(factionCount, npst_None); + labelPlayerNames[i].setText(""); + } + } + + // Next save closed slots + int closedCount = 0; + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + ControlType ct = + static_cast(listBoxControls[i].getSelectedItemIndex()); + if (ct == ctClosed) { + int slotIndex = factionCount + closedCount; + + gameSettings->setFactionControl(slotIndex, ct); + gameSettings->setTeam(slotIndex, listBoxTeams[i].getSelectedItemIndex()); + gameSettings->setStartLocationIndex(slotIndex, i); + // gameSettings->setResourceMultiplierIndex(slotIndex, 10); + listBoxRMultiplier[i].setSelectedItem("1.0"); + gameSettings->setResourceMultiplierIndex( + slotIndex, listBoxRMultiplier[i].getSelectedItemIndex()); + // printf("Test multiplier = + // %s\n",listBoxRMultiplier[i].getSelectedItem().c_str()); + + 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()); + + gameSettings->setFactionTypeName( + slotIndex, factionFiles[listBoxFactions[i].getSelectedItemIndex()]); + gameSettings->setNetworkPlayerName( + slotIndex, GameConstants::NETWORK_SLOT_CLOSED_SLOTNAME); + gameSettings->setNetworkPlayerUUID(slotIndex, ""); + gameSettings->setNetworkPlayerPlatform(slotIndex, ""); + + closedCount++; + } + } + + gameSettings->setFactionCount(factionCount); + + Config &config = Config::getInstance(); + gameSettings->setEnableServerControlledAI( + config.getBool("ServerControlledAI", "true")); + gameSettings->setNetworkFramePeriod( + config.getInt("NetworkSendFrameCount", "20")); + gameSettings->setNetworkPauseGameForLaggedClients( + ((checkBoxNetworkPauseGameForLaggedClients.getValue() == true))); + + setCRCsToGameSettings(gameSettings); + + if (this->headlessServerMode == true) { + time_t clientConnectedTime = 0; + bool masterserver_admin_found = false; + // printf("mapInfo.players [%d]\n",mapInfo.players); + + for (int i = 0; i < mapInfo.players; ++i) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (listBoxControls[i].getSelectedItemIndex() == ctNetwork || + listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + if (serverInterface->getSlot(i, true) != NULL && + serverInterface->getSlot(i, true)->isConnected()) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + // printf("slot = %d serverInterface->getSlot(i)->getConnectedTime() = + // %d session key + // [%d]\n",i,serverInterface->getSlot(i)->getConnectedTime(),serverInterface->getSlot(i)->getSessionKey()); + + if (clientConnectedTime == 0 || + (serverInterface->getSlot(i, true)->getConnectedTime() > 0 && + serverInterface->getSlot(i, true)->getConnectedTime() < + clientConnectedTime)) { + clientConnectedTime = + serverInterface->getSlot(i, true)->getConnectedTime(); + gameSettings->setMasterserver_admin( + serverInterface->getSlot(i, true)->getSessionKey()); + gameSettings->setMasterserver_admin_faction_index( + serverInterface->getSlot(i, true)->getPlayerIndex()); + labelGameName.setText( + createGameName(serverInterface->getSlot(i, true)->getName())); + // 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); + } + if (serverInterface->getSlot(i, true)->getSessionKey() == + gameSettings->getMasterserver_admin()) { + masterserver_admin_found = true; + } + } + } + } + if (masterserver_admin_found == false) { + for (int i = mapInfo.players; i < GameConstants::maxPlayers; ++i) { + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + // ConnectionSlot *slot = serverInterface->getSlot(i); + + if (serverInterface->getSlot(i, true) != NULL && + serverInterface->getSlot(i, true)->isConnected()) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + // printf("slot = %d serverInterface->getSlot(i)->getConnectedTime() = + // %d session key + // [%d]\n",i,serverInterface->getSlot(i)->getConnectedTime(),serverInterface->getSlot(i)->getSessionKey()); + + if (clientConnectedTime == 0 || + (serverInterface->getSlot(i, true)->getConnectedTime() > 0 && + serverInterface->getSlot(i, true)->getConnectedTime() < + clientConnectedTime)) { + clientConnectedTime = + serverInterface->getSlot(i, true)->getConnectedTime(); + gameSettings->setMasterserver_admin( + serverInterface->getSlot(i, true)->getSessionKey()); + gameSettings->setMasterserver_admin_faction_index( + serverInterface->getSlot(i, true)->getPlayerIndex()); + labelGameName.setText( + createGameName(serverInterface->getSlot(i, true)->getName())); + // 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); + } + if (serverInterface->getSlot(i, true)->getSessionKey() == + gameSettings->getMasterserver_admin()) { + masterserver_admin_found = true; + } + } + } + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (masterserver_admin_found == false) { + labelGameName.setText(createGameName()); + } + } - checkBoxNetworkPauseGameForLaggedClients.setValue(gameSettings.getNetworkPauseGameForLaggedClients()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); +} - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void MenuStateCustomGame::KeepCurrentHumanPlayerSlots( + GameSettings &gameSettings) { + // look for human players + bool foundValidHumanControlTypeInFile = false; + for (int index2 = 0; index2 < GameConstants::maxPlayers; ++index2) { + ControlType ctFile = + static_cast(gameSettings.getFactionControl(index2)); + if (ctFile == ctHuman) { + ControlType ctUI = static_cast( + listBoxControls[index2].getSelectedItemIndex()); + if (ctUI != ctNetwork && ctUI != ctNetworkUnassigned) { + foundValidHumanControlTypeInFile = true; + // printf("Human found in file [%d]\n",index2); + } else if (labelPlayerNames[index2].getText() == "") { + foundValidHumanControlTypeInFile = true; + } + } + } + + for (int index = 0; index < GameConstants::maxPlayers; ++index) { + ControlType ct = + static_cast(listBoxControls[index].getSelectedItemIndex()); + if (ct == ctHuman) { + // printf("Human found in UI [%d] and file + // [%d]\n",index,foundControlType); + + if (foundValidHumanControlTypeInFile == false) { + gameSettings.setFactionControl(index, ctHuman); + gameSettings.setNetworkPlayerName(index, getHumanPlayerName()); + } + } - reloadFactions(false,(checkBoxScenario.getValue() == true ? scenarioFiles[listBoxScenario.getSelectedItemIndex()] : "")); - //reloadFactions(true); + ControlType ctFile = + static_cast(gameSettings.getFactionControl(index)); + if (ctFile == ctHuman) { + gameSettings.setFactionControl(index, ctHuman); + } + } +} - 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()); +void MenuStateCustomGame::saveGameSettings(std::string fileName) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + GameSettings gameSettings; + copyToGameSettings(&gameSettings); + CoreData::getInstance().saveGameSettingsToFile(fileName, &gameSettings, + checkBoxAdvanced.getValue()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); +} - for(int i = 0; i < GameConstants::maxPlayers; ++i) { - int slotIndex = gameSettings.getStartLocationIndex(i); - if(gameSettings.getFactionControl(i) < listBoxControls[slotIndex].getItemCount()) { - listBoxControls[slotIndex].setSelectedItemIndex(gameSettings.getFactionControl(i)); - } +bool MenuStateCustomGame::loadGameSettingsFromFile(GameSettings *gameSettings, + std::string fileName) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + GameSettings originalGameSettings; + copyToGameSettings(&originalGameSettings); + + try { + bool loadSuccessful = CoreData::getInstance().loadGameSettingsFromFile( + fileName, gameSettings); + if (!loadSuccessful) { + console.addLine("Cannot load '" + fileName + "'"); + // do nothing on failure + return false; + } + KeepCurrentHumanPlayerSlots(*gameSettings); - //if(slotIndex == 0) printf("#2 slotIndex = %d, i = %d, multiplier = %d\n",slotIndex,i,listBoxRMultiplier[i].getSelectedItemIndex()); + // correct game settings for headless: + if (this->headlessServerMode == true) { + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + if (gameSettings->getFactionControl(i) == ctHuman) { + gameSettings->setFactionControl(i, ctNetwork); + } + } + } - updateResourceMultiplier(slotIndex); + vector mapsV = playerSortedMaps[0]; + if (std::find(mapsV.begin(), mapsV.end(), gameSettings->getMap()) == + mapsV.end()) { + console.addLine("Cannot load '" + fileName + "', map unknown ('" + + gameSettings->getMap() + "')"); + return false; // map unknown + } + if (std::find(tilesetFiles.begin(), tilesetFiles.end(), + gameSettings->getTileset()) == tilesetFiles.end()) { + console.addLine("Cannot load '" + fileName + "', tileset unknown ('" + + gameSettings->getTileset() + "')"); + return false; // tileset unknown + } + if (std::find(techTreeFiles.begin(), techTreeFiles.end(), + gameSettings->getTech()) == techTreeFiles.end()) { + console.addLine("Cannot load '" + fileName + "', techtree unknown ('" + + gameSettings->getTech() + "')"); + return false; // techtree unknown + } - //if(slotIndex == 0) printf("#3 slotIndex = %d, i = %d, multiplier = %d\n",slotIndex,i,listBoxRMultiplier[i].getSelectedItemIndex()); + setupUIFromGameSettings(*gameSettings); + } catch (const exception &ex) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + 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()); + + showMessageBox(ex.what(), "Error", false); + + setupUIFromGameSettings(originalGameSettings); + *gameSettings = originalGameSettings; + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + return true; +} - listBoxRMultiplier[slotIndex].setSelectedItemIndex(gameSettings.getResourceMultiplierIndex(i)); +void MenuStateCustomGame::setupUIFromGameSettings( + const GameSettings &gameSettings) { + string humanPlayerName = getHumanPlayerName(); + + string scenarioDir = ""; + checkBoxScenario.setValue((gameSettings.getScenario() != "")); + if (checkBoxScenario.getValue() == true) { + listBoxScenario.setSelectedItem(formatString(gameSettings.getScenario())); + + loadScenarioInfo( + Scenario::getScenarioPath( + dirList, scenarioFiles[listBoxScenario.getSelectedItemIndex()]), + &scenarioInfo); + scenarioDir = Scenario::getScenarioDir(dirList, gameSettings.getScenario()); + + // printf("scenarioInfo.fogOfWar = %d scenarioInfo.fogOfWar_exploredFlag = + // %d\n",scenarioInfo.fogOfWar,scenarioInfo.fogOfWar_exploredFlag); + if (scenarioInfo.fogOfWar == false && + scenarioInfo.fogOfWar_exploredFlag == false) { + listBoxFogOfWar.setSelectedItemIndex(2); + } else if (scenarioInfo.fogOfWar_exploredFlag == true) { + listBoxFogOfWar.setSelectedItemIndex(1); + } else { + listBoxFogOfWar.setSelectedItemIndex(0); + } + checkBoxAllowTeamUnitSharing.setValue(scenarioInfo.allowTeamUnitSharing); + checkBoxAllowTeamResourceSharing.setValue( + scenarioInfo.allowTeamResourceSharing); + } + setupMapList(gameSettings.getScenario()); + setupTechList(gameSettings.getScenario(), false); + setupTilesetList(gameSettings.getScenario()); + + if (checkBoxScenario.getValue() == true) { + // string file = Scenario::getScenarioPath(dirList, + // gameSettings.getScenario()); loadScenarioInfo(file, &scenarioInfo); + + // printf("#6.1 about to load map [%s]\n",scenarioInfo.mapName.c_str()); + // loadMapInfo(Config::getMapPath(scenarioInfo.mapName, scenarioDir, true), + // &mapInfo, false); printf("#6.2\n"); + + listBoxMapFilter.setSelectedItemIndex(0); + comboBoxMap.setItems(formattedPlayerSortedMaps[mapInfo.players]); + comboBoxMap.setSelectedItem(formatString(scenarioInfo.mapName)); + } else { + // printf("gameSettings.getMapFilter()=%d \n",gameSettings.getMapFilter()); + if (gameSettings.getMapFilter() == 0) { + listBoxMapFilter.setSelectedItemIndex(0); + } else { + listBoxMapFilter.setSelectedItem(intToStr(gameSettings.getMapFilter())); + } + comboBoxMap.setItems( + formattedPlayerSortedMaps[gameSettings.getMapFilter()]); + } + + // printf("gameSettings.getMap() [%s] + // [%s]\n",gameSettings.getMap().c_str(),listBoxMap.getSelectedItem().c_str()); + + string mapFile = gameSettings.getMap(); + if (find(mapFiles.begin(), mapFiles.end(), mapFile) != mapFiles.end()) { + mapFile = formatString(mapFile); + comboBoxMap.setSelectedItem(mapFile); + + loadMapInfo(Config::getMapPath(getCurrentMapFile(), scenarioDir, true), + &mapInfo, true, true); + labelMapInfo.setText(mapInfo.desc); + } + + string tilesetFile = gameSettings.getTileset(); + if (find(tilesetFiles.begin(), tilesetFiles.end(), tilesetFile) != + tilesetFiles.end()) { + tilesetFile = formatString(tilesetFile); + listBoxTileset.setSelectedItem(tilesetFile); + } + + string techtreeFile = gameSettings.getTech(); + if (find(techTreeFiles.begin(), techTreeFiles.end(), techtreeFile) != + techTreeFiles.end()) { + techtreeFile = formatString(techtreeFile); + listBoxTechTree.setSelectedItem(techtreeFile); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // gameSettings->setDefaultUnits(true); + // gameSettings->setDefaultResources(true); + // gameSettings->setDefaultVictoryConditions(true); + + // FogOfWar + if (checkBoxScenario.getValue() == false) { + listBoxFogOfWar.setSelectedItemIndex(0); // default is 0! + if (gameSettings.getFogOfWar() == false) { + listBoxFogOfWar.setSelectedItemIndex(2); + } - //if(slotIndex == 0) printf("#4 slotIndex = %d, i = %d, multiplier = %d\n",slotIndex,i,listBoxRMultiplier[i].getSelectedItemIndex()); + if ((gameSettings.getFlagTypes1() & ft1_show_map_resources) == + ft1_show_map_resources) { + if (gameSettings.getFogOfWar() == true) { + listBoxFogOfWar.setSelectedItemIndex(1); + } + } + } + + // printf("In [%s::%s line + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + checkBoxAllowObservers.setValue( + gameSettings.getAllowObservers() == true ? true : false); + // listBoxEnableObserverMode.setSelectedItem(gameSettings.getEnableObserverModeAtEndGame() + // == true ? lang.getString("Yes") : lang.getString("No")); + + checkBoxEnableSwitchTeamMode.setValue( + (gameSettings.getFlagTypes1() & ft1_allow_team_switching) == + ft1_allow_team_switching + ? true + : false); + listBoxAISwitchTeamAcceptPercent.setSelectedItem( + intToStr(gameSettings.getAiAcceptSwitchTeamPercentChance())); + listBoxFallbackCpuMultiplier.setSelectedItemIndex( + gameSettings.getFallbackCpuMultiplier()); + + checkBoxAllowInGameJoinPlayer.setValue( + (gameSettings.getFlagTypes1() & ft1_allow_in_game_joining) == + ft1_allow_in_game_joining + ? true + : false); + + checkBoxAllowTeamUnitSharing.setValue( + (gameSettings.getFlagTypes1() & ft1_allow_shared_team_units) == + ft1_allow_shared_team_units + ? true + : false); + checkBoxAllowTeamResourceSharing.setValue( + (gameSettings.getFlagTypes1() & ft1_allow_shared_team_resources) == + ft1_allow_shared_team_resources + ? true + : false); + + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + if (serverInterface != NULL) { + serverInterface->setAllowInGameConnections( + checkBoxAllowInGameJoinPlayer.getValue() == true); + } + + checkBoxAllowNativeLanguageTechtree.setValue( + gameSettings.getNetworkAllowNativeLanguageTechtree()); + + // listBoxPathFinderType.setSelectedItemIndex(gameSettings.getPathFinderType()); + + // listBoxEnableServerControlledAI.setSelectedItem(gameSettings.getEnableServerControlledAI() + // == true ? lang.getString("Yes") : lang.getString("No")); + + // labelNetworkFramePeriod.setText(lang.getString("NetworkFramePeriod")); + + // listBoxNetworkFramePeriod.setSelectedItem(intToStr(gameSettings.getNetworkFramePeriod()/10*10)); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + checkBoxNetworkPauseGameForLaggedClients.setValue( + gameSettings.getNetworkPauseGameForLaggedClients()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + reloadFactions(false, + (checkBoxScenario.getValue() == true + ? scenarioFiles[listBoxScenario.getSelectedItemIndex()] + : "")); + // reloadFactions(true); + + 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()); + + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + int slotIndex = gameSettings.getStartLocationIndex(i); + if (gameSettings.getFactionControl(i) < + listBoxControls[slotIndex].getItemCount()) { + listBoxControls[slotIndex].setSelectedItemIndex( + gameSettings.getFactionControl(i)); + } - listBoxTeams[slotIndex].setSelectedItemIndex(gameSettings.getTeam(i)); + // if(slotIndex == 0) printf("#2 slotIndex = %d, i = %d, multiplier = + // %d\n",slotIndex,i,listBoxRMultiplier[i].getSelectedItemIndex()); - lastSelectedTeamIndex[slotIndex] = listBoxTeams[slotIndex].getSelectedItemIndex(); + updateResourceMultiplier(slotIndex); - string factionName = gameSettings.getFactionTypeName(i); - factionName = formatString(factionName); + // if(slotIndex == 0) printf("#3 slotIndex = %d, i = %d, multiplier = + // %d\n",slotIndex,i,listBoxRMultiplier[i].getSelectedItemIndex()); - //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()); + listBoxRMultiplier[slotIndex].setSelectedItemIndex( + gameSettings.getResourceMultiplierIndex(i)); - 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()); + // if(slotIndex == 0) printf("#4 slotIndex = %d, i = %d, multiplier = + // %d\n",slotIndex,i,listBoxRMultiplier[i].getSelectedItemIndex()); - if(listBoxFactions[slotIndex].hasItem(factionName) == true) { - listBoxFactions[slotIndex].setSelectedItem(factionName); - } - else { - listBoxFactions[slotIndex].setSelectedItem(formatString(GameConstants::RANDOMFACTION_SLOTNAME)); - } + listBoxTeams[slotIndex].setSelectedItemIndex(gameSettings.getTeam(i)); - 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()); + lastSelectedTeamIndex[slotIndex] = + listBoxTeams[slotIndex].getSelectedItemIndex(); - //labelPlayerNames[slotIndex].setText(gameSettings.getNetworkPlayerName(i)); - } + string factionName = gameSettings.getFactionTypeName(i); + factionName = formatString(factionName); - //SetActivePlayerNameEditor(); + // 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()); - updateControlers(); - updateNetworkSlots(); + 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()); - if(this->headlessServerMode == false && humanPlayerName != "") { - for(int index = 0; index < GameConstants::maxPlayers; ++index) { - ControlType ct= static_cast(listBoxControls[index].getSelectedItemIndex()); - if(ct == ctHuman) { - if(humanPlayerName != labelPlayerNames[index].getText()) { - //printf("Player name changing from [%s] to [%s]\n",labelPlayerNames[index].getText().c_str(),humanPlayerName.c_str()); + if (listBoxFactions[slotIndex].hasItem(factionName) == true) { + listBoxFactions[slotIndex].setSelectedItem(factionName); + } else { + listBoxFactions[slotIndex].setSelectedItem( + formatString(GameConstants::RANDOMFACTION_SLOTNAME)); + } - labelPlayerNames[index].setText(""); - labelPlayerNames[index].setText(humanPlayerName); - } - } - } - } + 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()); + + // labelPlayerNames[slotIndex].setText(gameSettings.getNetworkPlayerName(i)); + } + + // SetActivePlayerNameEditor(); + + updateControlers(); + updateNetworkSlots(); + + if (this->headlessServerMode == false && humanPlayerName != "") { + for (int index = 0; index < GameConstants::maxPlayers; ++index) { + ControlType ct = static_cast( + listBoxControls[index].getSelectedItemIndex()); + if (ct == ctHuman) { + if (humanPlayerName != labelPlayerNames[index].getText()) { + // printf("Player name changing from [%s] to + // [%s]\n",labelPlayerNames[index].getText().c_str(),humanPlayerName.c_str()); + + labelPlayerNames[index].setText(""); + labelPlayerNames[index].setText(humanPlayerName); + } + } + } + } - if(hasNetworkGameSettings() == true) { - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); - } + if (hasNetworkGameSettings() == true) { + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + } } // ============ PRIVATE =========================== -void MenuStateCustomGame::setRefreshedCrcToGameSettings(GameSettings *gameSettings){ - Config &config = Config::getInstance(); - bool forceRefresh=false; - - if( gameSettings->getTileset() != "" && lastRecalculatedCRCTilesetName != gameSettings->getTileset() ) { - lastRecalculatedCRCTilesetName=gameSettings->getTileset() ; - // Check if we have calculated the crc since menu_state started - time_t lastUpdateDate = getFolderTreeContentsCheckSumRecursivelyLastGenerated(config.getPathListForType(ptTilesets,""), string("/") + gameSettings->getTileset() + string("/*"), ".xml"); - if(difftime(lastUpdateDate,initTime) <0 ) { - forceRefresh=true; - } - } - - if(gameSettings->getTech() != "" && lastRecalculatedCRCTechtreeName != gameSettings->getTech()) { - lastRecalculatedCRCTechtreeName=gameSettings->getTech(); - // Check if we have calculated the crc since menu_state started - time_t lastUpdateDate = getFolderTreeContentsCheckSumRecursivelyLastGenerated(config.getPathListForType(ptTechs,""), "/" + gameSettings->getTech() + "/*", ".xml"); - if(difftime(lastUpdateDate,initTime) <0 ) { - forceRefresh=true; - } - } - // no need to deal with map CRC this is always calculated - - //if( forceRefresh) console.addLine("forced refresh CRCCache"); - setCRCsToSettingsInternal( gameSettings,forceRefresh); +void MenuStateCustomGame::setRefreshedCrcToGameSettings( + GameSettings *gameSettings) { + Config &config = Config::getInstance(); + bool forceRefresh = false; + + if (gameSettings->getTileset() != "" && + lastRecalculatedCRCTilesetName != gameSettings->getTileset()) { + lastRecalculatedCRCTilesetName = gameSettings->getTileset(); + // Check if we have calculated the crc since menu_state started + time_t lastUpdateDate = + getFolderTreeContentsCheckSumRecursivelyLastGenerated( + config.getPathListForType(ptTilesets, ""), + string("/") + gameSettings->getTileset() + string("/*"), ".xml"); + if (difftime(lastUpdateDate, initTime) < 0) { + forceRefresh = true; + } + } + + if (gameSettings->getTech() != "" && + lastRecalculatedCRCTechtreeName != gameSettings->getTech()) { + lastRecalculatedCRCTechtreeName = gameSettings->getTech(); + // Check if we have calculated the crc since menu_state started + time_t lastUpdateDate = + getFolderTreeContentsCheckSumRecursivelyLastGenerated( + config.getPathListForType(ptTechs, ""), + "/" + gameSettings->getTech() + "/*", ".xml"); + if (difftime(lastUpdateDate, initTime) < 0) { + forceRefresh = true; + } + } + // no need to deal with map CRC this is always calculated + + // if( forceRefresh) console.addLine("forced refresh CRCCache"); + setCRCsToSettingsInternal(gameSettings, forceRefresh); } -void MenuStateCustomGame::setCRCsToGameSettings(GameSettings *gameSettings) -{ - //printf("lastTechtreeChange=%f\n",difftime(time(NULL),lastTechtreeChange) ); - if(lastCheckedCRCTechtreeName != gameSettings->getTech()) { - lastTechtreeChange= time(NULL); // now - } - - if(this->headlessServerMode == false && difftime(time(NULL),lastTechtreeChange) >5 && hasNetworkGameSettings()) { - // try a forced CRC recalculation if game settings stay the same for 5 seconds. - // it will only recalculted CRC if it was not already done since program start. - setRefreshedCrcToGameSettings(gameSettings); - } - else { - setCRCsToSettingsInternal(gameSettings,false); - } +void MenuStateCustomGame::setCRCsToGameSettings(GameSettings *gameSettings) { + // printf("lastTechtreeChange=%f\n",difftime(time(NULL),lastTechtreeChange) ); + if (lastCheckedCRCTechtreeName != gameSettings->getTech()) { + lastTechtreeChange = time(NULL); // now + } + + if (this->headlessServerMode == false && + difftime(time(NULL), lastTechtreeChange) > 5 && + hasNetworkGameSettings()) { + // try a forced CRC recalculation if game settings stay the same for 5 + // seconds. it will only recalculted CRC if it was not already done since + // program start. + setRefreshedCrcToGameSettings(gameSettings); + } else { + setCRCsToSettingsInternal(gameSettings, false); + } } -void MenuStateCustomGame::setCRCsToSettingsInternal(GameSettings *gameSettings, bool forceRefresh){ - Config &config = Config::getInstance(); - if( forceRefresh ==true ){ - lastCheckedCRCTilesetName=""; - lastCheckedCRCTechtreeName=""; - } - - if( gameSettings->getTileset() != "") { - if(lastCheckedCRCTilesetName != gameSettings->getTileset()) { - //console.addLine("Checking tileset CRC [" + gameSettings->getTileset() + "]"); - lastCheckedCRCTilesetValue = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTilesets,""), string("/") + gameSettings->getTileset() + string("/*"), ".xml", NULL,forceRefresh); - lastCheckedCRCTilesetName = gameSettings->getTileset(); - } - gameSettings->setTilesetCRC(lastCheckedCRCTilesetValue); - } - - if(config.getBool("DisableServerLobbyTechtreeCRCCheck","false") == false) { - if(gameSettings->getTech() != "") { - if(lastCheckedCRCTechtreeName != gameSettings->getTech()) { - //console.addLine("Checking techtree CRC [" + gameSettings->getTech() + "]"); - uint32 oldCRC=0; - if( forceRefresh){ - oldCRC=getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), "/" + gameSettings->getTech() + "/*", ".xml", NULL,false); - } - lastCheckedCRCTechtreeValue = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), "/" + gameSettings->getTech() + "/*", ".xml", NULL,forceRefresh); - if( forceRefresh && lastCheckedCRCTechtreeValue!=oldCRC){ - // we really had a bad CRC before! - console.addLine("techtree CRC fixed!"); - } - reloadFactions(true,(checkBoxScenario.getValue() == true ? scenarioFiles[listBoxScenario.getSelectedItemIndex()] : "")); - factionCRCList.clear(); - for(unsigned int factionIdx = 0; factionIdx < factionFiles.size(); ++factionIdx) { - string factionName = factionFiles[factionIdx]; - if(factionName != GameConstants::RANDOMFACTION_SLOTNAME && - factionName != GameConstants::OBSERVER_SLOTNAME) { - //factionCRC = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), "/" + gameSettings->getTech() + "/factions/" + factionName + "/*", ".xml", NULL, true); - uint32 factionCRC = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), "/" + gameSettings->getTech() + "/factions/" + factionName + "/*", ".xml", NULL,forceRefresh); - factionCRCList.push_back(make_pair(factionName,factionCRC)); - } - } - //console.addLine("Found factions: " + intToStr(factionCRCList.size())); - lastCheckedCRCTechtreeName = gameSettings->getTech(); - } - - gameSettings->setFactionCRCList(factionCRCList); - gameSettings->setTechCRC(lastCheckedCRCTechtreeValue); - } - } - - if(gameSettings->getMap() != "") { - if(lastCheckedCRCMapName != gameSettings->getMap()) { - Checksum checksum; - string file = Config::getMapPath(gameSettings->getMap(),"",false); - //console.addLine("Checking map CRC [" + file + "]"); - checksum.addFile(file); - lastCheckedCRCMapValue = checksum.getSum(); - lastCheckedCRCMapName = gameSettings->getMap(); - } - gameSettings->setMapCRC(lastCheckedCRCMapValue); - } +void MenuStateCustomGame::setCRCsToSettingsInternal(GameSettings *gameSettings, + bool forceRefresh) { + Config &config = Config::getInstance(); + if (forceRefresh == true) { + lastCheckedCRCTilesetName = ""; + lastCheckedCRCTechtreeName = ""; + } + + if (gameSettings->getTileset() != "") { + if (lastCheckedCRCTilesetName != gameSettings->getTileset()) { + // console.addLine("Checking tileset CRC [" + gameSettings->getTileset() + + // "]"); + lastCheckedCRCTilesetValue = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTilesets, ""), + string("/") + gameSettings->getTileset() + string("/*"), ".xml", NULL, + forceRefresh); + lastCheckedCRCTilesetName = gameSettings->getTileset(); + } + gameSettings->setTilesetCRC(lastCheckedCRCTilesetValue); + } + + if (config.getBool("DisableServerLobbyTechtreeCRCCheck", "false") == false) { + if (gameSettings->getTech() != "") { + if (lastCheckedCRCTechtreeName != gameSettings->getTech()) { + // console.addLine("Checking techtree CRC [" + gameSettings->getTech() + + // "]"); + uint32 oldCRC = 0; + if (forceRefresh) { + oldCRC = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTechs, ""), + "/" + gameSettings->getTech() + "/*", ".xml", NULL, false); + } + lastCheckedCRCTechtreeValue = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTechs, ""), + "/" + gameSettings->getTech() + "/*", ".xml", NULL, forceRefresh); + if (forceRefresh && lastCheckedCRCTechtreeValue != oldCRC) { + // we really had a bad CRC before! + console.addLine("techtree CRC fixed!"); + } + reloadFactions( + true, (checkBoxScenario.getValue() == true + ? scenarioFiles[listBoxScenario.getSelectedItemIndex()] + : "")); + factionCRCList.clear(); + for (unsigned int factionIdx = 0; factionIdx < factionFiles.size(); + ++factionIdx) { + string factionName = factionFiles[factionIdx]; + if (factionName != GameConstants::RANDOMFACTION_SLOTNAME && + factionName != GameConstants::OBSERVER_SLOTNAME) { + // factionCRC = + // getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), + // "/" + gameSettings->getTech() + "/factions/" + factionName + + // "/*", ".xml", NULL, true); + uint32 factionCRC = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTechs, ""), + "/" + gameSettings->getTech() + "/factions/" + factionName + + "/*", + ".xml", NULL, forceRefresh); + factionCRCList.push_back(make_pair(factionName, factionCRC)); + } + } + // console.addLine("Found factions: " + + // intToStr(factionCRCList.size())); + lastCheckedCRCTechtreeName = gameSettings->getTech(); + } + gameSettings->setFactionCRCList(factionCRCList); + gameSettings->setTechCRC(lastCheckedCRCTechtreeValue); + } + } + + if (gameSettings->getMap() != "") { + if (lastCheckedCRCMapName != gameSettings->getMap()) { + Checksum checksum; + string file = Config::getMapPath(gameSettings->getMap(), "", false); + // console.addLine("Checking map CRC [" + file + "]"); + checksum.addFile(file); + lastCheckedCRCMapValue = checksum.getSum(); + lastCheckedCRCMapName = gameSettings->getMap(); + } + gameSettings->setMapCRC(lastCheckedCRCMapValue); + } } -void MenuStateCustomGame::setSmallFont(GraphicLabel l){ - l.setFont(CoreData::getInstance().getDisplayFontSmall()); - l.setFont3D(CoreData::getInstance().getDisplayFontSmall3D()); +void MenuStateCustomGame::setSmallFont(GraphicLabel l) { + l.setFont(CoreData::getInstance().getDisplayFontSmall()); + l.setFont3D(CoreData::getInstance().getDisplayFontSmall3D()); } void MenuStateCustomGame::lastPlayerDisconnected() { - // this is for headless mode only! - // if last player disconnects we load the network defaults. - if(this->headlessServerMode == false) { - return; - } - - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - bool foundConnectedPlayer=false; - for(int i = 0; i < GameConstants::maxPlayers; ++i) { - if(serverInterface->getSlot(i,true) != NULL && - (listBoxControls[i].getSelectedItemIndex() == ctNetwork || - listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned)) { - if(serverInterface->getSlot(i,true)->isConnected() == true) { - foundConnectedPlayer=true; - } - } - } - - if(!foundConnectedPlayer && headlessHasConnectedPlayer==true ){ - // load defaults - string data_path = getGameReadWritePath(GameConstants::path_data_CacheLookupKey); - if(fileExists(data_path + DEFAULT_NETWORK_SETUP_FILENAME) == true) - loadGameSettings(data_path + DEFAULT_NETWORK_SETUP_FILENAME); - } - headlessHasConnectedPlayer=foundConnectedPlayer; + // this is for headless mode only! + // if last player disconnects we load the network defaults. + if (this->headlessServerMode == false) { + return; + } + + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + bool foundConnectedPlayer = false; + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + if (serverInterface->getSlot(i, true) != NULL && + (listBoxControls[i].getSelectedItemIndex() == ctNetwork || + listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned)) { + if (serverInterface->getSlot(i, true)->isConnected() == true) { + foundConnectedPlayer = true; + } + } + } + + if (!foundConnectedPlayer && headlessHasConnectedPlayer == true) { + // load defaults + string data_path = + getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + if (fileExists(data_path + DEFAULT_NETWORK_SETUP_FILENAME) == true) + loadGameSettings(data_path + DEFAULT_NETWORK_SETUP_FILENAME); + } + headlessHasConnectedPlayer = foundConnectedPlayer; } bool MenuStateCustomGame::hasNetworkGameSettings() { - bool hasNetworkSlot = false; - - try { - for(int i=0; i(listBoxControls[i].getSelectedItemIndex()); - if(ct != ctClosed) { - if(ct == ctNetwork || ct == ctNetworkUnassigned) { - hasNetworkSlot = true; - break; - } - } - } - if(hasNetworkSlot == false) { - for(int i=0; i < GameConstants::maxPlayers; ++i) { - ControlType ct= static_cast(listBoxControls[i].getSelectedItemIndex()); - if(ct != ctClosed) { - if(ct == ctNetworkUnassigned) { - hasNetworkSlot = true; - break; - } - } - } - } - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - - showGeneralError=true; - generalErrorToShow = szBuf; - } - - return hasNetworkSlot; + bool hasNetworkSlot = false; + + try { + for (int i = 0; i < mapInfo.players; ++i) { + ControlType ct = + static_cast(listBoxControls[i].getSelectedItemIndex()); + if (ct != ctClosed) { + if (ct == ctNetwork || ct == ctNetworkUnassigned) { + hasNetworkSlot = true; + break; + } + } + } + if (hasNetworkSlot == false) { + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + ControlType ct = + static_cast(listBoxControls[i].getSelectedItemIndex()); + if (ct != ctClosed) { + if (ct == ctNetworkUnassigned) { + hasNetworkSlot = true; + break; + } + } + } + } + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + showGeneralError = true; + generalErrorToShow = szBuf; + } + + return hasNetworkSlot; } -void MenuStateCustomGame::loadMapInfo(string file, MapInfo *mapInfo, bool loadMapPreview, bool doPlayerSetup) { - try { - Lang &lang= Lang::getInstance(); - if(MapPreview::loadMapInfo(file, mapInfo, lang.getString("MaxPlayers"),lang.getString("Size"),true) == true) { - if (doPlayerSetup) { - ServerInterface* serverInterface = NetworkManager::getInstance().getServerInterface(); - for (int i = 0; i < GameConstants::maxPlayers; ++i) { - if (serverInterface->getSlot(i, true) != NULL - && (listBoxControls[i].getSelectedItemIndex() == ctNetwork || listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned)) { - if (serverInterface->getSlot(i, true)->isConnected() == true) { - if (i + 1 > mapInfo->players && listBoxControls[i].getSelectedItemIndex() != ctNetworkUnassigned) { - listBoxControls[i].setSelectedItemIndex(ctNetworkUnassigned); - } - } - } - - labelPlayers[i].setVisible(i + 1 <= mapInfo->players); - labelPlayerNames[i].setVisible(i + 1 <= mapInfo->players); - listBoxControls[i].setVisible(i + 1 <= mapInfo->players); - listBoxFactions[i].setVisible(i + 1 <= mapInfo->players); - listBoxTeams[i].setVisible(i + 1 <= mapInfo->players); - labelNetStatus[i].setVisible(i + 1 <= mapInfo->players); - } - } - - // Not painting properly so this is on hold - if(loadMapPreview == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - mapPreview.loadFromFile(file.c_str()); - - //printf("Loading map preview MAP\n"); - cleanupMapPreviewTexture(); - } - } - } - catch(exception &e) { - 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()); - throw megaglest_runtime_error("Error loading map file: [" + file + "] msg: " + e.what()); - } +void MenuStateCustomGame::loadMapInfo(string file, MapInfo *mapInfo, + bool loadMapPreview, bool doPlayerSetup) { + try { + Lang &lang = Lang::getInstance(); + if (MapPreview::loadMapInfo(file, mapInfo, lang.getString("MaxPlayers"), + lang.getString("Size"), true) == true) { + if (doPlayerSetup) { + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + if (serverInterface->getSlot(i, true) != NULL && + (listBoxControls[i].getSelectedItemIndex() == ctNetwork || + listBoxControls[i].getSelectedItemIndex() == + ctNetworkUnassigned)) { + if (serverInterface->getSlot(i, true)->isConnected() == true) { + if (i + 1 > mapInfo->players && + listBoxControls[i].getSelectedItemIndex() != + ctNetworkUnassigned) { + listBoxControls[i].setSelectedItemIndex(ctNetworkUnassigned); + } + } + } + + labelPlayers[i].setVisible(i + 1 <= mapInfo->players); + labelPlayerNames[i].setVisible(i + 1 <= mapInfo->players); + listBoxControls[i].setVisible(i + 1 <= mapInfo->players); + listBoxFactions[i].setVisible(i + 1 <= mapInfo->players); + listBoxTeams[i].setVisible(i + 1 <= mapInfo->players); + labelNetStatus[i].setVisible(i + 1 <= mapInfo->players); + } + } + + // Not painting properly so this is on hold + if (loadMapPreview == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + mapPreview.loadFromFile(file.c_str()); + + // printf("Loading map preview MAP\n"); + cleanupMapPreviewTexture(); + } + } + } catch (exception &e) { + 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()); + throw megaglest_runtime_error("Error loading map file: [" + file + + "] msg: " + e.what()); + } } void MenuStateCustomGame::updateControlers() { - try { - bool humanPlayer= false; - - for(int i = 0; i < mapInfo.players; ++i) { - if(listBoxControls[i].getSelectedItemIndex() == ctHuman) { - humanPlayer= true; - } - } - - if(humanPlayer == false) { - if(this->headlessServerMode == false) { - bool foundNewSlotForHuman = false; - for(int i = 0; i < mapInfo.players; ++i) { - if(listBoxControls[i].getSelectedItemIndex() == ctClosed) { - setSlotHuman(i); - foundNewSlotForHuman = true; - break; - } - } - - if(foundNewSlotForHuman == false) { - for(int i = 0; i < mapInfo.players; ++i) { - if(listBoxControls[i].getSelectedItemIndex() == ctClosed || - listBoxControls[i].getSelectedItemIndex() == ctCpuEasy || - listBoxControls[i].getSelectedItemIndex() == ctCpu || - listBoxControls[i].getSelectedItemIndex() == ctCpuUltra || - listBoxControls[i].getSelectedItemIndex() == ctCpuMega) { - setSlotHuman(i); - - foundNewSlotForHuman = true; - break; - } - } - } - - if(foundNewSlotForHuman == false) { - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - ConnectionSlot *slot = serverInterface->getSlot(0,true); - if(slot != NULL && slot->isConnected() == true) { - serverInterface->removeSlot(0); - } - setSlotHuman(0); - } - } - } - - for(int i= mapInfo.players; i < GameConstants::maxPlayers; ++i) { - if( listBoxControls[i].getSelectedItemIndex() != ctNetwork && - listBoxControls[i].getSelectedItemIndex() != ctNetworkUnassigned) { - //printf("Closed A [%d] [%s]\n",i,labelPlayerNames[i].getText().c_str()); - - listBoxControls[i].setSelectedItemIndex(ctClosed); - } - } - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - throw megaglest_runtime_error(szBuf); - } + try { + bool humanPlayer = false; + + for (int i = 0; i < mapInfo.players; ++i) { + if (listBoxControls[i].getSelectedItemIndex() == ctHuman) { + humanPlayer = true; + } + } + + if (humanPlayer == false) { + if (this->headlessServerMode == false) { + bool foundNewSlotForHuman = false; + for (int i = 0; i < mapInfo.players; ++i) { + if (listBoxControls[i].getSelectedItemIndex() == ctClosed) { + setSlotHuman(i); + foundNewSlotForHuman = true; + break; + } + } + + if (foundNewSlotForHuman == false) { + for (int i = 0; i < mapInfo.players; ++i) { + if (listBoxControls[i].getSelectedItemIndex() == ctClosed || + listBoxControls[i].getSelectedItemIndex() == ctCpuEasy || + listBoxControls[i].getSelectedItemIndex() == ctCpu || + listBoxControls[i].getSelectedItemIndex() == ctCpuUltra || + listBoxControls[i].getSelectedItemIndex() == ctCpuMega) { + setSlotHuman(i); + + foundNewSlotForHuman = true; + break; + } + } + } + + if (foundNewSlotForHuman == false) { + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + ConnectionSlot *slot = serverInterface->getSlot(0, true); + if (slot != NULL && slot->isConnected() == true) { + serverInterface->removeSlot(0); + } + setSlotHuman(0); + } + } + } + + for (int i = mapInfo.players; i < GameConstants::maxPlayers; ++i) { + if (listBoxControls[i].getSelectedItemIndex() != ctNetwork && + listBoxControls[i].getSelectedItemIndex() != ctNetworkUnassigned) { + // printf("Closed A [%d] + // [%s]\n",i,labelPlayerNames[i].getText().c_str()); + + listBoxControls[i].setSelectedItemIndex(ctClosed); + } + } + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + throw megaglest_runtime_error(szBuf); + } } -void MenuStateCustomGame::closeUnusedSlots(){ - try { - if(checkBoxScenario.getValue() == false) { - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - //for(int i= 0; igetSlot(i,true) == NULL || - serverInterface->getSlot(i,true)->isConnected() == false || - serverInterface->getSlot(i,true)->getConnectHasHandshaked() == false) { - //printf("Closed A [%d] [%s]\n",i,labelPlayerNames[i].getText().c_str()); - - listBoxControls[i].setSelectedItemIndex(ctClosed); - } - } - } - updateNetworkSlots(); - } - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - throw megaglest_runtime_error(szBuf); - } +void MenuStateCustomGame::closeUnusedSlots() { + try { + if (checkBoxScenario.getValue() == false) { + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + // for(int i= 0; igetSlot(i, true) == NULL || + serverInterface->getSlot(i, true)->isConnected() == false || + serverInterface->getSlot(i, true)->getConnectHasHandshaked() == + false) { + // printf("Closed A [%d] + // [%s]\n",i,labelPlayerNames[i].getText().c_str()); + + listBoxControls[i].setSelectedItemIndex(ctClosed); + } + } + } + updateNetworkSlots(); + } + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + throw megaglest_runtime_error(szBuf); + } } void MenuStateCustomGame::updateNetworkSlots() { - try { - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); + try { + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); - if(hasNetworkGameSettings() == true) { - if(hasCheckedForUPNP == false) { + if (hasNetworkGameSettings() == true) { + if (hasCheckedForUPNP == false) { - if(checkBoxPublishServer.getValue() == true || - this->headlessServerMode == true) { + if (checkBoxPublishServer.getValue() == true || + this->headlessServerMode == true) { - hasCheckedForUPNP = true; - serverInterface->getServerSocket()->NETdiscoverUPnPDevices(); - } - } + hasCheckedForUPNP = true; + serverInterface->getServerSocket()->NETdiscoverUPnPDevices(); } - else { - hasCheckedForUPNP = false; + } + } else { + hasCheckedForUPNP = false; + } + + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + ConnectionSlot *slot = serverInterface->getSlot(i, true); + // printf("A i = %d control type = %d slot + // [%p]\n",i,listBoxControls[i].getSelectedItemIndex(),slot); + + if (slot == NULL && + listBoxControls[i].getSelectedItemIndex() == ctNetwork) { + try { + serverInterface->addSlot(i); + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + showGeneralError = true; + if (serverInterface->isPortBound() == false) { + generalErrorToShow = + Lang::getInstance().getString("ErrorBindingPort") + " : " + + intToStr(serverInterface->getBindPort()); + } else { + generalErrorToShow = ex.what(); + } + + // Revert network to CPU + listBoxControls[i].setSelectedItemIndex(ctCpu); } + } + slot = serverInterface->getSlot(i, true); + if (slot != NULL) { + if ((listBoxControls[i].getSelectedItemIndex() != ctNetwork) || + (listBoxControls[i].getSelectedItemIndex() == ctNetwork && + slot->isConnected() == false && i >= mapInfo.players)) { + if (slot->getCanAcceptConnections() == true) { + slot->setCanAcceptConnections(false); + } + if (slot->isConnected() == true) { + if (listBoxControls[i].getSelectedItemIndex() != + ctNetworkUnassigned) { + listBoxControls[i].setSelectedItemIndex(ctNetworkUnassigned); + } + } else { + serverInterface->removeSlot(i); - for(int i= 0; i < GameConstants::maxPlayers; ++i) { - ConnectionSlot *slot = serverInterface->getSlot(i,true); - //printf("A i = %d control type = %d slot [%p]\n",i,listBoxControls[i].getSelectedItemIndex(),slot); - - if(slot == NULL && - listBoxControls[i].getSelectedItemIndex() == ctNetwork) { - try { - serverInterface->addSlot(i); - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - showGeneralError=true; - if(serverInterface->isPortBound() == false) { - generalErrorToShow = Lang::getInstance().getString("ErrorBindingPort") + " : " + intToStr(serverInterface->getBindPort()); - } - else { - generalErrorToShow = ex.what(); - } - - // Revert network to CPU - listBoxControls[i].setSelectedItemIndex(ctCpu); - } - } - slot = serverInterface->getSlot(i,true); - if(slot != NULL) { - if((listBoxControls[i].getSelectedItemIndex() != ctNetwork) || - (listBoxControls[i].getSelectedItemIndex() == ctNetwork && - slot->isConnected() == false && i >= mapInfo.players)) { - if(slot->getCanAcceptConnections() == true) { - slot->setCanAcceptConnections(false); - } - if(slot->isConnected() == true) { - if(listBoxControls[i].getSelectedItemIndex() != ctNetworkUnassigned) { - listBoxControls[i].setSelectedItemIndex(ctNetworkUnassigned); - } - } - else { - serverInterface->removeSlot(i); - - if(listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) { - listBoxControls[i].setSelectedItemIndex(ctClosed); - } - } - } - else if(slot->getCanAcceptConnections() == false) { - slot->setCanAcceptConnections(true); - } - } - } - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - //throw megaglest_runtime_error(szBuf); - showGeneralError=true; - generalErrorToShow = szBuf; - - } + if (listBoxControls[i].getSelectedItemIndex() == + ctNetworkUnassigned) { + listBoxControls[i].setSelectedItemIndex(ctClosed); + } + } + } else if (slot->getCanAcceptConnections() == false) { + slot->setCanAcceptConnections(true); + } + } + } + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + // throw megaglest_runtime_error(szBuf); + showGeneralError = true; + generalErrorToShow = szBuf; + } } bool MenuStateCustomGame::textInput(std::string text) { - //printf("In [%s::%s Line: %d] text [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,text.c_str()); - if(activeInputLabel != NULL) { - bool handled = textInputEditLabel(text, &activeInputLabel); - if(handled == true && &labelGameName != activeInputLabel) { - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - if(hasNetworkGameSettings() == true) { - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); - } - } - } - else { - if(hasNetworkGameSettings() == true) { - chatManager.textInput(text); - } - } - return false; + // printf("In [%s::%s Line: %d] text + // [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,text.c_str()); + if (activeInputLabel != NULL) { + bool handled = textInputEditLabel(text, &activeInputLabel); + if (handled == true && &labelGameName != activeInputLabel) { + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + MutexSafeWrapper safeMutexCLI( + (publishToClientsThread != NULL + ? publishToClientsThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + if (hasNetworkGameSettings() == true) { + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + } + } + } else { + if (hasNetworkGameSettings() == true) { + chatManager.textInput(text); + } + } + return false; } void MenuStateCustomGame::keyDown(SDL_KeyboardEvent key) { - if(isMasterserverMode() == true) { - return; - } - - if(activeInputLabel != NULL) { - bool handled = keyDownEditLabel(key, &activeInputLabel); - if(handled == true) { - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - if(hasNetworkGameSettings() == true) { - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); - } - } - } - else { - //send key to the chat manager - if(hasNetworkGameSettings() == true) { - chatManager.keyDown(key); - } - if(chatManager.getEditEnabled() == false && - (::Shared::Platform::Window::isKeyStateModPressed(KMOD_SHIFT) == false) ) { - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - - //if(key == configKeys.getCharKey("ShowFullConsole")) { - if(isKeyPressed(configKeys.getSDLKey("ShowFullConsole"),key) == true) { - showFullConsole= true; - } - //Toggle music - //else if(key == configKeys.getCharKey("ToggleMusic")) { - else if(isKeyPressed(configKeys.getSDLKey("ToggleMusic"),key) == true) { - Config &config = Config::getInstance(); - Lang &lang= Lang::getInstance(); - - float configVolume = (config.getInt("SoundVolumeMusic") / 100.f); - float currentVolume = CoreData::getInstance().getMenuMusic()->getVolume(); - if(currentVolume > 0) { - CoreData::getInstance().getMenuMusic()->setVolume(0.f); - console.addLine(lang.getString("GameMusic") + " " + lang.getString("Off")); - } - else { - CoreData::getInstance().getMenuMusic()->setVolume(configVolume); - //If the config says zero, use the default music volume - //gameMusic->setVolume(configVolume ? configVolume : 0.9); - console.addLine(lang.getString("GameMusic")); - } - } - //else if(key == configKeys.getCharKey("SaveGUILayout")) { - else if(isKeyPressed(configKeys.getSDLKey("SaveGUILayout"),key) == true) { - bool saved = GraphicComponent::saveAllCustomProperties(containerName); - Lang &lang= Lang::getInstance(); - console.addLine(lang.getString("GUILayoutSaved") + " [" + (saved ? lang.getString("Yes") : lang.getString("No"))+ "]"); - } - } - } + if (isMasterserverMode() == true) { + return; + } + + if (activeInputLabel != NULL) { + bool handled = keyDownEditLabel(key, &activeInputLabel); + if (handled == true) { + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + MutexSafeWrapper safeMutexCLI( + (publishToClientsThread != NULL + ? publishToClientsThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + if (hasNetworkGameSettings() == true) { + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + } + } + } else { + // send key to the chat manager + if (hasNetworkGameSettings() == true) { + chatManager.keyDown(key); + } + if (chatManager.getEditEnabled() == false && + (::Shared::Platform::Window::isKeyStateModPressed(KMOD_SHIFT) == + false)) { + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + + // if(key == configKeys.getCharKey("ShowFullConsole")) { + if (isKeyPressed(configKeys.getSDLKey("ShowFullConsole"), key) == true) { + showFullConsole = true; + } + // Toggle music + // else if(key == configKeys.getCharKey("ToggleMusic")) { + else if (isKeyPressed(configKeys.getSDLKey("ToggleMusic"), key) == true) { + Config &config = Config::getInstance(); + Lang &lang = Lang::getInstance(); + + float configVolume = (config.getInt("SoundVolumeMusic") / 100.f); + float currentVolume = + CoreData::getInstance().getMenuMusic()->getVolume(); + if (currentVolume > 0) { + CoreData::getInstance().getMenuMusic()->setVolume(0.f); + console.addLine(lang.getString("GameMusic") + " " + + lang.getString("Off")); + } else { + CoreData::getInstance().getMenuMusic()->setVolume(configVolume); + // If the config says zero, use the default music volume + // gameMusic->setVolume(configVolume ? configVolume : 0.9); + console.addLine(lang.getString("GameMusic")); + } + } + // else if(key == configKeys.getCharKey("SaveGUILayout")) { + else if (isKeyPressed(configKeys.getSDLKey("SaveGUILayout"), key) == + true) { + bool saved = GraphicComponent::saveAllCustomProperties(containerName); + Lang &lang = Lang::getInstance(); + console.addLine(lang.getString("GUILayoutSaved") + " [" + + (saved ? lang.getString("Yes") : lang.getString("No")) + + "]"); + } + } + } } void MenuStateCustomGame::keyPress(SDL_KeyboardEvent c) { - if(isMasterserverMode() == true) { - return; - } - - if(activeInputLabel != NULL) { - bool handled = keyPressEditLabel(c, &activeInputLabel); - if(handled == true && &labelGameName != activeInputLabel) { - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - if(hasNetworkGameSettings() == true) { - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); - } - } - } - else { - if(hasNetworkGameSettings() == true) { - chatManager.keyPress(c); - } - } + if (isMasterserverMode() == true) { + return; + } + + if (activeInputLabel != NULL) { + bool handled = keyPressEditLabel(c, &activeInputLabel); + if (handled == true && &labelGameName != activeInputLabel) { + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + MutexSafeWrapper safeMutexCLI( + (publishToClientsThread != NULL + ? publishToClientsThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + if (hasNetworkGameSettings() == true) { + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + } + } + } else { + if (hasNetworkGameSettings() == true) { + chatManager.keyPress(c); + } + } } void MenuStateCustomGame::keyUp(SDL_KeyboardEvent key) { - if(isMasterserverMode() == true) { - return; - } - - if(activeInputLabel==NULL) { - if(hasNetworkGameSettings() == true) { - chatManager.keyUp(key); - } - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - - if(chatManager.getEditEnabled()) { - //send key to the chat manager - if(hasNetworkGameSettings() == true) { - chatManager.keyUp(key); - } - } - //else if(key == configKeys.getCharKey("ShowFullConsole")) { - else if(isKeyPressed(configKeys.getSDLKey("ShowFullConsole"),key) == true) { - showFullConsole= false; - } - } + if (isMasterserverMode() == true) { + return; + } + + if (activeInputLabel == NULL) { + if (hasNetworkGameSettings() == true) { + chatManager.keyUp(key); + } + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + + if (chatManager.getEditEnabled()) { + // send key to the chat manager + if (hasNetworkGameSettings() == true) { + chatManager.keyUp(key); + } + } + // else if(key == configKeys.getCharKey("ShowFullConsole")) { + else if (isKeyPressed(configKeys.getSDLKey("ShowFullConsole"), key) == + true) { + showFullConsole = false; + } + } } -void MenuStateCustomGame::showMessageBox(const string &text, const string &header, bool toggle){ - if(!toggle){ - mainMessageBox.setEnabled(false); - } - - if(!mainMessageBox.getEnabled()){ - mainMessageBox.setText(text); - mainMessageBox.setHeader(header); - mainMessageBox.setEnabled(true); - } - else{ - mainMessageBox.setEnabled(false); - } +void MenuStateCustomGame::showMessageBox(const string &text, + const string &header, bool toggle) { + if (!toggle) { + mainMessageBox.setEnabled(false); + } + + if (!mainMessageBox.getEnabled()) { + mainMessageBox.setText(text); + mainMessageBox.setHeader(header); + mainMessageBox.setEnabled(true); + } else { + mainMessageBox.setEnabled(false); + } } -void MenuStateCustomGame::switchToNextMapGroup(const int direction){ - int i=listBoxMapFilter.getSelectedItemIndex(); - // if there are no maps for the current selection we switch to next selection - while(formattedPlayerSortedMaps[i].empty()){ - i=i+direction; - if(i>GameConstants::maxPlayers){ - i=0; - } - if(i<0){ - i=GameConstants::maxPlayers; - } - } - listBoxMapFilter.setSelectedItemIndex(i); - comboBoxMap.setItems(formattedPlayerSortedMaps[i]); +void MenuStateCustomGame::switchToNextMapGroup(const int direction) { + int i = listBoxMapFilter.getSelectedItemIndex(); + // if there are no maps for the current selection we switch to next selection + while (formattedPlayerSortedMaps[i].empty()) { + i = i + direction; + if (i > GameConstants::maxPlayers) { + i = 0; + } + if (i < 0) { + i = GameConstants::maxPlayers; + } + } + listBoxMapFilter.setSelectedItemIndex(i); + comboBoxMap.setItems(formattedPlayerSortedMaps[i]); } -string MenuStateCustomGame::getCurrentMapFile(){ - int i=listBoxMapFilter.getSelectedItemIndex(); - int mapIndex=comboBoxMap.getSelectedItemIndex(); - if(playerSortedMaps[i].empty() == false) { - return playerSortedMaps[i].at(mapIndex); - } - return ""; +string MenuStateCustomGame::getCurrentMapFile() { + int i = listBoxMapFilter.getSelectedItemIndex(); + int mapIndex = comboBoxMap.getSelectedItemIndex(); + if (playerSortedMaps[i].empty() == false) { + return playerSortedMaps[i].at(mapIndex); + } + return ""; } -string MenuStateCustomGame::getPreselectedMapFile(){ - int i=listBoxMapFilter.getSelectedItemIndex(); - int mapIndex=comboBoxMap.getPreselectedItemIndex(); - if(playerSortedMaps[i].empty() == false) { - return playerSortedMaps[i].at(mapIndex); - } - return ""; +string MenuStateCustomGame::getPreselectedMapFile() { + int i = listBoxMapFilter.getSelectedItemIndex(); + int mapIndex = comboBoxMap.getPreselectedItemIndex(); + if (playerSortedMaps[i].empty() == false) { + return playerSortedMaps[i].at(mapIndex); + } + return ""; } void MenuStateCustomGame::setActiveInputLabel(GraphicLabel *newLable) { - MenuState::setActiveInputLabel(newLable,&activeInputLabel); + MenuState::setActiveInputLabel(newLable, &activeInputLabel); } string MenuStateCustomGame::getHumanPlayerName(int index) { - string result = defaultPlayerName; - if(index < 0) { - for(int j = 0; j < GameConstants::maxPlayers; ++j) { - if(listBoxControls[j].getSelectedItemIndex() >= 0) { - ControlType ct = static_cast(listBoxControls[j].getSelectedItemIndex()); - if(ct == ctHuman) { - index = j; - break; - } - } - } - } - - if(index >= 0 && index < GameConstants::maxPlayers && - labelPlayerNames[index].getText() != "" && - labelPlayerNames[index].getText() != GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME) { - result = labelPlayerNames[index].getText(); - - if(activeInputLabel != NULL) { - size_t found = result.find_last_of("_"); - if (found != string::npos) { - result = result.substr(0,found); - } - } - } - - return result; + string result = defaultPlayerName; + if (index < 0) { + for (int j = 0; j < GameConstants::maxPlayers; ++j) { + if (listBoxControls[j].getSelectedItemIndex() >= 0) { + ControlType ct = + static_cast(listBoxControls[j].getSelectedItemIndex()); + if (ct == ctHuman) { + index = j; + break; + } + } + } + } + + if (index >= 0 && index < GameConstants::maxPlayers && + labelPlayerNames[index].getText() != "" && + labelPlayerNames[index].getText() != + GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME) { + result = labelPlayerNames[index].getText(); + + if (activeInputLabel != NULL) { + size_t found = result.find_last_of("_"); + if (found != string::npos) { + result = result.substr(0, found); + } + } + } + + return result; } void MenuStateCustomGame::loadFactionTexture(string filepath) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(enableFactionTexturePreview == true) { - if(filepath == "") { - factionTexture = NULL; - } - else { - 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()); - - factionTexture = Renderer::findTexture(filepath); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (enableFactionTexturePreview == true) { + if (filepath == "") { + factionTexture = NULL; + } else { + 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()); + + factionTexture = Renderer::findTexture(filepath); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + } + } } void MenuStateCustomGame::cleanupMapPreviewTexture() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //printf("CLEANUP map preview texture\n"); - - if(mapPreviewTexture != NULL) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - mapPreviewTexture->end(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - delete mapPreviewTexture; - mapPreviewTexture = NULL; - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // printf("CLEANUP map preview texture\n"); + + if (mapPreviewTexture != NULL) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + mapPreviewTexture->end(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + delete mapPreviewTexture; + mapPreviewTexture = NULL; + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); } int32 MenuStateCustomGame::getNetworkPlayerStatus() { - int32 result = npst_None; - switch(listBoxPlayerStatus.getSelectedItemIndex()) { - case 2: - result = npst_Ready; - break; - case 1: - result = npst_BeRightBack; - break; - case 0: - default: - result = npst_PickSettings; - break; - } - - return result; + int32 result = npst_None; + switch (listBoxPlayerStatus.getSelectedItemIndex()) { + case 2: + result = npst_Ready; + break; + case 1: + result = npst_BeRightBack; + break; + case 0: + default: + result = npst_PickSettings; + break; + } + + return result; } -void MenuStateCustomGame::loadScenarioInfo(string file, ScenarioInfo *scenarioInfo) { - //printf("Load scenario file [%s]\n",file.c_str()); - bool isTutorial = Scenario::isGameTutorial(file); - Scenario::loadScenarioInfo(file, scenarioInfo, isTutorial); +void MenuStateCustomGame::loadScenarioInfo(string file, + ScenarioInfo *scenarioInfo) { + // printf("Load scenario file [%s]\n",file.c_str()); + bool isTutorial = Scenario::isGameTutorial(file); + Scenario::loadScenarioInfo(file, scenarioInfo, isTutorial); - //cleanupPreviewTexture(); - previewLoadDelayTimer=time(NULL); - needToLoadTextures=true; + // cleanupPreviewTexture(); + previewLoadDelayTimer = time(NULL); + needToLoadTextures = true; } bool MenuStateCustomGame::isInSpecialKeyCaptureEvent() { - bool result = (chatManager.getEditEnabled() || activeInputLabel != NULL); - return result; + bool result = (chatManager.getEditEnabled() || activeInputLabel != NULL); + return result; } void MenuStateCustomGame::processScenario() { - try { - if(checkBoxScenario.getValue() == true) { - //printf("listBoxScenario.getSelectedItemIndex() = %d [%s] scenarioFiles.size() = %d\n",listBoxScenario.getSelectedItemIndex(),listBoxScenario.getSelectedItem().c_str(),scenarioFiles.size()); - loadScenarioInfo(Scenario::getScenarioPath(dirList, scenarioFiles[listBoxScenario.getSelectedItemIndex()]), &scenarioInfo); - string scenarioDir = Scenario::getScenarioDir(dirList, scenarioInfo.name); - - //printf("scenarioInfo.fogOfWar = %d scenarioInfo.fogOfWar_exploredFlag = %d\n",scenarioInfo.fogOfWar,scenarioInfo.fogOfWar_exploredFlag); - if(scenarioInfo.fogOfWar == false && scenarioInfo.fogOfWar_exploredFlag == false) { - listBoxFogOfWar.setSelectedItemIndex(2); - } - else if(scenarioInfo.fogOfWar_exploredFlag == true) { - listBoxFogOfWar.setSelectedItemIndex(1); - } - else { - listBoxFogOfWar.setSelectedItemIndex(0); - } - - checkBoxAllowTeamUnitSharing.setValue(scenarioInfo.allowTeamUnitSharing); - checkBoxAllowTeamResourceSharing.setValue(scenarioInfo.allowTeamResourceSharing); - - setupTechList(scenarioInfo.name, false); - listBoxTechTree.setSelectedItem(formatString(scenarioInfo.techTreeName)); - reloadFactions(false,scenarioInfo.name); - - setupTilesetList(scenarioInfo.name); - listBoxTileset.setSelectedItem(formatString(scenarioInfo.tilesetName)); - - setupMapList(scenarioInfo.name); - comboBoxMap.setSelectedItem(formatString(scenarioInfo.mapName)); - loadMapInfo(Config::getMapPath(getCurrentMapFile(),scenarioDir,true), &mapInfo, true,true); - labelMapInfo.setText(mapInfo.desc); - - //printf("scenarioInfo.name [%s] [%s]\n",scenarioInfo.name.c_str(),listBoxMap.getSelectedItem().c_str()); - - // Loop twice to set the human slot or else it closes network slots in some cases - for(int humanIndex = 0; humanIndex < 2; ++humanIndex) { - for(int i = 0; i < mapInfo.players; ++i) { - listBoxRMultiplier[i].setSelectedItem(floatToStr(scenarioInfo.resourceMultipliers[i],1)); - - ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface(); - ConnectionSlot *slot = serverInterface->getSlot(i,true); - - int selectedControlItemIndex = listBoxControls[i].getSelectedItemIndex(); - if(selectedControlItemIndex != ctNetwork || - (selectedControlItemIndex == ctNetwork && (slot == NULL || slot->isConnected() == false))) { - } - - listBoxControls[i].setSelectedItemIndex(scenarioInfo.factionControls[i]); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - // Skip over networkunassigned - //if(listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned && - // selectedControlItemIndex != ctNetworkUnassigned) { - // listBoxControls[i].mouseClick(x, y); - //} - - //look for human players - int humanIndex1= -1; - int humanIndex2= -1; - for(int j = 0; j < GameConstants::maxPlayers; ++j) { - ControlType ct= static_cast(listBoxControls[j].getSelectedItemIndex()); - if(ct == ctHuman) { - if(humanIndex1 == -1) { - humanIndex1= j; - } - else { - humanIndex2= j; - } - } - } - - 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); - - //no human - if(humanIndex1 == -1 && humanIndex2 == -1) { - setSlotHuman(i); - 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()); - - //printf("humanIndex1 = %d humanIndex2 = %d i = %d listBoxControls[i].getSelectedItemIndex() = %d\n",humanIndex1,humanIndex2,i,listBoxControls[i].getSelectedItemIndex()); - } - //2 humans - else if(humanIndex1 != -1 && humanIndex2 != -1) { - int closeSlotIndex = (humanIndex1 == i ? humanIndex2: humanIndex1); - int humanSlotIndex = (closeSlotIndex == humanIndex1 ? humanIndex2 : humanIndex1); - - string origPlayName = labelPlayerNames[closeSlotIndex].getText(); - - 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()); - //printf("humanIndex1 = %d humanIndex2 = %d i = %d closeSlotIndex = %d humanSlotIndex = %d\n",humanIndex1,humanIndex2,i,closeSlotIndex,humanSlotIndex); - - listBoxControls[closeSlotIndex].setSelectedItemIndex(ctClosed); - labelPlayerNames[humanSlotIndex].setText((origPlayName != "" ? origPlayName : getHumanPlayerName())); - } - - ControlType ct= static_cast(listBoxControls[i].getSelectedItemIndex()); - if(ct != ctClosed) { - //updateNetworkSlots(); - //updateResourceMultiplier(i); - updateResourceMultiplier(i); - - //printf("Setting scenario faction i = %d [ %s]\n",i,scenarioInfo.factionTypeNames[i].c_str()); - listBoxFactions[i].setSelectedItem(formatString(scenarioInfo.factionTypeNames[i])); - //printf("DONE Setting scenario faction i = %d [ %s]\n",i,scenarioInfo.factionTypeNames[i].c_str()); - - // Disallow CPU players to be observers - if(factionFiles[listBoxFactions[i].getSelectedItemIndex()] == formatString(GameConstants::OBSERVER_SLOTNAME) && - (listBoxControls[i].getSelectedItemIndex() == ctCpuEasy || listBoxControls[i].getSelectedItemIndex() == ctCpu || - listBoxControls[i].getSelectedItemIndex() == ctCpuUltra || listBoxControls[i].getSelectedItemIndex() == ctCpuMega)) { - listBoxFactions[i].setSelectedItemIndex(0); - } - // - - listBoxTeams[i].setSelectedItem(intToStr(scenarioInfo.teams[i])); - if(factionFiles[listBoxFactions[i].getSelectedItemIndex()] != formatString(GameConstants::OBSERVER_SLOTNAME)) { - if(listBoxTeams[i].getSelectedItemIndex() + 1 != (GameConstants::maxPlayers + fpt_Observer)) { - lastSelectedTeamIndex[i] = listBoxTeams[i].getSelectedItemIndex(); - } - // Alow Neutral cpu players - else if(listBoxControls[i].getSelectedItemIndex() == ctCpuEasy || listBoxControls[i].getSelectedItemIndex() == ctCpu || - listBoxControls[i].getSelectedItemIndex() == ctCpuUltra || listBoxControls[i].getSelectedItemIndex() == ctCpuMega) { - lastSelectedTeamIndex[i] = listBoxTeams[i].getSelectedItemIndex(); - } - } - else { - lastSelectedTeamIndex[i] = -1; - } - } - - if(checkBoxPublishServer.getValue() == true) { - needToRepublishToMasterserver = true; - } - - if(hasNetworkGameSettings() == true) { - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL);; - } - } - } - - updateControlers(); - updateNetworkSlots(); - - MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__)); - - if(checkBoxPublishServer.getValue() == true) { - needToRepublishToMasterserver = true; - } - if(hasNetworkGameSettings() == true) { - needToSetChangedGameSettings = true; - lastSetChangedGameSettings = time(NULL); - } - - //labelInfo.setText(scenarioInfo.desc); - } - else { - setupMapList(""); - comboBoxMap.setSelectedItem(formatString(formattedPlayerSortedMaps[0][0])); - loadMapInfo(Config::getMapPath(getCurrentMapFile(),"",true), &mapInfo, true,true); - labelMapInfo.setText(mapInfo.desc); - - int initialTechSelection=setupTechList("", false); - if(listBoxTechTree.getItemCount() > 0) { - listBoxTechTree.setSelectedItemIndex(initialTechSelection); - } - reloadFactions(false,""); - setupTilesetList(""); - updateControlers(); - } - SetupUIForScenarios(); - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - - mainMessageBoxState=1; - showMessageBox( szBuf, "Error detected", false); - } + try { + if (checkBoxScenario.getValue() == true) { + // printf("listBoxScenario.getSelectedItemIndex() = %d [%s] + // scenarioFiles.size() = + // %d\n",listBoxScenario.getSelectedItemIndex(),listBoxScenario.getSelectedItem().c_str(),scenarioFiles.size()); + loadScenarioInfo( + Scenario::getScenarioPath( + dirList, scenarioFiles[listBoxScenario.getSelectedItemIndex()]), + &scenarioInfo); + string scenarioDir = Scenario::getScenarioDir(dirList, scenarioInfo.name); + + // printf("scenarioInfo.fogOfWar = %d scenarioInfo.fogOfWar_exploredFlag = + // %d\n",scenarioInfo.fogOfWar,scenarioInfo.fogOfWar_exploredFlag); + if (scenarioInfo.fogOfWar == false && + scenarioInfo.fogOfWar_exploredFlag == false) { + listBoxFogOfWar.setSelectedItemIndex(2); + } else if (scenarioInfo.fogOfWar_exploredFlag == true) { + listBoxFogOfWar.setSelectedItemIndex(1); + } else { + listBoxFogOfWar.setSelectedItemIndex(0); + } + + checkBoxAllowTeamUnitSharing.setValue(scenarioInfo.allowTeamUnitSharing); + checkBoxAllowTeamResourceSharing.setValue( + scenarioInfo.allowTeamResourceSharing); + + setupTechList(scenarioInfo.name, false); + listBoxTechTree.setSelectedItem(formatString(scenarioInfo.techTreeName)); + reloadFactions(false, scenarioInfo.name); + + setupTilesetList(scenarioInfo.name); + listBoxTileset.setSelectedItem(formatString(scenarioInfo.tilesetName)); + + setupMapList(scenarioInfo.name); + comboBoxMap.setSelectedItem(formatString(scenarioInfo.mapName)); + loadMapInfo(Config::getMapPath(getCurrentMapFile(), scenarioDir, true), + &mapInfo, true, true); + labelMapInfo.setText(mapInfo.desc); + + // printf("scenarioInfo.name [%s] + // [%s]\n",scenarioInfo.name.c_str(),listBoxMap.getSelectedItem().c_str()); + + // Loop twice to set the human slot or else it closes network slots in + // some cases + for (int humanIndex = 0; humanIndex < 2; ++humanIndex) { + for (int i = 0; i < mapInfo.players; ++i) { + listBoxRMultiplier[i].setSelectedItem( + floatToStr(scenarioInfo.resourceMultipliers[i], 1)); + + ServerInterface *serverInterface = + NetworkManager::getInstance().getServerInterface(); + ConnectionSlot *slot = serverInterface->getSlot(i, true); + + int selectedControlItemIndex = + listBoxControls[i].getSelectedItemIndex(); + if (selectedControlItemIndex != ctNetwork || + (selectedControlItemIndex == ctNetwork && + (slot == NULL || slot->isConnected() == false))) { + } + + listBoxControls[i].setSelectedItemIndex( + scenarioInfo.factionControls[i]); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + // Skip over networkunassigned + // if(listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned + // && selectedControlItemIndex != ctNetworkUnassigned) { + // listBoxControls[i].mouseClick(x, y); + //} + + // look for human players + int humanIndex1 = -1; + int humanIndex2 = -1; + for (int j = 0; j < GameConstants::maxPlayers; ++j) { + ControlType ct = static_cast( + listBoxControls[j].getSelectedItemIndex()); + if (ct == ctHuman) { + if (humanIndex1 == -1) { + humanIndex1 = j; + } else { + humanIndex2 = j; + } + } + } + + 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); + + // no human + if (humanIndex1 == -1 && humanIndex2 == -1) { + setSlotHuman(i); + 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()); + + // printf("humanIndex1 = %d humanIndex2 = %d i = %d + // listBoxControls[i].getSelectedItemIndex() = + // %d\n",humanIndex1,humanIndex2,i,listBoxControls[i].getSelectedItemIndex()); + } + // 2 humans + else if (humanIndex1 != -1 && humanIndex2 != -1) { + int closeSlotIndex = (humanIndex1 == i ? humanIndex2 : humanIndex1); + int humanSlotIndex = + (closeSlotIndex == humanIndex1 ? humanIndex2 : humanIndex1); + + string origPlayName = labelPlayerNames[closeSlotIndex].getText(); + + 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()); + // printf("humanIndex1 = %d humanIndex2 = %d i = %d closeSlotIndex = + // %d humanSlotIndex = + // %d\n",humanIndex1,humanIndex2,i,closeSlotIndex,humanSlotIndex); + + listBoxControls[closeSlotIndex].setSelectedItemIndex(ctClosed); + labelPlayerNames[humanSlotIndex].setText( + (origPlayName != "" ? origPlayName : getHumanPlayerName())); + } + + ControlType ct = static_cast( + listBoxControls[i].getSelectedItemIndex()); + if (ct != ctClosed) { + // updateNetworkSlots(); + // updateResourceMultiplier(i); + updateResourceMultiplier(i); + + // printf("Setting scenario faction i = %d [ + // %s]\n",i,scenarioInfo.factionTypeNames[i].c_str()); + listBoxFactions[i].setSelectedItem( + formatString(scenarioInfo.factionTypeNames[i])); + // printf("DONE Setting scenario faction i = %d [ + // %s]\n",i,scenarioInfo.factionTypeNames[i].c_str()); + + // Disallow CPU players to be observers + if (factionFiles[listBoxFactions[i].getSelectedItemIndex()] == + formatString(GameConstants::OBSERVER_SLOTNAME) && + (listBoxControls[i].getSelectedItemIndex() == ctCpuEasy || + listBoxControls[i].getSelectedItemIndex() == ctCpu || + listBoxControls[i].getSelectedItemIndex() == ctCpuUltra || + listBoxControls[i].getSelectedItemIndex() == ctCpuMega)) { + listBoxFactions[i].setSelectedItemIndex(0); + } + // + + listBoxTeams[i].setSelectedItem(intToStr(scenarioInfo.teams[i])); + if (factionFiles[listBoxFactions[i].getSelectedItemIndex()] != + formatString(GameConstants::OBSERVER_SLOTNAME)) { + if (listBoxTeams[i].getSelectedItemIndex() + 1 != + (GameConstants::maxPlayers + fpt_Observer)) { + lastSelectedTeamIndex[i] = + listBoxTeams[i].getSelectedItemIndex(); + } + // Alow Neutral cpu players + else if (listBoxControls[i].getSelectedItemIndex() == ctCpuEasy || + listBoxControls[i].getSelectedItemIndex() == ctCpu || + listBoxControls[i].getSelectedItemIndex() == + ctCpuUltra || + listBoxControls[i].getSelectedItemIndex() == ctCpuMega) { + lastSelectedTeamIndex[i] = + listBoxTeams[i].getSelectedItemIndex(); + } + } else { + lastSelectedTeamIndex[i] = -1; + } + } + + if (checkBoxPublishServer.getValue() == true) { + needToRepublishToMasterserver = true; + } + + if (hasNetworkGameSettings() == true) { + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + ; + } + } + } + + updateControlers(); + updateNetworkSlots(); + + MutexSafeWrapper safeMutex( + (publishToMasterserverThread != NULL + ? publishToMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + MutexSafeWrapper safeMutexCLI( + (publishToClientsThread != NULL + ? publishToClientsThread->getMutexThreadObjectAccessor() + : NULL), + string(__FILE__) + "_" + intToStr(__LINE__)); + + if (checkBoxPublishServer.getValue() == true) { + needToRepublishToMasterserver = true; + } + if (hasNetworkGameSettings() == true) { + needToSetChangedGameSettings = true; + lastSetChangedGameSettings = time(NULL); + } + + // labelInfo.setText(scenarioInfo.desc); + } else { + setupMapList(""); + comboBoxMap.setSelectedItem( + formatString(formattedPlayerSortedMaps[0][0])); + loadMapInfo(Config::getMapPath(getCurrentMapFile(), "", true), &mapInfo, + true, true); + labelMapInfo.setText(mapInfo.desc); + + int initialTechSelection = setupTechList("", false); + if (listBoxTechTree.getItemCount() > 0) { + listBoxTechTree.setSelectedItemIndex(initialTechSelection); + } + reloadFactions(false, ""); + setupTilesetList(""); + updateControlers(); + } + SetupUIForScenarios(); + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + mainMessageBoxState = 1; + showMessageBox(szBuf, "Error detected", false); + } } void MenuStateCustomGame::SetupUIForScenarios() { - try { - if(checkBoxScenario.getValue() == true) { - // START - Disable changes to controls while in Scenario mode - for(int i = 0; i < GameConstants::maxPlayers; ++i) { - listBoxControls[i].setEditable(false); - listBoxFactions[i].setEditable(false); - listBoxRMultiplier[i].setEditable(false); - listBoxTeams[i].setEditable(false); - } - listBoxFogOfWar.setEditable(false); - checkBoxAllowObservers.setEditable(false); - checkBoxAllowTeamUnitSharing.setEditable(false); - checkBoxAllowTeamResourceSharing.setEditable(false); - //listBoxPathFinderType.setEditable(false); - checkBoxEnableSwitchTeamMode.setEditable(false); - listBoxAISwitchTeamAcceptPercent.setEditable(false); - listBoxFallbackCpuMultiplier.setEditable(false); - comboBoxMap.setEditable(false); - listBoxTileset.setEditable(false); - listBoxMapFilter.setEditable(false); - listBoxTechTree.setEditable(false); - // END - Disable changes to controls while in Scenario mode - } - else { - // START - Disable changes to controls while in Scenario mode - for(int i = 0; i < GameConstants::maxPlayers; ++i) { - listBoxControls[i].setEditable(true); - listBoxFactions[i].setEditable(true); - listBoxRMultiplier[i].setEditable(true); - listBoxTeams[i].setEditable(true); - } - listBoxFogOfWar.setEditable(true); - checkBoxAllowObservers.setEditable(true); - checkBoxAllowTeamUnitSharing.setEditable(true); - checkBoxAllowTeamResourceSharing.setEditable(true); - //listBoxPathFinderType.setEditable(true); - checkBoxEnableSwitchTeamMode.setEditable(true); - listBoxAISwitchTeamAcceptPercent.setEditable(true); - listBoxFallbackCpuMultiplier.setEditable(true); - comboBoxMap.setEditable(true); - listBoxTileset.setEditable(true); - listBoxMapFilter.setEditable(true); - listBoxTechTree.setEditable(true); - // END - Disable changes to controls while in Scenario mode - } - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - - throw megaglest_runtime_error(szBuf); - } - + try { + if (checkBoxScenario.getValue() == true) { + // START - Disable changes to controls while in Scenario mode + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + listBoxControls[i].setEditable(false); + listBoxFactions[i].setEditable(false); + listBoxRMultiplier[i].setEditable(false); + listBoxTeams[i].setEditable(false); + } + listBoxFogOfWar.setEditable(false); + checkBoxAllowObservers.setEditable(false); + checkBoxAllowTeamUnitSharing.setEditable(false); + checkBoxAllowTeamResourceSharing.setEditable(false); + // listBoxPathFinderType.setEditable(false); + checkBoxEnableSwitchTeamMode.setEditable(false); + listBoxAISwitchTeamAcceptPercent.setEditable(false); + listBoxFallbackCpuMultiplier.setEditable(false); + comboBoxMap.setEditable(false); + listBoxTileset.setEditable(false); + listBoxMapFilter.setEditable(false); + listBoxTechTree.setEditable(false); + // END - Disable changes to controls while in Scenario mode + } else { + // START - Disable changes to controls while in Scenario mode + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + listBoxControls[i].setEditable(true); + listBoxFactions[i].setEditable(true); + listBoxRMultiplier[i].setEditable(true); + listBoxTeams[i].setEditable(true); + } + listBoxFogOfWar.setEditable(true); + checkBoxAllowObservers.setEditable(true); + checkBoxAllowTeamUnitSharing.setEditable(true); + checkBoxAllowTeamResourceSharing.setEditable(true); + // listBoxPathFinderType.setEditable(true); + checkBoxEnableSwitchTeamMode.setEditable(true); + listBoxAISwitchTeamAcceptPercent.setEditable(true); + listBoxFallbackCpuMultiplier.setEditable(true); + comboBoxMap.setEditable(true); + listBoxTileset.setEditable(true); + listBoxMapFilter.setEditable(true); + listBoxTechTree.setEditable(true); + // END - Disable changes to controls while in Scenario mode + } + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + throw megaglest_runtime_error(szBuf); + } } void MenuStateCustomGame::loadSavedSetupNames() { - Config &config = Config::getInstance(); - Lang &lang= Lang::getInstance(); - vector paths; - string userData = config.getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - string saveSetupDir ; - saveSetupDir = userData +"setups"; - paths.push_back(saveSetupDir); - savedSetupFilenames.clear(); - findAll(paths, "*.mgg", savedSetupFilenames, true, false, true); - sort(savedSetupFilenames.begin(),savedSetupFilenames.end()); - savedSetupFilenames.insert(savedSetupFilenames.begin(),1,lang.getString(LAST_SETUP_STRING)); + Config &config = Config::getInstance(); + Lang &lang = Lang::getInstance(); + vector paths; + string userData = config.getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + string saveSetupDir; + saveSetupDir = userData + "setups"; + paths.push_back(saveSetupDir); + savedSetupFilenames.clear(); + findAll(paths, "*.mgg", savedSetupFilenames, true, false, true); + sort(savedSetupFilenames.begin(), savedSetupFilenames.end()); + savedSetupFilenames.insert(savedSetupFilenames.begin(), 1, + lang.getString(LAST_SETUP_STRING)); } int MenuStateCustomGame::setupMapList(string scenario) { - int initialMapSelection = 0; - - try { - Config &config = Config::getInstance(); - vector invalidMapList; - string scenarioDir = Scenario::getScenarioDir(dirList, scenario); - vector pathList = config.getPathListForType(ptMaps,scenarioDir); - vector allMaps = MapPreview::findAllValidMaps(pathList,scenarioDir,false,true,&invalidMapList); - if(scenario != "") { - vector allMaps2 = MapPreview::findAllValidMaps(config.getPathListForType(ptMaps,""),"",false,true,&invalidMapList); - copy(allMaps2.begin(), allMaps2.end(), std::inserter(allMaps, allMaps.begin())); - } - // sort map list non case sensitive - std::sort(allMaps.begin(),allMaps.end(),compareNonCaseSensitive); - - if (allMaps.empty()) { - throw megaglest_runtime_error("No maps were found!"); - } - vector results; - copy(allMaps.begin(), allMaps.end(), std::back_inserter(results)); - mapFiles = results; - - for(unsigned int i = 0; i < GameConstants::maxPlayers+1; ++i) { - playerSortedMaps[i].clear(); - formattedPlayerSortedMaps[i].clear(); - } - - // at index=0 fill in the whole list - copy(mapFiles.begin(), mapFiles.end(), std::back_inserter(playerSortedMaps[0])); - copy(playerSortedMaps[0].begin(), playerSortedMaps[0].end(), std::back_inserter(formattedPlayerSortedMaps[0])); - std::for_each(formattedPlayerSortedMaps[0].begin(), formattedPlayerSortedMaps[0].end(), FormatString()); - - // fill playerSortedMaps and formattedPlayerSortedMaps according to map player count - for(int i= 0; i < (int)mapFiles.size(); i++){// fetch info and put map in right list - loadMapInfo(Config::getMapPath(mapFiles.at(i), scenarioDir, false), &mapInfo, false,true); - - if(GameConstants::maxPlayers+1 <= mapInfo.players) { - char szBuf[8096]=""; - 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()); - throw megaglest_runtime_error(szBuf); - } - playerSortedMaps[mapInfo.players].push_back(mapFiles.at(i)); - formattedPlayerSortedMaps[mapInfo.players].push_back(formatString(mapFiles.at(i))); - if(config.getString("InitialMap", "Conflict") == formattedPlayerSortedMaps[mapInfo.players].back()){ - initialMapSelection= i; - } - } - - //printf("#6 scenario [%s] [%s]\n",scenario.c_str(),scenarioDir.c_str()); - if(scenario != "") { - string file = Scenario::getScenarioPath(dirList, scenario); - loadScenarioInfo(file, &scenarioInfo); - - //printf("#6.1 about to load map [%s]\n",scenarioInfo.mapName.c_str()); - loadMapInfo(Config::getMapPath(scenarioInfo.mapName, scenarioDir, true), &mapInfo, false,true); - //printf("#6.2\n"); - listBoxMapFilter.setSelectedItem(intToStr(mapInfo.players)); - comboBoxMap.setItems(formattedPlayerSortedMaps[mapInfo.players]); - } - else { - listBoxMapFilter.setSelectedItemIndex(0); - comboBoxMap.setItems(formattedPlayerSortedMaps[0]); - } - //printf("#7\n"); - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - - throw megaglest_runtime_error(szBuf); - //abort(); - } - - return initialMapSelection; + int initialMapSelection = 0; + + try { + Config &config = Config::getInstance(); + vector invalidMapList; + string scenarioDir = Scenario::getScenarioDir(dirList, scenario); + vector pathList = config.getPathListForType(ptMaps, scenarioDir); + vector allMaps = MapPreview::findAllValidMaps( + pathList, scenarioDir, false, true, &invalidMapList); + if (scenario != "") { + vector allMaps2 = + MapPreview::findAllValidMaps(config.getPathListForType(ptMaps, ""), + "", false, true, &invalidMapList); + copy(allMaps2.begin(), allMaps2.end(), + std::inserter(allMaps, allMaps.begin())); + } + // sort map list non case sensitive + std::sort(allMaps.begin(), allMaps.end(), compareNonCaseSensitive); + + if (allMaps.empty()) { + throw megaglest_runtime_error("No maps were found!"); + } + vector results; + copy(allMaps.begin(), allMaps.end(), std::back_inserter(results)); + mapFiles = results; + + for (unsigned int i = 0; i < GameConstants::maxPlayers + 1; ++i) { + playerSortedMaps[i].clear(); + formattedPlayerSortedMaps[i].clear(); + } + + // at index=0 fill in the whole list + copy(mapFiles.begin(), mapFiles.end(), + std::back_inserter(playerSortedMaps[0])); + copy(playerSortedMaps[0].begin(), playerSortedMaps[0].end(), + std::back_inserter(formattedPlayerSortedMaps[0])); + std::for_each(formattedPlayerSortedMaps[0].begin(), + formattedPlayerSortedMaps[0].end(), FormatString()); + + // fill playerSortedMaps and formattedPlayerSortedMaps according to map + // player count + for (int i = 0; i < (int)mapFiles.size(); + i++) { // fetch info and put map in right list + loadMapInfo(Config::getMapPath(mapFiles.at(i), scenarioDir, false), + &mapInfo, false, true); + + if (GameConstants::maxPlayers + 1 <= mapInfo.players) { + char szBuf[8096] = ""; + 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()); + throw megaglest_runtime_error(szBuf); + } + playerSortedMaps[mapInfo.players].push_back(mapFiles.at(i)); + formattedPlayerSortedMaps[mapInfo.players].push_back( + formatString(mapFiles.at(i))); + if (config.getString("InitialMap", "Conflict") == + formattedPlayerSortedMaps[mapInfo.players].back()) { + initialMapSelection = i; + } + } + + // printf("#6 scenario [%s] [%s]\n",scenario.c_str(),scenarioDir.c_str()); + if (scenario != "") { + string file = Scenario::getScenarioPath(dirList, scenario); + loadScenarioInfo(file, &scenarioInfo); + + // printf("#6.1 about to load map [%s]\n",scenarioInfo.mapName.c_str()); + loadMapInfo(Config::getMapPath(scenarioInfo.mapName, scenarioDir, true), + &mapInfo, false, true); + // printf("#6.2\n"); + listBoxMapFilter.setSelectedItem(intToStr(mapInfo.players)); + comboBoxMap.setItems(formattedPlayerSortedMaps[mapInfo.players]); + } else { + listBoxMapFilter.setSelectedItemIndex(0); + comboBoxMap.setItems(formattedPlayerSortedMaps[0]); + } + // printf("#7\n"); + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + throw megaglest_runtime_error(szBuf); + // abort(); + } + + return initialMapSelection; } int MenuStateCustomGame::setupTechList(string scenario, bool forceLoad) { - int initialTechSelection = 0; - try { - Config &config = Config::getInstance(); - - string scenarioDir = Scenario::getScenarioDir(dirList, scenario); - vector results; - vector techPaths = config.getPathListForType(ptTechs,scenarioDir); - findDirs(techPaths, results); + int initialTechSelection = 0; + try { + Config &config = Config::getInstance(); - if(results.empty()) { - //throw megaglest_runtime_error("No tech-trees were found!"); - printf("No tech-trees were found (custom)!\n"); - } + string scenarioDir = Scenario::getScenarioDir(dirList, scenario); + vector results; + vector techPaths = config.getPathListForType(ptTechs, scenarioDir); + findDirs(techPaths, results); - techTreeFiles= results; + if (results.empty()) { + // throw megaglest_runtime_error("No tech-trees were found!"); + printf("No tech-trees were found (custom)!\n"); + } - vector translatedTechs; + techTreeFiles = results; - for(unsigned int i= 0; i < results.size(); i++) { - //printf("TECHS i = %d results [%s] scenario [%s]\n",i,results[i].c_str(),scenario.c_str()); + vector translatedTechs; - results.at(i)= formatString(results.at(i)); - if(config.getString("InitialTechTree", "Megapack") == results.at(i)) { - initialTechSelection= i; - } - string txTech = techTree->getTranslatedName(techTreeFiles.at(i), forceLoad); - translatedTechs.push_back(formatString(txTech)); - } + for (unsigned int i = 0; i < results.size(); i++) { + // printf("TECHS i = %d results [%s] scenario + // [%s]\n",i,results[i].c_str(),scenario.c_str()); + results.at(i) = formatString(results.at(i)); + if (config.getString("InitialTechTree", "Megapack") == results.at(i)) { + initialTechSelection = i; + } + string txTech = + techTree->getTranslatedName(techTreeFiles.at(i), forceLoad); + translatedTechs.push_back(formatString(txTech)); + } - listBoxTechTree.setItems(results,translatedTechs); - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); + listBoxTechTree.setItems(results, translatedTechs); + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); - throw megaglest_runtime_error(szBuf); - } + throw megaglest_runtime_error(szBuf); + } - return initialTechSelection; + return initialTechSelection; } -void MenuStateCustomGame::reloadFactions(bool keepExistingSelectedItem, string scenario) { - try { - Config &config = Config::getInstance(); - Lang &lang= Lang::getInstance(); - - vector results; - string scenarioDir = Scenario::getScenarioDir(dirList, scenario); - vector techPaths = config.getPathListForType(ptTechs,scenarioDir); - - //printf("#1 techPaths.size() = %d scenarioDir [%s] [%s]\n",techPaths.size(),scenario.c_str(),scenarioDir.c_str()); - - if(listBoxTechTree.getItemCount() > 0) { - for(int idx = 0; idx < (int)techPaths.size(); idx++) { - string &techPath = techPaths[idx]; - endPathWithSlash(techPath); - string factionPath = techPath + techTreeFiles[listBoxTechTree.getSelectedItemIndex()] + "/factions/"; - findDirs(factionPath, results, false, false); - - //printf("idx = %d factionPath [%s] results.size() = %d\n",idx,factionPath.c_str(),results.size()); - - if(results.empty() == false) { - break; - } - } - } - - if(results.empty() == true) { - //throw megaglest_runtime_error("(2)There are no factions for the tech tree [" + techTreeFiles[listBoxTechTree.getSelectedItemIndex()] + "]"); - showGeneralError=true; - if(listBoxTechTree.getItemCount() > 0) { - generalErrorToShow = "[#2] There are no factions for the tech tree [" + techTreeFiles[listBoxTechTree.getSelectedItemIndex()] + "]"; - } - else { - generalErrorToShow = "[#2] There are no factions since there is no tech tree!"; - } - } - -// results.push_back(formatString(GameConstants::RANDOMFACTION_SLOTNAME)); -// -// // Add special Observer Faction -// if(checkBoxAllowObservers.getValue() == 1) { -// results.push_back(formatString(GameConstants::OBSERVER_SLOTNAME)); -// } - - vector translatedFactionNames; - factionFiles= results; - for(int i = 0; i < (int)results.size(); ++i) { - results[i]= formatString(results[i]); - - string translatedString = ""; - if(listBoxTechTree.getItemCount() > 0) { - translatedString = techTree->getTranslatedFactionName(techTreeFiles[listBoxTechTree.getSelectedItemIndex()],factionFiles[i]); - } - //printf("translatedString=%s formatString(results[i])=%s \n",translatedString.c_str(),formatString(results[i]).c_str() ); - if(toLower(translatedString)==toLower(results[i])){ - translatedFactionNames.push_back(results[i]); - } - else { - translatedFactionNames.push_back(results[i]+" ("+translatedString+")"); - } - //printf("FACTIONS i = %d results [%s]\n",i,results[i].c_str()); - - 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()); - } - results.push_back(formatString(GameConstants::RANDOMFACTION_SLOTNAME)); - factionFiles.push_back(formatString(GameConstants::RANDOMFACTION_SLOTNAME)); - translatedFactionNames.push_back("*"+lang.getString("Random","",true)+"*"); - - // Add special Observer Faction - if(checkBoxAllowObservers.getValue() == 1) { - results.push_back(formatString(GameConstants::OBSERVER_SLOTNAME)); - factionFiles.push_back(formatString(GameConstants::OBSERVER_SLOTNAME)); - translatedFactionNames.push_back("*"+lang.getString("Observer","",true)+"*"); - } - - for(int i = 0; i < GameConstants::maxPlayers; ++i) { - int originalIndex = listBoxFactions[i].getSelectedItemIndex(); - string originalValue = (listBoxFactions[i].getItemCount() > 0 ? listBoxFactions[i].getSelectedItem() : ""); - - listBoxFactions[i].setItems(results,translatedFactionNames); - if( keepExistingSelectedItem == false || - (checkBoxAllowObservers.getValue() == 0 && - originalValue == formatString(GameConstants::OBSERVER_SLOTNAME)) ) { - - listBoxFactions[i].setSelectedItemIndex(i % results.size()); - - if( originalValue == formatString(GameConstants::OBSERVER_SLOTNAME) && - listBoxFactions[i].getSelectedItem() != formatString(GameConstants::OBSERVER_SLOTNAME)) { - if(listBoxTeams[i].getSelectedItem() == intToStr(GameConstants::maxPlayers + fpt_Observer)) { - listBoxTeams[i].setSelectedItem(intToStr(1)); - } - } - } - else if(originalIndex < (int)results.size()) { - listBoxFactions[i].setSelectedItemIndex(originalIndex); - } - } - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - - throw megaglest_runtime_error(szBuf); - } +void MenuStateCustomGame::reloadFactions(bool keepExistingSelectedItem, + string scenario) { + try { + Config &config = Config::getInstance(); + Lang &lang = Lang::getInstance(); + + vector results; + string scenarioDir = Scenario::getScenarioDir(dirList, scenario); + vector techPaths = config.getPathListForType(ptTechs, scenarioDir); + + // printf("#1 techPaths.size() = %d scenarioDir [%s] + // [%s]\n",techPaths.size(),scenario.c_str(),scenarioDir.c_str()); + + if (listBoxTechTree.getItemCount() > 0) { + for (int idx = 0; idx < (int)techPaths.size(); idx++) { + string &techPath = techPaths[idx]; + endPathWithSlash(techPath); + string factionPath = + techPath + techTreeFiles[listBoxTechTree.getSelectedItemIndex()] + + "/factions/"; + findDirs(factionPath, results, false, false); + + // printf("idx = %d factionPath [%s] results.size() = + // %d\n",idx,factionPath.c_str(),results.size()); + + if (results.empty() == false) { + break; + } + } + } + + if (results.empty() == true) { + // throw megaglest_runtime_error("(2)There are no factions for the tech + // tree [" + techTreeFiles[listBoxTechTree.getSelectedItemIndex()] + "]"); + showGeneralError = true; + if (listBoxTechTree.getItemCount() > 0) { + generalErrorToShow = + "[#2] There are no factions for the tech tree [" + + techTreeFiles[listBoxTechTree.getSelectedItemIndex()] + "]"; + } else { + generalErrorToShow = + "[#2] There are no factions since there is no tech tree!"; + } + } + + // results.push_back(formatString(GameConstants::RANDOMFACTION_SLOTNAME)); + // + // // Add special Observer Faction + // if(checkBoxAllowObservers.getValue() == 1) { + // results.push_back(formatString(GameConstants::OBSERVER_SLOTNAME)); + // } + + vector translatedFactionNames; + factionFiles = results; + for (int i = 0; i < (int)results.size(); ++i) { + results[i] = formatString(results[i]); + + string translatedString = ""; + if (listBoxTechTree.getItemCount() > 0) { + translatedString = techTree->getTranslatedFactionName( + techTreeFiles[listBoxTechTree.getSelectedItemIndex()], + factionFiles[i]); + } + // printf("translatedString=%s formatString(results[i])=%s + // \n",translatedString.c_str(),formatString(results[i]).c_str() ); + if (toLower(translatedString) == toLower(results[i])) { + translatedFactionNames.push_back(results[i]); + } else { + translatedFactionNames.push_back(results[i] + " (" + translatedString + + ")"); + } + // printf("FACTIONS i = %d results [%s]\n",i,results[i].c_str()); + + 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()); + } + results.push_back(formatString(GameConstants::RANDOMFACTION_SLOTNAME)); + factionFiles.push_back(formatString(GameConstants::RANDOMFACTION_SLOTNAME)); + translatedFactionNames.push_back("*" + lang.getString("Random", "", true) + + "*"); + + // Add special Observer Faction + if (checkBoxAllowObservers.getValue() == 1) { + results.push_back(formatString(GameConstants::OBSERVER_SLOTNAME)); + factionFiles.push_back(formatString(GameConstants::OBSERVER_SLOTNAME)); + translatedFactionNames.push_back( + "*" + lang.getString("Observer", "", true) + "*"); + } + + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + int originalIndex = listBoxFactions[i].getSelectedItemIndex(); + string originalValue = (listBoxFactions[i].getItemCount() > 0 + ? listBoxFactions[i].getSelectedItem() + : ""); + + listBoxFactions[i].setItems(results, translatedFactionNames); + if (keepExistingSelectedItem == false || + (checkBoxAllowObservers.getValue() == 0 && + originalValue == formatString(GameConstants::OBSERVER_SLOTNAME))) { + + listBoxFactions[i].setSelectedItemIndex(i % results.size()); + + if (originalValue == formatString(GameConstants::OBSERVER_SLOTNAME) && + listBoxFactions[i].getSelectedItem() != + formatString(GameConstants::OBSERVER_SLOTNAME)) { + if (listBoxTeams[i].getSelectedItem() == + intToStr(GameConstants::maxPlayers + fpt_Observer)) { + listBoxTeams[i].setSelectedItem(intToStr(1)); + } + } + } else if (originalIndex < (int)results.size()) { + listBoxFactions[i].setSelectedItemIndex(originalIndex); + } + } + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + throw megaglest_runtime_error(szBuf); + } } void MenuStateCustomGame::setSlotHuman(int i) { - if(labelPlayerNames[i].getEditable()) { - return; - } - listBoxControls[i].setSelectedItemIndex(ctHuman); - listBoxRMultiplier[i].setSelectedItem("1.0"); - - labelPlayerNames[i].setText(getHumanPlayerName()); - for(int j = 0; j < GameConstants::maxPlayers; ++j) { - labelPlayerNames[j].setEditable(false); - } - labelPlayerNames[i].setEditable(true); + if (labelPlayerNames[i].getEditable()) { + return; + } + listBoxControls[i].setSelectedItemIndex(ctHuman); + listBoxRMultiplier[i].setSelectedItem("1.0"); + + labelPlayerNames[i].setText(getHumanPlayerName()); + for (int j = 0; j < GameConstants::maxPlayers; ++j) { + labelPlayerNames[j].setEditable(false); + } + labelPlayerNames[i].setEditable(true); } void MenuStateCustomGame::setupTilesetList(string scenario) { - try { - Config &config = Config::getInstance(); - - string scenarioDir = Scenario::getScenarioDir(dirList, scenario); - - vector results; - findDirs(config.getPathListForType(ptTilesets,scenarioDir), results); - if (results.empty()) { - throw megaglest_runtime_error("No tile-sets were found!"); - } - tilesetFiles= results; - std::for_each(results.begin(), results.end(), FormatString()); - - listBoxTileset.setItems(results); - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - - throw megaglest_runtime_error(szBuf); - } + try { + Config &config = Config::getInstance(); + string scenarioDir = Scenario::getScenarioDir(dirList, scenario); + + vector results; + findDirs(config.getPathListForType(ptTilesets, scenarioDir), results); + if (results.empty()) { + throw megaglest_runtime_error("No tile-sets were found!"); + } + tilesetFiles = results; + std::for_each(results.begin(), results.end(), FormatString()); + + listBoxTileset.setItems(results); + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + throw megaglest_runtime_error(szBuf); + } } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/menu/menu_state_custom_game.h b/source/glest_game/menu/menu_state_custom_game.h index 5f67c5e96..b0643a595 100644 --- a/source/glest_game/menu/menu_state_custom_game.h +++ b/source/glest_game/menu/menu_state_custom_game.h @@ -12,329 +12,334 @@ #ifndef _GLEST_GAME_MENUSTATECUSTOMGAME_H_ #define _GLEST_GAME_MENUSTATECUSTOMGAME_H_ -#include "main_menu.h" #include "chat_manager.h" -#include "simple_threads.h" -#include "map_preview.h" #include "common_scoped_ptr.h" #include "leak_dumper.h" +#include "main_menu.h" +#include "map_preview.h" +#include "simple_threads.h" using namespace Shared::Map; -namespace Shared { namespace Graphics { - class VideoPlayer; -}} +namespace Shared { +namespace Graphics { +class VideoPlayer; +} +} // namespace Shared -namespace Glest { namespace Game { +namespace Glest { +namespace Game { class SwitchSetupRequest; class ServerInterface; class TechTree; -enum ParentMenuState { - pNewGame, - pMasterServer, - pLanGame -}; +enum ParentMenuState { pNewGame, pMasterServer, pLanGame }; // =============================== // class MenuStateCustomGame // =============================== -class MenuStateCustomGame : public MenuState, public SimpleTaskCallbackInterface { +class MenuStateCustomGame : public MenuState, + public SimpleTaskCallbackInterface { private: - GraphicButton buttonReturn; - GraphicButton buttonPlayNow; - GraphicLabel labelControl; - GraphicLabel labelRMultiplier; - GraphicLabel labelFaction; - GraphicLabel labelTeam; - GraphicLabel labelMap; - GraphicLabel labelFogOfWar; - GraphicLabel labelTechTree; - GraphicLabel labelTileset; - GraphicLabel labelMapInfo; - GraphicLabel labelGameName; - - GraphicComboBox comboBoxMap; - GraphicListBox listBoxFogOfWar; - GraphicListBox listBoxTechTree; - GraphicListBox listBoxTileset; - - vector mapFiles; - vector playerSortedMaps[GameConstants::maxPlayers+1]; - vector formattedPlayerSortedMaps[GameConstants::maxPlayers+1]; - vector techTreeFiles; - vector tilesetFiles; - vector factionFiles; - GraphicLabel labelPlayers[GameConstants::maxPlayers]; - GraphicLabel labelPlayerNames[GameConstants::maxPlayers]; - GraphicListBox listBoxControls[GameConstants::maxPlayers]; - GraphicButton buttonBlockPlayers[GameConstants::maxPlayers]; - GraphicListBox listBoxRMultiplier[GameConstants::maxPlayers]; - GraphicListBox listBoxFactions[GameConstants::maxPlayers]; - GraphicListBox listBoxTeams[GameConstants::maxPlayers]; - GraphicLabel labelNetStatus[GameConstants::maxPlayers]; - MapInfo mapInfo; - - GraphicButton buttonClearBlockedPlayers; - - GraphicLabel labelPublishServer; - GraphicCheckBox checkBoxPublishServer; - - GraphicMessageBox mainMessageBox; - int mainMessageBoxState; - - GraphicLabel labelNetworkPauseGameForLaggedClients; - GraphicCheckBox checkBoxNetworkPauseGameForLaggedClients; - - GraphicLabel labelMapFilter; - GraphicListBox listBoxMapFilter; - - GraphicLabel labelAdvanced; - GraphicCheckBox checkBoxAdvanced; - - GraphicLabel labelAllowObservers; - GraphicCheckBox checkBoxAllowObservers; - - GraphicLabel *activeInputLabel; - - GraphicLabel labelPlayerStatus[GameConstants::maxPlayers]; - GraphicListBox listBoxPlayerStatus; - - GraphicLabel labelEnableSwitchTeamMode; - GraphicCheckBox checkBoxEnableSwitchTeamMode; - - GraphicLabel labelAISwitchTeamAcceptPercent; - GraphicListBox listBoxAISwitchTeamAcceptPercent; - GraphicLabel labelFallbackCpuMultiplier; - GraphicListBox listBoxFallbackCpuMultiplier; - - GraphicLabel labelAllowInGameJoinPlayer; - GraphicCheckBox checkBoxAllowInGameJoinPlayer; - - GraphicLabel labelAllowTeamUnitSharing; - GraphicCheckBox checkBoxAllowTeamUnitSharing; - - GraphicLabel labelAllowTeamResourceSharing; - GraphicCheckBox checkBoxAllowTeamResourceSharing; - - - GraphicLabel labelAllowNativeLanguageTechtree; - GraphicCheckBox checkBoxAllowNativeLanguageTechtree; - - GraphicButton buttonShowLanInfo; - - GraphicButton buttonSaveSetup; - GraphicLabel labelSaveSetupName; - GraphicButton buttonLoadSetup; - GraphicButton buttonDeleteSetup; - GraphicComboBox comboBoxLoadSetup; - string savedSetupsDir; - vector savedSetupFilenames; - - GraphicCheckBox checkBoxScenario; - GraphicLabel labelScenario; - GraphicListBox listBoxScenario; - - vector scenarioFiles; - ScenarioInfo scenarioInfo; - vector dirList; - string autoloadScenarioName; - time_t previewLoadDelayTimer; - bool needToLoadTextures; - bool enableScenarioTexturePreview; - Texture2D *scenarioLogoTexture; - - bool needToSetChangedGameSettings; - time_t lastSetChangedGameSettings; - time_t lastMasterserverPublishing; - time_t lastNetworkPing; - time_t mapPublishingDelayTimer; - time_t lastTechtreeChange; + GraphicButton buttonReturn; + GraphicButton buttonPlayNow; + GraphicLabel labelControl; + GraphicLabel labelRMultiplier; + GraphicLabel labelFaction; + GraphicLabel labelTeam; + GraphicLabel labelMap; + GraphicLabel labelFogOfWar; + GraphicLabel labelTechTree; + GraphicLabel labelTileset; + GraphicLabel labelMapInfo; + GraphicLabel labelGameName; + + GraphicComboBox comboBoxMap; + GraphicListBox listBoxFogOfWar; + GraphicListBox listBoxTechTree; + GraphicListBox listBoxTileset; + + vector mapFiles; + vector playerSortedMaps[GameConstants::maxPlayers + 1]; + vector formattedPlayerSortedMaps[GameConstants::maxPlayers + 1]; + vector techTreeFiles; + vector tilesetFiles; + vector factionFiles; + GraphicLabel labelPlayers[GameConstants::maxPlayers]; + GraphicLabel labelPlayerNames[GameConstants::maxPlayers]; + GraphicListBox listBoxControls[GameConstants::maxPlayers]; + GraphicButton buttonBlockPlayers[GameConstants::maxPlayers]; + GraphicListBox listBoxRMultiplier[GameConstants::maxPlayers]; + GraphicListBox listBoxFactions[GameConstants::maxPlayers]; + GraphicListBox listBoxTeams[GameConstants::maxPlayers]; + GraphicLabel labelNetStatus[GameConstants::maxPlayers]; + MapInfo mapInfo; + + GraphicButton buttonClearBlockedPlayers; + + GraphicLabel labelPublishServer; + GraphicCheckBox checkBoxPublishServer; + + GraphicMessageBox mainMessageBox; + int mainMessageBoxState; + + GraphicLabel labelNetworkPauseGameForLaggedClients; + GraphicCheckBox checkBoxNetworkPauseGameForLaggedClients; + + GraphicLabel labelMapFilter; + GraphicListBox listBoxMapFilter; + + GraphicLabel labelAdvanced; + GraphicCheckBox checkBoxAdvanced; + + GraphicLabel labelAllowObservers; + GraphicCheckBox checkBoxAllowObservers; + + GraphicLabel *activeInputLabel; + + GraphicLabel labelPlayerStatus[GameConstants::maxPlayers]; + GraphicListBox listBoxPlayerStatus; + + GraphicLabel labelEnableSwitchTeamMode; + GraphicCheckBox checkBoxEnableSwitchTeamMode; + + GraphicLabel labelAISwitchTeamAcceptPercent; + GraphicListBox listBoxAISwitchTeamAcceptPercent; + GraphicLabel labelFallbackCpuMultiplier; + GraphicListBox listBoxFallbackCpuMultiplier; + + GraphicLabel labelAllowInGameJoinPlayer; + GraphicCheckBox checkBoxAllowInGameJoinPlayer; + + GraphicLabel labelAllowTeamUnitSharing; + GraphicCheckBox checkBoxAllowTeamUnitSharing; + + GraphicLabel labelAllowTeamResourceSharing; + GraphicCheckBox checkBoxAllowTeamResourceSharing; + + GraphicLabel labelAllowNativeLanguageTechtree; + GraphicCheckBox checkBoxAllowNativeLanguageTechtree; + + GraphicButton buttonShowLanInfo; + + GraphicButton buttonSaveSetup; + GraphicLabel labelSaveSetupName; + GraphicButton buttonLoadSetup; + GraphicButton buttonDeleteSetup; + GraphicComboBox comboBoxLoadSetup; + string savedSetupsDir; + vector savedSetupFilenames; + + GraphicCheckBox checkBoxScenario; + GraphicLabel labelScenario; + GraphicListBox listBoxScenario; + + vector scenarioFiles; + ScenarioInfo scenarioInfo; + vector dirList; + string autoloadScenarioName; + time_t previewLoadDelayTimer; + bool needToLoadTextures; + bool enableScenarioTexturePreview; + Texture2D *scenarioLogoTexture; + + bool needToSetChangedGameSettings; + time_t lastSetChangedGameSettings; + time_t lastMasterserverPublishing; + time_t lastNetworkPing; + time_t mapPublishingDelayTimer; + time_t lastTechtreeChange; - bool needToPublishDelayed; + bool needToPublishDelayed; - bool headlessHasConnectedPlayer; + bool headlessHasConnectedPlayer; - bool needToRepublishToMasterserver; - bool needToBroadcastServerSettings; - std::map publishToServerInfo; - SimpleTaskThread *publishToMasterserverThread; - SimpleTaskThread *publishToClientsThread; + bool needToRepublishToMasterserver; + bool needToBroadcastServerSettings; + std::map publishToServerInfo; + SimpleTaskThread *publishToMasterserverThread; + SimpleTaskThread *publishToClientsThread; - ParentMenuState parentMenuState; - int soundConnectionCount; + ParentMenuState parentMenuState; + int soundConnectionCount; - time_t tMasterserverErrorElapsed; - bool showMasterserverError; - string masterServererErrorToShow; + time_t tMasterserverErrorElapsed; + bool showMasterserverError; + string masterServererErrorToShow; - bool showGeneralError; - string generalErrorToShow; - bool serverInitError; + bool showGeneralError; + string generalErrorToShow; + bool serverInitError; - //Console console; - ChatManager chatManager; - bool showFullConsole; + // Console console; + ChatManager chatManager; + bool showFullConsole; - string lastMapDataSynchError; - string lastTileDataSynchError; - string lastTechtreeDataSynchError; + string lastMapDataSynchError; + string lastTileDataSynchError; + string lastTechtreeDataSynchError; - string defaultPlayerName; - int8 switchSetupRequestFlagType; + string defaultPlayerName; + int8 switchSetupRequestFlagType; - bool enableFactionTexturePreview; - bool enableMapPreview; + bool enableFactionTexturePreview; + bool enableMapPreview; - string currentTechName_factionPreview; - string currentFactionName_factionPreview; - string currentFactionLogo; - Texture2D *factionTexture; - ::Shared::Graphics::VideoPlayer *factionVideo; - bool factionVideoSwitchedOffVolume; + string currentTechName_factionPreview; + string currentFactionName_factionPreview; + string currentFactionLogo; + Texture2D *factionTexture; + ::Shared::Graphics::VideoPlayer *factionVideo; + bool factionVideoSwitchedOffVolume; - MapPreview mapPreview; - Texture2D *mapPreviewTexture; - bool zoomedMap; - int render_mapPreviewTexture_X; - int render_mapPreviewTexture_Y; - int render_mapPreviewTexture_W; - int render_mapPreviewTexture_H; + MapPreview mapPreview; + Texture2D *mapPreviewTexture; + bool zoomedMap; + int render_mapPreviewTexture_X; + int render_mapPreviewTexture_Y; + int render_mapPreviewTexture_W; + int render_mapPreviewTexture_H; - bool autostart; - GameSettings *autoStartSettings; + bool autostart; + GameSettings *autoStartSettings; - std::map lastSelectedTeamIndex; - float rMultiplierOffset; - bool hasCheckedForUPNP; + std::map lastSelectedTeamIndex; + float rMultiplierOffset; + bool hasCheckedForUPNP; - string lastCheckedCRCTilesetName; - string lastCheckedCRCTechtreeName; - string lastCheckedCRCMapName; + string lastCheckedCRCTilesetName; + string lastCheckedCRCTechtreeName; + string lastCheckedCRCMapName; - string lastRecalculatedCRCTilesetName; - string lastRecalculatedCRCTechtreeName; + string lastRecalculatedCRCTilesetName; + string lastRecalculatedCRCTechtreeName; - time_t initTime; + time_t initTime; - uint32 lastCheckedCRCTilesetValue; - uint32 lastCheckedCRCTechtreeValue; - uint32 lastCheckedCRCMapValue; - vector > factionCRCList; + uint32 lastCheckedCRCTilesetValue; + uint32 lastCheckedCRCTechtreeValue; + uint32 lastCheckedCRCMapValue; + vector> factionCRCList; - bool forceWaitForShutdown; - bool headlessServerMode; - bool masterserverModeMinimalResources; - int lastMasterServerSettingsUpdateCount; + bool forceWaitForShutdown; + bool headlessServerMode; + bool masterserverModeMinimalResources; + int lastMasterServerSettingsUpdateCount; - auto_ptr techTree; + auto_ptr techTree; - string gameUUID; + string gameUUID; - int lastGameSettingsreceivedCount; + int lastGameSettingsreceivedCount; - string lastPreviewedMapFile; + string lastPreviewedMapFile; public: - MenuStateCustomGame(Program *program, MainMenu *mainMenu , - bool openNetworkSlots= false, ParentMenuState parentMenuState=pNewGame, - bool autostart=false,GameSettings *settings=NULL,bool masterserverMode=false, - string autoloadScenarioName=""); - virtual ~MenuStateCustomGame(); - - void mouseClick(int x, int y, MouseButton mouseButton); - void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; - void mouseMove(int x, int y, const MouseState *mouseState); - void eventMouseWheel(int x, int y,int zDelta); - void render(); - void update(); - - virtual bool textInput(std::string text); - virtual void keyDown(SDL_KeyboardEvent key); - virtual void keyPress(SDL_KeyboardEvent c); - virtual void keyUp(SDL_KeyboardEvent key); - - - virtual void simpleTask(BaseThread *callingThread,void *userdata); - virtual void setupTask(BaseThread *callingThread,void *userdata); - virtual void shutdownTask(BaseThread *callingThread,void *userdata); - static void setupTaskStatic(BaseThread *callingThread); - static void shutdownTaskStatic(BaseThread *callingThread); - - virtual bool isInSpecialKeyCaptureEvent(); - virtual bool isMasterserverMode() const; - - virtual bool isVideoPlaying(); -private: + MenuStateCustomGame(Program *program, MainMenu *mainMenu, + bool openNetworkSlots = false, + ParentMenuState parentMenuState = pNewGame, + bool autostart = false, GameSettings *settings = NULL, + bool masterserverMode = false, + string autoloadScenarioName = ""); + virtual ~MenuStateCustomGame(); + + void mouseClick(int x, int y, MouseButton mouseButton); + void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; + void mouseMove(int x, int y, const MouseState *mouseState); + void eventMouseWheel(int x, int y, int zDelta); + void render(); + void update(); + + virtual bool textInput(std::string text); + virtual void keyDown(SDL_KeyboardEvent key); + virtual void keyPress(SDL_KeyboardEvent c); + virtual void keyUp(SDL_KeyboardEvent key); + + virtual void simpleTask(BaseThread *callingThread, void *userdata); + virtual void setupTask(BaseThread *callingThread, void *userdata); + virtual void shutdownTask(BaseThread *callingThread, void *userdata); + static void setupTaskStatic(BaseThread *callingThread); + static void shutdownTaskStatic(BaseThread *callingThread); + + virtual bool isInSpecialKeyCaptureEvent(); + virtual bool isMasterserverMode() const; + + virtual bool isVideoPlaying(); - void setCRCsToSettingsInternal(GameSettings *gameSettings, bool forceRefresh); - void setCRCsToGameSettings(GameSettings *gameSettings); - void setRefreshedCrcToGameSettings(GameSettings *gameSettings); - void setSmallFont(GraphicLabel l); - void lastPlayerDisconnected(); - bool hasNetworkGameSettings(); - void copyToGameSettings(GameSettings *gameSettings, bool forceCloseUnusedSlots=false); - void loadMapInfo(string file, MapInfo *mapInfo,bool loadMapPreview, bool doPlayerSetup); - void cleanupMapPreviewTexture(); - - void updateControlers(); - void closeUnusedSlots(); - void updateNetworkSlots(); - void publishToMasterserver(); - void returnToParentMenu(); - void showMessageBox(const string &text, const string &header, bool toggle); - - void switchToNextMapGroup(const int direction); - void updateAllResourceMultiplier(); - void updateResourceMultiplier(const int index); - string getCurrentMapFile(); - string getPreselectedMapFile(); - - void setActiveInputLabel(GraphicLabel *newLable); - string getHumanPlayerName(int index=-1); - - void loadFactionTexture(string filepath); - - void saveGameSettings(std::string fileName); - bool loadGameSettingsFromFile(GameSettings *gameSettings,std::string fileName); - bool loadGameSettings(const std::string &fileName); - void RestoreLastGameSettings(); - void PlayNow(bool saveGame); - - void SetActivePlayerNameEditor(); - void cleanup(); - - int32 getNetworkPlayerStatus(); - void setupUIFromGameSettings(const GameSettings &gameSettings); - - void switchSetupForSlots(SwitchSetupRequest **switchSetupRequests, - ServerInterface *& serverInterface, int startIndex, int endIndex, - bool onlyNetworkUnassigned); - - string createGameName(string controllingPlayer=""); - void reloadUI(); - void loadScenarioInfo(string file, ScenarioInfo *scenarioInfo); - void processScenario(); - void SetupUIForScenarios(); - int setupMapList(string scenario); - void loadSavedSetupNames(); - int setupTechList(string scenario, bool forceLoad=false); - void reloadFactions(bool keepExistingSelectedItem, string scenario); - void setupTilesetList(string scenario); - void setSlotHuman(int i); - - void initFactionPreview(const GameSettings *gameSettings); - - bool checkNetworkPlayerDataSynch(bool checkMapCRC,bool checkTileSetCRC, bool checkTechTreeCRC); - - void cleanupThread(SimpleTaskThread **thread); - void simpleTaskForMasterServer(BaseThread *callingThread); - void simpleTaskForClients(BaseThread *callingThread); - void KeepCurrentHumanPlayerSlots(GameSettings &gameSettings); +private: + void setCRCsToSettingsInternal(GameSettings *gameSettings, bool forceRefresh); + void setCRCsToGameSettings(GameSettings *gameSettings); + void setRefreshedCrcToGameSettings(GameSettings *gameSettings); + void setSmallFont(GraphicLabel l); + void lastPlayerDisconnected(); + bool hasNetworkGameSettings(); + void copyToGameSettings(GameSettings *gameSettings, + bool forceCloseUnusedSlots = false); + void loadMapInfo(string file, MapInfo *mapInfo, bool loadMapPreview, + bool doPlayerSetup); + void cleanupMapPreviewTexture(); + + void updateControlers(); + void closeUnusedSlots(); + void updateNetworkSlots(); + void publishToMasterserver(); + void returnToParentMenu(); + void showMessageBox(const string &text, const string &header, bool toggle); + + void switchToNextMapGroup(const int direction); + void updateAllResourceMultiplier(); + void updateResourceMultiplier(const int index); + string getCurrentMapFile(); + string getPreselectedMapFile(); + + void setActiveInputLabel(GraphicLabel *newLable); + string getHumanPlayerName(int index = -1); + + void loadFactionTexture(string filepath); + + void saveGameSettings(std::string fileName); + bool loadGameSettingsFromFile(GameSettings *gameSettings, + std::string fileName); + bool loadGameSettings(const std::string &fileName); + void RestoreLastGameSettings(); + void PlayNow(bool saveGame); + + void SetActivePlayerNameEditor(); + void cleanup(); + + int32 getNetworkPlayerStatus(); + void setupUIFromGameSettings(const GameSettings &gameSettings); + + void switchSetupForSlots(SwitchSetupRequest **switchSetupRequests, + ServerInterface *&serverInterface, int startIndex, + int endIndex, bool onlyNetworkUnassigned); + + string createGameName(string controllingPlayer = ""); + void reloadUI(); + void loadScenarioInfo(string file, ScenarioInfo *scenarioInfo); + void processScenario(); + void SetupUIForScenarios(); + int setupMapList(string scenario); + void loadSavedSetupNames(); + int setupTechList(string scenario, bool forceLoad = false); + void reloadFactions(bool keepExistingSelectedItem, string scenario); + void setupTilesetList(string scenario); + void setSlotHuman(int i); + + void initFactionPreview(const GameSettings *gameSettings); + + bool checkNetworkPlayerDataSynch(bool checkMapCRC, bool checkTileSetCRC, + bool checkTechTreeCRC); + + void cleanupThread(SimpleTaskThread **thread); + void simpleTaskForMasterServer(BaseThread *callingThread); + void simpleTaskForClients(BaseThread *callingThread); + void KeepCurrentHumanPlayerSlots(GameSettings &gameSettings); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/menu/menu_state_graphic_info.cpp b/source/glest_game/menu/menu_state_graphic_info.cpp index 25742b220..5c9fb3e1f 100644 --- a/source/glest_game/menu/menu_state_graphic_info.cpp +++ b/source/glest_game/menu/menu_state_graphic_info.cpp @@ -11,147 +11,163 @@ #include "menu_state_graphic_info.h" -#include "renderer.h" -#include "sound_renderer.h" +#include "config.h" #include "core_data.h" +#include "leak_dumper.h" #include "menu_state_options_graphics.h" -#include "config.h" #include "opengl.h" -#include "leak_dumper.h" +#include "renderer.h" +#include "sound_renderer.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class MenuStateGraphicInfo // ===================================================== -MenuStateGraphicInfo::MenuStateGraphicInfo(Program *program, MainMenu *mainMenu): - MenuState(program, mainMenu, "info") -{ - Lang &lang= Lang::getInstance(); - - containerName = "GraphicInfo"; - buttonReturn.registerGraphicComponent(containerName,"buttonReturn"); - buttonReturn.init(650, 575, 125); - - buttonReturn.setText(lang.getString("Return")); - - labelInfo.registerGraphicComponent(containerName,"labelInfo"); - labelInfo.init(0, 730); - - labelMoreInfo.registerGraphicComponent(containerName,"labelMoreInfo"); - labelMoreInfo.init(0, 555); - labelMoreInfo.setFont(CoreData::getInstance().getDisplayFontSmall()); - labelMoreInfo.setFont3D(CoreData::getInstance().getDisplayFontSmall3D()); - - labelInternalInfo.registerGraphicComponent(containerName,"labelInternalInfo"); - labelInternalInfo.init(300, 730); - labelInternalInfo.setFont(CoreData::getInstance().getDisplayFontSmall()); - labelInternalInfo.setFont3D(CoreData::getInstance().getDisplayFontSmall3D()); - - GraphicComponent::applyAllCustomProperties(containerName); - - Renderer &renderer= Renderer::getInstance(); - - string glInfo= renderer.getGlInfo(); - string glMoreInfo= renderer.getGlMoreInfo(); - labelInfo.setText(glInfo); - labelMoreInfo.setText(glMoreInfo); - - string strInternalInfo = ""; - strInternalInfo += "VBOSupported: " + boolToStr(getVBOSupported()); - if(getenv("MEGAGLEST_FONT") != NULL) { - char *tryFont = getenv("MEGAGLEST_FONT"); - strInternalInfo += "\nMEGAGLEST_FONT: " + string(tryFont); - } - strInternalInfo += "\nforceLegacyFonts: " + boolToStr(Font::forceLegacyFonts); - strInternalInfo += "\nrenderText3DEnabled: " + boolToStr(Renderer::renderText3DEnabled); - strInternalInfo += "\nuseTextureCompression: " + boolToStr(Texture::useTextureCompression); - strInternalInfo += "\nfontIsRightToLeft: " + boolToStr(Font::fontIsRightToLeft); - strInternalInfo += "\nscaleFontValue: " + floatToStr(Font::scaleFontValue); - strInternalInfo += "\nscaleFontValueCenterHFactor: " + floatToStr(Font::scaleFontValueCenterHFactor); - strInternalInfo += "\nlangHeightText: " + Font::langHeightText; - strInternalInfo += "\nAllowAltEnterFullscreenToggle: " + boolToStr(Window::getAllowAltEnterFullscreenToggle()); - strInternalInfo += "\nTryVSynch: " + boolToStr(Window::getTryVSynch()); - strInternalInfo += "\nVERBOSE_MODE_ENABLED: " + boolToStr(SystemFlags::VERBOSE_MODE_ENABLED); - labelInternalInfo.setText(strInternalInfo); +MenuStateGraphicInfo::MenuStateGraphicInfo(Program *program, MainMenu *mainMenu) + : MenuState(program, mainMenu, "info") { + Lang &lang = Lang::getInstance(); + + containerName = "GraphicInfo"; + buttonReturn.registerGraphicComponent(containerName, "buttonReturn"); + buttonReturn.init(650, 575, 125); + + buttonReturn.setText(lang.getString("Return")); + + labelInfo.registerGraphicComponent(containerName, "labelInfo"); + labelInfo.init(0, 730); + + labelMoreInfo.registerGraphicComponent(containerName, "labelMoreInfo"); + labelMoreInfo.init(0, 555); + labelMoreInfo.setFont(CoreData::getInstance().getDisplayFontSmall()); + labelMoreInfo.setFont3D(CoreData::getInstance().getDisplayFontSmall3D()); + + labelInternalInfo.registerGraphicComponent(containerName, + "labelInternalInfo"); + labelInternalInfo.init(300, 730); + labelInternalInfo.setFont(CoreData::getInstance().getDisplayFontSmall()); + labelInternalInfo.setFont3D(CoreData::getInstance().getDisplayFontSmall3D()); + + GraphicComponent::applyAllCustomProperties(containerName); + + Renderer &renderer = Renderer::getInstance(); + + string glInfo = renderer.getGlInfo(); + string glMoreInfo = renderer.getGlMoreInfo(); + labelInfo.setText(glInfo); + labelMoreInfo.setText(glMoreInfo); + + string strInternalInfo = ""; + strInternalInfo += "VBOSupported: " + boolToStr(getVBOSupported()); + if (getenv("MEGAGLEST_FONT") != NULL) { + char *tryFont = getenv("MEGAGLEST_FONT"); + strInternalInfo += "\nMEGAGLEST_FONT: " + string(tryFont); + } + strInternalInfo += "\nforceLegacyFonts: " + boolToStr(Font::forceLegacyFonts); + strInternalInfo += + "\nrenderText3DEnabled: " + boolToStr(Renderer::renderText3DEnabled); + strInternalInfo += + "\nuseTextureCompression: " + boolToStr(Texture::useTextureCompression); + strInternalInfo += + "\nfontIsRightToLeft: " + boolToStr(Font::fontIsRightToLeft); + strInternalInfo += "\nscaleFontValue: " + floatToStr(Font::scaleFontValue); + strInternalInfo += "\nscaleFontValueCenterHFactor: " + + floatToStr(Font::scaleFontValueCenterHFactor); + strInternalInfo += "\nlangHeightText: " + Font::langHeightText; + strInternalInfo += "\nAllowAltEnterFullscreenToggle: " + + boolToStr(Window::getAllowAltEnterFullscreenToggle()); + strInternalInfo += "\nTryVSynch: " + boolToStr(Window::getTryVSynch()); + strInternalInfo += + "\nVERBOSE_MODE_ENABLED: " + boolToStr(SystemFlags::VERBOSE_MODE_ENABLED); + labelInternalInfo.setText(strInternalInfo); } void MenuStateGraphicInfo::reloadUI() { - Lang &lang= Lang::getInstance(); - - console.resetFonts(); - buttonReturn.setText(lang.getString("Return")); - - labelMoreInfo.setFont(CoreData::getInstance().getDisplayFontSmall()); - labelMoreInfo.setFont3D(CoreData::getInstance().getDisplayFontSmall3D()); - - labelInternalInfo.setFont(CoreData::getInstance().getDisplayFontSmall()); - labelInternalInfo.setFont3D(CoreData::getInstance().getDisplayFontSmall3D()); - - Renderer &renderer= Renderer::getInstance(); - - string glInfo= renderer.getGlInfo(); - string glMoreInfo= renderer.getGlMoreInfo(); - labelInfo.setText(glInfo); - labelMoreInfo.setText(glMoreInfo); - - string strInternalInfo = ""; - strInternalInfo += "VBOSupported: " + boolToStr(getVBOSupported()); - if(getenv("MEGAGLEST_FONT") != NULL) { - char *tryFont = getenv("MEGAGLEST_FONT"); - strInternalInfo += "\nMEGAGLEST_FONT: " + string(tryFont); - } - strInternalInfo += "\nforceLegacyFonts: " + boolToStr(Font::forceLegacyFonts); - strInternalInfo += "\nrenderText3DEnabled: " + boolToStr(Renderer::renderText3DEnabled); - strInternalInfo += "\nuseTextureCompression: " + boolToStr(Texture::useTextureCompression); - strInternalInfo += "\nfontIsRightToLeft: " + boolToStr(Font::fontIsRightToLeft); - strInternalInfo += "\nscaleFontValue: " + floatToStr(Font::scaleFontValue); - strInternalInfo += "\nscaleFontValueCenterHFactor: " + floatToStr(Font::scaleFontValueCenterHFactor); - strInternalInfo += "\nlangHeightText: " + Font::langHeightText; - strInternalInfo += "\nAllowAltEnterFullscreenToggle: " + boolToStr(Window::getAllowAltEnterFullscreenToggle()); - strInternalInfo += "\nTryVSynch: " + boolToStr(Window::getTryVSynch()); - strInternalInfo += "\nVERBOSE_MODE_ENABLED: " + boolToStr(SystemFlags::VERBOSE_MODE_ENABLED); - labelInternalInfo.setText(strInternalInfo); - - GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); + Lang &lang = Lang::getInstance(); + + console.resetFonts(); + buttonReturn.setText(lang.getString("Return")); + + labelMoreInfo.setFont(CoreData::getInstance().getDisplayFontSmall()); + labelMoreInfo.setFont3D(CoreData::getInstance().getDisplayFontSmall3D()); + + labelInternalInfo.setFont(CoreData::getInstance().getDisplayFontSmall()); + labelInternalInfo.setFont3D(CoreData::getInstance().getDisplayFontSmall3D()); + + Renderer &renderer = Renderer::getInstance(); + + string glInfo = renderer.getGlInfo(); + string glMoreInfo = renderer.getGlMoreInfo(); + labelInfo.setText(glInfo); + labelMoreInfo.setText(glMoreInfo); + + string strInternalInfo = ""; + strInternalInfo += "VBOSupported: " + boolToStr(getVBOSupported()); + if (getenv("MEGAGLEST_FONT") != NULL) { + char *tryFont = getenv("MEGAGLEST_FONT"); + strInternalInfo += "\nMEGAGLEST_FONT: " + string(tryFont); + } + strInternalInfo += "\nforceLegacyFonts: " + boolToStr(Font::forceLegacyFonts); + strInternalInfo += + "\nrenderText3DEnabled: " + boolToStr(Renderer::renderText3DEnabled); + strInternalInfo += + "\nuseTextureCompression: " + boolToStr(Texture::useTextureCompression); + strInternalInfo += + "\nfontIsRightToLeft: " + boolToStr(Font::fontIsRightToLeft); + strInternalInfo += "\nscaleFontValue: " + floatToStr(Font::scaleFontValue); + strInternalInfo += "\nscaleFontValueCenterHFactor: " + + floatToStr(Font::scaleFontValueCenterHFactor); + strInternalInfo += "\nlangHeightText: " + Font::langHeightText; + strInternalInfo += "\nAllowAltEnterFullscreenToggle: " + + boolToStr(Window::getAllowAltEnterFullscreenToggle()); + strInternalInfo += "\nTryVSynch: " + boolToStr(Window::getTryVSynch()); + strInternalInfo += + "\nVERBOSE_MODE_ENABLED: " + boolToStr(SystemFlags::VERBOSE_MODE_ENABLED); + labelInternalInfo.setText(strInternalInfo); + + GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); } -void MenuStateGraphicInfo::mouseClick(int x, int y, MouseButton mouseButton){ - CoreData &coreData= CoreData::getInstance(); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); +void MenuStateGraphicInfo::mouseClick(int x, int y, MouseButton mouseButton) { + CoreData &coreData = CoreData::getInstance(); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); - if(buttonReturn.mouseClick(x,y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - mainMenu->setState(new MenuStateOptionsGraphics(program, mainMenu)); - } + if (buttonReturn.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + mainMenu->setState(new MenuStateOptionsGraphics(program, mainMenu)); + } } -void MenuStateGraphicInfo::mouseMove(int x, int y, const MouseState *ms){ - buttonReturn.mouseMove(x, y); +void MenuStateGraphicInfo::mouseMove(int x, int y, const MouseState *ms) { + buttonReturn.mouseMove(x, y); } -void MenuStateGraphicInfo::render(){ +void MenuStateGraphicInfo::render() { - Renderer &renderer= Renderer::getInstance(); - //Lang &lang= Lang::getInstance(); + Renderer &renderer = Renderer::getInstance(); + // Lang &lang= Lang::getInstance(); - renderer.renderButton(&buttonReturn); - renderer.renderLabel(&labelInfo); - renderer.renderLabel(&labelInternalInfo); - renderer.renderLabel(&labelMoreInfo); + renderer.renderButton(&buttonReturn); + renderer.renderLabel(&labelInfo); + renderer.renderLabel(&labelInternalInfo); + renderer.renderLabel(&labelMoreInfo); - renderer.renderConsole(&console); + renderer.renderConsole(&console); } void MenuStateGraphicInfo::keyDown(SDL_KeyboardEvent key) { - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - //if(key == configKeys.getCharKey("SaveGUILayout")) { - if(isKeyPressed(configKeys.getSDLKey("SaveGUILayout"),key) == true) { - GraphicComponent::saveAllCustomProperties(containerName); - //Lang &lang= Lang::getInstance(); - //console.addLine(lang.getString("GUILayoutSaved") + " [" + (saved ? lang.getString("Yes") : lang.getString("No"))+ "]"); - } + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + // if(key == configKeys.getCharKey("SaveGUILayout")) { + if (isKeyPressed(configKeys.getSDLKey("SaveGUILayout"), key) == true) { + GraphicComponent::saveAllCustomProperties(containerName); + // Lang &lang= Lang::getInstance(); + // console.addLine(lang.getString("GUILayoutSaved") + " [" + (saved ? + // lang.getString("Yes") : lang.getString("No"))+ "]"); + } } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/menu/menu_state_graphic_info.h b/source/glest_game/menu/menu_state_graphic_info.h index 2d4b1e9f8..5980bd92e 100644 --- a/source/glest_game/menu/menu_state_graphic_info.h +++ b/source/glest_game/menu/menu_state_graphic_info.h @@ -3,49 +3,51 @@ // // Copyright (C) 2001-2005 Martio Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== #ifndef _GLEST_GAME_MENUSTATEGRAPHICINFO_H_ #define _GLEST_GAME_MENUSTATEGRAPHICINFO_H_ -#include "main_menu.h" #include "leak_dumper.h" +#include "main_menu.h" using namespace Shared::Graphics::Gl; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // =============================== -// class MenuStateGraphicInfo +// class MenuStateGraphicInfo // =============================== -class MenuStateGraphicInfo: public MenuState { +class MenuStateGraphicInfo : public MenuState { private: - GraphicButton buttonReturn; - GraphicLabel labelInfo; - GraphicLabel labelMoreInfo; + GraphicButton buttonReturn; + GraphicLabel labelInfo; + GraphicLabel labelMoreInfo; - GraphicLabel labelInternalInfo; + GraphicLabel labelInternalInfo; - //string glInfo; - //string glMoreInfo; + // string glInfo; + // string glMoreInfo; public: - MenuStateGraphicInfo(Program *program, MainMenu *mainMenu); + MenuStateGraphicInfo(Program *program, MainMenu *mainMenu); - void mouseClick(int x, int y, MouseButton mouseButton); - void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; - void mouseMove(int x, int y, const MouseState *mouseState); - void render(); - virtual void keyDown(SDL_KeyboardEvent key); + void mouseClick(int x, int y, MouseButton mouseButton); + void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; + void mouseMove(int x, int y, const MouseState *mouseState); + void render(); + virtual void keyDown(SDL_KeyboardEvent key); - virtual void reloadUI(); + virtual void reloadUI(); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/menu/menu_state_join_game.cpp b/source/glest_game/menu/menu_state_join_game.cpp index dda936bf0..870bba08d 100644 --- a/source/glest_game/menu/menu_state_join_game.cpp +++ b/source/glest_game/menu/menu_state_join_game.cpp @@ -11,25 +11,26 @@ #include "menu_state_join_game.h" -#include "menu_state_connected_game.h" -#include "renderer.h" -#include "sound_renderer.h" -#include "core_data.h" +#include "client_interface.h" #include "config.h" -#include "menu_state_new_game.h" +#include "conversion.h" +#include "core_data.h" +#include "game.h" +#include "menu_state_connected_game.h" #include "menu_state_custom_game.h" +#include "menu_state_new_game.h" #include "metrics.h" #include "network_manager.h" #include "network_message.h" -#include "client_interface.h" -#include "conversion.h" -#include "game.h" -#include "string_utils.h" +#include "renderer.h" #include "socket.h" +#include "sound_renderer.h" +#include "string_utils.h" #include "leak_dumper.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { using namespace ::Shared::Util; @@ -37,796 +38,869 @@ using namespace ::Shared::Util; // class MenuStateJoinGame // =============================== -const int MenuStateJoinGame::newServerIndex= 0; -const int MenuStateJoinGame::newPrevServerIndex= 1; -const int MenuStateJoinGame::foundServersIndex= 2; - -const string MenuStateJoinGame::serverFileName= "servers.ini"; - -MenuStateJoinGame::MenuStateJoinGame(Program *program, MainMenu *mainMenu, bool *autoFindHost) : - MenuState(program, mainMenu, "join-game") { - CommonInit(false,Ip(),-1); +const int MenuStateJoinGame::newServerIndex = 0; +const int MenuStateJoinGame::newPrevServerIndex = 1; +const int MenuStateJoinGame::foundServersIndex = 2; - if(autoFindHost != NULL && *autoFindHost == true) { - //if(clientInterface->isConnected() == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); +const string MenuStateJoinGame::serverFileName = "servers.ini"; - buttonAutoFindServers.setEnabled(false); - buttonConnect.setEnabled(false); - - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface* clientInterface= networkManager.getClientInterface(); - clientInterface->discoverServers(this); - //} - } +MenuStateJoinGame::MenuStateJoinGame(Program *program, MainMenu *mainMenu, + bool *autoFindHost) + : MenuState(program, mainMenu, "join-game") { + CommonInit(false, Ip(), -1); + + if (autoFindHost != NULL && *autoFindHost == true) { + // if(clientInterface->isConnected() == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + buttonAutoFindServers.setEnabled(false); + buttonConnect.setEnabled(false); + + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + clientInterface->discoverServers(this); + //} + } } MenuStateJoinGame::MenuStateJoinGame(Program *program, MainMenu *mainMenu, - bool connect, Ip serverIp,int portNumberOverride) : - MenuState(program, mainMenu, "join-game") { - CommonInit(connect, serverIp,portNumberOverride); + bool connect, Ip serverIp, + int portNumberOverride) + : MenuState(program, mainMenu, "join-game") { + CommonInit(connect, serverIp, portNumberOverride); } -void MenuStateJoinGame::CommonInit(bool connect, Ip serverIp,int portNumberOverride) { - containerName = "JoinGame"; - abortAutoFind = false; - autoConnectToServer = false; - Lang &lang= Lang::getInstance(); - Config &config= Config::getInstance(); - NetworkManager &networkManager= NetworkManager::getInstance(); - networkManager.end(); - networkManager.init(nrClient); - - serversSavedFile = serverFileName; - - string serverListPath = config.getString("ServerListPath",""); - if(serverListPath != "") { - endPathWithSlash(serverListPath); +void MenuStateJoinGame::CommonInit(bool connect, Ip serverIp, + int portNumberOverride) { + containerName = "JoinGame"; + abortAutoFind = false; + autoConnectToServer = false; + Lang &lang = Lang::getInstance(); + Config &config = Config::getInstance(); + NetworkManager &networkManager = NetworkManager::getInstance(); + networkManager.end(); + networkManager.init(nrClient); + + serversSavedFile = serverFileName; + + string serverListPath = config.getString("ServerListPath", ""); + if (serverListPath != "") { + endPathWithSlash(serverListPath); + } + + string userData = config.getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + serversSavedFile = userData + serversSavedFile; + + if (fileExists(serversSavedFile) == true) { + servers.load(serversSavedFile); + } else if (fileExists(serverListPath + serverFileName) == true) { + servers.load(serverListPath + serverFileName); + } else if (fileExists(Properties::getApplicationPath() + serverFileName) == + true) { + servers.load(Properties::getApplicationPath() + serverFileName); + } else if (fileExists(serverFileName) == true) { + servers.load(serverFileName); + } + + // buttons + buttonReturn.registerGraphicComponent(containerName, "buttonReturn"); + buttonReturn.init(250, 300, 150); + buttonReturn.setText(lang.getString("Return")); + + buttonConnect.registerGraphicComponent(containerName, "buttonConnect"); + buttonConnect.init(425, 300, 150); + buttonConnect.setText(lang.getString("Connect")); + + buttonCreateGame.registerGraphicComponent(containerName, "buttonCreateGame"); + buttonCreateGame.init(600, 300, 150); + buttonCreateGame.setText(lang.getString("HostGame")); + + buttonAutoFindServers.registerGraphicComponent(containerName, + "buttonAutoFindServers"); + buttonAutoFindServers.init(360, 250, 280); + buttonAutoFindServers.setText(lang.getString("FindLANGames")); + buttonAutoFindServers.setEnabled(true); + + int labelXleft = 300; + int labelXright = 480; + + // server type label + labelServerType.registerGraphicComponent(containerName, "labelServerType"); + labelServerType.init(labelXleft, 490); + labelServerType.setText(lang.getString("ServerType")); + + // server type list box + listBoxServerType.registerGraphicComponent(containerName, + "listBoxServerType"); + listBoxServerType.init(labelXright, 490, 210); + listBoxServerType.pushBackItem(lang.getString("ServerTypeNew")); + listBoxServerType.pushBackItem(lang.getString("ServerTypePrevious")); + listBoxServerType.pushBackItem(lang.getString("ServerTypeFound")); + + // server label + labelServer.registerGraphicComponent(containerName, "labelServer"); + labelServer.init(labelXleft, 460); + labelServer.setText(lang.getString("Server")); + + // server listbox + listBoxServers.registerGraphicComponent(containerName, "listBoxServers"); + listBoxServers.init(labelXright, 460, 210); + for (int i = 0; i < servers.getPropertyCount(); ++i) { + listBoxServers.pushBackItem(servers.getKey(i)); + } + + // found servers listbox + listBoxFoundServers.registerGraphicComponent(containerName, + "listBoxFoundServers"); + listBoxFoundServers.init(labelXright, 460, 210); + + // server ip + labelServerIp.registerGraphicComponent(containerName, "labelServerIp"); + labelServerIp.setEditable(true); + labelServerIp.setMaxEditWidth(26); + labelServerIp.setMaxEditRenderWidth(210); + labelServerIp.init(labelXright, 460); + + // server port + labelServerPortLabel.registerGraphicComponent(containerName, + "labelServerPortLabel"); + labelServerPortLabel.init(labelXleft, 430); + labelServerPortLabel.setText(lang.getString("ServerPort")); + + labelServerPort.registerGraphicComponent(containerName, "labelServerPort"); + labelServerPort.init(labelXright, 430); + + string host = labelServerIp.getText(); + int portNumber = + config.getInt("PortServer", intToStr(GameConstants::serverPort).c_str()); + std::vector hostPartsList; + Tokenize(host, hostPartsList, ":"); + if (hostPartsList.size() > 1) { + host = hostPartsList[0]; + replaceAll(hostPartsList[1], "_", ""); + portNumber = strToInt(hostPartsList[1]); + } + + string port = " (" + intToStr(portNumber) + ")"; + labelServerPort.setText(port); + + labelStatus.registerGraphicComponent(containerName, "labelStatus"); + labelStatus.init(labelXleft, 400); + labelStatus.setText(""); + + labelInfo.registerGraphicComponent(containerName, "labelInfo"); + labelInfo.init(labelXleft, 370); + labelInfo.setText(""); + + connected = false; + playerIndex = -1; + + // server ip + if (connect == true) { + string hostIP = serverIp.getString(); + if (portNumberOverride > 0) { + hostIP += ":" + intToStr(portNumberOverride); } - string userData = config.getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - serversSavedFile = userData + serversSavedFile; + labelServerIp.setText(hostIP + "_"); - if(fileExists(serversSavedFile) == true) { - servers.load(serversSavedFile); - } - else if(fileExists(serverListPath + serverFileName) == true) { - servers.load(serverListPath + serverFileName); - } - else if(fileExists(Properties::getApplicationPath() + serverFileName) == true) { - servers.load(Properties::getApplicationPath() + serverFileName); - } - else if(fileExists(serverFileName) == true) { - servers.load(serverFileName); + autoConnectToServer = true; + } else { + string hostIP = config.getString("ServerIp"); + if (portNumberOverride > 0) { + hostIP += ":" + intToStr(portNumberOverride); } - //buttons - buttonReturn.registerGraphicComponent(containerName,"buttonReturn"); - buttonReturn.init(250, 300, 150); - buttonReturn.setText(lang.getString("Return")); - - buttonConnect.registerGraphicComponent(containerName,"buttonConnect"); - buttonConnect.init(425, 300, 150); - buttonConnect.setText(lang.getString("Connect")); - - buttonCreateGame.registerGraphicComponent(containerName,"buttonCreateGame"); - buttonCreateGame.init(600, 300, 150); - buttonCreateGame.setText(lang.getString("HostGame")); - - buttonAutoFindServers.registerGraphicComponent(containerName,"buttonAutoFindServers"); - buttonAutoFindServers.init(360, 250, 280); - buttonAutoFindServers.setText(lang.getString("FindLANGames")); - buttonAutoFindServers.setEnabled(true); - - int labelXleft = 300; - int labelXright = 480; - - //server type label - labelServerType.registerGraphicComponent(containerName,"labelServerType"); - labelServerType.init(labelXleft, 490); - labelServerType.setText(lang.getString("ServerType")); - - //server type list box - listBoxServerType.registerGraphicComponent(containerName,"listBoxServerType"); - listBoxServerType.init(labelXright, 490, 210); - listBoxServerType.pushBackItem(lang.getString("ServerTypeNew")); - listBoxServerType.pushBackItem(lang.getString("ServerTypePrevious")); - listBoxServerType.pushBackItem(lang.getString("ServerTypeFound")); - - //server label - labelServer.registerGraphicComponent(containerName,"labelServer"); - labelServer.init(labelXleft, 460); - labelServer.setText(lang.getString("Server")); - - //server listbox - listBoxServers.registerGraphicComponent(containerName,"listBoxServers"); - listBoxServers.init(labelXright, 460, 210); - for(int i= 0; i hostPartsList; - Tokenize(host,hostPartsList,":"); - if(hostPartsList.size() > 1) { - host = hostPartsList[0]; - replaceAll(hostPartsList[1],"_",""); - portNumber = strToInt(hostPartsList[1]); - } - - string port = " ("+intToStr(portNumber)+")"; - labelServerPort.setText(port); - - labelStatus.registerGraphicComponent(containerName,"labelStatus"); - labelStatus.init(labelXleft, 400); - labelStatus.setText(""); - - labelInfo.registerGraphicComponent(containerName,"labelInfo"); - labelInfo.init(labelXleft, 370); - labelInfo.setText(""); - - connected= false; - playerIndex= -1; - - //server ip - if(connect == true) { - string hostIP = serverIp.getString(); - if(portNumberOverride > 0) { - hostIP += ":" + intToStr(portNumberOverride); - } - - labelServerIp.setText(hostIP + "_"); - - autoConnectToServer = true; - } - else { - string hostIP = config.getString("ServerIp"); - if(portNumberOverride > 0) { - hostIP += ":" + intToStr(portNumberOverride); - } - - labelServerIp.setText(hostIP + "_"); - } - - host = labelServerIp.getText(); - portNumber = config.getInt("PortServer",intToStr(GameConstants::serverPort).c_str()); - hostPartsList.clear(); - Tokenize(host,hostPartsList,":"); - if(hostPartsList.size() > 1) { - host = hostPartsList[0]; - replaceAll(hostPartsList[1],"_",""); - portNumber = strToInt(hostPartsList[1]); - } - - port = " ("+intToStr(portNumber)+")"; - labelServerPort.setText(port); - - GraphicComponent::applyAllCustomProperties(containerName); - - chatManager.init(&console, -1); + labelServerIp.setText(hostIP + "_"); + } + + host = labelServerIp.getText(); + portNumber = + config.getInt("PortServer", intToStr(GameConstants::serverPort).c_str()); + hostPartsList.clear(); + Tokenize(host, hostPartsList, ":"); + if (hostPartsList.size() > 1) { + host = hostPartsList[0]; + replaceAll(hostPartsList[1], "_", ""); + portNumber = strToInt(hostPartsList[1]); + } + + port = " (" + intToStr(portNumber) + ")"; + labelServerPort.setText(port); + + GraphicComponent::applyAllCustomProperties(containerName); + + chatManager.init(&console, -1); } void MenuStateJoinGame::reloadUI() { - Lang &lang= Lang::getInstance(); - Config &config= Config::getInstance(); + Lang &lang = Lang::getInstance(); + Config &config = Config::getInstance(); - console.resetFonts(); + console.resetFonts(); - buttonReturn.setText(lang.getString("Return")); - buttonConnect.setText(lang.getString("Connect")); - buttonCreateGame.setText(lang.getString("HostGame")); - buttonAutoFindServers.setText(lang.getString("FindLANGames")); - labelServerType.setText(lang.getString("ServerType")); + buttonReturn.setText(lang.getString("Return")); + buttonConnect.setText(lang.getString("Connect")); + buttonCreateGame.setText(lang.getString("HostGame")); + buttonAutoFindServers.setText(lang.getString("FindLANGames")); + labelServerType.setText(lang.getString("ServerType")); - std::vector listboxData; - listboxData.push_back(lang.getString("ServerTypeNew")); - listboxData.push_back(lang.getString("ServerTypePrevious")); - listboxData.push_back(lang.getString("ServerTypeFound")); - listBoxServerType.setItems(listboxData); + std::vector listboxData; + listboxData.push_back(lang.getString("ServerTypeNew")); + listboxData.push_back(lang.getString("ServerTypePrevious")); + listboxData.push_back(lang.getString("ServerTypeFound")); + listBoxServerType.setItems(listboxData); - labelServer.setText(lang.getString("Server")); + labelServer.setText(lang.getString("Server")); - labelServerPortLabel.setText(lang.getString("ServerPort")); + labelServerPortLabel.setText(lang.getString("ServerPort")); - string host = labelServerIp.getText(); - int portNumber = config.getInt("PortServer",intToStr(GameConstants::serverPort).c_str()); - std::vector hostPartsList; - Tokenize(host,hostPartsList,":"); - if(hostPartsList.size() > 1) { - host = hostPartsList[0]; - replaceAll(hostPartsList[1],"_",""); - portNumber = strToInt(hostPartsList[1]); - } + string host = labelServerIp.getText(); + int portNumber = + config.getInt("PortServer", intToStr(GameConstants::serverPort).c_str()); + std::vector hostPartsList; + Tokenize(host, hostPartsList, ":"); + if (hostPartsList.size() > 1) { + host = hostPartsList[0]; + replaceAll(hostPartsList[1], "_", ""); + portNumber = strToInt(hostPartsList[1]); + } - string port = " ("+intToStr(portNumber)+")"; - labelServerPort.setText(port); + string port = " (" + intToStr(portNumber) + ")"; + labelServerPort.setText(port); - chatManager.init(&console, -1); + chatManager.init(&console, -1); - GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); + GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); } MenuStateJoinGame::~MenuStateJoinGame() { - abortAutoFind = true; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + abortAutoFind = true; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); } void MenuStateJoinGame::DiscoveredServers(std::vector serverList) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(abortAutoFind == true) { - return; - } - // Testing multi-server - //serverList.push_back("test1"); - //serverList.push_back("test2"); - // - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] serverList.size() = %d\n",__FILE__,__FUNCTION__,__LINE__,(int)serverList.size()); - - autoConnectToServer = false; - buttonAutoFindServers.setEnabled(true); - buttonConnect.setEnabled(true); - if(serverList.empty() == false) { - Config &config= Config::getInstance(); - string bestIPMatch = ""; - int serverGamePort = config.getInt("PortServer",intToStr(GameConstants::serverPort).c_str()); - std::vector localIPList = Socket::getLocalIPAddressList(); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - for(int idx = 0; idx < (int)serverList.size(); idx++) { - - vector paramPartPortsTokens; - Tokenize(serverList[idx],paramPartPortsTokens,":"); - if(paramPartPortsTokens.size() >= 2 && paramPartPortsTokens[1].length() > 0) { - serverGamePort = strToInt(paramPartPortsTokens[1]); - } - - bestIPMatch = serverList[idx]; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] bestIPMatch = [%s]\n",__FILE__,__FUNCTION__,__LINE__,bestIPMatch.c_str()); - if(localIPList.empty() == true) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - break; - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] bestIPMatch = [%s] localIPList[0] = [%s]\n",__FILE__,__FUNCTION__,__LINE__,bestIPMatch.c_str(),localIPList[0].c_str()); - if(strncmp(localIPList[0].c_str(),serverList[idx].c_str(),4) == 0) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - break; - } - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(bestIPMatch != "") { - bestIPMatch += ":" + intToStr(serverGamePort); - } - labelServerIp.setText(bestIPMatch); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(serverList.size() > 1) { - listBoxServerType.setSelectedItemIndex(MenuStateJoinGame::foundServersIndex); - listBoxFoundServers.setItems(serverList); - } - else { - autoConnectToServer = true; - } - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + + if (abortAutoFind == true) { + return; + } + // Testing multi-server + // serverList.push_back("test1"); + // serverList.push_back("test2"); + // + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] serverList.size() = %d\n", __FILE__, + __FUNCTION__, __LINE__, (int)serverList.size()); + + autoConnectToServer = false; + buttonAutoFindServers.setEnabled(true); + buttonConnect.setEnabled(true); + if (serverList.empty() == false) { + Config &config = Config::getInstance(); + string bestIPMatch = ""; + int serverGamePort = config.getInt( + "PortServer", intToStr(GameConstants::serverPort).c_str()); + std::vector localIPList = Socket::getLocalIPAddressList(); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + + for (int idx = 0; idx < (int)serverList.size(); idx++) { + + vector paramPartPortsTokens; + Tokenize(serverList[idx], paramPartPortsTokens, ":"); + if (paramPartPortsTokens.size() >= 2 && + paramPartPortsTokens[1].length() > 0) { + serverGamePort = strToInt(paramPartPortsTokens[1]); + } + + bestIPMatch = serverList[idx]; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] bestIPMatch = [%s]\n", + __FILE__, __FUNCTION__, __LINE__, + bestIPMatch.c_str()); + if (localIPList.empty() == true) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + break; + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] bestIPMatch = [%s] localIPList[0] = [%s]\n", + __FILE__, __FUNCTION__, __LINE__, bestIPMatch.c_str(), + localIPList[0].c_str()); + if (strncmp(localIPList[0].c_str(), serverList[idx].c_str(), 4) == 0) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + break; + } + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + + if (bestIPMatch != "") { + bestIPMatch += ":" + intToStr(serverGamePort); + } + labelServerIp.setText(bestIPMatch); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + + if (serverList.size() > 1) { + listBoxServerType.setSelectedItemIndex( + MenuStateJoinGame::foundServersIndex); + listBoxFoundServers.setItems(serverList); + } else { + autoConnectToServer = true; + } + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); } void MenuStateJoinGame::mouseClick(int x, int y, MouseButton mouseButton) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] START\n",__FILE__,__FUNCTION__); - - CoreData &coreData= CoreData::getInstance(); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - NetworkManager &networkManager= NetworkManager::getInstance(); - ClientInterface* clientInterface= networkManager.getClientInterface(); - - if(clientInterface->isConnected() == false) { - //server type - if(listBoxServerType.mouseClick(x, y)){ - if(!listBoxServers.getText().empty()){ - labelServerIp.setText(servers.getString(listBoxServers.getText())+"_"); - } - } - //server list - else if(listBoxServerType.getSelectedItemIndex() == newPrevServerIndex){ - if(listBoxServers.mouseClick(x, y)) { - labelServerIp.setText(servers.getString(listBoxServers.getText())+"_"); - } - } - else if(listBoxServerType.getSelectedItemIndex() == foundServersIndex){ - if(listBoxFoundServers.mouseClick(x, y)) { - labelServerIp.setText(listBoxFoundServers.getText()); - } - } - - string host = labelServerIp.getText(); - Config &config= Config::getInstance(); - int portNumber = config.getInt("PortServer",intToStr(GameConstants::serverPort).c_str()); - std::vector hostPartsList; - Tokenize(host,hostPartsList,":"); - if(hostPartsList.size() > 1) { - host = hostPartsList[0]; - replaceAll(hostPartsList[1],"_",""); - portNumber = strToInt(hostPartsList[1]); - } - - string port = " ("+intToStr(portNumber)+")"; - labelServerPort.setText(port); - - } - - //return - if(buttonReturn.mouseClick(x, y)) { - soundRenderer.playFx(coreData.getClickSoundA()); - - clientInterface->stopServerDiscovery(); - - if(clientInterface->getSocket() != NULL) { - //if(clientInterface->isConnected() == true) { - // string sQuitText = Config::getInstance().getString("NetPlayerName",Socket::getHostName().c_str()) + " has chosen to leave the game!"; - // clientInterface->sendTextMessage(sQuitText,-1); - //} - clientInterface->close(); - } - abortAutoFind = true; - mainMenu->setState(new MenuStateNewGame(program, mainMenu)); - return; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] START\n", + __FILE__, __FUNCTION__); + + CoreData &coreData = CoreData::getInstance(); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + NetworkManager &networkManager = NetworkManager::getInstance(); + ClientInterface *clientInterface = networkManager.getClientInterface(); + + if (clientInterface->isConnected() == false) { + // server type + if (listBoxServerType.mouseClick(x, y)) { + if (!listBoxServers.getText().empty()) { + labelServerIp.setText(servers.getString(listBoxServers.getText()) + + "_"); + } } - - //connect - else if(buttonConnect.mouseClick(x, y) && buttonConnect.getEnabled() == true) { - ClientInterface* clientInterface= networkManager.getClientInterface(); - - soundRenderer.playFx(coreData.getClickSoundB()); - labelInfo.setText(""); - - if(clientInterface->isConnected()) { - clientInterface->reset(); - } - else { - if(connectToServer() == true) { - return; - } - } - } - else if(buttonCreateGame.mouseClick(x, y)){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - soundRenderer.playFx(coreData.getClickSoundB()); - - clientInterface->stopServerDiscovery(); - if(clientInterface->getSocket() != NULL) { - clientInterface->close(); - } - abortAutoFind = true; - mainMenu->setState(new MenuStateCustomGame(program, mainMenu,true,pLanGame)); - return; + // server list + else if (listBoxServerType.getSelectedItemIndex() == newPrevServerIndex) { + if (listBoxServers.mouseClick(x, y)) { + labelServerIp.setText(servers.getString(listBoxServers.getText()) + + "_"); + } + } else if (listBoxServerType.getSelectedItemIndex() == foundServersIndex) { + if (listBoxFoundServers.mouseClick(x, y)) { + labelServerIp.setText(listBoxFoundServers.getText()); + } } - else if(buttonAutoFindServers.mouseClick(x, y) && buttonAutoFindServers.getEnabled() == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + string host = labelServerIp.getText(); + Config &config = Config::getInstance(); + int portNumber = config.getInt("PortServer", + intToStr(GameConstants::serverPort).c_str()); + std::vector hostPartsList; + Tokenize(host, hostPartsList, ":"); + if (hostPartsList.size() > 1) { + host = hostPartsList[0]; + replaceAll(hostPartsList[1], "_", ""); + portNumber = strToInt(hostPartsList[1]); + } - ClientInterface* clientInterface= networkManager.getClientInterface(); - soundRenderer.playFx(coreData.getClickSoundB()); + string port = " (" + intToStr(portNumber) + ")"; + labelServerPort.setText(port); + } - // Triggers a thread which calls back into MenuStateJoinGame::DiscoveredServers - // with the results - if(clientInterface->isConnected() == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + // return + if (buttonReturn.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); - buttonAutoFindServers.setEnabled(false); - buttonConnect.setEnabled(false); - clientInterface->discoverServers(this); - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - } + clientInterface->stopServerDiscovery(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] END\n",__FILE__,__FUNCTION__); + if (clientInterface->getSocket() != NULL) { + // if(clientInterface->isConnected() == true) { + // string sQuitText = + // Config::getInstance().getString("NetPlayerName",Socket::getHostName().c_str()) + // + " has chosen to leave the game!"; + // clientInterface->sendTextMessage(sQuitText,-1); + //} + clientInterface->close(); + } + abortAutoFind = true; + mainMenu->setState(new MenuStateNewGame(program, mainMenu)); + return; + } + + // connect + else if (buttonConnect.mouseClick(x, y) && + buttonConnect.getEnabled() == true) { + ClientInterface *clientInterface = networkManager.getClientInterface(); + + soundRenderer.playFx(coreData.getClickSoundB()); + labelInfo.setText(""); + + if (clientInterface->isConnected()) { + clientInterface->reset(); + } else { + if (connectToServer() == true) { + return; + } + } + } else if (buttonCreateGame.mouseClick(x, y)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + soundRenderer.playFx(coreData.getClickSoundB()); + + clientInterface->stopServerDiscovery(); + if (clientInterface->getSocket() != NULL) { + clientInterface->close(); + } + abortAutoFind = true; + mainMenu->setState( + new MenuStateCustomGame(program, mainMenu, true, pLanGame)); + return; + } + + else if (buttonAutoFindServers.mouseClick(x, y) && + buttonAutoFindServers.getEnabled() == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + ClientInterface *clientInterface = networkManager.getClientInterface(); + soundRenderer.playFx(coreData.getClickSoundB()); + + // Triggers a thread which calls back into + // MenuStateJoinGame::DiscoveredServers with the results + if (clientInterface->isConnected() == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + + buttonAutoFindServers.setEnabled(false); + buttonConnect.setEnabled(false); + clientInterface->discoverServers(this); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] END\n", + __FILE__, __FUNCTION__); } -void MenuStateJoinGame::mouseMove(int x, int y, const MouseState *ms){ - buttonReturn.mouseMove(x, y); - buttonConnect.mouseMove(x, y); - buttonAutoFindServers.mouseMove(x, y); - buttonCreateGame.mouseMove(x, y); - listBoxServerType.mouseMove(x, y); - - //hide-show options depending on the selection - if(listBoxServers.getSelectedItemIndex() == newServerIndex) { - labelServerIp.mouseMove(x, y); - } - else if(listBoxServers.getSelectedItemIndex() == newPrevServerIndex) { - listBoxServers.mouseMove(x, y); - } - else { - listBoxFoundServers.mouseMove(x, y); - } +void MenuStateJoinGame::mouseMove(int x, int y, const MouseState *ms) { + buttonReturn.mouseMove(x, y); + buttonConnect.mouseMove(x, y); + buttonAutoFindServers.mouseMove(x, y); + buttonCreateGame.mouseMove(x, y); + listBoxServerType.mouseMove(x, y); + + // hide-show options depending on the selection + if (listBoxServers.getSelectedItemIndex() == newServerIndex) { + labelServerIp.mouseMove(x, y); + } else if (listBoxServers.getSelectedItemIndex() == newPrevServerIndex) { + listBoxServers.mouseMove(x, y); + } else { + listBoxFoundServers.mouseMove(x, y); + } } -void MenuStateJoinGame::render(){ - Renderer &renderer= Renderer::getInstance(); - - renderer.renderButton(&buttonReturn); - renderer.renderLabel(&labelServer); - renderer.renderLabel(&labelServerType); - renderer.renderLabel(&labelStatus); - renderer.renderLabel(&labelInfo); - renderer.renderLabel(&labelServerPort); - renderer.renderLabel(&labelServerPortLabel); - renderer.renderButton(&buttonConnect); - renderer.renderButton(&buttonCreateGame); - - renderer.renderButton(&buttonAutoFindServers); - renderer.renderListBox(&listBoxServerType); - - if(listBoxServerType.getSelectedItemIndex() == newServerIndex) { - renderer.renderLabel(&labelServerIp); - } - else if(listBoxServerType.getSelectedItemIndex() == newPrevServerIndex) { - renderer.renderListBox(&listBoxServers); - } - else { - renderer.renderListBox(&listBoxFoundServers); - } - - renderer.renderChatManager(&chatManager); - renderer.renderConsole(&console); - - if(program != NULL) program->renderProgramMsgBox(); +void MenuStateJoinGame::render() { + Renderer &renderer = Renderer::getInstance(); + + renderer.renderButton(&buttonReturn); + renderer.renderLabel(&labelServer); + renderer.renderLabel(&labelServerType); + renderer.renderLabel(&labelStatus); + renderer.renderLabel(&labelInfo); + renderer.renderLabel(&labelServerPort); + renderer.renderLabel(&labelServerPortLabel); + renderer.renderButton(&buttonConnect); + renderer.renderButton(&buttonCreateGame); + + renderer.renderButton(&buttonAutoFindServers); + renderer.renderListBox(&listBoxServerType); + + if (listBoxServerType.getSelectedItemIndex() == newServerIndex) { + renderer.renderLabel(&labelServerIp); + } else if (listBoxServerType.getSelectedItemIndex() == newPrevServerIndex) { + renderer.renderListBox(&listBoxServers); + } else { + renderer.renderListBox(&listBoxFoundServers); + } + + renderer.renderChatManager(&chatManager); + renderer.renderConsole(&console); + + if (program != NULL) + program->renderProgramMsgBox(); } -void MenuStateJoinGame::update() -{ - ClientInterface* clientInterface= NetworkManager::getInstance().getClientInterface(); - Lang &lang= Lang::getInstance(); - - //update status label - if(clientInterface->isConnected()) - { - buttonConnect.setText(lang.getString("Disconnect")); - - if(clientInterface->getAllowDownloadDataSynch() == false) - { - string label = lang.getString("ConnectedToServer"); - - if(!clientInterface->getServerName().empty()) - { - label = label + " " + clientInterface->getServerName(); - } - - if(clientInterface->getAllowGameDataSynchCheck() == true && - clientInterface->getNetworkGameDataSynchCheckOk() == false) - { - label = label + " - warning synch mismatch for:"; - if(clientInterface->getNetworkGameDataSynchCheckOkMap() == false) - { - label = label + " map"; - } - if(clientInterface->getNetworkGameDataSynchCheckOkTile() == false) - { - label = label + " tile"; - } - if(clientInterface->getNetworkGameDataSynchCheckOkTech() == false) - { - label = label + " techtree"; - } - } - else if(clientInterface->getAllowGameDataSynchCheck() == true) - { - label += " - data synch is ok"; - } - labelStatus.setText(label); - } - else - { - string label = lang.getString("ConnectedToServer"); - - if(!clientInterface->getServerName().empty()) - { - label = label + " " + clientInterface->getServerName(); - } - - if(clientInterface->getAllowGameDataSynchCheck() == true && - clientInterface->getNetworkGameDataSynchCheckOk() == false) - { - label = label + " - waiting to synch:"; - if(clientInterface->getNetworkGameDataSynchCheckOkMap() == false) - { - label = label + " map"; - } - if(clientInterface->getNetworkGameDataSynchCheckOkTile() == false) - { - label = label + " tile"; - } - if(clientInterface->getNetworkGameDataSynchCheckOkTech() == false) - { - label = label + " techtree"; - } - } - else if(clientInterface->getAllowGameDataSynchCheck() == true) - { - label += " - data synch is ok"; - } - - labelStatus.setText(label); - } - } - else - { - buttonConnect.setText(lang.getString("Connect")); - string connectedStatus = lang.getString("NotConnected"); - if(buttonAutoFindServers.getEnabled() == false) { - connectedStatus += " - searching for servers, please wait..."; - } - labelStatus.setText(connectedStatus); - labelInfo.setText(""); - } - - //process network messages - if(clientInterface->isConnected()) { - //update lobby - clientInterface->updateLobby(); - - clientInterface= NetworkManager::getInstance().getClientInterface(); - if(clientInterface != NULL && clientInterface->isConnected()) { - //call the chat manager - chatManager.updateNetwork(); - - //console - console.update(); - - //intro - if(clientInterface->getIntroDone()) { - labelInfo.setText(lang.getString("WaitingHost")); - - string host = labelServerIp.getText(); - std::vector hostPartsList; - Tokenize(host,hostPartsList,":"); - if(hostPartsList.size() > 1) { - host = hostPartsList[0]; - replaceAll(hostPartsList[1],"_",""); - } - string saveHost = Ip(host).getString(); - if(hostPartsList.size() > 1) { - saveHost += ":" + hostPartsList[1]; - } - - servers.setString(clientInterface->getServerName(), saveHost); - } - - //launch - if(clientInterface->getLaunchGame()) - { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] clientInterface->getLaunchGame() - A\n",__FILE__,__FUNCTION__); - - servers.save(serversSavedFile); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] clientInterface->getLaunchGame() - B\n",__FILE__,__FUNCTION__); - - abortAutoFind = true; - clientInterface->stopServerDiscovery(); - program->setState(new Game(program, clientInterface->getGameSettings(),false)); - return; - } - } - } - else if(autoConnectToServer == true) { - autoConnectToServer = false; - if(connectToServer() == true) { - return; - } - } - - if(clientInterface != NULL && clientInterface->getLaunchGame()) if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] clientInterface->getLaunchGame() - D\n",__FILE__,__FUNCTION__); +void MenuStateJoinGame::update() { + ClientInterface *clientInterface = + NetworkManager::getInstance().getClientInterface(); + Lang &lang = Lang::getInstance(); + + // update status label + if (clientInterface->isConnected()) { + buttonConnect.setText(lang.getString("Disconnect")); + + if (clientInterface->getAllowDownloadDataSynch() == false) { + string label = lang.getString("ConnectedToServer"); + + if (!clientInterface->getServerName().empty()) { + label = label + " " + clientInterface->getServerName(); + } + + if (clientInterface->getAllowGameDataSynchCheck() == true && + clientInterface->getNetworkGameDataSynchCheckOk() == false) { + label = label + " - warning synch mismatch for:"; + if (clientInterface->getNetworkGameDataSynchCheckOkMap() == false) { + label = label + " map"; + } + if (clientInterface->getNetworkGameDataSynchCheckOkTile() == false) { + label = label + " tile"; + } + if (clientInterface->getNetworkGameDataSynchCheckOkTech() == false) { + label = label + " techtree"; + } + } else if (clientInterface->getAllowGameDataSynchCheck() == true) { + label += " - data synch is ok"; + } + labelStatus.setText(label); + } else { + string label = lang.getString("ConnectedToServer"); + + if (!clientInterface->getServerName().empty()) { + label = label + " " + clientInterface->getServerName(); + } + + if (clientInterface->getAllowGameDataSynchCheck() == true && + clientInterface->getNetworkGameDataSynchCheckOk() == false) { + label = label + " - waiting to synch:"; + if (clientInterface->getNetworkGameDataSynchCheckOkMap() == false) { + label = label + " map"; + } + if (clientInterface->getNetworkGameDataSynchCheckOkTile() == false) { + label = label + " tile"; + } + if (clientInterface->getNetworkGameDataSynchCheckOkTech() == false) { + label = label + " techtree"; + } + } else if (clientInterface->getAllowGameDataSynchCheck() == true) { + label += " - data synch is ok"; + } + + labelStatus.setText(label); + } + } else { + buttonConnect.setText(lang.getString("Connect")); + string connectedStatus = lang.getString("NotConnected"); + if (buttonAutoFindServers.getEnabled() == false) { + connectedStatus += " - searching for servers, please wait..."; + } + labelStatus.setText(connectedStatus); + labelInfo.setText(""); + } + + // process network messages + if (clientInterface->isConnected()) { + // update lobby + clientInterface->updateLobby(); + + clientInterface = NetworkManager::getInstance().getClientInterface(); + if (clientInterface != NULL && clientInterface->isConnected()) { + // call the chat manager + chatManager.updateNetwork(); + + // console + console.update(); + + // intro + if (clientInterface->getIntroDone()) { + labelInfo.setText(lang.getString("WaitingHost")); + + string host = labelServerIp.getText(); + std::vector hostPartsList; + Tokenize(host, hostPartsList, ":"); + if (hostPartsList.size() > 1) { + host = hostPartsList[0]; + replaceAll(hostPartsList[1], "_", ""); + } + string saveHost = Ip(host).getString(); + if (hostPartsList.size() > 1) { + saveHost += ":" + hostPartsList[1]; + } + + servers.setString(clientInterface->getServerName(), saveHost); + } + + // launch + if (clientInterface->getLaunchGame()) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s] clientInterface->getLaunchGame() - A\n", __FILE__, + __FUNCTION__); + + servers.save(serversSavedFile); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s] clientInterface->getLaunchGame() - B\n", __FILE__, + __FUNCTION__); + + abortAutoFind = true; + clientInterface->stopServerDiscovery(); + program->setState( + new Game(program, clientInterface->getGameSettings(), false)); + return; + } + } + } else if (autoConnectToServer == true) { + autoConnectToServer = false; + if (connectToServer() == true) { + return; + } + } + + if (clientInterface != NULL && clientInterface->getLaunchGame()) + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s] clientInterface->getLaunchGame() - D\n", __FILE__, + __FUNCTION__); } bool MenuStateJoinGame::textInput(std::string text) { - if(chatManager.getEditEnabled() == true) { - return chatManager.textInput(text); - } - return false; + if (chatManager.getEditEnabled() == true) { + return chatManager.textInput(text); + } + return false; } void MenuStateJoinGame::keyDown(SDL_KeyboardEvent key) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] key = [%c][%d]\n",__FILE__,__FUNCTION__,__LINE__,key.keysym.sym,key.keysym.sym); - - ClientInterface* clientInterface= NetworkManager::getInstance().getClientInterface(); - if(clientInterface->isConnected() == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - - string text = labelServerIp.getText(); - if(isKeyPressed(SDLK_BACKSPACE,key) == true && text.length() > 0) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - size_t found = text.find_last_of("_"); - if (found == string::npos) { - text.erase(text.end() - 1); - } - else { - if(text.size() > 1) { - text.erase(text.end() - 2); - } - } - - labelServerIp.setText(text); - } - //else if(key == configKeys.getCharKey("SaveGUILayout")) { - else if(isKeyPressed(configKeys.getSDLKey("SaveGUILayout"),key) == true) { - bool saved = GraphicComponent::saveAllCustomProperties(containerName); - Lang &lang= Lang::getInstance(); - console.addLine(lang.getString("GUILayoutSaved") + " [" + (saved ? lang.getString("Yes") : lang.getString("No"))+ "]"); - } - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - //send key to the chat manager - chatManager.keyDown(key); - - if(chatManager.getEditEnabled() == false) { - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - //if(key == configKeys.getCharKey("SaveGUILayout")) { - if(isKeyPressed(configKeys.getSDLKey("SaveGUILayout"),key) == true) { - bool saved = GraphicComponent::saveAllCustomProperties(containerName); - Lang &lang= Lang::getInstance(); - console.addLine(lang.getString("GUILayoutSaved") + " [" + (saved ? lang.getString("Yes") : lang.getString("No"))+ "]"); - } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d] key = [%c][%d]\n", + __FILE__, __FUNCTION__, __LINE__, key.keysym.sym, key.keysym.sym); + + ClientInterface *clientInterface = + NetworkManager::getInstance().getClientInterface(); + if (clientInterface->isConnected() == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + + string text = labelServerIp.getText(); + if (isKeyPressed(SDLK_BACKSPACE, key) == true && text.length() > 0) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + size_t found = text.find_last_of("_"); + if (found == string::npos) { + text.erase(text.end() - 1); + } else { + if (text.size() > 1) { + text.erase(text.end() - 2); } - } + } + + labelServerIp.setText(text); + } + // else if(key == configKeys.getCharKey("SaveGUILayout")) { + else if (isKeyPressed(configKeys.getSDLKey("SaveGUILayout"), key) == true) { + bool saved = GraphicComponent::saveAllCustomProperties(containerName); + Lang &lang = Lang::getInstance(); + console.addLine(lang.getString("GUILayoutSaved") + " [" + + (saved ? lang.getString("Yes") : lang.getString("No")) + + "]"); + } + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + // send key to the chat manager + chatManager.keyDown(key); + + if (chatManager.getEditEnabled() == false) { + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + // if(key == configKeys.getCharKey("SaveGUILayout")) { + if (isKeyPressed(configKeys.getSDLKey("SaveGUILayout"), key) == true) { + bool saved = GraphicComponent::saveAllCustomProperties(containerName); + Lang &lang = Lang::getInstance(); + console.addLine(lang.getString("GUILayoutSaved") + " [" + + (saved ? lang.getString("Yes") : lang.getString("No")) + + "]"); + } + } + } } void MenuStateJoinGame::keyPress(SDL_KeyboardEvent c) { - ClientInterface* clientInterface= NetworkManager::getInstance().getClientInterface(); - - if(clientInterface->isConnected() == false) { - int maxTextSize= 22; - - //Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - - SDL_Keycode key = extractKeyPressed(c); - - //if(c>='0' && c<='9') { - if( (key >= SDLK_0 && key <= SDLK_9) || - (key >= SDLK_KP_0 && key <= SDLK_KP_9)) { - if((int)labelServerIp.getText().size() < maxTextSize) { - string text= labelServerIp.getText(); - //text.insert(text.end()-1, key); - char szCharText[26]=""; - snprintf(szCharText,26,"%c",key); - char *utfStr = ConvertToUTF8(&szCharText[0]); - if(text.size() > 0) { - text.insert(text.end() -1, utfStr[0]); - } - else { - text = utfStr[0]; - } - - delete [] utfStr; - - labelServerIp.setText(text); - } - } - //else if (c=='.') { - else if (key == SDLK_PERIOD) { - if((int)labelServerIp.getText().size() < maxTextSize) { - string text= labelServerIp.getText(); - if(text.size() > 0) { - text.insert(text.end() -1, '.'); - } - else { - text = "."; - } - - labelServerIp.setText(text); - } - } - //else if (c==':') { - else if (key == SDLK_COLON) { - if((int)labelServerIp.getText().size() < maxTextSize) { - string text= labelServerIp.getText(); - if(text.size() > 0) { - text.insert(text.end() -1, ':'); - } - else { - text = ":"; - } - - labelServerIp.setText(text); - } - } - } - else { - chatManager.keyPress(c); - } + ClientInterface *clientInterface = + NetworkManager::getInstance().getClientInterface(); + + if (clientInterface->isConnected() == false) { + int maxTextSize = 22; + + // Config &configKeys = + // Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); + + SDL_Keycode key = extractKeyPressed(c); + + // if(c>='0' && c<='9') { + if ((key >= SDLK_0 && key <= SDLK_9) || + (key >= SDLK_KP_0 && key <= SDLK_KP_9)) { + if ((int)labelServerIp.getText().size() < maxTextSize) { + string text = labelServerIp.getText(); + // text.insert(text.end()-1, key); + char szCharText[26] = ""; + snprintf(szCharText, 26, "%c", key); + char *utfStr = ConvertToUTF8(&szCharText[0]); + if (text.size() > 0) { + text.insert(text.end() - 1, utfStr[0]); + } else { + text = utfStr[0]; + } + + delete[] utfStr; + + labelServerIp.setText(text); + } + } + // else if (c=='.') { + else if (key == SDLK_PERIOD) { + if ((int)labelServerIp.getText().size() < maxTextSize) { + string text = labelServerIp.getText(); + if (text.size() > 0) { + text.insert(text.end() - 1, '.'); + } else { + text = "."; + } + + labelServerIp.setText(text); + } + } + // else if (c==':') { + else if (key == SDLK_COLON) { + if ((int)labelServerIp.getText().size() < maxTextSize) { + string text = labelServerIp.getText(); + if (text.size() > 0) { + text.insert(text.end() - 1, ':'); + } else { + text = ":"; + } + + labelServerIp.setText(text); + } + } + } else { + chatManager.keyPress(c); + } } bool MenuStateJoinGame::connectToServer() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] START\n",__FILE__,__FUNCTION__); - - Config& config= Config::getInstance(); - string host = labelServerIp.getText(); - int port = config.getInt("PortServer",intToStr(GameConstants::serverPort).c_str()); - std::vector hostPartsList; - Tokenize(host,hostPartsList,":"); - if(hostPartsList.size() > 1) { - host = hostPartsList[0]; - replaceAll(hostPartsList[1],"_",""); - port = strToInt(hostPartsList[1]); - } - Ip serverIp(host); - - ClientInterface* clientInterface= NetworkManager::getInstance().getClientInterface(); - clientInterface->connect(serverIp, port); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] server - [%s]\n",__FILE__,__FUNCTION__,serverIp.getString().c_str()); - - labelServerIp.setText(serverIp.getString() + '_'); - labelInfo.setText(""); - - //save server ip - if(config.getString("ServerIp") != serverIp.getString()) { - config.setString("ServerIp", serverIp.getString()); - config.save(); - } - - for(time_t elapsedWait = time(NULL); - clientInterface->getIntroDone() == false && - clientInterface->isConnected() && - difftime(time(NULL),elapsedWait) <= 10;) { - if(clientInterface->isConnected()) { - //update lobby - clientInterface->updateLobby(); - sleep(0); - //this->render(); - } - } - if( clientInterface->isConnected() == true && - clientInterface->getIntroDone() == true) { - - string saveHost = Ip(host).getString(); - if(hostPartsList.size() > 1) { - saveHost += ":" + hostPartsList[1]; - } - servers.setString(clientInterface->getServerName(), saveHost); - servers.save(serversSavedFile); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] Using FTP port #: %d\n",__FILE__,__FUNCTION__,__LINE__,clientInterface->getServerFTPPort()); - abortAutoFind = true; - clientInterface->stopServerDiscovery(); - mainMenu->setState(new MenuStateConnectedGame(program, mainMenu)); - return true; - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] END\n",__FILE__,__FUNCTION__); - return false; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] START\n", + __FILE__, __FUNCTION__); + + Config &config = Config::getInstance(); + string host = labelServerIp.getText(); + int port = + config.getInt("PortServer", intToStr(GameConstants::serverPort).c_str()); + std::vector hostPartsList; + Tokenize(host, hostPartsList, ":"); + if (hostPartsList.size() > 1) { + host = hostPartsList[0]; + replaceAll(hostPartsList[1], "_", ""); + port = strToInt(hostPartsList[1]); + } + Ip serverIp(host); + + ClientInterface *clientInterface = + NetworkManager::getInstance().getClientInterface(); + clientInterface->connect(serverIp, port); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s] server - [%s]\n", __FILE__, + __FUNCTION__, serverIp.getString().c_str()); + + labelServerIp.setText(serverIp.getString() + '_'); + labelInfo.setText(""); + + // save server ip + if (config.getString("ServerIp") != serverIp.getString()) { + config.setString("ServerIp", serverIp.getString()); + config.save(); + } + + for (time_t elapsedWait = time(NULL); + clientInterface->getIntroDone() == false && + clientInterface->isConnected() && + difftime(time(NULL), elapsedWait) <= 10;) { + if (clientInterface->isConnected()) { + // update lobby + clientInterface->updateLobby(); + sleep(0); + // this->render(); + } + } + if (clientInterface->isConnected() == true && + clientInterface->getIntroDone() == true) { + + string saveHost = Ip(host).getString(); + if (hostPartsList.size() > 1) { + saveHost += ":" + hostPartsList[1]; + } + servers.setString(clientInterface->getServerName(), saveHost); + servers.save(serversSavedFile); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d] Using FTP port #: %d\n", + __FILE__, __FUNCTION__, __LINE__, + clientInterface->getServerFTPPort()); + abortAutoFind = true; + clientInterface->stopServerDiscovery(); + mainMenu->setState(new MenuStateConnectedGame(program, mainMenu)); + return true; + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] END\n", + __FILE__, __FUNCTION__); + return false; } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/menu/menu_state_join_game.h b/source/glest_game/menu/menu_state_join_game.h index 85b1ff096..35e81fb77 100644 --- a/source/glest_game/menu/menu_state_join_game.h +++ b/source/glest_game/menu/menu_state_join_game.h @@ -13,20 +13,21 @@ #define _GLEST_GAME_MENUSTATEJOINGAME_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include "properties.h" -#include "main_menu.h" #include "chat_manager.h" -#include -#include #include "leak_dumper.h" +#include "main_menu.h" +#include "properties.h" +#include +#include using Shared::Util::Properties; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { class NetworkMessageIntro; @@ -34,67 +35,69 @@ class NetworkMessageIntro; // class MenuStateJoinGame // =============================== -class MenuStateJoinGame: public MenuState, public DiscoveredServersInterface { +class MenuStateJoinGame : public MenuState, public DiscoveredServersInterface { private: - static const int newServerIndex; - static const int newPrevServerIndex; - static const int foundServersIndex; - static const string serverFileName; + static const int newServerIndex; + static const int newPrevServerIndex; + static const int foundServersIndex; + static const string serverFileName; private: - GraphicButton buttonReturn; - GraphicButton buttonConnect; - GraphicButton buttonAutoFindServers; - GraphicButton buttonCreateGame; - - GraphicLabel labelServer; - GraphicLabel labelServerType; - GraphicLabel labelServerIp; - GraphicLabel labelStatus; - GraphicLabel labelInfo; - GraphicListBox listBoxServerType; - GraphicListBox listBoxServers; - GraphicListBox listBoxFoundServers; - GraphicLabel labelServerPort; - GraphicLabel labelServerPortLabel; - - - bool connected; - int playerIndex; - Properties servers; - - //Console console; - ChatManager chatManager; - - string serversSavedFile; - bool abortAutoFind; - bool autoConnectToServer; + GraphicButton buttonReturn; + GraphicButton buttonConnect; + GraphicButton buttonAutoFindServers; + GraphicButton buttonCreateGame; + + GraphicLabel labelServer; + GraphicLabel labelServerType; + GraphicLabel labelServerIp; + GraphicLabel labelStatus; + GraphicLabel labelInfo; + GraphicListBox listBoxServerType; + GraphicListBox listBoxServers; + GraphicListBox listBoxFoundServers; + GraphicLabel labelServerPort; + GraphicLabel labelServerPortLabel; + + bool connected; + int playerIndex; + Properties servers; + + // Console console; + ChatManager chatManager; + + string serversSavedFile; + bool abortAutoFind; + bool autoConnectToServer; public: - MenuStateJoinGame(Program *program, MainMenu *mainMenu, bool connect= false, Ip serverIp= Ip(),int portNumberOverride=-1); - MenuStateJoinGame(Program *program, MainMenu *mainMenu, bool *autoFindHost); - virtual ~MenuStateJoinGame(); + MenuStateJoinGame(Program *program, MainMenu *mainMenu, bool connect = false, + Ip serverIp = Ip(), int portNumberOverride = -1); + MenuStateJoinGame(Program *program, MainMenu *mainMenu, bool *autoFindHost); + virtual ~MenuStateJoinGame(); - void mouseClick(int x, int y, MouseButton mouseButton); - void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; - void mouseMove(int x, int y, const MouseState *mouseState); - void render(); - void update(); + void mouseClick(int x, int y, MouseButton mouseButton); + void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; + void mouseMove(int x, int y, const MouseState *mouseState); + void render(); + void update(); - virtual bool textInput(std::string text); - virtual void keyDown(SDL_KeyboardEvent key); - virtual void keyPress(SDL_KeyboardEvent c); + virtual bool textInput(std::string text); + virtual void keyDown(SDL_KeyboardEvent key); + virtual void keyPress(SDL_KeyboardEvent c); - virtual bool isInSpecialKeyCaptureEvent() { return chatManager.getEditEnabled(); } + virtual bool isInSpecialKeyCaptureEvent() { + return chatManager.getEditEnabled(); + } - void reloadUI(); + void reloadUI(); private: - - void CommonInit(bool connect, Ip serverIp,int portNumberOverride); - bool connectToServer(); - virtual void DiscoveredServers(std::vector serverList); + void CommonInit(bool connect, Ip serverIp, int portNumberOverride); + bool connectToServer(); + virtual void DiscoveredServers(std::vector serverList); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/menu/menu_state_keysetup.cpp b/source/glest_game/menu/menu_state_keysetup.cpp index e2403d892..69101174b 100644 --- a/source/glest_game/menu/menu_state_keysetup.cpp +++ b/source/glest_game/menu/menu_state_keysetup.cpp @@ -11,620 +11,734 @@ #include "menu_state_keysetup.h" -#include "renderer.h" -#include "sound_renderer.h" -#include "core_data.h" #include "config.h" -#include "menu_state_options.h" -#include "menu_state_root.h" +#include "core_data.h" #include "menu_state_keysetup.h" +#include "menu_state_options.h" #include "menu_state_options_graphics.h" -#include "menu_state_options_sound.h" #include "menu_state_options_network.h" #include "menu_state_options_sound.h" +#include "menu_state_root.h" #include "metrics.h" +#include "renderer.h" +#include "sound_renderer.h" #include "string_utils.h" #include "leak_dumper.h" -namespace Glest{ namespace Game{ - +namespace Glest { +namespace Game { // ===================================================== // class MenuStateKeysetup // ===================================================== MenuStateKeysetup::MenuStateKeysetup(Program *program, MainMenu *mainMenu, - ProgramState **parentUI) : - MenuState(program, mainMenu, "config"), - buttonOk("KeySetup","buttonOk"), - buttonDefaults("KeySetup","buttonDefaults"), - buttonReturn("KeySetup","buttonReturn"), + ProgramState **parentUI) + : MenuState(program, mainMenu, "config"), buttonOk("KeySetup", "buttonOk"), + buttonDefaults("KeySetup", "buttonDefaults"), + buttonReturn("KeySetup", "buttonReturn"), - buttonKeyboardSetup("KeySetup","buttonKeyboardSetup"), - buttonVideoSection("KeySetup","buttonVideoSection"), - buttonAudioSection("KeySetup","buttonAudioSection"), - buttonMiscSection("KeySetup","buttonMiscSection"), - buttonNetworkSettings("KeySetup","buttonNetworkSettings"), + buttonKeyboardSetup("KeySetup", "buttonKeyboardSetup"), + buttonVideoSection("KeySetup", "buttonVideoSection"), + buttonAudioSection("KeySetup", "buttonAudioSection"), + buttonMiscSection("KeySetup", "buttonMiscSection"), + buttonNetworkSettings("KeySetup", "buttonNetworkSettings"), - labelTitle("KeySetup","labelTitle"), + labelTitle("KeySetup", "labelTitle"), - keyScrollBar("KeySetup","keyScrollBar"), + keyScrollBar("KeySetup", "keyScrollBar"), - mainMessageBox("KeySetup","mainMessageBox"), + mainMessageBox("KeySetup", "mainMessageBox"), - labelTestTitle("KeySetup","labelTestTitle"), - labelTestValue("KeySetup","labelTestValue") + labelTestTitle("KeySetup", "labelTestTitle"), + labelTestValue("KeySetup", "labelTestValue") { - try { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - containerName = "KeySetup"; - - keyButtonsLineHeight=30; - keyButtonsHeight=25; - keyButtonsWidth=400; - keyButtonsXBase=200; - keyButtonsYBase=200+400-keyButtonsLineHeight; - keyButtonsToRender=400/keyButtonsLineHeight; - int labelWidth=100; - - this->parentUI = parentUI; - this->console.setOnlyChatMessagesInStoredLines(false); - hotkeyIndex = -1; - hotkeyChar = SDLK_UNKNOWN; - - Lang &lang= Lang::getInstance(); - int buttonStartPos=170; - int buttonRowPos=50; - if(this->parentUI==NULL){ - int tabButtonWidth=200; - int tabButtonHeight=30; - - buttonAudioSection.init(0, 720,tabButtonWidth,tabButtonHeight); - buttonAudioSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonAudioSection.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonAudioSection.setText(lang.getString("Audio")); - // Video Section - buttonVideoSection.init(200, 720,tabButtonWidth,tabButtonHeight); - buttonVideoSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonVideoSection.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonVideoSection.setText(lang.getString("Video")); - //currentLine-=lineOffset; - //MiscSection - buttonMiscSection.init(400, 720,tabButtonWidth,tabButtonHeight); - buttonMiscSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonMiscSection.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonMiscSection.setText(lang.getString("Misc")); - //NetworkSettings - buttonNetworkSettings.init(600, 720,tabButtonWidth,tabButtonHeight); - buttonNetworkSettings.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonNetworkSettings.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonNetworkSettings.setText(lang.getString("Network")); - - //KeyboardSetup - buttonKeyboardSetup.init(800, 700,tabButtonWidth,tabButtonHeight+20); - buttonKeyboardSetup.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonKeyboardSetup.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonKeyboardSetup.setText(lang.getString("Keyboardsetup")); - } - // header - labelTitle.init(375,650); - labelTitle.setFont(CoreData::getInstance().getMenuFontVeryBig()); - labelTitle.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - labelTitle.setText(lang.getString("KeyboardsetupL")); - - labelTestTitle.init(keyButtonsXBase,155); - labelTestTitle.setFont(CoreData::getInstance().getMenuFontNormal()); - labelTestTitle.setFont3D(CoreData::getInstance().getMenuFontNormal3D()); - labelTestTitle.setText(lang.getString("KeyboardsetupTest")); - - labelTestValue.init(keyButtonsXBase,155-28); - labelTestValue.setFont(CoreData::getInstance().getMenuFontBig()); - labelTestValue.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - labelTestValue.setRenderBackground(true); - labelTestValue.setMaxEditRenderWidth(keyButtonsWidth); - labelTestValue.setText(""); - - // mainMassegeBox - mainMessageBox.init(lang.getString("Ok")); - mainMessageBox.setEnabled(false); - mainMessageBoxState=0; - - keyScrollBar.init(800,200,false,200,20); - keyScrollBar.setLength(400); - keyScrollBar.setElementCount(0); - keyScrollBar.setVisibleSize(keyButtonsToRender); - keyScrollBar.setVisibleStart(0); - - // buttons - buttonOk.init(buttonStartPos, buttonRowPos, 100); - buttonOk.setText(lang.getString("Save")); - - buttonReturn.init(buttonStartPos+110, buttonRowPos, 100); - buttonReturn.setText(lang.getString("Return")); - - buttonDefaults.init(buttonStartPos+230, buttonRowPos, 125); - buttonDefaults.setText(lang.getString("Defaults")); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - mergedProperties=configKeys.getMergedProperties(); - masterProperties=configKeys.getMasterProperties(); - //userProperties=configKeys.getUserProperties(); - userProperties.clear(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - //throw megaglest_runtime_error("Test!"); - - for(int i = 0; i < (int)mergedProperties.size(); ++i) { - - string keyName = mergedProperties[i].second; - if(keyName.length() > 0) { - //char c = configKeys.translateStringToCharKey(keyName); - SDL_Keycode c = configKeys.translateStringToSDLKey(keyName); - if(c > SDLK_UNKNOWN && c < SDL_NUM_SCANCODES) { - SDL_Keycode keysym = static_cast(c); - // SDL skips capital letters - if(keysym >= 65 && keysym <= 90) { - keysym = (SDL_Keycode)((int)keysym + 32); - } - keyName = SDL_GetKeyName(keysym); - } - else { - keyName = ""; - } - if(keyName == "unknown key" || keyName == "") { - keyName = mergedProperties[i].second; - } - } - - GraphicButton *button = new GraphicButton(containerName,string("ScrollButton")+intToStr(i)); - button->init(keyButtonsXBase, keyButtonsYBase, keyButtonsWidth,keyButtonsHeight); - button->setText(mergedProperties[i].first); - keyButtons.push_back(button); - GraphicLabel *label = new GraphicLabel(containerName,string("ScrollLabel")+intToStr(i)); - label->init(keyButtonsXBase+keyButtonsWidth+5,keyButtonsYBase,labelWidth,20); - label->setRenderBackground(true); - label->setMaxEditRenderWidth(105); - label->setText(" " + keyName); - labels.push_back(label); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - keyScrollBar.init(keyButtonsXBase+keyButtonsWidth+labelWidth+20,200,false,200,20); - keyScrollBar.setLength(400); - keyScrollBar.setElementCount((int)keyButtons.size()); - keyScrollBar.setVisibleSize(keyButtonsToRender); - keyScrollBar.setVisibleStart(0); - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] Error detected:\n%s\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - - mainMessageBoxState=1; - showMessageBox( "Error: " + string(ex.what()), "Error detected", false); - } + try { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + containerName = "KeySetup"; + + keyButtonsLineHeight = 30; + keyButtonsHeight = 25; + keyButtonsWidth = 400; + keyButtonsXBase = 200; + keyButtonsYBase = 200 + 400 - keyButtonsLineHeight; + keyButtonsToRender = 400 / keyButtonsLineHeight; + int labelWidth = 100; + + this->parentUI = parentUI; + this->console.setOnlyChatMessagesInStoredLines(false); + hotkeyIndex = -1; + hotkeyChar = SDLK_UNKNOWN; + + Lang &lang = Lang::getInstance(); + int buttonStartPos = 170; + int buttonRowPos = 50; + if (this->parentUI == NULL) { + int tabButtonWidth = 200; + int tabButtonHeight = 30; + + buttonAudioSection.init(0, 720, tabButtonWidth, tabButtonHeight); + buttonAudioSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); + buttonAudioSection.setFont3D( + CoreData::getInstance().getMenuFontVeryBig3D()); + buttonAudioSection.setText(lang.getString("Audio")); + // Video Section + buttonVideoSection.init(200, 720, tabButtonWidth, tabButtonHeight); + buttonVideoSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); + buttonVideoSection.setFont3D( + CoreData::getInstance().getMenuFontVeryBig3D()); + buttonVideoSection.setText(lang.getString("Video")); + // currentLine-=lineOffset; + // MiscSection + buttonMiscSection.init(400, 720, tabButtonWidth, tabButtonHeight); + buttonMiscSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); + buttonMiscSection.setFont3D( + CoreData::getInstance().getMenuFontVeryBig3D()); + buttonMiscSection.setText(lang.getString("Misc")); + // NetworkSettings + buttonNetworkSettings.init(600, 720, tabButtonWidth, tabButtonHeight); + buttonNetworkSettings.setFont( + CoreData::getInstance().getMenuFontVeryBig()); + buttonNetworkSettings.setFont3D( + CoreData::getInstance().getMenuFontVeryBig3D()); + buttonNetworkSettings.setText(lang.getString("Network")); + + // KeyboardSetup + buttonKeyboardSetup.init(800, 700, tabButtonWidth, tabButtonHeight + 20); + buttonKeyboardSetup.setFont(CoreData::getInstance().getMenuFontVeryBig()); + buttonKeyboardSetup.setFont3D( + CoreData::getInstance().getMenuFontVeryBig3D()); + buttonKeyboardSetup.setText(lang.getString("Keyboardsetup")); + } + // header + labelTitle.init(375, 650); + labelTitle.setFont(CoreData::getInstance().getMenuFontVeryBig()); + labelTitle.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); + labelTitle.setText(lang.getString("KeyboardsetupL")); + + labelTestTitle.init(keyButtonsXBase, 155); + labelTestTitle.setFont(CoreData::getInstance().getMenuFontNormal()); + labelTestTitle.setFont3D(CoreData::getInstance().getMenuFontNormal3D()); + labelTestTitle.setText(lang.getString("KeyboardsetupTest")); + + labelTestValue.init(keyButtonsXBase, 155 - 28); + labelTestValue.setFont(CoreData::getInstance().getMenuFontBig()); + labelTestValue.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + labelTestValue.setRenderBackground(true); + labelTestValue.setMaxEditRenderWidth(keyButtonsWidth); + labelTestValue.setText(""); + + // mainMassegeBox + mainMessageBox.init(lang.getString("Ok")); + mainMessageBox.setEnabled(false); + mainMessageBoxState = 0; + + keyScrollBar.init(800, 200, false, 200, 20); + keyScrollBar.setLength(400); + keyScrollBar.setElementCount(0); + keyScrollBar.setVisibleSize(keyButtonsToRender); + keyScrollBar.setVisibleStart(0); + + // buttons + buttonOk.init(buttonStartPos, buttonRowPos, 100); + buttonOk.setText(lang.getString("Save")); + + buttonReturn.init(buttonStartPos + 110, buttonRowPos, 100); + buttonReturn.setText(lang.getString("Return")); + + buttonDefaults.init(buttonStartPos + 230, buttonRowPos, 125); + buttonDefaults.setText(lang.getString("Defaults")); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + mergedProperties = configKeys.getMergedProperties(); + masterProperties = configKeys.getMasterProperties(); + // userProperties=configKeys.getUserProperties(); + userProperties.clear(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + // throw megaglest_runtime_error("Test!"); + + for (int i = 0; i < (int)mergedProperties.size(); ++i) { + + string keyName = mergedProperties[i].second; + if (keyName.length() > 0) { + // char c = configKeys.translateStringToCharKey(keyName); + SDL_Keycode c = configKeys.translateStringToSDLKey(keyName); + if (c > SDLK_UNKNOWN && c < SDL_NUM_SCANCODES) { + SDL_Keycode keysym = static_cast(c); + // SDL skips capital letters + if (keysym >= 65 && keysym <= 90) { + keysym = (SDL_Keycode)((int)keysym + 32); + } + keyName = SDL_GetKeyName(keysym); + } else { + keyName = ""; + } + if (keyName == "unknown key" || keyName == "") { + keyName = mergedProperties[i].second; + } + } + + GraphicButton *button = new GraphicButton( + containerName, string("ScrollButton") + intToStr(i)); + button->init(keyButtonsXBase, keyButtonsYBase, keyButtonsWidth, + keyButtonsHeight); + button->setText(mergedProperties[i].first); + keyButtons.push_back(button); + GraphicLabel *label = + new GraphicLabel(containerName, string("ScrollLabel") + intToStr(i)); + label->init(keyButtonsXBase + keyButtonsWidth + 5, keyButtonsYBase, + labelWidth, 20); + label->setRenderBackground(true); + label->setMaxEditRenderWidth(105); + label->setText(" " + keyName); + labels.push_back(label); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + keyScrollBar.init(keyButtonsXBase + keyButtonsWidth + labelWidth + 20, 200, + false, 200, 20); + keyScrollBar.setLength(400); + keyScrollBar.setElementCount((int)keyButtons.size()); + keyScrollBar.setVisibleSize(keyButtonsToRender); + keyScrollBar.setVisibleStart(0); + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] Error detected:\n%s\n", __FILE__, + __FUNCTION__, __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + mainMessageBoxState = 1; + showMessageBox("Error: " + string(ex.what()), "Error detected", false); + } } void MenuStateKeysetup::reloadUI() { - Lang &lang= Lang::getInstance(); + Lang &lang = Lang::getInstance(); - labelTitle.setText(lang.getString("KeyboardsetupL")); - labelTestTitle.setText(lang.getString("KeyboardsetupTest")); - labelTestValue.setText(""); + labelTitle.setText(lang.getString("KeyboardsetupL")); + labelTestTitle.setText(lang.getString("KeyboardsetupTest")); + labelTestValue.setText(""); - // mainMassegeBox - mainMessageBox.init(lang.getString("Ok")); + // mainMassegeBox + mainMessageBox.init(lang.getString("Ok")); - buttonOk.setText(lang.getString("Save")); - buttonReturn.setText(lang.getString("Return")); - buttonDefaults.setText(lang.getString("Defaults")); + buttonOk.setText(lang.getString("Save")); + buttonReturn.setText(lang.getString("Return")); + buttonDefaults.setText(lang.getString("Defaults")); } void MenuStateKeysetup::cleanup() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - clearUserButtons(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] END\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + clearUserButtons(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] END\n", __FILE__, + __FUNCTION__, __LINE__); } MenuStateKeysetup::~MenuStateKeysetup() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - cleanup(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] END\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + cleanup(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] END\n", __FILE__, + __FUNCTION__, __LINE__); } void MenuStateKeysetup::clearUserButtons() { - while(!keyButtons.empty()) { - delete keyButtons.back(); - keyButtons.pop_back(); - } - while(!labels.empty()) { - delete labels.back(); - labels.pop_back(); - } + while (!keyButtons.empty()) { + delete keyButtons.back(); + keyButtons.pop_back(); + } + while (!labels.empty()) { + delete labels.back(); + labels.pop_back(); + } } -void MenuStateKeysetup::mouseClick(int x, int y, MouseButton mouseButton){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - CoreData &coreData= CoreData::getInstance(); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - - if(mainMessageBox.getEnabled()){ - int button= 0; - if(mainMessageBox.mouseClick(x, y, button)) - { - soundRenderer.playFx(coreData.getClickSoundA()); - if(button==0) - { - mainMessageBox.setEnabled(false); - } - } - } - else if(keyScrollBar.mouseClick(x, y)){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - soundRenderer.playFx(coreData.getClickSoundB()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - } - else if(buttonReturn.mouseClick(x, y)){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - soundRenderer.playFx(coreData.getClickSoundB()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(this->parentUI != NULL) { - // Set the parent pointer to NULL so the owner knows it was deleted - *this->parentUI = NULL; - // Delete the main menu - delete mainMenu; - return; - } - mainMenu->setState(new MenuStateRoot(program, mainMenu)); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); +void MenuStateKeysetup::mouseClick(int x, int y, MouseButton mouseButton) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + CoreData &coreData = CoreData::getInstance(); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + + if (mainMessageBox.getEnabled()) { + int button = 0; + if (mainMessageBox.mouseClick(x, y, button)) { + soundRenderer.playFx(coreData.getClickSoundA()); + if (button == 0) { + mainMessageBox.setEnabled(false); + } } - else if(buttonDefaults.mouseClick(x, y)){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - soundRenderer.playFx(coreData.getClickSoundB()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - string userKeysFile = configKeys.getFileName(true); - - bool result = removeFile(userKeysFile.c_str()); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] delete file [%s] returned %d\n",__FILE__,__FUNCTION__,__LINE__,userKeysFile.c_str(),result); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] delete file [%s] returned %d\n",__FILE__,__FUNCTION__,__LINE__,userKeysFile.c_str(),result); - configKeys.reload(); - - if(this->parentUI != NULL) { - // Set the parent pointer to NULL so the owner knows it was deleted - *this->parentUI = NULL; - // Delete the main menu - delete mainMenu; - return; - } - - mainMenu->setState(new MenuStateKeysetup(program, mainMenu)); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + } else if (keyScrollBar.mouseClick(x, y)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + soundRenderer.playFx(coreData.getClickSoundB()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + } else if (buttonReturn.mouseClick(x, y)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + soundRenderer.playFx(coreData.getClickSoundB()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + if (this->parentUI != NULL) { + // Set the parent pointer to NULL so the owner knows it was deleted + *this->parentUI = NULL; + // Delete the main menu + delete mainMenu; + return; } - else if(buttonOk.mouseClick(x, y)){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - soundRenderer.playFx(coreData.getClickSoundB()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(userProperties.empty() == false) { - Config &config = Config::getInstance(); - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys), - std::pair(Config::glestkeys_ini_filename,Config::glestuserkeys_ini_filename), - std::pair(true,false),config.getString("GlestKeysIniPath","")); - string userKeysFile = configKeys.getFileName(true); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] save file [%s] userProperties.size() = " MG_SIZE_T_SPECIFIER "\n",__FILE__,__FUNCTION__,__LINE__,userKeysFile.c_str(),userProperties.size()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] save file [%s] userProperties.size() = " MG_SIZE_T_SPECIFIER "\n",__FILE__,__FUNCTION__,__LINE__,userKeysFile.c_str(),userProperties.size()); - - configKeys.setUserProperties(userProperties); - configKeys.save(); - configKeys.reload(); - } - - Lang &lang= Lang::getInstance(); - console.addLine(lang.getString("SettingsSaved")); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + mainMenu->setState(new MenuStateRoot(program, mainMenu)); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + } else if (buttonDefaults.mouseClick(x, y)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + soundRenderer.playFx(coreData.getClickSoundB()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + string userKeysFile = configKeys.getFileName(true); + + bool result = removeFile(userKeysFile.c_str()); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] delete file [%s] returned %d\n", __FILE__, + __FUNCTION__, __LINE__, userKeysFile.c_str(), result); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] delete file [%s] returned %d\n", __FILE__, + __FUNCTION__, __LINE__, userKeysFile.c_str(), result); + configKeys.reload(); + + if (this->parentUI != NULL) { + // Set the parent pointer to NULL so the owner knows it was deleted + *this->parentUI = NULL; + // Delete the main menu + delete mainMenu; + return; } - else if ( keyScrollBar.getElementCount() != 0) { - for (int i = keyScrollBar.getVisibleStart(); i - <= keyScrollBar.getVisibleEnd(); ++i) { - if (keyButtons[i]->mouseClick(x, y)) { - hotkeyIndex = i; - hotkeyChar = SDLK_UNKNOWN; - break; - } - } - } - - if(this->parentUI==NULL){ - if(buttonKeyboardSetup.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - return; - } - else if(buttonAudioSection.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - mainMenu->setState(new MenuStateOptionsSound(program, mainMenu,this->parentUI)); // open keyboard shortcuts setup screen - return; - } - else if(buttonNetworkSettings.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - mainMenu->setState(new MenuStateOptionsNetwork(program, mainMenu,this->parentUI)); // open keyboard shortcuts setup screen - return; - } - else if(buttonMiscSection.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - mainMenu->setState(new MenuStateOptions(program, mainMenu,this->parentUI)); // open keyboard shortcuts setup screen - return; - } - else if(buttonVideoSection.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - mainMenu->setState(new MenuStateOptionsGraphics(program, mainMenu,this->parentUI)); // open keyboard shortcuts setup screen - return; - } - } -} -void MenuStateKeysetup::mouseUp(int x, int y, const MouseButton mouseButton){ - if (mouseButton == mbLeft) { - keyScrollBar.mouseUp(x, y); - } -} + mainMenu->setState(new MenuStateKeysetup(program, mainMenu)); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + } else if (buttonOk.mouseClick(x, y)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + soundRenderer.playFx(coreData.getClickSoundB()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + if (userProperties.empty() == false) { + Config &config = Config::getInstance(); + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys), + std::pair(Config::glestkeys_ini_filename, + Config::glestuserkeys_ini_filename), + std::pair(true, false), + config.getString("GlestKeysIniPath", "")); + string userKeysFile = configKeys.getFileName(true); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] save file [%s] userProperties.size() " + "= " MG_SIZE_T_SPECIFIER "\n", + __FILE__, __FUNCTION__, __LINE__, userKeysFile.c_str(), + userProperties.size()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] save file [%s] " + "userProperties.size() = " MG_SIZE_T_SPECIFIER + "\n", + __FILE__, __FUNCTION__, __LINE__, + userKeysFile.c_str(), userProperties.size()); + + configKeys.setUserProperties(userProperties); + configKeys.save(); + configKeys.reload(); + } -void MenuStateKeysetup::mouseMove(int x, int y, const MouseState *ms){ - buttonReturn.mouseMove(x, y); - buttonOk.mouseMove(x, y); - if(this->parentUI==NULL){ - buttonKeyboardSetup.mouseMove(x, y); - buttonAudioSection.mouseMove(x, y); - buttonNetworkSettings.mouseMove(x, y); - buttonMiscSection.mouseMove(x, y); - buttonVideoSection.mouseMove(x, y); + Lang &lang = Lang::getInstance(); + console.addLine(lang.getString("SettingsSaved")); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + } else if (keyScrollBar.getElementCount() != 0) { + for (int i = keyScrollBar.getVisibleStart(); + i <= keyScrollBar.getVisibleEnd(); ++i) { + if (keyButtons[i]->mouseClick(x, y)) { + hotkeyIndex = i; + hotkeyChar = SDLK_UNKNOWN; + break; + } } - if (ms->get(mbLeft)) { - keyScrollBar.mouseDown(x, y); - } else { - keyScrollBar.mouseMove(x, y); - } - - if(keyScrollBar.getElementCount()!=0 ) { - for(int i = keyScrollBar.getVisibleStart(); i <= keyScrollBar.getVisibleEnd(); ++i) { - keyButtons[i]->mouseMove(x, y); - } + } + + if (this->parentUI == NULL) { + if (buttonKeyboardSetup.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + return; + } else if (buttonAudioSection.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + mainMenu->setState(new MenuStateOptionsSound( + program, mainMenu, + this->parentUI)); // open keyboard shortcuts setup screen + return; + } else if (buttonNetworkSettings.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + mainMenu->setState(new MenuStateOptionsNetwork( + program, mainMenu, + this->parentUI)); // open keyboard shortcuts setup screen + return; + } else if (buttonMiscSection.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + mainMenu->setState(new MenuStateOptions( + program, mainMenu, + this->parentUI)); // open keyboard shortcuts setup screen + return; + } else if (buttonVideoSection.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + mainMenu->setState(new MenuStateOptionsGraphics( + program, mainMenu, + this->parentUI)); // open keyboard shortcuts setup screen + return; } - + } } -void MenuStateKeysetup::render(){ - Renderer &renderer= Renderer::getInstance(); - - //printf("MenuStateKeysetup::render A\n"); - - if(mainMessageBox.getEnabled()) { - //printf("MenuStateKeysetup::render B\n"); - renderer.renderMessageBox(&mainMessageBox); - } - else { - //printf("MenuStateKeysetup::render C\n"); - renderer.renderButton(&buttonReturn); - renderer.renderButton(&buttonDefaults); - renderer.renderButton(&buttonOk); - if(this->parentUI==NULL){ - renderer.renderButton(&buttonKeyboardSetup); - renderer.renderButton(&buttonVideoSection); - renderer.renderButton(&buttonAudioSection); - renderer.renderButton(&buttonMiscSection); - renderer.renderButton(&buttonNetworkSettings); - } - renderer.renderLabel(&labelTitle); - renderer.renderLabel(&labelTestTitle); - renderer.renderLabel(&labelTestValue); - - if(keyScrollBar.getElementCount()!=0 ) { - for(int i = keyScrollBar.getVisibleStart(); i <= keyScrollBar.getVisibleEnd(); ++i) { - if(hotkeyIndex == i) { - renderer.renderButton(keyButtons[i],&YELLOW); - } - else { - renderer.renderButton(keyButtons[i]); - } - renderer.renderLabel(labels[i]); - } - } - renderer.renderScrollBar(&keyScrollBar); - } - - renderer.renderConsole(&console); - if(program != NULL) program->renderProgramMsgBox(); +void MenuStateKeysetup::mouseUp(int x, int y, const MouseButton mouseButton) { + if (mouseButton == mbLeft) { + keyScrollBar.mouseUp(x, y); + } } -void MenuStateKeysetup::update() { - //printf("MenuStateKeysetup::update A\n"); - - if (keyScrollBar.getElementCount() != 0) { - for (int i = keyScrollBar.getVisibleStart(); i - <= keyScrollBar.getVisibleEnd(); ++i) { - keyButtons[i]->setY(keyButtonsYBase - keyButtonsLineHeight * (i - - keyScrollBar.getVisibleStart())); - labels[i]->setY(keyButtonsYBase - keyButtonsLineHeight * (i - - keyScrollBar.getVisibleStart())); - } - } - - console.update(); +void MenuStateKeysetup::mouseMove(int x, int y, const MouseState *ms) { + buttonReturn.mouseMove(x, y); + buttonOk.mouseMove(x, y); + if (this->parentUI == NULL) { + buttonKeyboardSetup.mouseMove(x, y); + buttonAudioSection.mouseMove(x, y); + buttonNetworkSettings.mouseMove(x, y); + buttonMiscSection.mouseMove(x, y); + buttonVideoSection.mouseMove(x, y); + } + if (ms->get(mbLeft)) { + keyScrollBar.mouseDown(x, y); + } else { + keyScrollBar.mouseMove(x, y); + } + + if (keyScrollBar.getElementCount() != 0) { + for (int i = keyScrollBar.getVisibleStart(); + i <= keyScrollBar.getVisibleEnd(); ++i) { + keyButtons[i]->mouseMove(x, y); + } + } } +void MenuStateKeysetup::render() { + Renderer &renderer = Renderer::getInstance(); + + // printf("MenuStateKeysetup::render A\n"); + + if (mainMessageBox.getEnabled()) { + // printf("MenuStateKeysetup::render B\n"); + renderer.renderMessageBox(&mainMessageBox); + } else { + // printf("MenuStateKeysetup::render C\n"); + renderer.renderButton(&buttonReturn); + renderer.renderButton(&buttonDefaults); + renderer.renderButton(&buttonOk); + if (this->parentUI == NULL) { + renderer.renderButton(&buttonKeyboardSetup); + renderer.renderButton(&buttonVideoSection); + renderer.renderButton(&buttonAudioSection); + renderer.renderButton(&buttonMiscSection); + renderer.renderButton(&buttonNetworkSettings); + } + renderer.renderLabel(&labelTitle); + renderer.renderLabel(&labelTestTitle); + renderer.renderLabel(&labelTestValue); + + if (keyScrollBar.getElementCount() != 0) { + for (int i = keyScrollBar.getVisibleStart(); + i <= keyScrollBar.getVisibleEnd(); ++i) { + if (hotkeyIndex == i) { + renderer.renderButton(keyButtons[i], &YELLOW); + } else { + renderer.renderButton(keyButtons[i]); + } + renderer.renderLabel(labels[i]); + } + } + renderer.renderScrollBar(&keyScrollBar); + } + renderer.renderConsole(&console); + if (program != NULL) + program->renderProgramMsgBox(); +} -void MenuStateKeysetup::showMessageBox(const string &text, const string &header, bool toggle){ - if(!toggle){ - mainMessageBox.setEnabled(false); - } +void MenuStateKeysetup::update() { + // printf("MenuStateKeysetup::update A\n"); + + if (keyScrollBar.getElementCount() != 0) { + for (int i = keyScrollBar.getVisibleStart(); + i <= keyScrollBar.getVisibleEnd(); ++i) { + keyButtons[i]->setY(keyButtonsYBase - + keyButtonsLineHeight * + (i - keyScrollBar.getVisibleStart())); + labels[i]->setY(keyButtonsYBase - + keyButtonsLineHeight * + (i - keyScrollBar.getVisibleStart())); + } + } - if(!mainMessageBox.getEnabled()){ - mainMessageBox.setText(text); - mainMessageBox.setHeader(header); - mainMessageBox.setEnabled(true); - } - else{ - mainMessageBox.setEnabled(false); - } + console.update(); } +void MenuStateKeysetup::showMessageBox(const string &text, const string &header, + bool toggle) { + if (!toggle) { + mainMessageBox.setEnabled(false); + } + + if (!mainMessageBox.getEnabled()) { + mainMessageBox.setText(text); + mainMessageBox.setHeader(header); + mainMessageBox.setEnabled(true); + } else { + mainMessageBox.setEnabled(false); + } +} void MenuStateKeysetup::keyDown(SDL_KeyboardEvent key) { - hotkeyChar = extractKeyPressed(key); - //printf("\nkeyDown [%d]\n",hotkeyChar); - - string keyName = ""; - //if(hotkeyChar > SDLK_UNKNOWN && hotkeyChar < SDL_NUM_SCANCODES) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf ("In [%s::%s Line: %d] keyName [%s] char [%d][%d]\n",__FILE__,__FUNCTION__,__LINE__,keyName.c_str(),hotkeyChar,key.keysym.sym); - keyName = SDL_GetKeyName(hotkeyChar); - //printf ("In [%s::%s Line: %d] keyName [%s] char [%d][%d]\n",__FILE__,__FUNCTION__,__LINE__,keyName.c_str(),hotkeyChar,key.keysym.sym); - //} - //key = hotkeyChar; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf ("In [%s::%s Line: %d] keyName [%s] char [%d][%d]\n",__FILE__,__FUNCTION__,__LINE__,keyName.c_str(),hotkeyChar,key.keysym.sym); - -// SDLKey keysym = SDLK_UNKNOWN; -// if(keyName == "unknown key" || keyName == "") { -// Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); -// keysym = configKeys.translateSpecialStringToSDLKey(hotkeyChar); -// -// if(SystemFlags::VERBOSE_MODE_ENABLED) printf ("In [%s::%s Line: %d] keysym [%d]\n",__FILE__,__FUNCTION__,__LINE__,keysym); -// -// // SDL skips capital letters -// if(keysym >= 65 && keysym <= 90) { -// keysym = (SDLKey)((int)keysym + 32); -// } -// //if(keysym < 255) { -// // key = keysym; -// //} -// keyName = SDL_GetKeyName(keysym); -// } - - char szCharText[20]=""; - snprintf(szCharText,20,"%c",hotkeyChar); - char *utfStr = ConvertToUTF8(&szCharText[0]); - - char szBuf[8096] = ""; - snprintf(szBuf,8096," %s [%s][%d][%d][%d]",keyName.c_str(),utfStr,key.keysym.sym,hotkeyChar,key.keysym.mod); - labelTestValue.setText(szBuf); - //printf ("In [%s::%s Line: %d] szBuf [%s]\n",__FILE__,__FUNCTION__,__LINE__,szBuf); - - delete [] utfStr; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] hotkeyChar [%d]\n",__FILE__,__FUNCTION__,__LINE__,hotkeyChar); + hotkeyChar = extractKeyPressed(key); + // printf("\nkeyDown [%d]\n",hotkeyChar); + + string keyName = ""; + // if(hotkeyChar > SDLK_UNKNOWN && hotkeyChar < SDL_NUM_SCANCODES) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] keyName [%s] char [%d][%d]\n", __FILE__, + __FUNCTION__, __LINE__, keyName.c_str(), hotkeyChar, key.keysym.sym); + keyName = SDL_GetKeyName(hotkeyChar); + // printf ("In [%s::%s Line: %d] keyName [%s] char + // [%d][%d]\n",__FILE__,__FUNCTION__,__LINE__,keyName.c_str(),hotkeyChar,key.keysym.sym); + // } + // key = hotkeyChar; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] keyName [%s] char [%d][%d]\n", __FILE__, + __FUNCTION__, __LINE__, keyName.c_str(), hotkeyChar, key.keysym.sym); + + // SDLKey keysym = SDLK_UNKNOWN; + // if(keyName == "unknown key" || keyName == "") { + // Config &configKeys = + // Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); + // keysym = configKeys.translateSpecialStringToSDLKey(hotkeyChar); + // + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf ("In [%s::%s Line: + //%d] keysym [%d]\n",__FILE__,__FUNCTION__,__LINE__,keysym); + // + // // SDL skips capital letters + // if(keysym >= 65 && keysym <= 90) { + // keysym = (SDLKey)((int)keysym + 32); + // } + // //if(keysym < 255) { + // // key = keysym; + // //} + // keyName = SDL_GetKeyName(keysym); + // } + + char szCharText[20] = ""; + snprintf(szCharText, 20, "%c", hotkeyChar); + char *utfStr = ConvertToUTF8(&szCharText[0]); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, " %s [%s][%d][%d][%d]", keyName.c_str(), utfStr, + key.keysym.sym, hotkeyChar, key.keysym.mod); + labelTestValue.setText(szBuf); + // printf ("In [%s::%s Line: %d] szBuf + // [%s]\n",__FILE__,__FUNCTION__,__LINE__,szBuf); + + delete[] utfStr; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] hotkeyChar [%d]\n", __FILE__, __FUNCTION__, + __LINE__, hotkeyChar); } -void MenuStateKeysetup::keyPress(SDL_KeyboardEvent c) { -} +void MenuStateKeysetup::keyPress(SDL_KeyboardEvent c) {} void MenuStateKeysetup::keyUp(SDL_KeyboardEvent key) { - //Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - - if(hotkeyIndex >= 0) { - if(hotkeyChar != 0) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf ("In [%s::%s Line: %d] char [%d][%d]\n",__FILE__,__FUNCTION__,__LINE__,hotkeyChar,key.keysym.sym); - - //string keyName = ""; - //if(hotkeyChar > SDLK_UNKNOWN && hotkeyChar < SDL_NUM_SCANCODES) { - - string keyName = SDL_GetKeyName(key.keysym.sym); - if(StartsWith(keyName,"Keypad ") == false) { - keyName = SDL_GetKeyName(hotkeyChar); - key.keysym.sym = hotkeyChar; - } - //} - //key.keysym.sym = hotkeyChar; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf ("In [%s::%s Line: %d] keyName [%s] char [%d][%d]\n",__FILE__,__FUNCTION__,__LINE__,keyName.c_str(),hotkeyChar,key.keysym.sym); - - //SDLKey keysym = SDLK_UNKNOWN; -// if(keyName == "unknown key" || keyName == "") { -// Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); -// keysym = configKeys.translateSpecialStringToSDLKey(hotkeyChar); -// -// if(SystemFlags::VERBOSE_MODE_ENABLED) printf ("In [%s::%s Line: %d] keysym [%d]\n",__FILE__,__FUNCTION__,__LINE__,keysym); -// -// // SDL skips capital letters -// if(keysym >= 65 && keysym <= 90) { -// keysym = (SDLKey)((int)keysym + 32); -// } -// if(keysym < 255) { -// key = keysym; -// } -// keyName = SDL_GetKeyName(keysym); -// } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf ("In [%s::%s Line: %d] keyName [%s] char [%d][%d]\n",__FILE__,__FUNCTION__,__LINE__,keyName.c_str(),hotkeyChar,key.keysym.sym); - - if(keyName != "unknown key") { - GraphicLabel *label= labels[hotkeyIndex]; - label->setText(keyName); - - pair &nameValuePair = mergedProperties[hotkeyIndex]; - - // Need to distinguish numeric keys to be translated to real keys - // from these ACTUAL sdl keys so surround in quotes. - //printf("KeyUp #1 keyName [%s]\n", keyName.c_str()); - - if(keyName.size() == 1 && keyName[0] >= '0' && keyName[0] <= '9') { - keyName = "'" + keyName + "'"; - } - //printf("KeyUp #2 keyName [%s]\n", keyName.c_str()); - - bool isNewUserKeyEntry = true; - for(int i = 0; i < (int)userProperties.size(); ++i) { - string hotKeyName = userProperties[i].first; - if(nameValuePair.first == hotKeyName) { -// if(keysym <= SDLK_ESCAPE || keysym > 255) { -// if(keysym <= SDLK_ESCAPE) { -// userProperties[i].second = intToStr(extractKeyPressed(key)); -// } -// else { -// userProperties[i].second = keyName; -// } -// } -// else { -// userProperties[i].second = ""; -// userProperties[i].second.push_back(extractKeyPressed(key)); -// } - userProperties[i].second = keyName; - isNewUserKeyEntry = false; - break; - } - } - if(isNewUserKeyEntry == true) { - pair newNameValuePair = nameValuePair; -// if(keysym <= SDLK_ESCAPE || keysym > 255) { -// if(keysym <= SDLK_ESCAPE) { -// newNameValuePair.second = intToStr(extractKeyPressed(key)); -// } -// else { -// newNameValuePair.second = keyName; -// } -// } -// else { -// newNameValuePair.second = extractKeyPressed(key); -// } - newNameValuePair.second = keyName; - userProperties.push_back(newNameValuePair); - } - } - } - hotkeyIndex = -1; - hotkeyChar = SDLK_UNKNOWN; + // Config &configKeys = + // Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); + + if (hotkeyIndex >= 0) { + if (hotkeyChar != 0) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] char [%d][%d]\n", __FILE__, __FUNCTION__, + __LINE__, hotkeyChar, key.keysym.sym); + + // string keyName = ""; + // if(hotkeyChar > SDLK_UNKNOWN && hotkeyChar < SDL_NUM_SCANCODES) { + + string keyName = SDL_GetKeyName(key.keysym.sym); + if (StartsWith(keyName, "Keypad ") == false) { + keyName = SDL_GetKeyName(hotkeyChar); + key.keysym.sym = hotkeyChar; + } + //} + // key.keysym.sym = hotkeyChar; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] keyName [%s] char [%d][%d]\n", __FILE__, + __FUNCTION__, __LINE__, keyName.c_str(), hotkeyChar, + key.keysym.sym); + + // SDLKey keysym = SDLK_UNKNOWN; + // if(keyName == "unknown key" || keyName == "") { + // Config &configKeys = + // Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); + // keysym = + // configKeys.translateSpecialStringToSDLKey(hotkeyChar); + // + // if(SystemFlags::VERBOSE_MODE_ENABLED) + // printf ("In [%s::%s Line: %d] keysym + //[%d]\n",__FILE__,__FUNCTION__,__LINE__,keysym); + // + // // SDL skips capital letters + // if(keysym >= 65 && keysym <= 90) { + // keysym = (SDLKey)((int)keysym + + // 32); + // } + // if(keysym < 255) { + // key = keysym; + // } + // keyName = SDL_GetKeyName(keysym); + // } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] keyName [%s] char [%d][%d]\n", __FILE__, + __FUNCTION__, __LINE__, keyName.c_str(), hotkeyChar, + key.keysym.sym); + + if (keyName != "unknown key") { + GraphicLabel *label = labels[hotkeyIndex]; + label->setText(keyName); + + pair &nameValuePair = mergedProperties[hotkeyIndex]; + + // Need to distinguish numeric keys to be translated to real keys + // from these ACTUAL sdl keys so surround in quotes. + // printf("KeyUp #1 keyName [%s]\n", keyName.c_str()); + + if (keyName.size() == 1 && keyName[0] >= '0' && keyName[0] <= '9') { + keyName = "'" + keyName + "'"; + } + // printf("KeyUp #2 keyName [%s]\n", keyName.c_str()); + + bool isNewUserKeyEntry = true; + for (int i = 0; i < (int)userProperties.size(); ++i) { + string hotKeyName = userProperties[i].first; + if (nameValuePair.first == hotKeyName) { + // if(keysym <= SDLK_ESCAPE || keysym > + //255) + //{ if(keysym <= SDLK_ESCAPE) { + //userProperties[i].second = intToStr(extractKeyPressed(key)); + // } + // else { + // userProperties[i].second + //= keyName; + // } + // } + // else { + // userProperties[i].second + //= + //""; + //userProperties[i].second.push_back(extractKeyPressed(key)); + // } + userProperties[i].second = keyName; + isNewUserKeyEntry = false; + break; + } + } + if (isNewUserKeyEntry == true) { + pair newNameValuePair = nameValuePair; + // if(keysym <= SDLK_ESCAPE || keysym > + //255) { if(keysym <= + //SDLK_ESCAPE) { newNameValuePair.second + //= intToStr(extractKeyPressed(key)); + // } + // else { + // newNameValuePair.second + //= keyName; + // } + // } + // else { + // newNameValuePair.second + //= extractKeyPressed(key); + // } + newNameValuePair.second = keyName; + userProperties.push_back(newNameValuePair); + } + } } + hotkeyIndex = -1; + hotkeyChar = SDLK_UNKNOWN; + } } - -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/menu/menu_state_keysetup.h b/source/glest_game/menu/menu_state_keysetup.h index bd6a71678..86fb4da98 100644 --- a/source/glest_game/menu/menu_state_keysetup.h +++ b/source/glest_game/menu/menu_state_keysetup.h @@ -12,87 +12,89 @@ #ifndef _GLEST_GAME_MENUSTATEKEYSETUP_H_ #define _GLEST_GAME_MENUSTATEKEYSETUP_H_ +#include "leak_dumper.h" #include "main_menu.h" #include "server_line.h" -#include "leak_dumper.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // =============================== // class // =============================== -typedef vector UserButtons; -typedef vector GraphicLabels; +typedef vector UserButtons; +typedef vector GraphicLabels; -class MenuStateKeysetup: public MenuState { +class MenuStateKeysetup : public MenuState { private: - - GraphicButton buttonOk; - GraphicButton buttonDefaults; - GraphicButton buttonReturn; - - GraphicButton buttonKeyboardSetup; // configure the keyboard - GraphicButton buttonVideoSection; - GraphicButton buttonAudioSection; - GraphicButton buttonMiscSection; - GraphicButton buttonNetworkSettings; - - GraphicLabel labelTitle; - - GraphicScrollBar keyScrollBar; - UserButtons keyButtons; - GraphicLabels labels; - int keyButtonsToRender; - int keyButtonsYBase; - int keyButtonsXBase; - int keyButtonsLineHeight; - int keyButtonsHeight; - int keyButtonsWidth; - - GraphicMessageBox mainMessageBox; - int mainMessageBoxState; - vector > mergedProperties; - vector > masterProperties; - vector > userProperties; - - int hotkeyIndex; - //char hotkeyChar; - SDL_Keycode hotkeyChar; - - GraphicLabel labelTestTitle; - GraphicLabel labelTestValue; - - ProgramState **parentUI; + GraphicButton buttonOk; + GraphicButton buttonDefaults; + GraphicButton buttonReturn; + + GraphicButton buttonKeyboardSetup; // configure the keyboard + GraphicButton buttonVideoSection; + GraphicButton buttonAudioSection; + GraphicButton buttonMiscSection; + GraphicButton buttonNetworkSettings; + + GraphicLabel labelTitle; + + GraphicScrollBar keyScrollBar; + UserButtons keyButtons; + GraphicLabels labels; + int keyButtonsToRender; + int keyButtonsYBase; + int keyButtonsXBase; + int keyButtonsLineHeight; + int keyButtonsHeight; + int keyButtonsWidth; + + GraphicMessageBox mainMessageBox; + int mainMessageBoxState; + vector> mergedProperties; + vector> masterProperties; + vector> userProperties; + + int hotkeyIndex; + // char hotkeyChar; + SDL_Keycode hotkeyChar; + + GraphicLabel labelTestTitle; + GraphicLabel labelTestValue; + + ProgramState **parentUI; public: - MenuStateKeysetup(Program *program, MainMenu *mainMenu, ProgramState **parentUI=NULL); - virtual ~MenuStateKeysetup(); + MenuStateKeysetup(Program *program, MainMenu *mainMenu, + ProgramState **parentUI = NULL); + virtual ~MenuStateKeysetup(); - void mouseClick(int x, int y, MouseButton mouseButton); - void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; - void mouseUp(int x, int y, const MouseButton mouseButton); - void mouseMove(int x, int y, const MouseState *mouseState); - void update(); - void render(); + void mouseClick(int x, int y, MouseButton mouseButton); + void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; + void mouseUp(int x, int y, const MouseButton mouseButton); + void mouseMove(int x, int y, const MouseState *mouseState); + void update(); + void render(); - virtual void keyDown(SDL_KeyboardEvent key); - virtual void keyPress(SDL_KeyboardEvent c); - virtual void keyUp(SDL_KeyboardEvent key); + virtual void keyDown(SDL_KeyboardEvent key); + virtual void keyPress(SDL_KeyboardEvent c); + virtual void keyUp(SDL_KeyboardEvent key); - virtual bool isInSpecialKeyCaptureEvent() { return true; } + virtual bool isInSpecialKeyCaptureEvent() { return true; } - //static void setDisplayMessageFunction(DisplayMessageFunction pDisplayMessage) { pCB_DisplayMessage = pDisplayMessage; } + // static void setDisplayMessageFunction(DisplayMessageFunction + // pDisplayMessage) { pCB_DisplayMessage = pDisplayMessage; } - void reloadUI(); + void reloadUI(); private: - void showMessageBox(const string &text, const string &header, bool toggle); - void clearUserButtons(); - void cleanup(); + void showMessageBox(const string &text, const string &header, bool toggle); + void clearUserButtons(); + void cleanup(); }; - -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/menu/menu_state_load_game.cpp b/source/glest_game/menu/menu_state_load_game.cpp index 955c25bf2..a049791e6 100644 --- a/source/glest_game/menu/menu_state_load_game.cpp +++ b/source/glest_game/menu/menu_state_load_game.cpp @@ -11,476 +11,509 @@ #include "menu_state_load_game.h" -#include "renderer.h" -#include "sound_renderer.h" -#include "core_data.h" +#include "auto_test.h" #include "config.h" +#include "core_data.h" +#include "game.h" #include "menu_state_root.h" #include "metrics.h" #include "network_message.h" -#include "game.h" -#include "auto_test.h" +#include "renderer.h" +#include "sound_renderer.h" #include "leak_dumper.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class MenuStateLoadGame // ===================================================== -MenuStateLoadGame::MenuStateLoadGame(Program *program, MainMenu *mainMenu): - MenuState(program, mainMenu, "root") -{ - containerName = "LoadGame"; - Lang &lang= Lang::getInstance(); - - int buttonWidth = 120; - int yPos=40; - int xPos=20; - int xSpacing=20; - int slotsToRender=20; - int slotWidth=200; - - slotLinesYBase=650; - slotsLineHeight=30; - previewTexture=NULL; - buttonToDelete=NULL; - - selectedButton=NULL; - - string userData = Config::getInstance().getString("UserData_Root",""); - if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - userData = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey); - } - if(userData != "") { - endPathWithSlash(userData); - } - saveGameDir = userData +"saved/"; - - lines[0].init(0,slotLinesYBase+slotsLineHeight); - lines[1].init(0, slotLinesYBase-(slotsToRender-1)*slotsLineHeight-5); - - headerLabel.registerGraphicComponent(containerName,"headerLabel"); - headerLabel.init(400, 730); - headerLabel.setFont(CoreData::getInstance().getMenuFontBig()); - headerLabel.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - headerLabel.setText(lang.getString("LoadGameMenu")); - - noSavedGamesLabel.registerGraphicComponent(containerName,"noSavedGamesLabel"); - noSavedGamesLabel.init(20, 400); - noSavedGamesLabel.setFont(CoreData::getInstance().getMenuFontBig()); - noSavedGamesLabel.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - noSavedGamesLabel.setText(lang.getString("NoSavedGames")); - - savedGamesLabel.registerGraphicComponent(containerName,"savedGamesLabel"); - savedGamesLabel.init(150, slotLinesYBase+slotsLineHeight+10); - savedGamesLabel.setFont(CoreData::getInstance().getMenuFontBig()); - savedGamesLabel.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - savedGamesLabel.setText(lang.getString("SavedGames")); - - infoHeaderLabel.registerGraphicComponent(containerName,"infoHeaderLabel"); - infoHeaderLabel.init(600, slotLinesYBase+slotsLineHeight+10); - infoHeaderLabel.setFont(CoreData::getInstance().getMenuFontBig()); - infoHeaderLabel.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - infoHeaderLabel.setText(lang.getString("SavegameInfo")); - - versionWarningLabel.registerGraphicComponent(containerName,"versionWarningLabel"); - versionWarningLabel.init(550, 350); - versionWarningLabel.setText(""); - versionWarningLabel.setTextColor(Vec3f(1.0f,0.5f,0.5f)); - - - infoTextLabel.registerGraphicComponent(containerName,"infoTextLabel"); - infoTextLabel.init(550, 310); - infoTextLabel.setText(""); - - abortButton.registerGraphicComponent(containerName,"abortButton"); - abortButton.init(xPos, yPos, buttonWidth); - abortButton.setText(lang.getString("Abort")); - xPos+=buttonWidth+xSpacing; - loadButton.registerGraphicComponent(containerName,"loadButton"); - loadButton.init(xPos, yPos, buttonWidth+80); - loadButton.setText(lang.getString("LoadGame")); - xPos+=buttonWidth+80+xSpacing; - deleteButton.registerGraphicComponent(containerName,"deleteButton"); - deleteButton.init(xPos, yPos, buttonWidth); - deleteButton.setText(lang.getString("Delete")); - - slotsScrollBar.init(500-20,slotLinesYBase-slotsLineHeight*(slotsToRender-1),false,slotWidth,20); - slotsScrollBar.setLength(slotsLineHeight*slotsToRender); - slotsScrollBar.setElementCount(0); - slotsScrollBar.setVisibleSize(slotsToRender); - slotsScrollBar.setVisibleStart(0); - - listFiles(); - slotsScrollBar.setElementCount((int)filenames.size()); - - mainMessageBox.registerGraphicComponent(containerName,"mainMessageBox"); - mainMessageBox.init(lang.getString("Ok"),450); - mainMessageBox.setEnabled(false); - - GraphicComponent::applyAllCustomProperties(containerName); +MenuStateLoadGame::MenuStateLoadGame(Program *program, MainMenu *mainMenu) + : MenuState(program, mainMenu, "root") { + containerName = "LoadGame"; + Lang &lang = Lang::getInstance(); + + int buttonWidth = 120; + int yPos = 40; + int xPos = 20; + int xSpacing = 20; + int slotsToRender = 20; + int slotWidth = 200; + + slotLinesYBase = 650; + slotsLineHeight = 30; + previewTexture = NULL; + buttonToDelete = NULL; + + selectedButton = NULL; + + string userData = Config::getInstance().getString("UserData_Root", ""); + if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { + userData = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey); + } + if (userData != "") { + endPathWithSlash(userData); + } + saveGameDir = userData + "saved/"; + + lines[0].init(0, slotLinesYBase + slotsLineHeight); + lines[1].init(0, slotLinesYBase - (slotsToRender - 1) * slotsLineHeight - 5); + + headerLabel.registerGraphicComponent(containerName, "headerLabel"); + headerLabel.init(400, 730); + headerLabel.setFont(CoreData::getInstance().getMenuFontBig()); + headerLabel.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + headerLabel.setText(lang.getString("LoadGameMenu")); + + noSavedGamesLabel.registerGraphicComponent(containerName, + "noSavedGamesLabel"); + noSavedGamesLabel.init(20, 400); + noSavedGamesLabel.setFont(CoreData::getInstance().getMenuFontBig()); + noSavedGamesLabel.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + noSavedGamesLabel.setText(lang.getString("NoSavedGames")); + + savedGamesLabel.registerGraphicComponent(containerName, "savedGamesLabel"); + savedGamesLabel.init(150, slotLinesYBase + slotsLineHeight + 10); + savedGamesLabel.setFont(CoreData::getInstance().getMenuFontBig()); + savedGamesLabel.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + savedGamesLabel.setText(lang.getString("SavedGames")); + + infoHeaderLabel.registerGraphicComponent(containerName, "infoHeaderLabel"); + infoHeaderLabel.init(600, slotLinesYBase + slotsLineHeight + 10); + infoHeaderLabel.setFont(CoreData::getInstance().getMenuFontBig()); + infoHeaderLabel.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + infoHeaderLabel.setText(lang.getString("SavegameInfo")); + + versionWarningLabel.registerGraphicComponent(containerName, + "versionWarningLabel"); + versionWarningLabel.init(550, 350); + versionWarningLabel.setText(""); + versionWarningLabel.setTextColor(Vec3f(1.0f, 0.5f, 0.5f)); + + infoTextLabel.registerGraphicComponent(containerName, "infoTextLabel"); + infoTextLabel.init(550, 310); + infoTextLabel.setText(""); + + abortButton.registerGraphicComponent(containerName, "abortButton"); + abortButton.init(xPos, yPos, buttonWidth); + abortButton.setText(lang.getString("Abort")); + xPos += buttonWidth + xSpacing; + loadButton.registerGraphicComponent(containerName, "loadButton"); + loadButton.init(xPos, yPos, buttonWidth + 80); + loadButton.setText(lang.getString("LoadGame")); + xPos += buttonWidth + 80 + xSpacing; + deleteButton.registerGraphicComponent(containerName, "deleteButton"); + deleteButton.init(xPos, yPos, buttonWidth); + deleteButton.setText(lang.getString("Delete")); + + slotsScrollBar.init(500 - 20, + slotLinesYBase - slotsLineHeight * (slotsToRender - 1), + false, slotWidth, 20); + slotsScrollBar.setLength(slotsLineHeight * slotsToRender); + slotsScrollBar.setElementCount(0); + slotsScrollBar.setVisibleSize(slotsToRender); + slotsScrollBar.setVisibleStart(0); + + listFiles(); + slotsScrollBar.setElementCount((int)filenames.size()); + + mainMessageBox.registerGraphicComponent(containerName, "mainMessageBox"); + mainMessageBox.init(lang.getString("Ok"), 450); + mainMessageBox.setEnabled(false); + + GraphicComponent::applyAllCustomProperties(containerName); } MenuStateLoadGame::~MenuStateLoadGame() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - clearSlots(); - - cleanupTexture(&previewTexture); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] END\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + clearSlots(); + + cleanupTexture(&previewTexture); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d] END\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); } void MenuStateLoadGame::cleanupTexture(Texture2D **texture) { - if(texture != NULL && *texture != NULL) { - (*texture)->end(); - delete *texture; - *texture=NULL; - } + if (texture != NULL && *texture != NULL) { + (*texture)->end(); + delete *texture; + *texture = NULL; + } } void MenuStateLoadGame::clearSlots() { - while(!slots.empty()) { - delete slots.back(); - slots.pop_back(); - slotsGB.pop_back(); - } + while (!slots.empty()) { + delete slots.back(); + slots.pop_back(); + slotsGB.pop_back(); + } } void MenuStateLoadGame::listFiles() { - int keyButtonsXBase = 2; - int keyButtonsYBase = slotLinesYBase; - int keyButtonsWidth = 476; - int keyButtonsHeight = slotsLineHeight; - - clearSlots(); - // Save the file now - vector paths; - paths.push_back(saveGameDir); - filenames.clear(); - findAll(paths, "*.xml", filenames, true, false, true); - sort(filenames.begin(),filenames.end()); - for(int i = (int)filenames.size()-1; i > -1; i--) { - GraphicButton *button=new GraphicButton(); - button->init( keyButtonsXBase, keyButtonsYBase, keyButtonsWidth,keyButtonsHeight); - button->setText(filenames[i]); - - slots.push_back(button); - slotsGB.push_back(button); - } + int keyButtonsXBase = 2; + int keyButtonsYBase = slotLinesYBase; + int keyButtonsWidth = 476; + int keyButtonsHeight = slotsLineHeight; + + clearSlots(); + // Save the file now + vector paths; + paths.push_back(saveGameDir); + filenames.clear(); + findAll(paths, "*.xml", filenames, true, false, true); + sort(filenames.begin(), filenames.end()); + for (int i = (int)filenames.size() - 1; i > -1; i--) { + GraphicButton *button = new GraphicButton(); + button->init(keyButtonsXBase, keyButtonsYBase, keyButtonsWidth, + keyButtonsHeight); + button->setText(filenames[i]); + + slots.push_back(button); + slotsGB.push_back(button); + } } - void MenuStateLoadGame::reloadUI() { - Lang &lang= Lang::getInstance(); + Lang &lang = Lang::getInstance(); - infoHeaderLabel.setText(lang.getString("SavegameInfo")); - savedGamesLabel.setText(lang.getString("SavedGames")); - noSavedGamesLabel.setText(lang.getString("NoSavedGames")); - headerLabel.setText(lang.getString("LoadGameMenu")); + infoHeaderLabel.setText(lang.getString("SavegameInfo")); + savedGamesLabel.setText(lang.getString("SavedGames")); + noSavedGamesLabel.setText(lang.getString("NoSavedGames")); + headerLabel.setText(lang.getString("LoadGameMenu")); - abortButton.setText(lang.getString("Abort")); - deleteButton.setText(lang.getString("Delete")); - loadButton.setText(lang.getString("LoadGame")); + abortButton.setText(lang.getString("Abort")); + deleteButton.setText(lang.getString("Delete")); + loadButton.setText(lang.getString("LoadGame")); - mainMessageBox.init(lang.getString("Ok"),450); + mainMessageBox.init(lang.getString("Ok"), 450); - GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); + GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); } -void MenuStateLoadGame::mouseDoubleClick(int x, int y, MouseButton mouseButton) { - if (mouseButton == mbLeft && selectedButton != NULL && selectedButton->mouseClick(x, y)) { - mouseClick(loadButton.getX()+1, loadButton.getY()+1, mouseButton); - } +void MenuStateLoadGame::mouseDoubleClick(int x, int y, + MouseButton mouseButton) { + if (mouseButton == mbLeft && selectedButton != NULL && + selectedButton->mouseClick(x, y)) { + mouseClick(loadButton.getX() + 1, loadButton.getY() + 1, mouseButton); + } } -void MenuStateLoadGame::mouseClick(int x, int y, MouseButton mouseButton){ - - CoreData &coreData= CoreData::getInstance(); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - - if(mainMessageBox.getEnabled()) { - soundRenderer.playFx(coreData.getClickSoundA()); - int button= 0; - if(mainMessageBox.mouseClick(x, y, button)) { - mainMessageBox.setEnabled(false); - - Lang &lang= Lang::getInstance(); - mainMessageBox.init(lang.getString("Ok"),450); - } - } - if(abortButton.mouseClick(x, y)) { - soundRenderer.playFx(coreData.getClickSoundA()); - mainMenu->setState(new MenuStateRoot(program, mainMenu)); +void MenuStateLoadGame::mouseClick(int x, int y, MouseButton mouseButton) { + + CoreData &coreData = CoreData::getInstance(); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + + if (mainMessageBox.getEnabled()) { + soundRenderer.playFx(coreData.getClickSoundA()); + int button = 0; + if (mainMessageBox.mouseClick(x, y, button)) { + mainMessageBox.setEnabled(false); + + Lang &lang = Lang::getInstance(); + mainMessageBox.init(lang.getString("Ok"), 450); } - else if(deleteButton.mouseClick(x, y)) { - soundRenderer.playFx(coreData.getClickSoundB()); - if(selectedButton == NULL) { - console.addStdMessage("NothingSelected",true); - } - else { - string slotname = selectedButton->getText(); - string filename = saveGameDir + selectedButton->getText() + ".xml"; - string jpgfilename = saveGameDir + selectedButton->getText() + ".xml.jpg"; - string replayfilename = saveGameDir + selectedButton->getText() + ".xml.replay"; - - Lang &lang= Lang::getInstance(); - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("LoadGameDeletingFile","",true).c_str(),filename.c_str()); - console.addLineOnly(szBuf); - - for(int i = 0; i < (int)slots.size(); i++) { - if(slots[i] == selectedButton) { - if(removeFile(filename) == true) { - removeFile(jpgfilename); - removeFile(replayfilename); - cleanupTexture(&previewTexture); - - infoTextLabel.setText(""); - listFiles(); - slotsScrollBar.setElementCount((int)filenames.size()); - - selectedButton = NULL; - } - break; - } - } - } + } + if (abortButton.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + mainMenu->setState(new MenuStateRoot(program, mainMenu)); + } else if (deleteButton.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundB()); + if (selectedButton == NULL) { + console.addStdMessage("NothingSelected", true); + } else { + string slotname = selectedButton->getText(); + string filename = saveGameDir + selectedButton->getText() + ".xml"; + string jpgfilename = saveGameDir + selectedButton->getText() + ".xml.jpg"; + string replayfilename = + saveGameDir + selectedButton->getText() + ".xml.replay"; + + Lang &lang = Lang::getInstance(); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("LoadGameDeletingFile", "", true).c_str(), + filename.c_str()); + console.addLineOnly(szBuf); + + for (int i = 0; i < (int)slots.size(); i++) { + if (slots[i] == selectedButton) { + if (removeFile(filename) == true) { + removeFile(jpgfilename); + removeFile(replayfilename); + cleanupTexture(&previewTexture); + + infoTextLabel.setText(""); + listFiles(); + slotsScrollBar.setElementCount((int)filenames.size()); + + selectedButton = NULL; + } + break; + } + } } - else if(loadButton.mouseClick(x, y)) { - soundRenderer.playFx(coreData.getClickSoundB()); - - if(selectedButton == NULL) { - console.addStdMessage("NothingSelected",true); - } - else { - string filename = saveGameDir + selectedButton->getText() + ".xml"; - - Lang &lang= Lang::getInstance(); - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("LoadGameLoadingFile","",true).c_str(),filename.c_str()); - console.addLineOnly(szBuf); - - try { - Game::loadGame(filename,program,false); - } - catch(const megaglest_runtime_error &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d]\nError [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - - showMessageBox(ex.what(), lang.getString("Notice"), false); - } - return; - } + } else if (loadButton.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundB()); + + if (selectedButton == NULL) { + console.addStdMessage("NothingSelected", true); + } else { + string filename = saveGameDir + selectedButton->getText() + ".xml"; + + Lang &lang = Lang::getInstance(); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("LoadGameLoadingFile", "", true).c_str(), + filename.c_str()); + console.addLineOnly(szBuf); + + try { + Game::loadGame(filename, program, false); + } catch (const megaglest_runtime_error &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d]\nError [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + + showMessageBox(ex.what(), lang.getString("Notice"), false); + } + return; } - else if(slotsScrollBar.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - } - else { - if(slotsScrollBar.getElementCount()!=0){ - for(int i = slotsScrollBar.getVisibleStart(); i <= slotsScrollBar.getVisibleEnd(); ++i) { - if(slots[i]->mouseClick(x, y) && selectedButton != slots[i]) { - soundRenderer.playFx(coreData.getClickSoundB()); - - Lang &lang= Lang::getInstance(); - cleanupTexture(&previewTexture); - selectedButton = slots[i]; - string filename = saveGameDir + selectedButton->getText()+".xml"; - string screenShotFilename = filename + ".jpg"; - if(fileExists(screenShotFilename) == true) { - try { - previewTexture = GraphicsInterface::getInstance().getFactory()->newTexture2D(); - if(previewTexture) { - previewTexture->setMipmap(true); - previewTexture->load(screenShotFilename); - previewTexture->init(); - } - } - catch(const megaglest_runtime_error &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d]\nError [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - - cleanupTexture(&previewTexture); - showMessageBox(ex.what(), lang.getString("Notice"), false); - } - } - else { - previewTexture=NULL; - } - - if(fileExists(filename) == true) { - // Xerces is infinitely slower than rapidxml - xml_engine_parser_type engine_type = XML_RAPIDXML_ENGINE; + } else if (slotsScrollBar.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + } else { + if (slotsScrollBar.getElementCount() != 0) { + for (int i = slotsScrollBar.getVisibleStart(); + i <= slotsScrollBar.getVisibleEnd(); ++i) { + if (slots[i]->mouseClick(x, y) && selectedButton != slots[i]) { + soundRenderer.playFx(coreData.getClickSoundB()); + + Lang &lang = Lang::getInstance(); + cleanupTexture(&previewTexture); + selectedButton = slots[i]; + string filename = saveGameDir + selectedButton->getText() + ".xml"; + string screenShotFilename = filename + ".jpg"; + if (fileExists(screenShotFilename) == true) { + try { + previewTexture = + GraphicsInterface::getInstance().getFactory()->newTexture2D(); + if (previewTexture) { + previewTexture->setMipmap(true); + previewTexture->load(screenShotFilename); + previewTexture->init(); + } + } catch (const megaglest_runtime_error &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d]\nError [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + + cleanupTexture(&previewTexture); + showMessageBox(ex.what(), lang.getString("Notice"), false); + } + } else { + previewTexture = NULL; + } + + if (fileExists(filename) == true) { + // Xerces is infinitely slower than rapidxml + xml_engine_parser_type engine_type = XML_RAPIDXML_ENGINE; #if defined(WANT_XERCES) - if(Config::getInstance().getBool("ForceXMLLoadGameUsingXerces","false") == true) { - engine_type = XML_XERCES_ENGINE; - } + if (Config::getInstance().getBool("ForceXMLLoadGameUsingXerces", + "false") == true) { + engine_type = XML_XERCES_ENGINE; + } #endif - XmlTree xmlTree(engine_type); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Before load of XML\n"); - std::map mapExtraTagReplacementValues; - try { - xmlTree.load(filename, Properties::getTagReplacementValues(&mapExtraTagReplacementValues),true,false,true); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("After load of XML\n"); - - const XmlNode *rootNode= xmlTree.getRootNode(); - if(rootNode != NULL && rootNode->hasChild("megaglest-saved-game") == true) { - rootNode = rootNode->getChild("megaglest-saved-game"); - } - - if(rootNode == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Invalid XML saved game file: [%s]",filename.c_str()); - infoTextLabel.setText(szBuf); - return; - } - - const XmlNode *versionNode= rootNode; - string gameVer = versionNode->getAttribute("version")->getValue(); - if(gameVer != glestVersionString && checkVersionComptability(gameVer, glestVersionString) == false) { - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("SavedGameBadVersion").c_str(),gameVer.c_str(),glestVersionString.c_str()); - versionWarningLabel.setText(szBuf); - } - else { - versionWarningLabel.setText(""); - } - XmlNode *gameNode = rootNode->getChild("Game"); - GameSettings newGameSettings; - newGameSettings.loadGame(gameNode); - - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("LoadSavedGameInfo").c_str(), - newGameSettings.getMap().c_str(), - newGameSettings.getTileset().c_str(), - newGameSettings.getTech().c_str(), - newGameSettings.getScenario().c_str(), - newGameSettings.getFactionCount(), - (newGameSettings.getThisFactionIndex() >= 0 && - newGameSettings.getThisFactionIndex() < newGameSettings.getFactionCount() ? - newGameSettings.getFactionTypeName(newGameSettings.getThisFactionIndex()).c_str() : "")); - infoTextLabel.setText(szBuf); - } - catch(const megaglest_runtime_error &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d]\nError [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - - showMessageBox(ex.what(), lang.getString("Notice"), false); - } - } - else { - infoTextLabel.setText(""); - } - - break; - } - } - } + XmlTree xmlTree(engine_type); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Before load of XML\n"); + std::map mapExtraTagReplacementValues; + try { + xmlTree.load(filename, + Properties::getTagReplacementValues( + &mapExtraTagReplacementValues), + true, false, true); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("After load of XML\n"); + + const XmlNode *rootNode = xmlTree.getRootNode(); + if (rootNode != NULL && + rootNode->hasChild("megaglest-saved-game") == true) { + rootNode = rootNode->getChild("megaglest-saved-game"); + } + + if (rootNode == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "Invalid XML saved game file: [%s]", + filename.c_str()); + infoTextLabel.setText(szBuf); + return; + } + + const XmlNode *versionNode = rootNode; + string gameVer = versionNode->getAttribute("version")->getValue(); + if (gameVer != glestVersionString && + checkVersionComptability(gameVer, glestVersionString) == + false) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("SavedGameBadVersion").c_str(), + gameVer.c_str(), glestVersionString.c_str()); + versionWarningLabel.setText(szBuf); + } else { + versionWarningLabel.setText(""); + } + XmlNode *gameNode = rootNode->getChild("Game"); + GameSettings newGameSettings; + newGameSettings.loadGame(gameNode); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, lang.getString("LoadSavedGameInfo").c_str(), + newGameSettings.getMap().c_str(), + newGameSettings.getTileset().c_str(), + newGameSettings.getTech().c_str(), + newGameSettings.getScenario().c_str(), + newGameSettings.getFactionCount(), + (newGameSettings.getThisFactionIndex() >= 0 && + newGameSettings.getThisFactionIndex() < + newGameSettings.getFactionCount() + ? newGameSettings + .getFactionTypeName( + newGameSettings.getThisFactionIndex()) + .c_str() + : "")); + infoTextLabel.setText(szBuf); + } catch (const megaglest_runtime_error &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d]\nError [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + + showMessageBox(ex.what(), lang.getString("Notice"), false); + } + } else { + infoTextLabel.setText(""); + } + + break; + } + } } + } } void MenuStateLoadGame::mouseUp(int x, int y, const MouseButton mouseButton) { - if (mouseButton == mbLeft) { - slotsScrollBar.mouseUp(x, y); - } + if (mouseButton == mbLeft) { + slotsScrollBar.mouseUp(x, y); + } } void MenuStateLoadGame::mouseMove(int x, int y, const MouseState *ms) { - abortButton.mouseMove(x, y); - deleteButton.mouseMove(x, y); - loadButton.mouseMove(x, y); - if(slotsScrollBar.getElementCount()!=0){ - for(int i = slotsScrollBar.getVisibleStart(); i <= slotsScrollBar.getVisibleEnd(); ++i) { - slots[i]->mouseMove(x, y); - } - } - slotsScrollBar.mouseMove(x,y); + abortButton.mouseMove(x, y); + deleteButton.mouseMove(x, y); + loadButton.mouseMove(x, y); + if (slotsScrollBar.getElementCount() != 0) { + for (int i = slotsScrollBar.getVisibleStart(); + i <= slotsScrollBar.getVisibleEnd(); ++i) { + slots[i]->mouseMove(x, y); + } + } + slotsScrollBar.mouseMove(x, y); } void MenuStateLoadGame::render() { - Renderer &renderer= Renderer::getInstance(); - - renderer.renderLabel(&headerLabel); - renderer.renderLabel(&savedGamesLabel); - renderer.renderLabel(&infoHeaderLabel); - renderer.renderLabel(&infoTextLabel); - if(versionWarningLabel.getText()!="") - renderer.renderLabel(&versionWarningLabel); + Renderer &renderer = Renderer::getInstance(); + + renderer.renderLabel(&headerLabel); + renderer.renderLabel(&savedGamesLabel); + renderer.renderLabel(&infoHeaderLabel); + renderer.renderLabel(&infoTextLabel); + if (versionWarningLabel.getText() != "") + renderer.renderLabel(&versionWarningLabel); + + renderer.renderButton(&abortButton); + renderer.renderButton(&deleteButton); + renderer.renderButton(&loadButton); + + for (int i = 0; i < (int)sizeof(lines) / (int)sizeof(lines[0]); ++i) { + renderer.renderLine(&lines[i]); + } + + if (slotsScrollBar.getElementCount() == 0) { + renderer.renderLabel(&noSavedGamesLabel); + } else { + for (int i = slotsScrollBar.getVisibleStart(); + i <= slotsScrollBar.getVisibleEnd(); ++i) { + if (slots[i] == selectedButton) { + bool lightedOverride = true; + renderer.renderButton(slots[i], &YELLOW, &lightedOverride); + } else { + renderer.renderButton(slots[i]); + } + } + } + renderer.renderScrollBar(&slotsScrollBar); - renderer.renderButton(&abortButton); - renderer.renderButton(&deleteButton); - renderer.renderButton(&loadButton); + if (previewTexture != NULL) { + renderer.renderTextureQuad(550, slotLinesYBase - 300 + slotsLineHeight, 400, + 300, previewTexture, 1.0f); + } - for(int i = 0; i < (int)sizeof(lines) / (int)sizeof(lines[0]); ++i){ - renderer.renderLine(&lines[i]); - } + if (mainMessageBox.getEnabled()) { + renderer.renderMessageBox(&mainMessageBox); + } - if(slotsScrollBar.getElementCount()==0 ) { - renderer.renderLabel(&noSavedGamesLabel); - } - else{ - for(int i = slotsScrollBar.getVisibleStart(); i <= slotsScrollBar.getVisibleEnd(); ++i) { - if(slots[i]==selectedButton){ - bool lightedOverride = true; - renderer.renderButton(slots[i],&YELLOW,&lightedOverride); - } - else{ - renderer.renderButton(slots[i]); - } - } - } - renderer.renderScrollBar(&slotsScrollBar); - - if(previewTexture != NULL) { - renderer.renderTextureQuad(550,slotLinesYBase-300+slotsLineHeight,400,300,previewTexture,1.0f); - } - - if(mainMessageBox.getEnabled()) { - renderer.renderMessageBox(&mainMessageBox); - } - - renderer.renderConsole(&console); - if(program != NULL) program->renderProgramMsgBox(); + renderer.renderConsole(&console); + if (program != NULL) + program->renderProgramMsgBox(); } -void MenuStateLoadGame::update(){ - if(Config::getInstance().getBool("AutoTest")){ - AutoTest::getInstance().updateNewGame(program, mainMenu); - return; - } - slotsScrollBar.arrangeComponents(slotsGB); - console.update(); +void MenuStateLoadGame::update() { + if (Config::getInstance().getBool("AutoTest")) { + AutoTest::getInstance().updateNewGame(program, mainMenu); + return; + } + slotsScrollBar.arrangeComponents(slotsGB); + console.update(); } void MenuStateLoadGame::keyDown(SDL_KeyboardEvent key) { - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - if(isKeyPressed(configKeys.getSDLKey("SaveGUILayout"),key) == true) { - GraphicComponent::saveAllCustomProperties(containerName); - } + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + if (isKeyPressed(configKeys.getSDLKey("SaveGUILayout"), key) == true) { + GraphicComponent::saveAllCustomProperties(containerName); + } } -void MenuStateLoadGame::showMessageBox(const string &text, const string &header, bool toggle) { - if(toggle == false) { - mainMessageBox.setEnabled(false); - } - - if(mainMessageBox.getEnabled() == false) { - mainMessageBox.setText(text); - mainMessageBox.setHeader(header); - mainMessageBox.setEnabled(true); - } - else{ - mainMessageBox.setEnabled(false); - } +void MenuStateLoadGame::showMessageBox(const string &text, const string &header, + bool toggle) { + if (toggle == false) { + mainMessageBox.setEnabled(false); + } + + if (mainMessageBox.getEnabled() == false) { + mainMessageBox.setText(text); + mainMessageBox.setHeader(header); + mainMessageBox.setEnabled(true); + } else { + mainMessageBox.setEnabled(false); + } } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/menu/menu_state_load_game.h b/source/glest_game/menu/menu_state_load_game.h index ca344ce92..bdd84b4b6 100644 --- a/source/glest_game/menu/menu_state_load_game.h +++ b/source/glest_game/menu/menu_state_load_game.h @@ -3,79 +3,79 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== #ifndef _GLEST_GAME_MENUSTATELOADGAME_H_ #define _GLEST_GAME_MENUSTATELOADGAME_H_ -#include "main_menu.h" #include "leak_dumper.h" +#include "main_menu.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // =============================== // class MenuStateLoadGame // =============================== -//typedef vector SaveSlotButtons; -class MenuStateLoadGame: public MenuState{ +// typedef vector SaveSlotButtons; +class MenuStateLoadGame : public MenuState { private: - GraphicButton loadButton; - GraphicButton deleteButton; - GraphicButton abortButton; - vector slots; - vector slotsGB; - vector filenames; - GraphicScrollBar slotsScrollBar; - GraphicButton* selectedButton; + GraphicButton loadButton; + GraphicButton deleteButton; + GraphicButton abortButton; + vector slots; + vector slotsGB; + vector filenames; + GraphicScrollBar slotsScrollBar; + GraphicButton *selectedButton; - GraphicButton* buttonToDelete; + GraphicButton *buttonToDelete; - Texture2D *previewTexture; + Texture2D *previewTexture; - GraphicLabel headerLabel; - GraphicLabel noSavedGamesLabel; - GraphicLabel savedGamesLabel; - GraphicLabel infoHeaderLabel; - GraphicLabel infoTextLabel; - GraphicLabel versionWarningLabel; + GraphicLabel headerLabel; + GraphicLabel noSavedGamesLabel; + GraphicLabel savedGamesLabel; + GraphicLabel infoHeaderLabel; + GraphicLabel infoTextLabel; + GraphicLabel versionWarningLabel; - GraphicLine lines[2]; + GraphicLine lines[2]; - GraphicMessageBox mainMessageBox; + GraphicMessageBox mainMessageBox; - string saveGameDir; - int slotLinesYBase; - int slotsLineHeight; + string saveGameDir; + int slotLinesYBase; + int slotsLineHeight; public: - MenuStateLoadGame(Program *program, MainMenu *mainMenu); - ~MenuStateLoadGame(); + MenuStateLoadGame(Program *program, MainMenu *mainMenu); + ~MenuStateLoadGame(); - void mouseClick(int x, int y, MouseButton mouseButton); - void mouseDoubleClick(int x, int y, MouseButton mouseButton); - void mouseUp(int x, int y, const MouseButton mouseButton); - void mouseMove(int x, int y, const MouseState *mouseState); - void update(); - void render(); - virtual void keyDown(SDL_KeyboardEvent key); + void mouseClick(int x, int y, MouseButton mouseButton); + void mouseDoubleClick(int x, int y, MouseButton mouseButton); + void mouseUp(int x, int y, const MouseButton mouseButton); + void mouseMove(int x, int y, const MouseState *mouseState); + void update(); + void render(); + virtual void keyDown(SDL_KeyboardEvent key); - void reloadUI(); + void reloadUI(); private: + void clearSlots(); + void listFiles(); - void clearSlots(); - void listFiles(); + void showMessageBox(const string &text, const string &header, bool toggle); - void showMessageBox(const string &text, const string &header, bool toggle); - - void cleanupTexture(Texture2D **texture); + void cleanupTexture(Texture2D **texture); }; - -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/menu/menu_state_masterserver.cpp b/source/glest_game/menu/menu_state_masterserver.cpp index 720b84c4e..08aca4d41 100644 --- a/source/glest_game/menu/menu_state_masterserver.cpp +++ b/source/glest_game/menu/menu_state_masterserver.cpp @@ -11,1242 +11,1549 @@ #include "menu_state_masterserver.h" -#include "server_line.h" -#include "renderer.h" -#include "sound_renderer.h" -#include "core_data.h" +#include "auto_test.h" +#include "cache_manager.h" #include "config.h" +#include "core_data.h" +#include "leak_dumper.h" +#include "masterserver_info.h" #include "menu_state_connected_game.h" #include "menu_state_custom_game.h" #include "menu_state_new_game.h" #include "metrics.h" #include "network_manager.h" #include "network_message.h" -#include "auto_test.h" +#include "renderer.h" +#include "server_line.h" #include "socket.h" -#include "masterserver_info.h" +#include "sound_renderer.h" #include -#include "cache_manager.h" -#include "leak_dumper.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { DisplayMessageFunction MenuStateMasterserver::pCB_DisplayMessage = NULL; -static string IRC_SERVER = "irc.libera.chat"; -static string IRC_CHANNEL = "#megaglest-lobby"; +static string IRC_SERVER = "irc.libera.chat"; +static string IRC_CHANNEL = "#megaglest-lobby"; // ===================================================== // class MenuStateMasterserver // ===================================================== -MenuStateMasterserver::MenuStateMasterserver(Program *program, MainMenu *mainMenu) : - MenuState(program, mainMenu, "masterserver"), mutexIRCClient(new Mutex(CODE_AT_LINE)) -{ - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n\n\n******************** ENTERING MASTERSERVER MENU\n\n\n\n\n"); - - containerName = "MasterServer"; - masterserverParseErrorShown = false; - updateFromMasterserverThread = NULL; - ircClient = NULL; - serverInfoString="empty"; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - Lang &lang= Lang::getInstance(); - - //Configure ConsolePosition - consoleIRC.setYPos(60); - consoleIRC.setFont(CoreData::getInstance().getMenuFontNormal()); - consoleIRC.setFont3D(CoreData::getInstance().getMenuFontNormal3D()); - consoleIRC.setLineHeight(18); - consoleIRC.setOnlyChatMessagesInStoredLines(false); - - serverLinesToRender=8; - serverLinesLineHeight=25; - serverLinesYBase=680; - - userButtonsHeight=20; - userButtonsWidth=150; - userButtonsLineHeight=userButtonsHeight+2; - userButtonsYBase=serverLinesYBase-(serverLinesToRender)*serverLinesLineHeight-90; - userButtonsToRender=userButtonsYBase/userButtonsLineHeight; - userButtonsXBase=1000-userButtonsWidth; - - userScrollBar.init(1000-20,0,false,200,20); - userScrollBar.setLength(userButtonsYBase+userButtonsLineHeight); - userScrollBar.setElementCount(0); - userScrollBar.setVisibleSize(userButtonsToRender); - userScrollBar.setVisibleStart(0); - - userButtonsXBase=1000-userButtonsWidth-userScrollBar.getW(); - - serverScrollBar.init(1000-20,serverLinesYBase-serverLinesLineHeight*(serverLinesToRender-1),false,200,20); - serverScrollBar.setLength(serverLinesLineHeight*serverLinesToRender); - serverScrollBar.setElementCount(0); - serverScrollBar.setVisibleSize(serverLinesToRender); - serverScrollBar.setVisibleStart(0); - - lines[0].init(0, userButtonsYBase+userButtonsLineHeight+serverLinesLineHeight); - lines[1].init(userButtonsXBase-5,0,5,userButtonsYBase+2*userButtonsLineHeight); - lines[1].setHorizontal(false); - - autoRefreshTime=0; - playServerFoundSound=false; - announcementLoaded=false; - - mainMessageBox.registerGraphicComponent(containerName,"mainMessageBox"); - mainMessageBox.init(lang.getString("Ok")); - mainMessageBox.setEnabled(false); - mainMessageBoxState=0; - - lastRefreshTimer= time(NULL); - - // announcement - announcementLabel.registerGraphicComponent(containerName,"announcementLabel"); - announcementLabel.init(10, 730); - announcementLabel.setFont(CoreData::getInstance().getMenuFontBig()); - announcementLabel.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - announcementLabel.setText(""); - - // versionInfo - versionInfoLabel.registerGraphicComponent(containerName,"versionInfoLabel"); - versionInfoLabel.init(10, 680); - versionInfoLabel.setFont(CoreData::getInstance().getMenuFontBig()); - versionInfoLabel.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - versionInfoLabel.setText(""); - - // header - labelTitle.registerGraphicComponent(containerName,"labelTitle"); - labelTitle.init(410, serverLinesYBase+45); - labelTitle.setFont(CoreData::getInstance().getMenuFontBig()); - labelTitle.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - labelTitle.setText(lang.getString("AvailableServers")); - - if(Config::getInstance().getString("Masterserver","") == "") { - labelTitle.setText("*** " + lang.getString("AvailableServers")); - } - - // bottom - int buttonPos=230; - - // Titles for current games - START - int lineIndex = 0; - int lineOffset=25*lineIndex; - int i=5; - int startOffset=serverLinesYBase+23; - - //general info: - //i+=10; - glestVersionLabel.registerGraphicComponent(containerName,"glestVersionLabel"); - glestVersionLabel.init(i,startOffset-lineOffset); - glestVersionLabel.setText(lang.getString("MGVersion")); - - i+=80; - platformLabel.registerGraphicComponent(containerName,"platformLabel"); - platformLabel.init(i+15,startOffset-lineOffset); - platformLabel.setText(lang.getString("MGPlatform")); - -// i+=50; -// binaryCompileDateLabel.registerGraphicComponent(containerName,"binaryCompileDateLabel"); -// binaryCompileDateLabel.init(i,startOffset-lineOffset); -// binaryCompileDateLabel.setText(lang.getString("MGBuildDateTime")); - - //game info: - i+=120; - serverTitleLabel.registerGraphicComponent(containerName,"serverTitleLabel"); - serverTitleLabel.init(i,startOffset-lineOffset); - serverTitleLabel.setText(lang.getString("MGGameTitle")); - - i+=170; - countryLabel.registerGraphicComponent(containerName,"countryLabel"); - countryLabel.init(i-10,startOffset-lineOffset); - countryLabel.setText(lang.getString("MGGameCountry")); - - i+=60; - -// ipAddressLabel.registerGraphicComponent(containerName,"ipAddressLabel"); -// ipAddressLabel.init(i,startOffset-lineOffset); -// ipAddressLabel.setText(lang.getString("MGGameIP")); -// i+=100; - - //game setup info: - techLabel.registerGraphicComponent(containerName,"techLabel"); - techLabel.init(i,startOffset-lineOffset); - techLabel.setText(lang.getString("TechTree")); - - i+=165; - mapLabel.registerGraphicComponent(containerName,"mapLabel"); - mapLabel.init(i,startOffset-lineOffset); - mapLabel.setText(lang.getString("Map")); - - i+=95; -// tilesetLabel.registerGraphicComponent(containerName,"tilesetLabel"); -// tilesetLabel.init(i,startOffset-lineOffset); -// tilesetLabel.setText(lang.getString("Tileset")); -// i+=100; - - activeSlotsLabel.registerGraphicComponent(containerName,"activeSlotsLabel"); - activeSlotsLabel.init(i,startOffset-lineOffset); - activeSlotsLabel.setText(lang.getString("MGGameSlots")); - - i+=50; - //externalConnectPort.registerGraphicComponent(containerName,"externalConnectPort"); - //externalConnectPort.init(i,startOffset-lineOffset); - //externalConnectPort.setText(lang.getString("Port")); - - i+=30; - statusLabel.registerGraphicComponent(containerName,"statusLabel"); - statusLabel.init(i+5,startOffset-lineOffset); - statusLabel.setText(lang.getString("MGGameStatus")); - - i+=130; - selectButton.registerGraphicComponent(containerName,"selectButton"); - selectButton.init(i-5, startOffset-lineOffset); - selectButton.setText(lang.getString("MGJoinGameSlots")); - - // Titles for current games - END - - buttonReturn.registerGraphicComponent(containerName,"buttonReturn"); - buttonReturn.init(50, buttonPos, 150); - - buttonCreateGame.registerGraphicComponent(containerName,"buttonCreateGame"); - buttonCreateGame.init(275, buttonPos, 150); - - buttonRefresh.registerGraphicComponent(containerName,"buttonRefresh"); - buttonRefresh.init(500, buttonPos, 150); - - buttonRefresh.setText(lang.getString("RefreshList")); - buttonReturn.setText(lang.getString("Return")); - buttonCreateGame.setText(lang.getString("HostGame")); - labelAutoRefresh.setText(lang.getString("AutoRefreshRate")); - - labelAutoRefresh.registerGraphicComponent(containerName,"labelAutoRefresh"); - labelAutoRefresh.init(750,buttonPos+30); - - listBoxAutoRefresh.registerGraphicComponent(containerName,"listBoxAutoRefresh"); - listBoxAutoRefresh.init(750,buttonPos); - listBoxAutoRefresh.pushBackItem(lang.getString("Off")); - listBoxAutoRefresh.pushBackItem("10 s"); - listBoxAutoRefresh.pushBackItem("20 s"); - listBoxAutoRefresh.pushBackItem("30 s"); - listBoxAutoRefresh.setSelectedItemIndex(2); - autoRefreshTime=10*listBoxAutoRefresh.getSelectedItemIndex(); - - ircOnlinePeopleLabel.registerGraphicComponent(containerName,"ircOnlinePeopleLabel"); - ircOnlinePeopleLabel.init(userButtonsXBase,userButtonsYBase+userButtonsLineHeight); - ircOnlinePeopleLabel.setText(lang.getString("IRCPeopleOnline")); - - ircOnlinePeopleStatusLabel.registerGraphicComponent(containerName,"ircOnlinePeopleStatusLabel"); - ircOnlinePeopleStatusLabel.init(userButtonsXBase,userButtonsYBase+userButtonsLineHeight-20); - ircOnlinePeopleStatusLabel.setText(""); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - NetworkManager::getInstance().end(); - NetworkManager::getInstance().init(nrClient); - - //console.addLine(lang.getString("ToSwitchOffMusicPress")+" - \""+configKeys.getCharKey("ToggleMusic")+"\""); - - GraphicComponent::applyAllCustomProperties(containerName); - - char szIRCNick[80]=""; - Chrono seed(true); - srand((unsigned int)seed.getCurTicks()); - - int randomNickId = rand() % 999; - string netPlayerName=Config::getInstance().getString("NetPlayerName",Socket::getHostName().c_str()); - string ircname=netPlayerName.substr(0,9); - snprintf(szIRCNick,80,"MG_%s_%d",ircname.c_str(),randomNickId); - normalizeNick(szIRCNick); - - currentIrcNick=ircname; - consoleIRC.setStringToHighlight(currentIrcNick); - - lines[2].init(0,consoleIRC.getYPos()-10,userButtonsXBase,5); - chatManager.init(&consoleIRC, -1, true, szIRCNick); - chatManager.setXPos(0); - chatManager.setYPos(consoleIRC.getYPos()-20); - chatManager.setFont(CoreData::getInstance().getMenuFontNormal()); - chatManager.setFont3D(CoreData::getInstance().getMenuFontNormal3D()); - - needUpdateFromServer = true; - - static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); - updateFromMasterserverThread = new SimpleTaskThread(this,0,100); - updateFromMasterserverThread->setUniqueID(mutexOwnerId); - updateFromMasterserverThread->start(); - - if(Config::getInstance().getString("IRCServer","") != "") { - IRC_SERVER = Config::getInstance().getString("IRCServer"); - } - ircArgs.push_back(IRC_SERVER); - - if(Config::getInstance().getString("IRCNick","") != "") { - ircArgs.push_back(Config::getInstance().getString("IRCNick")); - } - else { - ircArgs.push_back(szIRCNick); - } - - if(Config::getInstance().getString("IRCChannel","") != "") { - IRC_CHANNEL = Config::getInstance().getString("IRCChannel"); - } - ircArgs.push_back(IRC_CHANNEL); - - if(Config::getInstance().getString("IRCUsername","") != "") { - ircArgs.push_back(Config::getInstance().getString("IRCUsername")); - } - else { - ircArgs.push_back(szIRCNick); - } - if(Config::getInstance().getString("IRCPassword","") != "") { - ircArgs.push_back("identify " + Config::getInstance().getString("IRCPassword")); - } - else { - ircArgs.push_back(""); - } - - MutexSafeWrapper safeMutexIRCPtr(mutexIRCClient,string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + intToStr(__LINE__)); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("#1 IRCCLient Cache check\n"); - IRCThread * &ircThread = CacheManager::getCachedItem< IRCThread * >(GameConstants::ircClientCacheLookupKey); - - // Playername changed so restart the IRC Thread - if(ircThread != NULL && netPlayerName != ircThread->getPlayerName()) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - ircThread->leaveChannel(); - ircThread->setCallbackObj(NULL); - ircThread->signalQuit(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - ircThread = NULL; - } - - if(ircThread == NULL) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("#2 IRCCLient Cache check\n"); - - static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); - ircThread = new IRCThread(ircArgs,this); - ircClient = ircThread; - ircClient->setUniqueID(mutexOwnerId); - ircClient->setPlayerName(netPlayerName); - ircClient->setGlestVersionString(glestVersionString); - ircClient->start(); - } - else { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("#3 IRCCLient Cache check\n"); - ircClient = ircThread; - ircClient->setCallbackObj(this); - ircClient->joinChannel(); - } - - if(netPlayerName=="newbie"){ - showMessageBox(lang.getString("PlayerNameNotSetPrompt"),lang.getString("PlayerNameNotSetTitle"),false); - } - //showMessageBox("Go back and set your name in the game options!\n\nAt the moment you are just called >>newbie<< !","Player name not set!",false); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +MenuStateMasterserver::MenuStateMasterserver(Program *program, + MainMenu *mainMenu) + : MenuState(program, mainMenu, "masterserver"), + mutexIRCClient(new Mutex(CODE_AT_LINE)) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\n\n\n\n******************** ENTERING MASTERSERVER MENU\n\n\n\n\n"); + + containerName = "MasterServer"; + masterserverParseErrorShown = false; + updateFromMasterserverThread = NULL; + ircClient = NULL; + serverInfoString = "empty"; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + Lang &lang = Lang::getInstance(); + + // Configure ConsolePosition + consoleIRC.setYPos(60); + consoleIRC.setFont(CoreData::getInstance().getMenuFontNormal()); + consoleIRC.setFont3D(CoreData::getInstance().getMenuFontNormal3D()); + consoleIRC.setLineHeight(18); + consoleIRC.setOnlyChatMessagesInStoredLines(false); + + serverLinesToRender = 8; + serverLinesLineHeight = 25; + serverLinesYBase = 680; + + userButtonsHeight = 20; + userButtonsWidth = 150; + userButtonsLineHeight = userButtonsHeight + 2; + userButtonsYBase = + serverLinesYBase - (serverLinesToRender)*serverLinesLineHeight - 90; + userButtonsToRender = userButtonsYBase / userButtonsLineHeight; + userButtonsXBase = 1000 - userButtonsWidth; + + userScrollBar.init(1000 - 20, 0, false, 200, 20); + userScrollBar.setLength(userButtonsYBase + userButtonsLineHeight); + userScrollBar.setElementCount(0); + userScrollBar.setVisibleSize(userButtonsToRender); + userScrollBar.setVisibleStart(0); + + userButtonsXBase = 1000 - userButtonsWidth - userScrollBar.getW(); + + serverScrollBar.init(1000 - 20, + serverLinesYBase - + serverLinesLineHeight * (serverLinesToRender - 1), + false, 200, 20); + serverScrollBar.setLength(serverLinesLineHeight * serverLinesToRender); + serverScrollBar.setElementCount(0); + serverScrollBar.setVisibleSize(serverLinesToRender); + serverScrollBar.setVisibleStart(0); + + lines[0].init(0, userButtonsYBase + userButtonsLineHeight + + serverLinesLineHeight); + lines[1].init(userButtonsXBase - 5, 0, 5, + userButtonsYBase + 2 * userButtonsLineHeight); + lines[1].setHorizontal(false); + + autoRefreshTime = 0; + playServerFoundSound = false; + announcementLoaded = false; + + mainMessageBox.registerGraphicComponent(containerName, "mainMessageBox"); + mainMessageBox.init(lang.getString("Ok")); + mainMessageBox.setEnabled(false); + mainMessageBoxState = 0; + + lastRefreshTimer = time(NULL); + + // announcement + announcementLabel.registerGraphicComponent(containerName, + "announcementLabel"); + announcementLabel.init(10, 730); + announcementLabel.setFont(CoreData::getInstance().getMenuFontBig()); + announcementLabel.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + announcementLabel.setText(""); + + // versionInfo + versionInfoLabel.registerGraphicComponent(containerName, "versionInfoLabel"); + versionInfoLabel.init(10, 680); + versionInfoLabel.setFont(CoreData::getInstance().getMenuFontBig()); + versionInfoLabel.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + versionInfoLabel.setText(""); + + // header + labelTitle.registerGraphicComponent(containerName, "labelTitle"); + labelTitle.init(410, serverLinesYBase + 45); + labelTitle.setFont(CoreData::getInstance().getMenuFontBig()); + labelTitle.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + labelTitle.setText(lang.getString("AvailableServers")); + + if (Config::getInstance().getString("Masterserver", "") == "") { + labelTitle.setText("*** " + lang.getString("AvailableServers")); + } + + // bottom + int buttonPos = 230; + + // Titles for current games - START + int lineIndex = 0; + int lineOffset = 25 * lineIndex; + int i = 5; + int startOffset = serverLinesYBase + 23; + + // general info: + // i+=10; + glestVersionLabel.registerGraphicComponent(containerName, + "glestVersionLabel"); + glestVersionLabel.init(i, startOffset - lineOffset); + glestVersionLabel.setText(lang.getString("MGVersion")); + + i += 80; + platformLabel.registerGraphicComponent(containerName, "platformLabel"); + platformLabel.init(i + 15, startOffset - lineOffset); + platformLabel.setText(lang.getString("MGPlatform")); + + // i+=50; + // binaryCompileDateLabel.registerGraphicComponent(containerName,"binaryCompileDateLabel"); + // binaryCompileDateLabel.init(i,startOffset-lineOffset); + // binaryCompileDateLabel.setText(lang.getString("MGBuildDateTime")); + + // game info: + i += 120; + serverTitleLabel.registerGraphicComponent(containerName, "serverTitleLabel"); + serverTitleLabel.init(i, startOffset - lineOffset); + serverTitleLabel.setText(lang.getString("MGGameTitle")); + + i += 170; + countryLabel.registerGraphicComponent(containerName, "countryLabel"); + countryLabel.init(i - 10, startOffset - lineOffset); + countryLabel.setText(lang.getString("MGGameCountry")); + + i += 60; + + // ipAddressLabel.registerGraphicComponent(containerName,"ipAddressLabel"); + // ipAddressLabel.init(i,startOffset-lineOffset); + // ipAddressLabel.setText(lang.getString("MGGameIP")); + // i+=100; + + // game setup info: + techLabel.registerGraphicComponent(containerName, "techLabel"); + techLabel.init(i, startOffset - lineOffset); + techLabel.setText(lang.getString("TechTree")); + + i += 165; + mapLabel.registerGraphicComponent(containerName, "mapLabel"); + mapLabel.init(i, startOffset - lineOffset); + mapLabel.setText(lang.getString("Map")); + + i += 95; + // tilesetLabel.registerGraphicComponent(containerName,"tilesetLabel"); + // tilesetLabel.init(i,startOffset-lineOffset); + // tilesetLabel.setText(lang.getString("Tileset")); + // i+=100; + + activeSlotsLabel.registerGraphicComponent(containerName, "activeSlotsLabel"); + activeSlotsLabel.init(i, startOffset - lineOffset); + activeSlotsLabel.setText(lang.getString("MGGameSlots")); + + i += 50; + // externalConnectPort.registerGraphicComponent(containerName,"externalConnectPort"); + // externalConnectPort.init(i,startOffset-lineOffset); + // externalConnectPort.setText(lang.getString("Port")); + + i += 30; + statusLabel.registerGraphicComponent(containerName, "statusLabel"); + statusLabel.init(i + 5, startOffset - lineOffset); + statusLabel.setText(lang.getString("MGGameStatus")); + + i += 130; + selectButton.registerGraphicComponent(containerName, "selectButton"); + selectButton.init(i - 5, startOffset - lineOffset); + selectButton.setText(lang.getString("MGJoinGameSlots")); + + // Titles for current games - END + + buttonReturn.registerGraphicComponent(containerName, "buttonReturn"); + buttonReturn.init(50, buttonPos, 150); + + buttonCreateGame.registerGraphicComponent(containerName, "buttonCreateGame"); + buttonCreateGame.init(275, buttonPos, 150); + + buttonRefresh.registerGraphicComponent(containerName, "buttonRefresh"); + buttonRefresh.init(500, buttonPos, 150); + + buttonRefresh.setText(lang.getString("RefreshList")); + buttonReturn.setText(lang.getString("Return")); + buttonCreateGame.setText(lang.getString("HostGame")); + labelAutoRefresh.setText(lang.getString("AutoRefreshRate")); + + labelAutoRefresh.registerGraphicComponent(containerName, "labelAutoRefresh"); + labelAutoRefresh.init(750, buttonPos + 30); + + listBoxAutoRefresh.registerGraphicComponent(containerName, + "listBoxAutoRefresh"); + listBoxAutoRefresh.init(750, buttonPos); + listBoxAutoRefresh.pushBackItem(lang.getString("Off")); + listBoxAutoRefresh.pushBackItem("10 s"); + listBoxAutoRefresh.pushBackItem("20 s"); + listBoxAutoRefresh.pushBackItem("30 s"); + listBoxAutoRefresh.setSelectedItemIndex(2); + autoRefreshTime = 10 * listBoxAutoRefresh.getSelectedItemIndex(); + + ircOnlinePeopleLabel.registerGraphicComponent(containerName, + "ircOnlinePeopleLabel"); + ircOnlinePeopleLabel.init(userButtonsXBase, + userButtonsYBase + userButtonsLineHeight); + ircOnlinePeopleLabel.setText(lang.getString("IRCPeopleOnline")); + + ircOnlinePeopleStatusLabel.registerGraphicComponent( + containerName, "ircOnlinePeopleStatusLabel"); + ircOnlinePeopleStatusLabel.init( + userButtonsXBase, userButtonsYBase + userButtonsLineHeight - 20); + ircOnlinePeopleStatusLabel.setText(""); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + NetworkManager::getInstance().end(); + NetworkManager::getInstance().init(nrClient); + + // console.addLine(lang.getString("ToSwitchOffMusicPress")+" - + // \""+configKeys.getCharKey("ToggleMusic")+"\""); + + GraphicComponent::applyAllCustomProperties(containerName); + + char szIRCNick[80] = ""; + Chrono seed(true); + srand((unsigned int)seed.getCurTicks()); + + int randomNickId = rand() % 999; + string netPlayerName = Config::getInstance().getString( + "NetPlayerName", Socket::getHostName().c_str()); + string ircname = netPlayerName.substr(0, 9); + snprintf(szIRCNick, 80, "MG_%s_%d", ircname.c_str(), randomNickId); + normalizeNick(szIRCNick); + + currentIrcNick = ircname; + consoleIRC.setStringToHighlight(currentIrcNick); + + lines[2].init(0, consoleIRC.getYPos() - 10, userButtonsXBase, 5); + chatManager.init(&consoleIRC, -1, true, szIRCNick); + chatManager.setXPos(0); + chatManager.setYPos(consoleIRC.getYPos() - 20); + chatManager.setFont(CoreData::getInstance().getMenuFontNormal()); + chatManager.setFont3D(CoreData::getInstance().getMenuFontNormal3D()); + + needUpdateFromServer = true; + + static string mutexOwnerId = + string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + + intToStr(__LINE__); + updateFromMasterserverThread = new SimpleTaskThread(this, 0, 100); + updateFromMasterserverThread->setUniqueID(mutexOwnerId); + updateFromMasterserverThread->start(); + + if (Config::getInstance().getString("IRCServer", "") != "") { + IRC_SERVER = Config::getInstance().getString("IRCServer"); + } + ircArgs.push_back(IRC_SERVER); + + if (Config::getInstance().getString("IRCNick", "") != "") { + ircArgs.push_back(Config::getInstance().getString("IRCNick")); + } else { + ircArgs.push_back(szIRCNick); + } + + if (Config::getInstance().getString("IRCChannel", "") != "") { + IRC_CHANNEL = Config::getInstance().getString("IRCChannel"); + } + ircArgs.push_back(IRC_CHANNEL); + + if (Config::getInstance().getString("IRCUsername", "") != "") { + ircArgs.push_back(Config::getInstance().getString("IRCUsername")); + } else { + ircArgs.push_back(szIRCNick); + } + if (Config::getInstance().getString("IRCPassword", "") != "") { + ircArgs.push_back("identify " + + Config::getInstance().getString("IRCPassword")); + } else { + ircArgs.push_back(""); + } + + MutexSafeWrapper safeMutexIRCPtr( + mutexIRCClient, string(extractFileFromDirectoryPath(__FILE__).c_str()) + + "_" + intToStr(__LINE__)); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("#1 IRCCLient Cache check\n"); + IRCThread *&ircThread = CacheManager::getCachedItem( + GameConstants::ircClientCacheLookupKey); + + // Playername changed so restart the IRC Thread + if (ircThread != NULL && netPlayerName != ircThread->getPlayerName()) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + ircThread->leaveChannel(); + ircThread->setCallbackObj(NULL); + ircThread->signalQuit(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + ircThread = NULL; + } + + if (ircThread == NULL) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("#2 IRCCLient Cache check\n"); + + static string mutexOwnerId = + string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + + intToStr(__LINE__); + ircThread = new IRCThread(ircArgs, this); + ircClient = ircThread; + ircClient->setUniqueID(mutexOwnerId); + ircClient->setPlayerName(netPlayerName); + ircClient->setGlestVersionString(glestVersionString); + ircClient->start(); + } else { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("#3 IRCCLient Cache check\n"); + ircClient = ircThread; + ircClient->setCallbackObj(this); + ircClient->joinChannel(); + } + + if (netPlayerName == "newbie") { + showMessageBox(lang.getString("PlayerNameNotSetPrompt"), + lang.getString("PlayerNameNotSetTitle"), false); + } + // showMessageBox("Go back and set your name in the game options!\n\nAt the + // moment you are just called >>newbie<< !","Player name not set!",false); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); } void MenuStateMasterserver::reloadUI() { - Lang &lang= Lang::getInstance(); + Lang &lang = Lang::getInstance(); - console.resetFonts(); - consoleIRC.setFont(CoreData::getInstance().getMenuFontNormal()); - consoleIRC.setFont3D(CoreData::getInstance().getMenuFontNormal3D()); + console.resetFonts(); + consoleIRC.setFont(CoreData::getInstance().getMenuFontNormal()); + consoleIRC.setFont3D(CoreData::getInstance().getMenuFontNormal3D()); - mainMessageBox.init(lang.getString("Ok")); + mainMessageBox.init(lang.getString("Ok")); - announcementLabel.setFont(CoreData::getInstance().getMenuFontBig()); - announcementLabel.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + announcementLabel.setFont(CoreData::getInstance().getMenuFontBig()); + announcementLabel.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - versionInfoLabel.setFont(CoreData::getInstance().getMenuFontBig()); - versionInfoLabel.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + versionInfoLabel.setFont(CoreData::getInstance().getMenuFontBig()); + versionInfoLabel.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - labelTitle.setFont(CoreData::getInstance().getMenuFontBig()); - labelTitle.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - labelTitle.setText(lang.getString("AvailableServers")); + labelTitle.setFont(CoreData::getInstance().getMenuFontBig()); + labelTitle.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + labelTitle.setText(lang.getString("AvailableServers")); - if(Config::getInstance().getString("Masterserver","") == "") { - labelTitle.setText("*** " + lang.getString("AvailableServers")); - } + if (Config::getInstance().getString("Masterserver", "") == "") { + labelTitle.setText("*** " + lang.getString("AvailableServers")); + } - glestVersionLabel.setText(lang.getString("MGVersion")); + glestVersionLabel.setText(lang.getString("MGVersion")); - platformLabel.setText(lang.getString("MGPlatform")); + platformLabel.setText(lang.getString("MGPlatform")); - serverTitleLabel.setText(lang.getString("MGGameTitle")); + serverTitleLabel.setText(lang.getString("MGGameTitle")); - countryLabel.setText(lang.getString("MGGameCountry")); + countryLabel.setText(lang.getString("MGGameCountry")); - techLabel.setText(lang.getString("TechTree")); + techLabel.setText(lang.getString("TechTree")); - mapLabel.setText(lang.getString("Map")); + mapLabel.setText(lang.getString("Map")); - activeSlotsLabel.setText(lang.getString("MGGameSlots")); + activeSlotsLabel.setText(lang.getString("MGGameSlots")); - //externalConnectPort.setText(lang.getString("Port")); + // externalConnectPort.setText(lang.getString("Port")); - statusLabel.setText(lang.getString("MGGameStatus")); + statusLabel.setText(lang.getString("MGGameStatus")); - selectButton.setText(lang.getString("MGJoinGameSlots")); + selectButton.setText(lang.getString("MGJoinGameSlots")); - // Titles for current games - END + // Titles for current games - END - buttonRefresh.setText(lang.getString("RefreshList")); - buttonReturn.setText(lang.getString("Return")); - buttonCreateGame.setText(lang.getString("HostGame")); - labelAutoRefresh.setText(lang.getString("AutoRefreshRate")); + buttonRefresh.setText(lang.getString("RefreshList")); + buttonReturn.setText(lang.getString("Return")); + buttonCreateGame.setText(lang.getString("HostGame")); + labelAutoRefresh.setText(lang.getString("AutoRefreshRate")); - ircOnlinePeopleLabel.setText(lang.getString("IRCPeopleOnline")); + ircOnlinePeopleLabel.setText(lang.getString("IRCPeopleOnline")); - chatManager.setFont(CoreData::getInstance().getMenuFontNormal()); - chatManager.setFont3D(CoreData::getInstance().getMenuFontNormal3D()); + chatManager.setFont(CoreData::getInstance().getMenuFontNormal()); + chatManager.setFont3D(CoreData::getInstance().getMenuFontNormal3D()); - GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); + GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); } -//void MenuStateMasterserver::setConsolePos(int yPos){ +// void MenuStateMasterserver::setConsolePos(int yPos){ // consoleIRC.setYPos(yPos); // lines[2].setY(consoleIRC.getYPos()-10); // chatManager.setYPos(consoleIRC.getYPos()-20); -//} - -void MenuStateMasterserver::setButtonLinePosition(int pos){ - buttonReturn.setY(pos); - buttonCreateGame.setY(pos); - buttonRefresh.setY(pos); - labelAutoRefresh.setY(pos+30); - listBoxAutoRefresh.setY(pos); +// } + +void MenuStateMasterserver::setButtonLinePosition(int pos) { + buttonReturn.setY(pos); + buttonCreateGame.setY(pos); + buttonRefresh.setY(pos); + labelAutoRefresh.setY(pos + 30); + listBoxAutoRefresh.setY(pos); } -void MenuStateMasterserver::IRC_CallbackEvent(IRCEventType evt, const char* origin, const char **params, unsigned int count) { - MutexSafeWrapper safeMutexIRCPtr(mutexIRCClient,string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + intToStr(__LINE__)); - if(ircClient != NULL) { - if(evt == IRC_evt_exitThread) { - ircClient->leaveChannel(); - ircClient->setCallbackObj(NULL); - - ircClient = NULL; - } - else if(evt == IRC_evt_chatText) { - //printf ("===> IRC: '%s' said in channel %s: %s\n",origin ? origin : "someone",params[0], params[1] ); - - char szBuf[8096]=""; - snprintf(szBuf,8096,"%s: %s",origin ? origin : "someone",params[1]); - string helpSTr=szBuf; - if(helpSTr.find(currentIrcNick)!=string::npos){ - CoreData &coreData= CoreData::getInstance(); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - - soundRenderer.playFx(coreData.getHighlightSound()); - } - consoleIRC.addLine(szBuf); - } +void MenuStateMasterserver::IRC_CallbackEvent(IRCEventType evt, + const char *origin, + const char **params, + unsigned int count) { + MutexSafeWrapper safeMutexIRCPtr( + mutexIRCClient, string(extractFileFromDirectoryPath(__FILE__).c_str()) + + "_" + intToStr(__LINE__)); + if (ircClient != NULL) { + if (evt == IRC_evt_exitThread) { + ircClient->leaveChannel(); + ircClient->setCallbackObj(NULL); + + ircClient = NULL; + } else if (evt == IRC_evt_chatText) { + // printf ("===> IRC: '%s' said in channel %s: %s\n",origin ? origin : + // "someone",params[0], params[1] ); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "%s: %s", origin ? origin : "someone", params[1]); + string helpSTr = szBuf; + if (helpSTr.find(currentIrcNick) != string::npos) { + CoreData &coreData = CoreData::getInstance(); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + + soundRenderer.playFx(coreData.getHighlightSound()); + } + consoleIRC.addLine(szBuf); } + } } void MenuStateMasterserver::cleanup() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - MutexSafeWrapper safeMutex((updateFromMasterserverThread != NULL ? updateFromMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + intToStr(__LINE__)); - needUpdateFromServer = false; - safeMutex.ReleaseLock(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - -// if(updateFromMasterserverThread != NULL && -// updateFromMasterserverThread->canShutdown(true) == true) { -// if(updateFromMasterserverThread->shutdownAndWait() == true) { -// delete updateFromMasterserverThread; -// } -// } -// updateFromMasterserverThread = NULL; - if(updateFromMasterserverThread != NULL) { - updateFromMasterserverThread->signalQuit(); - } - if(updateFromMasterserverThread != NULL && updateFromMasterserverThread->canShutdown(false) == true && - updateFromMasterserverThread->getRunningStatus() == false) { - //printf("#2 Ending client SLOT: %d\n",playerIndex); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - delete updateFromMasterserverThread; - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - } - //else if(BaseThread::shutdownAndWait(slotThreadWorker) == true) { - else if(updateFromMasterserverThread != NULL && updateFromMasterserverThread->canShutdown(true) == true) { - if(updateFromMasterserverThread->getRunningStatus() == false) { - //printf("#3 Ending client SLOT: %d\n",playerIndex); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - delete updateFromMasterserverThread; - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - } - else { - updateFromMasterserverThread->setDeleteSelfOnExecutionDone(true); - updateFromMasterserverThread->setDeleteAfterExecute(true); - } - } - //printf("#4 Ending client SLOT: %d\n",playerIndex); - updateFromMasterserverThread = NULL; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - clearServerLines(); - clearUserButtons(); - - MutexSafeWrapper safeMutexIRCPtr(mutexIRCClient,string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + intToStr(__LINE__)); - if(ircClient != NULL) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - ircClient->leaveChannel(); - ircClient->setCallbackObj(NULL); - //ircClient->signalQuit(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - ircClient = NULL; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + MutexSafeWrapper safeMutex( + (updateFromMasterserverThread != NULL + ? updateFromMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + + intToStr(__LINE__)); + needUpdateFromServer = false; + safeMutex.ReleaseLock(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // if(updateFromMasterserverThread != NULL && + // updateFromMasterserverThread->canShutdown(true) == true) { + // if(updateFromMasterserverThread->shutdownAndWait() == true) { + // delete updateFromMasterserverThread; + // } + // } + // updateFromMasterserverThread = NULL; + if (updateFromMasterserverThread != NULL) { + updateFromMasterserverThread->signalQuit(); + } + if (updateFromMasterserverThread != NULL && + updateFromMasterserverThread->canShutdown(false) == true && + updateFromMasterserverThread->getRunningStatus() == false) { + // printf("#2 Ending client SLOT: %d\n",playerIndex); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + delete updateFromMasterserverThread; + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + } + // else if(BaseThread::shutdownAndWait(slotThreadWorker) == true) { + else if (updateFromMasterserverThread != NULL && + updateFromMasterserverThread->canShutdown(true) == true) { + if (updateFromMasterserverThread->getRunningStatus() == false) { + // printf("#3 Ending client SLOT: %d\n",playerIndex); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + delete updateFromMasterserverThread; + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + } else { + updateFromMasterserverThread->setDeleteSelfOnExecutionDone(true); + updateFromMasterserverThread->setDeleteAfterExecute(true); } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] END\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + } + // printf("#4 Ending client SLOT: %d\n",playerIndex); + updateFromMasterserverThread = NULL; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + clearServerLines(); + clearUserButtons(); + + MutexSafeWrapper safeMutexIRCPtr( + mutexIRCClient, string(extractFileFromDirectoryPath(__FILE__).c_str()) + + "_" + intToStr(__LINE__)); + if (ircClient != NULL) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + ircClient->leaveChannel(); + ircClient->setCallbackObj(NULL); + // ircClient->signalQuit(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + ircClient = NULL; + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d] END\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); } MenuStateMasterserver::~MenuStateMasterserver() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - cleanup(); + cleanup(); - delete mutexIRCClient; - mutexIRCClient = NULL; + delete mutexIRCClient; + mutexIRCClient = NULL; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] END\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d] END\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); } void MenuStateMasterserver::clearServerLines() { - while(!serverLines.empty()) { - delete serverLines.back(); - serverLines.pop_back(); - } + while (!serverLines.empty()) { + delete serverLines.back(); + serverLines.pop_back(); + } } void MenuStateMasterserver::clearUserButtons() { - while(!userButtons.empty()){ - delete userButtons.back(); - userButtons.pop_back(); - } + while (!userButtons.empty()) { + delete userButtons.back(); + userButtons.pop_back(); + } } -void MenuStateMasterserver::mouseClick(int x, int y, MouseButton mouseButton){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - CoreData &coreData= CoreData::getInstance(); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - - if(mainMessageBox.getEnabled()){ - int button= 0; - if(mainMessageBox.mouseClick(x, y, button)) { - soundRenderer.playFx(coreData.getClickSoundA()); - if(button == 0) { - mainMessageBox.setEnabled(false); - } - } - } - else if(userScrollBar.mouseClick(x, y)){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - soundRenderer.playFx(coreData.getClickSoundA()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - else if(serverScrollBar.mouseClick(x, y)){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - soundRenderer.playFx(coreData.getClickSoundA()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - else if(buttonRefresh.mouseClick(x, y)){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - MutexSafeWrapper safeMutex((updateFromMasterserverThread != NULL ? updateFromMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + intToStr(__LINE__)); - soundRenderer.playFx(coreData.getClickSoundB()); - needUpdateFromServer = true; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void MenuStateMasterserver::mouseClick(int x, int y, MouseButton mouseButton) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + CoreData &coreData = CoreData::getInstance(); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + + if (mainMessageBox.getEnabled()) { + int button = 0; + if (mainMessageBox.mouseClick(x, y, button)) { + soundRenderer.playFx(coreData.getClickSoundA()); + if (button == 0) { + mainMessageBox.setEnabled(false); + } } - else if(buttonReturn.mouseClick(x, y)){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - soundRenderer.playFx(coreData.getClickSoundA()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if (ircClient != NULL && ircClient->isConnected() == true - && ircClient->getHasJoinedChannel() == true) { - ircClient->SendIRCCmdMessage(IRC_CHANNEL, " << left the lobby"); - sleep(30); - } - cleanup(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - mainMenu->setState(new MenuStateNewGame(program, mainMenu)); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + } else if (userScrollBar.mouseClick(x, y)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + soundRenderer.playFx(coreData.getClickSoundA()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + } else if (serverScrollBar.mouseClick(x, y)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + soundRenderer.playFx(coreData.getClickSoundA()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + } else if (buttonRefresh.mouseClick(x, y)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + MutexSafeWrapper safeMutex( + (updateFromMasterserverThread != NULL + ? updateFromMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + + intToStr(__LINE__)); + soundRenderer.playFx(coreData.getClickSoundB()); + needUpdateFromServer = true; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + } else if (buttonReturn.mouseClick(x, y)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + soundRenderer.playFx(coreData.getClickSoundA()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + if (ircClient != NULL && ircClient->isConnected() == true && + ircClient->getHasJoinedChannel() == true) { + ircClient->SendIRCCmdMessage(IRC_CHANNEL, " << left the lobby"); + sleep(30); } - else if(buttonCreateGame.mouseClick(x, y)){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - MutexSafeWrapper safeMutex((updateFromMasterserverThread != NULL ? updateFromMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + intToStr(__LINE__)); - soundRenderer.playFx(coreData.getClickSoundB()); - needUpdateFromServer = false; - safeMutex.ReleaseLock(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if (ircClient != NULL && ircClient->isConnected() == true - && ircClient->getHasJoinedChannel() == true) { - ircClient->SendIRCCmdMessage(IRC_CHANNEL, " << tries to create a game"); - sleep(30); - } - cleanup(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - mainMenu->setState(new MenuStateCustomGame(program, mainMenu,true,pMasterServer)); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + cleanup(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + mainMenu->setState(new MenuStateNewGame(program, mainMenu)); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + } else if (buttonCreateGame.mouseClick(x, y)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + MutexSafeWrapper safeMutex( + (updateFromMasterserverThread != NULL + ? updateFromMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + + intToStr(__LINE__)); + soundRenderer.playFx(coreData.getClickSoundB()); + needUpdateFromServer = false; + safeMutex.ReleaseLock(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + if (ircClient != NULL && ircClient->isConnected() == true && + ircClient->getHasJoinedChannel() == true) { + ircClient->SendIRCCmdMessage(IRC_CHANNEL, + " << tries to create a game"); + sleep(30); } - else if(listBoxAutoRefresh.mouseClick(x, y)){ - MutexSafeWrapper safeMutex((updateFromMasterserverThread != NULL ? updateFromMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + intToStr(__LINE__)); - soundRenderer.playFx(coreData.getClickSoundA()); - autoRefreshTime=10*listBoxAutoRefresh.getSelectedItemIndex(); + cleanup(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + mainMenu->setState( + new MenuStateCustomGame(program, mainMenu, true, pMasterServer)); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + } else if (listBoxAutoRefresh.mouseClick(x, y)) { + MutexSafeWrapper safeMutex( + (updateFromMasterserverThread != NULL + ? updateFromMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + + intToStr(__LINE__)); + soundRenderer.playFx(coreData.getClickSoundA()); + autoRefreshTime = 10 * listBoxAutoRefresh.getSelectedItemIndex(); + } else { + MutexSafeWrapper safeMutex( + (updateFromMasterserverThread != NULL + ? updateFromMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + + intToStr(__LINE__)); + bool clicked = false; + if (serverScrollBar.getElementCount() != 0) { + for (int i = serverScrollBar.getVisibleStart(); + i <= serverScrollBar.getVisibleEnd(); ++i) { + if (serverLines[i]->buttonMouseClick(x, y)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + clicked = true; + soundRenderer.playFx(coreData.getClickSoundB()); + string connectServerIP = + serverLines[i]->getMasterServerInfo()->getIpAddress(); + int connectServerPort = + serverLines[i]->getMasterServerInfo()->getExternalConnectPort(); + bool connected = connectToServer(connectServerIP, connectServerPort); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + safeMutex.ReleaseLock(); + if (connected) { + soundRenderer.playFx(coreData.getClickSoundB()); + + if (ircClient != NULL && ircClient->isConnected() == true && + ircClient->getHasJoinedChannel() == true) { + ircClient->SendIRCCmdMessage( + IRC_CHANNEL, + " << is connecting to '" + + serverLines[i]->getMasterServerInfo()->getServerTitle() + + "'"); + sleep(30); + } + cleanup(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + mainMenu->setState( + new MenuStateConnectedGame(program, mainMenu, jmMasterserver)); + } + break; + } + } } - else { - MutexSafeWrapper safeMutex((updateFromMasterserverThread != NULL ? updateFromMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + intToStr(__LINE__)); - bool clicked=false; - if(serverScrollBar.getElementCount() != 0) { - for(int i = serverScrollBar.getVisibleStart(); i <= serverScrollBar.getVisibleEnd(); ++i) { - if(serverLines[i]->buttonMouseClick(x, y)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - clicked=true; - soundRenderer.playFx(coreData.getClickSoundB()); - string connectServerIP = serverLines[i]->getMasterServerInfo()->getIpAddress(); - int connectServerPort = serverLines[i]->getMasterServerInfo()->getExternalConnectPort(); - bool connected=connectToServer(connectServerIP,connectServerPort); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - safeMutex.ReleaseLock(); - if(connected){ - soundRenderer.playFx(coreData.getClickSoundB()); - - if (ircClient != NULL && ircClient->isConnected() == true - && ircClient->getHasJoinedChannel() == true) { - ircClient->SendIRCCmdMessage(IRC_CHANNEL, " << is connecting to '"+serverLines[i]->getMasterServerInfo()->getServerTitle()+"'"); - sleep(30); - } - cleanup(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - mainMenu->setState(new MenuStateConnectedGame(program, mainMenu,jmMasterserver)); - } - break; - } - } - } - if(!clicked && userScrollBar.getElementCount()!=0){ - for(int i = userScrollBar.getVisibleStart(); i <= userScrollBar.getVisibleEnd(); ++i) { - if(userButtons[i]->getEnabled() == true && userButtons[i]->mouseClick(x, y)) { - //clicked=true; - if(!chatManager.getEditEnabled()) - { - chatManager.switchOnEdit(); - chatManager.addText(userButtons[i]->getText()+" "); - } - else - { - chatManager.addText(userButtons[i]->getText()); - } - break; - } - } - } + if (!clicked && userScrollBar.getElementCount() != 0) { + for (int i = userScrollBar.getVisibleStart(); + i <= userScrollBar.getVisibleEnd(); ++i) { + if (userButtons[i]->getEnabled() == true && + userButtons[i]->mouseClick(x, y)) { + // clicked=true; + if (!chatManager.getEditEnabled()) { + chatManager.switchOnEdit(); + chatManager.addText(userButtons[i]->getText() + " "); + } else { + chatManager.addText(userButtons[i]->getText()); + } + break; + } + } } + } } -void MenuStateMasterserver::mouseUp(int x, int y, const MouseButton mouseButton){ - if (mouseButton == mbLeft) { - userScrollBar.mouseUp(x, y); - serverScrollBar.mouseUp(x, y); - } +void MenuStateMasterserver::mouseUp(int x, int y, + const MouseButton mouseButton) { + if (mouseButton == mbLeft) { + userScrollBar.mouseUp(x, y); + serverScrollBar.mouseUp(x, y); + } } -void MenuStateMasterserver::mouseMove(int x, int y, const MouseState *ms){ - MutexSafeWrapper safeMutex((updateFromMasterserverThread != NULL ? updateFromMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + intToStr(__LINE__)); - - if (mainMessageBox.getEnabled()) { - mainMessageBox.mouseMove(x, y); - } - buttonRefresh.mouseMove(x, y); - buttonReturn.mouseMove(x, y); - buttonCreateGame.mouseMove(x, y); - if (ms->get(mbLeft)) { - userScrollBar.mouseDown(x, y); - serverScrollBar.mouseDown(x, y); - } else { - userScrollBar.mouseMove(x, y); - serverScrollBar.mouseMove(x, y); - } - listBoxAutoRefresh.mouseMove(x, y); - - if(serverScrollBar.getElementCount()!=0 ) { - for(int i = serverScrollBar.getVisibleStart(); i <= serverScrollBar.getVisibleEnd(); ++i) { - serverLines[i]->buttonMouseMove(x, y); - } +void MenuStateMasterserver::mouseMove(int x, int y, const MouseState *ms) { + MutexSafeWrapper safeMutex( + (updateFromMasterserverThread != NULL + ? updateFromMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + + intToStr(__LINE__)); + + if (mainMessageBox.getEnabled()) { + mainMessageBox.mouseMove(x, y); + } + buttonRefresh.mouseMove(x, y); + buttonReturn.mouseMove(x, y); + buttonCreateGame.mouseMove(x, y); + if (ms->get(mbLeft)) { + userScrollBar.mouseDown(x, y); + serverScrollBar.mouseDown(x, y); + } else { + userScrollBar.mouseMove(x, y); + serverScrollBar.mouseMove(x, y); + } + listBoxAutoRefresh.mouseMove(x, y); + + if (serverScrollBar.getElementCount() != 0) { + for (int i = serverScrollBar.getVisibleStart(); + i <= serverScrollBar.getVisibleEnd(); ++i) { + serverLines[i]->buttonMouseMove(x, y); } - if(userScrollBar.getElementCount()!=0 ) { - for(int i = userScrollBar.getVisibleStart(); i <= userScrollBar.getVisibleEnd(); ++i) { - if(userButtons[i]->getEnabled() == true) { - userButtons[i]->mouseMove(x, y); - } - } + } + if (userScrollBar.getElementCount() != 0) { + for (int i = userScrollBar.getVisibleStart(); + i <= userScrollBar.getVisibleEnd(); ++i) { + if (userButtons[i]->getEnabled() == true) { + userButtons[i]->mouseMove(x, y); + } } - + } } -void MenuStateMasterserver::render(){ - Renderer &renderer= Renderer::getInstance(); - - MutexSafeWrapper safeMutex((updateFromMasterserverThread != NULL ? updateFromMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + intToStr(__LINE__)); - if(mainMessageBox.getEnabled()) { - renderer.renderMessageBox(&mainMessageBox); - } - else - { - renderer.renderLabel(&labelTitle,&GREEN); - renderer.renderLabel(&announcementLabel,&YELLOW); - renderer.renderLabel(&versionInfoLabel); - - // Render titles for server games listed - const Vec4f titleLabelColor = CYAN; - - //general info: - renderer.renderLabel(&glestVersionLabel,&titleLabelColor); - renderer.renderLabel(&platformLabel,&titleLabelColor); - //renderer.renderLabel(&binaryCompileDateLabel,&titleLabelColor); - - //game info: - renderer.renderLabel(&serverTitleLabel,&titleLabelColor); - renderer.renderLabel(&countryLabel,&titleLabelColor); - renderer.renderLabel(&statusLabel,&titleLabelColor); - //renderer.renderLabel(&ipAddressLabel,&titleLabelColor); - - //game setup info: - renderer.renderLabel(&techLabel,&titleLabelColor); - renderer.renderLabel(&mapLabel,&titleLabelColor); - //renderer.renderLabel(&tilesetLabel,&titleLabelColor); - renderer.renderLabel(&activeSlotsLabel,&titleLabelColor); - //renderer.renderLabel(&externalConnectPort,&titleLabelColor); - renderer.renderLabel(&selectButton,&titleLabelColor); - - Lang &lang= Lang::getInstance(); - MutexSafeWrapper safeMutexIRCPtr(mutexIRCClient,string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + intToStr(__LINE__)); - if(ircClient != NULL && - ircClient->isConnected() == true && - ircClient->getHasJoinedChannel() == true) { - const Vec4f titleLabelColor = GREEN; - - if(ircOnlinePeopleStatusLabel.getText() != "") { - ircOnlinePeopleStatusLabel.setText(""); - } +void MenuStateMasterserver::render() { + Renderer &renderer = Renderer::getInstance(); + + MutexSafeWrapper safeMutex( + (updateFromMasterserverThread != NULL + ? updateFromMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + + intToStr(__LINE__)); + if (mainMessageBox.getEnabled()) { + renderer.renderMessageBox(&mainMessageBox); + } else { + renderer.renderLabel(&labelTitle, &GREEN); + renderer.renderLabel(&announcementLabel, &YELLOW); + renderer.renderLabel(&versionInfoLabel); + + // Render titles for server games listed + const Vec4f titleLabelColor = CYAN; + + // general info: + renderer.renderLabel(&glestVersionLabel, &titleLabelColor); + renderer.renderLabel(&platformLabel, &titleLabelColor); + // renderer.renderLabel(&binaryCompileDateLabel,&titleLabelColor); + + // game info: + renderer.renderLabel(&serverTitleLabel, &titleLabelColor); + renderer.renderLabel(&countryLabel, &titleLabelColor); + renderer.renderLabel(&statusLabel, &titleLabelColor); + // renderer.renderLabel(&ipAddressLabel,&titleLabelColor); + + // game setup info: + renderer.renderLabel(&techLabel, &titleLabelColor); + renderer.renderLabel(&mapLabel, &titleLabelColor); + // renderer.renderLabel(&tilesetLabel,&titleLabelColor); + renderer.renderLabel(&activeSlotsLabel, &titleLabelColor); + // renderer.renderLabel(&externalConnectPort,&titleLabelColor); + renderer.renderLabel(&selectButton, &titleLabelColor); + + Lang &lang = Lang::getInstance(); + MutexSafeWrapper safeMutexIRCPtr( + mutexIRCClient, string(extractFileFromDirectoryPath(__FILE__).c_str()) + + "_" + intToStr(__LINE__)); + if (ircClient != NULL && ircClient->isConnected() == true && + ircClient->getHasJoinedChannel() == true) { + const Vec4f titleLabelColor = GREEN; + + if (ircOnlinePeopleStatusLabel.getText() != "") { + ircOnlinePeopleStatusLabel.setText(""); + } + + renderer.renderLabel(&ircOnlinePeopleLabel, &titleLabelColor); + // renderer.renderLabel(&ircOnlinePeopleStatusLabel,&titleLabelColor); + } else { + const Vec4f titleLabelColor = RED; + + if (ircOnlinePeopleStatusLabel.getText() != + lang.getString("Connecting")) { + ircOnlinePeopleStatusLabel.setText(lang.getString("Connecting")); + } + + renderer.renderLabel(&ircOnlinePeopleLabel, &titleLabelColor); + renderer.renderLabel(&ircOnlinePeopleStatusLabel, &titleLabelColor); + } + safeMutexIRCPtr.ReleaseLock(); - renderer.renderLabel(&ircOnlinePeopleLabel,&titleLabelColor); - //renderer.renderLabel(&ircOnlinePeopleStatusLabel,&titleLabelColor); - } - else { - const Vec4f titleLabelColor = RED; + // const Vec4f titleLabelColorList = YELLOW; - if(ircOnlinePeopleStatusLabel.getText() != lang.getString("Connecting")) { - ircOnlinePeopleStatusLabel.setText(lang.getString("Connecting")); - } + if (serverScrollBar.getElementCount() != 0) { + for (int i = serverScrollBar.getVisibleStart(); + i <= serverScrollBar.getVisibleEnd(); ++i) { + serverLines[i]->render(); + } + } + renderer.renderScrollBar(&serverScrollBar); - renderer.renderLabel(&ircOnlinePeopleLabel,&titleLabelColor); - renderer.renderLabel(&ircOnlinePeopleStatusLabel,&titleLabelColor); - } - safeMutexIRCPtr.ReleaseLock(); - - //const Vec4f titleLabelColorList = YELLOW; - - if(serverScrollBar.getElementCount()!=0 ) { - for(int i = serverScrollBar.getVisibleStart(); i <= serverScrollBar.getVisibleEnd(); ++i) { - serverLines[i]->render(); - } - } - renderer.renderScrollBar(&serverScrollBar); - - for(int i = 0; i < (int)sizeof(lines) / (int)sizeof(lines[0]); ++i){ - renderer.renderLine(&lines[i]); - } - renderer.renderButton(&buttonRefresh); - renderer.renderButton(&buttonReturn); - renderer.renderLabel(&labelAutoRefresh); - renderer.renderButton(&buttonCreateGame); - renderer.renderListBox(&listBoxAutoRefresh); - - if(userScrollBar.getElementCount()!=0 ) { - for(int i = userScrollBar.getVisibleStart(); i <= userScrollBar.getVisibleEnd(); ++i) { - renderer.renderButton(userButtons[i]); - } - } - renderer.renderScrollBar(&userScrollBar); - if(ircClient != NULL && - ircClient->isConnected() == true && - ircClient->getHasJoinedChannel() == true) { - renderer.renderChatManager(&chatManager); - } - renderer.renderConsole(&consoleIRC,consoleStoredOnly,21); - - } - if(program != NULL) program->renderProgramMsgBox(); + for (int i = 0; i < (int)sizeof(lines) / (int)sizeof(lines[0]); ++i) { + renderer.renderLine(&lines[i]); + } + renderer.renderButton(&buttonRefresh); + renderer.renderButton(&buttonReturn); + renderer.renderLabel(&labelAutoRefresh); + renderer.renderButton(&buttonCreateGame); + renderer.renderListBox(&listBoxAutoRefresh); + + if (userScrollBar.getElementCount() != 0) { + for (int i = userScrollBar.getVisibleStart(); + i <= userScrollBar.getVisibleEnd(); ++i) { + renderer.renderButton(userButtons[i]); + } + } + renderer.renderScrollBar(&userScrollBar); + if (ircClient != NULL && ircClient->isConnected() == true && + ircClient->getHasJoinedChannel() == true) { + renderer.renderChatManager(&chatManager); + } + renderer.renderConsole(&consoleIRC, consoleStoredOnly, 21); + } + if (program != NULL) + program->renderProgramMsgBox(); } void MenuStateMasterserver::update() { - MutexSafeWrapper safeMutex((updateFromMasterserverThread != NULL ? updateFromMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + intToStr(__LINE__)); - if(autoRefreshTime!=0 && difftime(time(NULL),lastRefreshTimer) >= autoRefreshTime ) { - needUpdateFromServer = true; - lastRefreshTimer= time(NULL); - } - - // calculate button linepos: - setButtonLinePosition(serverLinesYBase-(serverLinesToRender)*serverLinesLineHeight-30); - - if(playServerFoundSound) - { - SoundRenderer::getInstance().playFx(CoreData::getInstance().getAttentionSound()); - //switch on music again!! - Config &config = Config::getInstance(); - float configVolume = (config.getInt("SoundVolumeMusic") / 100.f); - CoreData::getInstance().getMenuMusic()->setVolume(configVolume); - - playServerFoundSound=false; - } - - //console.update(); - - //call the chat manager - chatManager.updateNetwork(); - - //console - consoleIRC.update(); - - MutexSafeWrapper safeMutexIRCPtr(mutexIRCClient,string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + intToStr(__LINE__)); - if(ircClient != NULL) { - std::vector nickList = ircClient->getNickList(); - - if(currentIrcNick != ircClient->getNick()) { - currentIrcNick = ircClient->getNick(); - consoleIRC.setStringToHighlight(currentIrcNick); - } - - bool isNew=false; - //check if there is something new - if( oldNickList.size() != nickList.size()) { - isNew=true; - } - else { - for(unsigned int i = 0; i < nickList.size(); ++i) { - if(nickList[i] != oldNickList[i]) { - isNew=true; - break; - } - } - } + MutexSafeWrapper safeMutex( + (updateFromMasterserverThread != NULL + ? updateFromMasterserverThread->getMutexThreadObjectAccessor() + : NULL), + string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + + intToStr(__LINE__)); + if (autoRefreshTime != 0 && + difftime(time(NULL), lastRefreshTimer) >= autoRefreshTime) { + needUpdateFromServer = true; + lastRefreshTimer = time(NULL); + } + + // calculate button linepos: + setButtonLinePosition(serverLinesYBase - + (serverLinesToRender)*serverLinesLineHeight - 30); + + if (playServerFoundSound) { + SoundRenderer::getInstance().playFx( + CoreData::getInstance().getAttentionSound()); + // switch on music again!! + Config &config = Config::getInstance(); + float configVolume = (config.getInt("SoundVolumeMusic") / 100.f); + CoreData::getInstance().getMenuMusic()->setVolume(configVolume); + + playServerFoundSound = false; + } + + // console.update(); + + // call the chat manager + chatManager.updateNetwork(); + + // console + consoleIRC.update(); + + MutexSafeWrapper safeMutexIRCPtr( + mutexIRCClient, string(extractFileFromDirectoryPath(__FILE__).c_str()) + + "_" + intToStr(__LINE__)); + if (ircClient != NULL) { + std::vector nickList = ircClient->getNickList(); + + if (currentIrcNick != ircClient->getNick()) { + currentIrcNick = ircClient->getNick(); + consoleIRC.setStringToHighlight(currentIrcNick); + } - if(isNew) { - clearUserButtons(); - for(int i = 0; i < (int)nickList.size(); ++i) { - GraphicButton *button=new GraphicButton(); - button->init(userButtonsXBase,userButtonsYBase,userButtonsWidth,userButtonsHeight); - //button->init(userButtonsXBase,userButtonsYBase-userButtonsLineHeight*i,userButtonsWidth,userButtonsHeight); - button->setFont(CoreData::getInstance().getDisplayFontSmall()); - button->setFont3D(CoreData::getInstance().getDisplayFontSmall3D()); - button->setText(nickList[i]); - if(strncmp(&nickList[i][0],"MG_",3) != 0 || &nickList[i][0] == currentIrcNick) { - button->setEnabled(false); - button->setEditable(false); - button->setCustomTexture(CoreData::getInstance().getCustomTexture()); - button->setUseCustomTexture(true); - } - - userButtons.push_back(button); - } - userScrollBar.setElementCount((int)userButtons.size()); - oldNickList = nickList; - chatManager.setAutoCompleteTextList(oldNickList); + bool isNew = false; + // check if there is something new + if (oldNickList.size() != nickList.size()) { + isNew = true; + } else { + for (unsigned int i = 0; i < nickList.size(); ++i) { + if (nickList[i] != oldNickList[i]) { + isNew = true; + break; } - if(userScrollBar.getElementCount()!=0 ) { - for(int i = userScrollBar.getVisibleStart(); i <= userScrollBar.getVisibleEnd(); ++i) { - userButtons[i]->setY(userButtonsYBase-userButtonsLineHeight*(i-userScrollBar.getVisibleStart())); - } + } + } + + if (isNew) { + clearUserButtons(); + for (int i = 0; i < (int)nickList.size(); ++i) { + GraphicButton *button = new GraphicButton(); + button->init(userButtonsXBase, userButtonsYBase, userButtonsWidth, + userButtonsHeight); + // button->init(userButtonsXBase,userButtonsYBase-userButtonsLineHeight*i,userButtonsWidth,userButtonsHeight); + button->setFont(CoreData::getInstance().getDisplayFontSmall()); + button->setFont3D(CoreData::getInstance().getDisplayFontSmall3D()); + button->setText(nickList[i]); + if (strncmp(&nickList[i][0], "MG_", 3) != 0 || + &nickList[i][0] == currentIrcNick) { + button->setEnabled(false); + button->setEditable(false); + button->setCustomTexture(CoreData::getInstance().getCustomTexture()); + button->setUseCustomTexture(true); } + + userButtons.push_back(button); + } + userScrollBar.setElementCount((int)userButtons.size()); + oldNickList = nickList; + chatManager.setAutoCompleteTextList(oldNickList); } - safeMutexIRCPtr.ReleaseLock(); - if(serverInfoString!="empty") - { - rebuildServerLines(serverInfoString); - serverInfoString="empty"; + if (userScrollBar.getElementCount() != 0) { + for (int i = userScrollBar.getVisibleStart(); + i <= userScrollBar.getVisibleEnd(); ++i) { + userButtons[i]->setY(userButtonsYBase - + userButtonsLineHeight * + (i - userScrollBar.getVisibleStart())); + } + } + } + safeMutexIRCPtr.ReleaseLock(); + if (serverInfoString != "empty") { + rebuildServerLines(serverInfoString); + serverInfoString = "empty"; + } + + serverScrollBar.setElementCount((int)serverLines.size()); + if (serverScrollBar.getElementCount() != 0) { + for (int i = serverScrollBar.getVisibleStart(); + i <= serverScrollBar.getVisibleEnd(); ++i) { + serverLines[i]->setY(serverLinesYBase - + serverLinesLineHeight * + (i - serverScrollBar.getVisibleStart())); } + } - serverScrollBar.setElementCount((int)serverLines.size()); - if(serverScrollBar.getElementCount()!=0 ) { - for(int i = serverScrollBar.getVisibleStart(); i <= serverScrollBar.getVisibleEnd(); ++i) { - serverLines[i]->setY(serverLinesYBase-serverLinesLineHeight*(i-serverScrollBar.getVisibleStart())); - } - } - - if(threadedErrorMsg != "") { - std::string sError = threadedErrorMsg; - threadedErrorMsg = ""; - - if(pCB_DisplayMessage != NULL) { - pCB_DisplayMessage(sError.c_str(),false); - } - else { - throw megaglest_runtime_error(sError.c_str()); - } - } -} + if (threadedErrorMsg != "") { + std::string sError = threadedErrorMsg; + threadedErrorMsg = ""; -void MenuStateMasterserver::simpleTask(BaseThread *callingThread,void *userdata) { - if(callingThread->getQuitStatus() == true) { - return; - } - MutexSafeWrapper safeMutex(callingThread->getMutexThreadObjectAccessor(),string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + intToStr(__LINE__)); - bool needUpdate = needUpdateFromServer; + if (pCB_DisplayMessage != NULL) { + pCB_DisplayMessage(sError.c_str(), false); + } else { + throw megaglest_runtime_error(sError.c_str()); + } + } +} - if(needUpdate == true) { - try { +void MenuStateMasterserver::simpleTask(BaseThread *callingThread, + void *userdata) { + if (callingThread->getQuitStatus() == true) { + return; + } + MutexSafeWrapper safeMutex( + callingThread->getMutexThreadObjectAccessor(), + string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + + intToStr(__LINE__)); + bool needUpdate = needUpdateFromServer; + + if (needUpdate == true) { + try { - if(callingThread->getQuitStatus() == true) { - return; + if (callingThread->getQuitStatus() == true) { + return; + } + + needUpdateFromServer = false; + + if (announcementLoaded == false) { + string announcementURL = Config::getInstance().getString( + "AnnouncementURL", + "http://master.megaglest.org/files/announcement.txt"); + if (announcementURL != "") { + + safeMutex.ReleaseLock(true); + CURL *handle = SystemFlags::initHTTP(); + std::string announcementTxt = + SystemFlags::getHTTP(announcementURL, handle); + SystemFlags::cleanupHTTP(&handle); + if (callingThread->getQuitStatus() == true) { + return; + } + safeMutex.Lock(); + + if (StartsWith(announcementTxt, "Announcement from Masterserver:") == + true) { + int newlineCount = 0; + size_t lastIndex = 0; + + // announcementLabel.setText(announcementTxt); + consoleIRC.addLine(announcementTxt, true, Vec3f(1.0f, 1.0f, 0.0f)); + + while (true) { + lastIndex = announcementTxt.find("\n", lastIndex + 1); + if (lastIndex == string::npos) { + break; + } else { + newlineCount++; + } } - - needUpdateFromServer = false; - - if(announcementLoaded == false) { - string announcementURL = Config::getInstance().getString("AnnouncementURL","http://master.megaglest.org/files/announcement.txt"); - if(announcementURL != "") { - - safeMutex.ReleaseLock(true); - CURL *handle = SystemFlags::initHTTP(); - std::string announcementTxt = SystemFlags::getHTTP(announcementURL,handle); - SystemFlags::cleanupHTTP(&handle); - if(callingThread->getQuitStatus() == true) { - return; - } - safeMutex.Lock(); - - if(StartsWith(announcementTxt,"Announcement from Masterserver:") == true) { - int newlineCount=0; - size_t lastIndex=0; - - //announcementLabel.setText(announcementTxt); - consoleIRC.addLine(announcementTxt, true, Vec3f(1.0f,1.0f,0.0f)); - - while(true) { - lastIndex=announcementTxt.find("\n",lastIndex+1); - if(lastIndex==string::npos) { - break; - } - else { - newlineCount++; - } - } - newlineCount--;// remove my own line - for( int i=0; i< newlineCount;++i ) { - consoleIRC.addLine(""); - } - } - } - consoleIRC.addLine("---------------------------------------------"); - string versionURL = Config::getInstance().getString("VersionURL","http://master.megaglest.org/files/versions/")+glestVersionString+".txt"; - //printf("\nversionURL=%s\n",versionURL.c_str()); - if(versionURL != "") { - safeMutex.ReleaseLock(true); - CURL *handle = SystemFlags::initHTTP(); - std::string versionTxt = SystemFlags::getHTTP(versionURL,handle); - SystemFlags::cleanupHTTP(&handle); - if(callingThread->getQuitStatus() == true) { - return; - } - safeMutex.Lock(); - - if(StartsWith(versionTxt,"Version info:") == true) { - int newlineCount=0; - size_t lastIndex=0; - - //versionInfoLabel.setText(versionTxt); - consoleIRC.addLine(versionTxt, true, Vec3f(1.0f,0.0f,0.0f)); - - while(true) { - lastIndex=versionTxt.find("\n",lastIndex+1); - if(lastIndex==string::npos) { - break; - } - else { - newlineCount++; - } - } - newlineCount--;// remove my own line - for( int i=0; i< newlineCount;++i ) { - consoleIRC.addLine(""); - } - } - } - consoleIRC.addLine("---------------------------------------------"); - // write hint to console: - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - consoleIRC.addLine(Lang::getInstance().getString("ToSwitchOffMusicPress")+" - \""+configKeys.getString("ToggleMusic")+"\""); - - announcementLoaded=true; + newlineCount--; // remove my own line + for (int i = 0; i < newlineCount; ++i) { + consoleIRC.addLine(""); } - - //Lang &lang= Lang::getInstance(); - try { - if(Config::getInstance().getString("Masterserver","") != "") { - - safeMutex.ReleaseLock(true); - CURL *handle = SystemFlags::initHTTP(); - - string playerUUID = "?uuid=" + SystemFlags::escapeURL(Config::getInstance().getString("PlayerId","")); - - string baseURL = Config::getInstance().getString("Masterserver"); - if(baseURL != "") { - endPathWithSlash(baseURL,false); - } - - std::string localServerInfoString = SystemFlags::getHTTP(baseURL + "showServersForGlest.php" + playerUUID,handle); - SystemFlags::cleanupHTTP(&handle); - if(callingThread->getQuitStatus() == true) { - return; - } - safeMutex.Lock(); - - serverInfoString=localServerInfoString; - } + } + } + consoleIRC.addLine("---------------------------------------------"); + string versionURL = + Config::getInstance().getString( + "VersionURL", "http://master.megaglest.org/files/versions/") + + glestVersionString + ".txt"; + // printf("\nversionURL=%s\n",versionURL.c_str()); + if (versionURL != "") { + safeMutex.ReleaseLock(true); + CURL *handle = SystemFlags::initHTTP(); + std::string versionTxt = SystemFlags::getHTTP(versionURL, handle); + SystemFlags::cleanupHTTP(&handle); + if (callingThread->getQuitStatus() == true) { + return; + } + safeMutex.Lock(); + + if (StartsWith(versionTxt, "Version info:") == true) { + int newlineCount = 0; + size_t lastIndex = 0; + + // versionInfoLabel.setText(versionTxt); + consoleIRC.addLine(versionTxt, true, Vec3f(1.0f, 0.0f, 0.0f)); + + while (true) { + lastIndex = versionTxt.find("\n", lastIndex + 1); + if (lastIndex == string::npos) { + break; + } else { + newlineCount++; + } } - catch(const exception &ex) { - serverInfoString=ex.what(); - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line %d] error during Internet game status update: [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); + newlineCount--; // remove my own line + for (int i = 0; i < newlineCount; ++i) { + consoleIRC.addLine(""); } + } } - catch(const exception &e){ - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d, error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what()); - threadedErrorMsg = e.what(); + consoleIRC.addLine("---------------------------------------------"); + // write hint to console: + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + consoleIRC.addLine( + Lang::getInstance().getString("ToSwitchOffMusicPress") + " - \"" + + configKeys.getString("ToggleMusic") + "\""); + + announcementLoaded = true; + } + + // Lang &lang= Lang::getInstance(); + try { + if (Config::getInstance().getString("Masterserver", "") != "") { + + safeMutex.ReleaseLock(true); + CURL *handle = SystemFlags::initHTTP(); + + string playerUUID = + "?uuid=" + SystemFlags::escapeURL( + Config::getInstance().getString("PlayerId", "")); + + string baseURL = Config::getInstance().getString("Masterserver"); + if (baseURL != "") { + endPathWithSlash(baseURL, false); + } + + std::string localServerInfoString = SystemFlags::getHTTP( + baseURL + "showServersForGlest.php" + playerUUID, handle); + SystemFlags::cleanupHTTP(&handle); + if (callingThread->getQuitStatus() == true) { + return; + } + safeMutex.Lock(); + + serverInfoString = localServerInfoString; } - } + } catch (const exception &ex) { + serverInfoString = ex.what(); + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line %d] error during Internet " + "game status update: [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + } + } catch (const exception &e) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, e.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s] Line: %d, error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, e.what()); + threadedErrorMsg = e.what(); + } + } } void MenuStateMasterserver::rebuildServerLines(const string &serverInfo) { - int numberOfOldServerLines = (int)serverLines.size(); - clearServerLines(); - Lang &lang= Lang::getInstance(); - try { - if(serverInfo != "") { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("--------------> serverInfo [%s]\n",serverInfo.c_str()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - std::vector serverList; - Tokenize(serverInfo,serverList,"\n"); - for(int i = 0; i < (int)serverList.size(); i++) { - string &server = serverList[i]; - if(trim(server) == "") { - continue; - } - std::vector serverEntities; - Tokenize(server,serverEntities,"|"); - const int MIN_FIELDS_EXPECTED = 14; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("--------------> server [%s] serverEntities.size() = " MG_SIZE_T_SPECIFIER " MIN_FIELDS_EXPECTED = %d\n",server.c_str(),serverEntities.size(),MIN_FIELDS_EXPECTED); - - if((int)serverEntities.size() >= MIN_FIELDS_EXPECTED) { - labelTitle.setText(lang.getString("AvailableServers")); - - if(Config::getInstance().getString("Masterserver","") == "") { - labelTitle.setText("*** " + lang.getString("AvailableServers")); - } - - MasterServerInfo *masterServerInfo=new MasterServerInfo(); - - //general info: - masterServerInfo->setGlestVersion(serverEntities[0]); - masterServerInfo->setPlatform(serverEntities[1]); - masterServerInfo->setBinaryCompileDate(serverEntities[2]); - - //game info: - masterServerInfo->setServerTitle(serverEntities[3]); - masterServerInfo->setIpAddress(serverEntities[4]); - - //game setup info: - masterServerInfo->setTech(serverEntities[5]); - masterServerInfo->setMap(serverEntities[6]); - masterServerInfo->setTileset(serverEntities[7]); - masterServerInfo->setActiveSlots(strToInt(serverEntities[8])); - masterServerInfo->setNetworkSlots(strToInt(serverEntities[9])); - masterServerInfo->setConnectedClients(strToInt(serverEntities[10])); - masterServerInfo->setExternalConnectPort(strToInt(serverEntities[11])); - masterServerInfo->setCountry(serverEntities[12]); - masterServerInfo->setStatus(strToInt(serverEntities[13])); - - //printf("--------------> Country [%s] Status [%d]\n",masterServerInfo->getCountry().c_str(),masterServerInfo->getStatus()); - - //printf("Getting Ping time for host %s\n",masterServerInfo->getIpAddress().c_str()); - //float pingTime = Socket::getAveragePingMS(masterServerInfo->getIpAddress().c_str(),1); - //printf("Ping time = %f\n",pingTime); - char szBuf[8096]=""; - snprintf(szBuf,8096,"%s",masterServerInfo->getServerTitle().c_str()); - masterServerInfo->setServerTitle(szBuf); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - serverLines.push_back(new ServerLine( masterServerInfo, i, serverLinesYBase, serverLinesLineHeight, containerName)); - delete masterServerInfo; - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - Lang &lang= Lang::getInstance(); - labelTitle.setText("*** " + lang.getString("AvailableServers") + "[" + intToStr(serverEntities.size()) + "][" + intToStr(MIN_FIELDS_EXPECTED) + "] [" + serverInfo + "]"); - - if(masterserverParseErrorShown == false) { - masterserverParseErrorShown = true; - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line %d] error, no masterserver defined!\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } + int numberOfOldServerLines = (int)serverLines.size(); + clearServerLines(); + Lang &lang = Lang::getInstance(); + try { + if (serverInfo != "") { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("--------------> serverInfo [%s]\n", serverInfo.c_str()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + std::vector serverList; + Tokenize(serverInfo, serverList, "\n"); + for (int i = 0; i < (int)serverList.size(); i++) { + string &server = serverList[i]; + if (trim(server) == "") { + continue; + } + std::vector serverEntities; + Tokenize(server, serverEntities, "|"); + const int MIN_FIELDS_EXPECTED = 14; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("--------------> server [%s] serverEntities.size() " + "= " MG_SIZE_T_SPECIFIER " MIN_FIELDS_EXPECTED = %d\n", + server.c_str(), serverEntities.size(), MIN_FIELDS_EXPECTED); + + if ((int)serverEntities.size() >= MIN_FIELDS_EXPECTED) { + labelTitle.setText(lang.getString("AvailableServers")); + + if (Config::getInstance().getString("Masterserver", "") == "") { + labelTitle.setText("*** " + lang.getString("AvailableServers")); + } + + MasterServerInfo *masterServerInfo = new MasterServerInfo(); + + // general info: + masterServerInfo->setGlestVersion(serverEntities[0]); + masterServerInfo->setPlatform(serverEntities[1]); + masterServerInfo->setBinaryCompileDate(serverEntities[2]); + + // game info: + masterServerInfo->setServerTitle(serverEntities[3]); + masterServerInfo->setIpAddress(serverEntities[4]); + + // game setup info: + masterServerInfo->setTech(serverEntities[5]); + masterServerInfo->setMap(serverEntities[6]); + masterServerInfo->setTileset(serverEntities[7]); + masterServerInfo->setActiveSlots(strToInt(serverEntities[8])); + masterServerInfo->setNetworkSlots(strToInt(serverEntities[9])); + masterServerInfo->setConnectedClients(strToInt(serverEntities[10])); + masterServerInfo->setExternalConnectPort( + strToInt(serverEntities[11])); + masterServerInfo->setCountry(serverEntities[12]); + masterServerInfo->setStatus(strToInt(serverEntities[13])); + + // printf("--------------> Country [%s] Status + // [%d]\n",masterServerInfo->getCountry().c_str(),masterServerInfo->getStatus()); + + // printf("Getting Ping time for host + // %s\n",masterServerInfo->getIpAddress().c_str()); float pingTime = + // Socket::getAveragePingMS(masterServerInfo->getIpAddress().c_str(),1); + // printf("Ping time = %f\n",pingTime); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "%s", + masterServerInfo->getServerTitle().c_str()); + masterServerInfo->setServerTitle(szBuf); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + serverLines.push_back( + new ServerLine(masterServerInfo, i, serverLinesYBase, + serverLinesLineHeight, containerName)); + delete masterServerInfo; + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + Lang &lang = Lang::getInstance(); + labelTitle.setText("*** " + lang.getString("AvailableServers") + "[" + + intToStr(serverEntities.size()) + "][" + + intToStr(MIN_FIELDS_EXPECTED) + "] [" + + serverInfo + "]"); + + if (masterserverParseErrorShown == false) { + masterserverParseErrorShown = true; + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line %d] error, no masterserver defined!\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); } - catch(const exception &ex) { - labelTitle.setText("*** " + lang.getString("AvailableServers") + " [" + ex.what() + "]"); - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line %d] error during Internet game status update: [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - } - - if((int)serverLines.size() > numberOfOldServerLines) { - playServerFoundSound = true; - } -} + } catch (const exception &ex) { + labelTitle.setText("*** " + lang.getString("AvailableServers") + " [" + + ex.what() + "]"); + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line %d] error during Internet game status update: [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + ex.what()); + } + + if ((int)serverLines.size() > numberOfOldServerLines) { + playServerFoundSound = true; + } +} bool MenuStateMasterserver::connectToServer(string ipString, int port) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] START ipString='%s'\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,ipString.c_str()); - - ClientInterface* clientInterface= NetworkManager::getInstance().getClientInterface(); - //Config& config= Config::getInstance(); - Ip serverIp(ipString); - - //int serverPort = Config::getInstance().getInt("PortServer",intToStr(GameConstants::serverPort).c_str()); - int serverPort = port; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] try to connect to [%s] serverPort = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,serverIp.getString().c_str(),serverPort); - clientInterface->connect(serverIp, serverPort); - if(clientInterface->isConnected() == false) { - NetworkManager::getInstance().end(); - NetworkManager::getInstance().init(nrClient); - - mainMessageBoxState=1; - Lang &lang= Lang::getInstance(); - showMessageBox(lang.getString("CouldNotConnect"), lang.getString("ConnectionFailed"), false); - return false; - - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] connection failed\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] connected to [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,serverIp.getString().c_str()); - - //save server ip - //config.setString("ServerIp", serverIp.getString()); - //config.save(); - - for(time_t elapsedWait = time(NULL); - clientInterface->getIntroDone() == false && - clientInterface->isConnected() && - difftime(time(NULL),elapsedWait) <= 8;) { - if(clientInterface->isConnected()) { - //update lobby - clientInterface->updateLobby(); - sleep(0); - //this->render(); - } - } - if( clientInterface->isConnected() == true && - clientInterface->getIntroDone() == true) { - return true; - } - - return false; - } -} + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s] START ipString='%s'\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, ipString.c_str()); + + ClientInterface *clientInterface = + NetworkManager::getInstance().getClientInterface(); + // Config& config= Config::getInstance(); + Ip serverIp(ipString); + + // int serverPort = + // Config::getInstance().getInt("PortServer",intToStr(GameConstants::serverPort).c_str()); + int serverPort = port; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s] try to connect to [%s] serverPort = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + serverIp.getString().c_str(), serverPort); + clientInterface->connect(serverIp, serverPort); + if (clientInterface->isConnected() == false) { + NetworkManager::getInstance().end(); + NetworkManager::getInstance().init(nrClient); + + mainMessageBoxState = 1; + Lang &lang = Lang::getInstance(); + showMessageBox(lang.getString("CouldNotConnect"), + lang.getString("ConnectionFailed"), false); + return false; + + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] connection + // failed\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s] connected to [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, serverIp.getString().c_str()); + + // save server ip + // config.setString("ServerIp", serverIp.getString()); + // config.save(); + + for (time_t elapsedWait = time(NULL); + clientInterface->getIntroDone() == false && + clientInterface->isConnected() && + difftime(time(NULL), elapsedWait) <= 8;) { + if (clientInterface->isConnected()) { + // update lobby + clientInterface->updateLobby(); + sleep(0); + // this->render(); + } + } + if (clientInterface->isConnected() == true && + clientInterface->getIntroDone() == true) { + return true; + } -void MenuStateMasterserver::showMessageBox(const string &text, const string &header, bool toggle){ - if(!toggle){ - mainMessageBox.setEnabled(false); - } - - if(!mainMessageBox.getEnabled()){ - mainMessageBox.setText(text); - mainMessageBox.setHeader(header); - mainMessageBox.setEnabled(true); - } - else{ - mainMessageBox.setEnabled(false); - } + return false; + } } +void MenuStateMasterserver::showMessageBox(const string &text, + const string &header, bool toggle) { + if (!toggle) { + mainMessageBox.setEnabled(false); + } + + if (!mainMessageBox.getEnabled()) { + mainMessageBox.setText(text); + mainMessageBox.setHeader(header); + mainMessageBox.setEnabled(true); + } else { + mainMessageBox.setEnabled(false); + } +} bool MenuStateMasterserver::textInput(std::string text) { - if (ircClient != NULL && ircClient->isConnected() == true - && ircClient->getHasJoinedChannel() == true) { - return chatManager.textInput(text); - } - return false; + if (ircClient != NULL && ircClient->isConnected() == true && + ircClient->getHasJoinedChannel() == true) { + return chatManager.textInput(text); + } + return false; } void MenuStateMasterserver::keyDown(SDL_KeyboardEvent key) { - //printf("In [%s::%s Line: %d] key [%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,key.keysym.sym); - - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - - if (ircClient != NULL && ircClient->isConnected() == true - && ircClient->getHasJoinedChannel() == true) { - //chatmanger only if connected to irc! - if (chatManager.getEditEnabled() == true) { - //printf("keyDown key [%d] chatManager.getText() [%s]\n",key,chatManager.getText().c_str()); - MutexSafeWrapper safeMutexIRCPtr(mutexIRCClient,string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + intToStr(__LINE__)); - //if (key == vkReturn && ircClient != NULL) { - if(isKeyPressed(SDLK_RETURN,key,false) == true && ircClient != NULL) { - ircClient->SendIRCCmdMessage(IRC_CHANNEL, chatManager.getText()); - } - } - chatManager.keyDown(key); - } - if(chatManager.getEditEnabled() == false) { - //if(key == configKeys.getCharKey("ToggleMusic")) { - if(isKeyPressed(configKeys.getSDLKey("ToggleMusic"),key) == true) { - Config &config = Config::getInstance(); - Lang &lang= Lang::getInstance(); - - float configVolume = (config.getInt("SoundVolumeMusic") / 100.f); - float currentVolume = CoreData::getInstance().getMenuMusic()->getVolume(); - if(currentVolume > 0) { - CoreData::getInstance().getMenuMusic()->setVolume(0.f); - consoleIRC.addLine(lang.getString("GameMusic") + " " + lang.getString("Off")); - } - else { - CoreData::getInstance().getMenuMusic()->setVolume(configVolume); - //If the config says zero, use the default music volume - //gameMusic->setVolume(configVolume ? configVolume : 0.9); - consoleIRC.addLine(lang.getString("GameMusic")); - } - } - //else if(key == configKeys.getCharKey("SaveGUILayout")) { - else if(isKeyPressed(configKeys.getSDLKey("SaveGUILayout"),key) == true) { - bool saved = GraphicComponent::saveAllCustomProperties(containerName); - Lang &lang= Lang::getInstance(); - consoleIRC.addLine(lang.getString("GUILayoutSaved") + " [" + (saved ? lang.getString("Yes") : lang.getString("No"))+ "]"); - } + // printf("In [%s::%s Line: %d] key + // [%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,key.keysym.sym); + + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + + if (ircClient != NULL && ircClient->isConnected() == true && + ircClient->getHasJoinedChannel() == true) { + // chatmanger only if connected to irc! + if (chatManager.getEditEnabled() == true) { + // printf("keyDown key [%d] chatManager.getText() + // [%s]\n",key,chatManager.getText().c_str()); + MutexSafeWrapper safeMutexIRCPtr( + mutexIRCClient, + string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + + intToStr(__LINE__)); + // if (key == vkReturn && ircClient != NULL) { + if (isKeyPressed(SDLK_RETURN, key, false) == true && ircClient != NULL) { + ircClient->SendIRCCmdMessage(IRC_CHANNEL, chatManager.getText()); + } + } + chatManager.keyDown(key); + } + if (chatManager.getEditEnabled() == false) { + // if(key == configKeys.getCharKey("ToggleMusic")) { + if (isKeyPressed(configKeys.getSDLKey("ToggleMusic"), key) == true) { + Config &config = Config::getInstance(); + Lang &lang = Lang::getInstance(); + + float configVolume = (config.getInt("SoundVolumeMusic") / 100.f); + float currentVolume = CoreData::getInstance().getMenuMusic()->getVolume(); + if (currentVolume > 0) { + CoreData::getInstance().getMenuMusic()->setVolume(0.f); + consoleIRC.addLine(lang.getString("GameMusic") + " " + + lang.getString("Off")); + } else { + CoreData::getInstance().getMenuMusic()->setVolume(configVolume); + // If the config says zero, use the default music volume + // gameMusic->setVolume(configVolume ? configVolume : 0.9); + consoleIRC.addLine(lang.getString("GameMusic")); + } + } + // else if(key == configKeys.getCharKey("SaveGUILayout")) { + else if (isKeyPressed(configKeys.getSDLKey("SaveGUILayout"), key) == true) { + bool saved = GraphicComponent::saveAllCustomProperties(containerName); + Lang &lang = Lang::getInstance(); + consoleIRC.addLine( + lang.getString("GUILayoutSaved") + " [" + + (saved ? lang.getString("Yes") : lang.getString("No")) + "]"); } + } } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/menu/menu_state_masterserver.h b/source/glest_game/menu/menu_state_masterserver.h index 2b36f208e..9b8a2c462 100644 --- a/source/glest_game/menu/menu_state_masterserver.h +++ b/source/glest_game/menu/menu_state_masterserver.h @@ -12,141 +12,147 @@ #ifndef _GLEST_GAME_MENUSTATEMASTERSERVER_H_ #define _GLEST_GAME_MENUSTATEMASTERSERVER_H_ +#include "chat_manager.h" +#include "ircclient.h" +#include "leak_dumper.h" #include "main_menu.h" -#include "server_line.h" #include "masterserver_info.h" -#include "simple_threads.h" #include "network_interface.h" -#include "ircclient.h" -#include "chat_manager.h" -#include "leak_dumper.h" +#include "server_line.h" +#include "simple_threads.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // =============================== // class MenuStateMasterserver // =============================== -typedef vector ServerLines; -typedef vector UserButtons; -typedef vector MasterServerInfos; +typedef vector ServerLines; +typedef vector UserButtons; +typedef vector MasterServerInfos; -class MenuStateMasterserver : public MenuState, public SimpleTaskCallbackInterface, public IRCCallbackInterface { +class MenuStateMasterserver : public MenuState, + public SimpleTaskCallbackInterface, + public IRCCallbackInterface { private: - - GraphicButton buttonRefresh; - GraphicButton buttonReturn; - GraphicButton buttonCreateGame; - GraphicLabel labelAutoRefresh; - GraphicListBox listBoxAutoRefresh; - GraphicLabel labelTitle; - - GraphicLabel announcementLabel; - GraphicLabel versionInfoLabel; - - GraphicLine lines[3]; - - GraphicLabel glestVersionLabel; - GraphicLabel platformLabel; - //GraphicLabel binaryCompileDateLabel; - - //game info: - GraphicLabel serverTitleLabel; - GraphicLabel countryLabel; - GraphicLabel statusLabel; - - GraphicLabel ipAddressLabel; - - //game setup info: - GraphicLabel techLabel; - GraphicLabel mapLabel; - GraphicLabel tilesetLabel; - GraphicLabel activeSlotsLabel; - - GraphicLabel externalConnectPort; - - GraphicLabel selectButton; - - GraphicMessageBox mainMessageBox; - int mainMessageBoxState; - - GraphicLabel ircOnlinePeopleLabel; - GraphicLabel ircOnlinePeopleStatusLabel; - - bool announcementLoaded; - bool needUpdateFromServer; - int autoRefreshTime; - time_t lastRefreshTimer; - SimpleTaskThread *updateFromMasterserverThread; - bool playServerFoundSound; - ServerLines serverLines; - string serverInfoString; - int serverLinesToRender; - int serverLinesYBase; - int serverLinesLineHeight; - GraphicScrollBar userScrollBar; - GraphicScrollBar serverScrollBar; - UserButtons userButtons; - UserButtons userButtonsToRemove; - int userButtonsToRender; - int userButtonsYBase; - int userButtonsXBase; - int userButtonsLineHeight; - int userButtonsHeight; - int userButtonsWidth; - string currentIrcNick; - - - //Console console; - - static DisplayMessageFunction pCB_DisplayMessage; - std::string threadedErrorMsg; - - std::vector ircArgs; - Mutex *mutexIRCClient; - IRCThread *ircClient; - std::vector oldNickList; - - Console consoleIRC; - ChatManager chatManager; - - bool masterserverParseErrorShown; + GraphicButton buttonRefresh; + GraphicButton buttonReturn; + GraphicButton buttonCreateGame; + GraphicLabel labelAutoRefresh; + GraphicListBox listBoxAutoRefresh; + GraphicLabel labelTitle; + + GraphicLabel announcementLabel; + GraphicLabel versionInfoLabel; + + GraphicLine lines[3]; + + GraphicLabel glestVersionLabel; + GraphicLabel platformLabel; + // GraphicLabel binaryCompileDateLabel; + + // game info: + GraphicLabel serverTitleLabel; + GraphicLabel countryLabel; + GraphicLabel statusLabel; + + GraphicLabel ipAddressLabel; + + // game setup info: + GraphicLabel techLabel; + GraphicLabel mapLabel; + GraphicLabel tilesetLabel; + GraphicLabel activeSlotsLabel; + + GraphicLabel externalConnectPort; + + GraphicLabel selectButton; + + GraphicMessageBox mainMessageBox; + int mainMessageBoxState; + + GraphicLabel ircOnlinePeopleLabel; + GraphicLabel ircOnlinePeopleStatusLabel; + + bool announcementLoaded; + bool needUpdateFromServer; + int autoRefreshTime; + time_t lastRefreshTimer; + SimpleTaskThread *updateFromMasterserverThread; + bool playServerFoundSound; + ServerLines serverLines; + string serverInfoString; + int serverLinesToRender; + int serverLinesYBase; + int serverLinesLineHeight; + GraphicScrollBar userScrollBar; + GraphicScrollBar serverScrollBar; + UserButtons userButtons; + UserButtons userButtonsToRemove; + int userButtonsToRender; + int userButtonsYBase; + int userButtonsXBase; + int userButtonsLineHeight; + int userButtonsHeight; + int userButtonsWidth; + string currentIrcNick; + + // Console console; + + static DisplayMessageFunction pCB_DisplayMessage; + std::string threadedErrorMsg; + + std::vector ircArgs; + Mutex *mutexIRCClient; + IRCThread *ircClient; + std::vector oldNickList; + + Console consoleIRC; + ChatManager chatManager; + + bool masterserverParseErrorShown; public: - MenuStateMasterserver(Program *program, MainMenu *mainMenu); - ~MenuStateMasterserver(); + MenuStateMasterserver(Program *program, MainMenu *mainMenu); + ~MenuStateMasterserver(); - void mouseClick(int x, int y, MouseButton mouseButton); - void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; - void mouseUp(int x, int y, const MouseButton mouseButton); - void mouseMove(int x, int y, const MouseState *mouseState); - void update(); - void render(); + void mouseClick(int x, int y, MouseButton mouseButton); + void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; + void mouseUp(int x, int y, const MouseButton mouseButton); + void mouseMove(int x, int y, const MouseState *mouseState); + void update(); + void render(); - virtual bool textInput(std::string text); - virtual void keyDown(SDL_KeyboardEvent key); + virtual bool textInput(std::string text); + virtual void keyDown(SDL_KeyboardEvent key); - virtual void simpleTask(BaseThread *callingThread,void *userdata); - virtual bool isInSpecialKeyCaptureEvent() { return chatManager.getEditEnabled(); } + virtual void simpleTask(BaseThread *callingThread, void *userdata); + virtual bool isInSpecialKeyCaptureEvent() { + return chatManager.getEditEnabled(); + } - static void setDisplayMessageFunction(DisplayMessageFunction pDisplayMessage) { pCB_DisplayMessage = pDisplayMessage; } + static void + setDisplayMessageFunction(DisplayMessageFunction pDisplayMessage) { + pCB_DisplayMessage = pDisplayMessage; + } - virtual void reloadUI(); + virtual void reloadUI(); private: - void showMessageBox(const string &text, const string &header, bool toggle); - bool connectToServer(string ipString, int port); - //void setConsolePos(int yPos); - void setButtonLinePosition(int pos); - void clearServerLines(); - void clearUserButtons(); - void rebuildServerLines(const string &serverInfo); - void cleanup(); - virtual void IRC_CallbackEvent(IRCEventType evt, const char* origin, const char **params, unsigned int count); - + void showMessageBox(const string &text, const string &header, bool toggle); + bool connectToServer(string ipString, int port); + // void setConsolePos(int yPos); + void setButtonLinePosition(int pos); + void clearServerLines(); + void clearUserButtons(); + void rebuildServerLines(const string &serverInfo); + void cleanup(); + virtual void IRC_CallbackEvent(IRCEventType evt, const char *origin, + const char **params, unsigned int count); }; - -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/menu/menu_state_mods.cpp b/source/glest_game/menu/menu_state_mods.cpp index b1321bb45..5ae0a2933 100644 --- a/source/glest_game/menu/menu_state_mods.cpp +++ b/source/glest_game/menu/menu_state_mods.cpp @@ -11,2730 +11,3283 @@ #include "menu_state_mods.h" -#include "renderer.h" -#include "sound_renderer.h" -#include "core_data.h" +#include "cache_manager.h" #include "config.h" +#include "conversion.h" +#include "core_data.h" #include "menu_state_root.h" #include "metrics.h" -#include "conversion.h" +#include "renderer.h" +#include "sound_renderer.h" #include #include -#include "cache_manager.h" // Need the include below for vc++ 2010 because Microsoft messed up their STL! -#include #include "leak_dumper.h" +#include - -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { using namespace ::Shared::Util; struct FormatString { - void operator()(string &s) { - s = formatString(s); - } + void operator()(string &s) { s = formatString(s); } }; - - // =============================== // class ModInfo // =============================== ModInfo::ModInfo() { - name = ""; - url = ""; - imageUrl = ""; - description = ""; - count = ""; - crc = ""; - type = mt_None; + name = ""; + url = ""; + imageUrl = ""; + description = ""; + count = ""; + crc = ""; + type = mt_None; } - - // ===================================================== // class MenuStateConnectedGame // ===================================================== -MenuStateMods::MenuStateMods(Program *program, MainMenu *mainMenu) : - MenuState(program, mainMenu, "mods") { - - containerName = "Mods"; - Lang &lang= Lang::getInstance(); - Config &config = Config::getInstance(); - - modPreviewImage = NULL; - displayModPreviewImage.clear(); - - ftpClientThread = NULL; - selectedTechName = ""; - selectedTilesetName = ""; - selectedMapName = ""; - selectedScenarioName = ""; - modInfoSelected = NULL; - showFullConsole = false; - keyButtonsLineHeight = 20; - keyButtonsHeight = 20; - keyButtonsWidth = 200; - keyButtonsWidthTech = keyButtonsWidth; - keyButtonsWidthMap = keyButtonsWidth + 15; - keyButtonsWidthTil = keyButtonsWidth - 5; - keyButtonsWidthScen = keyButtonsWidth + 20; - scrollListsYPos = 700; - listBoxLength = 200; - keyButtonsYBase = scrollListsYPos; - keyButtonsToRender = listBoxLength / keyButtonsLineHeight; - labelWidth = 5; - keyButtonsXBase = 0; - modMenuState = mmst_None; - oldMenuState = mmst_None; - - int installButtonYPos = scrollListsYPos-listBoxLength-20; - - int returnLineY = 80; - enableMapPreview = config.getBool("MapPreview","true"); - validMapPreview = false; - mapPreviewTexture=NULL; - - //create - techInfoXPos = 5; - keyTechScrollBarTitle1.registerGraphicComponent(containerName,"keyTechScrollBarTitle1"); - keyTechScrollBarTitle1.init(techInfoXPos + 5,scrollListsYPos + 30,labelWidth,20); - keyTechScrollBarTitle1.setText(lang.getString("TechTitle1")); - keyTechScrollBarTitle1.setFont(CoreData::getInstance().getMenuFontBig()); - keyTechScrollBarTitle1.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - keyTechScrollBarTitle2.registerGraphicComponent(containerName,"keyTechScrollBarTitle2"); - keyTechScrollBarTitle2.init(techInfoXPos - 10 + keyButtonsWidthTech,scrollListsYPos + 17,labelWidth,20); - keyTechScrollBarTitle2.setText(lang.getString("TechTitle2")); - keyTechScrollBarTitle2.setFont(CoreData::getInstance().getMenuFontNormal()); - keyTechScrollBarTitle2.setFont3D(CoreData::getInstance().getMenuFontNormal3D()); - - mapInfoXPos = 260; - keyMapScrollBarTitle1.registerGraphicComponent(containerName,"keyMapScrollBarTitle1"); - keyMapScrollBarTitle1.init(mapInfoXPos + 5,scrollListsYPos + 30,labelWidth,20); - keyMapScrollBarTitle1.setText(lang.getString("MapTitle1")); - keyMapScrollBarTitle1.setFont(CoreData::getInstance().getMenuFontBig()); - keyMapScrollBarTitle1.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - keyMapScrollBarTitle2.registerGraphicComponent(containerName,"keyMapScrollBarTitle2"); - keyMapScrollBarTitle2.init(mapInfoXPos - 10 + keyButtonsWidthMap,scrollListsYPos + 17,labelWidth,20); - keyMapScrollBarTitle2.setText(lang.getString("MapTitle2")); - keyMapScrollBarTitle2.setFont(CoreData::getInstance().getMenuFontNormal()); - keyMapScrollBarTitle2.setFont3D(CoreData::getInstance().getMenuFontNormal3D()); - - tilesetInfoXPos = 530; - keyTilesetScrollBarTitle1.registerGraphicComponent(containerName,"keyTilesetScrollBarTitle1"); - keyTilesetScrollBarTitle1.init(tilesetInfoXPos + 5,scrollListsYPos + 30,labelWidth,20); - keyTilesetScrollBarTitle1.setText(lang.getString("TilesetTitle1")); - keyTilesetScrollBarTitle1.setFont(CoreData::getInstance().getMenuFontBig()); - keyTilesetScrollBarTitle1.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - - - scenarioInfoXPos = 755; - keyScenarioScrollBarTitle1.registerGraphicComponent(containerName,"keyScenarioScrollBarTitle1"); - keyScenarioScrollBarTitle1.init(scenarioInfoXPos,scrollListsYPos + 30,labelWidth,20); - keyScenarioScrollBarTitle1.setText(lang.getString("ScenarioTitle1")); - keyScenarioScrollBarTitle1.setFont(CoreData::getInstance().getMenuFontBig()); - keyScenarioScrollBarTitle1.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - - mainMessageBoxState = ftpmsg_None; - mainMessageBox.registerGraphicComponent(containerName,"mainMessageBox"); - mainMessageBox.init(lang.getString("Yes"),lang.getString("No"),450); - mainMessageBox.setEnabled(false); - - lineHorizontal.init(0,installButtonYPos-60); - lineVertical.init(500,returnLineY, 5, installButtonYPos-60-returnLineY); - lineVertical.setHorizontal(false); - lineReturn.init(0, returnLineY); - - modDescrLabel.registerGraphicComponent(containerName,"modDescrLabel"); - modDescrLabel.init(15,installButtonYPos-60 - 20,450,20); - modDescrLabel.setWordWrap(true); - modDescrLabel.setText("description is empty"); - - pleaseWaitLabel.registerGraphicComponent(containerName,"pleaseWaitLabel"); - pleaseWaitLabel.init(50,installButtonYPos-120,450,20); - pleaseWaitLabel.setText(""); - pleaseWaitLabel.setFont(CoreData::getInstance().getMenuFontBig()); - pleaseWaitLabel.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - - buttonReturn.registerGraphicComponent(containerName,"buttonReturn"); - buttonReturn.init(800, returnLineY - 30, 125); - buttonReturn.setText(lang.getString("Return")); - - lineVerticalReturn.init(buttonReturn.getX() - 10, returnLineY-80, 5, 81); - lineVerticalReturn.setHorizontal(false); - - int buttonLineUpY=installButtonYPos+10; - int buttonLineDownY=installButtonYPos-20; - - int legendButtonY= buttonLineDownY-30; - buttonInstalled.registerGraphicComponent(containerName,"buttonInstalled"); - buttonInstalled.init(5, legendButtonY, 240); - buttonInstalled.setText(" " + lang.getString("ModInstalled")); - buttonInstalled.setUseCustomTexture(true); - buttonInstalled.setCustomTexture(CoreData::getInstance().getOnServerInstalledTexture()); - buttonInstalled.setEnabled(false); - - buttonAvailable.registerGraphicComponent(containerName,"buttonAvailable"); - buttonAvailable.init(255, legendButtonY, 240); - buttonAvailable.setUseCustomTexture(true); - buttonAvailable.setCustomTexture(CoreData::getInstance().getOnServerTexture()); - buttonAvailable.setText(" " + lang.getString("ModAvailable")); - - buttonOnlyLocal.registerGraphicComponent(containerName,"buttonOnlyLocal"); - buttonOnlyLocal.init(505, legendButtonY, 240); - buttonOnlyLocal.setUseCustomTexture(true); - buttonOnlyLocal.setCustomTexture(CoreData::getInstance().getNotOnServerTexture()); - buttonOnlyLocal.setText(" " + lang.getString("ModOnlyLocal")); - - buttonConflict.registerGraphicComponent(containerName,"buttonConflict"); - buttonConflict.init(755, legendButtonY, 240); - buttonConflict.setUseCustomTexture(true); - buttonConflict.setCustomTexture(CoreData::getInstance().getOnServerDifferentTexture()); - buttonConflict.setText(" " + lang.getString("ModHasConflict")); - - - buttonInstallTech.registerGraphicComponent(containerName,"buttonInstallTech"); - buttonInstallTech.init(techInfoXPos + 45, buttonLineUpY, 125); - buttonInstallTech.setText(lang.getString("Install")); - buttonRemoveTech.registerGraphicComponent(containerName,"buttonRemoveTech"); - buttonRemoveTech.init(techInfoXPos + 45, buttonLineDownY, 125); - buttonRemoveTech.setText(lang.getString("Remove")); - - buttonInstallTileset.registerGraphicComponent(containerName,"buttonInstallTileset"); - buttonInstallTileset.init(tilesetInfoXPos + 30, buttonLineUpY, 125); - buttonInstallTileset.setText(lang.getString("Install")); - buttonRemoveTileset.registerGraphicComponent(containerName,"buttonRemoveTileset"); - buttonRemoveTileset.init(tilesetInfoXPos + 30, buttonLineDownY, 125); - buttonRemoveTileset.setText(lang.getString("Remove")); - - buttonInstallMap.registerGraphicComponent(containerName,"buttonInstallMap"); - buttonInstallMap.init(mapInfoXPos + 50, buttonLineUpY, 125); - buttonInstallMap.setText(lang.getString("Install")); - buttonRemoveMap.registerGraphicComponent(containerName,"buttonRemoveMap"); - buttonRemoveMap.init(mapInfoXPos + 50, buttonLineDownY, 125); - buttonRemoveMap.setText(lang.getString("Remove")); - - buttonInstallScenario.registerGraphicComponent(containerName,"buttonInstallScenario"); - buttonInstallScenario.init(scenarioInfoXPos + 45, buttonLineUpY, 125); - buttonInstallScenario.setText(lang.getString("Install")); - buttonRemoveScenario.registerGraphicComponent(containerName,"buttonRemoveScenario"); - buttonRemoveScenario.init(scenarioInfoXPos + 45, buttonLineDownY, 125); - buttonRemoveScenario.setText(lang.getString("Remove")); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - keyTilesetScrollBar.init(tilesetInfoXPos + keyButtonsWidthTil,scrollListsYPos-listBoxLength+keyButtonsLineHeight,false,200,20); - keyTilesetScrollBar.setLength(listBoxLength); - keyTilesetScrollBar.setElementCount(0); - keyTilesetScrollBar.setVisibleSize(keyButtonsToRender); - keyTilesetScrollBar.setVisibleStart(0); - - keyTechScrollBar.init(techInfoXPos + keyButtonsWidthTech + labelWidth + 20,scrollListsYPos-listBoxLength+keyButtonsLineHeight,false,200,20); - keyTechScrollBar.setLength(listBoxLength); - keyTechScrollBar.setElementCount(0); - keyTechScrollBar.setVisibleSize(keyButtonsToRender); - keyTechScrollBar.setVisibleStart(0); - - keyMapScrollBar.init(mapInfoXPos + keyButtonsWidthMap + labelWidth + 20,scrollListsYPos-listBoxLength+keyButtonsLineHeight,false,200,20); - keyMapScrollBar.setLength(listBoxLength); - keyMapScrollBar.setElementCount(0); - keyMapScrollBar.setVisibleSize(keyButtonsToRender); - keyMapScrollBar.setVisibleStart(0); - - keyScenarioScrollBar.init(scenarioInfoXPos + keyButtonsWidthScen,scrollListsYPos-listBoxLength+keyButtonsLineHeight,false,200,20); - keyScenarioScrollBar.setLength(listBoxLength); - keyScenarioScrollBar.setElementCount(0); - keyScenarioScrollBar.setVisibleSize(keyButtonsToRender); - keyScenarioScrollBar.setVisibleStart(0); - - GraphicComponent::applyAllCustomProperties(containerName); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - // Start http meta data thread - static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); - modHttpServerThread = new SimpleTaskThread(this,0,200); - modHttpServerThread->setUniqueID(mutexOwnerId); - modHttpServerThread->start(); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - // Setup File Transfer thread - findDirs(config.getPathListForType(ptTilesets), tilesetFiles); - findDirs(config.getPathListForType(ptTechs), techTreeFiles); - - vector mapPathList = config.getPathListForType(ptMaps); - std::pair mapsPath; - if(mapPathList.empty() == false) { - mapsPath.first = mapPathList[0]; - } - if(mapPathList.size() > 1) { - mapsPath.second = mapPathList[1]; - } - std::pair tilesetsPath; - vector tilesetsList = Config::getInstance().getPathListForType(ptTilesets); - if(tilesetsList.empty() == false) { - tilesetsPath.first = tilesetsList[0]; - if(tilesetsList.size() > 1) { - tilesetsPath.second = tilesetsList[1]; - } - } - - std::pair techtreesPath; - vector techtreesList = Config::getInstance().getPathListForType(ptTechs); - if(techtreesList.empty() == false) { - techtreesPath.first = techtreesList[0]; - if(techtreesList.size() > 1) { - techtreesPath.second = techtreesList[1]; - } - } - - std::pair scenariosPath; - vector scenariosList = Config::getInstance().getPathListForType(ptScenarios); - if(scenariosList.empty() == false) { - scenariosPath.first = scenariosList[0]; - if(scenariosList.size() > 1) { - scenariosPath.second = scenariosList[1]; - } +MenuStateMods::MenuStateMods(Program *program, MainMenu *mainMenu) + : MenuState(program, mainMenu, "mods") { + + containerName = "Mods"; + Lang &lang = Lang::getInstance(); + Config &config = Config::getInstance(); + + modPreviewImage = NULL; + displayModPreviewImage.clear(); + + ftpClientThread = NULL; + selectedTechName = ""; + selectedTilesetName = ""; + selectedMapName = ""; + selectedScenarioName = ""; + modInfoSelected = NULL; + showFullConsole = false; + keyButtonsLineHeight = 20; + keyButtonsHeight = 20; + keyButtonsWidth = 200; + keyButtonsWidthTech = keyButtonsWidth; + keyButtonsWidthMap = keyButtonsWidth + 15; + keyButtonsWidthTil = keyButtonsWidth - 5; + keyButtonsWidthScen = keyButtonsWidth + 20; + scrollListsYPos = 700; + listBoxLength = 200; + keyButtonsYBase = scrollListsYPos; + keyButtonsToRender = listBoxLength / keyButtonsLineHeight; + labelWidth = 5; + keyButtonsXBase = 0; + modMenuState = mmst_None; + oldMenuState = mmst_None; + + int installButtonYPos = scrollListsYPos - listBoxLength - 20; + + int returnLineY = 80; + enableMapPreview = config.getBool("MapPreview", "true"); + validMapPreview = false; + mapPreviewTexture = NULL; + + // create + techInfoXPos = 5; + keyTechScrollBarTitle1.registerGraphicComponent(containerName, + "keyTechScrollBarTitle1"); + keyTechScrollBarTitle1.init(techInfoXPos + 5, scrollListsYPos + 30, + labelWidth, 20); + keyTechScrollBarTitle1.setText(lang.getString("TechTitle1")); + keyTechScrollBarTitle1.setFont(CoreData::getInstance().getMenuFontBig()); + keyTechScrollBarTitle1.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + keyTechScrollBarTitle2.registerGraphicComponent(containerName, + "keyTechScrollBarTitle2"); + keyTechScrollBarTitle2.init(techInfoXPos - 10 + keyButtonsWidthTech, + scrollListsYPos + 17, labelWidth, 20); + keyTechScrollBarTitle2.setText(lang.getString("TechTitle2")); + keyTechScrollBarTitle2.setFont(CoreData::getInstance().getMenuFontNormal()); + keyTechScrollBarTitle2.setFont3D( + CoreData::getInstance().getMenuFontNormal3D()); + + mapInfoXPos = 260; + keyMapScrollBarTitle1.registerGraphicComponent(containerName, + "keyMapScrollBarTitle1"); + keyMapScrollBarTitle1.init(mapInfoXPos + 5, scrollListsYPos + 30, labelWidth, + 20); + keyMapScrollBarTitle1.setText(lang.getString("MapTitle1")); + keyMapScrollBarTitle1.setFont(CoreData::getInstance().getMenuFontBig()); + keyMapScrollBarTitle1.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + keyMapScrollBarTitle2.registerGraphicComponent(containerName, + "keyMapScrollBarTitle2"); + keyMapScrollBarTitle2.init(mapInfoXPos - 10 + keyButtonsWidthMap, + scrollListsYPos + 17, labelWidth, 20); + keyMapScrollBarTitle2.setText(lang.getString("MapTitle2")); + keyMapScrollBarTitle2.setFont(CoreData::getInstance().getMenuFontNormal()); + keyMapScrollBarTitle2.setFont3D( + CoreData::getInstance().getMenuFontNormal3D()); + + tilesetInfoXPos = 530; + keyTilesetScrollBarTitle1.registerGraphicComponent( + containerName, "keyTilesetScrollBarTitle1"); + keyTilesetScrollBarTitle1.init(tilesetInfoXPos + 5, scrollListsYPos + 30, + labelWidth, 20); + keyTilesetScrollBarTitle1.setText(lang.getString("TilesetTitle1")); + keyTilesetScrollBarTitle1.setFont(CoreData::getInstance().getMenuFontBig()); + keyTilesetScrollBarTitle1.setFont3D( + CoreData::getInstance().getMenuFontBig3D()); + + scenarioInfoXPos = 755; + keyScenarioScrollBarTitle1.registerGraphicComponent( + containerName, "keyScenarioScrollBarTitle1"); + keyScenarioScrollBarTitle1.init(scenarioInfoXPos, scrollListsYPos + 30, + labelWidth, 20); + keyScenarioScrollBarTitle1.setText(lang.getString("ScenarioTitle1")); + keyScenarioScrollBarTitle1.setFont(CoreData::getInstance().getMenuFontBig()); + keyScenarioScrollBarTitle1.setFont3D( + CoreData::getInstance().getMenuFontBig3D()); + + mainMessageBoxState = ftpmsg_None; + mainMessageBox.registerGraphicComponent(containerName, "mainMessageBox"); + mainMessageBox.init(lang.getString("Yes"), lang.getString("No"), 450); + mainMessageBox.setEnabled(false); + + lineHorizontal.init(0, installButtonYPos - 60); + lineVertical.init(500, returnLineY, 5, installButtonYPos - 60 - returnLineY); + lineVertical.setHorizontal(false); + lineReturn.init(0, returnLineY); + + modDescrLabel.registerGraphicComponent(containerName, "modDescrLabel"); + modDescrLabel.init(15, installButtonYPos - 60 - 20, 450, 20); + modDescrLabel.setWordWrap(true); + modDescrLabel.setText("description is empty"); + + pleaseWaitLabel.registerGraphicComponent(containerName, "pleaseWaitLabel"); + pleaseWaitLabel.init(50, installButtonYPos - 120, 450, 20); + pleaseWaitLabel.setText(""); + pleaseWaitLabel.setFont(CoreData::getInstance().getMenuFontBig()); + pleaseWaitLabel.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + + buttonReturn.registerGraphicComponent(containerName, "buttonReturn"); + buttonReturn.init(800, returnLineY - 30, 125); + buttonReturn.setText(lang.getString("Return")); + + lineVerticalReturn.init(buttonReturn.getX() - 10, returnLineY - 80, 5, 81); + lineVerticalReturn.setHorizontal(false); + + int buttonLineUpY = installButtonYPos + 10; + int buttonLineDownY = installButtonYPos - 20; + + int legendButtonY = buttonLineDownY - 30; + buttonInstalled.registerGraphicComponent(containerName, "buttonInstalled"); + buttonInstalled.init(5, legendButtonY, 240); + buttonInstalled.setText(" " + lang.getString("ModInstalled")); + buttonInstalled.setUseCustomTexture(true); + buttonInstalled.setCustomTexture( + CoreData::getInstance().getOnServerInstalledTexture()); + buttonInstalled.setEnabled(false); + + buttonAvailable.registerGraphicComponent(containerName, "buttonAvailable"); + buttonAvailable.init(255, legendButtonY, 240); + buttonAvailable.setUseCustomTexture(true); + buttonAvailable.setCustomTexture( + CoreData::getInstance().getOnServerTexture()); + buttonAvailable.setText(" " + lang.getString("ModAvailable")); + + buttonOnlyLocal.registerGraphicComponent(containerName, "buttonOnlyLocal"); + buttonOnlyLocal.init(505, legendButtonY, 240); + buttonOnlyLocal.setUseCustomTexture(true); + buttonOnlyLocal.setCustomTexture( + CoreData::getInstance().getNotOnServerTexture()); + buttonOnlyLocal.setText(" " + lang.getString("ModOnlyLocal")); + + buttonConflict.registerGraphicComponent(containerName, "buttonConflict"); + buttonConflict.init(755, legendButtonY, 240); + buttonConflict.setUseCustomTexture(true); + buttonConflict.setCustomTexture( + CoreData::getInstance().getOnServerDifferentTexture()); + buttonConflict.setText(" " + lang.getString("ModHasConflict")); + + buttonInstallTech.registerGraphicComponent(containerName, + "buttonInstallTech"); + buttonInstallTech.init(techInfoXPos + 45, buttonLineUpY, 125); + buttonInstallTech.setText(lang.getString("Install")); + buttonRemoveTech.registerGraphicComponent(containerName, "buttonRemoveTech"); + buttonRemoveTech.init(techInfoXPos + 45, buttonLineDownY, 125); + buttonRemoveTech.setText(lang.getString("Remove")); + + buttonInstallTileset.registerGraphicComponent(containerName, + "buttonInstallTileset"); + buttonInstallTileset.init(tilesetInfoXPos + 30, buttonLineUpY, 125); + buttonInstallTileset.setText(lang.getString("Install")); + buttonRemoveTileset.registerGraphicComponent(containerName, + "buttonRemoveTileset"); + buttonRemoveTileset.init(tilesetInfoXPos + 30, buttonLineDownY, 125); + buttonRemoveTileset.setText(lang.getString("Remove")); + + buttonInstallMap.registerGraphicComponent(containerName, "buttonInstallMap"); + buttonInstallMap.init(mapInfoXPos + 50, buttonLineUpY, 125); + buttonInstallMap.setText(lang.getString("Install")); + buttonRemoveMap.registerGraphicComponent(containerName, "buttonRemoveMap"); + buttonRemoveMap.init(mapInfoXPos + 50, buttonLineDownY, 125); + buttonRemoveMap.setText(lang.getString("Remove")); + + buttonInstallScenario.registerGraphicComponent(containerName, + "buttonInstallScenario"); + buttonInstallScenario.init(scenarioInfoXPos + 45, buttonLineUpY, 125); + buttonInstallScenario.setText(lang.getString("Install")); + buttonRemoveScenario.registerGraphicComponent(containerName, + "buttonRemoveScenario"); + buttonRemoveScenario.init(scenarioInfoXPos + 45, buttonLineDownY, 125); + buttonRemoveScenario.setText(lang.getString("Remove")); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + keyTilesetScrollBar.init( + tilesetInfoXPos + keyButtonsWidthTil, + scrollListsYPos - listBoxLength + keyButtonsLineHeight, false, 200, 20); + keyTilesetScrollBar.setLength(listBoxLength); + keyTilesetScrollBar.setElementCount(0); + keyTilesetScrollBar.setVisibleSize(keyButtonsToRender); + keyTilesetScrollBar.setVisibleStart(0); + + keyTechScrollBar.init(techInfoXPos + keyButtonsWidthTech + labelWidth + 20, + scrollListsYPos - listBoxLength + keyButtonsLineHeight, + false, 200, 20); + keyTechScrollBar.setLength(listBoxLength); + keyTechScrollBar.setElementCount(0); + keyTechScrollBar.setVisibleSize(keyButtonsToRender); + keyTechScrollBar.setVisibleStart(0); + + keyMapScrollBar.init(mapInfoXPos + keyButtonsWidthMap + labelWidth + 20, + scrollListsYPos - listBoxLength + keyButtonsLineHeight, + false, 200, 20); + keyMapScrollBar.setLength(listBoxLength); + keyMapScrollBar.setElementCount(0); + keyMapScrollBar.setVisibleSize(keyButtonsToRender); + keyMapScrollBar.setVisibleStart(0); + + keyScenarioScrollBar.init( + scenarioInfoXPos + keyButtonsWidthScen, + scrollListsYPos - listBoxLength + keyButtonsLineHeight, false, 200, 20); + keyScenarioScrollBar.setLength(listBoxLength); + keyScenarioScrollBar.setElementCount(0); + keyScenarioScrollBar.setVisibleSize(keyButtonsToRender); + keyScenarioScrollBar.setVisibleStart(0); + + GraphicComponent::applyAllCustomProperties(containerName); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + // Start http meta data thread + static string mutexOwnerId = + string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + + intToStr(__LINE__); + modHttpServerThread = new SimpleTaskThread(this, 0, 200); + modHttpServerThread->setUniqueID(mutexOwnerId); + modHttpServerThread->start(); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + // Setup File Transfer thread + findDirs(config.getPathListForType(ptTilesets), tilesetFiles); + findDirs(config.getPathListForType(ptTechs), techTreeFiles); + + vector mapPathList = config.getPathListForType(ptMaps); + std::pair mapsPath; + if (mapPathList.empty() == false) { + mapsPath.first = mapPathList[0]; + } + if (mapPathList.size() > 1) { + mapsPath.second = mapPathList[1]; + } + std::pair tilesetsPath; + vector tilesetsList = + Config::getInstance().getPathListForType(ptTilesets); + if (tilesetsList.empty() == false) { + tilesetsPath.first = tilesetsList[0]; + if (tilesetsList.size() > 1) { + tilesetsPath.second = tilesetsList[1]; } - - string fileArchiveExtension = config.getString("FileArchiveExtension",""); - string fileArchiveExtractCommand = config.getString("FileArchiveExtractCommand",""); - string fileArchiveExtractCommandParameters = config.getString("FileArchiveExtractCommandParameters",""); - int32 fileArchiveExtractCommandSuccessResult = config.getInt("FileArchiveExtractCommandSuccessResult","0"); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - console.setOnlyChatMessagesInStoredLines(false); - - // Get path to temp files - string tempFilePath = "temp/"; - if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - tempFilePath = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + tempFilePath; - } - else { - string userData = config.getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - tempFilePath = userData + tempFilePath; - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Temp files path [%s]\n",tempFilePath.c_str()); - - ftpClientThread = new FTPClientThread(-1,"", - mapsPath,tilesetsPath,techtreesPath,scenariosPath, - this,fileArchiveExtension,fileArchiveExtractCommand, - fileArchiveExtractCommandParameters, - fileArchiveExtractCommandSuccessResult, - tempFilePath); - ftpClientThread->start(); - - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); + } + + std::pair techtreesPath; + vector techtreesList = + Config::getInstance().getPathListForType(ptTechs); + if (techtreesList.empty() == false) { + techtreesPath.first = techtreesList[0]; + if (techtreesList.size() > 1) { + techtreesPath.second = techtreesList[1]; + } + } + + std::pair scenariosPath; + vector scenariosList = + Config::getInstance().getPathListForType(ptScenarios); + if (scenariosList.empty() == false) { + scenariosPath.first = scenariosList[0]; + if (scenariosList.size() > 1) { + scenariosPath.second = scenariosList[1]; + } + } + + string fileArchiveExtension = config.getString("FileArchiveExtension", ""); + string fileArchiveExtractCommand = + config.getString("FileArchiveExtractCommand", ""); + string fileArchiveExtractCommandParameters = + config.getString("FileArchiveExtractCommandParameters", ""); + int32 fileArchiveExtractCommandSuccessResult = + config.getInt("FileArchiveExtractCommandSuccessResult", "0"); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + console.setOnlyChatMessagesInStoredLines(false); + + // Get path to temp files + string tempFilePath = "temp/"; + if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { + tempFilePath = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + + tempFilePath; + } else { + string userData = config.getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + tempFilePath = userData + tempFilePath; + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Temp files path [%s]\n", tempFilePath.c_str()); + + ftpClientThread = new FTPClientThread( + -1, "", mapsPath, tilesetsPath, techtreesPath, scenariosPath, this, + fileArchiveExtension, fileArchiveExtractCommand, + fileArchiveExtractCommandParameters, + fileArchiveExtractCommandSuccessResult, tempFilePath); + ftpClientThread->start(); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + __FILE__, __FUNCTION__, __LINE__); } void MenuStateMods::reloadUI() { - Lang &lang= Lang::getInstance(); + Lang &lang = Lang::getInstance(); - console.resetFonts(); - keyTechScrollBarTitle1.setText(lang.getString("TechTitle1")); - keyTechScrollBarTitle1.setFont(CoreData::getInstance().getMenuFontBig()); - keyTechScrollBarTitle1.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - keyTechScrollBarTitle2.setText(lang.getString("TechTitle2")); - keyTechScrollBarTitle2.setFont(CoreData::getInstance().getMenuFontNormal()); - keyTechScrollBarTitle2.setFont3D(CoreData::getInstance().getMenuFontNormal3D()); + console.resetFonts(); + keyTechScrollBarTitle1.setText(lang.getString("TechTitle1")); + keyTechScrollBarTitle1.setFont(CoreData::getInstance().getMenuFontBig()); + keyTechScrollBarTitle1.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + keyTechScrollBarTitle2.setText(lang.getString("TechTitle2")); + keyTechScrollBarTitle2.setFont(CoreData::getInstance().getMenuFontNormal()); + keyTechScrollBarTitle2.setFont3D( + CoreData::getInstance().getMenuFontNormal3D()); - keyMapScrollBarTitle1.setText(lang.getString("MapTitle1")); - keyMapScrollBarTitle1.setFont(CoreData::getInstance().getMenuFontBig()); - keyMapScrollBarTitle1.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - keyMapScrollBarTitle2.setText(lang.getString("MapTitle2")); - keyMapScrollBarTitle2.setFont(CoreData::getInstance().getMenuFontNormal()); - keyMapScrollBarTitle2.setFont3D(CoreData::getInstance().getMenuFontNormal3D()); + keyMapScrollBarTitle1.setText(lang.getString("MapTitle1")); + keyMapScrollBarTitle1.setFont(CoreData::getInstance().getMenuFontBig()); + keyMapScrollBarTitle1.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + keyMapScrollBarTitle2.setText(lang.getString("MapTitle2")); + keyMapScrollBarTitle2.setFont(CoreData::getInstance().getMenuFontNormal()); + keyMapScrollBarTitle2.setFont3D( + CoreData::getInstance().getMenuFontNormal3D()); - keyTilesetScrollBarTitle1.setText(lang.getString("TilesetTitle1")); - keyTilesetScrollBarTitle1.setFont(CoreData::getInstance().getMenuFontBig()); - keyTilesetScrollBarTitle1.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + keyTilesetScrollBarTitle1.setText(lang.getString("TilesetTitle1")); + keyTilesetScrollBarTitle1.setFont(CoreData::getInstance().getMenuFontBig()); + keyTilesetScrollBarTitle1.setFont3D( + CoreData::getInstance().getMenuFontBig3D()); - pleaseWaitLabel.setText(""); - pleaseWaitLabel.setFont(CoreData::getInstance().getMenuFontBig()); - pleaseWaitLabel.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + pleaseWaitLabel.setText(""); + pleaseWaitLabel.setFont(CoreData::getInstance().getMenuFontBig()); + pleaseWaitLabel.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - keyScenarioScrollBarTitle1.setText(lang.getString("ScenarioTitle1")); - keyScenarioScrollBarTitle1.setFont(CoreData::getInstance().getMenuFontBig()); - keyScenarioScrollBarTitle1.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + keyScenarioScrollBarTitle1.setText(lang.getString("ScenarioTitle1")); + keyScenarioScrollBarTitle1.setFont(CoreData::getInstance().getMenuFontBig()); + keyScenarioScrollBarTitle1.setFont3D( + CoreData::getInstance().getMenuFontBig3D()); - mainMessageBox.init(lang.getString("Yes"),lang.getString("No"),450); + mainMessageBox.init(lang.getString("Yes"), lang.getString("No"), 450); - modDescrLabel.setText("description is empty"); + modDescrLabel.setText("description is empty"); - buttonReturn.setText(lang.getString("Return")); + buttonReturn.setText(lang.getString("Return")); - buttonInstalled.setText(lang.getString("ModInstalled")); + buttonInstalled.setText(lang.getString("ModInstalled")); - buttonAvailable.setText(lang.getString("ModAvailable")); + buttonAvailable.setText(lang.getString("ModAvailable")); - buttonOnlyLocal.setText(lang.getString("ModOnlyLocal")); + buttonOnlyLocal.setText(lang.getString("ModOnlyLocal")); - buttonConflict.setText(lang.getString("ModHasConflict")); + buttonConflict.setText(lang.getString("ModHasConflict")); - buttonInstallTech.setText(lang.getString("Install")); - buttonRemoveTech.setText(lang.getString("Remove")); + buttonInstallTech.setText(lang.getString("Install")); + buttonRemoveTech.setText(lang.getString("Remove")); - buttonInstallTileset.setText(lang.getString("Install")); - buttonRemoveTileset.setText(lang.getString("Remove")); + buttonInstallTileset.setText(lang.getString("Install")); + buttonRemoveTileset.setText(lang.getString("Remove")); - buttonInstallMap.setText(lang.getString("Install")); - buttonRemoveMap.setText(lang.getString("Remove")); + buttonInstallMap.setText(lang.getString("Install")); + buttonRemoveMap.setText(lang.getString("Remove")); - buttonInstallScenario.setText(lang.getString("Install")); - buttonRemoveScenario.setText(lang.getString("Remove")); + buttonInstallScenario.setText(lang.getString("Install")); + buttonRemoveScenario.setText(lang.getString("Remove")); - GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); + GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); } -void MenuStateMods::simpleTask(BaseThread *callingThread,void *userdata) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexThreadOwner(callingThread->getMutexThreadOwnerValid(),mutexOwnerId); - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; +void MenuStateMods::simpleTask(BaseThread *callingThread, void *userdata) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexThreadOwner( + callingThread->getMutexThreadOwnerValid(), mutexOwnerId); + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; + } + + callingThread->getMutexThreadOwnerValid()->setOwnerId(mutexOwnerId); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + Lang &lang = Lang::getInstance(); + Config &config = Config::getInstance(); + string fileArchiveExtractCommand = + config.getString("FileArchiveExtractCommand", ""); + int expectedResult = + config.getInt("FileArchiveExtractCommandSuccessResult", "0"); + bool findArchive = + executeShellCommand(fileArchiveExtractCommand, expectedResult); + if (findArchive == false) { + mainMessageBoxState = ftpmsg_None; + mainMessageBox.init(lang.getString("Ok"), 450); + showMessageBox(lang.getString("ModRequires7z"), lang.getString("Notice"), + true); + } + + std::string techsMetaData = ""; + std::string tilesetsMetaData = ""; + std::string mapsMetaData = ""; + std::string scenariosMetaData = ""; + + modMenuState = mmst_Loading; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + if (config.getString("Masterserver", "") != "") { + string baseURL = config.getString("Masterserver"); + if (baseURL != "") { + endPathWithSlash(baseURL, false); } - callingThread->getMutexThreadOwnerValid()->setOwnerId(mutexOwnerId); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - Lang &lang= Lang::getInstance(); - Config &config = Config::getInstance(); - string fileArchiveExtractCommand = config.getString("FileArchiveExtractCommand",""); - int expectedResult = config.getInt("FileArchiveExtractCommandSuccessResult","0"); - bool findArchive = executeShellCommand(fileArchiveExtractCommand,expectedResult); - if(findArchive == false) { - mainMessageBoxState = ftpmsg_None; - mainMessageBox.init(lang.getString("Ok"),450); - showMessageBox(lang.getString("ModRequires7z"), lang.getString("Notice"), true); - } - - std::string techsMetaData = ""; - std::string tilesetsMetaData = ""; - std::string mapsMetaData = ""; - std::string scenariosMetaData = ""; - - modMenuState=mmst_Loading; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(config.getString("Masterserver","") != "") { - string baseURL = config.getString("Masterserver"); - if(baseURL != "") { - endPathWithSlash(baseURL,false); - } - - string phpVersionParam = config.getString("phpVersionParam","?version=0.1"); - string playerUUID = "&uuid=" + SystemFlags::escapeURL(Config::getInstance().getString("PlayerId","")); - string gameVersion = "&glestVersion=" + SystemFlags::escapeURL(glestVersionString); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d] About to call first http url, base [%s]..\n",__FILE__,__FUNCTION__,__LINE__,baseURL.c_str()); - - CURL *handle = SystemFlags::initHTTP(); - CURLcode curlResult = CURLE_OK; - techsMetaData = SystemFlags::getHTTP(baseURL + "showTechsForGlest.php"+phpVersionParam+gameVersion+playerUUID,handle,-1,&curlResult); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("techsMetaData [%s] curlResult = %d\n",techsMetaData.c_str(),curlResult); - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; - } - - if(curlResult != CURLE_OK) { - string curlError = curl_easy_strerror(curlResult); - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModErrorGettingServerData").c_str(),curlError.c_str()); - console.addLine(string("#1 ") + szBuf,true); - } - - if(curlResult == CURLE_OK || - (curlResult != CURLE_COULDNT_RESOLVE_HOST && - curlResult != CURLE_COULDNT_CONNECT)) { - - tilesetsMetaData = SystemFlags::getHTTP(baseURL + "showTilesetsForGlest.php"+phpVersionParam+gameVersion,handle,-1,&curlResult); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("tilesetsMetaData [%s]\n",tilesetsMetaData.c_str()); - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; - } - - if(curlResult != CURLE_OK) { - string curlError = curl_easy_strerror(curlResult); - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModErrorGettingServerData").c_str(),curlError.c_str()); - console.addLine(string("#2 ") + szBuf,true); - } - - mapsMetaData = SystemFlags::getHTTP(baseURL + "showMapsForGlest.php"+phpVersionParam+gameVersion,handle,-1,&curlResult); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("mapsMetaData [%s]\n",mapsMetaData.c_str()); - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; - } - - if(curlResult != CURLE_OK) { - string curlError = curl_easy_strerror(curlResult); - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModErrorGettingServerData").c_str(),curlError.c_str()); - console.addLine(string("#3 ") + szBuf,true); - } - - scenariosMetaData = SystemFlags::getHTTP(baseURL + "showScenariosForGlest.php"+phpVersionParam+gameVersion,handle,-1,&curlResult); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("scenariosMetaData [%s]\n",scenariosMetaData.c_str()); - - if(curlResult != CURLE_OK) { - string curlError = curl_easy_strerror(curlResult); - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModErrorGettingServerData").c_str(),curlError.c_str()); - console.addLine(string("#4 ") + szBuf,true); - } - } - SystemFlags::cleanupHTTP(&handle); - } - else { - console.addLine(lang.getString("MasterServerMissing"),true); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; + string phpVersionParam = + config.getString("phpVersionParam", "?version=0.1"); + string playerUUID = + "&uuid=" + + SystemFlags::escapeURL(Config::getInstance().getString("PlayerId", "")); + string gameVersion = + "&glestVersion=" + SystemFlags::escapeURL(glestVersionString); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d] About to call first http url, base [%s]..\n", + __FILE__, __FUNCTION__, __LINE__, baseURL.c_str()); + + CURL *handle = SystemFlags::initHTTP(); + CURLcode curlResult = CURLE_OK; + techsMetaData = + SystemFlags::getHTTP(baseURL + "showTechsForGlest.php" + + phpVersionParam + gameVersion + playerUUID, + handle, -1, &curlResult); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("techsMetaData [%s] curlResult = %d\n", techsMetaData.c_str(), + curlResult); + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - tilesetListRemote.clear(); - Tokenize(tilesetsMetaData,tilesetListRemote,"\n"); - - modMenuState=mmst_CalculatingCRC; - - getTilesetsLocalList(); - for(unsigned int i=0; i < tilesetListRemote.size(); i++) { - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; - } - - string result=refreshTilesetModInfo(tilesetListRemote[i]); - if(result != "") { - ModInfo modinfo; - modinfo=tilesetCacheList[result]; - GraphicButton *button=new GraphicButton(); - button->init(tilesetInfoXPos, keyButtonsYBase, keyButtonsWidthTil,keyButtonsHeight); - button->setText(modinfo.name); - button->setUseCustomTexture(true); - button->setCustomTexture(CoreData::getInstance().getCustomTexture()); - keyTilesetButtons.push_back(button); - } - } - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; + if (curlResult != CURLE_OK) { + string curlError = curl_easy_strerror(curlResult); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, lang.getString("ModErrorGettingServerData").c_str(), + curlError.c_str()); + console.addLine(string("#1 ") + szBuf, true); } - for(unsigned int i=0; i < tilesetFilesUserData.size(); i++) { - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; - } + if (curlResult == CURLE_OK || (curlResult != CURLE_COULDNT_RESOLVE_HOST && + curlResult != CURLE_COULDNT_CONNECT)) { - string tilesetName = tilesetFilesUserData[i]; - bool alreadyHasTileset = (tilesetCacheList.find(tilesetName) != tilesetCacheList.end()); - if(alreadyHasTileset == false) { - GraphicButton *button=new GraphicButton(); - button->init(tilesetInfoXPos, keyButtonsYBase, keyButtonsWidthTil,keyButtonsHeight); - button->setText(tilesetName); - button->setUseCustomTexture(true); - button->setCustomTexture(CoreData::getInstance().getCustomTexture()); - keyTilesetButtons.push_back(button); - } - } + tilesetsMetaData = SystemFlags::getHTTP( + baseURL + "showTilesetsForGlest.php" + phpVersionParam + gameVersion, + handle, -1, &curlResult); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("tilesetsMetaData [%s]\n", tilesetsMetaData.c_str()); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); return; - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - techListRemote.clear(); - Tokenize(techsMetaData,techListRemote,"\n"); - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); + } + + if (curlResult != CURLE_OK) { + string curlError = curl_easy_strerror(curlResult); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("ModErrorGettingServerData").c_str(), + curlError.c_str()); + console.addLine(string("#2 ") + szBuf, true); + } + + mapsMetaData = SystemFlags::getHTTP(baseURL + "showMapsForGlest.php" + + phpVersionParam + gameVersion, + handle, -1, &curlResult); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("mapsMetaData [%s]\n", mapsMetaData.c_str()); + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); return; + } + + if (curlResult != CURLE_OK) { + string curlError = curl_easy_strerror(curlResult); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("ModErrorGettingServerData").c_str(), + curlError.c_str()); + console.addLine(string("#3 ") + szBuf, true); + } + + scenariosMetaData = SystemFlags::getHTTP( + baseURL + "showScenariosForGlest.php" + phpVersionParam + gameVersion, + handle, -1, &curlResult); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("scenariosMetaData [%s]\n", scenariosMetaData.c_str()); + + if (curlResult != CURLE_OK) { + string curlError = curl_easy_strerror(curlResult); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("ModErrorGettingServerData").c_str(), + curlError.c_str()); + console.addLine(string("#4 ") + szBuf, true); + } } - - getTechsLocalList(); - for(unsigned int i=0; i < techListRemote.size(); i++) { - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; - } - - string result=refreshTechModInfo(techListRemote[i]); - if(result != "") { - ModInfo modinfo; - modinfo=techCacheList[result]; - - GraphicButton *button=new GraphicButton(); - button->init(techInfoXPos, keyButtonsYBase, keyButtonsWidthTech,keyButtonsHeight); - button->setText(modinfo.name); - button->setUseCustomTexture(true); - button->setCustomTexture(CoreData::getInstance().getCustomTexture()); - - keyTechButtons.push_back(button); - GraphicLabel *label=new GraphicLabel(); - label->init(techInfoXPos + keyButtonsWidthTech+10,keyButtonsYBase,labelWidth,20); - label->setText(modinfo.count); - labelsTech.push_back(label); - } - } - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; + SystemFlags::cleanupHTTP(&handle); + } else { + console.addLine(lang.getString("MasterServerMissing"), true); + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + tilesetListRemote.clear(); + Tokenize(tilesetsMetaData, tilesetListRemote, "\n"); + + modMenuState = mmst_CalculatingCRC; + + getTilesetsLocalList(); + for (unsigned int i = 0; i < tilesetListRemote.size(); i++) { + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; } - for(unsigned int i=0; i < techTreeFilesUserData.size(); i++) { - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; - } - - string techName = techTreeFilesUserData[i]; - bool alreadyHasTech = (techCacheList.find(techName) != techCacheList.end()); - if(alreadyHasTech == false) { - vector techPaths = config.getPathListForType(ptTechs); - string &techPath = techPaths[1]; - endPathWithSlash(techPath); - vector factions; - findAll(techPath + techName + "/factions/*.", factions, false, false); - - GraphicButton *button=new GraphicButton(); - button->init(techInfoXPos, keyButtonsYBase, keyButtonsWidthTech,keyButtonsHeight); - button->setText(techName); - button->setUseCustomTexture(true); - button->setCustomTexture(CoreData::getInstance().getCustomTexture()); - keyTechButtons.push_back(button); - - int techFactionCount = (int)factions.size(); - GraphicLabel *label=new GraphicLabel(); - label->init(techInfoXPos + keyButtonsWidthTech+10,keyButtonsYBase,labelWidth,20); - label->setText(intToStr(techFactionCount)); - labelsTech.push_back(label); - } - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; + string result = refreshTilesetModInfo(tilesetListRemote[i]); + if (result != "") { + ModInfo modinfo; + modinfo = tilesetCacheList[result]; + GraphicButton *button = new GraphicButton(); + button->init(tilesetInfoXPos, keyButtonsYBase, keyButtonsWidthTil, + keyButtonsHeight); + button->setText(modinfo.name); + button->setUseCustomTexture(true); + button->setCustomTexture(CoreData::getInstance().getCustomTexture()); + keyTilesetButtons.push_back(button); + } + } + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; + } + + for (unsigned int i = 0; i < tilesetFilesUserData.size(); i++) { + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - mapListRemote.clear(); - Tokenize(mapsMetaData,mapListRemote,"\n"); - - getMapsLocalList(); - for(unsigned int i=0; i < mapListRemote.size(); i++) { - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; - } - - string result=refreshMapModInfo(mapListRemote[i]); - if(result != "") { - ModInfo modinfo; - modinfo=mapCacheList[result]; - - GraphicButton *button=new GraphicButton(); - button->init(mapInfoXPos, keyButtonsYBase, keyButtonsWidthMap,keyButtonsHeight); - button->setText(modinfo.name); - button->setUseCustomTexture(true); - button->setCustomTexture(CoreData::getInstance().getCustomTexture()); - keyMapButtons.push_back(button); - - GraphicLabel *label=new GraphicLabel(); - label->init(mapInfoXPos + keyButtonsWidthMap + 10,keyButtonsYBase,labelWidth,20); - label->setText(modinfo.count); - labelsMap.push_back(label); - } - } - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; + string tilesetName = tilesetFilesUserData[i]; + bool alreadyHasTileset = + (tilesetCacheList.find(tilesetName) != tilesetCacheList.end()); + if (alreadyHasTileset == false) { + GraphicButton *button = new GraphicButton(); + button->init(tilesetInfoXPos, keyButtonsYBase, keyButtonsWidthTil, + keyButtonsHeight); + button->setText(tilesetName); + button->setUseCustomTexture(true); + button->setCustomTexture(CoreData::getInstance().getCustomTexture()); + keyTilesetButtons.push_back(button); + } + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + techListRemote.clear(); + Tokenize(techsMetaData, techListRemote, "\n"); + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; + } + + getTechsLocalList(); + for (unsigned int i = 0; i < techListRemote.size(); i++) { + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; } - for(unsigned int i=0; i < mapFilesUserData.size(); i++) { - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; - } - - string mapName = mapFilesUserData[i]; - bool alreadyHasMap = (mapCacheList.find(mapName) != mapCacheList.end()); - if(alreadyHasMap == false) { - vector mapPaths = config.getPathListForType(ptMaps); - string &mapPath = mapPaths[1]; - endPathWithSlash(mapPath); - mapPath += mapName; - MapInfo mapInfo = loadMapInfo(mapPath); - - GraphicButton *button=new GraphicButton(); - button->init(mapInfoXPos, keyButtonsYBase, keyButtonsWidthMap,keyButtonsHeight); - button->setText(mapName); - button->setUseCustomTexture(true); - button->setCustomTexture(CoreData::getInstance().getCustomTexture()); - keyMapButtons.push_back(button); - - int mapPlayerCount = mapInfo.players; - GraphicLabel *label=new GraphicLabel(); - label->init(mapInfoXPos + keyButtonsWidthMap + 10,keyButtonsYBase,labelWidth,20); - label->setText(intToStr(mapPlayerCount)); - labelsMap.push_back(label); - } - } - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; + string result = refreshTechModInfo(techListRemote[i]); + if (result != "") { + ModInfo modinfo; + modinfo = techCacheList[result]; + + GraphicButton *button = new GraphicButton(); + button->init(techInfoXPos, keyButtonsYBase, keyButtonsWidthTech, + keyButtonsHeight); + button->setText(modinfo.name); + button->setUseCustomTexture(true); + button->setCustomTexture(CoreData::getInstance().getCustomTexture()); + + keyTechButtons.push_back(button); + GraphicLabel *label = new GraphicLabel(); + label->init(techInfoXPos + keyButtonsWidthTech + 10, keyButtonsYBase, + labelWidth, 20); + label->setText(modinfo.count); + labelsTech.push_back(label); + } + } + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; + } + + for (unsigned int i = 0; i < techTreeFilesUserData.size(); i++) { + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + string techName = techTreeFilesUserData[i]; + bool alreadyHasTech = (techCacheList.find(techName) != techCacheList.end()); + if (alreadyHasTech == false) { + vector techPaths = config.getPathListForType(ptTechs); + string &techPath = techPaths[1]; + endPathWithSlash(techPath); + vector factions; + findAll(techPath + techName + "/factions/*.", factions, false, false); + + GraphicButton *button = new GraphicButton(); + button->init(techInfoXPos, keyButtonsYBase, keyButtonsWidthTech, + keyButtonsHeight); + button->setText(techName); + button->setUseCustomTexture(true); + button->setCustomTexture(CoreData::getInstance().getCustomTexture()); + keyTechButtons.push_back(button); + + int techFactionCount = (int)factions.size(); + GraphicLabel *label = new GraphicLabel(); + label->init(techInfoXPos + keyButtonsWidthTech + 10, keyButtonsYBase, + labelWidth, 20); + label->setText(intToStr(techFactionCount)); + labelsTech.push_back(label); + } + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); - scenarioListRemote.clear(); - Tokenize(scenariosMetaData,scenarioListRemote,"\n"); + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; + } - getScenariosLocalList(); - for(unsigned int i=0; i < scenarioListRemote.size(); i++) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; - } + mapListRemote.clear(); + Tokenize(mapsMetaData, mapListRemote, "\n"); - string result=refreshScenarioModInfo(scenarioListRemote[i]); - if(result != "") { - ModInfo modinfo; - modinfo=scenarioCacheList[result]; - GraphicButton *button=new GraphicButton(); - button->init(scenarioInfoXPos, keyButtonsYBase, keyButtonsWidthScen,keyButtonsHeight); - button->setText(modinfo.name); - button->setUseCustomTexture(true); - button->setCustomTexture(CoreData::getInstance().getCustomTexture()); - keyScenarioButtons.push_back(button); - } - } + getMapsLocalList(); + for (unsigned int i = 0; i < mapListRemote.size(); i++) { - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; } - for(unsigned int i=0; i < scenarioFilesUserData.size(); i++) { - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; - } - - string scenarioName = scenarioFilesUserData[i]; - bool alreadyHasScenario = (scenarioCacheList.find(scenarioName) != scenarioCacheList.end()); - if(alreadyHasScenario == false) { - vector scenarioPaths = config.getPathListForType(ptScenarios); - string &scenarioPath = scenarioPaths[1]; - endPathWithSlash(scenarioPath); - scenarioPath += scenarioName; - - GraphicButton *button=new GraphicButton(); - button->init(scenarioInfoXPos, keyButtonsYBase, keyButtonsWidthScen,keyButtonsHeight); - button->setText(scenarioName); - button->setUseCustomTexture(true); - button->setCustomTexture(CoreData::getInstance().getCustomTexture()); - keyScenarioButtons.push_back(button); - } - } - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; + string result = refreshMapModInfo(mapListRemote[i]); + if (result != "") { + ModInfo modinfo; + modinfo = mapCacheList[result]; + + GraphicButton *button = new GraphicButton(); + button->init(mapInfoXPos, keyButtonsYBase, keyButtonsWidthMap, + keyButtonsHeight); + button->setText(modinfo.name); + button->setUseCustomTexture(true); + button->setCustomTexture(CoreData::getInstance().getCustomTexture()); + keyMapButtons.push_back(button); + + GraphicLabel *label = new GraphicLabel(); + label->init(mapInfoXPos + keyButtonsWidthMap + 10, keyButtonsYBase, + labelWidth, 20); + label->setText(modinfo.count); + labelsMap.push_back(label); + } + } + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; + } + + for (unsigned int i = 0; i < mapFilesUserData.size(); i++) { + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - keyTilesetScrollBar.init(tilesetInfoXPos + keyButtonsWidthTil,scrollListsYPos-listBoxLength+keyButtonsLineHeight,false,200,20); - keyTilesetScrollBar.setLength(listBoxLength); - keyTilesetScrollBar.setElementCount((int)keyTilesetButtons.size()); - keyTilesetScrollBar.setVisibleSize(keyButtonsToRender); - keyTilesetScrollBar.setVisibleStart(0); - - keyTechScrollBar.init(techInfoXPos + keyButtonsWidthTech + labelWidth + 20,scrollListsYPos-listBoxLength+keyButtonsLineHeight,false,200,20); - keyTechScrollBar.setLength(listBoxLength); - keyTechScrollBar.setElementCount((int)keyTechButtons.size()); - keyTechScrollBar.setVisibleSize(keyButtonsToRender); - keyTechScrollBar.setVisibleStart(0); - - keyMapScrollBar.init(mapInfoXPos + keyButtonsWidthMap + labelWidth + 20,scrollListsYPos-listBoxLength+keyButtonsLineHeight,false,200,20); - keyMapScrollBar.setLength(listBoxLength); - keyMapScrollBar.setElementCount((int)keyMapButtons.size()); - keyMapScrollBar.setVisibleSize(keyButtonsToRender); - keyMapScrollBar.setVisibleStart(0); - - keyScenarioScrollBar.init(scenarioInfoXPos + keyButtonsWidthScen,scrollListsYPos-listBoxLength+keyButtonsLineHeight,false,200,20); - keyScenarioScrollBar.setLength(listBoxLength); - keyScenarioScrollBar.setElementCount((int)keyScenarioButtons.size()); - keyScenarioScrollBar.setVisibleSize(keyButtonsToRender); - keyScenarioScrollBar.setVisibleStart(0); - - modMenuState=mmst_None; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); + string mapName = mapFilesUserData[i]; + bool alreadyHasMap = (mapCacheList.find(mapName) != mapCacheList.end()); + if (alreadyHasMap == false) { + vector mapPaths = config.getPathListForType(ptMaps); + string &mapPath = mapPaths[1]; + endPathWithSlash(mapPath); + mapPath += mapName; + MapInfo mapInfo = loadMapInfo(mapPath); + + GraphicButton *button = new GraphicButton(); + button->init(mapInfoXPos, keyButtonsYBase, keyButtonsWidthMap, + keyButtonsHeight); + button->setText(mapName); + button->setUseCustomTexture(true); + button->setCustomTexture(CoreData::getInstance().getCustomTexture()); + keyMapButtons.push_back(button); + + int mapPlayerCount = mapInfo.players; + GraphicLabel *label = new GraphicLabel(); + label->init(mapInfoXPos + keyButtonsWidthMap + 10, keyButtonsYBase, + labelWidth, 20); + label->setText(intToStr(mapPlayerCount)); + labelsMap.push_back(label); + } + } + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + scenarioListRemote.clear(); + Tokenize(scenariosMetaData, scenarioListRemote, "\n"); + + getScenariosLocalList(); + for (unsigned int i = 0; i < scenarioListRemote.size(); i++) { + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; + } - if(modHttpServerThread != NULL) { - modHttpServerThread->signalQuit(); - } + string result = refreshScenarioModInfo(scenarioListRemote[i]); + if (result != "") { + ModInfo modinfo; + modinfo = scenarioCacheList[result]; + GraphicButton *button = new GraphicButton(); + button->init(scenarioInfoXPos, keyButtonsYBase, keyButtonsWidthScen, + keyButtonsHeight); + button->setText(modinfo.name); + button->setUseCustomTexture(true); + button->setCustomTexture(CoreData::getInstance().getCustomTexture()); + keyScenarioButtons.push_back(button); + } + } + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; + } + + for (unsigned int i = 0; i < scenarioFilesUserData.size(); i++) { + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; + } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); + string scenarioName = scenarioFilesUserData[i]; + bool alreadyHasScenario = + (scenarioCacheList.find(scenarioName) != scenarioCacheList.end()); + if (alreadyHasScenario == false) { + vector scenarioPaths = config.getPathListForType(ptScenarios); + string &scenarioPath = scenarioPaths[1]; + endPathWithSlash(scenarioPath); + scenarioPath += scenarioName; + + GraphicButton *button = new GraphicButton(); + button->init(scenarioInfoXPos, keyButtonsYBase, keyButtonsWidthScen, + keyButtonsHeight); + button->setText(scenarioName); + button->setUseCustomTexture(true); + button->setCustomTexture(CoreData::getInstance().getCustomTexture()); + keyScenarioButtons.push_back(button); + } + } + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + keyTilesetScrollBar.init( + tilesetInfoXPos + keyButtonsWidthTil, + scrollListsYPos - listBoxLength + keyButtonsLineHeight, false, 200, 20); + keyTilesetScrollBar.setLength(listBoxLength); + keyTilesetScrollBar.setElementCount((int)keyTilesetButtons.size()); + keyTilesetScrollBar.setVisibleSize(keyButtonsToRender); + keyTilesetScrollBar.setVisibleStart(0); + + keyTechScrollBar.init(techInfoXPos + keyButtonsWidthTech + labelWidth + 20, + scrollListsYPos - listBoxLength + keyButtonsLineHeight, + false, 200, 20); + keyTechScrollBar.setLength(listBoxLength); + keyTechScrollBar.setElementCount((int)keyTechButtons.size()); + keyTechScrollBar.setVisibleSize(keyButtonsToRender); + keyTechScrollBar.setVisibleStart(0); + + keyMapScrollBar.init(mapInfoXPos + keyButtonsWidthMap + labelWidth + 20, + scrollListsYPos - listBoxLength + keyButtonsLineHeight, + false, 200, 20); + keyMapScrollBar.setLength(listBoxLength); + keyMapScrollBar.setElementCount((int)keyMapButtons.size()); + keyMapScrollBar.setVisibleSize(keyButtonsToRender); + keyMapScrollBar.setVisibleStart(0); + + keyScenarioScrollBar.init( + scenarioInfoXPos + keyButtonsWidthScen, + scrollListsYPos - listBoxLength + keyButtonsLineHeight, false, 200, 20); + keyScenarioScrollBar.setLength(listBoxLength); + keyScenarioScrollBar.setElementCount((int)keyScenarioButtons.size()); + keyScenarioScrollBar.setVisibleSize(keyButtonsToRender); + keyScenarioScrollBar.setVisibleStart(0); + + modMenuState = mmst_None; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + if (modHttpServerThread != NULL) { + modHttpServerThread->signalQuit(); + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); } MapInfo MenuStateMods::loadMapInfo(string file) { - try{ - Lang &lang= Lang::getInstance(); - // Not painting properly so this is on hold - MapPreview::loadMapInfo(file, &mapInfo, lang.getString("MaxPlayers"),lang.getString("Size"),true); - } - catch(exception &e) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s] loading map [%s]\n",__FILE__,__FUNCTION__,__LINE__,e.what(),file.c_str()); - throw megaglest_runtime_error("Error loading map file: [" + file + "] msg: " + e.what()); - } - - return mapInfo; + try { + Lang &lang = Lang::getInstance(); + // Not painting properly so this is on hold + MapPreview::loadMapInfo(file, &mapInfo, lang.getString("MaxPlayers"), + lang.getString("Size"), true); + } catch (exception &e) { + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s] loading map [%s]\n", __FILE__, + __FUNCTION__, __LINE__, e.what(), file.c_str()); + throw megaglest_runtime_error("Error loading map file: [" + file + + "] msg: " + e.what()); + } + + return mapInfo; } void MenuStateMods::getTechsLocalList() { - Config &config = Config::getInstance(); - vector results; - findDirs(config.getPathListForType(ptTechs), results); - techTreeFiles = results; - - techTreeFilesUserData.clear(); - if(config.getPathListForType(ptTechs).size() > 1) { - string path = config.getPathListForType(ptTechs)[1]; - endPathWithSlash(path); - findDirs(path, techTreeFilesUserData, false, false); - } + Config &config = Config::getInstance(); + vector results; + findDirs(config.getPathListForType(ptTechs), results); + techTreeFiles = results; + + techTreeFilesUserData.clear(); + if (config.getPathListForType(ptTechs).size() > 1) { + string path = config.getPathListForType(ptTechs)[1]; + endPathWithSlash(path); + findDirs(path, techTreeFilesUserData, false, false); + } } string MenuStateMods::refreshTechModInfo(string techInfo) { - std::vector techInfoList; - Tokenize(techInfo,techInfoList,"|"); - if(techInfoList.size() >= 6) { - Config &config = Config::getInstance(); - ModInfo modinfo; - modinfo.name = techInfoList[0]; - modinfo.count = techInfoList[1]; - modinfo.crc = techInfoList[2]; - modinfo.description = techInfoList[3]; - modinfo.url = techInfoList[4]; - modinfo.imageUrl = techInfoList[5]; - modinfo.type = mt_Techtree; - - string itemPath = config.getPathListForType(ptTechs,"")[1] + "/" + modinfo.name + string("/*"); - if(itemPath.empty() == false) { - bool forceRefresh = (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); - uint32 crc = getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", NULL,forceRefresh); - if(crc == 0) { - itemPath = config.getPathListForType(ptTechs,"")[0] + "/" + modinfo.name + string("/*"); - if(itemPath.empty() == false) { - forceRefresh = (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); - crc = getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", NULL,forceRefresh); - } - } - modinfo.localCRC=uIntToStr(crc); - //printf("itemPath='%s' remote crc:'%s' local crc:'%s' crc='%d' \n",itemPath.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str(),crc); - } - else { - modinfo.localCRC=""; - } - techCacheList[modinfo.name] = modinfo; - return modinfo.name; - } - return ""; + std::vector techInfoList; + Tokenize(techInfo, techInfoList, "|"); + if (techInfoList.size() >= 6) { + Config &config = Config::getInstance(); + ModInfo modinfo; + modinfo.name = techInfoList[0]; + modinfo.count = techInfoList[1]; + modinfo.crc = techInfoList[2]; + modinfo.description = techInfoList[3]; + modinfo.url = techInfoList[4]; + modinfo.imageUrl = techInfoList[5]; + modinfo.type = mt_Techtree; + + string itemPath = config.getPathListForType(ptTechs, "")[1] + "/" + + modinfo.name + string("/*"); + if (itemPath.empty() == false) { + bool forceRefresh = + (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); + uint32 crc = getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", + NULL, forceRefresh); + if (crc == 0) { + itemPath = config.getPathListForType(ptTechs, "")[0] + "/" + + modinfo.name + string("/*"); + if (itemPath.empty() == false) { + forceRefresh = + (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); + crc = getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", NULL, + forceRefresh); + } + } + modinfo.localCRC = uIntToStr(crc); + // printf("itemPath='%s' remote crc:'%s' local crc:'%s' crc='%d' + // \n",itemPath.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str(),crc); + } else { + modinfo.localCRC = ""; + } + techCacheList[modinfo.name] = modinfo; + return modinfo.name; + } + return ""; } void MenuStateMods::refreshTechs() { - getTechsLocalList(); - for(int i=0; i < (int)techListRemote.size(); i++) { - refreshTechModInfo(techListRemote[i]); - } + getTechsLocalList(); + for (int i = 0; i < (int)techListRemote.size(); i++) { + refreshTechModInfo(techListRemote[i]); + } } void MenuStateMods::getTilesetsLocalList() { - Config &config = Config::getInstance(); - vector results; - findDirs(config.getPathListForType(ptTilesets), results); - tilesetFiles = results; - - tilesetFilesUserData.clear(); - if(config.getPathListForType(ptTilesets).size() > 1) { - string path = config.getPathListForType(ptTilesets)[1]; - endPathWithSlash(path); - findDirs(path, tilesetFilesUserData, false, false); - } + Config &config = Config::getInstance(); + vector results; + findDirs(config.getPathListForType(ptTilesets), results); + tilesetFiles = results; + + tilesetFilesUserData.clear(); + if (config.getPathListForType(ptTilesets).size() > 1) { + string path = config.getPathListForType(ptTilesets)[1]; + endPathWithSlash(path); + findDirs(path, tilesetFilesUserData, false, false); + } } string MenuStateMods::refreshTilesetModInfo(string tilesetInfo) { - std::vector tilesetInfoList; - Tokenize(tilesetInfo,tilesetInfoList,"|"); - if(tilesetInfoList.size() >= 5) { - Config &config = Config::getInstance(); - ModInfo modinfo; - modinfo.name = tilesetInfoList[0]; - modinfo.crc = tilesetInfoList[1]; - modinfo.description = tilesetInfoList[2]; - modinfo.url = tilesetInfoList[3]; - modinfo.imageUrl = tilesetInfoList[4]; - modinfo.type = mt_Tileset; - - string itemPath = config.getPathListForType(ptTilesets,"")[1] + "/" + modinfo.name + string("/*"); - if(itemPath.empty() == false) { - bool forceRefresh = (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); - uint32 crc = getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", NULL,forceRefresh); - if(crc == 0) { - itemPath = config.getPathListForType(ptTilesets,"")[0] + "/" + modinfo.name + string("/*"); - if(itemPath.empty() == false) { - forceRefresh = (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); - crc=getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", NULL,forceRefresh); - } - } - modinfo.localCRC=uIntToStr(crc); - //printf("itemPath='%s' remote crc:'%s' local crc:'%s' crc='%d' \n",itemPath.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str(),crc); - - //printf("#1 refreshTilesetModInfo name [%s] modInfo.crc [%s] modInfo.localCRC [%s]\n",modinfo.name.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str()); - } - else { - modinfo.localCRC=""; - - //printf("#2 refreshTilesetModInfo name [%s] modInfo.crc [%s] modInfo.localCRC [%s]\n",modinfo.name.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str()); - } - - tilesetCacheList[modinfo.name] = modinfo; - return modinfo.name; - } - return ""; + std::vector tilesetInfoList; + Tokenize(tilesetInfo, tilesetInfoList, "|"); + if (tilesetInfoList.size() >= 5) { + Config &config = Config::getInstance(); + ModInfo modinfo; + modinfo.name = tilesetInfoList[0]; + modinfo.crc = tilesetInfoList[1]; + modinfo.description = tilesetInfoList[2]; + modinfo.url = tilesetInfoList[3]; + modinfo.imageUrl = tilesetInfoList[4]; + modinfo.type = mt_Tileset; + + string itemPath = config.getPathListForType(ptTilesets, "")[1] + "/" + + modinfo.name + string("/*"); + if (itemPath.empty() == false) { + bool forceRefresh = + (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); + uint32 crc = getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", + NULL, forceRefresh); + if (crc == 0) { + itemPath = config.getPathListForType(ptTilesets, "")[0] + "/" + + modinfo.name + string("/*"); + if (itemPath.empty() == false) { + forceRefresh = + (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); + crc = getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", NULL, + forceRefresh); + } + } + modinfo.localCRC = uIntToStr(crc); + // printf("itemPath='%s' remote crc:'%s' local crc:'%s' crc='%d' + // \n",itemPath.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str(),crc); + + // printf("#1 refreshTilesetModInfo name [%s] modInfo.crc [%s] + // modInfo.localCRC + // [%s]\n",modinfo.name.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str()); + } else { + modinfo.localCRC = ""; + + // printf("#2 refreshTilesetModInfo name [%s] modInfo.crc [%s] + // modInfo.localCRC + // [%s]\n",modinfo.name.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str()); + } + + tilesetCacheList[modinfo.name] = modinfo; + return modinfo.name; + } + return ""; } void MenuStateMods::refreshTilesets() { - getTilesetsLocalList(); - for(int i=0; i < (int)tilesetListRemote.size(); i++) { - refreshTilesetModInfo(tilesetListRemote[i]); - } + getTilesetsLocalList(); + for (int i = 0; i < (int)tilesetListRemote.size(); i++) { + refreshTilesetModInfo(tilesetListRemote[i]); + } } void MenuStateMods::getMapsLocalList() { -/* - Config &config = Config::getInstance(); - vector results; - set allMaps; - findAll(config.getPathListForType(ptMaps), "*.gbm", results, false, false); - copy(results.begin(), results.end(), std::inserter(allMaps, allMaps.begin())); - results.clear(); - findAll(config.getPathListForType(ptMaps), "*.mgm", results, false, false); - copy(results.begin(), results.end(), std::inserter(allMaps, allMaps.begin())); - results.clear(); - - copy(allMaps.begin(), allMaps.end(), std::back_inserter(results)); - mapFiles = results; - - mapFilesUserData.clear(); - if(config.getPathListForType(ptMaps).size() > 1) { - string path = config.getPathListForType(ptMaps)[1]; - endPathWithSlash(path); - - vector results2; - set allMaps2; - findAll(path + "*.gbm", results2, false, false); - copy(results2.begin(), results2.end(), std::inserter(allMaps2, allMaps2.begin())); - - results2.clear(); - findAll(path + "*.mgm", results2, false, false); - copy(results2.begin(), results2.end(), std::inserter(allMaps2, allMaps2.begin())); - - results2.clear(); - copy(allMaps2.begin(), allMaps2.end(), std::back_inserter(results2)); - mapFilesUserData = results2; - //printf("\n\nMap path [%s] mapFilesUserData.size() = %d\n\n\n",path.c_str(),mapFilesUserData.size()); - } -*/ - - Config &config = Config::getInstance(); - string scenarioDir = ""; - vector pathList = config.getPathListForType(ptMaps,scenarioDir); - vector invalidMapList; - vector allMaps = MapPreview::findAllValidMaps(pathList,scenarioDir,false,false,&invalidMapList); - if (allMaps.empty()) { - throw megaglest_runtime_error("No maps were found!"); - } - vector results; - copy(allMaps.begin(), allMaps.end(), std::back_inserter(results)); - mapFiles = results; - - mapFilesUserData = MapPreview::findAllValidMaps(pathList,scenarioDir,true,false,&invalidMapList); + /* + Config &config = Config::getInstance(); + vector results; + set allMaps; + findAll(config.getPathListForType(ptMaps), "*.gbm", results, false, + false); copy(results.begin(), results.end(), std::inserter(allMaps, + allMaps.begin())); results.clear(); + findAll(config.getPathListForType(ptMaps), "*.mgm", results, false, + false); copy(results.begin(), results.end(), std::inserter(allMaps, + allMaps.begin())); results.clear(); + + copy(allMaps.begin(), allMaps.end(), std::back_inserter(results)); + mapFiles = results; + + mapFilesUserData.clear(); + if(config.getPathListForType(ptMaps).size() > 1) { + string path = config.getPathListForType(ptMaps)[1]; + endPathWithSlash(path); + + vector results2; + set allMaps2; + findAll(path + "*.gbm", results2, false, false); + copy(results2.begin(), results2.end(), std::inserter(allMaps2, + allMaps2.begin())); + + results2.clear(); + findAll(path + "*.mgm", results2, false, false); + copy(results2.begin(), results2.end(), std::inserter(allMaps2, + allMaps2.begin())); + + results2.clear(); + copy(allMaps2.begin(), allMaps2.end(), + std::back_inserter(results2)); mapFilesUserData = results2; + //printf("\n\nMap path [%s] mapFilesUserData.size() = + %d\n\n\n",path.c_str(),mapFilesUserData.size()); + } + */ + + Config &config = Config::getInstance(); + string scenarioDir = ""; + vector pathList = config.getPathListForType(ptMaps, scenarioDir); + vector invalidMapList; + vector allMaps = MapPreview::findAllValidMaps( + pathList, scenarioDir, false, false, &invalidMapList); + if (allMaps.empty()) { + throw megaglest_runtime_error("No maps were found!"); + } + vector results; + copy(allMaps.begin(), allMaps.end(), std::back_inserter(results)); + mapFiles = results; + + mapFilesUserData = MapPreview::findAllValidMaps(pathList, scenarioDir, true, + false, &invalidMapList); } string MenuStateMods::refreshMapModInfo(string mapInfo) { - std::vector mapInfoList; - Tokenize(mapInfo,mapInfoList,"|"); - if(mapInfoList.size() >= 6) { - //Config &config = Config::getInstance(); - ModInfo modinfo; - modinfo.name = mapInfoList[0]; - modinfo.count = mapInfoList[1]; - modinfo.crc = mapInfoList[2]; - modinfo.description = mapInfoList[3]; - modinfo.url = mapInfoList[4]; - modinfo.imageUrl = mapInfoList[5]; - modinfo.type = mt_Map; - modinfo.localCRC=getMapCRC(modinfo.name); - mapCacheList[modinfo.name] = modinfo; - return modinfo.name; - } - return ""; + std::vector mapInfoList; + Tokenize(mapInfo, mapInfoList, "|"); + if (mapInfoList.size() >= 6) { + // Config &config = Config::getInstance(); + ModInfo modinfo; + modinfo.name = mapInfoList[0]; + modinfo.count = mapInfoList[1]; + modinfo.crc = mapInfoList[2]; + modinfo.description = mapInfoList[3]; + modinfo.url = mapInfoList[4]; + modinfo.imageUrl = mapInfoList[5]; + modinfo.type = mt_Map; + modinfo.localCRC = getMapCRC(modinfo.name); + mapCacheList[modinfo.name] = modinfo; + return modinfo.name; + } + return ""; } string MenuStateMods::getMapCRC(string mapName) { - Config &config = Config::getInstance(); - vector mappaths=config.getPathListForType(ptMaps,""); - string result=""; - if(mappaths.empty() == false) { - Checksum checksum; - string itemPath = mappaths[1] + "/" + mapName; - if (fileExists(itemPath)){ - checksum.addFile(itemPath); - uint32 crc=checksum.getSum(); - result=uIntToStr(crc); - //printf("itemPath='%s' modinfo.name='%s' remote crc:'%s' local crc:'%s' crc='%d' \n",itemPath.c_str(),modinfo.name.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str(),crc); - } - else { - itemPath = mappaths[0] + "/" + mapName; - if (fileExists(itemPath)){ - checksum.addFile(itemPath); - uint32 crc=checksum.getSum(); - result=uIntToStr(crc); - //printf("itemPath='%s' modinfo.name='%s' remote crc:'%s' local crc:'%s' crc='%d' \n",itemPath.c_str(),modinfo.name.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str(),crc); - } - else { - result=""; - } - } - } - else { - result=""; - } - return result; + Config &config = Config::getInstance(); + vector mappaths = config.getPathListForType(ptMaps, ""); + string result = ""; + if (mappaths.empty() == false) { + Checksum checksum; + string itemPath = mappaths[1] + "/" + mapName; + if (fileExists(itemPath)) { + checksum.addFile(itemPath); + uint32 crc = checksum.getSum(); + result = uIntToStr(crc); + // printf("itemPath='%s' modinfo.name='%s' remote crc:'%s' local crc:'%s' + // crc='%d' + // \n",itemPath.c_str(),modinfo.name.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str(),crc); + } else { + itemPath = mappaths[0] + "/" + mapName; + if (fileExists(itemPath)) { + checksum.addFile(itemPath); + uint32 crc = checksum.getSum(); + result = uIntToStr(crc); + // printf("itemPath='%s' modinfo.name='%s' remote crc:'%s' local + // crc:'%s' crc='%d' + // \n",itemPath.c_str(),modinfo.name.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str(),crc); + } else { + result = ""; + } + } + } else { + result = ""; + } + return result; } void MenuStateMods::refreshMaps() { - getMapsLocalList(); - for(int i=0; i < (int)mapListRemote.size(); i++) { - refreshMapModInfo(mapListRemote[i]); - } + getMapsLocalList(); + for (int i = 0; i < (int)mapListRemote.size(); i++) { + refreshMapModInfo(mapListRemote[i]); + } } void MenuStateMods::getScenariosLocalList() { - Config &config = Config::getInstance(); - vector results; - findDirs(config.getPathListForType(ptScenarios), results); - scenarioFiles = results; - - scenarioFilesUserData.clear(); - if(config.getPathListForType(ptScenarios).size() > 1) { - string path = config.getPathListForType(ptScenarios)[1]; - endPathWithSlash(path); - findDirs(path, scenarioFilesUserData, false, false); - } + Config &config = Config::getInstance(); + vector results; + findDirs(config.getPathListForType(ptScenarios), results); + scenarioFiles = results; + + scenarioFilesUserData.clear(); + if (config.getPathListForType(ptScenarios).size() > 1) { + string path = config.getPathListForType(ptScenarios)[1]; + endPathWithSlash(path); + findDirs(path, scenarioFilesUserData, false, false); + } } string MenuStateMods::refreshScenarioModInfo(string scenarioInfo) { - std::vector scenarioInfoList; - Tokenize(scenarioInfo,scenarioInfoList,"|"); - if(scenarioInfoList.size() >= 5) { - Config &config = Config::getInstance(); - ModInfo modinfo; - modinfo.name = scenarioInfoList[0]; - modinfo.crc = scenarioInfoList[1]; - modinfo.description = scenarioInfoList[2]; - modinfo.url = scenarioInfoList[3]; - modinfo.imageUrl = scenarioInfoList[4]; - modinfo.type = mt_Scenario; - - string itemPath = config.getPathListForType(ptScenarios,"")[1] + "/" + modinfo.name + string("/*"); - if(itemPath.empty() == false) { - bool forceRefresh = (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); - uint32 crc = getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", NULL,forceRefresh); - if(crc == 0) { - itemPath = config.getPathListForType(ptScenarios,"")[0] + "/" + modinfo.name + string("/*"); - if(itemPath.empty() == false) { - forceRefresh = (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); - crc = getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", NULL,forceRefresh); - } - } - modinfo.localCRC=uIntToStr(crc); - //printf(" itemPath='%s' remote crc:'%s' local crc:'%s' crc='%d' \n",itemPath.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str(),crc); - } - else { - modinfo.localCRC=""; - } - scenarioCacheList[modinfo.name] = modinfo; - return modinfo.name; - } - return ""; + std::vector scenarioInfoList; + Tokenize(scenarioInfo, scenarioInfoList, "|"); + if (scenarioInfoList.size() >= 5) { + Config &config = Config::getInstance(); + ModInfo modinfo; + modinfo.name = scenarioInfoList[0]; + modinfo.crc = scenarioInfoList[1]; + modinfo.description = scenarioInfoList[2]; + modinfo.url = scenarioInfoList[3]; + modinfo.imageUrl = scenarioInfoList[4]; + modinfo.type = mt_Scenario; + + string itemPath = config.getPathListForType(ptScenarios, "")[1] + "/" + + modinfo.name + string("/*"); + if (itemPath.empty() == false) { + bool forceRefresh = + (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); + uint32 crc = getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", + NULL, forceRefresh); + if (crc == 0) { + itemPath = config.getPathListForType(ptScenarios, "")[0] + "/" + + modinfo.name + string("/*"); + if (itemPath.empty() == false) { + forceRefresh = + (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); + crc = getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", NULL, + forceRefresh); + } + } + modinfo.localCRC = uIntToStr(crc); + // printf(" itemPath='%s' remote crc:'%s' local crc:'%s' crc='%d' + // \n",itemPath.c_str(),modinfo.crc.c_str(),modinfo.localCRC.c_str(),crc); + } else { + modinfo.localCRC = ""; + } + scenarioCacheList[modinfo.name] = modinfo; + return modinfo.name; + } + return ""; } void MenuStateMods::refreshScenarios() { - getScenariosLocalList(); - for(int i=0; i < (int)scenarioListRemote.size(); i++) { - refreshScenarioModInfo(scenarioListRemote[i]); - } + getScenariosLocalList(); + for (int i = 0; i < (int)scenarioListRemote.size(); i++) { + refreshScenarioModInfo(scenarioListRemote[i]); + } } - void MenuStateMods::cleanUp() { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(modHttpServerThread != NULL) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - modHttpServerThread->signalQuit(); - //modHttpServerThread->setThreadOwnerValid(false); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - if( modHttpServerThread->canShutdown(true) == true && - modHttpServerThread->shutdownAndWait() == true) { - delete modHttpServerThread; - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - modHttpServerThread = NULL; - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(ftpClientThread != NULL) { - ftpClientThread->setCallBackObject(NULL); - ftpClientThread->signalQuit(); - sleep(0); - if(ftpClientThread->canShutdown(true) == true && - ftpClientThread->shutdownAndWait() == true) { - delete ftpClientThread; - } - else { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] Error cannot shutdown ftpClientThread\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s",szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - - //publishToMasterserverThread->cleanup(); - } - ftpClientThread = NULL; - -// ftpClientThread->signalQuit(); -// ftpClientThread->setCallBackObject(NULL); -// if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); -// if( ftpClientThread->shutdownAndWait() == true) { -// if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); -// delete ftpClientThread; -// } -// ftpClientThread = NULL; -// if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - clearUserButtons(); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - cleanupPreviewTexture(); - cleanupMapPreviewTexture(); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + __FILE__, __FUNCTION__, __LINE__); + if (modHttpServerThread != NULL) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, + __LINE__); + modHttpServerThread->signalQuit(); + // modHttpServerThread->setThreadOwnerValid(false); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, + __LINE__); + if (modHttpServerThread->canShutdown(true) == true && + modHttpServerThread->shutdownAndWait() == true) { + delete modHttpServerThread; + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + modHttpServerThread = NULL; + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + if (ftpClientThread != NULL) { + ftpClientThread->setCallBackObject(NULL); + ftpClientThread->signalQuit(); + sleep(0); + if (ftpClientThread->canShutdown(true) == true && + ftpClientThread->shutdownAndWait() == true) { + delete ftpClientThread; + } else { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s %d] Error cannot shutdown ftpClientThread\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + // SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("%s", szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + // publishToMasterserverThread->cleanup(); + } + ftpClientThread = NULL; + + // ftpClientThread->signalQuit(); + // ftpClientThread->setCallBackObject(NULL); + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line + //%d]\n",__FILE__,__FUNCTION__,__LINE__); if( + // ftpClientThread->shutdownAndWait() == true) { + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line + //%d]\n",__FILE__,__FUNCTION__,__LINE__); + // delete ftpClientThread; + // } + // ftpClientThread = NULL; + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line + //%d]\n",__FILE__,__FUNCTION__,__LINE__); + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + clearUserButtons(); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + cleanupPreviewTexture(); + cleanupMapPreviewTexture(); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); } MenuStateMods::~MenuStateMods() { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); - cleanUp(); + cleanUp(); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); } void MenuStateMods::clearUserButtons() { - // Techs - while(!keyTechButtons.empty()) { - delete keyTechButtons.back(); - keyTechButtons.pop_back(); - } - keyTechScrollBar.setElementCount(0); - - while(!labelsTech.empty()) { - delete labelsTech.back(); - labelsTech.pop_back(); - } - - // Tilesets - while(!keyTilesetButtons.empty()) { - delete keyTilesetButtons.back(); - keyTilesetButtons.pop_back(); - } - keyTilesetScrollBar.setElementCount(0); - - // Maps - while(!keyMapButtons.empty()) { - delete keyMapButtons.back(); - keyMapButtons.pop_back(); - } - while(!labelsMap.empty()) { - delete labelsMap.back(); - labelsMap.pop_back(); - } - keyMapScrollBar.setElementCount(0); - - // Scenarios - while(!keyScenarioButtons.empty()) { - delete keyScenarioButtons.back(); - keyScenarioButtons.pop_back(); - } - keyScenarioScrollBar.setElementCount(0); + // Techs + while (!keyTechButtons.empty()) { + delete keyTechButtons.back(); + keyTechButtons.pop_back(); + } + keyTechScrollBar.setElementCount(0); + + while (!labelsTech.empty()) { + delete labelsTech.back(); + labelsTech.pop_back(); + } + + // Tilesets + while (!keyTilesetButtons.empty()) { + delete keyTilesetButtons.back(); + keyTilesetButtons.pop_back(); + } + keyTilesetScrollBar.setElementCount(0); + + // Maps + while (!keyMapButtons.empty()) { + delete keyMapButtons.back(); + keyMapButtons.pop_back(); + } + while (!labelsMap.empty()) { + delete labelsMap.back(); + labelsMap.pop_back(); + } + keyMapScrollBar.setElementCount(0); + + // Scenarios + while (!keyScenarioButtons.empty()) { + delete keyScenarioButtons.back(); + keyScenarioButtons.pop_back(); + } + keyScenarioScrollBar.setElementCount(0); } void MenuStateMods::mouseClick(int x, int y, MouseButton mouseButton) { - CoreData &coreData= CoreData::getInstance(); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - Lang &lang= Lang::getInstance(); - - if(buttonReturn.mouseClick(x,y)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - soundRenderer.playFx(coreData.getClickSoundA()); - - if(fileFTPProgressList.empty() == false) { - mainMessageBoxState = ftpmsg_Quit; - mainMessageBox.init(lang.getString("Yes"),lang.getString("No"),450); - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModDownloadInProgressCancelQuestion").c_str(),fileFTPProgressList.size()); - showMessageBox(szBuf, lang.getString("Question"), true); - } - else { - cleanUp(); - mainMenu->setState(new MenuStateRoot(program, mainMenu)); - return; - } - } - else if(mainMessageBox.getEnabled()) { - int button= 0; - if(mainMessageBox.mouseClick(x, y, button)) { - soundRenderer.playFx(coreData.getClickSoundA()); - mainMessageBox.setEnabled(false); - mainMessageBox.init(lang.getString("Yes"),lang.getString("No"),450); - if(button == 0) { - if(mainMessageBoxState == ftpmsg_Quit) { - mainMessageBoxState = ftpmsg_None; - mainMenu->setState(new MenuStateRoot(program, mainMenu)); - return; - } - else if(mainMessageBoxState == ftpmsg_GetMap || - mainMessageBoxState == ftpmsg_ReplaceMap) { - bool getItemAfterRemoval = (mainMessageBoxState == ftpmsg_ReplaceMap); - mainMessageBoxState = ftpmsg_None; - - Config &config = Config::getInstance(); - vector mapPaths = config.getPathListForType(ptMaps); - if(mapPaths.size() > 1) { - string removeMap = mapPaths[1]; - endPathWithSlash(removeMap); - removeMap += selectedMapName; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Removing Map [%s]\n",removeMap.c_str()); - removeFile(removeMap); - - bool remoteHasMap = (mapCacheList.find(selectedMapName) != mapCacheList.end()); - if(remoteHasMap == false) { - for(unsigned int i = 0; i < keyMapButtons.size(); ++i) { - GraphicButton *button = keyMapButtons[i]; - if(button != NULL && button->getText() == selectedMapName) { - delete button; - keyMapButtons.erase(keyMapButtons.begin() + i); - labelsMap.erase(labelsMap.begin() + i); - keyMapScrollBar.setElementCount((int)keyMapButtons.size()); - break; - } - } - } - - if(getItemAfterRemoval == false) { - selectedMapName = ""; - } - refreshMaps(); - Checksum::clearFileCache(); - - if(getItemAfterRemoval == true) { - string mapName = selectedMapName; - string mapURL = mapCacheList[mapName].url; - if(ftpClientThread != NULL) ftpClientThread->addMapToRequests(mapName,mapURL); - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),mutexOwnerId); - if(ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); - fileFTPProgressList[mapName] = pair(0,""); - safeMutexFTPProgress.ReleaseLock(); - buttonInstallMap.setEnabled(false); - } - } - } - else if(mainMessageBoxState == ftpmsg_GetTileset || - mainMessageBoxState == ftpmsg_ReplaceTileset) { - bool getItemAfterRemoval = (mainMessageBoxState == ftpmsg_ReplaceTileset); - mainMessageBoxState = ftpmsg_None; - - Config &config = Config::getInstance(); - vector tilesetPaths = config.getPathListForType(ptTilesets); - if(tilesetPaths.size() > 1) { - string removeTileset = tilesetPaths[1]; - endPathWithSlash(removeTileset); - removeTileset += selectedTilesetName; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Removing Tileset [%s]\n",removeTileset.c_str()); - removeFolder(removeTileset); - - bool remoteHasTileset = (tilesetCacheList.find(selectedTilesetName) != tilesetCacheList.end()); - if(remoteHasTileset == false) { - //printf("\n\n\n$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ remote DOES NOT have removed tileset [%s]\n\n\n",selectedTilesetName.c_str()); - - for(unsigned int i = 0; i < keyTilesetButtons.size(); ++i) { - GraphicButton *button = keyTilesetButtons[i]; - if(button != NULL && button->getText() == selectedTilesetName) { - delete button; - keyTilesetButtons.erase(keyTilesetButtons.begin() + i); - keyTilesetScrollBar.setElementCount((int)keyTilesetButtons.size()); - break; - } - } - } - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),mutexOwnerId); - if(ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); - Checksum::clearFileCache(); - vector paths = Config::getInstance().getPathListForType(ptTilesets); - string pathSearchString = string("/") + selectedTilesetName + string("/*"); - const string filterFileExt = ".xml"; - clearFolderTreeContentsCheckSum(paths, pathSearchString, filterFileExt); - clearFolderTreeContentsCheckSumList(paths, pathSearchString, filterFileExt); - safeMutexFTPProgress.ReleaseLock(); - - if(getItemAfterRemoval == false) { - selectedTilesetName = ""; - } - refreshTilesets(); - } - - if(getItemAfterRemoval == true) { - string tilesetName = selectedTilesetName; - string tilesetURL = tilesetCacheList[tilesetName].url; - if(ftpClientThread != NULL) ftpClientThread->addTilesetToRequests(tilesetName,tilesetURL); - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),mutexOwnerId); - if(ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); - fileFTPProgressList[tilesetName] = pair(0,""); - safeMutexFTPProgress.ReleaseLock(); - buttonInstallTileset.setEnabled(false); - } - } - else if(mainMessageBoxState == ftpmsg_GetTechtree || - mainMessageBoxState == ftpmsg_ReplaceTechtree) { - bool getItemAfterRemoval = (mainMessageBoxState == ftpmsg_ReplaceTechtree); - mainMessageBoxState = ftpmsg_None; - - Config &config = Config::getInstance(); - vector techPaths = config.getPathListForType(ptTechs); - if(techPaths.size() > 1) { - string removeTech = techPaths[1]; - endPathWithSlash(removeTech); - removeTech+= selectedTechName; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Removing Techtree [%s]\n",removeTech.c_str()); - removeFolder(removeTech); - - bool remoteHasTech = (techCacheList.find(selectedTechName) != techCacheList.end()); - if(remoteHasTech == false) { - for(unsigned int i = 0; i < keyTechButtons.size(); ++i) { - GraphicButton *button = keyTechButtons[i]; - if(button != NULL && button->getText() == selectedTechName) { - delete button; - keyTechButtons.erase(keyTechButtons.begin() + i); - labelsTech.erase(labelsTech.begin() + i); - keyTechScrollBar.setElementCount((int)keyTechButtons.size()); - break; - } - } - } - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),mutexOwnerId); - if(ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); - // Clear the CRC file Cache - Checksum::clearFileCache(); - vector paths = Config::getInstance().getPathListForType(ptTechs); - string pathSearchString = string("/") + selectedTechName + string("/*"); - const string filterFileExt = ".xml"; - clearFolderTreeContentsCheckSum(paths, pathSearchString, filterFileExt); - clearFolderTreeContentsCheckSumList(paths, pathSearchString, filterFileExt); - safeMutexFTPProgress.ReleaseLock(); - - if(getItemAfterRemoval == false) { - selectedTechName = ""; - } - refreshTechs(); - } - - if(getItemAfterRemoval == true) { - string techName = selectedTechName; - string techURL = techCacheList[techName].url; - if(ftpClientThread != NULL) ftpClientThread->addTechtreeToRequests(techName,techURL); - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),mutexOwnerId); - if(ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); - fileFTPProgressList[techName] = pair(0,""); - safeMutexFTPProgress.ReleaseLock(); - buttonInstallTech.setEnabled(false); - } - } - else if(mainMessageBoxState == ftpmsg_GetScenario || - mainMessageBoxState == ftpmsg_ReplaceScenario) { - bool getItemAfterRemoval = (mainMessageBoxState == ftpmsg_ReplaceScenario); - mainMessageBoxState = ftpmsg_None; - - Config &config = Config::getInstance(); - vector scenarioPaths = config.getPathListForType(ptScenarios); - if(scenarioPaths.size() > 1) { - string removeScenario = scenarioPaths[1]; - endPathWithSlash(removeScenario); - removeScenario += selectedScenarioName; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Removing Scenario [%s]\n",removeScenario.c_str()); - removeFolder(removeScenario); - - bool remoteHasScenario = (scenarioCacheList.find(selectedScenarioName) != scenarioCacheList.end()); - if(remoteHasScenario == false) { - for(unsigned int i = 0; i < keyScenarioButtons.size(); ++i) { - GraphicButton *button = keyScenarioButtons[i]; - if(button != NULL && button->getText() == selectedScenarioName) { - delete button; - keyScenarioButtons.erase(keyScenarioButtons.begin() + i); - keyScenarioScrollBar.setElementCount((int)keyScenarioButtons.size()); - break; - } - } - } - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),mutexOwnerId); - if(ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); - Checksum::clearFileCache(); - vector paths = Config::getInstance().getPathListForType(ptScenarios); - string pathSearchString = string("/") + selectedScenarioName + string("/*"); - const string filterFileExt = ".xml"; - clearFolderTreeContentsCheckSum(paths, pathSearchString, filterFileExt); - clearFolderTreeContentsCheckSumList(paths, pathSearchString, filterFileExt); - safeMutexFTPProgress.ReleaseLock(); - - if(getItemAfterRemoval == false) { - selectedScenarioName = ""; - } - refreshScenarios(); - } - - if(getItemAfterRemoval == true) { - string scenarioName = selectedScenarioName; - string scenarioURL = scenarioCacheList[scenarioName].url; - if(ftpClientThread != NULL) ftpClientThread->addScenarioToRequests(scenarioName,scenarioURL); - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),mutexOwnerId); - if(ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); - fileFTPProgressList[scenarioName] = pair(0,""); - safeMutexFTPProgress.ReleaseLock(); - buttonInstallScenario.setEnabled(false); - } - } - } - } - } - else if(keyTechScrollBar.mouseClick(x, y)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - soundRenderer.playFx(coreData.getClickSoundA()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - } - else if(keyTilesetScrollBar.mouseClick(x, y)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - soundRenderer.playFx(coreData.getClickSoundA()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - } - else if(keyMapScrollBar.mouseClick(x, y)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - soundRenderer.playFx(coreData.getClickSoundA()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - } - else if(keyScenarioScrollBar.mouseClick(x, y)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - soundRenderer.playFx(coreData.getClickSoundA()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - } - else if(buttonInstallTech.mouseClick(x, y) && buttonInstallTech.getEnabled()) { - soundRenderer.playFx(coreData.getClickSoundB()); - if(selectedTechName != "") { - bool alreadyHasTech = (std::find(techTreeFiles.begin(),techTreeFiles.end(),selectedTechName) != techTreeFiles.end()); - if(alreadyHasTech == true) { - bool remoteHasTech = (techCacheList.find(selectedTechName) != techCacheList.end()); - if(remoteHasTech == true){ - ModInfo &modInfo = techCacheList[selectedTechName]; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d] remote CRC [%s]\n",__FILE__,__FUNCTION__,__LINE__,modInfo.crc.c_str()); - - Config &config = Config::getInstance(); - string itemPath = config.getPathListForType(ptTechs,"")[1] + "/" + selectedTechName + string("/*"); - bool forceRefresh = (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); - if( strToUInt(modInfo.crc) != 0 && - strToUInt(modInfo.crc) != getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", NULL,forceRefresh)) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d] local CRC [%u]\n",__FILE__,__FUNCTION__,__LINE__,getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", NULL)); - - mainMessageBoxState = ftpmsg_ReplaceTechtree; - mainMessageBox.init(lang.getString("Yes"),lang.getString("No"),450); - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModLocalRemoteMismatch").c_str(),selectedTechName.c_str()); - showMessageBox(szBuf, lang.getString("Notice"), true); - } - else { - mainMessageBoxState = ftpmsg_None; - mainMessageBox.init(lang.getString("Ok"),450); - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModTechAlreadyInstalled").c_str(),selectedTechName.c_str()); - showMessageBox(szBuf, lang.getString("Notice"), true); - } - mapCRCUpdateList[itemPath] = true; - } - } - else { - string techName = selectedTechName; - string techURL = techCacheList[techName].url; - if(ftpClientThread != NULL) ftpClientThread->addTechtreeToRequests(techName,techURL); - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),mutexOwnerId); - if(ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); - fileFTPProgressList[techName] = pair(0,""); - safeMutexFTPProgress.ReleaseLock(); - buttonInstallTech.setEnabled(false); - } - } - else { - mainMessageBoxState = ftpmsg_None; - mainMessageBox.init(lang.getString("Ok"),450); - showMessageBox(lang.getString("ModSelectTechToInstall"), lang.getString("Notice"), true); - } - } - else if(buttonRemoveTech.mouseClick(x, y) && buttonRemoveTech.getEnabled()) { - soundRenderer.playFx(coreData.getClickSoundB()); - if(selectedTechName != "") { - bool alreadyHasTech = (std::find(techTreeFiles.begin(),techTreeFiles.end(),selectedTechName) != techTreeFiles.end()); - if(alreadyHasTech == true) { - mainMessageBoxState = ftpmsg_GetTechtree; - - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModRemoveTechConfirm").c_str(),selectedTechName.c_str()); - showMessageBox(szBuf, lang.getString("Question"), true); - } - else { - mainMessageBoxState = ftpmsg_None; - mainMessageBox.init(lang.getString("Ok"),450); - - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModCannotRemoveTechNotInstalled").c_str(),selectedTechName.c_str()); - showMessageBox(szBuf, lang.getString("Notice"), true); - } - } - else { - mainMessageBoxState = ftpmsg_None; - mainMessageBox.init(lang.getString("Ok"),450); - - showMessageBox(lang.getString("ModSelectTechToRemove"), lang.getString("Notice"), true); - } - } - - else if(buttonInstallTileset.mouseClick(x, y) && buttonInstallTileset.getEnabled()) { - soundRenderer.playFx(coreData.getClickSoundB()); - if(selectedTilesetName != "") { - bool alreadyHasTileset = (std::find(tilesetFiles.begin(),tilesetFiles.end(),selectedTilesetName) != tilesetFiles.end()); - if(alreadyHasTileset == true) { - bool remoteHasTileset = (tilesetCacheList.find(selectedTilesetName) != tilesetCacheList.end()); - if(remoteHasTileset){ - ModInfo &modInfo = tilesetCacheList[selectedTilesetName]; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d] remote CRC [%s]\n",__FILE__,__FUNCTION__,__LINE__,modInfo.crc.c_str()); - - Config &config = Config::getInstance(); - string itemPath = config.getPathListForType(ptTilesets,"")[1] + "/" + selectedTilesetName + string("/*"); - bool forceRefresh = (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); - - if( strToUInt(modInfo.crc) != 0 && - strToUInt(modInfo.crc) != getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", NULL,forceRefresh)) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d] local CRC [%u] [%s]\n",__FILE__,__FUNCTION__,__LINE__,getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", NULL),itemPath.c_str()); - - mainMessageBoxState = ftpmsg_ReplaceTileset; - mainMessageBox.init(lang.getString("Yes"),lang.getString("No"),450); - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModLocalRemoteMismatch").c_str(),selectedTilesetName.c_str()); - showMessageBox(szBuf, lang.getString("Notice"), true); - } - else { - mainMessageBoxState = ftpmsg_None; - mainMessageBox.init(lang.getString("Ok"),450); - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModTilesetAlreadyInstalled").c_str(),selectedTilesetName.c_str()); - showMessageBox(szBuf, lang.getString("Notice"), true); - } - } - } - else { - string tilesetName = selectedTilesetName; - string tilesetURL = tilesetCacheList[tilesetName].url; - if(ftpClientThread != NULL) ftpClientThread->addTilesetToRequests(tilesetName,tilesetURL); - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),mutexOwnerId); - if(ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); - fileFTPProgressList[tilesetName] = pair(0,""); - safeMutexFTPProgress.ReleaseLock(); - buttonInstallTileset.setEnabled(false); - } - } - else { - mainMessageBoxState = ftpmsg_None; - mainMessageBox.init(lang.getString("Ok"),450); - showMessageBox(lang.getString("ModSelectTilesetToInstall"), lang.getString("Notice"), true); - } - } - else if(buttonRemoveTileset.mouseClick(x, y) && buttonRemoveTileset.getEnabled()) { - soundRenderer.playFx(coreData.getClickSoundB()); - if(selectedTilesetName != "") { - bool alreadyHasTileset = (std::find(tilesetFiles.begin(),tilesetFiles.end(),selectedTilesetName) != tilesetFiles.end()); - if(alreadyHasTileset == true) { - mainMessageBoxState = ftpmsg_GetTileset; - - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModRemoveTilesetConfirm").c_str(),selectedTilesetName.c_str()); - showMessageBox(szBuf, lang.getString("Question"), true); - } - else { - mainMessageBoxState = ftpmsg_None; - mainMessageBox.init(lang.getString("Ok"),450); - - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModCannotRemoveTilesetNotInstalled").c_str(),selectedTilesetName.c_str()); - showMessageBox(szBuf, lang.getString("Notice"), true); - } - } - else { - mainMessageBoxState = ftpmsg_None; - mainMessageBox.init(lang.getString("Ok"),450); - showMessageBox(lang.getString("ModSelectTilesetToRemove"), lang.getString("Notice"), true); - } - } - - else if(buttonInstallMap.mouseClick(x, y) && buttonInstallMap.getEnabled()) { - soundRenderer.playFx(coreData.getClickSoundB()); - if(selectedMapName != "") { - bool alreadyHasMap = (std::find(mapFiles.begin(),mapFiles.end(),selectedMapName) != mapFiles.end()); - if(alreadyHasMap == true) { - bool remoteHasMap = (mapCacheList.find(selectedMapName) != mapCacheList.end()); - if(remoteHasMap){ - ModInfo &modInfo = mapCacheList[selectedMapName]; - if( modInfo.crc != modInfo.localCRC ) { - mainMessageBoxState = ftpmsg_ReplaceMap; - mainMessageBox.init(lang.getString("Yes"),lang.getString("No"),450); - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModLocalRemoteMismatch").c_str(),selectedMapName.c_str()); - showMessageBox(szBuf, lang.getString("Notice"), true); - } - else { - mainMessageBoxState = ftpmsg_None; - mainMessageBox.init(lang.getString("Ok"),450); - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModMapAlreadyInstalled").c_str(),selectedMapName.c_str()); - showMessageBox(szBuf, lang.getString("Notice"), true); - } - } - } - else { - string mapName = selectedMapName; - string mapURL = mapCacheList[mapName].url; - if(ftpClientThread != NULL) ftpClientThread->addMapToRequests(mapName,mapURL); - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),mutexOwnerId); - if(ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); - fileFTPProgressList[mapName] = pair(0,""); - safeMutexFTPProgress.ReleaseLock(); - buttonInstallMap.setEnabled(false); - } - } - else { - mainMessageBoxState = ftpmsg_None; - mainMessageBox.init(lang.getString("Ok"),450); - showMessageBox(lang.getString("ModSelectMapToInstall"), lang.getString("Notice"), true); - } - } - else if(buttonRemoveMap.mouseClick(x, y) && buttonRemoveMap.getEnabled()) { - soundRenderer.playFx(coreData.getClickSoundB()); - if(selectedMapName != "") { - bool alreadyHasMap = (std::find(mapFiles.begin(),mapFiles.end(),selectedMapName) != mapFiles.end()); - if(alreadyHasMap == true) { - mainMessageBoxState = ftpmsg_GetMap; - - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModRemoveMapConfirm").c_str(),selectedMapName.c_str()); - showMessageBox(szBuf, lang.getString("Question"), true); - } - else { - mainMessageBoxState = ftpmsg_None; - mainMessageBox.init(lang.getString("Ok"),450); - - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModCannotRemoveMapNotInstalled").c_str(),selectedMapName.c_str()); - showMessageBox(szBuf, lang.getString("Notice"), true); - } - } - else { - mainMessageBoxState = ftpmsg_None; - mainMessageBox.init(lang.getString("Ok"),450); - showMessageBox(lang.getString("ModSelectMapToRemove"), lang.getString("Notice"), true); - } - } - - else if(buttonInstallScenario.mouseClick(x, y) && buttonInstallScenario.getEnabled()) { - soundRenderer.playFx(coreData.getClickSoundB()); - if(selectedScenarioName != "") { - bool alreadyHasScenario = (std::find(scenarioFiles.begin(),scenarioFiles.end(),selectedScenarioName) != scenarioFiles.end()); - if(alreadyHasScenario == true) { - bool remoteHasScenario = (scenarioCacheList.find(selectedScenarioName) != scenarioCacheList.end()); - if(remoteHasScenario){ - ModInfo &modInfo = scenarioCacheList[selectedScenarioName]; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d] remote CRC [%s]\n",__FILE__,__FUNCTION__,__LINE__,modInfo.crc.c_str()); - - Config &config = Config::getInstance(); - string itemPath = config.getPathListForType(ptScenarios,"")[1] + "/" + selectedScenarioName + string("/*"); - bool forceRefresh = (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); - - if( strToUInt(modInfo.crc) != 0 && - strToUInt(modInfo.crc) != getFolderTreeContentsCheckSumRecursively(itemPath, "", NULL,forceRefresh)) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d] local CRC [%u]\n",__FILE__,__FUNCTION__,__LINE__,getFolderTreeContentsCheckSumRecursively(itemPath, "", NULL)); - - mainMessageBoxState = ftpmsg_ReplaceScenario; - mainMessageBox.init(lang.getString("Yes"),lang.getString("No"),450); - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModLocalRemoteMismatch").c_str(),selectedScenarioName.c_str()); - showMessageBox(szBuf, lang.getString("Notice"), true); - } - else { - mainMessageBoxState = ftpmsg_None; - mainMessageBox.init(lang.getString("Ok"),450); - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModScenarioAlreadyInstalled").c_str(),selectedScenarioName.c_str()); - showMessageBox(szBuf, lang.getString("Notice"), true); - } - } - } - else { - string scenarioName = selectedScenarioName; - string scenarioURL = scenarioCacheList[scenarioName].url; - - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d] adding file to download [%s]\n",__FILE__,__FUNCTION__,__LINE__,scenarioURL.c_str()); - if(ftpClientThread != NULL) ftpClientThread->addScenarioToRequests(scenarioName,scenarioURL); - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),mutexOwnerId); - if(ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); - fileFTPProgressList[scenarioName] = pair(0,""); - safeMutexFTPProgress.ReleaseLock(); - buttonInstallScenario.setEnabled(false); - } - } - else { - mainMessageBoxState = ftpmsg_None; - mainMessageBox.init(lang.getString("Ok"),450); - showMessageBox(lang.getString("ModSelectScenarioToInstall"), lang.getString("Notice"), true); - } - } - else if(buttonRemoveScenario.mouseClick(x, y) && buttonRemoveScenario.getEnabled()) { - soundRenderer.playFx(coreData.getClickSoundB()); - if(selectedScenarioName != "") { - bool alreadyHasScenario = (std::find(scenarioFiles.begin(),scenarioFiles.end(),selectedScenarioName) != scenarioFiles.end()); - if(alreadyHasScenario == true) { - mainMessageBoxState = ftpmsg_GetScenario; - - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModRemoveScenarioConfirm").c_str(),selectedScenarioName.c_str()); - showMessageBox(szBuf, lang.getString("Question"), true); - } - else { - mainMessageBoxState = ftpmsg_None; - mainMessageBox.init(lang.getString("Ok"),450); - - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModCannotRemoveScenarioNotInstalled").c_str(),selectedScenarioName.c_str()); - showMessageBox(szBuf, lang.getString("Notice"), true); - } - } - else { - mainMessageBoxState = ftpmsg_None; - mainMessageBox.init(lang.getString("Ok"),450); - showMessageBox(lang.getString("ModSelectScenarioToRemove"), lang.getString("Notice"), true); - } - } - - else { - if(keyMapScrollBar.getElementCount() != 0) { - for (int i = keyMapScrollBar.getVisibleStart(); - i <= keyMapScrollBar.getVisibleEnd(); ++i) { - if(keyMapButtons[i]->mouseClick(x, y) && keyMapButtons[i]->getEnabled()) { - string mapName = keyMapButtons[i]->getText(); - selectedTechName = ""; - selectedTilesetName = ""; - selectedMapName = ""; - selectedScenarioName = ""; - if(mapName != "") { - selectedMapName = mapName; - bool remoteHasMap = (mapCacheList.find(mapName) != mapCacheList.end()); - if(remoteHasMap) { - showRemoteDesription(&mapCacheList[selectedMapName]); - if(mapCacheList[selectedMapName].localCRC!=""){ - loadMapPreview(mapName); - } - } - else { - showLocalDescription(mapName); - loadMapPreview(mapName); - } - - } - break; - } - } - } - if(keyTechScrollBar.getElementCount() != 0) { - for (int i = keyTechScrollBar.getVisibleStart(); - i <= keyTechScrollBar.getVisibleEnd(); ++i) { - if(keyTechButtons[i]->mouseClick(x, y) && keyTechButtons[i]->getEnabled()) { - string techName = keyTechButtons[i]->getText(); - selectedTechName = ""; - selectedTilesetName = ""; - selectedMapName = ""; - selectedScenarioName = ""; - if(techName != "") { - selectedTechName = techName; - bool remoteHasTech = (techCacheList.find(techName) != techCacheList.end()); - if(remoteHasTech) { - showRemoteDesription(&techCacheList[techName]); - } - else { - showLocalDescription(techName); - } - } - break; - } - } - } - if(keyTilesetScrollBar.getElementCount() != 0) { - for (int i = keyTilesetScrollBar.getVisibleStart(); - i <= keyTilesetScrollBar.getVisibleEnd(); ++i) { - if(keyTilesetButtons[i]->mouseClick(x, y) && keyTilesetButtons[i]->getEnabled()) { - string tilesetName = keyTilesetButtons[i]->getText(); - selectedTechName = ""; - selectedTilesetName = ""; - selectedMapName = ""; - selectedScenarioName = ""; - if(tilesetName != "") { - selectedTilesetName = tilesetName; - bool remoteHasTileset = (tilesetCacheList.find(tilesetName) != tilesetCacheList.end()); - if(remoteHasTileset) { - showRemoteDesription(&tilesetCacheList[tilesetName]); - } - else { - showLocalDescription(tilesetName); - } - } - break; - } - } - } - if(keyScenarioScrollBar.getElementCount() != 0) { - for (int i = keyScenarioScrollBar.getVisibleStart(); - i <= keyScenarioScrollBar.getVisibleEnd(); ++i) { - if(keyScenarioButtons[i]->mouseClick(x, y) && keyScenarioButtons[i]->getEnabled()) { - string scenarioName = keyScenarioButtons[i]->getText(); - selectedTechName = ""; - selectedTilesetName = ""; - selectedMapName = ""; - selectedScenarioName = ""; - if(scenarioName != "") { - selectedScenarioName = scenarioName; - bool remoteHasScenario = (scenarioCacheList.find(scenarioName) != scenarioCacheList.end()); - if(remoteHasScenario) { - showRemoteDesription(&scenarioCacheList[scenarioName]); - } - else { - showLocalDescription(scenarioName); - } - - } - break; - } - } - } - - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); -} + CoreData &coreData = CoreData::getInstance(); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + Lang &lang = Lang::getInstance(); + + if (buttonReturn.mouseClick(x, y)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + soundRenderer.playFx(coreData.getClickSoundA()); + + if (fileFTPProgressList.empty() == false) { + mainMessageBoxState = ftpmsg_Quit; + mainMessageBox.init(lang.getString("Yes"), lang.getString("No"), 450); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("ModDownloadInProgressCancelQuestion").c_str(), + fileFTPProgressList.size()); + showMessageBox(szBuf, lang.getString("Question"), true); + } else { + cleanUp(); + mainMenu->setState(new MenuStateRoot(program, mainMenu)); + return; + } + } else if (mainMessageBox.getEnabled()) { + int button = 0; + if (mainMessageBox.mouseClick(x, y, button)) { + soundRenderer.playFx(coreData.getClickSoundA()); + mainMessageBox.setEnabled(false); + mainMessageBox.init(lang.getString("Yes"), lang.getString("No"), 450); + if (button == 0) { + if (mainMessageBoxState == ftpmsg_Quit) { + mainMessageBoxState = ftpmsg_None; + mainMenu->setState(new MenuStateRoot(program, mainMenu)); + return; + } else if (mainMessageBoxState == ftpmsg_GetMap || + mainMessageBoxState == ftpmsg_ReplaceMap) { + bool getItemAfterRemoval = (mainMessageBoxState == ftpmsg_ReplaceMap); + mainMessageBoxState = ftpmsg_None; + + Config &config = Config::getInstance(); + vector mapPaths = config.getPathListForType(ptMaps); + if (mapPaths.size() > 1) { + string removeMap = mapPaths[1]; + endPathWithSlash(removeMap); + removeMap += selectedMapName; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Removing Map [%s]\n", removeMap.c_str()); + removeFile(removeMap); + + bool remoteHasMap = + (mapCacheList.find(selectedMapName) != mapCacheList.end()); + if (remoteHasMap == false) { + for (unsigned int i = 0; i < keyMapButtons.size(); ++i) { + GraphicButton *button = keyMapButtons[i]; + if (button != NULL && button->getText() == selectedMapName) { + delete button; + keyMapButtons.erase(keyMapButtons.begin() + i); + labelsMap.erase(labelsMap.begin() + i); + keyMapScrollBar.setElementCount((int)keyMapButtons.size()); + break; + } + } + } -string MenuStateMods::getPreviewImageFileForMod(const ModInfo *modInfo) { - string fileName = ""; - if(modInfo->imageUrl != "") { - Config &config = Config::getInstance(); - string userData = config.getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - string tempPath = userData + "temp/"; - if(isdir(tempPath.c_str()) == false) { - createDirectoryPaths(tempPath); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("### tempPath [%s] isdir = %d\n",tempPath.c_str(),isdir(tempPath.c_str())); - - if(isdir(tempPath.c_str()) == true) { - fileName = tempPath; - switch(modInfo->type) { - case mt_Map: - fileName += "map_"; - break; - case mt_Tileset: - fileName += "tileset_"; - break; - case mt_Techtree: - fileName += "tech_"; - break; - case mt_Scenario: - fileName += "scenario_"; - break; - } - fileName += extractFileFromDirectoryPath(modInfo->imageUrl); + if (getItemAfterRemoval == false) { + selectedMapName = ""; + } + refreshMaps(); + Checksum::clearFileCache(); + + if (getItemAfterRemoval == true) { + string mapName = selectedMapName; + string mapURL = mapCacheList[mapName].url; + if (ftpClientThread != NULL) + ftpClientThread->addMapToRequests(mapName, mapURL); + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + mutexOwnerId); + if (ftpClientThread != NULL && + ftpClientThread->getProgressMutex() != NULL) + ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); + fileFTPProgressList[mapName] = pair(0, ""); + safeMutexFTPProgress.ReleaseLock(); + buttonInstallMap.setEnabled(false); + } + } + } else if (mainMessageBoxState == ftpmsg_GetTileset || + mainMessageBoxState == ftpmsg_ReplaceTileset) { + bool getItemAfterRemoval = + (mainMessageBoxState == ftpmsg_ReplaceTileset); + mainMessageBoxState = ftpmsg_None; + + Config &config = Config::getInstance(); + vector tilesetPaths = config.getPathListForType(ptTilesets); + if (tilesetPaths.size() > 1) { + string removeTileset = tilesetPaths[1]; + endPathWithSlash(removeTileset); + removeTileset += selectedTilesetName; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Removing Tileset [%s]\n", removeTileset.c_str()); + removeFolder(removeTileset); + + bool remoteHasTileset = + (tilesetCacheList.find(selectedTilesetName) != + tilesetCacheList.end()); + if (remoteHasTileset == false) { + // printf("\n\n\n$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ remote + // DOES NOT have removed tileset + // [%s]\n\n\n",selectedTilesetName.c_str()); + + for (unsigned int i = 0; i < keyTilesetButtons.size(); ++i) { + GraphicButton *button = keyTilesetButtons[i]; + if (button != NULL && + button->getText() == selectedTilesetName) { + delete button; + keyTilesetButtons.erase(keyTilesetButtons.begin() + i); + keyTilesetScrollBar.setElementCount( + (int)keyTilesetButtons.size()); + break; + } + } + } + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + mutexOwnerId); + if (ftpClientThread != NULL && + ftpClientThread->getProgressMutex() != NULL) + ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); + Checksum::clearFileCache(); + vector paths = + Config::getInstance().getPathListForType(ptTilesets); + string pathSearchString = + string("/") + selectedTilesetName + string("/*"); + const string filterFileExt = ".xml"; + clearFolderTreeContentsCheckSum(paths, pathSearchString, + filterFileExt); + clearFolderTreeContentsCheckSumList(paths, pathSearchString, + filterFileExt); + safeMutexFTPProgress.ReleaseLock(); + + if (getItemAfterRemoval == false) { + selectedTilesetName = ""; + } + refreshTilesets(); + } + + if (getItemAfterRemoval == true) { + string tilesetName = selectedTilesetName; + string tilesetURL = tilesetCacheList[tilesetName].url; + if (ftpClientThread != NULL) + ftpClientThread->addTilesetToRequests(tilesetName, tilesetURL); + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + mutexOwnerId); + if (ftpClientThread != NULL && + ftpClientThread->getProgressMutex() != NULL) + ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); + fileFTPProgressList[tilesetName] = pair(0, ""); + safeMutexFTPProgress.ReleaseLock(); + buttonInstallTileset.setEnabled(false); + } + } else if (mainMessageBoxState == ftpmsg_GetTechtree || + mainMessageBoxState == ftpmsg_ReplaceTechtree) { + bool getItemAfterRemoval = + (mainMessageBoxState == ftpmsg_ReplaceTechtree); + mainMessageBoxState = ftpmsg_None; + + Config &config = Config::getInstance(); + vector techPaths = config.getPathListForType(ptTechs); + if (techPaths.size() > 1) { + string removeTech = techPaths[1]; + endPathWithSlash(removeTech); + removeTech += selectedTechName; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Removing Techtree [%s]\n", removeTech.c_str()); + removeFolder(removeTech); + + bool remoteHasTech = + (techCacheList.find(selectedTechName) != techCacheList.end()); + if (remoteHasTech == false) { + for (unsigned int i = 0; i < keyTechButtons.size(); ++i) { + GraphicButton *button = keyTechButtons[i]; + if (button != NULL && button->getText() == selectedTechName) { + delete button; + keyTechButtons.erase(keyTechButtons.begin() + i); + labelsTech.erase(labelsTech.begin() + i); + keyTechScrollBar.setElementCount((int)keyTechButtons.size()); + break; + } + } + } + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + mutexOwnerId); + if (ftpClientThread != NULL && + ftpClientThread->getProgressMutex() != NULL) + ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); + // Clear the CRC file Cache + Checksum::clearFileCache(); + vector paths = + Config::getInstance().getPathListForType(ptTechs); + string pathSearchString = + string("/") + selectedTechName + string("/*"); + const string filterFileExt = ".xml"; + clearFolderTreeContentsCheckSum(paths, pathSearchString, + filterFileExt); + clearFolderTreeContentsCheckSumList(paths, pathSearchString, + filterFileExt); + safeMutexFTPProgress.ReleaseLock(); + + if (getItemAfterRemoval == false) { + selectedTechName = ""; + } + refreshTechs(); + } + + if (getItemAfterRemoval == true) { + string techName = selectedTechName; + string techURL = techCacheList[techName].url; + if (ftpClientThread != NULL) + ftpClientThread->addTechtreeToRequests(techName, techURL); + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + mutexOwnerId); + if (ftpClientThread != NULL && + ftpClientThread->getProgressMutex() != NULL) + ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); + fileFTPProgressList[techName] = pair(0, ""); + safeMutexFTPProgress.ReleaseLock(); + buttonInstallTech.setEnabled(false); + } + } else if (mainMessageBoxState == ftpmsg_GetScenario || + mainMessageBoxState == ftpmsg_ReplaceScenario) { + bool getItemAfterRemoval = + (mainMessageBoxState == ftpmsg_ReplaceScenario); + mainMessageBoxState = ftpmsg_None; + + Config &config = Config::getInstance(); + vector scenarioPaths = config.getPathListForType(ptScenarios); + if (scenarioPaths.size() > 1) { + string removeScenario = scenarioPaths[1]; + endPathWithSlash(removeScenario); + removeScenario += selectedScenarioName; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Removing Scenario [%s]\n", removeScenario.c_str()); + removeFolder(removeScenario); + + bool remoteHasScenario = + (scenarioCacheList.find(selectedScenarioName) != + scenarioCacheList.end()); + if (remoteHasScenario == false) { + for (unsigned int i = 0; i < keyScenarioButtons.size(); ++i) { + GraphicButton *button = keyScenarioButtons[i]; + if (button != NULL && + button->getText() == selectedScenarioName) { + delete button; + keyScenarioButtons.erase(keyScenarioButtons.begin() + i); + keyScenarioScrollBar.setElementCount( + (int)keyScenarioButtons.size()); + break; + } + } + } + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + mutexOwnerId); + if (ftpClientThread != NULL && + ftpClientThread->getProgressMutex() != NULL) + ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); + Checksum::clearFileCache(); + vector paths = + Config::getInstance().getPathListForType(ptScenarios); + string pathSearchString = + string("/") + selectedScenarioName + string("/*"); + const string filterFileExt = ".xml"; + clearFolderTreeContentsCheckSum(paths, pathSearchString, + filterFileExt); + clearFolderTreeContentsCheckSumList(paths, pathSearchString, + filterFileExt); + safeMutexFTPProgress.ReleaseLock(); + + if (getItemAfterRemoval == false) { + selectedScenarioName = ""; + } + refreshScenarios(); + } + + if (getItemAfterRemoval == true) { + string scenarioName = selectedScenarioName; + string scenarioURL = scenarioCacheList[scenarioName].url; + if (ftpClientThread != NULL) + ftpClientThread->addScenarioToRequests(scenarioName, scenarioURL); + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + mutexOwnerId); + if (ftpClientThread != NULL && + ftpClientThread->getProgressMutex() != NULL) + ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); + fileFTPProgressList[scenarioName] = pair(0, ""); + safeMutexFTPProgress.ReleaseLock(); + buttonInstallScenario.setEnabled(false); + } + } + } + } + } else if (keyTechScrollBar.mouseClick(x, y)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + soundRenderer.playFx(coreData.getClickSoundA()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + } else if (keyTilesetScrollBar.mouseClick(x, y)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + soundRenderer.playFx(coreData.getClickSoundA()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + } else if (keyMapScrollBar.mouseClick(x, y)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + soundRenderer.playFx(coreData.getClickSoundA()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + } else if (keyScenarioScrollBar.mouseClick(x, y)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + soundRenderer.playFx(coreData.getClickSoundA()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + } else if (buttonInstallTech.mouseClick(x, y) && + buttonInstallTech.getEnabled()) { + soundRenderer.playFx(coreData.getClickSoundB()); + if (selectedTechName != "") { + bool alreadyHasTech = + (std::find(techTreeFiles.begin(), techTreeFiles.end(), + selectedTechName) != techTreeFiles.end()); + if (alreadyHasTech == true) { + bool remoteHasTech = + (techCacheList.find(selectedTechName) != techCacheList.end()); + if (remoteHasTech == true) { + ModInfo &modInfo = techCacheList[selectedTechName]; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d] remote CRC [%s]\n", __FILE__, + __FUNCTION__, __LINE__, modInfo.crc.c_str()); + + Config &config = Config::getInstance(); + string itemPath = config.getPathListForType(ptTechs, "")[1] + "/" + + selectedTechName + string("/*"); + bool forceRefresh = + (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); + if (strToUInt(modInfo.crc) != 0 && + strToUInt(modInfo.crc) != + getFolderTreeContentsCheckSumRecursively( + itemPath, ".xml", NULL, forceRefresh)) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d] local CRC [%u]\n", __FILE__, + __FUNCTION__, __LINE__, + getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", + NULL)); + + mainMessageBoxState = ftpmsg_ReplaceTechtree; + mainMessageBox.init(lang.getString("Yes"), lang.getString("No"), + 450); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("ModLocalRemoteMismatch").c_str(), + selectedTechName.c_str()); + showMessageBox(szBuf, lang.getString("Notice"), true); + } else { + mainMessageBoxState = ftpmsg_None; + mainMessageBox.init(lang.getString("Ok"), 450); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("ModTechAlreadyInstalled").c_str(), + selectedTechName.c_str()); + showMessageBox(szBuf, lang.getString("Notice"), true); + } + mapCRCUpdateList[itemPath] = true; + } + } else { + string techName = selectedTechName; + string techURL = techCacheList[techName].url; + if (ftpClientThread != NULL) + ftpClientThread->addTechtreeToRequests(techName, techURL); + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + mutexOwnerId); + if (ftpClientThread != NULL && + ftpClientThread->getProgressMutex() != NULL) + ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); + fileFTPProgressList[techName] = pair(0, ""); + safeMutexFTPProgress.ReleaseLock(); + buttonInstallTech.setEnabled(false); + } + } else { + mainMessageBoxState = ftpmsg_None; + mainMessageBox.init(lang.getString("Ok"), 450); + showMessageBox(lang.getString("ModSelectTechToInstall"), + lang.getString("Notice"), true); + } + } else if (buttonRemoveTech.mouseClick(x, y) && + buttonRemoveTech.getEnabled()) { + soundRenderer.playFx(coreData.getClickSoundB()); + if (selectedTechName != "") { + bool alreadyHasTech = + (std::find(techTreeFiles.begin(), techTreeFiles.end(), + selectedTechName) != techTreeFiles.end()); + if (alreadyHasTech == true) { + mainMessageBoxState = ftpmsg_GetTechtree; + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, lang.getString("ModRemoveTechConfirm").c_str(), + selectedTechName.c_str()); + showMessageBox(szBuf, lang.getString("Question"), true); + } else { + mainMessageBoxState = ftpmsg_None; + mainMessageBox.init(lang.getString("Ok"), 450); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("ModCannotRemoveTechNotInstalled").c_str(), + selectedTechName.c_str()); + showMessageBox(szBuf, lang.getString("Notice"), true); + } + } else { + mainMessageBoxState = ftpmsg_None; + mainMessageBox.init(lang.getString("Ok"), 450); + + showMessageBox(lang.getString("ModSelectTechToRemove"), + lang.getString("Notice"), true); + } + } + + else if (buttonInstallTileset.mouseClick(x, y) && + buttonInstallTileset.getEnabled()) { + soundRenderer.playFx(coreData.getClickSoundB()); + if (selectedTilesetName != "") { + bool alreadyHasTileset = + (std::find(tilesetFiles.begin(), tilesetFiles.end(), + selectedTilesetName) != tilesetFiles.end()); + if (alreadyHasTileset == true) { + bool remoteHasTileset = (tilesetCacheList.find(selectedTilesetName) != + tilesetCacheList.end()); + if (remoteHasTileset) { + ModInfo &modInfo = tilesetCacheList[selectedTilesetName]; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d] remote CRC [%s]\n", __FILE__, + __FUNCTION__, __LINE__, modInfo.crc.c_str()); + + Config &config = Config::getInstance(); + string itemPath = config.getPathListForType(ptTilesets, "")[1] + "/" + + selectedTilesetName + string("/*"); + bool forceRefresh = + (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); + + if (strToUInt(modInfo.crc) != 0 && + strToUInt(modInfo.crc) != + getFolderTreeContentsCheckSumRecursively( + itemPath, ".xml", NULL, forceRefresh)) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d] local CRC [%u] [%s]\n", __FILE__, + __FUNCTION__, __LINE__, + getFolderTreeContentsCheckSumRecursively(itemPath, ".xml", + NULL), + itemPath.c_str()); + + mainMessageBoxState = ftpmsg_ReplaceTileset; + mainMessageBox.init(lang.getString("Yes"), lang.getString("No"), + 450); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("ModLocalRemoteMismatch").c_str(), + selectedTilesetName.c_str()); + showMessageBox(szBuf, lang.getString("Notice"), true); + } else { + mainMessageBoxState = ftpmsg_None; + mainMessageBox.init(lang.getString("Ok"), 450); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("ModTilesetAlreadyInstalled").c_str(), + selectedTilesetName.c_str()); + showMessageBox(szBuf, lang.getString("Notice"), true); + } + } + } else { + string tilesetName = selectedTilesetName; + string tilesetURL = tilesetCacheList[tilesetName].url; + if (ftpClientThread != NULL) + ftpClientThread->addTilesetToRequests(tilesetName, tilesetURL); + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + mutexOwnerId); + if (ftpClientThread != NULL && + ftpClientThread->getProgressMutex() != NULL) + ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); + fileFTPProgressList[tilesetName] = pair(0, ""); + safeMutexFTPProgress.ReleaseLock(); + buttonInstallTileset.setEnabled(false); + } + } else { + mainMessageBoxState = ftpmsg_None; + mainMessageBox.init(lang.getString("Ok"), 450); + showMessageBox(lang.getString("ModSelectTilesetToInstall"), + lang.getString("Notice"), true); + } + } else if (buttonRemoveTileset.mouseClick(x, y) && + buttonRemoveTileset.getEnabled()) { + soundRenderer.playFx(coreData.getClickSoundB()); + if (selectedTilesetName != "") { + bool alreadyHasTileset = + (std::find(tilesetFiles.begin(), tilesetFiles.end(), + selectedTilesetName) != tilesetFiles.end()); + if (alreadyHasTileset == true) { + mainMessageBoxState = ftpmsg_GetTileset; + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, lang.getString("ModRemoveTilesetConfirm").c_str(), + selectedTilesetName.c_str()); + showMessageBox(szBuf, lang.getString("Question"), true); + } else { + mainMessageBoxState = ftpmsg_None; + mainMessageBox.init(lang.getString("Ok"), 450); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("ModCannotRemoveTilesetNotInstalled").c_str(), + selectedTilesetName.c_str()); + showMessageBox(szBuf, lang.getString("Notice"), true); + } + } else { + mainMessageBoxState = ftpmsg_None; + mainMessageBox.init(lang.getString("Ok"), 450); + showMessageBox(lang.getString("ModSelectTilesetToRemove"), + lang.getString("Notice"), true); + } + } + + else if (buttonInstallMap.mouseClick(x, y) && buttonInstallMap.getEnabled()) { + soundRenderer.playFx(coreData.getClickSoundB()); + if (selectedMapName != "") { + bool alreadyHasMap = (std::find(mapFiles.begin(), mapFiles.end(), + selectedMapName) != mapFiles.end()); + if (alreadyHasMap == true) { + bool remoteHasMap = + (mapCacheList.find(selectedMapName) != mapCacheList.end()); + if (remoteHasMap) { + ModInfo &modInfo = mapCacheList[selectedMapName]; + if (modInfo.crc != modInfo.localCRC) { + mainMessageBoxState = ftpmsg_ReplaceMap; + mainMessageBox.init(lang.getString("Yes"), lang.getString("No"), + 450); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("ModLocalRemoteMismatch").c_str(), + selectedMapName.c_str()); + showMessageBox(szBuf, lang.getString("Notice"), true); + } else { + mainMessageBoxState = ftpmsg_None; + mainMessageBox.init(lang.getString("Ok"), 450); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("ModMapAlreadyInstalled").c_str(), + selectedMapName.c_str()); + showMessageBox(szBuf, lang.getString("Notice"), true); + } + } + } else { + string mapName = selectedMapName; + string mapURL = mapCacheList[mapName].url; + if (ftpClientThread != NULL) + ftpClientThread->addMapToRequests(mapName, mapURL); + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + mutexOwnerId); + if (ftpClientThread != NULL && + ftpClientThread->getProgressMutex() != NULL) + ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); + fileFTPProgressList[mapName] = pair(0, ""); + safeMutexFTPProgress.ReleaseLock(); + buttonInstallMap.setEnabled(false); + } + } else { + mainMessageBoxState = ftpmsg_None; + mainMessageBox.init(lang.getString("Ok"), 450); + showMessageBox(lang.getString("ModSelectMapToInstall"), + lang.getString("Notice"), true); + } + } else if (buttonRemoveMap.mouseClick(x, y) && buttonRemoveMap.getEnabled()) { + soundRenderer.playFx(coreData.getClickSoundB()); + if (selectedMapName != "") { + bool alreadyHasMap = (std::find(mapFiles.begin(), mapFiles.end(), + selectedMapName) != mapFiles.end()); + if (alreadyHasMap == true) { + mainMessageBoxState = ftpmsg_GetMap; + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, lang.getString("ModRemoveMapConfirm").c_str(), + selectedMapName.c_str()); + showMessageBox(szBuf, lang.getString("Question"), true); + } else { + mainMessageBoxState = ftpmsg_None; + mainMessageBox.init(lang.getString("Ok"), 450); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("ModCannotRemoveMapNotInstalled").c_str(), + selectedMapName.c_str()); + showMessageBox(szBuf, lang.getString("Notice"), true); + } + } else { + mainMessageBoxState = ftpmsg_None; + mainMessageBox.init(lang.getString("Ok"), 450); + showMessageBox(lang.getString("ModSelectMapToRemove"), + lang.getString("Notice"), true); + } + } + + else if (buttonInstallScenario.mouseClick(x, y) && + buttonInstallScenario.getEnabled()) { + soundRenderer.playFx(coreData.getClickSoundB()); + if (selectedScenarioName != "") { + bool alreadyHasScenario = + (std::find(scenarioFiles.begin(), scenarioFiles.end(), + selectedScenarioName) != scenarioFiles.end()); + if (alreadyHasScenario == true) { + bool remoteHasScenario = + (scenarioCacheList.find(selectedScenarioName) != + scenarioCacheList.end()); + if (remoteHasScenario) { + ModInfo &modInfo = scenarioCacheList[selectedScenarioName]; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d] remote CRC [%s]\n", __FILE__, + __FUNCTION__, __LINE__, modInfo.crc.c_str()); + + Config &config = Config::getInstance(); + string itemPath = config.getPathListForType(ptScenarios, "")[1] + + "/" + selectedScenarioName + string("/*"); + bool forceRefresh = + (mapCRCUpdateList.find(itemPath) == mapCRCUpdateList.end()); + + if (strToUInt(modInfo.crc) != 0 && + strToUInt(modInfo.crc) != + getFolderTreeContentsCheckSumRecursively(itemPath, "", NULL, + forceRefresh)) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf( + "In [%s::%s Line %d] local CRC [%u]\n", __FILE__, + __FUNCTION__, __LINE__, + getFolderTreeContentsCheckSumRecursively(itemPath, "", NULL)); + + mainMessageBoxState = ftpmsg_ReplaceScenario; + mainMessageBox.init(lang.getString("Yes"), lang.getString("No"), + 450); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("ModLocalRemoteMismatch").c_str(), + selectedScenarioName.c_str()); + showMessageBox(szBuf, lang.getString("Notice"), true); + } else { + mainMessageBoxState = ftpmsg_None; + mainMessageBox.init(lang.getString("Ok"), 450); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("ModScenarioAlreadyInstalled").c_str(), + selectedScenarioName.c_str()); + showMessageBox(szBuf, lang.getString("Notice"), true); + } } - } - return fileName; + } else { + string scenarioName = selectedScenarioName; + string scenarioURL = scenarioCacheList[scenarioName].url; + + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d] + // adding file to download + // [%s]\n",__FILE__,__FUNCTION__,__LINE__,scenarioURL.c_str()); + if (ftpClientThread != NULL) + ftpClientThread->addScenarioToRequests(scenarioName, scenarioURL); + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + mutexOwnerId); + if (ftpClientThread != NULL && + ftpClientThread->getProgressMutex() != NULL) + ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); + fileFTPProgressList[scenarioName] = pair(0, ""); + safeMutexFTPProgress.ReleaseLock(); + buttonInstallScenario.setEnabled(false); + } + } else { + mainMessageBoxState = ftpmsg_None; + mainMessageBox.init(lang.getString("Ok"), 450); + showMessageBox(lang.getString("ModSelectScenarioToInstall"), + lang.getString("Notice"), true); + } + } else if (buttonRemoveScenario.mouseClick(x, y) && + buttonRemoveScenario.getEnabled()) { + soundRenderer.playFx(coreData.getClickSoundB()); + if (selectedScenarioName != "") { + bool alreadyHasScenario = + (std::find(scenarioFiles.begin(), scenarioFiles.end(), + selectedScenarioName) != scenarioFiles.end()); + if (alreadyHasScenario == true) { + mainMessageBoxState = ftpmsg_GetScenario; + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("ModRemoveScenarioConfirm").c_str(), + selectedScenarioName.c_str()); + showMessageBox(szBuf, lang.getString("Question"), true); + } else { + mainMessageBoxState = ftpmsg_None; + mainMessageBox.init(lang.getString("Ok"), 450); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("ModCannotRemoveScenarioNotInstalled").c_str(), + selectedScenarioName.c_str()); + showMessageBox(szBuf, lang.getString("Notice"), true); + } + } else { + mainMessageBoxState = ftpmsg_None; + mainMessageBox.init(lang.getString("Ok"), 450); + showMessageBox(lang.getString("ModSelectScenarioToRemove"), + lang.getString("Notice"), true); + } + } + + else { + if (keyMapScrollBar.getElementCount() != 0) { + for (int i = keyMapScrollBar.getVisibleStart(); + i <= keyMapScrollBar.getVisibleEnd(); ++i) { + if (keyMapButtons[i]->mouseClick(x, y) && + keyMapButtons[i]->getEnabled()) { + string mapName = keyMapButtons[i]->getText(); + selectedTechName = ""; + selectedTilesetName = ""; + selectedMapName = ""; + selectedScenarioName = ""; + if (mapName != "") { + selectedMapName = mapName; + bool remoteHasMap = + (mapCacheList.find(mapName) != mapCacheList.end()); + if (remoteHasMap) { + showRemoteDesription(&mapCacheList[selectedMapName]); + if (mapCacheList[selectedMapName].localCRC != "") { + loadMapPreview(mapName); + } + } else { + showLocalDescription(mapName); + loadMapPreview(mapName); + } + } + break; + } + } + } + if (keyTechScrollBar.getElementCount() != 0) { + for (int i = keyTechScrollBar.getVisibleStart(); + i <= keyTechScrollBar.getVisibleEnd(); ++i) { + if (keyTechButtons[i]->mouseClick(x, y) && + keyTechButtons[i]->getEnabled()) { + string techName = keyTechButtons[i]->getText(); + selectedTechName = ""; + selectedTilesetName = ""; + selectedMapName = ""; + selectedScenarioName = ""; + if (techName != "") { + selectedTechName = techName; + bool remoteHasTech = + (techCacheList.find(techName) != techCacheList.end()); + if (remoteHasTech) { + showRemoteDesription(&techCacheList[techName]); + } else { + showLocalDescription(techName); + } + } + break; + } + } + } + if (keyTilesetScrollBar.getElementCount() != 0) { + for (int i = keyTilesetScrollBar.getVisibleStart(); + i <= keyTilesetScrollBar.getVisibleEnd(); ++i) { + if (keyTilesetButtons[i]->mouseClick(x, y) && + keyTilesetButtons[i]->getEnabled()) { + string tilesetName = keyTilesetButtons[i]->getText(); + selectedTechName = ""; + selectedTilesetName = ""; + selectedMapName = ""; + selectedScenarioName = ""; + if (tilesetName != "") { + selectedTilesetName = tilesetName; + bool remoteHasTileset = + (tilesetCacheList.find(tilesetName) != tilesetCacheList.end()); + if (remoteHasTileset) { + showRemoteDesription(&tilesetCacheList[tilesetName]); + } else { + showLocalDescription(tilesetName); + } + } + break; + } + } + } + if (keyScenarioScrollBar.getElementCount() != 0) { + for (int i = keyScenarioScrollBar.getVisibleStart(); + i <= keyScenarioScrollBar.getVisibleEnd(); ++i) { + if (keyScenarioButtons[i]->mouseClick(x, y) && + keyScenarioButtons[i]->getEnabled()) { + string scenarioName = keyScenarioButtons[i]->getText(); + selectedTechName = ""; + selectedTilesetName = ""; + selectedMapName = ""; + selectedScenarioName = ""; + if (scenarioName != "") { + selectedScenarioName = scenarioName; + bool remoteHasScenario = (scenarioCacheList.find(scenarioName) != + scenarioCacheList.end()); + if (remoteHasScenario) { + showRemoteDesription(&scenarioCacheList[scenarioName]); + } else { + showLocalDescription(scenarioName); + } + } + break; + } + } + } + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + __FILE__, __FUNCTION__, __LINE__); } +string MenuStateMods::getPreviewImageFileForMod(const ModInfo *modInfo) { + string fileName = ""; + if (modInfo->imageUrl != "") { + Config &config = Config::getInstance(); + string userData = config.getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + string tempPath = userData + "temp/"; + if (isdir(tempPath.c_str()) == false) { + createDirectoryPaths(tempPath); + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("### tempPath [%s] isdir = %d\n", tempPath.c_str(), + isdir(tempPath.c_str())); + + if (isdir(tempPath.c_str()) == true) { + fileName = tempPath; + switch (modInfo->type) { + case mt_Map: + fileName += "map_"; + break; + case mt_Tileset: + fileName += "tileset_"; + break; + case mt_Techtree: + fileName += "tech_"; + break; + case mt_Scenario: + fileName += "scenario_"; + break; + } + fileName += extractFileFromDirectoryPath(modInfo->imageUrl); + } + } + return fileName; +} void MenuStateMods::showLocalDescription(string name) { - Lang &lang= Lang::getInstance(); - modInfoSelected=NULL; - cleanupPreviewTexture(); - validMapPreview=false; - cleanupMapPreviewTexture(); - modDescrLabel.setText(lang.getString("ModOnlyLocal")+":\n'"+name+"'"); + Lang &lang = Lang::getInstance(); + modInfoSelected = NULL; + cleanupPreviewTexture(); + validMapPreview = false; + cleanupMapPreviewTexture(); + modDescrLabel.setText(lang.getString("ModOnlyLocal") + ":\n'" + name + "'"); } void MenuStateMods::loadMapPreview(string mapName) { - Config &config = Config::getInstance(); - cleanupMapPreviewTexture(); - vector mapPaths = config.getPathListForType(ptMaps); - string &mapPath = mapPaths[1]; - endPathWithSlash(mapPath); - mapPath += mapName; - MapInfo mapInfo = loadMapInfo(mapPath); - if(enableMapPreview == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - mapPreview.loadFromFile(mapPath.c_str()); - - //printf("Loading map preview MAP\n"); - cleanupMapPreviewTexture(); - validMapPreview=true; - } + Config &config = Config::getInstance(); + cleanupMapPreviewTexture(); + vector mapPaths = config.getPathListForType(ptMaps); + string &mapPath = mapPaths[1]; + endPathWithSlash(mapPath); + mapPath += mapName; + MapInfo mapInfo = loadMapInfo(mapPath); + if (enableMapPreview == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + mapPreview.loadFromFile(mapPath.c_str()); + + // printf("Loading map preview MAP\n"); + cleanupMapPreviewTexture(); + validMapPreview = true; + } } - - void MenuStateMods::showRemoteDesription(ModInfo *modInfo) { - //displayModPreviewImage = false; - modInfoSelected = modInfo; - validMapPreview=false; - cleanupMapPreviewTexture(); - - string modText = modInfo->description; - replaceAll(modText, "\\n", "\n"); - modDescrLabel.setText(modText); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("### modInfo->imageUrl [%s]\n",modInfo->imageUrl.c_str()); - - if(modInfo->imageUrl != "") { - cleanupPreviewTexture(); - string tempImage = getPreviewImageFileForMod(modInfo); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("### tempImage [%s] exists [%d]\n",tempImage.c_str(),fileExists(tempImage)); - - if(tempImage != "" && fileExists(tempImage) == false) { - if(ftpClientThread != NULL) ftpClientThread->addFileToRequests(tempImage,modInfo->imageUrl); - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),mutexOwnerId); - if(ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); - fileFTPProgressList[tempImage] = pair(0,""); - safeMutexFTPProgress.ReleaseLock(); - - } - else { - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),mutexOwnerId); - if(ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); - if(fileFTPProgressList.find(tempImage) == fileFTPProgressList.end()) { - //displayModPreviewImage = true; - displayModPreviewImage[tempImage] = true; - } - safeMutexFTPProgress.ReleaseLock(); - } - } + // displayModPreviewImage = false; + modInfoSelected = modInfo; + validMapPreview = false; + cleanupMapPreviewTexture(); + + string modText = modInfo->description; + replaceAll(modText, "\\n", "\n"); + modDescrLabel.setText(modText); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("### modInfo->imageUrl [%s]\n", modInfo->imageUrl.c_str()); + + if (modInfo->imageUrl != "") { + cleanupPreviewTexture(); + string tempImage = getPreviewImageFileForMod(modInfo); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("### tempImage [%s] exists [%d]\n", tempImage.c_str(), + fileExists(tempImage)); + + if (tempImage != "" && fileExists(tempImage) == false) { + if (ftpClientThread != NULL) + ftpClientThread->addFileToRequests(tempImage, modInfo->imageUrl); + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + mutexOwnerId); + if (ftpClientThread != NULL && + ftpClientThread->getProgressMutex() != NULL) + ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); + fileFTPProgressList[tempImage] = pair(0, ""); + safeMutexFTPProgress.ReleaseLock(); + + } else { + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + mutexOwnerId); + if (ftpClientThread != NULL && + ftpClientThread->getProgressMutex() != NULL) + ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); + if (fileFTPProgressList.find(tempImage) == fileFTPProgressList.end()) { + // displayModPreviewImage = true; + displayModPreviewImage[tempImage] = true; + } + safeMutexFTPProgress.ReleaseLock(); + } + } } -void MenuStateMods::mouseUp(int x, int y, const MouseButton mouseButton){ - if (mouseButton == mbLeft) { - keyTechScrollBar.mouseUp(x, y); - keyTilesetScrollBar.mouseUp(x, y); - keyMapScrollBar.mouseUp(x, y); - keyScenarioScrollBar.mouseUp(x, y); - } +void MenuStateMods::mouseUp(int x, int y, const MouseButton mouseButton) { + if (mouseButton == mbLeft) { + keyTechScrollBar.mouseUp(x, y); + keyTilesetScrollBar.mouseUp(x, y); + keyMapScrollBar.mouseUp(x, y); + keyScenarioScrollBar.mouseUp(x, y); + } } void MenuStateMods::mouseMove(int x, int y, const MouseState *ms) { - buttonReturn.mouseMove(x, y); - - if (mainMessageBox.getEnabled()) { - mainMessageBox.mouseMove(x, y); - } - - buttonInstallTech.mouseMove(x, y); - buttonRemoveTech.mouseMove(x, y); - buttonInstallTileset.mouseMove(x, y); - buttonRemoveTileset.mouseMove(x, y); - buttonInstallMap.mouseMove(x, y); - buttonRemoveMap.mouseMove(x, y); - buttonInstallScenario.mouseMove(x, y); - buttonRemoveScenario.mouseMove(x, y); - - if (ms->get(mbLeft)) { - keyMapScrollBar.mouseDown(x, y); - keyTechScrollBar.mouseDown(x, y); - keyTilesetScrollBar.mouseDown(x, y); - keyScenarioScrollBar.mouseDown(x, y); - } - else { - keyMapScrollBar.mouseMove(x, y); - keyTechScrollBar.mouseMove(x, y); - keyTilesetScrollBar.mouseMove(x, y); - keyScenarioScrollBar.mouseMove(x, y); - } - - if(keyMapScrollBar.getElementCount() !=0) { - for(int i = keyMapScrollBar.getVisibleStart(); i <= keyMapScrollBar.getVisibleEnd(); ++i) { - keyMapButtons[i]->mouseMove(x, y); - } - } - if(keyTechScrollBar.getElementCount() !=0) { - for(int i = keyTechScrollBar.getVisibleStart(); i <= keyTechScrollBar.getVisibleEnd(); ++i) { - keyTechButtons[i]->mouseMove(x, y); - } - } - if(keyTilesetScrollBar.getElementCount() !=0) { - for(int i = keyTilesetScrollBar.getVisibleStart(); i <= keyTilesetScrollBar.getVisibleEnd(); ++i) { - keyTilesetButtons[i]->mouseMove(x, y); - } - } - if(keyScenarioScrollBar.getElementCount() !=0) { - for(int i = keyScenarioScrollBar.getVisibleStart(); i <= keyScenarioScrollBar.getVisibleEnd(); ++i) { - keyScenarioButtons[i]->mouseMove(x, y); - } + buttonReturn.mouseMove(x, y); + + if (mainMessageBox.getEnabled()) { + mainMessageBox.mouseMove(x, y); + } + + buttonInstallTech.mouseMove(x, y); + buttonRemoveTech.mouseMove(x, y); + buttonInstallTileset.mouseMove(x, y); + buttonRemoveTileset.mouseMove(x, y); + buttonInstallMap.mouseMove(x, y); + buttonRemoveMap.mouseMove(x, y); + buttonInstallScenario.mouseMove(x, y); + buttonRemoveScenario.mouseMove(x, y); + + if (ms->get(mbLeft)) { + keyMapScrollBar.mouseDown(x, y); + keyTechScrollBar.mouseDown(x, y); + keyTilesetScrollBar.mouseDown(x, y); + keyScenarioScrollBar.mouseDown(x, y); + } else { + keyMapScrollBar.mouseMove(x, y); + keyTechScrollBar.mouseMove(x, y); + keyTilesetScrollBar.mouseMove(x, y); + keyScenarioScrollBar.mouseMove(x, y); + } + + if (keyMapScrollBar.getElementCount() != 0) { + for (int i = keyMapScrollBar.getVisibleStart(); + i <= keyMapScrollBar.getVisibleEnd(); ++i) { + keyMapButtons[i]->mouseMove(x, y); + } + } + if (keyTechScrollBar.getElementCount() != 0) { + for (int i = keyTechScrollBar.getVisibleStart(); + i <= keyTechScrollBar.getVisibleEnd(); ++i) { + keyTechButtons[i]->mouseMove(x, y); + } + } + if (keyTilesetScrollBar.getElementCount() != 0) { + for (int i = keyTilesetScrollBar.getVisibleStart(); + i <= keyTilesetScrollBar.getVisibleEnd(); ++i) { + keyTilesetButtons[i]->mouseMove(x, y); + } + } + if (keyScenarioScrollBar.getElementCount() != 0) { + for (int i = keyScenarioScrollBar.getVisibleStart(); + i <= keyScenarioScrollBar.getVisibleEnd(); ++i) { + keyScenarioButtons[i]->mouseMove(x, y); } + } } -bool MenuStateMods::eventMouseWheel( GraphicScrollBar* scrollBar, UserButtons* buttons, int x, int y, int zDelta) { - int result=false; - int overButton=false; - if(scrollBar->getElementCount() !=0) { - for(int i = scrollBar->getVisibleStart(); i <= scrollBar->getVisibleEnd(); ++i) { - if((*buttons)[i]->mouseMove(x, y)) { - overButton=true; - break; - } - } - } - result= scrollBar->eventMouseWheel(x, y, zDelta,overButton); - if(result) layoutButtons(scrollBar,buttons,NULL); - - if(scrollBar->getElementCount() !=0) { - for(int i = scrollBar->getVisibleStart(); i <= scrollBar->getVisibleEnd(); ++i) { - (*buttons)[i]->mouseMove(x, y); - } - } - return result; +bool MenuStateMods::eventMouseWheel(GraphicScrollBar *scrollBar, + UserButtons *buttons, int x, int y, + int zDelta) { + int result = false; + int overButton = false; + if (scrollBar->getElementCount() != 0) { + for (int i = scrollBar->getVisibleStart(); i <= scrollBar->getVisibleEnd(); + ++i) { + if ((*buttons)[i]->mouseMove(x, y)) { + overButton = true; + break; + } + } + } + result = scrollBar->eventMouseWheel(x, y, zDelta, overButton); + if (result) + layoutButtons(scrollBar, buttons, NULL); + + if (scrollBar->getElementCount() != 0) { + for (int i = scrollBar->getVisibleStart(); i <= scrollBar->getVisibleEnd(); + ++i) { + (*buttons)[i]->mouseMove(x, y); + } + } + return result; } void MenuStateMods::eventMouseWheel(int x, int y, int zDelta) { - bool result = eventMouseWheel(&keyMapScrollBar, &keyMapButtons, x, y, zDelta); - if (!result) - result = eventMouseWheel(&keyTechScrollBar, &keyTechButtons, x, y, zDelta); - if (!result) - result = eventMouseWheel(&keyScenarioScrollBar, &keyScenarioButtons, x, y, zDelta); - if (!result) - result = eventMouseWheel(&keyTilesetScrollBar, &keyTilesetButtons, x, y, zDelta); + bool result = eventMouseWheel(&keyMapScrollBar, &keyMapButtons, x, y, zDelta); + if (!result) + result = eventMouseWheel(&keyTechScrollBar, &keyTechButtons, x, y, zDelta); + if (!result) + result = eventMouseWheel(&keyScenarioScrollBar, &keyScenarioButtons, x, y, + zDelta); + if (!result) + result = + eventMouseWheel(&keyTilesetScrollBar, &keyTilesetButtons, x, y, zDelta); } void MenuStateMods::cleanupPreviewTexture() { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] scenarioLogoTexture [%p]\n",__FILE__,__FUNCTION__,__LINE__,modPreviewImage); - - if(modPreviewImage != NULL) { - Renderer::getInstance().endTexture(rsGlobal, modPreviewImage, false); - } - modPreviewImage = NULL; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] scenarioLogoTexture [%p]\n", __FILE__, + __FUNCTION__, __LINE__, modPreviewImage); + + if (modPreviewImage != NULL) { + Renderer::getInstance().endTexture(rsGlobal, modPreviewImage, false); + } + modPreviewImage = NULL; } void MenuStateMods::cleanupMapPreviewTexture() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //printf("CLEANUP map preview texture\n"); - if(mapPreviewTexture != NULL) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - mapPreviewTexture->end(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - delete mapPreviewTexture; - mapPreviewTexture = NULL; - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // printf("CLEANUP map preview texture\n"); + if (mapPreviewTexture != NULL) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + mapPreviewTexture->end(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + delete mapPreviewTexture; + mapPreviewTexture = NULL; + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); } - void MenuStateMods::render() { - try { - Renderer &renderer= Renderer::getInstance(); - - renderer.renderLine(&lineHorizontal); - renderer.renderLine(&lineVertical); - renderer.renderLine(&lineReturn); - renderer.renderLine(&lineVerticalReturn); - renderer.renderButton(&buttonReturn); - - renderer.renderButton(&buttonInstallTech); - renderer.renderButton(&buttonRemoveTech); - renderer.renderButton(&buttonInstallTileset); - renderer.renderButton(&buttonRemoveTileset); - renderer.renderButton(&buttonInstallMap); - renderer.renderButton(&buttonRemoveMap); - renderer.renderButton(&buttonInstallScenario); - renderer.renderButton(&buttonRemoveScenario); - - renderer.renderButton(&buttonInstalled); - renderer.renderButton(&buttonAvailable); - renderer.renderButton(&buttonConflict); - renderer.renderButton(&buttonOnlyLocal); - - renderer.renderLabel(&modDescrLabel); - if(modInfoSelected!=NULL){ - string tempImage = getPreviewImageFileForMod(modInfoSelected); - if(displayModPreviewImage.find(tempImage) != displayModPreviewImage.end() && - displayModPreviewImage[tempImage] == true) { - if(modPreviewImage == NULL) { - string tempImage = getPreviewImageFileForMod(modInfoSelected); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("### Render tempImage [%s] fileExists(tempImage) = %d\n",tempImage.c_str(),fileExists(tempImage)); - - if(tempImage != "" && fileExists(tempImage) == true) { - cleanupPreviewTexture(); - modPreviewImage = Renderer::findTexture(tempImage); - } - } - if(modPreviewImage != NULL) { - renderer.renderTextureQuad(508,90,485,325,modPreviewImage,1.0f); - } - } - } - - // Render Tech List - renderer.renderLabel(&keyTechScrollBarTitle1); - renderer.renderLabel(&keyTechScrollBarTitle2); - if(keyTechScrollBar.getElementCount() != 0) { - for(int i = keyTechScrollBar.getVisibleStart(); - i <= keyTechScrollBar.getVisibleEnd(); ++i) { - bool alreadyHasTech = (std::find(techTreeFiles.begin(),techTreeFiles.end(),keyTechButtons[i]->getText()) != techTreeFiles.end()); - if(keyTechButtons[i]->getText() == selectedTechName) { - bool lightedOverride = true; - renderer.renderButton(keyTechButtons[i],&WHITE,&lightedOverride); - } - else if(alreadyHasTech == true) { - Vec4f buttonColor = WHITE; - buttonColor.w = 0.75f; - bool remoteHasTech = (techCacheList.find(keyTechButtons[i]->getText()) != techCacheList.end()); - if(remoteHasTech) - { - ModInfo &modInfo = techCacheList[keyTechButtons[i]->getText()]; - if( modInfo.crc==modInfo.localCRC) { - keyTechButtons[i]->setCustomTexture(CoreData::getInstance().getOnServerInstalledTexture()); - } - else { - //printf("modInfo.name=%s modInfo.crc=%s modInfo.localCRC=%s\n",modInfo.name.c_str(),modInfo.crc.c_str(),modInfo.localCRC.c_str()); - keyTechButtons[i]->setCustomTexture(CoreData::getInstance().getOnServerDifferentTexture()); - } - } - else - { - keyTechButtons[i]->setCustomTexture(CoreData::getInstance().getNotOnServerTexture()); - } - renderer.renderButton(keyTechButtons[i],&buttonColor); - } - else { - Vec4f fontColor=Vec4f(200.0f/255.0f, 187.0f/255.0f, 190.0f/255.0f, 0.75f); - //Vec4f fontColor=Vec4f(1.0f, 0.0f, 0.0f, 0.75f); - keyTechButtons[i]->setCustomTexture(CoreData::getInstance().getOnServerTexture()); - renderer.renderButton(keyTechButtons[i],&fontColor); - } - renderer.renderLabel(labelsTech[i]); - } - } - renderer.renderScrollBar(&keyTechScrollBar); - - // Render Tileset List - renderer.renderLabel(&keyTilesetScrollBarTitle1); - if(keyTilesetScrollBar.getElementCount() != 0) { - for(int i = keyTilesetScrollBar.getVisibleStart(); - i <= keyTilesetScrollBar.getVisibleEnd(); ++i) { - bool alreadyHasTileset = (std::find(tilesetFiles.begin(),tilesetFiles.end(),keyTilesetButtons[i]->getText()) != tilesetFiles.end()); - if(keyTilesetButtons[i]->getText() == selectedTilesetName) { - bool lightedOverride = true; - renderer.renderButton(keyTilesetButtons[i],&WHITE,&lightedOverride); - } - else if(alreadyHasTileset == true) { - Vec4f buttonColor = WHITE; - buttonColor.w = 0.75f; - bool remoteHasTileset= (tilesetCacheList.find(keyTilesetButtons[i]->getText()) != tilesetCacheList.end()); - if(remoteHasTileset) - { - ModInfo &modInfo = tilesetCacheList[keyTilesetButtons[i]->getText()]; - - if( modInfo.crc==modInfo.localCRC) { - keyTilesetButtons[i]->setCustomTexture(CoreData::getInstance().getOnServerInstalledTexture()); - } - else { - //printf("modInfo.name=%s modInfo.crc=%s modInfo.localCRC=%s\n",modInfo.name.c_str(),modInfo.crc.c_str(),modInfo.localCRC.c_str()); - //printf("name [%s] modInfo.crc [%s] modInfo.localCRC [%s]\n",modInfo.name.c_str(),modInfo.crc.c_str(),modInfo.localCRC.c_str()); - - keyTilesetButtons[i]->setCustomTexture(CoreData::getInstance().getOnServerDifferentTexture()); - } - } - else - { - keyTilesetButtons[i]->setCustomTexture(CoreData::getInstance().getNotOnServerTexture()); - } - renderer.renderButton(keyTilesetButtons[i],&buttonColor); - } - else { - Vec4f fontColor=Vec4f(200.0f/255.0f, 187.0f/255.0f, 190.0f/255.0f, 0.75f); - keyTilesetButtons[i]->setCustomTexture(CoreData::getInstance().getOnServerTexture()); - renderer.renderButton(keyTilesetButtons[i],&fontColor); - } - } - } - renderer.renderScrollBar(&keyTilesetScrollBar); - - // Render Map list - renderer.renderLabel(&keyMapScrollBarTitle1); - renderer.renderLabel(&keyMapScrollBarTitle2); - if(keyMapScrollBar.getElementCount() != 0) { - for(int i = keyMapScrollBar.getVisibleStart(); - i <= keyMapScrollBar.getVisibleEnd(); ++i) { - string mapNameToRender = keyMapButtons[i]->getText(); - bool alreadyHasMap = (std::find(mapFiles.begin(),mapFiles.end(),mapNameToRender) != mapFiles.end()); - if(keyMapButtons[i]->getText() == selectedMapName) { - bool lightedOverride = true; - renderer.renderButton(keyMapButtons[i],&WHITE,&lightedOverride); - } - else if(alreadyHasMap == true) { - Vec4f buttonColor = WHITE; - buttonColor.w = 0.75f; - bool remoteHasMap = (mapCacheList.find(keyMapButtons[i]->getText()) != mapCacheList.end()); - if(remoteHasMap) - { - ModInfo &modInfo = mapCacheList[keyMapButtons[i]->getText()]; - if( modInfo.crc==modInfo.localCRC) { - keyMapButtons[i]->setCustomTexture(CoreData::getInstance().getOnServerInstalledTexture()); - } - else { - //printf("modInfo.name=%s modInfo.crc=%s modInfo.localCRC=%s\n",modInfo.name.c_str(),modInfo.crc.c_str(),modInfo.localCRC.c_str()); - keyMapButtons[i]->setCustomTexture(CoreData::getInstance().getOnServerDifferentTexture()); - } - } - else - { - keyMapButtons[i]->setCustomTexture(CoreData::getInstance().getNotOnServerTexture()); - } - renderer.renderButton(keyMapButtons[i],&buttonColor); - } - else { - Vec4f fontColor=Vec4f(200.0f/255.0f, 187.0f/255.0f, 190.0f/255.0f, 0.75f); - keyMapButtons[i]->setCustomTexture(CoreData::getInstance().getOnServerTexture()); - renderer.renderButton(keyMapButtons[i],&fontColor); - } - renderer.renderLabel(labelsMap[i]); - } - } - renderer.renderScrollBar(&keyMapScrollBar); - - // Render Scenario List - renderer.renderLabel(&keyScenarioScrollBarTitle1); - if(keyScenarioScrollBar.getElementCount() != 0) { - for(int i = keyScenarioScrollBar.getVisibleStart(); - i <= keyScenarioScrollBar.getVisibleEnd(); ++i) { - if(i >= (int)keyScenarioButtons.size()) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"i >= keyScenarioButtons.size(), i = %d keyScenarioButtons.size() = %d",i,(int)keyScenarioButtons.size()); - throw megaglest_runtime_error(szBuf); - } - bool alreadyHasScenario = (std::find(scenarioFiles.begin(),scenarioFiles.end(),keyScenarioButtons[i]->getText()) != scenarioFiles.end()); - - if(keyScenarioButtons[i]->getText() == selectedScenarioName) { - bool lightedOverride = true; - renderer.renderButton(keyScenarioButtons[i],&WHITE,&lightedOverride); - } - else if(alreadyHasScenario == true) { - Vec4f buttonColor = WHITE; - buttonColor.w = 0.75f; - bool remoteHasScenario= (scenarioCacheList.find(keyScenarioButtons[i]->getText()) != scenarioCacheList.end()); - if(remoteHasScenario) - { - ModInfo &modInfo = scenarioCacheList[keyScenarioButtons[i]->getText()]; - if( modInfo.crc==modInfo.localCRC) { - keyScenarioButtons[i]->setCustomTexture(CoreData::getInstance().getOnServerInstalledTexture()); - } - else { - //printf("modInfo.name=%s modInfo.crc=%s modInfo.localCRC=%s\n",modInfo.name.c_str(),modInfo.crc.c_str(),modInfo.localCRC.c_str()); - keyScenarioButtons[i]->setCustomTexture(CoreData::getInstance().getOnServerDifferentTexture()); - } - } - else - { - keyScenarioButtons[i]->setCustomTexture(CoreData::getInstance().getNotOnServerTexture()); - } - renderer.renderButton(keyScenarioButtons[i],&buttonColor); - } - else { - Vec4f fontColor=Vec4f(200.0f/255.0f, 187.0f/255.0f, 190.0f/255.0f, 0.75f); - keyScenarioButtons[i]->setCustomTexture(CoreData::getInstance().getOnServerTexture()); - renderer.renderButton(keyScenarioButtons[i],&fontColor); - } - } - } - renderer.renderScrollBar(&keyScenarioScrollBar); - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),mutexOwnerId); - if(ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); - if(fileFTPProgressList.empty() == false) { - Lang &lang= Lang::getInstance(); - int xLocation = buttonReturn.getX(); - int yLocation = buttonReturn.getY() - 12; - for(std::map >::iterator iterMap = fileFTPProgressList.begin(); - iterMap != fileFTPProgressList.end(); ++iterMap) { - - string progressLabelPrefix = lang.getString("ModDownloading") + " " + extractFileFromDirectoryPath(iterMap->first) + " "; - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\nRendering file progress with the following prefix [%s]\n",progressLabelPrefix.c_str()); - - if(Renderer::renderText3DEnabled) { - renderer.renderProgressBar3D( - iterMap->second.first, - //10, - //yLocation, - xLocation, - yLocation, - CoreData::getInstance().getDisplayFontSmall3D(), - 185,progressLabelPrefix,false); - } - else { - renderer.renderProgressBar( - iterMap->second.first, - //10, - //yLocation, - xLocation, - yLocation, - CoreData::getInstance().getDisplayFontSmall(), - 185,progressLabelPrefix,false); - } + try { + Renderer &renderer = Renderer::getInstance(); + + renderer.renderLine(&lineHorizontal); + renderer.renderLine(&lineVertical); + renderer.renderLine(&lineReturn); + renderer.renderLine(&lineVerticalReturn); + renderer.renderButton(&buttonReturn); + + renderer.renderButton(&buttonInstallTech); + renderer.renderButton(&buttonRemoveTech); + renderer.renderButton(&buttonInstallTileset); + renderer.renderButton(&buttonRemoveTileset); + renderer.renderButton(&buttonInstallMap); + renderer.renderButton(&buttonRemoveMap); + renderer.renderButton(&buttonInstallScenario); + renderer.renderButton(&buttonRemoveScenario); + + renderer.renderButton(&buttonInstalled); + renderer.renderButton(&buttonAvailable); + renderer.renderButton(&buttonConflict); + renderer.renderButton(&buttonOnlyLocal); + + renderer.renderLabel(&modDescrLabel); + if (modInfoSelected != NULL) { + string tempImage = getPreviewImageFileForMod(modInfoSelected); + if (displayModPreviewImage.find(tempImage) != + displayModPreviewImage.end() && + displayModPreviewImage[tempImage] == true) { + if (modPreviewImage == NULL) { + string tempImage = getPreviewImageFileForMod(modInfoSelected); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("### Render tempImage [%s] fileExists(tempImage) = %d\n", + tempImage.c_str(), fileExists(tempImage)); + + if (tempImage != "" && fileExists(tempImage) == true) { + cleanupPreviewTexture(); + modPreviewImage = Renderer::findTexture(tempImage); + } + } + if (modPreviewImage != NULL) { + renderer.renderTextureQuad(508, 90, 485, 325, modPreviewImage, 1.0f); + } + } + } - yLocation -= 14; + // Render Tech List + renderer.renderLabel(&keyTechScrollBarTitle1); + renderer.renderLabel(&keyTechScrollBarTitle2); + if (keyTechScrollBar.getElementCount() != 0) { + for (int i = keyTechScrollBar.getVisibleStart(); + i <= keyTechScrollBar.getVisibleEnd(); ++i) { + bool alreadyHasTech = + (std::find(techTreeFiles.begin(), techTreeFiles.end(), + keyTechButtons[i]->getText()) != techTreeFiles.end()); + if (keyTechButtons[i]->getText() == selectedTechName) { + bool lightedOverride = true; + renderer.renderButton(keyTechButtons[i], &WHITE, &lightedOverride); + } else if (alreadyHasTech == true) { + Vec4f buttonColor = WHITE; + buttonColor.w = 0.75f; + bool remoteHasTech = + (techCacheList.find(keyTechButtons[i]->getText()) != + techCacheList.end()); + if (remoteHasTech) { + ModInfo &modInfo = techCacheList[keyTechButtons[i]->getText()]; + if (modInfo.crc == modInfo.localCRC) { + keyTechButtons[i]->setCustomTexture( + CoreData::getInstance().getOnServerInstalledTexture()); + } else { + // printf("modInfo.name=%s modInfo.crc=%s + // modInfo.localCRC=%s\n",modInfo.name.c_str(),modInfo.crc.c_str(),modInfo.localCRC.c_str()); + keyTechButtons[i]->setCustomTexture( + CoreData::getInstance().getOnServerDifferentTexture()); } + } else { + keyTechButtons[i]->setCustomTexture( + CoreData::getInstance().getNotOnServerTexture()); + } + renderer.renderButton(keyTechButtons[i], &buttonColor); + } else { + Vec4f fontColor = + Vec4f(200.0f / 255.0f, 187.0f / 255.0f, 190.0f / 255.0f, 0.75f); + // Vec4f fontColor=Vec4f(1.0f, 0.0f, 0.0f, 0.75f); + keyTechButtons[i]->setCustomTexture( + CoreData::getInstance().getOnServerTexture()); + renderer.renderButton(keyTechButtons[i], &fontColor); } - safeMutexFTPProgress.ReleaseLock(); - - renderer.renderConsole(&console,consoleNormal,3); - - if(mainMessageBox.getEnabled()) { - renderer.renderMessageBox(&mainMessageBox); - } - - if(modMenuState!=mmst_None) { - if(oldMenuState!=modMenuState) - { - Lang &lang= Lang::getInstance(); - if(modMenuState== mmst_Loading){ - pleaseWaitLabel.setText(lang.getString("GettingModlistFromMasterserver")); - } - else if(modMenuState== mmst_CalculatingCRC){ - pleaseWaitLabel.setText(lang.getString("PleaseWaitCalculatingCRC")); - } - oldMenuState=modMenuState; - } - float anim= GraphicComponent::getAnim(); - if(anim < 0.5f) { - anim = 1.f - anim; - } - Vec4f colorWithAlpha = Vec4f(ORANGE.x,ORANGE.y,ORANGE.z,anim); - renderer.renderLabel(&pleaseWaitLabel,&colorWithAlpha); - } - if(validMapPreview){ - if(mapPreviewTexture != NULL) { - renderer.renderTextureQuad(5,185,150,150,mapPreviewTexture,1.0f); - } - if(enableMapPreview && (mapPreview.hasFileLoaded() == true)) { - - int mouseX = mainMenu->getMouseX(); - int mouseY = mainMenu->getMouseY(); - int mouse2dAnim = mainMenu->getMouse2dAnim(); - - if(mapPreviewTexture == NULL) { - renderer.renderMouse2d(mouseX, mouseY, mouse2dAnim); - renderer.renderMapPreview(&mapPreview, true, 10, 350, &mapPreviewTexture); - } - } - } - - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - throw megaglest_runtime_error(szBuf); - } -} - -void MenuStateMods::layoutButtons(GraphicScrollBar * scrollBar,UserButtons* buttons, GraphicLabels* labels){ - if (scrollBar->getElementCount() != 0) { - for (int i = scrollBar->getVisibleStart(); - i <= scrollBar->getVisibleEnd(); ++i) { - if(i >= (int)buttons->size()) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"i >= buttons->size(), i = %d, buttons->size() = %d",i,(int)buttons->size()); - throw megaglest_runtime_error(szBuf); - } - (*buttons)[i]->setY(keyButtonsYBase - keyButtonsLineHeight * (i - scrollBar->getVisibleStart())); - if (labels != NULL) { - (*labels)[i]->setY(keyButtonsYBase - keyButtonsLineHeight * (i - scrollBar->getVisibleStart())); - } - } - } -} - -void MenuStateMods::update() { - Chrono chrono; - chrono.start(); - - layoutButtons(&keyMapScrollBar, &keyMapButtons, &labelsMap); - layoutButtons(&keyTechScrollBar, &keyTechButtons, &labelsTech); - layoutButtons(&keyTilesetScrollBar, &keyTilesetButtons, NULL); - layoutButtons(&keyScenarioScrollBar, &keyScenarioButtons, NULL); - - console.update(); -} - -void MenuStateMods::keyDown(SDL_KeyboardEvent key) { - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - //if(key == configKeys.getCharKey("ShowFullConsole")) { - if(isKeyPressed(configKeys.getSDLKey("ShowFullConsole"),key) == true) { - showFullConsole= true; - } -} - -void MenuStateMods::keyPress(SDL_KeyboardEvent c) { -} - -void MenuStateMods::keyUp(SDL_KeyboardEvent key) { - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - //if(key== configKeys.getCharKey("ShowFullConsole")) { - if(isKeyPressed(configKeys.getSDLKey("ShowFullConsole"),key) == true) { - showFullConsole= false; - } -} - -void MenuStateMods::showMessageBox(const string &text, const string &header, bool toggle) { - if(toggle == false) { - mainMessageBox.setEnabled(false); - } - - if(mainMessageBox.getEnabled() == false) { - mainMessageBox.setText(text); - mainMessageBox.setHeader(header); - mainMessageBox.setEnabled(true); - } - else{ - mainMessageBox.setEnabled(false); - } -} - -void MenuStateMods::FTPClient_CallbackEvent(string itemName, - FTP_Client_CallbackType type, pair result,void *userdata) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - Lang &lang= Lang::getInstance(); - if(type == ftp_cct_DownloadProgress) { - FTPClientCallbackInterface::FtpProgressStats *stats = (FTPClientCallbackInterface::FtpProgressStats *)userdata; - if(stats != NULL) { - int fileProgress = 0; - if(stats->download_total > 0) { - fileProgress = ((stats->download_now / stats->download_total) * 100.0); + renderer.renderLabel(labelsTech[i]); + } + } + renderer.renderScrollBar(&keyTechScrollBar); + + // Render Tileset List + renderer.renderLabel(&keyTilesetScrollBarTitle1); + if (keyTilesetScrollBar.getElementCount() != 0) { + for (int i = keyTilesetScrollBar.getVisibleStart(); + i <= keyTilesetScrollBar.getVisibleEnd(); ++i) { + bool alreadyHasTileset = + (std::find(tilesetFiles.begin(), tilesetFiles.end(), + keyTilesetButtons[i]->getText()) != tilesetFiles.end()); + if (keyTilesetButtons[i]->getText() == selectedTilesetName) { + bool lightedOverride = true; + renderer.renderButton(keyTilesetButtons[i], &WHITE, &lightedOverride); + } else if (alreadyHasTileset == true) { + Vec4f buttonColor = WHITE; + buttonColor.w = 0.75f; + bool remoteHasTileset = + (tilesetCacheList.find(keyTilesetButtons[i]->getText()) != + tilesetCacheList.end()); + if (remoteHasTileset) { + ModInfo &modInfo = + tilesetCacheList[keyTilesetButtons[i]->getText()]; + + if (modInfo.crc == modInfo.localCRC) { + keyTilesetButtons[i]->setCustomTexture( + CoreData::getInstance().getOnServerInstalledTexture()); + } else { + // printf("modInfo.name=%s modInfo.crc=%s + // modInfo.localCRC=%s\n",modInfo.name.c_str(),modInfo.crc.c_str(),modInfo.localCRC.c_str()); + // printf("name [%s] modInfo.crc [%s] modInfo.localCRC + // [%s]\n",modInfo.name.c_str(),modInfo.crc.c_str(),modInfo.localCRC.c_str()); + + keyTilesetButtons[i]->setCustomTexture( + CoreData::getInstance().getOnServerDifferentTexture()); } - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Got FTP Callback for [%s] current file [%s] fileProgress = %d [now = %f, total = %f]\n",itemName.c_str(),stats->currentFilename.c_str(), fileProgress,stats->download_now,stats->download_total); - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),mutexOwnerId); - if(ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); - pair lastProgress = fileFTPProgressList[itemName]; - fileFTPProgressList[itemName] = pair(fileProgress,stats->currentFilename); - safeMutexFTPProgress.ReleaseLock(); + } else { + keyTilesetButtons[i]->setCustomTexture( + CoreData::getInstance().getNotOnServerTexture()); + } + renderer.renderButton(keyTilesetButtons[i], &buttonColor); + } else { + Vec4f fontColor = + Vec4f(200.0f / 255.0f, 187.0f / 255.0f, 190.0f / 255.0f, 0.75f); + keyTilesetButtons[i]->setCustomTexture( + CoreData::getInstance().getOnServerTexture()); + renderer.renderButton(keyTilesetButtons[i], &fontColor); } + } } - else if(type == ftp_cct_ExtractProgress) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Got FTP extract Callback for [%s] result = %d [%s]\n",itemName.c_str(),result.first,result.second.c_str()); - //printf("Got FTP extract Callback for [%s] result = %d [%s]\n",itemName.c_str(),result.first,result.second.c_str()); - - if(userdata == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("DataMissingExtractDownloadMod").c_str(),itemName.c_str()); - //printf("%s\n",szBuf); - console.addLine(szBuf,true); - } - else { - char *szBuf = (char *)userdata; - //printf("%s\n",szBuf); - console.addLine(szBuf); - } - } - else if(type == ftp_cct_File) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Got FTP Callback for [%s] result = %d [%s]\n",itemName.c_str(),result.first,result.second.c_str()); - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),mutexOwnerId); - if(ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); - fileFTPProgressList.erase(itemName); - safeMutexFTPProgress.ReleaseLock(); - - //printf("### downloaded file [%s] result = %d\n",itemName.c_str(),result.first); - - if(result.first == ftp_crt_SUCCESS) { - displayModPreviewImage[itemName] = true; + renderer.renderScrollBar(&keyTilesetScrollBar); + + // Render Map list + renderer.renderLabel(&keyMapScrollBarTitle1); + renderer.renderLabel(&keyMapScrollBarTitle2); + if (keyMapScrollBar.getElementCount() != 0) { + for (int i = keyMapScrollBar.getVisibleStart(); + i <= keyMapScrollBar.getVisibleEnd(); ++i) { + string mapNameToRender = keyMapButtons[i]->getText(); + bool alreadyHasMap = (std::find(mapFiles.begin(), mapFiles.end(), + mapNameToRender) != mapFiles.end()); + if (keyMapButtons[i]->getText() == selectedMapName) { + bool lightedOverride = true; + renderer.renderButton(keyMapButtons[i], &WHITE, &lightedOverride); + } else if (alreadyHasMap == true) { + Vec4f buttonColor = WHITE; + buttonColor.w = 0.75f; + bool remoteHasMap = (mapCacheList.find(keyMapButtons[i]->getText()) != + mapCacheList.end()); + if (remoteHasMap) { + ModInfo &modInfo = mapCacheList[keyMapButtons[i]->getText()]; + if (modInfo.crc == modInfo.localCRC) { + keyMapButtons[i]->setCustomTexture( + CoreData::getInstance().getOnServerInstalledTexture()); + } else { + // printf("modInfo.name=%s modInfo.crc=%s + // modInfo.localCRC=%s\n",modInfo.name.c_str(),modInfo.crc.c_str(),modInfo.localCRC.c_str()); + keyMapButtons[i]->setCustomTexture( + CoreData::getInstance().getOnServerDifferentTexture()); + } + } else { + keyMapButtons[i]->setCustomTexture( + CoreData::getInstance().getNotOnServerTexture()); + } + renderer.renderButton(keyMapButtons[i], &buttonColor); + } else { + Vec4f fontColor = + Vec4f(200.0f / 255.0f, 187.0f / 255.0f, 190.0f / 255.0f, 0.75f); + keyMapButtons[i]->setCustomTexture( + CoreData::getInstance().getOnServerTexture()); + renderer.renderButton(keyMapButtons[i], &fontColor); } + renderer.renderLabel(labelsMap[i]); + } } - - else if(type == ftp_cct_Map) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Got FTP Callback for [%s] result = %d [%s]\n",itemName.c_str(),result.first,result.second.c_str()); - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),mutexOwnerId); - if(ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); - fileFTPProgressList.erase(itemName); - safeMutexFTPProgress.ReleaseLock(); - selectedMapName = ""; - buttonInstallMap.setEnabled(true); - - if(result.first == ftp_crt_SUCCESS) { - refreshMaps(); - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModDownloadMapSuccess").c_str(),itemName.c_str()); - console.addLine(szBuf,true); + renderer.renderScrollBar(&keyMapScrollBar); + + // Render Scenario List + renderer.renderLabel(&keyScenarioScrollBarTitle1); + if (keyScenarioScrollBar.getElementCount() != 0) { + for (int i = keyScenarioScrollBar.getVisibleStart(); + i <= keyScenarioScrollBar.getVisibleEnd(); ++i) { + if (i >= (int)keyScenarioButtons.size()) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "i >= keyScenarioButtons.size(), i = %d " + "keyScenarioButtons.size() = %d", + i, (int)keyScenarioButtons.size()); + throw megaglest_runtime_error(szBuf); } - else { - curl_version_info_data *curlVersion= curl_version_info(CURLVERSION_NOW); - - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModDownloadMapFail").c_str(),itemName.c_str(),curlVersion->version,result.second.c_str()); - console.addLine(szBuf,true); + bool alreadyHasScenario = + (std::find(scenarioFiles.begin(), scenarioFiles.end(), + keyScenarioButtons[i]->getText()) != + scenarioFiles.end()); + + if (keyScenarioButtons[i]->getText() == selectedScenarioName) { + bool lightedOverride = true; + renderer.renderButton(keyScenarioButtons[i], &WHITE, + &lightedOverride); + } else if (alreadyHasScenario == true) { + Vec4f buttonColor = WHITE; + buttonColor.w = 0.75f; + bool remoteHasScenario = + (scenarioCacheList.find(keyScenarioButtons[i]->getText()) != + scenarioCacheList.end()); + if (remoteHasScenario) { + ModInfo &modInfo = + scenarioCacheList[keyScenarioButtons[i]->getText()]; + if (modInfo.crc == modInfo.localCRC) { + keyScenarioButtons[i]->setCustomTexture( + CoreData::getInstance().getOnServerInstalledTexture()); + } else { + // printf("modInfo.name=%s modInfo.crc=%s + // modInfo.localCRC=%s\n",modInfo.name.c_str(),modInfo.crc.c_str(),modInfo.localCRC.c_str()); + keyScenarioButtons[i]->setCustomTexture( + CoreData::getInstance().getOnServerDifferentTexture()); + } + } else { + keyScenarioButtons[i]->setCustomTexture( + CoreData::getInstance().getNotOnServerTexture()); + } + renderer.renderButton(keyScenarioButtons[i], &buttonColor); + } else { + Vec4f fontColor = + Vec4f(200.0f / 255.0f, 187.0f / 255.0f, 190.0f / 255.0f, 0.75f); + keyScenarioButtons[i]->setCustomTexture( + CoreData::getInstance().getOnServerTexture()); + renderer.renderButton(keyScenarioButtons[i], &fontColor); } + } } - else if(type == ftp_cct_Tileset) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Got FTP Callback for [%s] result = %d [%s]\n",itemName.c_str(),result.first,result.second.c_str()); + renderer.renderScrollBar(&keyScenarioScrollBar); + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL), + mutexOwnerId); + if (ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) + ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); + if (fileFTPProgressList.empty() == false) { + Lang &lang = Lang::getInstance(); + int xLocation = buttonReturn.getX(); + int yLocation = buttonReturn.getY() - 12; + for (std::map>::iterator iterMap = + fileFTPProgressList.begin(); + iterMap != fileFTPProgressList.end(); ++iterMap) { + + string progressLabelPrefix = + lang.getString("ModDownloading") + " " + + extractFileFromDirectoryPath(iterMap->first) + " "; + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\nRendering file + // progress with the following prefix + // [%s]\n",progressLabelPrefix.c_str()); + + if (Renderer::renderText3DEnabled) { + renderer.renderProgressBar3D( + iterMap->second.first, + // 10, + // yLocation, + xLocation, yLocation, + CoreData::getInstance().getDisplayFontSmall3D(), 185, + progressLabelPrefix, false); + } else { + renderer.renderProgressBar( + iterMap->second.first, + // 10, + // yLocation, + xLocation, yLocation, + CoreData::getInstance().getDisplayFontSmall(), 185, + progressLabelPrefix, false); + } - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),mutexOwnerId); - if(ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); - fileFTPProgressList.erase(itemName); - safeMutexFTPProgress.ReleaseLock(true); + yLocation -= 14; + } + } + safeMutexFTPProgress.ReleaseLock(); - selectedTilesetName = ""; - buttonInstallTileset.setEnabled(true); + renderer.renderConsole(&console, consoleNormal, 3); - if(result.first == ftp_crt_SUCCESS) { - refreshTilesets(); + if (mainMessageBox.getEnabled()) { + renderer.renderMessageBox(&mainMessageBox); + } - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModDownloadTilesetSuccess").c_str(),itemName.c_str()); - console.addLine(szBuf,true); - // END + if (modMenuState != mmst_None) { + if (oldMenuState != modMenuState) { + Lang &lang = Lang::getInstance(); + if (modMenuState == mmst_Loading) { + pleaseWaitLabel.setText( + lang.getString("GettingModlistFromMasterserver")); + } else if (modMenuState == mmst_CalculatingCRC) { + pleaseWaitLabel.setText(lang.getString("PleaseWaitCalculatingCRC")); } - else { - curl_version_info_data *curlVersion= curl_version_info(CURLVERSION_NOW); - - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModDownloadTilesetFail").c_str(),itemName.c_str(),curlVersion->version,result.second.c_str()); - console.addLine(szBuf,true); + oldMenuState = modMenuState; + } + float anim = GraphicComponent::getAnim(); + if (anim < 0.5f) { + anim = 1.f - anim; + } + Vec4f colorWithAlpha = Vec4f(ORANGE.x, ORANGE.y, ORANGE.z, anim); + renderer.renderLabel(&pleaseWaitLabel, &colorWithAlpha); + } + if (validMapPreview) { + if (mapPreviewTexture != NULL) { + renderer.renderTextureQuad(5, 185, 150, 150, mapPreviewTexture, 1.0f); + } + if (enableMapPreview && (mapPreview.hasFileLoaded() == true)) { + + int mouseX = mainMenu->getMouseX(); + int mouseY = mainMenu->getMouseY(); + int mouse2dAnim = mainMenu->getMouse2dAnim(); + + if (mapPreviewTexture == NULL) { + renderer.renderMouse2d(mouseX, mouseY, mouse2dAnim); + renderer.renderMapPreview(&mapPreview, true, 10, 350, + &mapPreviewTexture); } + } } - else if(type == ftp_cct_Techtree) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Got FTP Callback for [%s] result = %d [%s]\n",itemName.c_str(),result.first,result.second.c_str()); - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),mutexOwnerId); - if(ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); - fileFTPProgressList.erase(itemName); - safeMutexFTPProgress.ReleaseLock(true); - selectedTechName = ""; - buttonInstallTech.setEnabled(true); - - if(result.first == ftp_crt_SUCCESS) { - - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModDownloadTechSuccess").c_str(),itemName.c_str()); - console.addLine(szBuf,true); - - // START - // Clear the CRC Cache if it is populated - safeMutexFTPProgress.Lock(); - Checksum::clearFileCache(); - - vector paths = Config::getInstance().getPathListForType(ptTechs); - string pathSearchString = string("/") + itemName + string("/*"); - const string filterFileExt = ".xml"; - clearFolderTreeContentsCheckSum(paths, pathSearchString, filterFileExt); - clearFolderTreeContentsCheckSumList(paths, pathSearchString, filterFileExt); - - // Refresh CRC - Config &config = Config::getInstance(); - getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), string("/") + itemName + string("/*"), ".xml", NULL, true); - safeMutexFTPProgress.ReleaseLock(); - - refreshTechs(); - // END - } - else { - curl_version_info_data *curlVersion= curl_version_info(CURLVERSION_NOW); + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] error [%s]\n", __FILE__, __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + throw megaglest_runtime_error(szBuf); + } +} - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModDownloadTechFail").c_str(),itemName.c_str(),curlVersion->version,result.second.c_str()); - console.addLine(szBuf,true); - } +void MenuStateMods::layoutButtons(GraphicScrollBar *scrollBar, + UserButtons *buttons, GraphicLabels *labels) { + if (scrollBar->getElementCount() != 0) { + for (int i = scrollBar->getVisibleStart(); i <= scrollBar->getVisibleEnd(); + ++i) { + if (i >= (int)buttons->size()) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "i >= buttons->size(), i = %d, buttons->size() = %d", i, + (int)buttons->size()); + throw megaglest_runtime_error(szBuf); + } + (*buttons)[i]->setY(keyButtonsYBase - + keyButtonsLineHeight * + (i - scrollBar->getVisibleStart())); + if (labels != NULL) { + (*labels)[i]->setY(keyButtonsYBase - + keyButtonsLineHeight * + (i - scrollBar->getVisibleStart())); + } } - else if(type == ftp_cct_Scenario) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Got FTP Callback for [%s] result = %d [%s]\n",itemName.c_str(),result.first,result.second.c_str()); + } +} - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),mutexOwnerId); - if(ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); - fileFTPProgressList.erase(itemName); - safeMutexFTPProgress.ReleaseLock(true); +void MenuStateMods::update() { + Chrono chrono; + chrono.start(); - selectedScenarioName = ""; - buttonInstallScenario.setEnabled(true); + layoutButtons(&keyMapScrollBar, &keyMapButtons, &labelsMap); + layoutButtons(&keyTechScrollBar, &keyTechButtons, &labelsTech); + layoutButtons(&keyTilesetScrollBar, &keyTilesetButtons, NULL); + layoutButtons(&keyScenarioScrollBar, &keyScenarioButtons, NULL); - if(result.first == ftp_crt_SUCCESS) { - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModDownloadScenarioSuccess").c_str(),itemName.c_str()); - console.addLine(szBuf,true); + console.update(); +} - // START - // Clear the CRC Cache if it is populated - // - // Clear the CRC file Cache - safeMutexFTPProgress.Lock(); - Checksum::clearFileCache(); +void MenuStateMods::keyDown(SDL_KeyboardEvent key) { + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + // if(key == configKeys.getCharKey("ShowFullConsole")) { + if (isKeyPressed(configKeys.getSDLKey("ShowFullConsole"), key) == true) { + showFullConsole = true; + } +} - vector paths = Config::getInstance().getPathListForType(ptScenarios); - string pathSearchString = string("/") + itemName + string("/*"); - const string filterFileExt = ".xml"; - clearFolderTreeContentsCheckSum(paths, pathSearchString, filterFileExt); - clearFolderTreeContentsCheckSumList(paths, pathSearchString, filterFileExt); +void MenuStateMods::keyPress(SDL_KeyboardEvent c) {} - // Refresh CRC - Config &config = Config::getInstance(); - getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptScenarios,""), string("/") + itemName + string("/*"), ".xml", NULL, true); - safeMutexFTPProgress.ReleaseLock(); +void MenuStateMods::keyUp(SDL_KeyboardEvent key) { + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + // if(key== configKeys.getCharKey("ShowFullConsole")) { + if (isKeyPressed(configKeys.getSDLKey("ShowFullConsole"), key) == true) { + showFullConsole = false; + } +} - refreshScenarios(); - // END - } - else { - curl_version_info_data *curlVersion= curl_version_info(CURLVERSION_NOW); +void MenuStateMods::showMessageBox(const string &text, const string &header, + bool toggle) { + if (toggle == false) { + mainMessageBox.setEnabled(false); + } + + if (mainMessageBox.getEnabled() == false) { + mainMessageBox.setText(text); + mainMessageBox.setHeader(header); + mainMessageBox.setEnabled(true); + } else { + mainMessageBox.setEnabled(false); + } +} - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("ModDownloadScenarioFail").c_str(),itemName.c_str(),curlVersion->version,result.second.c_str()); - console.addLine(szBuf,true); - } +void MenuStateMods::FTPClient_CallbackEvent( + string itemName, FTP_Client_CallbackType type, + pair result, void *userdata) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + Lang &lang = Lang::getInstance(); + if (type == ftp_cct_DownloadProgress) { + FTPClientCallbackInterface::FtpProgressStats *stats = + (FTPClientCallbackInterface::FtpProgressStats *)userdata; + if (stats != NULL) { + int fileProgress = 0; + if (stats->download_total > 0) { + fileProgress = ((stats->download_now / stats->download_total) * 100.0); + } + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Got FTP Callback for [%s] + // current file [%s] fileProgress = %d [now = %f, total = + // %f]\n",itemName.c_str(),stats->currentFilename.c_str(), + // fileProgress,stats->download_now,stats->download_total); + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + mutexOwnerId); + if (ftpClientThread != NULL && + ftpClientThread->getProgressMutex() != NULL) + ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); + pair lastProgress = fileFTPProgressList[itemName]; + fileFTPProgressList[itemName] = + pair(fileProgress, stats->currentFilename); + safeMutexFTPProgress.ReleaseLock(); } - + } else if (type == ftp_cct_ExtractProgress) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Got FTP extract Callback for [%s] result = %d [%s]\n", + itemName.c_str(), result.first, result.second.c_str()); + // printf("Got FTP extract Callback for [%s] result = %d + // [%s]\n",itemName.c_str(),result.first,result.second.c_str()); + + if (userdata == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("DataMissingExtractDownloadMod").c_str(), + itemName.c_str()); + // printf("%s\n",szBuf); + console.addLine(szBuf, true); + } else { + char *szBuf = (char *)userdata; + // printf("%s\n",szBuf); + console.addLine(szBuf); + } + } else if (type == ftp_cct_File) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Got FTP Callback for [%s] result = %d [%s]\n", itemName.c_str(), + result.first, result.second.c_str()); + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL), + mutexOwnerId); + if (ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) + ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); + fileFTPProgressList.erase(itemName); + safeMutexFTPProgress.ReleaseLock(); + + // printf("### downloaded file [%s] result = + // %d\n",itemName.c_str(),result.first); + + if (result.first == ftp_crt_SUCCESS) { + displayModPreviewImage[itemName] = true; + } + } + + else if (type == ftp_cct_Map) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Got FTP Callback for [%s] result = %d [%s]\n", itemName.c_str(), + result.first, result.second.c_str()); + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL), + mutexOwnerId); + if (ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) + ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); + fileFTPProgressList.erase(itemName); + safeMutexFTPProgress.ReleaseLock(); + selectedMapName = ""; + buttonInstallMap.setEnabled(true); + + if (result.first == ftp_crt_SUCCESS) { + refreshMaps(); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, lang.getString("ModDownloadMapSuccess").c_str(), + itemName.c_str()); + console.addLine(szBuf, true); + } else { + curl_version_info_data *curlVersion = curl_version_info(CURLVERSION_NOW); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, lang.getString("ModDownloadMapFail").c_str(), + itemName.c_str(), curlVersion->version, result.second.c_str()); + console.addLine(szBuf, true); + } + } else if (type == ftp_cct_Tileset) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Got FTP Callback for [%s] result = %d [%s]\n", itemName.c_str(), + result.first, result.second.c_str()); + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL), + mutexOwnerId); + if (ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) + ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); + fileFTPProgressList.erase(itemName); + safeMutexFTPProgress.ReleaseLock(true); + + selectedTilesetName = ""; + buttonInstallTileset.setEnabled(true); + + if (result.first == ftp_crt_SUCCESS) { + refreshTilesets(); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, lang.getString("ModDownloadTilesetSuccess").c_str(), + itemName.c_str()); + console.addLine(szBuf, true); + // END + } else { + curl_version_info_data *curlVersion = curl_version_info(CURLVERSION_NOW); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, lang.getString("ModDownloadTilesetFail").c_str(), + itemName.c_str(), curlVersion->version, result.second.c_str()); + console.addLine(szBuf, true); + } + } else if (type == ftp_cct_Techtree) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Got FTP Callback for [%s] result = %d [%s]\n", itemName.c_str(), + result.first, result.second.c_str()); + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL), + mutexOwnerId); + if (ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) + ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); + fileFTPProgressList.erase(itemName); + safeMutexFTPProgress.ReleaseLock(true); + + selectedTechName = ""; + buttonInstallTech.setEnabled(true); + + if (result.first == ftp_crt_SUCCESS) { + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, lang.getString("ModDownloadTechSuccess").c_str(), + itemName.c_str()); + console.addLine(szBuf, true); + + // START + // Clear the CRC Cache if it is populated + safeMutexFTPProgress.Lock(); + Checksum::clearFileCache(); + + vector paths = Config::getInstance().getPathListForType(ptTechs); + string pathSearchString = string("/") + itemName + string("/*"); + const string filterFileExt = ".xml"; + clearFolderTreeContentsCheckSum(paths, pathSearchString, filterFileExt); + clearFolderTreeContentsCheckSumList(paths, pathSearchString, + filterFileExt); + + // Refresh CRC + Config &config = Config::getInstance(); + getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTechs, ""), + string("/") + itemName + string("/*"), ".xml", NULL, true); + safeMutexFTPProgress.ReleaseLock(); + + refreshTechs(); + // END + } else { + curl_version_info_data *curlVersion = curl_version_info(CURLVERSION_NOW); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, lang.getString("ModDownloadTechFail").c_str(), + itemName.c_str(), curlVersion->version, result.second.c_str()); + console.addLine(szBuf, true); + } + } else if (type == ftp_cct_Scenario) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Got FTP Callback for [%s] result = %d [%s]\n", itemName.c_str(), + result.first, result.second.c_str()); + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL), + mutexOwnerId); + if (ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) + ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); + fileFTPProgressList.erase(itemName); + safeMutexFTPProgress.ReleaseLock(true); + + selectedScenarioName = ""; + buttonInstallScenario.setEnabled(true); + + if (result.first == ftp_crt_SUCCESS) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("ModDownloadScenarioSuccess").c_str(), + itemName.c_str()); + console.addLine(szBuf, true); + + // START + // Clear the CRC Cache if it is populated + // + // Clear the CRC file Cache + safeMutexFTPProgress.Lock(); + Checksum::clearFileCache(); + + vector paths = + Config::getInstance().getPathListForType(ptScenarios); + string pathSearchString = string("/") + itemName + string("/*"); + const string filterFileExt = ".xml"; + clearFolderTreeContentsCheckSum(paths, pathSearchString, filterFileExt); + clearFolderTreeContentsCheckSumList(paths, pathSearchString, + filterFileExt); + + // Refresh CRC + Config &config = Config::getInstance(); + getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptScenarios, ""), + string("/") + itemName + string("/*"), ".xml", NULL, true); + safeMutexFTPProgress.ReleaseLock(); + + refreshScenarios(); + // END + } else { + curl_version_info_data *curlVersion = curl_version_info(CURLVERSION_NOW); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, lang.getString("ModDownloadScenarioFail").c_str(), + itemName.c_str(), curlVersion->version, result.second.c_str()); + console.addLine(szBuf, true); + } + } } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/menu/menu_state_mods.h b/source/glest_game/menu/menu_state_mods.h index 74406eb31..e63dcfec8 100644 --- a/source/glest_game/menu/menu_state_mods.h +++ b/source/glest_game/menu/menu_state_mods.h @@ -12,213 +12,215 @@ #ifndef MENU_STATE_MODS_H_ #define MENU_STATE_MODS_H_ +#include "leak_dumper.h" #include "main_menu.h" #include "map_preview.h" #include "miniftpclient.h" #include #include -#include "leak_dumper.h" -namespace Glest { namespace Game { +namespace Glest { +namespace Game { enum FTPMessageType { - ftpmsg_None, - ftpmsg_GetMap, - ftpmsg_GetTileset, - ftpmsg_GetTechtree, - ftpmsg_GetScenario, - - ftpmsg_ReplaceMap, - ftpmsg_ReplaceTileset, - ftpmsg_ReplaceTechtree, - ftpmsg_ReplaceScenario, - - ftpmsg_Quit + ftpmsg_None, + ftpmsg_GetMap, + ftpmsg_GetTileset, + ftpmsg_GetTechtree, + ftpmsg_GetScenario, + + ftpmsg_ReplaceMap, + ftpmsg_ReplaceTileset, + ftpmsg_ReplaceTechtree, + ftpmsg_ReplaceScenario, + + ftpmsg_Quit }; -enum ModMenuState { - mmst_None, - mmst_Loading, - mmst_CalculatingCRC -}; +enum ModMenuState { mmst_None, mmst_Loading, mmst_CalculatingCRC }; -typedef vector UserButtons; -typedef vector GraphicLabels; +typedef vector UserButtons; +typedef vector GraphicLabels; // =============================== // class MenuStateMods // =============================== -class MenuStateMods: public MenuState, public FTPClientCallbackInterface, public SimpleTaskCallbackInterface { +class MenuStateMods : public MenuState, + public FTPClientCallbackInterface, + public SimpleTaskCallbackInterface { private: + GraphicButton buttonReturn; + GraphicLine lineHorizontal; + GraphicLine lineVertical; + GraphicLine lineReturn; + GraphicLine lineVerticalReturn; + + GraphicMessageBox mainMessageBox; + FTPMessageType mainMessageBoxState; + + int techInfoXPos; + int mapInfoXPos; + int tilesetInfoXPos; + int scenarioInfoXPos; + int labelWidth; + int scrollListsYPos; + int listBoxLength; + + GraphicButton buttonInstallTech; + GraphicButton buttonRemoveTech; + GraphicLabel keyTechScrollBarTitle1; + GraphicLabel keyTechScrollBarTitle2; + GraphicScrollBar keyTechScrollBar; + UserButtons keyTechButtons; + GraphicLabels labelsTech; + + GraphicButton buttonInstallTileset; + GraphicButton buttonRemoveTileset; + GraphicLabel keyTilesetScrollBarTitle1; + GraphicScrollBar keyTilesetScrollBar; + UserButtons keyTilesetButtons; + + GraphicButton buttonInstallMap; + GraphicButton buttonRemoveMap; + GraphicLabel keyMapScrollBarTitle1; + GraphicLabel keyMapScrollBarTitle2; + GraphicScrollBar keyMapScrollBar; + UserButtons keyMapButtons; + GraphicLabels labelsMap; + + GraphicButton buttonInstallScenario; + GraphicButton buttonRemoveScenario; + GraphicLabel keyScenarioScrollBarTitle1; + GraphicLabel keyScenarioScrollBarTitle2; + GraphicScrollBar keyScenarioScrollBar; + UserButtons keyScenarioButtons; + + GraphicLabel modDescrLabel; + Texture2D *modPreviewImage; + ModInfo *modInfoSelected; + map displayModPreviewImage; + + GraphicButton buttonInstalled; + GraphicButton buttonAvailable; + GraphicButton buttonConflict; + GraphicButton buttonOnlyLocal; + + GraphicLabel pleaseWaitLabel; + ModMenuState modMenuState; + ModMenuState oldMenuState; + + bool enableMapPreview; + bool validMapPreview; + MapInfo mapInfo; + MapPreview mapPreview; + Texture2D *mapPreviewTexture; + + int keyButtonsToRender; + int keyButtonsYBase; + int keyButtonsXBase; + int keyButtonsLineHeight; + int keyButtonsHeight; + int keyButtonsWidth; + int keyButtonsWidthTech; + int keyButtonsWidthMap; + int keyButtonsWidthTil; + int keyButtonsWidthScen; + + // Console console; + bool showFullConsole; + + string selectedTechName; + std::vector techListRemote; + std::map techCacheList; + vector techTreeFiles; + vector techTreeFilesUserData; + + string selectedTilesetName; + std::vector tilesetListRemote; + std::map tilesetCacheList; + vector tilesetFiles; + vector tilesetFilesUserData; + + string selectedMapName; + std::vector mapListRemote; + std::map mapCacheList; + vector mapFiles; + vector mapFilesUserData; + + string selectedScenarioName; + std::vector scenarioListRemote; + std::map scenarioCacheList; + vector scenarioFiles; + vector scenarioFilesUserData; + + FTPClientThread *ftpClientThread; + std::map> fileFTPProgressList; + + SimpleTaskThread *modHttpServerThread; + + void getTechsLocalList(); + string refreshTechModInfo(string techInfo); + void refreshTechs(); + + void getTilesetsLocalList(); + string refreshTilesetModInfo(string tilesetInfo); + void refreshTilesets(); + + void getMapsLocalList(); + string refreshMapModInfo(string mapInfo); + void refreshMaps(); + string getMapCRC(string mapName); + + void getScenariosLocalList(); + string refreshScenarioModInfo(string scenarioInfo); + void refreshScenarios(); + + void showLocalDescription(string name); + void loadMapPreview(string name); + void showRemoteDesription(ModInfo *modInfo); + + std::map mapCRCUpdateList; - GraphicButton buttonReturn; - GraphicLine lineHorizontal; - GraphicLine lineVertical; - GraphicLine lineReturn; - GraphicLine lineVerticalReturn; - - GraphicMessageBox mainMessageBox; - FTPMessageType mainMessageBoxState; - - int techInfoXPos; - int mapInfoXPos; - int tilesetInfoXPos; - int scenarioInfoXPos; - int labelWidth; - int scrollListsYPos; - int listBoxLength; - - GraphicButton buttonInstallTech; - GraphicButton buttonRemoveTech; - GraphicLabel keyTechScrollBarTitle1; - GraphicLabel keyTechScrollBarTitle2; - GraphicScrollBar keyTechScrollBar; - UserButtons keyTechButtons; - GraphicLabels labelsTech; - - GraphicButton buttonInstallTileset; - GraphicButton buttonRemoveTileset; - GraphicLabel keyTilesetScrollBarTitle1; - GraphicScrollBar keyTilesetScrollBar; - UserButtons keyTilesetButtons; - - GraphicButton buttonInstallMap; - GraphicButton buttonRemoveMap; - GraphicLabel keyMapScrollBarTitle1; - GraphicLabel keyMapScrollBarTitle2; - GraphicScrollBar keyMapScrollBar; - UserButtons keyMapButtons; - GraphicLabels labelsMap; - - GraphicButton buttonInstallScenario; - GraphicButton buttonRemoveScenario; - GraphicLabel keyScenarioScrollBarTitle1; - GraphicLabel keyScenarioScrollBarTitle2; - GraphicScrollBar keyScenarioScrollBar; - UserButtons keyScenarioButtons; - - GraphicLabel modDescrLabel; - Texture2D *modPreviewImage; - ModInfo *modInfoSelected; - map displayModPreviewImage; - - GraphicButton buttonInstalled; - GraphicButton buttonAvailable; - GraphicButton buttonConflict; - GraphicButton buttonOnlyLocal; - - GraphicLabel pleaseWaitLabel; - ModMenuState modMenuState; - ModMenuState oldMenuState; - - bool enableMapPreview; - bool validMapPreview; - MapInfo mapInfo; - MapPreview mapPreview; - Texture2D *mapPreviewTexture; - - int keyButtonsToRender; - int keyButtonsYBase; - int keyButtonsXBase; - int keyButtonsLineHeight; - int keyButtonsHeight; - int keyButtonsWidth; - int keyButtonsWidthTech; - int keyButtonsWidthMap; - int keyButtonsWidthTil; - int keyButtonsWidthScen; - - //Console console; - bool showFullConsole; - - string selectedTechName; - std::vector techListRemote; - std::map techCacheList; - vector techTreeFiles; - vector techTreeFilesUserData; - - string selectedTilesetName; - std::vector tilesetListRemote; - std::map tilesetCacheList; - vector tilesetFiles; - vector tilesetFilesUserData; - - string selectedMapName; - std::vector mapListRemote; - std::map mapCacheList; - vector mapFiles; - vector mapFilesUserData; - - string selectedScenarioName; - std::vector scenarioListRemote; - std::map scenarioCacheList; - vector scenarioFiles; - vector scenarioFilesUserData; - - FTPClientThread *ftpClientThread; - std::map > fileFTPProgressList; - - SimpleTaskThread *modHttpServerThread; - - void getTechsLocalList(); - string refreshTechModInfo(string techInfo); - void refreshTechs(); - - void getTilesetsLocalList(); - string refreshTilesetModInfo(string tilesetInfo); - void refreshTilesets(); - - void getMapsLocalList(); - string refreshMapModInfo(string mapInfo); - void refreshMaps(); - string getMapCRC(string mapName); - - void getScenariosLocalList(); - string refreshScenarioModInfo(string scenarioInfo); - void refreshScenarios(); - - void showLocalDescription(string name); - void loadMapPreview(string name); - void showRemoteDesription(ModInfo *modInfo); - - std::map mapCRCUpdateList; public: + MenuStateMods(Program *program, MainMenu *mainMenu); + virtual ~MenuStateMods(); - MenuStateMods(Program *program, MainMenu *mainMenu); - virtual ~MenuStateMods(); + void mouseClick(int x, int y, MouseButton mouseButton); + void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; + void mouseUp(int x, int y, const MouseButton mouseButton); + void mouseMove(int x, int y, const MouseState *mouseState); + void eventMouseWheel(int x, int y, int zDelta); + void render(); + void update(); - void mouseClick(int x, int y, MouseButton mouseButton); - void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; - void mouseUp(int x, int y, const MouseButton mouseButton); - void mouseMove(int x, int y, const MouseState *mouseState); - void eventMouseWheel(int x, int y,int zDelta); - void render(); - void update(); + virtual void keyDown(SDL_KeyboardEvent key); + virtual void keyPress(SDL_KeyboardEvent c); + virtual void keyUp(SDL_KeyboardEvent key); - virtual void keyDown(SDL_KeyboardEvent key); - virtual void keyPress(SDL_KeyboardEvent c); - virtual void keyUp(SDL_KeyboardEvent key); + virtual void simpleTask(BaseThread *callingThread, void *userdata); - virtual void simpleTask(BaseThread *callingThread,void *userdata); - - virtual void reloadUI(); + virtual void reloadUI(); private: - - bool eventMouseWheel(GraphicScrollBar* scrollBar, UserButtons* buttons,int x, int y,int zDelta); - void layoutButtons(GraphicScrollBar * scrollBar,UserButtons* buttons, GraphicLabels* labels); - void cleanUp(); - MapInfo loadMapInfo(string file); - void showMessageBox(const string &text, const string &header, bool toggle); - void clearUserButtons(); - virtual void FTPClient_CallbackEvent(string itemName, - FTP_Client_CallbackType type, pair result,void *userdata); - - string getPreviewImageFileForMod(const ModInfo *modInfo); - void cleanupPreviewTexture(); - void cleanupMapPreviewTexture(); + bool eventMouseWheel(GraphicScrollBar *scrollBar, UserButtons *buttons, int x, + int y, int zDelta); + void layoutButtons(GraphicScrollBar *scrollBar, UserButtons *buttons, + GraphicLabels *labels); + void cleanUp(); + MapInfo loadMapInfo(string file); + void showMessageBox(const string &text, const string &header, bool toggle); + void clearUserButtons(); + virtual void + FTPClient_CallbackEvent(string itemName, FTP_Client_CallbackType type, + pair result, + void *userdata); + + string getPreviewImageFileForMod(const ModInfo *modInfo); + void cleanupPreviewTexture(); + void cleanupMapPreviewTexture(); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif /* MENU_STATE_MODS_H_ */ diff --git a/source/glest_game/menu/menu_state_new_game.cpp b/source/glest_game/menu/menu_state_new_game.cpp index 3e57d773e..bad2f2e7f 100644 --- a/source/glest_game/menu/menu_state_new_game.cpp +++ b/source/glest_game/menu/menu_state_new_game.cpp @@ -11,174 +11,178 @@ #include "menu_state_new_game.h" -#include "renderer.h" -#include "sound_renderer.h" -#include "core_data.h" +#include "auto_test.h" #include "config.h" +#include "core_data.h" #include "menu_state_custom_game.h" -#include "menu_state_scenario.h" #include "menu_state_join_game.h" #include "menu_state_masterserver.h" #include "menu_state_root.h" +#include "menu_state_scenario.h" #include "metrics.h" #include "network_manager.h" #include "network_message.h" -#include "auto_test.h" +#include "renderer.h" #include "socket.h" +#include "sound_renderer.h" #include "leak_dumper.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class MenuStateNewGame // ===================================================== -MenuStateNewGame::MenuStateNewGame(Program *program, MainMenu *mainMenu): - MenuState(program, mainMenu, "root") -{ - containerName = "NewGame"; - Lang &lang= Lang::getInstance(); - - int buttonWidth = 200; - int buttonXPosition = (1000 - buttonWidth) / 2; - int yPos=465; - buttonTutorial.registerGraphicComponent(containerName,"buttonTutorial"); - buttonTutorial.init(buttonXPosition, yPos, buttonWidth); - yPos-=40; - buttonScenario.registerGraphicComponent(containerName,"buttonScenario"); - buttonScenario.init(buttonXPosition, yPos, buttonWidth); - yPos-=40; - buttonCustomGame.registerGraphicComponent(containerName,"buttonCustomGame"); - buttonCustomGame.init(buttonXPosition, yPos, buttonWidth); - yPos-=40; - buttonMasterserverGame.registerGraphicComponent(containerName,"buttonMasterserverGame"); - buttonMasterserverGame.init(buttonXPosition, yPos, buttonWidth); - yPos-=40; - buttonJoinGame.registerGraphicComponent(containerName,"buttonJoinGame"); - buttonJoinGame.init(buttonXPosition, yPos, buttonWidth); - yPos-=40; - buttonReturn.registerGraphicComponent(containerName,"buttonReturn"); - buttonReturn.init(buttonXPosition, yPos, buttonWidth); - - buttonCustomGame.setText(lang.getString("CustomGame")); - buttonScenario.setText(lang.getString("Scenario")); - buttonJoinGame.setText(lang.getString("JoinGame")); - buttonMasterserverGame.setText(lang.getString("JoinInternetGame")); - buttonTutorial.setText(lang.getString("Tutorial")); - buttonReturn.setText(lang.getString("Return")); - - GraphicComponent::applyAllCustomProperties(containerName); - - NetworkManager::getInstance().end(); +MenuStateNewGame::MenuStateNewGame(Program *program, MainMenu *mainMenu) + : MenuState(program, mainMenu, "root") { + containerName = "NewGame"; + Lang &lang = Lang::getInstance(); + + int buttonWidth = 200; + int buttonXPosition = (1000 - buttonWidth) / 2; + int yPos = 465; + buttonTutorial.registerGraphicComponent(containerName, "buttonTutorial"); + buttonTutorial.init(buttonXPosition, yPos, buttonWidth); + yPos -= 40; + buttonScenario.registerGraphicComponent(containerName, "buttonScenario"); + buttonScenario.init(buttonXPosition, yPos, buttonWidth); + yPos -= 40; + buttonCustomGame.registerGraphicComponent(containerName, "buttonCustomGame"); + buttonCustomGame.init(buttonXPosition, yPos, buttonWidth); + yPos -= 40; + buttonMasterserverGame.registerGraphicComponent(containerName, + "buttonMasterserverGame"); + buttonMasterserverGame.init(buttonXPosition, yPos, buttonWidth); + yPos -= 40; + buttonJoinGame.registerGraphicComponent(containerName, "buttonJoinGame"); + buttonJoinGame.init(buttonXPosition, yPos, buttonWidth); + yPos -= 40; + buttonReturn.registerGraphicComponent(containerName, "buttonReturn"); + buttonReturn.init(buttonXPosition, yPos, buttonWidth); + + buttonCustomGame.setText(lang.getString("CustomGame")); + buttonScenario.setText(lang.getString("Scenario")); + buttonJoinGame.setText(lang.getString("JoinGame")); + buttonMasterserverGame.setText(lang.getString("JoinInternetGame")); + buttonTutorial.setText(lang.getString("Tutorial")); + buttonReturn.setText(lang.getString("Return")); + + GraphicComponent::applyAllCustomProperties(containerName); + + NetworkManager::getInstance().end(); } void MenuStateNewGame::reloadUI() { - Lang &lang= Lang::getInstance(); + Lang &lang = Lang::getInstance(); - buttonCustomGame.setText(lang.getString("CustomGame")); - buttonScenario.setText(lang.getString("Scenario")); - buttonJoinGame.setText(lang.getString("JoinGame")); - buttonMasterserverGame.setText(lang.getString("JoinInternetGame")); - buttonTutorial.setText(lang.getString("Tutorial")); - buttonReturn.setText(lang.getString("Return")); + buttonCustomGame.setText(lang.getString("CustomGame")); + buttonScenario.setText(lang.getString("Scenario")); + buttonJoinGame.setText(lang.getString("JoinGame")); + buttonMasterserverGame.setText(lang.getString("JoinInternetGame")); + buttonTutorial.setText(lang.getString("Tutorial")); + buttonReturn.setText(lang.getString("Return")); - GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); + GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); } -void MenuStateNewGame::mouseClick(int x, int y, MouseButton mouseButton){ - - CoreData &coreData= CoreData::getInstance(); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - - if(buttonCustomGame.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundB()); - mainMenu->setState(new MenuStateCustomGame(program, mainMenu)); - } - else if(buttonScenario.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundB()); - mainMenu->setState(new MenuStateScenario(program, mainMenu, false, - Config::getInstance().getPathListForType(ptScenarios))); +void MenuStateNewGame::mouseClick(int x, int y, MouseButton mouseButton) { + + CoreData &coreData = CoreData::getInstance(); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + + if (buttonCustomGame.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundB()); + mainMenu->setState(new MenuStateCustomGame(program, mainMenu)); + } else if (buttonScenario.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundB()); + mainMenu->setState(new MenuStateScenario( + program, mainMenu, false, + Config::getInstance().getPathListForType(ptScenarios))); + } else if (buttonJoinGame.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundB()); + mainMenu->setState(new MenuStateJoinGame(program, mainMenu)); + } else if (buttonMasterserverGame.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundB()); + bool playScenario = false; + if (Config::getInstance().getString("InternetGamesBlockScenario", "") != + "" && + Config::getInstance().getBool("InternetGamesAllowed", "false") == + false) { + + // check if scenario exists; + vector dirList = + Config::getInstance().getPathListForType(ptScenarios); + string scenarioName = + Config::getInstance().getString("InternetGamesBlockScenario"); + + string scenarioPath = Scenario::getScenarioPath(dirList, scenarioName); + + if (scenarioPath != "") { + mainMenu->setState(new MenuStateScenario(program, mainMenu, false, + dirList, scenarioName)); + playScenario = true; + } } - else if(buttonJoinGame.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundB()); - mainMenu->setState(new MenuStateJoinGame(program, mainMenu)); - } - else if(buttonMasterserverGame.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundB()); - bool playScenario=false; - if (Config::getInstance().getString("InternetGamesBlockScenario", "") != "" - && Config::getInstance().getBool("InternetGamesAllowed", "false") == false) { - - // check if scenario exists; - vector dirList=Config::getInstance().getPathListForType(ptScenarios); - string scenarioName=Config::getInstance().getString( - "InternetGamesBlockScenario"); - - string scenarioPath = Scenario::getScenarioPath(dirList, scenarioName); - - if (scenarioPath != "") { - mainMenu->setState( - new MenuStateScenario(program, mainMenu, false, dirList, - scenarioName)); - playScenario=true; - } - } - - if(playScenario==false){ - mainMenu->setState(new MenuStateMasterserver(program, mainMenu)); - } - } - else if(buttonTutorial.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundB()); - mainMenu->setState(new MenuStateScenario(program, mainMenu, true, - Config::getInstance().getPathListForType(ptTutorials))); - } - else if(buttonReturn.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundB()); - mainMenu->setState(new MenuStateRoot(program, mainMenu)); + + if (playScenario == false) { + mainMenu->setState(new MenuStateMasterserver(program, mainMenu)); } + } else if (buttonTutorial.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundB()); + mainMenu->setState(new MenuStateScenario( + program, mainMenu, true, + Config::getInstance().getPathListForType(ptTutorials))); + } else if (buttonReturn.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundB()); + mainMenu->setState(new MenuStateRoot(program, mainMenu)); + } } -void MenuStateNewGame::mouseMove(int x, int y, const MouseState *ms){ - buttonCustomGame.mouseMove(x, y); - buttonScenario.mouseMove(x, y); - buttonJoinGame.mouseMove(x, y); - buttonMasterserverGame.mouseMove(x, y); - buttonTutorial.mouseMove(x, y); - buttonReturn.mouseMove(x, y); +void MenuStateNewGame::mouseMove(int x, int y, const MouseState *ms) { + buttonCustomGame.mouseMove(x, y); + buttonScenario.mouseMove(x, y); + buttonJoinGame.mouseMove(x, y); + buttonMasterserverGame.mouseMove(x, y); + buttonTutorial.mouseMove(x, y); + buttonReturn.mouseMove(x, y); } -void MenuStateNewGame::render(){ - Renderer &renderer= Renderer::getInstance(); +void MenuStateNewGame::render() { + Renderer &renderer = Renderer::getInstance(); - renderer.renderButton(&buttonCustomGame); - renderer.renderButton(&buttonScenario); - renderer.renderButton(&buttonJoinGame); - renderer.renderButton(&buttonMasterserverGame); - renderer.renderButton(&buttonTutorial); - renderer.renderButton(&buttonReturn); + renderer.renderButton(&buttonCustomGame); + renderer.renderButton(&buttonScenario); + renderer.renderButton(&buttonJoinGame); + renderer.renderButton(&buttonMasterserverGame); + renderer.renderButton(&buttonTutorial); + renderer.renderButton(&buttonReturn); - renderer.renderConsole(&console); - if(program != NULL) program->renderProgramMsgBox(); + renderer.renderConsole(&console); + if (program != NULL) + program->renderProgramMsgBox(); } -void MenuStateNewGame::update(){ - if(Config::getInstance().getBool("AutoTest")){ - AutoTest::getInstance().updateNewGame(program, mainMenu); - return; - } - console.update(); +void MenuStateNewGame::update() { + if (Config::getInstance().getBool("AutoTest")) { + AutoTest::getInstance().updateNewGame(program, mainMenu); + return; + } + console.update(); } void MenuStateNewGame::keyDown(SDL_KeyboardEvent key) { - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - //if(key == configKeys.getCharKey("SaveGUILayout")) { - if(isKeyPressed(configKeys.getSDLKey("SaveGUILayout"),key) == true) { - GraphicComponent::saveAllCustomProperties(containerName); - //Lang &lang= Lang::getInstance(); - //console.addLine(lang.getString("GUILayoutSaved") + " [" + (saved ? lang.getString("Yes") : lang.getString("No"))+ "]"); - } + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + // if(key == configKeys.getCharKey("SaveGUILayout")) { + if (isKeyPressed(configKeys.getSDLKey("SaveGUILayout"), key) == true) { + GraphicComponent::saveAllCustomProperties(containerName); + // Lang &lang= Lang::getInstance(); + // console.addLine(lang.getString("GUILayoutSaved") + " [" + (saved ? + // lang.getString("Yes") : lang.getString("No"))+ "]"); + } } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/menu/menu_state_new_game.h b/source/glest_game/menu/menu_state_new_game.h index d3066e5be..0b51c7e97 100644 --- a/source/glest_game/menu/menu_state_new_game.h +++ b/source/glest_game/menu/menu_state_new_game.h @@ -3,47 +3,48 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== #ifndef _GLEST_GAME_MENUSTATENEWGAME_H_ #define _GLEST_GAME_MENUSTATENEWGAME_H_ -#include "main_menu.h" #include "leak_dumper.h" +#include "main_menu.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // =============================== -// class MenuStateNewGame +// class MenuStateNewGame // =============================== -class MenuStateNewGame: public MenuState{ +class MenuStateNewGame : public MenuState { private: - GraphicButton buttonCustomGame; - GraphicButton buttonScenario; - GraphicButton buttonJoinGame; - GraphicButton buttonMasterserverGame; - GraphicButton buttonTutorial; - GraphicButton buttonReturn; + GraphicButton buttonCustomGame; + GraphicButton buttonScenario; + GraphicButton buttonJoinGame; + GraphicButton buttonMasterserverGame; + GraphicButton buttonTutorial; + GraphicButton buttonReturn; public: - MenuStateNewGame(Program *program, MainMenu *mainMenu); + MenuStateNewGame(Program *program, MainMenu *mainMenu); - void mouseClick(int x, int y, MouseButton mouseButton); - void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; - void mouseMove(int x, int y, const MouseState *mouseState); - void update(); - void render(); - virtual void keyDown(SDL_KeyboardEvent key); + void mouseClick(int x, int y, MouseButton mouseButton); + void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; + void mouseMove(int x, int y, const MouseState *mouseState); + void update(); + void render(); + virtual void keyDown(SDL_KeyboardEvent key); - void reloadUI(); + void reloadUI(); }; - -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/menu/menu_state_options.cpp b/source/glest_game/menu/menu_state_options.cpp index ec7a39089..6c49beea4 100644 --- a/source/glest_game/menu/menu_state_options.cpp +++ b/source/glest_game/menu/menu_state_options.cpp @@ -11,1164 +11,1238 @@ #include "menu_state_options.h" -#include "renderer.h" -#include "game.h" -#include "program.h" -#include "sound_renderer.h" -#include "core_data.h" #include "config.h" -#include "menu_state_root.h" -#include "util.h" +#include "core_data.h" +#include "game.h" +#include "leak_dumper.h" #include "menu_state_graphic_info.h" #include "menu_state_keysetup.h" #include "menu_state_options_graphics.h" #include "menu_state_options_network.h" #include "menu_state_options_sound.h" -#include "string_utils.h" +#include "menu_state_root.h" #include "metrics.h" -#include "leak_dumper.h" +#include "program.h" +#include "renderer.h" +#include "sound_renderer.h" +#include "string_utils.h" +#include "util.h" using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class MenuStateOptions // ===================================================== -MenuStateOptions::MenuStateOptions(Program *program, MainMenu *mainMenu, ProgramState **parentUI) : - MenuState(program, mainMenu, "config"), - buttonOk("Options","buttonOk"), - buttonReturn("Options","buttonReturn"), +MenuStateOptions::MenuStateOptions(Program *program, MainMenu *mainMenu, + ProgramState **parentUI) + : MenuState(program, mainMenu, "config"), buttonOk("Options", "buttonOk"), + buttonReturn("Options", "buttonReturn"), - labelLang("Options","labelLang"), - listBoxLang("Options","listBoxLang"), - labelPlayerName("Options","labelPlayerName"), - labelPlayerNameLabel("Options","labelPlayerNameLabel"), + labelLang("Options", "labelLang"), listBoxLang("Options", "listBoxLang"), + labelPlayerName("Options", "labelPlayerName"), + labelPlayerNameLabel("Options", "labelPlayerNameLabel"), - buttonKeyboardSetup("Options","buttonKeyboardSetup"), - buttonVideoSection("Options","buttonVideoSection"), - buttonAudioSection("Options","buttonAudioSection"), - buttonMiscSection("Options","buttonMiscSection"), - buttonNetworkSettings("Options","buttonNetworkSettings"), + buttonKeyboardSetup("Options", "buttonKeyboardSetup"), + buttonVideoSection("Options", "buttonVideoSection"), + buttonAudioSection("Options", "buttonAudioSection"), + buttonMiscSection("Options", "buttonMiscSection"), + buttonNetworkSettings("Options", "buttonNetworkSettings"), - labelFontSizeAdjustment("Options","labelFontSizeAdjustment"), - listFontSizeAdjustment("Options","listFontSizeAdjustment"), + labelFontSizeAdjustment("Options", "labelFontSizeAdjustment"), + listFontSizeAdjustment("Options", "listFontSizeAdjustment"), - mainMessageBox("Options","mainMessageBox"), + mainMessageBox("Options", "mainMessageBox"), - labelScreenShotType("Options","labelScreenShotType"), - listBoxScreenShotType("Options","listBoxScreenShotType"), + labelScreenShotType("Options", "labelScreenShotType"), + listBoxScreenShotType("Options", "listBoxScreenShotType"), - labelDisableScreenshotConsoleText("Options","labelDisableScreenshotConsoleText"), - checkBoxDisableScreenshotConsoleText("Options","checkBoxDisableScreenshotConsoleText"), + labelDisableScreenshotConsoleText("Options", + "labelDisableScreenshotConsoleText"), + checkBoxDisableScreenshotConsoleText( + "Options", "checkBoxDisableScreenshotConsoleText"), - labelMouseMoveScrollsWorld("Options","labelMouseMoveScrollsWorld"), - checkBoxMouseMoveScrollsWorld("Options","checkBoxMouseMoveScrollsWorld"), + labelMouseMoveScrollsWorld("Options", "labelMouseMoveScrollsWorld"), + checkBoxMouseMoveScrollsWorld("Options", "checkBoxMouseMoveScrollsWorld"), - labelCameraMoveSpeed("Options","labelCameraMoveSpeed"), - listCameraMoveSpeed("Options","listCameraMoveSpeed"), + labelCameraMoveSpeed("Options", "labelCameraMoveSpeed"), + listCameraMoveSpeed("Options", "listCameraMoveSpeed"), - labelVisibleHud("Options","labelVisibleHud"), - checkBoxVisibleHud("Options","checkBoxVisibleHud"), - labelHealthBars("Options","labelHealthBars"), - listBoxHealthBars("Options","listBoxHealthBars"), + labelVisibleHud("Options", "labelVisibleHud"), + checkBoxVisibleHud("Options", "checkBoxVisibleHud"), + labelHealthBars("Options", "labelHealthBars"), + listBoxHealthBars("Options", "listBoxHealthBars"), - labelTimeDisplay("Options","labelTimeDisplay"), - checkBoxTimeDisplay("Options","checkBoxTimeDisplay"), - labelChatStaysActive("Options","labelChatStaysActive"), - checkBoxChatStaysActive("Options","checkBoxChatStaysActive"), + labelTimeDisplay("Options", "labelTimeDisplay"), + checkBoxTimeDisplay("Options", "checkBoxTimeDisplay"), + labelChatStaysActive("Options", "labelChatStaysActive"), + checkBoxChatStaysActive("Options", "checkBoxChatStaysActive"), - labelLuaDisableSecuritySandbox("Options","labelLuaDisableSecuritySandbox"), - checkBoxLuaDisableSecuritySandbox("Options","checkBoxLuaDisableSecuritySandbox"), + labelLuaDisableSecuritySandbox("Options", + "labelLuaDisableSecuritySandbox"), + checkBoxLuaDisableSecuritySandbox("Options", + "checkBoxLuaDisableSecuritySandbox"), - luaMessageBox("Options","luaMessageBox"), + luaMessageBox("Options", "luaMessageBox"), - labelCustomTranslation("Options","labelCustomTranslation"), - checkBoxCustomTranslation("Options","checkBoxCustomTranslation"), + labelCustomTranslation("Options", "labelCustomTranslation"), + checkBoxCustomTranslation("Options", "checkBoxCustomTranslation"), - buttonGetNewLanguageFiles("Options","buttonGetNewLanguageFiles"), - buttonDeleteNewLanguageFiles("Options","buttonDeleteNewLanguageFiles"), - labelTransifexUserLabel("Options","labelTransifexUserLabel"), - labelTransifexUser("Options","labelTransifexUser"), - labelTransifexPwdLabel("Options","labelTransifexPwdLabel"), - labelTransifexPwd("Options","labelTransifexPwd"), - labelTransifexI18NLabel("Options","labelTransifexI18NLabel"), - labelTransifexI18N("Options","labelTransifexI18N") + buttonGetNewLanguageFiles("Options", "buttonGetNewLanguageFiles"), + buttonDeleteNewLanguageFiles("Options", "buttonDeleteNewLanguageFiles"), + labelTransifexUserLabel("Options", "labelTransifexUserLabel"), + labelTransifexUser("Options", "labelTransifexUser"), + labelTransifexPwdLabel("Options", "labelTransifexPwdLabel"), + labelTransifexPwd("Options", "labelTransifexPwd"), + labelTransifexI18NLabel("Options", "labelTransifexI18NLabel"), + labelTransifexI18N("Options", "labelTransifexI18N") { - try { - containerName = "Options"; - this->parentUI=parentUI; - Lang &lang= Lang::getInstance(); - Config &config= Config::getInstance(); - - this->console.setOnlyChatMessagesInStoredLines(false); - activeInputLabel=NULL; - - int leftLabelStart=100; - int leftColumnStart=leftLabelStart+300; - int buttonRowPos=50; - int buttonStartPos=170; - int lineOffset=30; - int tabButtonWidth=200; - int tabButtonHeight=30; - - mainMessageBox.init(lang.getString("Ok")); - mainMessageBox.setEnabled(false); - mainMessageBoxState=0; - - buttonAudioSection.init(0, 720,tabButtonWidth,tabButtonHeight); - buttonAudioSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonAudioSection.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonAudioSection.setText(lang.getString("Audio")); - // Video Section - buttonVideoSection.init(200, 720,tabButtonWidth,tabButtonHeight); - buttonVideoSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonVideoSection.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonVideoSection.setText(lang.getString("Video")); - //MiscSection - buttonMiscSection.init(400, 700,tabButtonWidth,tabButtonHeight+20); - buttonMiscSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonMiscSection.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonMiscSection.setText(lang.getString("Misc")); - //NetworkSettings - buttonNetworkSettings.init(600, 720,tabButtonWidth,tabButtonHeight); - buttonNetworkSettings.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonNetworkSettings.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonNetworkSettings.setText(lang.getString("Network")); - - //KeyboardSetup - buttonKeyboardSetup.init(800, 720,tabButtonWidth,tabButtonHeight); - buttonKeyboardSetup.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonKeyboardSetup.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonKeyboardSetup.setText(lang.getString("Keyboardsetup")); - - int currentLine=650; // reset line pos - int currentLabelStart=leftLabelStart; // set to right side - int currentColumnStart=leftColumnStart; // set to right side - - //lang - labelLang.init(currentLabelStart, currentLine); - labelLang.setText(lang.getString("Language")); - - listBoxLang.init(currentColumnStart, currentLine, 375); - vector langResults; - - languageList = Lang::getInstance().getDiscoveredLanguageList(true); - for(map::iterator iterMap = languageList.begin(); - iterMap != languageList.end(); ++iterMap) { - langResults.push_back(iterMap->first + "-" + iterMap->second); - } - - listBoxLang.setItems(langResults); - - pair defaultLang = Lang::getInstance().getNavtiveNameFromLanguageName(config.getString("Lang")); - if(defaultLang.first == "" && defaultLang.second == "") { - defaultLang = Lang::getInstance().getNavtiveNameFromLanguageName(Lang::getInstance().getDefaultLanguage()); - } - listBoxLang.setSelectedItem(defaultLang.second + "-" + defaultLang.first); - currentLine-=lineOffset; - - //playerName - labelPlayerNameLabel.init(currentLabelStart,currentLine); - labelPlayerNameLabel.setText(lang.getString("Playername")); - - labelPlayerName.init(currentColumnStart,currentLine); - labelPlayerName.setText(config.getString("NetPlayerName",Socket::getHostName().c_str())); - labelPlayerName.setFont(CoreData::getInstance().getMenuFontBig()); - labelPlayerName.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - labelPlayerName.setEditable(true); - labelPlayerName.setMaxEditWidth(16); - labelPlayerName.setMaxEditRenderWidth(200); - currentLine-=lineOffset; - - //FontSizeAdjustment - labelFontSizeAdjustment.init(currentLabelStart,currentLine); - labelFontSizeAdjustment.setText(lang.getString("FontSizeAdjustment")); - - listFontSizeAdjustment.init(currentColumnStart, currentLine, 80); - for(int i=-5; i<=5; i+=1){ - listFontSizeAdjustment.pushBackItem(intToStr(i)); - } - listFontSizeAdjustment.setSelectedItem(intToStr(config.getInt("FontSizeAdjustment"))); - - currentLine-=lineOffset; - // Screenshot type flag - labelScreenShotType.init(currentLabelStart ,currentLine); - labelScreenShotType.setText(lang.getString("ScreenShotFileType")); - - listBoxScreenShotType.init(currentColumnStart ,currentLine, 80 ); - listBoxScreenShotType.pushBackItem("bmp"); - listBoxScreenShotType.pushBackItem("jpg"); - listBoxScreenShotType.pushBackItem("png"); - listBoxScreenShotType.pushBackItem("tga"); - listBoxScreenShotType.setSelectedItem(config.getString("ScreenShotFileType","jpg")); - - currentLine-=lineOffset; - - labelDisableScreenshotConsoleText.init(currentLabelStart ,currentLine); - labelDisableScreenshotConsoleText.setText(lang.getString("ScreenShotConsoleText")); - - checkBoxDisableScreenshotConsoleText.init(currentColumnStart ,currentLine ); - checkBoxDisableScreenshotConsoleText.setValue(!config.getBool("DisableScreenshotConsoleText","false")); - - currentLine-=lineOffset; - - labelMouseMoveScrollsWorld.init(currentLabelStart ,currentLine); - labelMouseMoveScrollsWorld.setText(lang.getString("MouseScrollsWorld")); - - checkBoxMouseMoveScrollsWorld.init(currentColumnStart ,currentLine ); - checkBoxMouseMoveScrollsWorld.setValue(config.getBool("MouseMoveScrollsWorld","true")); - currentLine-=lineOffset; - - //CameraMoveSpeed - labelCameraMoveSpeed.init(currentLabelStart,currentLine); - labelCameraMoveSpeed.setText(lang.getString("CameraMoveSpeed")); - - listCameraMoveSpeed.init(currentColumnStart, currentLine, 80); - for(int i=15; i<=50; i+=5){ - listCameraMoveSpeed.pushBackItem(intToStr(i)); - } - listCameraMoveSpeed.setSelectedItem(intToStr((int) (config.getFloat("CameraMoveSpeed","15")))); - currentLine-=lineOffset; - - labelVisibleHud.init(currentLabelStart ,currentLine); - labelVisibleHud.setText(lang.getString("VisibleHUD")); - - checkBoxVisibleHud.init(currentColumnStart ,currentLine ); - checkBoxVisibleHud.setValue(config.getBool("VisibleHud","true")); - - currentLine-=lineOffset; - - labelHealthBars.init(currentLabelStart ,currentLine); - labelHealthBars.setText(lang.getString("Healthbar")); - - listBoxHealthBars.init(currentColumnStart ,currentLine, 375); - listBoxHealthBars.pushBackItem(lang.getString("HealthbarsFactionDefault")); - listBoxHealthBars.pushBackItem(lang.getString("HealthbarsOff")); - listBoxHealthBars.pushBackItem(lang.getString("HealthbarsAlways")); - listBoxHealthBars.pushBackItem(lang.getString("HealthbarsIfNeeded")); - listBoxHealthBars.pushBackItem(lang.getString("HealthbarsSelected")); - listBoxHealthBars.pushBackItem(lang.getString("HealthbarsSelectedOrNeeded")); - - int hpMode=config.getInt("HealthBarMode","4"); - int hpIndex=0; - switch (hpMode) { - case hbvUndefined: - hpIndex = 0; - break; - case hbvOff: - hpIndex = 1; - break; - case hbvAlways: - hpIndex = 2; - break; - case hbvIfNeeded: - hpIndex = 3; - break; - case hbvSelected: - hpIndex = 4; - break; - case hbvSelected | hbvIfNeeded: - hpIndex = 5; - break; - default: - hpIndex = 0; - break; - } - - listBoxHealthBars.setSelectedItemIndex(hpIndex); - - currentLine-=lineOffset; - - labelChatStaysActive.init(currentLabelStart ,currentLine); - labelChatStaysActive.setText(lang.getString("ChatStaysActive")); - - checkBoxChatStaysActive.init(currentColumnStart ,currentLine ); - checkBoxChatStaysActive.setValue(config.getBool("ChatStaysActive","false")); - - currentLine-=lineOffset; - - labelTimeDisplay.init(currentLabelStart ,currentLine); - labelTimeDisplay.setText(lang.getString("TimeDisplay")); - - checkBoxTimeDisplay.init(currentColumnStart ,currentLine ); - checkBoxTimeDisplay.setValue(config.getBool("TimeDisplay","true")); - - currentLine-=lineOffset; - - labelLuaDisableSecuritySandbox.init(currentLabelStart ,currentLine); - labelLuaDisableSecuritySandbox.setText(lang.getString("LuaDisableSecuritySandbox")); - - checkBoxLuaDisableSecuritySandbox.init(currentColumnStart ,currentLine ); - checkBoxLuaDisableSecuritySandbox.setValue(config.getBool("DisableLuaSandbox","false")); + try { + containerName = "Options"; + this->parentUI = parentUI; + Lang &lang = Lang::getInstance(); + Config &config = Config::getInstance(); + + this->console.setOnlyChatMessagesInStoredLines(false); + activeInputLabel = NULL; + + int leftLabelStart = 100; + int leftColumnStart = leftLabelStart + 300; + int buttonRowPos = 50; + int buttonStartPos = 170; + int lineOffset = 30; + int tabButtonWidth = 200; + int tabButtonHeight = 30; + + mainMessageBox.init(lang.getString("Ok")); + mainMessageBox.setEnabled(false); + mainMessageBoxState = 0; + + buttonAudioSection.init(0, 720, tabButtonWidth, tabButtonHeight); + buttonAudioSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); + buttonAudioSection.setFont3D( + CoreData::getInstance().getMenuFontVeryBig3D()); + buttonAudioSection.setText(lang.getString("Audio")); + // Video Section + buttonVideoSection.init(200, 720, tabButtonWidth, tabButtonHeight); + buttonVideoSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); + buttonVideoSection.setFont3D( + CoreData::getInstance().getMenuFontVeryBig3D()); + buttonVideoSection.setText(lang.getString("Video")); + // MiscSection + buttonMiscSection.init(400, 700, tabButtonWidth, tabButtonHeight + 20); + buttonMiscSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); + buttonMiscSection.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); + buttonMiscSection.setText(lang.getString("Misc")); + // NetworkSettings + buttonNetworkSettings.init(600, 720, tabButtonWidth, tabButtonHeight); + buttonNetworkSettings.setFont(CoreData::getInstance().getMenuFontVeryBig()); + buttonNetworkSettings.setFont3D( + CoreData::getInstance().getMenuFontVeryBig3D()); + buttonNetworkSettings.setText(lang.getString("Network")); + + // KeyboardSetup + buttonKeyboardSetup.init(800, 720, tabButtonWidth, tabButtonHeight); + buttonKeyboardSetup.setFont(CoreData::getInstance().getMenuFontVeryBig()); + buttonKeyboardSetup.setFont3D( + CoreData::getInstance().getMenuFontVeryBig3D()); + buttonKeyboardSetup.setText(lang.getString("Keyboardsetup")); + + int currentLine = 650; // reset line pos + int currentLabelStart = leftLabelStart; // set to right side + int currentColumnStart = leftColumnStart; // set to right side + + // lang + labelLang.init(currentLabelStart, currentLine); + labelLang.setText(lang.getString("Language")); + + listBoxLang.init(currentColumnStart, currentLine, 375); + vector langResults; + + languageList = Lang::getInstance().getDiscoveredLanguageList(true); + for (map::iterator iterMap = languageList.begin(); + iterMap != languageList.end(); ++iterMap) { + langResults.push_back(iterMap->first + "-" + iterMap->second); + } - luaMessageBox.init(lang.getString("Yes"),lang.getString("No")); - luaMessageBox.setEnabled(false); - luaMessageBoxState=0; - - currentLine-=lineOffset; - - currentLine-=lineOffset/2; - - // buttons - buttonOk.init(buttonStartPos, buttonRowPos, 100); - buttonOk.setText(lang.getString("Save")); - - buttonReturn.init(buttonStartPos+110, buttonRowPos, 100); - buttonReturn.setText(lang.getString("Return")); - - // Transifex related UI - currentLine-=lineOffset*3; - labelCustomTranslation.init(currentLabelStart ,currentLine); - labelCustomTranslation.setText(lang.getString("CustomTranslation")); - - checkBoxCustomTranslation.init(currentColumnStart ,currentLine ); - checkBoxCustomTranslation.setValue(false); - currentLine-=lineOffset; - - labelTransifexUserLabel.init(currentLabelStart,currentLine); - labelTransifexUserLabel.setText(lang.getString("TransifexUserName")); - - labelTransifexPwdLabel.init(currentLabelStart + 260 ,currentLine); - labelTransifexPwdLabel.setText(lang.getString("TransifexPwd")); - - labelTransifexI18NLabel.init(currentLabelStart + 520 ,currentLine); - labelTransifexI18NLabel.setText(lang.getString("TransifexI18N")); - - currentLine-=lineOffset; - - labelTransifexUser.init(currentLabelStart,currentLine); - labelTransifexUser.setEditable(true); - labelTransifexUser.setMaxEditWidth(28); - labelTransifexUser.setMaxEditRenderWidth(250); - labelTransifexUser.setText(config.getString("TranslationGetURLUser","")); - - labelTransifexPwd.init(currentLabelStart + 260 ,currentLine); - labelTransifexPwd.setIsPassword(true); - labelTransifexPwd.setEditable(true); - labelTransifexPwd.setMaxEditWidth(28); - labelTransifexPwd.setMaxEditRenderWidth(250); - labelTransifexPwd.setText(config.getString("TranslationGetURLPassword","")); - - labelTransifexI18N.init(currentLabelStart + 520 ,currentLine); - labelTransifexI18N.setEditable(true); - labelTransifexI18N.setMaxEditWidth(6); - labelTransifexI18N.setMaxEditRenderWidth(70); - labelTransifexI18N.setText(config.getString("TranslationGetURLLanguage","en")); - currentLine-=lineOffset; + listBoxLang.setItems(langResults); - buttonGetNewLanguageFiles.init(currentLabelStart, currentLine, 250); - buttonGetNewLanguageFiles.setText(lang.getString("TransifexGetLanguageFiles")); + pair defaultLang = + Lang::getInstance().getNavtiveNameFromLanguageName( + config.getString("Lang")); + if (defaultLang.first == "" && defaultLang.second == "") { + defaultLang = Lang::getInstance().getNavtiveNameFromLanguageName( + Lang::getInstance().getDefaultLanguage()); + } + listBoxLang.setSelectedItem(defaultLang.second + "-" + defaultLang.first); + currentLine -= lineOffset; + + // playerName + labelPlayerNameLabel.init(currentLabelStart, currentLine); + labelPlayerNameLabel.setText(lang.getString("Playername")); + + labelPlayerName.init(currentColumnStart, currentLine); + labelPlayerName.setText( + config.getString("NetPlayerName", Socket::getHostName().c_str())); + labelPlayerName.setFont(CoreData::getInstance().getMenuFontBig()); + labelPlayerName.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + labelPlayerName.setEditable(true); + labelPlayerName.setMaxEditWidth(16); + labelPlayerName.setMaxEditRenderWidth(200); + currentLine -= lineOffset; + + // FontSizeAdjustment + labelFontSizeAdjustment.init(currentLabelStart, currentLine); + labelFontSizeAdjustment.setText(lang.getString("FontSizeAdjustment")); + + listFontSizeAdjustment.init(currentColumnStart, currentLine, 80); + for (int i = -5; i <= 5; i += 1) { + listFontSizeAdjustment.pushBackItem(intToStr(i)); + } + listFontSizeAdjustment.setSelectedItem( + intToStr(config.getInt("FontSizeAdjustment"))); - buttonDeleteNewLanguageFiles.init(currentLabelStart + 260, currentLine, 250); - buttonDeleteNewLanguageFiles.setText(lang.getString("TransifexDeleteLanguageFiles")); + currentLine -= lineOffset; + // Screenshot type flag + labelScreenShotType.init(currentLabelStart, currentLine); + labelScreenShotType.setText(lang.getString("ScreenShotFileType")); - setupTransifexUI(); + listBoxScreenShotType.init(currentColumnStart, currentLine, 80); + listBoxScreenShotType.pushBackItem("bmp"); + listBoxScreenShotType.pushBackItem("jpg"); + listBoxScreenShotType.pushBackItem("png"); + listBoxScreenShotType.pushBackItem("tga"); + listBoxScreenShotType.setSelectedItem( + config.getString("ScreenShotFileType", "jpg")); - GraphicComponent::applyAllCustomProperties(containerName); - } - catch(exception &e) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error loading options: %s\n",__FILE__,__FUNCTION__,__LINE__,e.what()); - throw megaglest_runtime_error(string("Error loading options msg: ") + e.what()); - } -} + currentLine -= lineOffset; + + labelDisableScreenshotConsoleText.init(currentLabelStart, currentLine); + labelDisableScreenshotConsoleText.setText( + lang.getString("ScreenShotConsoleText")); + + checkBoxDisableScreenshotConsoleText.init(currentColumnStart, currentLine); + checkBoxDisableScreenshotConsoleText.setValue( + !config.getBool("DisableScreenshotConsoleText", "false")); + + currentLine -= lineOffset; + + labelMouseMoveScrollsWorld.init(currentLabelStart, currentLine); + labelMouseMoveScrollsWorld.setText(lang.getString("MouseScrollsWorld")); + + checkBoxMouseMoveScrollsWorld.init(currentColumnStart, currentLine); + checkBoxMouseMoveScrollsWorld.setValue( + config.getBool("MouseMoveScrollsWorld", "true")); + currentLine -= lineOffset; + + // CameraMoveSpeed + labelCameraMoveSpeed.init(currentLabelStart, currentLine); + labelCameraMoveSpeed.setText(lang.getString("CameraMoveSpeed")); + + listCameraMoveSpeed.init(currentColumnStart, currentLine, 80); + for (int i = 15; i <= 50; i += 5) { + listCameraMoveSpeed.pushBackItem(intToStr(i)); + } + listCameraMoveSpeed.setSelectedItem( + intToStr((int)(config.getFloat("CameraMoveSpeed", "15")))); + currentLine -= lineOffset; + + labelVisibleHud.init(currentLabelStart, currentLine); + labelVisibleHud.setText(lang.getString("VisibleHUD")); + + checkBoxVisibleHud.init(currentColumnStart, currentLine); + checkBoxVisibleHud.setValue(config.getBool("VisibleHud", "true")); + + currentLine -= lineOffset; + + labelHealthBars.init(currentLabelStart, currentLine); + labelHealthBars.setText(lang.getString("Healthbar")); + + listBoxHealthBars.init(currentColumnStart, currentLine, 375); + listBoxHealthBars.pushBackItem(lang.getString("HealthbarsFactionDefault")); + listBoxHealthBars.pushBackItem(lang.getString("HealthbarsOff")); + listBoxHealthBars.pushBackItem(lang.getString("HealthbarsAlways")); + listBoxHealthBars.pushBackItem(lang.getString("HealthbarsIfNeeded")); + listBoxHealthBars.pushBackItem(lang.getString("HealthbarsSelected")); + listBoxHealthBars.pushBackItem( + lang.getString("HealthbarsSelectedOrNeeded")); + + int hpMode = config.getInt("HealthBarMode", "4"); + int hpIndex = 0; + switch (hpMode) { + case hbvUndefined: + hpIndex = 0; + break; + case hbvOff: + hpIndex = 1; + break; + case hbvAlways: + hpIndex = 2; + break; + case hbvIfNeeded: + hpIndex = 3; + break; + case hbvSelected: + hpIndex = 4; + break; + case hbvSelected | hbvIfNeeded: + hpIndex = 5; + break; + default: + hpIndex = 0; + break; + } + + listBoxHealthBars.setSelectedItemIndex(hpIndex); + + currentLine -= lineOffset; + + labelChatStaysActive.init(currentLabelStart, currentLine); + labelChatStaysActive.setText(lang.getString("ChatStaysActive")); -MenuStateOptions::~MenuStateOptions() { + checkBoxChatStaysActive.init(currentColumnStart, currentLine); + checkBoxChatStaysActive.setValue( + config.getBool("ChatStaysActive", "false")); + + currentLine -= lineOffset; + + labelTimeDisplay.init(currentLabelStart, currentLine); + labelTimeDisplay.setText(lang.getString("TimeDisplay")); + + checkBoxTimeDisplay.init(currentColumnStart, currentLine); + checkBoxTimeDisplay.setValue(config.getBool("TimeDisplay", "true")); + + currentLine -= lineOffset; + + labelLuaDisableSecuritySandbox.init(currentLabelStart, currentLine); + labelLuaDisableSecuritySandbox.setText( + lang.getString("LuaDisableSecuritySandbox")); + + checkBoxLuaDisableSecuritySandbox.init(currentColumnStart, currentLine); + checkBoxLuaDisableSecuritySandbox.setValue( + config.getBool("DisableLuaSandbox", "false")); + + luaMessageBox.init(lang.getString("Yes"), lang.getString("No")); + luaMessageBox.setEnabled(false); + luaMessageBoxState = 0; + + currentLine -= lineOffset; + + currentLine -= lineOffset / 2; + + // buttons + buttonOk.init(buttonStartPos, buttonRowPos, 100); + buttonOk.setText(lang.getString("Save")); + + buttonReturn.init(buttonStartPos + 110, buttonRowPos, 100); + buttonReturn.setText(lang.getString("Return")); + + // Transifex related UI + currentLine -= lineOffset * 3; + labelCustomTranslation.init(currentLabelStart, currentLine); + labelCustomTranslation.setText(lang.getString("CustomTranslation")); + + checkBoxCustomTranslation.init(currentColumnStart, currentLine); + checkBoxCustomTranslation.setValue(false); + currentLine -= lineOffset; + + labelTransifexUserLabel.init(currentLabelStart, currentLine); + labelTransifexUserLabel.setText(lang.getString("TransifexUserName")); + + labelTransifexPwdLabel.init(currentLabelStart + 260, currentLine); + labelTransifexPwdLabel.setText(lang.getString("TransifexPwd")); + + labelTransifexI18NLabel.init(currentLabelStart + 520, currentLine); + labelTransifexI18NLabel.setText(lang.getString("TransifexI18N")); + + currentLine -= lineOffset; + + labelTransifexUser.init(currentLabelStart, currentLine); + labelTransifexUser.setEditable(true); + labelTransifexUser.setMaxEditWidth(28); + labelTransifexUser.setMaxEditRenderWidth(250); + labelTransifexUser.setText( + config.getString("TranslationGetURLUser", "")); + + labelTransifexPwd.init(currentLabelStart + 260, currentLine); + labelTransifexPwd.setIsPassword(true); + labelTransifexPwd.setEditable(true); + labelTransifexPwd.setMaxEditWidth(28); + labelTransifexPwd.setMaxEditRenderWidth(250); + labelTransifexPwd.setText( + config.getString("TranslationGetURLPassword", "")); + + labelTransifexI18N.init(currentLabelStart + 520, currentLine); + labelTransifexI18N.setEditable(true); + labelTransifexI18N.setMaxEditWidth(6); + labelTransifexI18N.setMaxEditRenderWidth(70); + labelTransifexI18N.setText( + config.getString("TranslationGetURLLanguage", "en")); + currentLine -= lineOffset; + + buttonGetNewLanguageFiles.init(currentLabelStart, currentLine, 250); + buttonGetNewLanguageFiles.setText( + lang.getString("TransifexGetLanguageFiles")); + + buttonDeleteNewLanguageFiles.init(currentLabelStart + 260, currentLine, + 250); + buttonDeleteNewLanguageFiles.setText( + lang.getString("TransifexDeleteLanguageFiles")); + + setupTransifexUI(); + + GraphicComponent::applyAllCustomProperties(containerName); + } catch (exception &e) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error loading options: %s\n", + __FILE__, __FUNCTION__, __LINE__, e.what()); + throw megaglest_runtime_error(string("Error loading options msg: ") + + e.what()); + } } +MenuStateOptions::~MenuStateOptions() {} + void MenuStateOptions::reloadUI() { - Lang &lang = Lang::getInstance(); - - mainMessageBox.init(lang.getString("Ok")); - luaMessageBox.init(lang.getString("Yes"),lang.getString("No")); - - buttonAudioSection.setText(lang.getString("Audio")); - buttonVideoSection.setText(lang.getString("Video")); - buttonMiscSection.setText(lang.getString("Misc")); - buttonNetworkSettings.setText(lang.getString("Network")); - buttonKeyboardSetup.setText(lang.getString("Keyboardsetup")); - - labelVisibleHud.setText(lang.getString("VisibleHUD")); - labelHealthBars.setText(lang.getString("Healthbar")); - - int healthBarSelection=listBoxHealthBars.getSelectedItemIndex(); - listBoxHealthBars.clearItems(); - listBoxHealthBars.pushBackItem(lang.getString("HealthbarsFactionDefault")); - listBoxHealthBars.pushBackItem(lang.getString("HealthbarsOff")); - listBoxHealthBars.pushBackItem(lang.getString("HealthbarsAlways")); - listBoxHealthBars.pushBackItem(lang.getString("HealthbarsIfNeeded")); - listBoxHealthBars.pushBackItem(lang.getString("HealthbarsSelected")); - listBoxHealthBars.pushBackItem(lang.getString("HealthbarsSelectedOrNeeded")); - listBoxHealthBars.setSelectedItemIndex(healthBarSelection); - - labelChatStaysActive.setText(lang.getString("ChatStaysActive")); - labelTimeDisplay.setText(lang.getString("TimeDisplay")); - - labelLuaDisableSecuritySandbox.setText(lang.getString("LuaDisableSecuritySandbox")); - labelLang.setText(lang.getString("Language")); - labelPlayerNameLabel.setText(lang.getString("Playername")); - labelFontSizeAdjustment.setText(lang.getString("FontSizeAdjustment")); - labelScreenShotType.setText(lang.getString("ScreenShotFileType")); - labelDisableScreenshotConsoleText.setText(lang.getString("ScreenShotConsoleText")); - labelMouseMoveScrollsWorld.setText(lang.getString("MouseScrollsWorld")); - labelCameraMoveSpeed.setText(lang.getString("CameraMoveSpeed")); - - buttonOk.setText(lang.getString("Save")); - buttonReturn.setText(lang.getString("Return")); - - labelCustomTranslation.setText(lang.getString("CustomTranslation")); - buttonGetNewLanguageFiles.setText(lang.getString("TransifexGetLanguageFiles")); - buttonDeleteNewLanguageFiles.setText(lang.getString("TransifexDeleteLanguageFiles")); - labelTransifexUserLabel.setText(lang.getString("TransifexUserName")); - labelTransifexPwdLabel.setText(lang.getString("TransifexPwd")); - labelTransifexI18NLabel.setText(lang.getString("TransifexI18N")); + Lang &lang = Lang::getInstance(); + + mainMessageBox.init(lang.getString("Ok")); + luaMessageBox.init(lang.getString("Yes"), lang.getString("No")); + + buttonAudioSection.setText(lang.getString("Audio")); + buttonVideoSection.setText(lang.getString("Video")); + buttonMiscSection.setText(lang.getString("Misc")); + buttonNetworkSettings.setText(lang.getString("Network")); + buttonKeyboardSetup.setText(lang.getString("Keyboardsetup")); + + labelVisibleHud.setText(lang.getString("VisibleHUD")); + labelHealthBars.setText(lang.getString("Healthbar")); + + int healthBarSelection = listBoxHealthBars.getSelectedItemIndex(); + listBoxHealthBars.clearItems(); + listBoxHealthBars.pushBackItem(lang.getString("HealthbarsFactionDefault")); + listBoxHealthBars.pushBackItem(lang.getString("HealthbarsOff")); + listBoxHealthBars.pushBackItem(lang.getString("HealthbarsAlways")); + listBoxHealthBars.pushBackItem(lang.getString("HealthbarsIfNeeded")); + listBoxHealthBars.pushBackItem(lang.getString("HealthbarsSelected")); + listBoxHealthBars.pushBackItem(lang.getString("HealthbarsSelectedOrNeeded")); + listBoxHealthBars.setSelectedItemIndex(healthBarSelection); + + labelChatStaysActive.setText(lang.getString("ChatStaysActive")); + labelTimeDisplay.setText(lang.getString("TimeDisplay")); + + labelLuaDisableSecuritySandbox.setText( + lang.getString("LuaDisableSecuritySandbox")); + labelLang.setText(lang.getString("Language")); + labelPlayerNameLabel.setText(lang.getString("Playername")); + labelFontSizeAdjustment.setText(lang.getString("FontSizeAdjustment")); + labelScreenShotType.setText(lang.getString("ScreenShotFileType")); + labelDisableScreenshotConsoleText.setText( + lang.getString("ScreenShotConsoleText")); + labelMouseMoveScrollsWorld.setText(lang.getString("MouseScrollsWorld")); + labelCameraMoveSpeed.setText(lang.getString("CameraMoveSpeed")); + + buttonOk.setText(lang.getString("Save")); + buttonReturn.setText(lang.getString("Return")); + + labelCustomTranslation.setText(lang.getString("CustomTranslation")); + buttonGetNewLanguageFiles.setText( + lang.getString("TransifexGetLanguageFiles")); + buttonDeleteNewLanguageFiles.setText( + lang.getString("TransifexDeleteLanguageFiles")); + labelTransifexUserLabel.setText(lang.getString("TransifexUserName")); + labelTransifexPwdLabel.setText(lang.getString("TransifexPwd")); + labelTransifexI18NLabel.setText(lang.getString("TransifexI18N")); } void MenuStateOptions::setupTransifexUI() { - buttonGetNewLanguageFiles.setEnabled(checkBoxCustomTranslation.getValue()); - buttonDeleteNewLanguageFiles.setEnabled(checkBoxCustomTranslation.getValue()); - labelTransifexUserLabel.setEnabled(checkBoxCustomTranslation.getValue()); - labelTransifexUser.setEnabled(checkBoxCustomTranslation.getValue()); - labelTransifexPwdLabel.setEnabled(checkBoxCustomTranslation.getValue()); - labelTransifexPwd.setEnabled(checkBoxCustomTranslation.getValue()); - labelTransifexI18NLabel.setEnabled(checkBoxCustomTranslation.getValue()); - labelTransifexI18N.setEnabled(checkBoxCustomTranslation.getValue()); + buttonGetNewLanguageFiles.setEnabled(checkBoxCustomTranslation.getValue()); + buttonDeleteNewLanguageFiles.setEnabled(checkBoxCustomTranslation.getValue()); + labelTransifexUserLabel.setEnabled(checkBoxCustomTranslation.getValue()); + labelTransifexUser.setEnabled(checkBoxCustomTranslation.getValue()); + labelTransifexPwdLabel.setEnabled(checkBoxCustomTranslation.getValue()); + labelTransifexPwd.setEnabled(checkBoxCustomTranslation.getValue()); + labelTransifexI18NLabel.setEnabled(checkBoxCustomTranslation.getValue()); + labelTransifexI18N.setEnabled(checkBoxCustomTranslation.getValue()); } -void MenuStateOptions::showMessageBox(const string &text, const string &header, bool toggle){ - if(!toggle){ - mainMessageBox.setEnabled(false); - } - - if(!mainMessageBox.getEnabled()){ - mainMessageBox.setText(text); - mainMessageBox.setHeader(header); - mainMessageBox.setEnabled(true); - } - else{ - mainMessageBox.setEnabled(false); - } +void MenuStateOptions::showMessageBox(const string &text, const string &header, + bool toggle) { + if (!toggle) { + mainMessageBox.setEnabled(false); + } + + if (!mainMessageBox.getEnabled()) { + mainMessageBox.setText(text); + mainMessageBox.setHeader(header); + mainMessageBox.setEnabled(true); + } else { + mainMessageBox.setEnabled(false); + } } -void MenuStateOptions::showLuaMessageBox(const string &text, const string &header, bool toggle) { - if(!toggle) { - luaMessageBox.setEnabled(false); - } - - if(!luaMessageBox.getEnabled()){ - luaMessageBox.setText(text); - luaMessageBox.setHeader(header); - luaMessageBox.setEnabled(true); - } - else{ - luaMessageBox.setEnabled(false); - } +void MenuStateOptions::showLuaMessageBox(const string &text, + const string &header, bool toggle) { + if (!toggle) { + luaMessageBox.setEnabled(false); + } + + if (!luaMessageBox.getEnabled()) { + luaMessageBox.setText(text); + luaMessageBox.setHeader(header); + luaMessageBox.setEnabled(true); + } else { + luaMessageBox.setEnabled(false); + } } -void MenuStateOptions::mouseClick(int x, int y, MouseButton mouseButton){ - - Config &config= Config::getInstance(); - CoreData &coreData= CoreData::getInstance(); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - - if(mainMessageBox.getEnabled()) { - int button= 0; - if(mainMessageBox.mouseClick(x, y, button)) { - soundRenderer.playFx(coreData.getClickSoundA()); - if(button == 0) { - if(mainMessageBoxState == 1) { - mainMessageBoxState=0; - mainMessageBox.setEnabled(false); - saveConfig(); - - Lang &lang= Lang::getInstance(); - mainMessageBox.init(lang.getString("Ok")); - mainMenu->setState(new MenuStateRoot(program, mainMenu)); - } - else { - mainMessageBox.setEnabled(false); - - Lang &lang= Lang::getInstance(); - mainMessageBox.init(lang.getString("Ok")); - } - } - else { - if(mainMessageBoxState == 1) { - mainMessageBoxState=0; - mainMessageBox.setEnabled(false); - - Lang &lang= Lang::getInstance(); - mainMessageBox.init(lang.getString("Ok")); - } - } - } - } - else if(luaMessageBox.getEnabled()){ - int button= 0; - if(luaMessageBox.mouseClick(x, y, button)) { - checkBoxLuaDisableSecuritySandbox.setValue(false); - soundRenderer.playFx(coreData.getClickSoundA()); - if(button == 0) { - if(luaMessageBoxState == 1) { - checkBoxLuaDisableSecuritySandbox.setValue(true); - } - } - luaMessageBox.setEnabled(false); - } - } - else if(checkBoxLuaDisableSecuritySandbox.mouseClick(x, y)) { - if(checkBoxLuaDisableSecuritySandbox.getValue() == true) { - checkBoxLuaDisableSecuritySandbox.setValue(false); - - luaMessageBoxState=1; - Lang &lang= Lang::getInstance(); - showLuaMessageBox(lang.getString("LuaDisableSecuritySandboxWarning"), lang.getString("Question"), false); - } - } - else if(buttonOk.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - - string currentFontSizeAdjustment=config.getString("FontSizeAdjustment"); - string selectedFontSizeAdjustment=listFontSizeAdjustment.getSelectedItem(); - if(currentFontSizeAdjustment != selectedFontSizeAdjustment){ - mainMessageBoxState=1; - Lang &lang= Lang::getInstance(); - showMessageBox(lang.getString("RestartNeeded"), lang.getString("FontSizeAdjustmentChanged"), false); - return; - } - saveConfig(); - //mainMenu->setState(new MenuStateRoot(program, mainMenu)); - reloadUI(); - return; +void MenuStateOptions::mouseClick(int x, int y, MouseButton mouseButton) { + + Config &config = Config::getInstance(); + CoreData &coreData = CoreData::getInstance(); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + + if (mainMessageBox.getEnabled()) { + int button = 0; + if (mainMessageBox.mouseClick(x, y, button)) { + soundRenderer.playFx(coreData.getClickSoundA()); + if (button == 0) { + if (mainMessageBoxState == 1) { + mainMessageBoxState = 0; + mainMessageBox.setEnabled(false); + saveConfig(); + + Lang &lang = Lang::getInstance(); + mainMessageBox.init(lang.getString("Ok")); + mainMenu->setState(new MenuStateRoot(program, mainMenu)); + } else { + mainMessageBox.setEnabled(false); + + Lang &lang = Lang::getInstance(); + mainMessageBox.init(lang.getString("Ok")); + } + } else { + if (mainMessageBoxState == 1) { + mainMessageBoxState = 0; + mainMessageBox.setEnabled(false); + + Lang &lang = Lang::getInstance(); + mainMessageBox.init(lang.getString("Ok")); + } + } } - else if(buttonReturn.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - if(this->parentUI != NULL) { - *this->parentUI = NULL; - delete *this->parentUI; - } - mainMenu->setState(new MenuStateRoot(program, mainMenu)); - return; + } else if (luaMessageBox.getEnabled()) { + int button = 0; + if (luaMessageBox.mouseClick(x, y, button)) { + checkBoxLuaDisableSecuritySandbox.setValue(false); + soundRenderer.playFx(coreData.getClickSoundA()); + if (button == 0) { + if (luaMessageBoxState == 1) { + checkBoxLuaDisableSecuritySandbox.setValue(true); + } + } + luaMessageBox.setEnabled(false); } - else if(buttonKeyboardSetup.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - mainMenu->setState(new MenuStateKeysetup(program, mainMenu,this->parentUI)); // open keyboard shortcuts setup screen - //showMessageBox("Not implemented yet", "Keyboard setup", false); - return; - } - else if(buttonAudioSection.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - mainMenu->setState(new MenuStateOptionsSound(program, mainMenu,this->parentUI)); // open keyboard shortcuts setup screen - return; - } - else if(buttonNetworkSettings.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - mainMenu->setState(new MenuStateOptionsNetwork(program, mainMenu,this->parentUI)); // open keyboard shortcuts setup screen - return; - } - else if(buttonMiscSection.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - //mainMenu->setState(new MenuStateOptions(program, mainMenu,this->parentUI)); // open keyboard shortcuts setup screen - return; - } - else if(buttonVideoSection.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - mainMenu->setState(new MenuStateOptionsGraphics(program, mainMenu,this->parentUI)); // open keyboard shortcuts setup screen - return; - } - else if(checkBoxCustomTranslation.mouseClick(x, y)) { - setupTransifexUI(); - } - else if(buttonDeleteNewLanguageFiles.mouseClick(x, y)) { - soundRenderer.playFx(coreData.getClickSoundA()); - - setActiveInputLable(NULL); - - if(labelTransifexI18N.getText() != "") { - Lang &lang= Lang::getInstance(); - string language = lang.getLanguageFile(labelTransifexI18N.getText()); - replaceAll(language,"(",""); - replaceAll(language,")",""); - - if(language != "") { - bool foundFilesToDelete = false; - - Config &config = Config::getInstance(); - string data_path = config.getString("UserData_Root",""); - if(data_path != "") { - endPathWithSlash(data_path); - } - - if(data_path != "") { - - string txnURLFileListMapping = Config::getInstance().getString("TranslationGetURLFileListMapping"); - vector languageFileMappings; - Tokenize(txnURLFileListMapping,languageFileMappings,"|"); - - Config &config = Config::getInstance(); - - // Cleanup Scenarios - vector scenarioPaths = config.getPathListForType(ptScenarios); - if(scenarioPaths.size() > 1) { - string &scenarioPath = scenarioPaths[1]; - endPathWithSlash(scenarioPath); - - vector scenarioList; - findDirs(scenarioPath, scenarioList, false,false); - for(unsigned int i = 0; i < scenarioList.size(); ++i) { - string scenario = scenarioList[i]; - - vector langResults; - findAll(scenarioPath + scenario + "/*.lng", langResults, false, false); - for(unsigned int j = 0; j < langResults.size(); ++j) { - string testLanguage = langResults[j]; - - string removeLngFile = scenarioPath + scenario + "/" + testLanguage; - - if(EndsWith(testLanguage,language + ".lng") == true) { - - for(unsigned int k = 0; k < languageFileMappings.size(); ++k) { - string mapping = languageFileMappings[k]; - replaceAll(mapping,"$language",language); - - //printf("Comparing found [%s] with [%s]\n",removeLngFile.c_str(),mapping.c_str()); - - if(EndsWith(removeLngFile,mapping) == true) { - printf("About to delete file [%s]\n",removeLngFile.c_str()); - removeFile(removeLngFile); - foundFilesToDelete = true; - break; - } - } - } - } - } - } - - // Cleanup tutorials - vector tutorialPaths = config.getPathListForType(ptTutorials); - if(tutorialPaths.size() > 1) { - string &tutorialPath = tutorialPaths[1]; - endPathWithSlash(tutorialPath); - - vector tutorialList; - findDirs(tutorialPath, tutorialList, false, false); - for(unsigned int i = 0; i < tutorialList.size(); ++i) { - string tutorial = tutorialList[i]; - - vector langResults; - findAll(tutorialPath + tutorial + "/*.lng", langResults, false, false); - for(unsigned int j = 0; j < langResults.size(); ++j) { - string testLanguage = langResults[j]; - - string removeLngFile = tutorialPath + tutorial + "/" + testLanguage; - if(EndsWith(testLanguage,language + ".lng") == true) { - - - for(unsigned int k = 0; k < languageFileMappings.size(); ++k) { - string mapping = languageFileMappings[k]; - replaceAll(mapping,"$language",language); - - //printf("Comparing found [%s] with [%s]\n",removeLngFile.c_str(),mapping.c_str()); - - if(EndsWith(removeLngFile,mapping) == true) { - printf("About to delete file [%s]\n",removeLngFile.c_str()); - removeFile(removeLngFile); - foundFilesToDelete = true; - break; - } - } - } - } - } - } - - // Cleanup main and hint language files - string mainLngFile = data_path + "data/lang/" + language + ".lng"; - if(fileExists(mainLngFile) == true) { - - for(unsigned int k = 0; k < languageFileMappings.size(); ++k) { - string mapping = languageFileMappings[k]; - replaceAll(mapping,"$language",language); - - if(EndsWith(mainLngFile,mapping) == true) { - printf("About to delete file [%s]\n",mainLngFile.c_str()); - removeFile(mainLngFile); - foundFilesToDelete = true; - break; - } - } - } - - string hintLngFile = data_path + "data/lang/hint/hint_" + language + ".lng"; - if(fileExists(hintLngFile) == true) { - for(unsigned int k = 0; k < languageFileMappings.size(); ++k) { - string mapping = languageFileMappings[k]; - replaceAll(mapping,"$language",language); - - if(EndsWith(hintLngFile,mapping) == true) { - printf("About to delete file [%s]\n",hintLngFile.c_str()); - removeFile(hintLngFile); - foundFilesToDelete = true; - break; - } - } - } - } - - if(lang.isLanguageLocal(toLower(language)) == true) { - lang.loadGameStrings(toLower(language)); - } - - if(foundFilesToDelete == true) { - mainMessageBoxState=0; - Lang &lang= Lang::getInstance(); - showMessageBox(lang.getString("TransifexDeleteSuccess"), lang.getString("Notice"), false); - } - } - } - } - else if(buttonGetNewLanguageFiles.mouseClick(x, y)) { - soundRenderer.playFx(coreData.getClickSoundA()); - - setActiveInputLable(NULL); - - string orig_txnURLUser = Config::getInstance().getString("TranslationGetURLUser"); - //string orig_txnURLPwd = Config::getInstance().getString("TranslationGetURLPassword",""); - string orig_txnURLLang = Config::getInstance().getString("TranslationGetURLLanguage"); - - Config::getInstance().setString("TranslationGetURLUser",labelTransifexUser.getText()); - Config::getInstance().setString("TranslationGetURLPassword",labelTransifexPwd.getText(),true); - Config::getInstance().setString("TranslationGetURLLanguage",labelTransifexI18N.getText()); - - bool saveChanges = (orig_txnURLUser != labelTransifexUser.getText() || - orig_txnURLLang != labelTransifexI18N.getText()); - - string txnURL = Config::getInstance().getString("TranslationGetURL"); - string txnURLUser = Config::getInstance().getString("TranslationGetURLUser"); - string txnURLPwd = Config::getInstance().getString("TranslationGetURLPassword"); - string txnURLLang = Config::getInstance().getString("TranslationGetURLLanguage"); - string txnURLFileList = Config::getInstance().getString("TranslationGetURLFileList"); - string txnURLFileListMapping = Config::getInstance().getString("TranslationGetURLFileListMapping"); - - string txnURLDetails = Config::getInstance().getString("TranslationGetURLDetails"); - - string credentials = txnURLUser + ":" + txnURLPwd; - - printf("URL1 [%s] credentials [%s]\n",txnURL.c_str(),credentials.c_str()); - - //txnURLUser = SystemFlags::escapeURL(txnURLUser,handle); - //replaceAll(txnURL,"$user",txnURLUser); - - //printf("URL2 [%s]\n",txnURL.c_str()); - - //txnURLPwd = SystemFlags::escapeURL(txnURLPwd,handle); - //replaceAll(txnURL,"$password",txnURLPwd); - - //printf("URL3 [%s]\n",txnURL.c_str()); - - replaceAll(txnURL,"$language",txnURLLang); - - printf("URL4 [%s]\n",txnURL.c_str()); - - //txnURLFileList - vector languageFiles; - Tokenize(txnURLFileList,languageFiles,"|"); - - vector languageFileMappings; - Tokenize(txnURLFileListMapping,languageFileMappings,"|"); - - printf("URL5 file count = " MG_SIZE_T_SPECIFIER ", " MG_SIZE_T_SPECIFIER " [%s]\n",languageFiles.size(),languageFileMappings.size(),(languageFiles.empty() == false ? languageFiles[0].c_str() : "")); - - if(languageFiles.empty() == false) { - - bool gotDownloads = false; - bool reloadLanguage = false; - string langName = ""; - - CURL *handle = SystemFlags::initHTTP(); - for(unsigned int i = 0; i < languageFiles.size(); ++i) { - string fileURL = txnURL; - replaceAll(fileURL,"$file",languageFiles[i]); - - if(langName == "") { - // Get language name for file - string fileURLDetails = txnURLDetails; - replaceAll(fileURLDetails,"$file",languageFiles[0]); - - printf(" i = %u Trying [%s]\n",i,fileURLDetails.c_str()); - curl_easy_setopt(handle, CURLOPT_VERBOSE, 1); - curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, 0L); - curl_easy_setopt(handle, CURLOPT_USERPWD, credentials.c_str()); - std::string fileDataDetails = SystemFlags::getHTTP(fileURLDetails,handle); - - // "available_languages": [ - // { - // "code_aliases": " ", - // "code": "ca", - // "name": "Catalan" - // }, - // { - // "code_aliases": " ", - // "code": "zh", - // "name": "Chinese" - // }, - // curl -i -L --user softcoder -X GET https://www.transifex.com/api/2/project/megaglest/resource/main-language-file/?details - - string search_detail_key = "\"code\": \"" + txnURLLang + "\""; - size_t posDetails = fileDataDetails.find( search_detail_key, 0 ); - if( posDetails != fileDataDetails.npos ) { - posDetails = fileDataDetails.find( "\"name\": \"", posDetails+search_detail_key.length() ); - - if( posDetails != fileDataDetails.npos ) { - - size_t posDetailsEnd = fileDataDetails.find( "\"", posDetails + 9 ); - - langName = fileDataDetails.substr(posDetails + 9, posDetailsEnd - (posDetails + 9)); - replaceAll(langName,",",""); - replaceAll(langName,"\\",""); - replaceAll(langName,"/",""); - replaceAll(langName,"?",""); - replaceAll(langName,":",""); - replaceAll(langName,"@",""); - replaceAll(langName,"!",""); - replaceAll(langName,"*",""); - replaceAll(langName,"(",""); - replaceAll(langName,")",""); - langName = trim(langName); - replaceAll(langName," ","-"); - } - - printf("PARSED Language filename [%s]\n",langName.c_str()); - } - } - - printf("i = %u Trying [%s]\n",i,fileURL.c_str()); - curl_easy_setopt(handle, CURLOPT_VERBOSE, 1); - curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, 0L); - curl_easy_setopt(handle, CURLOPT_USERPWD, credentials.c_str()); - std::string fileData = SystemFlags::getHTTP(fileURL,handle); - - // "content": " - // ", - // "mimetype": "text/plain" - size_t pos = fileData.find( "\"content\": \"", 0 ); - if( pos != fileData.npos ) { - fileData = fileData.substr(pos+12, fileData.length()); - - pos = fileData.find( "\",\n", 0 ); - if( pos != fileData.npos ) { - fileData = fileData.substr(0, pos); - } - - replaceAll(fileData,"\\\\n","$requires-newline$"); - replaceAll(fileData,"\\n","\n"); - replaceAll(fileData,"$requires-newline$","\\n"); - - //replaceAll(fileData,""","\""); - replaceAllHTMLEntities(fileData); - - - printf("PARSED Language text\n[%s]\n",fileData.c_str()); - - //vector languageName; - //Tokenize(fileData,languageName," "); - //printf("PARSED Language Name guessed to be [%s]\n",languageName[1].c_str()); - - //string data_path= getGameReadWritePath(GameConstants::path_data_CacheLookupKey); - //if(data_path != ""){ - //endPathWithSlash(data_path); - //} - Config &config = Config::getInstance(); - string data_path = config.getString("UserData_Root",""); - if(data_path != "") { - endPathWithSlash(data_path); - } - - string outputFile = languageFileMappings[i]; - replaceAll(outputFile,"$language",toLower(langName)); - //string lngFile = getGameCustomCoreDataPath(data_path, "data/lang/" + toLower(languageName[1]) + ".lng"); - string lngFile = getGameCustomCoreDataPath(data_path, outputFile); - - string lngPath = extractDirectoryPathFromFile(lngFile); - createDirectoryPaths(lngPath); - - printf("Save data to Language Name [%s]\n",lngFile.c_str()); - saveDataToFile(lngFile, fileData); - gotDownloads = true; - - reloadLanguage = true; - if(saveChanges == true) { - saveChanges = false; - config.save(); - } - } - else { - printf("UNPARSED Language text\n[%s]\n",fileData.c_str()); - } - } - - SystemFlags::cleanupHTTP(&handle); - - if(reloadLanguage == true && langName != "") { - Lang &lang= Lang::getInstance(); - if(lang.isLanguageLocal(toLower(langName)) == true) { - lang.loadGameStrings(toLower(langName)); - } - } - - if(gotDownloads == true) { - mainMessageBoxState=0; - Lang &lang= Lang::getInstance(); - showMessageBox(lang.getString("TransifexDownloadSuccess") + "\n" + langName, lang.getString("Notice"), false); - } - } - return; - } - else if(labelPlayerName.mouseClick(x, y) && ( activeInputLabel != &labelPlayerName )){ - setActiveInputLable(&labelPlayerName); - } - else if(labelTransifexUser.mouseClick(x, y) && ( activeInputLabel != &labelTransifexUser )){ - setActiveInputLable(&labelTransifexUser); - } - else if(labelTransifexPwd.mouseClick(x, y) && ( activeInputLabel != &labelTransifexPwd )){ - setActiveInputLable(&labelTransifexPwd); - } - else if(labelTransifexI18N.mouseClick(x, y) && ( activeInputLabel != &labelTransifexI18N )){ - setActiveInputLable(&labelTransifexI18N); - } - else - { - listBoxLang.mouseClick(x, y); - listFontSizeAdjustment.mouseClick(x, y); - - listBoxScreenShotType.mouseClick(x, y); - - checkBoxDisableScreenshotConsoleText.mouseClick(x, y); - checkBoxMouseMoveScrollsWorld.mouseClick(x, y); - listCameraMoveSpeed.mouseClick(x, y); - checkBoxVisibleHud.mouseClick(x, y); - listBoxHealthBars.mouseClick(x, y); - checkBoxChatStaysActive.mouseClick(x, y); - checkBoxTimeDisplay.mouseClick(x, y); - checkBoxLuaDisableSecuritySandbox.mouseClick(x, y); - } + } else if (checkBoxLuaDisableSecuritySandbox.mouseClick(x, y)) { + if (checkBoxLuaDisableSecuritySandbox.getValue() == true) { + checkBoxLuaDisableSecuritySandbox.setValue(false); + + luaMessageBoxState = 1; + Lang &lang = Lang::getInstance(); + showLuaMessageBox(lang.getString("LuaDisableSecuritySandboxWarning"), + lang.getString("Question"), false); + } + } else if (buttonOk.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + + string currentFontSizeAdjustment = config.getString("FontSizeAdjustment"); + string selectedFontSizeAdjustment = + listFontSizeAdjustment.getSelectedItem(); + if (currentFontSizeAdjustment != selectedFontSizeAdjustment) { + mainMessageBoxState = 1; + Lang &lang = Lang::getInstance(); + showMessageBox(lang.getString("RestartNeeded"), + lang.getString("FontSizeAdjustmentChanged"), false); + return; + } + saveConfig(); + // mainMenu->setState(new MenuStateRoot(program, mainMenu)); + reloadUI(); + return; + } else if (buttonReturn.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + if (this->parentUI != NULL) { + *this->parentUI = NULL; + delete *this->parentUI; + } + mainMenu->setState(new MenuStateRoot(program, mainMenu)); + return; + } else if (buttonKeyboardSetup.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + mainMenu->setState(new MenuStateKeysetup( + program, mainMenu, + this->parentUI)); // open keyboard shortcuts setup screen + // showMessageBox("Not implemented yet", "Keyboard setup", false); + return; + } else if (buttonAudioSection.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + mainMenu->setState(new MenuStateOptionsSound( + program, mainMenu, + this->parentUI)); // open keyboard shortcuts setup screen + return; + } else if (buttonNetworkSettings.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + mainMenu->setState(new MenuStateOptionsNetwork( + program, mainMenu, + this->parentUI)); // open keyboard shortcuts setup screen + return; + } else if (buttonMiscSection.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + // mainMenu->setState(new MenuStateOptions(program, + // mainMenu,this->parentUI)); // open keyboard shortcuts setup screen + return; + } else if (buttonVideoSection.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + mainMenu->setState(new MenuStateOptionsGraphics( + program, mainMenu, + this->parentUI)); // open keyboard shortcuts setup screen + return; + } else if (checkBoxCustomTranslation.mouseClick(x, y)) { + setupTransifexUI(); + } else if (buttonDeleteNewLanguageFiles.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + + setActiveInputLable(NULL); + + if (labelTransifexI18N.getText() != "") { + Lang &lang = Lang::getInstance(); + string language = lang.getLanguageFile(labelTransifexI18N.getText()); + replaceAll(language, "(", ""); + replaceAll(language, ")", ""); + + if (language != "") { + bool foundFilesToDelete = false; + + Config &config = Config::getInstance(); + string data_path = config.getString("UserData_Root", ""); + if (data_path != "") { + endPathWithSlash(data_path); + } + + if (data_path != "") { + + string txnURLFileListMapping = Config::getInstance().getString( + "TranslationGetURLFileListMapping"); + vector languageFileMappings; + Tokenize(txnURLFileListMapping, languageFileMappings, "|"); + + Config &config = Config::getInstance(); + + // Cleanup Scenarios + vector scenarioPaths = config.getPathListForType(ptScenarios); + if (scenarioPaths.size() > 1) { + string &scenarioPath = scenarioPaths[1]; + endPathWithSlash(scenarioPath); + + vector scenarioList; + findDirs(scenarioPath, scenarioList, false, false); + for (unsigned int i = 0; i < scenarioList.size(); ++i) { + string scenario = scenarioList[i]; + + vector langResults; + findAll(scenarioPath + scenario + "/*.lng", langResults, false, + false); + for (unsigned int j = 0; j < langResults.size(); ++j) { + string testLanguage = langResults[j]; + + string removeLngFile = + scenarioPath + scenario + "/" + testLanguage; + + if (EndsWith(testLanguage, language + ".lng") == true) { + + for (unsigned int k = 0; k < languageFileMappings.size(); + ++k) { + string mapping = languageFileMappings[k]; + replaceAll(mapping, "$language", language); + + // printf("Comparing found [%s] with + // [%s]\n",removeLngFile.c_str(),mapping.c_str()); + + if (EndsWith(removeLngFile, mapping) == true) { + printf("About to delete file [%s]\n", + removeLngFile.c_str()); + removeFile(removeLngFile); + foundFilesToDelete = true; + break; + } + } + } + } + } + } + + // Cleanup tutorials + vector tutorialPaths = config.getPathListForType(ptTutorials); + if (tutorialPaths.size() > 1) { + string &tutorialPath = tutorialPaths[1]; + endPathWithSlash(tutorialPath); + + vector tutorialList; + findDirs(tutorialPath, tutorialList, false, false); + for (unsigned int i = 0; i < tutorialList.size(); ++i) { + string tutorial = tutorialList[i]; + + vector langResults; + findAll(tutorialPath + tutorial + "/*.lng", langResults, false, + false); + for (unsigned int j = 0; j < langResults.size(); ++j) { + string testLanguage = langResults[j]; + + string removeLngFile = + tutorialPath + tutorial + "/" + testLanguage; + if (EndsWith(testLanguage, language + ".lng") == true) { + + for (unsigned int k = 0; k < languageFileMappings.size(); + ++k) { + string mapping = languageFileMappings[k]; + replaceAll(mapping, "$language", language); + + // printf("Comparing found [%s] with + // [%s]\n",removeLngFile.c_str(),mapping.c_str()); + + if (EndsWith(removeLngFile, mapping) == true) { + printf("About to delete file [%s]\n", + removeLngFile.c_str()); + removeFile(removeLngFile); + foundFilesToDelete = true; + break; + } + } + } + } + } + } + + // Cleanup main and hint language files + string mainLngFile = data_path + "data/lang/" + language + ".lng"; + if (fileExists(mainLngFile) == true) { + + for (unsigned int k = 0; k < languageFileMappings.size(); ++k) { + string mapping = languageFileMappings[k]; + replaceAll(mapping, "$language", language); + + if (EndsWith(mainLngFile, mapping) == true) { + printf("About to delete file [%s]\n", mainLngFile.c_str()); + removeFile(mainLngFile); + foundFilesToDelete = true; + break; + } + } + } + + string hintLngFile = + data_path + "data/lang/hint/hint_" + language + ".lng"; + if (fileExists(hintLngFile) == true) { + for (unsigned int k = 0; k < languageFileMappings.size(); ++k) { + string mapping = languageFileMappings[k]; + replaceAll(mapping, "$language", language); + + if (EndsWith(hintLngFile, mapping) == true) { + printf("About to delete file [%s]\n", hintLngFile.c_str()); + removeFile(hintLngFile); + foundFilesToDelete = true; + break; + } + } + } + } + + if (lang.isLanguageLocal(toLower(language)) == true) { + lang.loadGameStrings(toLower(language)); + } + + if (foundFilesToDelete == true) { + mainMessageBoxState = 0; + Lang &lang = Lang::getInstance(); + showMessageBox(lang.getString("TransifexDeleteSuccess"), + lang.getString("Notice"), false); + } + } + } + } else if (buttonGetNewLanguageFiles.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + + setActiveInputLable(NULL); + + string orig_txnURLUser = + Config::getInstance().getString("TranslationGetURLUser"); + // string orig_txnURLPwd = + // Config::getInstance().getString("TranslationGetURLPassword",""); + string orig_txnURLLang = + Config::getInstance().getString("TranslationGetURLLanguage"); + + Config::getInstance().setString("TranslationGetURLUser", + labelTransifexUser.getText()); + Config::getInstance().setString("TranslationGetURLPassword", + labelTransifexPwd.getText(), true); + Config::getInstance().setString("TranslationGetURLLanguage", + labelTransifexI18N.getText()); + + bool saveChanges = (orig_txnURLUser != labelTransifexUser.getText() || + orig_txnURLLang != labelTransifexI18N.getText()); + + string txnURL = Config::getInstance().getString("TranslationGetURL"); + string txnURLUser = + Config::getInstance().getString("TranslationGetURLUser"); + string txnURLPwd = + Config::getInstance().getString("TranslationGetURLPassword"); + string txnURLLang = + Config::getInstance().getString("TranslationGetURLLanguage"); + string txnURLFileList = + Config::getInstance().getString("TranslationGetURLFileList"); + string txnURLFileListMapping = + Config::getInstance().getString("TranslationGetURLFileListMapping"); + + string txnURLDetails = + Config::getInstance().getString("TranslationGetURLDetails"); + + string credentials = txnURLUser + ":" + txnURLPwd; + + printf("URL1 [%s] credentials [%s]\n", txnURL.c_str(), credentials.c_str()); + + // txnURLUser = SystemFlags::escapeURL(txnURLUser,handle); + // replaceAll(txnURL,"$user",txnURLUser); + + // printf("URL2 [%s]\n",txnURL.c_str()); + + // txnURLPwd = SystemFlags::escapeURL(txnURLPwd,handle); + // replaceAll(txnURL,"$password",txnURLPwd); + + // printf("URL3 [%s]\n",txnURL.c_str()); + + replaceAll(txnURL, "$language", txnURLLang); + + printf("URL4 [%s]\n", txnURL.c_str()); + + // txnURLFileList + vector languageFiles; + Tokenize(txnURLFileList, languageFiles, "|"); + + vector languageFileMappings; + Tokenize(txnURLFileListMapping, languageFileMappings, "|"); + + printf("URL5 file count = " MG_SIZE_T_SPECIFIER ", " MG_SIZE_T_SPECIFIER + " [%s]\n", + languageFiles.size(), languageFileMappings.size(), + (languageFiles.empty() == false ? languageFiles[0].c_str() : "")); + + if (languageFiles.empty() == false) { + + bool gotDownloads = false; + bool reloadLanguage = false; + string langName = ""; + + CURL *handle = SystemFlags::initHTTP(); + for (unsigned int i = 0; i < languageFiles.size(); ++i) { + string fileURL = txnURL; + replaceAll(fileURL, "$file", languageFiles[i]); + + if (langName == "") { + // Get language name for file + string fileURLDetails = txnURLDetails; + replaceAll(fileURLDetails, "$file", languageFiles[0]); + + printf(" i = %u Trying [%s]\n", i, fileURLDetails.c_str()); + curl_easy_setopt(handle, CURLOPT_VERBOSE, 1); + curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, 0L); + curl_easy_setopt(handle, CURLOPT_USERPWD, credentials.c_str()); + std::string fileDataDetails = + SystemFlags::getHTTP(fileURLDetails, handle); + + // "available_languages": [ + // { + // "code_aliases": " ", + // "code": "ca", + // "name": "Catalan" + // }, + // { + // "code_aliases": " ", + // "code": "zh", + // "name": "Chinese" + // }, + // curl -i -L --user softcoder -X GET + // https://www.transifex.com/api/2/project/megaglest/resource/main-language-file/?details + + string search_detail_key = "\"code\": \"" + txnURLLang + "\""; + size_t posDetails = fileDataDetails.find(search_detail_key, 0); + if (posDetails != fileDataDetails.npos) { + posDetails = fileDataDetails.find( + "\"name\": \"", posDetails + search_detail_key.length()); + + if (posDetails != fileDataDetails.npos) { + + size_t posDetailsEnd = fileDataDetails.find("\"", posDetails + 9); + + langName = fileDataDetails.substr( + posDetails + 9, posDetailsEnd - (posDetails + 9)); + replaceAll(langName, ",", ""); + replaceAll(langName, "\\", ""); + replaceAll(langName, "/", ""); + replaceAll(langName, "?", ""); + replaceAll(langName, ":", ""); + replaceAll(langName, "@", ""); + replaceAll(langName, "!", ""); + replaceAll(langName, "*", ""); + replaceAll(langName, "(", ""); + replaceAll(langName, ")", ""); + langName = trim(langName); + replaceAll(langName, " ", "-"); + } + + printf("PARSED Language filename [%s]\n", langName.c_str()); + } + } + + printf("i = %u Trying [%s]\n", i, fileURL.c_str()); + curl_easy_setopt(handle, CURLOPT_VERBOSE, 1); + curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, 0L); + curl_easy_setopt(handle, CURLOPT_USERPWD, credentials.c_str()); + std::string fileData = SystemFlags::getHTTP(fileURL, handle); + + // "content": " + // ", + // "mimetype": "text/plain" + size_t pos = fileData.find("\"content\": \"", 0); + if (pos != fileData.npos) { + fileData = fileData.substr(pos + 12, fileData.length()); + + pos = fileData.find("\",\n", 0); + if (pos != fileData.npos) { + fileData = fileData.substr(0, pos); + } + + replaceAll(fileData, "\\\\n", "$requires-newline$"); + replaceAll(fileData, "\\n", "\n"); + replaceAll(fileData, "$requires-newline$", "\\n"); + + // replaceAll(fileData,""","\""); + replaceAllHTMLEntities(fileData); + + printf("PARSED Language text\n[%s]\n", fileData.c_str()); + + // vector languageName; + // Tokenize(fileData,languageName," "); + // printf("PARSED Language Name guessed to be + // [%s]\n",languageName[1].c_str()); + + // string data_path= + // getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + // if(data_path != ""){ + // endPathWithSlash(data_path); + //} + Config &config = Config::getInstance(); + string data_path = config.getString("UserData_Root", ""); + if (data_path != "") { + endPathWithSlash(data_path); + } + + string outputFile = languageFileMappings[i]; + replaceAll(outputFile, "$language", toLower(langName)); + // string lngFile = getGameCustomCoreDataPath(data_path, "data/lang/" + // + toLower(languageName[1]) + ".lng"); + string lngFile = getGameCustomCoreDataPath(data_path, outputFile); + + string lngPath = extractDirectoryPathFromFile(lngFile); + createDirectoryPaths(lngPath); + + printf("Save data to Language Name [%s]\n", lngFile.c_str()); + saveDataToFile(lngFile, fileData); + gotDownloads = true; + + reloadLanguage = true; + if (saveChanges == true) { + saveChanges = false; + config.save(); + } + } else { + printf("UNPARSED Language text\n[%s]\n", fileData.c_str()); + } + } + + SystemFlags::cleanupHTTP(&handle); + + if (reloadLanguage == true && langName != "") { + Lang &lang = Lang::getInstance(); + if (lang.isLanguageLocal(toLower(langName)) == true) { + lang.loadGameStrings(toLower(langName)); + } + } + + if (gotDownloads == true) { + mainMessageBoxState = 0; + Lang &lang = Lang::getInstance(); + showMessageBox(lang.getString("TransifexDownloadSuccess") + "\n" + + langName, + lang.getString("Notice"), false); + } + } + return; + } else if (labelPlayerName.mouseClick(x, y) && + (activeInputLabel != &labelPlayerName)) { + setActiveInputLable(&labelPlayerName); + } else if (labelTransifexUser.mouseClick(x, y) && + (activeInputLabel != &labelTransifexUser)) { + setActiveInputLable(&labelTransifexUser); + } else if (labelTransifexPwd.mouseClick(x, y) && + (activeInputLabel != &labelTransifexPwd)) { + setActiveInputLable(&labelTransifexPwd); + } else if (labelTransifexI18N.mouseClick(x, y) && + (activeInputLabel != &labelTransifexI18N)) { + setActiveInputLable(&labelTransifexI18N); + } else { + listBoxLang.mouseClick(x, y); + listFontSizeAdjustment.mouseClick(x, y); + + listBoxScreenShotType.mouseClick(x, y); + + checkBoxDisableScreenshotConsoleText.mouseClick(x, y); + checkBoxMouseMoveScrollsWorld.mouseClick(x, y); + listCameraMoveSpeed.mouseClick(x, y); + checkBoxVisibleHud.mouseClick(x, y); + listBoxHealthBars.mouseClick(x, y); + checkBoxChatStaysActive.mouseClick(x, y); + checkBoxTimeDisplay.mouseClick(x, y); + checkBoxLuaDisableSecuritySandbox.mouseClick(x, y); + } } -void MenuStateOptions::mouseMove(int x, int y, const MouseState *ms){ - if (mainMessageBox.getEnabled()) { - mainMessageBox.mouseMove(x, y); - } - if (luaMessageBox.getEnabled()) { - luaMessageBox.mouseMove(x, y); - } - - buttonOk.mouseMove(x, y); - buttonReturn.mouseMove(x, y); - buttonKeyboardSetup.mouseMove(x, y); - buttonAudioSection.mouseMove(x, y); - buttonNetworkSettings.mouseMove(x, y); - buttonMiscSection.mouseMove(x, y); - buttonVideoSection.mouseMove(x, y); - buttonGetNewLanguageFiles.mouseMove(x, y); - buttonDeleteNewLanguageFiles.mouseMove(x, y); - listBoxLang.mouseMove(x, y); - listBoxLang.mouseMove(x, y); - listFontSizeAdjustment.mouseMove(x, y); - listBoxScreenShotType.mouseMove(x, y); - checkBoxDisableScreenshotConsoleText.mouseMove(x, y); - checkBoxMouseMoveScrollsWorld.mouseMove(x, y); - listCameraMoveSpeed.mouseMove(x, y); - listBoxHealthBars.mouseMove(x, y); - checkBoxVisibleHud.mouseMove(x, y); - checkBoxChatStaysActive.mouseMove(x, y); - checkBoxTimeDisplay.mouseMove(x, y); - checkBoxLuaDisableSecuritySandbox.mouseMove(x, y); - checkBoxCustomTranslation.mouseMove(x, y); +void MenuStateOptions::mouseMove(int x, int y, const MouseState *ms) { + if (mainMessageBox.getEnabled()) { + mainMessageBox.mouseMove(x, y); + } + if (luaMessageBox.getEnabled()) { + luaMessageBox.mouseMove(x, y); + } + + buttonOk.mouseMove(x, y); + buttonReturn.mouseMove(x, y); + buttonKeyboardSetup.mouseMove(x, y); + buttonAudioSection.mouseMove(x, y); + buttonNetworkSettings.mouseMove(x, y); + buttonMiscSection.mouseMove(x, y); + buttonVideoSection.mouseMove(x, y); + buttonGetNewLanguageFiles.mouseMove(x, y); + buttonDeleteNewLanguageFiles.mouseMove(x, y); + listBoxLang.mouseMove(x, y); + listBoxLang.mouseMove(x, y); + listFontSizeAdjustment.mouseMove(x, y); + listBoxScreenShotType.mouseMove(x, y); + checkBoxDisableScreenshotConsoleText.mouseMove(x, y); + checkBoxMouseMoveScrollsWorld.mouseMove(x, y); + listCameraMoveSpeed.mouseMove(x, y); + listBoxHealthBars.mouseMove(x, y); + checkBoxVisibleHud.mouseMove(x, y); + checkBoxChatStaysActive.mouseMove(x, y); + checkBoxTimeDisplay.mouseMove(x, y); + checkBoxLuaDisableSecuritySandbox.mouseMove(x, y); + checkBoxCustomTranslation.mouseMove(x, y); } bool MenuStateOptions::isInSpecialKeyCaptureEvent() { - return (activeInputLabel != NULL); + return (activeInputLabel != NULL); } void MenuStateOptions::keyDown(SDL_KeyboardEvent key) { - if(activeInputLabel != NULL) { - keyDownEditLabel(key, &activeInputLabel); - } + if (activeInputLabel != NULL) { + keyDownEditLabel(key, &activeInputLabel); + } } bool MenuStateOptions::textInput(std::string text) { - if(activeInputLabel != NULL) { - //printf("[%d]\n",c); fflush(stdout); - if( &labelPlayerName == activeInputLabel || - &labelTransifexUser == activeInputLabel || - &labelTransifexPwd == activeInputLabel || - &labelTransifexI18N == activeInputLabel) { - return textInputEditLabel(text, &activeInputLabel); - } - } - return false; + if (activeInputLabel != NULL) { + // printf("[%d]\n",c); fflush(stdout); + if (&labelPlayerName == activeInputLabel || + &labelTransifexUser == activeInputLabel || + &labelTransifexPwd == activeInputLabel || + &labelTransifexI18N == activeInputLabel) { + return textInputEditLabel(text, &activeInputLabel); + } + } + return false; } void MenuStateOptions::keyPress(SDL_KeyboardEvent c) { - if (activeInputLabel != NULL) { - keyPressEditLabel(c, &activeInputLabel); - } else { - Config &configKeys = Config::getInstance( - std::pair(cfgMainKeys, cfgUserKeys)); - if (isKeyPressed(configKeys.getSDLKey("SaveGUILayout"), c) == true) { - GraphicComponent::saveAllCustomProperties(containerName); - //Lang &lang= Lang::getInstance(); - //console.addLine(lang.getString("GUILayoutSaved") + " [" + (saved ? lang.getString("Yes") : lang.getString("No"))+ "]"); - } - } + if (activeInputLabel != NULL) { + keyPressEditLabel(c, &activeInputLabel); + } else { + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + if (isKeyPressed(configKeys.getSDLKey("SaveGUILayout"), c) == true) { + GraphicComponent::saveAllCustomProperties(containerName); + // Lang &lang= Lang::getInstance(); + // console.addLine(lang.getString("GUILayoutSaved") + " [" + (saved ? + // lang.getString("Yes") : lang.getString("No"))+ "]"); + } + } } -void MenuStateOptions::render(){ - Renderer &renderer= Renderer::getInstance(); -// char szBuf[8096]=""; -// snprintf(szBuf,8096,"\nIn [%s::%s Line: %d]\n\nRender options menu [%p]!\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this); -// printf(szBuf); - - if(mainMessageBox.getEnabled()){ - renderer.renderMessageBox(&mainMessageBox); - } - else if(luaMessageBox.getEnabled()){ - renderer.renderMessageBox(&luaMessageBox); - } - else - { - renderer.renderButton(&buttonOk); - renderer.renderButton(&buttonReturn); - renderer.renderButton(&buttonKeyboardSetup); - renderer.renderButton(&buttonVideoSection); - renderer.renderButton(&buttonAudioSection); - renderer.renderButton(&buttonMiscSection); - renderer.renderButton(&buttonNetworkSettings); - - renderer.renderLabel(&labelCustomTranslation); - renderer.renderCheckBox(&checkBoxCustomTranslation); - - if(buttonGetNewLanguageFiles.getEnabled()) renderer.renderButton(&buttonGetNewLanguageFiles); - if(buttonDeleteNewLanguageFiles.getEnabled()) renderer.renderButton(&buttonDeleteNewLanguageFiles); - if(labelTransifexUserLabel.getEnabled()) renderer.renderLabel(&labelTransifexUserLabel); - if(labelTransifexPwdLabel.getEnabled()) renderer.renderLabel(&labelTransifexPwdLabel); - if(labelTransifexI18NLabel.getEnabled()) renderer.renderLabel(&labelTransifexI18NLabel); - if(labelTransifexUser.getEnabled()) renderer.renderLabel(&labelTransifexUser); - if(labelTransifexPwd.getEnabled()) renderer.renderLabel(&labelTransifexPwd); - if(labelTransifexI18N.getEnabled()) renderer.renderLabel(&labelTransifexI18N); - - renderer.renderListBox(&listBoxLang); - renderer.renderLabel(&labelLang); - renderer.renderLabel(&labelPlayerNameLabel); - renderer.renderLabel(&labelPlayerName); - renderer.renderListBox(&listFontSizeAdjustment); - renderer.renderLabel(&labelFontSizeAdjustment); - - renderer.renderLabel(&labelScreenShotType); - renderer.renderListBox(&listBoxScreenShotType); - - renderer.renderLabel(&labelDisableScreenshotConsoleText); - renderer.renderCheckBox(&checkBoxDisableScreenshotConsoleText); - - renderer.renderLabel(&labelMouseMoveScrollsWorld); - renderer.renderCheckBox(&checkBoxMouseMoveScrollsWorld); - renderer.renderLabel(&labelCameraMoveSpeed); - renderer.renderListBox(&listCameraMoveSpeed); - - renderer.renderLabel(&labelVisibleHud); - renderer.renderLabel(&labelHealthBars); - renderer.renderListBox(&listBoxHealthBars); - renderer.renderLabel(&labelChatStaysActive); - renderer.renderLabel(&labelTimeDisplay); - - renderer.renderLabel(&labelLuaDisableSecuritySandbox); - renderer.renderCheckBox(&checkBoxLuaDisableSecuritySandbox); - - renderer.renderCheckBox(&checkBoxVisibleHud); - renderer.renderCheckBox(&checkBoxChatStaysActive); - renderer.renderCheckBox(&checkBoxTimeDisplay); - - } - - renderer.renderConsole(&console); - if(program != NULL) program->renderProgramMsgBox(); +void MenuStateOptions::render() { + Renderer &renderer = Renderer::getInstance(); + // char szBuf[8096]=""; + // snprintf(szBuf,8096,"\nIn [%s::%s Line: %d]\n\nRender options menu + //[%p]!\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this); + // printf(szBuf); + + if (mainMessageBox.getEnabled()) { + renderer.renderMessageBox(&mainMessageBox); + } else if (luaMessageBox.getEnabled()) { + renderer.renderMessageBox(&luaMessageBox); + } else { + renderer.renderButton(&buttonOk); + renderer.renderButton(&buttonReturn); + renderer.renderButton(&buttonKeyboardSetup); + renderer.renderButton(&buttonVideoSection); + renderer.renderButton(&buttonAudioSection); + renderer.renderButton(&buttonMiscSection); + renderer.renderButton(&buttonNetworkSettings); + + renderer.renderLabel(&labelCustomTranslation); + renderer.renderCheckBox(&checkBoxCustomTranslation); + + if (buttonGetNewLanguageFiles.getEnabled()) + renderer.renderButton(&buttonGetNewLanguageFiles); + if (buttonDeleteNewLanguageFiles.getEnabled()) + renderer.renderButton(&buttonDeleteNewLanguageFiles); + if (labelTransifexUserLabel.getEnabled()) + renderer.renderLabel(&labelTransifexUserLabel); + if (labelTransifexPwdLabel.getEnabled()) + renderer.renderLabel(&labelTransifexPwdLabel); + if (labelTransifexI18NLabel.getEnabled()) + renderer.renderLabel(&labelTransifexI18NLabel); + if (labelTransifexUser.getEnabled()) + renderer.renderLabel(&labelTransifexUser); + if (labelTransifexPwd.getEnabled()) + renderer.renderLabel(&labelTransifexPwd); + if (labelTransifexI18N.getEnabled()) + renderer.renderLabel(&labelTransifexI18N); + + renderer.renderListBox(&listBoxLang); + renderer.renderLabel(&labelLang); + renderer.renderLabel(&labelPlayerNameLabel); + renderer.renderLabel(&labelPlayerName); + renderer.renderListBox(&listFontSizeAdjustment); + renderer.renderLabel(&labelFontSizeAdjustment); + + renderer.renderLabel(&labelScreenShotType); + renderer.renderListBox(&listBoxScreenShotType); + + renderer.renderLabel(&labelDisableScreenshotConsoleText); + renderer.renderCheckBox(&checkBoxDisableScreenshotConsoleText); + + renderer.renderLabel(&labelMouseMoveScrollsWorld); + renderer.renderCheckBox(&checkBoxMouseMoveScrollsWorld); + renderer.renderLabel(&labelCameraMoveSpeed); + renderer.renderListBox(&listCameraMoveSpeed); + + renderer.renderLabel(&labelVisibleHud); + renderer.renderLabel(&labelHealthBars); + renderer.renderListBox(&listBoxHealthBars); + renderer.renderLabel(&labelChatStaysActive); + renderer.renderLabel(&labelTimeDisplay); + + renderer.renderLabel(&labelLuaDisableSecuritySandbox); + renderer.renderCheckBox(&checkBoxLuaDisableSecuritySandbox); + + renderer.renderCheckBox(&checkBoxVisibleHud); + renderer.renderCheckBox(&checkBoxChatStaysActive); + renderer.renderCheckBox(&checkBoxTimeDisplay); + } + + renderer.renderConsole(&console); + if (program != NULL) + program->renderProgramMsgBox(); } -void MenuStateOptions::saveConfig(){ - Config &config= Config::getInstance(); - Lang &lang= Lang::getInstance(); - setActiveInputLable(NULL); - - if(labelPlayerName.getText().length()>0) - { - config.setString("NetPlayerName", labelPlayerName.getText()); - } - //Copy values - map::iterator iterMap = languageList.begin(); - std::advance(iterMap, listBoxLang.getSelectedItemIndex()); - - config.setString("Lang", iterMap->first); - lang.loadGameStrings(config.getString("Lang")); - - config.setString("FontSizeAdjustment", listFontSizeAdjustment.getSelectedItem()); - config.setString("ScreenShotFileType", listBoxScreenShotType.getSelectedItem()); - - config.setBool("DisableScreenshotConsoleText", !checkBoxDisableScreenshotConsoleText.getValue()); - config.setBool("MouseMoveScrollsWorld", checkBoxMouseMoveScrollsWorld.getValue()); - config.setString("CameraMoveSpeed", listCameraMoveSpeed.getSelectedItem()); - - int hpIndex=listBoxHealthBars.getSelectedItemIndex(); - int hpMode=hbvUndefined; - switch (hpIndex) { - case 0: - hpMode = hbvUndefined; - break; - case 1: - hpMode = hbvOff; - break; - case 2: - hpMode = hbvAlways; - break; - case 3: - hpMode = hbvIfNeeded; - break; - case 4: - hpMode = hbvSelected; - break; - case 5: - hpMode = hbvSelected | hbvIfNeeded; - break; - default: - hpMode = hbvUndefined; - break; - } - - config.setInt("HealthBarMode",hpMode ); - config.setBool("VisibleHud", checkBoxVisibleHud.getValue()); - config.setBool("ChatStaysActive", checkBoxChatStaysActive.getValue()); - config.setBool("TimeDisplay", checkBoxTimeDisplay.getValue()); - - config.setBool("DisableLuaSandbox", checkBoxLuaDisableSecuritySandbox.getValue()); - config.save(); - - if(config.getBool("DisableLuaSandbox","false") == true) { - LuaScript::setDisableSandbox(true); - } - Renderer::getInstance().loadConfig(); - console.addLine(lang.getString("SettingsSaved")); +void MenuStateOptions::saveConfig() { + Config &config = Config::getInstance(); + Lang &lang = Lang::getInstance(); + setActiveInputLable(NULL); + + if (labelPlayerName.getText().length() > 0) { + config.setString("NetPlayerName", labelPlayerName.getText()); + } + // Copy values + map::iterator iterMap = languageList.begin(); + std::advance(iterMap, listBoxLang.getSelectedItemIndex()); + + config.setString("Lang", iterMap->first); + lang.loadGameStrings(config.getString("Lang")); + + config.setString("FontSizeAdjustment", + listFontSizeAdjustment.getSelectedItem()); + config.setString("ScreenShotFileType", + listBoxScreenShotType.getSelectedItem()); + + config.setBool("DisableScreenshotConsoleText", + !checkBoxDisableScreenshotConsoleText.getValue()); + config.setBool("MouseMoveScrollsWorld", + checkBoxMouseMoveScrollsWorld.getValue()); + config.setString("CameraMoveSpeed", listCameraMoveSpeed.getSelectedItem()); + + int hpIndex = listBoxHealthBars.getSelectedItemIndex(); + int hpMode = hbvUndefined; + switch (hpIndex) { + case 0: + hpMode = hbvUndefined; + break; + case 1: + hpMode = hbvOff; + break; + case 2: + hpMode = hbvAlways; + break; + case 3: + hpMode = hbvIfNeeded; + break; + case 4: + hpMode = hbvSelected; + break; + case 5: + hpMode = hbvSelected | hbvIfNeeded; + break; + default: + hpMode = hbvUndefined; + break; + } + + config.setInt("HealthBarMode", hpMode); + config.setBool("VisibleHud", checkBoxVisibleHud.getValue()); + config.setBool("ChatStaysActive", checkBoxChatStaysActive.getValue()); + config.setBool("TimeDisplay", checkBoxTimeDisplay.getValue()); + + config.setBool("DisableLuaSandbox", + checkBoxLuaDisableSecuritySandbox.getValue()); + config.save(); + + if (config.getBool("DisableLuaSandbox", "false") == true) { + LuaScript::setDisableSandbox(true); + } + Renderer::getInstance().loadConfig(); + console.addLine(lang.getString("SettingsSaved")); } void MenuStateOptions::setActiveInputLable(GraphicLabel *newLable) { - MenuState::setActiveInputLabel(newLable,&activeInputLabel); - - if(newLable == &labelTransifexPwd) { - labelTransifexPwd.setIsPassword(false); - } - else { - labelTransifexPwd.setIsPassword(true); - } + MenuState::setActiveInputLabel(newLable, &activeInputLabel); + + if (newLable == &labelTransifexPwd) { + labelTransifexPwd.setIsPassword(false); + } else { + labelTransifexPwd.setIsPassword(true); + } } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/menu/menu_state_options.h b/source/glest_game/menu/menu_state_options.h index 4dab996b6..469878d12 100644 --- a/source/glest_game/menu/menu_state_options.h +++ b/source/glest_game/menu/menu_state_options.h @@ -12,107 +12,109 @@ #ifndef _GLEST_GAME_MENUSTATEOPTIONS_H_ #define _GLEST_GAME_MENUSTATEOPTIONS_H_ -#include "main_menu.h" #include "leak_dumper.h" +#include "main_menu.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // =============================== // class MenuStateOptions // =============================== -class MenuStateOptions: public MenuState{ +class MenuStateOptions : public MenuState { private: - GraphicButton buttonOk; - GraphicButton buttonReturn; - - GraphicLabel labelLang; - GraphicListBox listBoxLang; - GraphicLabel labelPlayerName; - GraphicLabel labelPlayerNameLabel; - GraphicLabel *activeInputLabel; + GraphicButton buttonOk; + GraphicButton buttonReturn; + GraphicLabel labelLang; + GraphicListBox listBoxLang; + GraphicLabel labelPlayerName; + GraphicLabel labelPlayerNameLabel; + GraphicLabel *activeInputLabel; - GraphicButton buttonKeyboardSetup; // configure the keyboard - GraphicButton buttonVideoSection; - GraphicButton buttonAudioSection; - GraphicButton buttonMiscSection; - GraphicButton buttonNetworkSettings; + GraphicButton buttonKeyboardSetup; // configure the keyboard + GraphicButton buttonVideoSection; + GraphicButton buttonAudioSection; + GraphicButton buttonMiscSection; + GraphicButton buttonNetworkSettings; - GraphicLabel labelFontSizeAdjustment; - GraphicListBox listFontSizeAdjustment; + GraphicLabel labelFontSizeAdjustment; + GraphicListBox listFontSizeAdjustment; - GraphicMessageBox mainMessageBox; - int mainMessageBoxState; + GraphicMessageBox mainMessageBox; + int mainMessageBoxState; - GraphicLabel labelScreenShotType; - GraphicListBox listBoxScreenShotType; + GraphicLabel labelScreenShotType; + GraphicListBox listBoxScreenShotType; - GraphicLabel labelDisableScreenshotConsoleText; - GraphicCheckBox checkBoxDisableScreenshotConsoleText; + GraphicLabel labelDisableScreenshotConsoleText; + GraphicCheckBox checkBoxDisableScreenshotConsoleText; - GraphicLabel labelMouseMoveScrollsWorld; - GraphicCheckBox checkBoxMouseMoveScrollsWorld; + GraphicLabel labelMouseMoveScrollsWorld; + GraphicCheckBox checkBoxMouseMoveScrollsWorld; - GraphicLabel labelCameraMoveSpeed; - GraphicListBox listCameraMoveSpeed; + GraphicLabel labelCameraMoveSpeed; + GraphicListBox listCameraMoveSpeed; - GraphicLabel labelVisibleHud; - GraphicCheckBox checkBoxVisibleHud; - GraphicLabel labelHealthBars; - GraphicListBox listBoxHealthBars; + GraphicLabel labelVisibleHud; + GraphicCheckBox checkBoxVisibleHud; + GraphicLabel labelHealthBars; + GraphicListBox listBoxHealthBars; - GraphicLabel labelTimeDisplay; - GraphicCheckBox checkBoxTimeDisplay; - GraphicLabel labelChatStaysActive; - GraphicCheckBox checkBoxChatStaysActive; + GraphicLabel labelTimeDisplay; + GraphicCheckBox checkBoxTimeDisplay; + GraphicLabel labelChatStaysActive; + GraphicCheckBox checkBoxChatStaysActive; - GraphicLabel labelLuaDisableSecuritySandbox; - GraphicCheckBox checkBoxLuaDisableSecuritySandbox; + GraphicLabel labelLuaDisableSecuritySandbox; + GraphicCheckBox checkBoxLuaDisableSecuritySandbox; - GraphicMessageBox luaMessageBox; - int luaMessageBoxState; + GraphicMessageBox luaMessageBox; + int luaMessageBoxState; - map languageList; + map languageList; - GraphicLabel labelCustomTranslation; - GraphicCheckBox checkBoxCustomTranslation; + GraphicLabel labelCustomTranslation; + GraphicCheckBox checkBoxCustomTranslation; - GraphicButton buttonGetNewLanguageFiles; - GraphicButton buttonDeleteNewLanguageFiles; - GraphicLabel labelTransifexUserLabel; - GraphicLabel labelTransifexUser; - GraphicLabel labelTransifexPwdLabel; - GraphicLabel labelTransifexPwd; - GraphicLabel labelTransifexI18NLabel; - GraphicLabel labelTransifexI18N; + GraphicButton buttonGetNewLanguageFiles; + GraphicButton buttonDeleteNewLanguageFiles; + GraphicLabel labelTransifexUserLabel; + GraphicLabel labelTransifexUser; + GraphicLabel labelTransifexPwdLabel; + GraphicLabel labelTransifexPwd; + GraphicLabel labelTransifexI18NLabel; + GraphicLabel labelTransifexI18N; - ProgramState **parentUI; + ProgramState **parentUI; public: - MenuStateOptions(Program *program, MainMenu *mainMenu, ProgramState **parentUI=NULL); - virtual ~MenuStateOptions(); + MenuStateOptions(Program *program, MainMenu *mainMenu, + ProgramState **parentUI = NULL); + virtual ~MenuStateOptions(); - void mouseClick(int x, int y, MouseButton mouseButton); - void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; - void mouseMove(int x, int y, const MouseState *mouseState); - void render(); - virtual bool textInput(std::string text); - virtual void keyDown(SDL_KeyboardEvent key); - virtual void keyPress(SDL_KeyboardEvent c); - virtual bool isInSpecialKeyCaptureEvent(); + void mouseClick(int x, int y, MouseButton mouseButton); + void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; + void mouseMove(int x, int y, const MouseState *mouseState); + void render(); + virtual bool textInput(std::string text); + virtual void keyDown(SDL_KeyboardEvent key); + virtual void keyPress(SDL_KeyboardEvent c); + virtual bool isInSpecialKeyCaptureEvent(); - virtual void reloadUI(); + virtual void reloadUI(); private: - void saveConfig(); - void setActiveInputLable(GraphicLabel* newLable); - void showMessageBox(const string &text, const string &header, bool toggle); - void showLuaMessageBox(const string &text, const string &header, bool toggle); + void saveConfig(); + void setActiveInputLable(GraphicLabel *newLable); + void showMessageBox(const string &text, const string &header, bool toggle); + void showLuaMessageBox(const string &text, const string &header, bool toggle); - void setupTransifexUI(); + void setupTransifexUI(); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/menu/menu_state_options_graphics.cpp b/source/glest_game/menu/menu_state_options_graphics.cpp index 71d5c6e6c..906ff6412 100644 --- a/source/glest_game/menu/menu_state_options_graphics.cpp +++ b/source/glest_game/menu/menu_state_options_graphics.cpp @@ -11,938 +11,972 @@ #include "menu_state_options_graphics.h" -#include "renderer.h" -#include "game.h" -#include "program.h" -#include "sound_renderer.h" -#include "core_data.h" #include "config.h" -#include "menu_state_root.h" -#include "menu_state_options.h" -#include "util.h" +#include "core_data.h" +#include "game.h" +#include "leak_dumper.h" #include "menu_state_graphic_info.h" #include "menu_state_keysetup.h" +#include "menu_state_options.h" #include "menu_state_options_graphics.h" -#include "menu_state_options_sound.h" #include "menu_state_options_network.h" -#include "string_utils.h" +#include "menu_state_options_sound.h" +#include "menu_state_root.h" #include "metrics.h" -#include "leak_dumper.h" +#include "program.h" +#include "renderer.h" +#include "sound_renderer.h" +#include "string_utils.h" +#include "util.h" using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class MenuStateOptions // ===================================================== -MenuStateOptionsGraphics::MenuStateOptionsGraphics(Program *program, MainMenu *mainMenu, ProgramState **parentUI) : - MenuState(program, mainMenu, "config"), - buttonOk("Options_Graphics","buttonOk"), - buttonReturn("Options_Graphics","buttonReturn"), - buttonAutoConfig("Options_Graphics","buttonAutoConfig"), - buttonVideoInfo("Options_Graphics","buttonVideoInfo"), - - buttonKeyboardSetup("Options_Graphics","buttonKeyboardSetup"), - buttonVideoSection("Options_Graphics","buttonVideoSection"), - buttonAudioSection("Options_Graphics","buttonAudioSection"), - buttonMiscSection("Options_Graphics","buttonMiscSection"), - buttonNetworkSettings("Options_Graphics","buttonNetworkSettings"), - - labelShadows("Options_Graphics","labelShadows"), - listBoxShadows("Options_Graphics","listBoxShadows"), - labelFilter("Options_Graphics","labelFilter"), - listBoxFilter("Options_Graphics","listBoxFilter"), - labelFilterMaxAnisotropy("Options_Graphics","labelFilterMaxAnisotropy"), - listBoxFilterMaxAnisotropy("Options_Graphics","listBoxFilterMaxAnisotropy"), - - labelTextures3D("Options_Graphics","labelTextures3D"), - checkBoxTextures3D("Options_Graphics","checkBoxTextures3D"), - labelLights("Options_Graphics","labelLights"), - listBoxLights("Options_Graphics","listBoxLights"), - labelUnitParticles("Options_Graphics","labelUnitParticles"), - checkBoxUnitParticles("Options_Graphics","checkBoxUnitParticles"), - - labelTilesetParticles("Options_Graphics","labelTilesetParticles"), - checkBoxTilesetParticles("Options_Graphics","checkBoxTilesetParticles"), - labelAnimatedTilesetObjects("Options_Graphics","labelAnimatedTilesetObjects"), - listBoxAnimatedTilesetObjects("Options_Graphics","listBoxAnimatedTilesetObjects"), +MenuStateOptionsGraphics::MenuStateOptionsGraphics(Program *program, + MainMenu *mainMenu, + ProgramState **parentUI) + : MenuState(program, mainMenu, "config"), + buttonOk("Options_Graphics", "buttonOk"), + buttonReturn("Options_Graphics", "buttonReturn"), + buttonAutoConfig("Options_Graphics", "buttonAutoConfig"), + buttonVideoInfo("Options_Graphics", "buttonVideoInfo"), + + buttonKeyboardSetup("Options_Graphics", "buttonKeyboardSetup"), + buttonVideoSection("Options_Graphics", "buttonVideoSection"), + buttonAudioSection("Options_Graphics", "buttonAudioSection"), + buttonMiscSection("Options_Graphics", "buttonMiscSection"), + buttonNetworkSettings("Options_Graphics", "buttonNetworkSettings"), + + labelShadows("Options_Graphics", "labelShadows"), + listBoxShadows("Options_Graphics", "listBoxShadows"), + labelFilter("Options_Graphics", "labelFilter"), + listBoxFilter("Options_Graphics", "listBoxFilter"), + labelFilterMaxAnisotropy("Options_Graphics", "labelFilterMaxAnisotropy"), + listBoxFilterMaxAnisotropy("Options_Graphics", + "listBoxFilterMaxAnisotropy"), + + labelTextures3D("Options_Graphics", "labelTextures3D"), + checkBoxTextures3D("Options_Graphics", "checkBoxTextures3D"), + labelLights("Options_Graphics", "labelLights"), + listBoxLights("Options_Graphics", "listBoxLights"), + labelUnitParticles("Options_Graphics", "labelUnitParticles"), + checkBoxUnitParticles("Options_Graphics", "checkBoxUnitParticles"), + + labelTilesetParticles("Options_Graphics", "labelTilesetParticles"), + checkBoxTilesetParticles("Options_Graphics", "checkBoxTilesetParticles"), + labelAnimatedTilesetObjects("Options_Graphics", + "labelAnimatedTilesetObjects"), + listBoxAnimatedTilesetObjects("Options_Graphics", + "listBoxAnimatedTilesetObjects"), + + labelScreenModes("Options_Graphics", "labelScreenModes"), + listBoxScreenModes("Options_Graphics", "listBoxScreenModes"), + + labelFullscreenWindowed("Options_Graphics", "labelFullscreenWindowed"), + checkBoxFullscreenWindowed("Options_Graphics", + "checkBoxFullscreenWindowed"), + + labelMapPreview("Options_Graphics", "labelMapPreview"), + checkBoxMapPreview("Options_Graphics", "checkBoxMapPreview"), + + mainMessageBox("Options_Graphics", "mainMessageBox"), + + labelEnableTextureCompression("Options_Graphics", + "labelEnableTextureCompression"), + checkBoxEnableTextureCompression("Options_Graphics", + "checkBoxEnableTextureCompression"), + + labelRainEffect("Options_Graphics", "labelRainEffect"), + labelRainEffectSeparator("Options_Graphics", "labelRainEffectSeparator"), + checkBoxRainEffect("Options_Graphics", "checkBoxRainEffect"), + checkBoxRainEffectMenu("Options_Graphics", "checkBoxRainEffectMenu"), + + labelGammaCorrection("Options_Graphics", "labelGammaCorrection"), + listBoxGammaCorrection("Options_Graphics", "listBoxGammaCorrection"), + + labelShadowIntensity("Options_Graphics", "labelShadowIntensity"), + listBoxShadowIntensity("Options_Graphics", "listBoxShadowIntensity"), + + labelShadowTextureSize("Options_Graphics", "labelShadowTextureSize"), + listBoxShadowTextureSize("Options_Graphics", "listBoxShadowTextureSize"), + + labelVideos("Options_Graphics", "labelVideos"), + checkBoxVideos("Options_Graphics", "checkBoxVideos"), + + labelSelectionType("Options_Graphics", "labelSelectionType"), + listBoxSelectionType("Options_Graphics", "listBoxSelectionType") - labelScreenModes("Options_Graphics","labelScreenModes"), - listBoxScreenModes("Options_Graphics","listBoxScreenModes"), - - labelFullscreenWindowed("Options_Graphics","labelFullscreenWindowed"), - checkBoxFullscreenWindowed("Options_Graphics","checkBoxFullscreenWindowed"), - - labelMapPreview("Options_Graphics","labelMapPreview"), - checkBoxMapPreview("Options_Graphics","checkBoxMapPreview"), - - mainMessageBox("Options_Graphics","mainMessageBox"), +{ + try { + containerName = "Options_Graphics"; + this->parentUI = parentUI; + Lang &lang = Lang::getInstance(); + Config &config = Config::getInstance(); + this->console.setOnlyChatMessagesInStoredLines(false); + screenModeChangedTimer = time(NULL); // just init + + ::Shared::PlatformCommon::getFullscreenVideoModes( + &modeInfos, !config.getBool("Windowed")); + + int leftLabelStart = 100; + int leftColumnStart = leftLabelStart + 300; + int buttonRowPos = 50; + int buttonStartPos = 170; + int lineOffset = 30; + int tabButtonWidth = 200; + int tabButtonHeight = 30; + + mainMessageBox.init(lang.getString("Ok")); + mainMessageBox.setEnabled(false); + mainMessageBoxState = 0; + + buttonAudioSection.init(0, 720, tabButtonWidth, tabButtonHeight); + buttonAudioSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); + buttonAudioSection.setFont3D( + CoreData::getInstance().getMenuFontVeryBig3D()); + buttonAudioSection.setText(lang.getString("Audio")); + // Video Section + buttonVideoSection.init(200, 700, tabButtonWidth, tabButtonHeight + 20); + buttonVideoSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); + buttonVideoSection.setFont3D( + CoreData::getInstance().getMenuFontVeryBig3D()); + buttonVideoSection.setText(lang.getString("Video")); + // MiscSection + buttonMiscSection.init(400, 720, tabButtonWidth, tabButtonHeight); + buttonMiscSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); + buttonMiscSection.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); + buttonMiscSection.setText(lang.getString("Misc")); + // NetworkSettings + buttonNetworkSettings.init(600, 720, tabButtonWidth, tabButtonHeight); + buttonNetworkSettings.setFont(CoreData::getInstance().getMenuFontVeryBig()); + buttonNetworkSettings.setFont3D( + CoreData::getInstance().getMenuFontVeryBig3D()); + buttonNetworkSettings.setText(lang.getString("Network")); + + // KeyboardSetup + buttonKeyboardSetup.init(800, 720, tabButtonWidth, tabButtonHeight); + buttonKeyboardSetup.setFont(CoreData::getInstance().getMenuFontVeryBig()); + buttonKeyboardSetup.setFont3D( + CoreData::getInstance().getMenuFontVeryBig3D()); + buttonKeyboardSetup.setText(lang.getString("Keyboardsetup")); + + int currentLine = 650; // reset line pos + int currentLabelStart = leftLabelStart; // set to right side + int currentColumnStart = leftColumnStart; // set to right side + + // resolution + labelScreenModes.init(currentLabelStart, currentLine); + labelScreenModes.setText(lang.getString("Resolution")); + + listBoxScreenModes.init(currentColumnStart, currentLine, 200); + + string currentResString = config.getString("ScreenWidth") + "x" + + config.getString("ScreenHeight") + "-" + + intToStr(config.getInt("ColorBits")); + bool currentResolutionFound = false; + for (vector::const_iterator it = modeInfos.begin(); + it != modeInfos.end(); ++it) { + if ((*it).getString() == currentResString) { + currentResolutionFound = true; + } + listBoxScreenModes.pushBackItem((*it).getString()); + } + if (currentResolutionFound == false) { + listBoxScreenModes.pushBackItem(currentResString); + } + listBoxScreenModes.setSelectedItem(currentResString); + currentLine -= lineOffset; - labelEnableTextureCompression("Options_Graphics","labelEnableTextureCompression"), - checkBoxEnableTextureCompression("Options_Graphics","checkBoxEnableTextureCompression"), + // FullscreenWindowed + labelFullscreenWindowed.init(currentLabelStart, currentLine); - labelRainEffect("Options_Graphics","labelRainEffect"), - labelRainEffectSeparator("Options_Graphics","labelRainEffectSeparator"), - checkBoxRainEffect("Options_Graphics","checkBoxRainEffect"), - checkBoxRainEffectMenu("Options_Graphics","checkBoxRainEffectMenu"), + checkBoxFullscreenWindowed.init(currentColumnStart, currentLine); + labelFullscreenWindowed.setText(lang.getString("Windowed")); + checkBoxFullscreenWindowed.setValue(config.getBool("Windowed")); + currentLine -= lineOffset; - labelGammaCorrection("Options_Graphics","labelGammaCorrection"), - listBoxGammaCorrection("Options_Graphics","listBoxGammaCorrection"), + // gammaCorrection + labelGammaCorrection.init(currentLabelStart, currentLine); + labelGammaCorrection.setText(lang.getString("GammaCorrection")); - labelShadowIntensity("Options_Graphics","labelShadowIntensity"), - listBoxShadowIntensity("Options_Graphics","listBoxShadowIntensity"), + listBoxGammaCorrection.init(currentColumnStart, currentLine, 200); + for (float f = 0.5; f < 3.0f; f = f + 0.1f) { + listBoxGammaCorrection.pushBackItem(floatToStr(f)); + } + float gammaValue = config.getFloat("GammaValue", "1.0"); + if (gammaValue == 0.0f) + gammaValue = 1.0f; + listBoxGammaCorrection.setSelectedItem(floatToStr(gammaValue), false); + + currentLine -= lineOffset; + + // filter + labelFilter.init(currentLabelStart, currentLine); + labelFilter.setText(lang.getString("Filter")); + + listBoxFilter.init(currentColumnStart, currentLine, 200); + listBoxFilter.pushBackItem("Bilinear"); + listBoxFilter.pushBackItem("Trilinear"); + listBoxFilter.setSelectedItem(config.getString("Filter")); + currentLine -= lineOffset; + + // FilterMaxAnisotropy + labelFilterMaxAnisotropy.init(currentLabelStart, currentLine); + labelFilterMaxAnisotropy.setText(lang.getString("FilterMaxAnisotropy")); + + listBoxFilterMaxAnisotropy.init(currentColumnStart, currentLine, 200); + listBoxFilterMaxAnisotropy.pushBackItem("1"); + listBoxFilterMaxAnisotropy.pushBackItem("2"); + listBoxFilterMaxAnisotropy.pushBackItem("4"); + listBoxFilterMaxAnisotropy.pushBackItem("8"); + listBoxFilterMaxAnisotropy.pushBackItem("16"); + listBoxFilterMaxAnisotropy.setSelectedItem( + config.getString("FilterMaxAnisotropy", "1")); + currentLine -= lineOffset; + + // selectionType + labelSelectionType.init(currentLabelStart, currentLine); + labelSelectionType.setText(lang.getString("SelectionType")); + + listBoxSelectionType.init(currentColumnStart, currentLine, 250); + listBoxSelectionType.pushBackItem("SelectBuffer (nvidia)"); + listBoxSelectionType.pushBackItem("ColorPicking (default)"); + listBoxSelectionType.pushBackItem("FrustumPicking (bad)"); + + const string selectionType = + toLower(config.getString("SelectionType", Config::colorPicking)); + if (selectionType == Config::colorPicking) + listBoxSelectionType.setSelectedItemIndex(1); + else if (selectionType == Config::frustumPicking) + listBoxSelectionType.setSelectedItemIndex(2); + else + listBoxSelectionType.setSelectedItemIndex(0); + currentLine -= lineOffset; + + // shadows + labelShadows.init(currentLabelStart, currentLine); + labelShadows.setText(lang.getString("Shadows")); + + listBoxShadows.init(currentColumnStart, currentLine, 250); + for (int i = 0; i < Renderer::sCount; ++i) { + listBoxShadows.pushBackItem(lang.getString( + Renderer::shadowsToStr(static_cast(i)))); + } + string str = config.getString("Shadows"); + listBoxShadows.setSelectedItemIndex( + clamp(Renderer::strToShadows(str), 0, Renderer::sCount - 1)); + currentLine -= lineOffset; + + // shadows + labelShadowTextureSize.init(currentLabelStart, currentLine); + labelShadowTextureSize.setText(lang.getString("ShadowTextureSize")); + + listBoxShadowTextureSize.init(currentColumnStart, currentLine, 200); + listBoxShadowTextureSize.pushBackItem("256"); + listBoxShadowTextureSize.pushBackItem("512"); + listBoxShadowTextureSize.pushBackItem("1024"); + listBoxShadowTextureSize.setSelectedItemIndex(1, false); + listBoxShadowTextureSize.setSelectedItem( + intToStr(config.getInt("ShadowTextureSize", "512")), false); + currentLine -= lineOffset; + + // shadows + labelShadowIntensity.init(currentLabelStart, currentLine); + labelShadowIntensity.setText(lang.getString("ShadowIntensity")); + + listBoxShadowIntensity.init(currentColumnStart, currentLine, 200); + for (float f = 0.5f; f < 3.0f; f = f + 0.1f) { + listBoxShadowIntensity.pushBackItem(floatToStr(f)); + } + float shadowIntensity = config.getFloat("ShadowIntensity", "1.0"); + if (shadowIntensity <= 0.0f) + shadowIntensity = 1.0f; + listBoxShadowIntensity.setSelectedItem(floatToStr(shadowIntensity), false); - labelShadowTextureSize("Options_Graphics","labelShadowTextureSize"), - listBoxShadowTextureSize("Options_Graphics","listBoxShadowTextureSize"), + currentLine -= lineOffset; - labelVideos("Options_Graphics","labelVideos"), - checkBoxVideos("Options_Graphics","checkBoxVideos"), + // textures 3d + labelTextures3D.init(currentLabelStart, currentLine); - labelSelectionType("Options_Graphics","labelSelectionType"), - listBoxSelectionType("Options_Graphics","listBoxSelectionType") + checkBoxTextures3D.init(currentColumnStart, currentLine); + labelTextures3D.setText(lang.getString("Textures3D")); + checkBoxTextures3D.setValue(config.getBool("Textures3D")); + currentLine -= lineOffset; -{ - try { - containerName = "Options_Graphics"; - this->parentUI=parentUI; - Lang &lang= Lang::getInstance(); - Config &config= Config::getInstance(); - this->console.setOnlyChatMessagesInStoredLines(false); - screenModeChangedTimer= time(NULL); // just init - - ::Shared::PlatformCommon::getFullscreenVideoModes(&modeInfos,!config.getBool("Windowed")); - - int leftLabelStart=100; - int leftColumnStart=leftLabelStart+300; - int buttonRowPos=50; - int buttonStartPos=170; - int lineOffset=30; - int tabButtonWidth=200; - int tabButtonHeight=30; - - mainMessageBox.init(lang.getString("Ok")); - mainMessageBox.setEnabled(false); - mainMessageBoxState=0; - - buttonAudioSection.init(0, 720,tabButtonWidth,tabButtonHeight); - buttonAudioSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonAudioSection.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonAudioSection.setText(lang.getString("Audio")); - // Video Section - buttonVideoSection.init(200, 700,tabButtonWidth,tabButtonHeight+20); - buttonVideoSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonVideoSection.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonVideoSection.setText(lang.getString("Video")); - //MiscSection - buttonMiscSection.init(400, 720,tabButtonWidth,tabButtonHeight); - buttonMiscSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonMiscSection.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonMiscSection.setText(lang.getString("Misc")); - //NetworkSettings - buttonNetworkSettings.init(600, 720,tabButtonWidth,tabButtonHeight); - buttonNetworkSettings.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonNetworkSettings.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonNetworkSettings.setText(lang.getString("Network")); - - //KeyboardSetup - buttonKeyboardSetup.init(800, 720,tabButtonWidth,tabButtonHeight); - buttonKeyboardSetup.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonKeyboardSetup.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonKeyboardSetup.setText(lang.getString("Keyboardsetup")); - - int currentLine=650; // reset line pos - int currentLabelStart=leftLabelStart; // set to right side - int currentColumnStart=leftColumnStart; // set to right side - - //resolution - labelScreenModes.init(currentLabelStart, currentLine); - labelScreenModes.setText(lang.getString("Resolution")); - - listBoxScreenModes.init(currentColumnStart, currentLine, 200); - - string currentResString = config.getString("ScreenWidth") + "x" + - config.getString("ScreenHeight") + "-" + - intToStr(config.getInt("ColorBits")); - bool currentResolutionFound = false; - for(vector::const_iterator it= modeInfos.begin(); it!=modeInfos.end(); ++it){ - if((*it).getString() == currentResString) { - currentResolutionFound = true; - } - listBoxScreenModes.pushBackItem((*it).getString()); - } - if(currentResolutionFound == false) { - listBoxScreenModes.pushBackItem(currentResString); - } - listBoxScreenModes.setSelectedItem(currentResString); - currentLine-=lineOffset; - - - //FullscreenWindowed - labelFullscreenWindowed.init(currentLabelStart, currentLine); - - checkBoxFullscreenWindowed.init(currentColumnStart, currentLine); - labelFullscreenWindowed.setText(lang.getString("Windowed")); - checkBoxFullscreenWindowed.setValue(config.getBool("Windowed")); - currentLine-=lineOffset; - - //gammaCorrection - labelGammaCorrection.init(currentLabelStart, currentLine); - labelGammaCorrection.setText(lang.getString("GammaCorrection")); - - listBoxGammaCorrection.init(currentColumnStart, currentLine, 200); - for (float f=0.5;f<3.0f;f=f+0.1f) { - listBoxGammaCorrection.pushBackItem(floatToStr(f)); - } - float gammaValue=config.getFloat("GammaValue","1.0"); - if(gammaValue==0.0f) gammaValue=1.0f; - listBoxGammaCorrection.setSelectedItem(floatToStr(gammaValue),false); - - currentLine-=lineOffset; - - //filter - labelFilter.init(currentLabelStart, currentLine); - labelFilter.setText(lang.getString("Filter")); - - listBoxFilter.init(currentColumnStart, currentLine, 200); - listBoxFilter.pushBackItem("Bilinear"); - listBoxFilter.pushBackItem("Trilinear"); - listBoxFilter.setSelectedItem(config.getString("Filter")); - currentLine-=lineOffset; - - //FilterMaxAnisotropy - labelFilterMaxAnisotropy.init(currentLabelStart, currentLine); - labelFilterMaxAnisotropy.setText(lang.getString("FilterMaxAnisotropy")); - - listBoxFilterMaxAnisotropy.init(currentColumnStart, currentLine, 200); - listBoxFilterMaxAnisotropy.pushBackItem("1"); - listBoxFilterMaxAnisotropy.pushBackItem("2"); - listBoxFilterMaxAnisotropy.pushBackItem("4"); - listBoxFilterMaxAnisotropy.pushBackItem("8"); - listBoxFilterMaxAnisotropy.pushBackItem("16"); - listBoxFilterMaxAnisotropy.setSelectedItem(config.getString("FilterMaxAnisotropy","1")); - currentLine-=lineOffset; - - //selectionType - labelSelectionType.init(currentLabelStart, currentLine); - labelSelectionType.setText(lang.getString("SelectionType")); - - listBoxSelectionType.init(currentColumnStart, currentLine, 250); - listBoxSelectionType.pushBackItem("SelectBuffer (nvidia)"); - listBoxSelectionType.pushBackItem("ColorPicking (default)"); - listBoxSelectionType.pushBackItem("FrustumPicking (bad)"); - - const string selectionType=toLower(config.getString("SelectionType",Config::colorPicking)); - if( selectionType==Config::colorPicking) - listBoxSelectionType.setSelectedItemIndex(1); - else if ( selectionType==Config::frustumPicking ) - listBoxSelectionType.setSelectedItemIndex(2); - else - listBoxSelectionType.setSelectedItemIndex(0); - currentLine-=lineOffset; - - //shadows - labelShadows.init(currentLabelStart, currentLine); - labelShadows.setText(lang.getString("Shadows")); - - listBoxShadows.init(currentColumnStart, currentLine, 250); - for(int i= 0; i(i)))); - } - string str= config.getString("Shadows"); - listBoxShadows.setSelectedItemIndex(clamp(Renderer::strToShadows(str), 0, Renderer::sCount-1)); - currentLine-=lineOffset; - - //shadows - labelShadowTextureSize.init(currentLabelStart, currentLine); - labelShadowTextureSize.setText(lang.getString("ShadowTextureSize")); - - listBoxShadowTextureSize.init(currentColumnStart, currentLine, 200); - listBoxShadowTextureSize.pushBackItem("256"); - listBoxShadowTextureSize.pushBackItem("512"); - listBoxShadowTextureSize.pushBackItem("1024"); - listBoxShadowTextureSize.setSelectedItemIndex(1,false); - listBoxShadowTextureSize.setSelectedItem(intToStr(config.getInt("ShadowTextureSize","512")),false); - currentLine-=lineOffset; - - //shadows - labelShadowIntensity.init(currentLabelStart, currentLine); - labelShadowIntensity.setText(lang.getString("ShadowIntensity")); - - listBoxShadowIntensity.init(currentColumnStart, currentLine, 200); - for (float f=0.5f;f<3.0f;f=f+0.1f) { - listBoxShadowIntensity.pushBackItem(floatToStr(f)); - } - float shadowIntensity=config.getFloat("ShadowIntensity","1.0"); - if(shadowIntensity<=0.0f) shadowIntensity=1.0f; - listBoxShadowIntensity.setSelectedItem(floatToStr(shadowIntensity),false); - - currentLine-=lineOffset; - - //textures 3d - labelTextures3D.init(currentLabelStart, currentLine); - - checkBoxTextures3D.init(currentColumnStart, currentLine); - labelTextures3D.setText(lang.getString("Textures3D")); - checkBoxTextures3D.setValue(config.getBool("Textures3D")); - currentLine-=lineOffset; - - //lights - labelLights.init(currentLabelStart, currentLine); - labelLights.setText(lang.getString("MaxLights")); - - listBoxLights.init(currentColumnStart, currentLine, 80); - for(int i= 1; i<=8; ++i){ - listBoxLights.pushBackItem(intToStr(i)); - } - listBoxLights.setSelectedItemIndex(clamp(config.getInt("MaxLights")-1, 0, 7)); - currentLine-=lineOffset; - - //unit particles - labelUnitParticles.init(currentLabelStart,currentLine); - labelUnitParticles.setText(lang.getString("ShowUnitParticles")); - - checkBoxUnitParticles.init(currentColumnStart,currentLine); - checkBoxUnitParticles.setValue(config.getBool("UnitParticles","true")); - currentLine-=lineOffset; - - //tileset particles - labelTilesetParticles.init(currentLabelStart,currentLine); - labelTilesetParticles.setText(lang.getString("ShowTilesetParticles")); - - checkBoxTilesetParticles.init(currentColumnStart,currentLine); - checkBoxTilesetParticles.setValue(config.getBool("TilesetParticles","true")); - currentLine-=lineOffset; - - //animated tileset objects - labelAnimatedTilesetObjects.init(currentLabelStart,currentLine); - labelAnimatedTilesetObjects.setText(lang.getString("AnimatedTilesetObjects")); - - listBoxAnimatedTilesetObjects.init(currentColumnStart, currentLine, 80); - listBoxAnimatedTilesetObjects.pushBackItem("0"); - listBoxAnimatedTilesetObjects.pushBackItem("10"); - listBoxAnimatedTilesetObjects.pushBackItem("25"); - listBoxAnimatedTilesetObjects.pushBackItem("50"); - listBoxAnimatedTilesetObjects.pushBackItem("100"); - listBoxAnimatedTilesetObjects.pushBackItem("300"); - listBoxAnimatedTilesetObjects.pushBackItem("500"); - listBoxAnimatedTilesetObjects.pushBackItem("∞"); - listBoxAnimatedTilesetObjects.setSelectedItem("∞",true); - listBoxAnimatedTilesetObjects.setSelectedItem(config.getString("AnimatedTilesetObjects","-1"),false); - currentLine-=lineOffset; - - //unit particles - labelMapPreview.init(currentLabelStart,currentLine); - labelMapPreview.setText(lang.getString("ShowMapPreview")); - - checkBoxMapPreview.init(currentColumnStart,currentLine); - checkBoxMapPreview.setValue(config.getBool("MapPreview","true")); - currentLine-=lineOffset; - - // Texture Compression flag - labelEnableTextureCompression.init(currentLabelStart ,currentLine); - labelEnableTextureCompression.setText(lang.getString("EnableTextureCompression")); - - checkBoxEnableTextureCompression.init(currentColumnStart ,currentLine ); - checkBoxEnableTextureCompression.setValue(config.getBool("EnableTextureCompression","false")); - currentLine-=lineOffset; - - labelRainEffect.init(currentLabelStart ,currentLine); - labelRainEffect.setText(lang.getString("RainEffectMenuGame")); - - checkBoxRainEffectMenu.init(currentColumnStart ,currentLine ); - checkBoxRainEffectMenu.setValue(config.getBool("RainEffectMenu","true")); - - labelRainEffectSeparator.init(currentColumnStart+30 ,currentLine); - labelRainEffectSeparator.setText("/"); - - checkBoxRainEffect.init(currentColumnStart+42 ,currentLine ); - checkBoxRainEffect.setValue(config.getBool("RainEffect","true")); - currentLine-=lineOffset; - - labelVideos.init(currentLabelStart ,currentLine); - labelVideos.setText(lang.getString("EnableVideos")); - - checkBoxVideos.init(currentColumnStart ,currentLine ); - checkBoxVideos.setValue(config.getBool("EnableVideos","true")); - - // end - - // external server port - - // buttons - buttonOk.init(buttonStartPos, buttonRowPos, 100); - buttonOk.setText(lang.getString("Save")); - buttonReturn.setText(lang.getString("Return")); + // lights + labelLights.init(currentLabelStart, currentLine); + labelLights.setText(lang.getString("MaxLights")); - buttonReturn.init(buttonStartPos+110, buttonRowPos, 100); - buttonAutoConfig.setText(lang.getString("AutoConfig")); - - buttonAutoConfig.init(buttonStartPos+230, buttonRowPos, 175); - - buttonVideoInfo.setText(lang.getString("VideoInfo")); - buttonVideoInfo.init(buttonStartPos+415, buttonRowPos, 175); // was 620 - - GraphicComponent::applyAllCustomProperties(containerName); - } - catch(exception &e) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error loading options: %s\n",__FILE__,__FUNCTION__,__LINE__,e.what()); - throw megaglest_runtime_error(string("Error loading options msg: ") + e.what()); - } + listBoxLights.init(currentColumnStart, currentLine, 80); + for (int i = 1; i <= 8; ++i) { + listBoxLights.pushBackItem(intToStr(i)); + } + listBoxLights.setSelectedItemIndex( + clamp(config.getInt("MaxLights") - 1, 0, 7)); + currentLine -= lineOffset; + + // unit particles + labelUnitParticles.init(currentLabelStart, currentLine); + labelUnitParticles.setText(lang.getString("ShowUnitParticles")); + + checkBoxUnitParticles.init(currentColumnStart, currentLine); + checkBoxUnitParticles.setValue(config.getBool("UnitParticles", "true")); + currentLine -= lineOffset; + + // tileset particles + labelTilesetParticles.init(currentLabelStart, currentLine); + labelTilesetParticles.setText(lang.getString("ShowTilesetParticles")); + + checkBoxTilesetParticles.init(currentColumnStart, currentLine); + checkBoxTilesetParticles.setValue( + config.getBool("TilesetParticles", "true")); + currentLine -= lineOffset; + + // animated tileset objects + labelAnimatedTilesetObjects.init(currentLabelStart, currentLine); + labelAnimatedTilesetObjects.setText( + lang.getString("AnimatedTilesetObjects")); + + listBoxAnimatedTilesetObjects.init(currentColumnStart, currentLine, 80); + listBoxAnimatedTilesetObjects.pushBackItem("0"); + listBoxAnimatedTilesetObjects.pushBackItem("10"); + listBoxAnimatedTilesetObjects.pushBackItem("25"); + listBoxAnimatedTilesetObjects.pushBackItem("50"); + listBoxAnimatedTilesetObjects.pushBackItem("100"); + listBoxAnimatedTilesetObjects.pushBackItem("300"); + listBoxAnimatedTilesetObjects.pushBackItem("500"); + listBoxAnimatedTilesetObjects.pushBackItem("∞"); + listBoxAnimatedTilesetObjects.setSelectedItem("∞", true); + listBoxAnimatedTilesetObjects.setSelectedItem( + config.getString("AnimatedTilesetObjects", "-1"), false); + currentLine -= lineOffset; + + // unit particles + labelMapPreview.init(currentLabelStart, currentLine); + labelMapPreview.setText(lang.getString("ShowMapPreview")); + + checkBoxMapPreview.init(currentColumnStart, currentLine); + checkBoxMapPreview.setValue(config.getBool("MapPreview", "true")); + currentLine -= lineOffset; + + // Texture Compression flag + labelEnableTextureCompression.init(currentLabelStart, currentLine); + labelEnableTextureCompression.setText( + lang.getString("EnableTextureCompression")); + + checkBoxEnableTextureCompression.init(currentColumnStart, currentLine); + checkBoxEnableTextureCompression.setValue( + config.getBool("EnableTextureCompression", "false")); + currentLine -= lineOffset; + + labelRainEffect.init(currentLabelStart, currentLine); + labelRainEffect.setText(lang.getString("RainEffectMenuGame")); + + checkBoxRainEffectMenu.init(currentColumnStart, currentLine); + checkBoxRainEffectMenu.setValue(config.getBool("RainEffectMenu", "true")); + + labelRainEffectSeparator.init(currentColumnStart + 30, currentLine); + labelRainEffectSeparator.setText("/"); + + checkBoxRainEffect.init(currentColumnStart + 42, currentLine); + checkBoxRainEffect.setValue(config.getBool("RainEffect", "true")); + currentLine -= lineOffset; + + labelVideos.init(currentLabelStart, currentLine); + labelVideos.setText(lang.getString("EnableVideos")); + + checkBoxVideos.init(currentColumnStart, currentLine); + checkBoxVideos.setValue(config.getBool("EnableVideos", "true")); + + // end + + // external server port + + // buttons + buttonOk.init(buttonStartPos, buttonRowPos, 100); + buttonOk.setText(lang.getString("Save")); + buttonReturn.setText(lang.getString("Return")); + + buttonReturn.init(buttonStartPos + 110, buttonRowPos, 100); + buttonAutoConfig.setText(lang.getString("AutoConfig")); + + buttonAutoConfig.init(buttonStartPos + 230, buttonRowPos, 175); + + buttonVideoInfo.setText(lang.getString("VideoInfo")); + buttonVideoInfo.init(buttonStartPos + 415, buttonRowPos, 175); // was 620 + + GraphicComponent::applyAllCustomProperties(containerName); + } catch (exception &e) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error loading options: %s\n", + __FILE__, __FUNCTION__, __LINE__, e.what()); + throw megaglest_runtime_error(string("Error loading options msg: ") + + e.what()); + } } void MenuStateOptionsGraphics::reloadUI() { - Lang &lang= Lang::getInstance(); - - mainMessageBox.init(lang.getString("Ok")); - - buttonAudioSection.setText(lang.getString("Audio")); - buttonVideoSection.setText(lang.getString("Video")); - buttonMiscSection.setText(lang.getString("Misc")); - buttonNetworkSettings.setText(lang.getString("Network")); - - std::vector listboxData; - listboxData.push_back("None"); - listboxData.push_back("OpenAL"); - - labelScreenModes.setText(lang.getString("Resolution")); - - labelFullscreenWindowed.setText(lang.getString("Windowed")); - labelFilter.setText(lang.getString("Filter")); - - listboxData.clear(); - listboxData.push_back("Bilinear"); - listboxData.push_back("Trilinear"); - listBoxFilter.setItems(listboxData); - - labelFilterMaxAnisotropy.setText(lang.getString("FilterMaxAnisotropy")); - listboxData.clear(); - listboxData.push_back("1"); - listboxData.push_back("2"); - listboxData.push_back("4"); - listboxData.push_back("8"); - listboxData.push_back("16"); - listBoxFilterMaxAnisotropy.setItems(listboxData); - - listboxData.clear(); - for (float f=0.0;f<2.1f;f=f+0.1f) { - listboxData.push_back(floatToStr(f)); - } - listBoxGammaCorrection.setItems(listboxData); - - - listboxData.clear(); - for (float f=0.5;f<3.0f;f=f+0.1f) { - listboxData.push_back(floatToStr(f)); - } - listBoxShadowIntensity.setItems(listboxData); - - - labelShadows.setText(lang.getString("Shadows")); - labelShadowTextureSize.setText(lang.getString("ShadowTextureSize")); - - labelShadowIntensity.setText(lang.getString("ShadowIntensity")); - labelGammaCorrection.setText(lang.getString("GammaCorrection")); - - listboxData.clear(); - for(int i= 0; i(i)))); - } - listBoxShadows.setItems(listboxData); - - labelTextures3D.setText(lang.getString("Textures3D")); - labelLights.setText(lang.getString("MaxLights")); - labelUnitParticles.setText(lang.getString("ShowUnitParticles")); - labelTilesetParticles.setText(lang.getString("ShowTilesetParticles")); - labelAnimatedTilesetObjects.setText(lang.getString("AnimatedTilesetObjects")); - labelMapPreview.setText(lang.getString("ShowMapPreview")); - labelEnableTextureCompression.setText(lang.getString("EnableTextureCompression")); - labelRainEffect.setText(lang.getString("RainEffectMenuGame")); - labelVideos.setText(lang.getString("EnableVideos")); - - buttonOk.setText(lang.getString("Save")); - buttonReturn.setText(lang.getString("Return")); - buttonAutoConfig.setText(lang.getString("AutoConfig")); - buttonVideoInfo.setText(lang.getString("VideoInfo")); - - labelSelectionType.setText(lang.getString("SelectionType")); + Lang &lang = Lang::getInstance(); + + mainMessageBox.init(lang.getString("Ok")); + + buttonAudioSection.setText(lang.getString("Audio")); + buttonVideoSection.setText(lang.getString("Video")); + buttonMiscSection.setText(lang.getString("Misc")); + buttonNetworkSettings.setText(lang.getString("Network")); + + std::vector listboxData; + listboxData.push_back("None"); + listboxData.push_back("OpenAL"); + + labelScreenModes.setText(lang.getString("Resolution")); + + labelFullscreenWindowed.setText(lang.getString("Windowed")); + labelFilter.setText(lang.getString("Filter")); + + listboxData.clear(); + listboxData.push_back("Bilinear"); + listboxData.push_back("Trilinear"); + listBoxFilter.setItems(listboxData); + + labelFilterMaxAnisotropy.setText(lang.getString("FilterMaxAnisotropy")); + listboxData.clear(); + listboxData.push_back("1"); + listboxData.push_back("2"); + listboxData.push_back("4"); + listboxData.push_back("8"); + listboxData.push_back("16"); + listBoxFilterMaxAnisotropy.setItems(listboxData); + + listboxData.clear(); + for (float f = 0.0; f < 2.1f; f = f + 0.1f) { + listboxData.push_back(floatToStr(f)); + } + listBoxGammaCorrection.setItems(listboxData); + + listboxData.clear(); + for (float f = 0.5; f < 3.0f; f = f + 0.1f) { + listboxData.push_back(floatToStr(f)); + } + listBoxShadowIntensity.setItems(listboxData); + + labelShadows.setText(lang.getString("Shadows")); + labelShadowTextureSize.setText(lang.getString("ShadowTextureSize")); + + labelShadowIntensity.setText(lang.getString("ShadowIntensity")); + labelGammaCorrection.setText(lang.getString("GammaCorrection")); + + listboxData.clear(); + for (int i = 0; i < Renderer::sCount; ++i) { + listboxData.push_back(lang.getString( + Renderer::shadowsToStr(static_cast(i)))); + } + listBoxShadows.setItems(listboxData); + + labelTextures3D.setText(lang.getString("Textures3D")); + labelLights.setText(lang.getString("MaxLights")); + labelUnitParticles.setText(lang.getString("ShowUnitParticles")); + labelTilesetParticles.setText(lang.getString("ShowTilesetParticles")); + labelAnimatedTilesetObjects.setText(lang.getString("AnimatedTilesetObjects")); + labelMapPreview.setText(lang.getString("ShowMapPreview")); + labelEnableTextureCompression.setText( + lang.getString("EnableTextureCompression")); + labelRainEffect.setText(lang.getString("RainEffectMenuGame")); + labelVideos.setText(lang.getString("EnableVideos")); + + buttonOk.setText(lang.getString("Save")); + buttonReturn.setText(lang.getString("Return")); + buttonAutoConfig.setText(lang.getString("AutoConfig")); + buttonVideoInfo.setText(lang.getString("VideoInfo")); + + labelSelectionType.setText(lang.getString("SelectionType")); } - -void MenuStateOptionsGraphics::showMessageBox(const string &text, const string &header, bool toggle){ - if(!toggle){ - mainMessageBox.setEnabled(false); - } - - if(!mainMessageBox.getEnabled()){ - mainMessageBox.setText(text); - mainMessageBox.setHeader(header); - mainMessageBox.setEnabled(true); - } - else{ - mainMessageBox.setEnabled(false); - } +void MenuStateOptionsGraphics::showMessageBox(const string &text, + const string &header, + bool toggle) { + if (!toggle) { + mainMessageBox.setEnabled(false); + } + + if (!mainMessageBox.getEnabled()) { + mainMessageBox.setText(text); + mainMessageBox.setHeader(header); + mainMessageBox.setEnabled(true); + } else { + mainMessageBox.setEnabled(false); + } } -void MenuStateOptionsGraphics::revertScreenMode(){ - Config &config= Config::getInstance(); - //!!! - // Revert resolution or fullscreen - checkBoxFullscreenWindowed.setValue(config.getBool("Windowed")); - string currentResString = config.getString("ScreenWidth") + "x" + - config.getString("ScreenHeight") + "-" + - intToStr(config.getInt("ColorBits")); - listBoxScreenModes.setSelectedItem(currentResString); - - - changeVideoModeFullScreen(!config.getBool("Windowed")); - WindowGl *window = this->program->getWindow(); - window->ChangeVideoMode(true, - config.getInt("ScreenWidth"), - config.getInt("ScreenHeight"), - !config.getBool("Windowed"), - config.getInt("ColorBits"), - config.getInt("DepthBits"), - config.getInt("StencilBits"), - config.getBool("HardwareAcceleration","false"), - config.getBool("FullScreenAntiAliasing","false"), - config.getFloat("GammaValue","0.0")); - Metrics::reload(this->program->getWindow()->getScreenWidth(), - this->program->getWindow()->getScreenHeight()); - window->setText(config.getString("WindowTitle","MegaGlest")); - - this->mainMenu->init(); +void MenuStateOptionsGraphics::revertScreenMode() { + Config &config = Config::getInstance(); + //!!! + // Revert resolution or fullscreen + checkBoxFullscreenWindowed.setValue(config.getBool("Windowed")); + string currentResString = config.getString("ScreenWidth") + "x" + + config.getString("ScreenHeight") + "-" + + intToStr(config.getInt("ColorBits")); + listBoxScreenModes.setSelectedItem(currentResString); + + changeVideoModeFullScreen(!config.getBool("Windowed")); + WindowGl *window = this->program->getWindow(); + window->ChangeVideoMode( + true, config.getInt("ScreenWidth"), config.getInt("ScreenHeight"), + !config.getBool("Windowed"), config.getInt("ColorBits"), + config.getInt("DepthBits"), config.getInt("StencilBits"), + config.getBool("HardwareAcceleration", "false"), + config.getBool("FullScreenAntiAliasing", "false"), + config.getFloat("GammaValue", "0.0")); + Metrics::reload(this->program->getWindow()->getScreenWidth(), + this->program->getWindow()->getScreenHeight()); + window->setText(config.getString("WindowTitle", "MegaGlest")); + + this->mainMenu->init(); } -void MenuStateOptionsGraphics::update(){ - if(mainMessageBox.getEnabled() && (mainMessageBoxState == 1)) { - int waitTime=10; - if(( time(NULL) - screenModeChangedTimer >waitTime)){ - mainMessageBoxState=0; - mainMessageBox.setEnabled(false); - - Lang &lang= Lang::getInstance(); - mainMessageBox.init(lang.getString("Ok")); - - revertScreenMode(); - } - else - { - Lang &lang= Lang::getInstance(); - int timeToShow=waitTime- time(NULL) + screenModeChangedTimer; - // show timer in button - mainMessageBox.getButton(0)->setText(lang.getString("Ok")+" ("+intToStr(timeToShow)+")"); - } - } +void MenuStateOptionsGraphics::update() { + if (mainMessageBox.getEnabled() && (mainMessageBoxState == 1)) { + int waitTime = 10; + if ((time(NULL) - screenModeChangedTimer > waitTime)) { + mainMessageBoxState = 0; + mainMessageBox.setEnabled(false); + + Lang &lang = Lang::getInstance(); + mainMessageBox.init(lang.getString("Ok")); + + revertScreenMode(); + } else { + Lang &lang = Lang::getInstance(); + int timeToShow = waitTime - time(NULL) + screenModeChangedTimer; + // show timer in button + mainMessageBox.getButton(0)->setText(lang.getString("Ok") + " (" + + intToStr(timeToShow) + ")"); + } + } } -void MenuStateOptionsGraphics::mouseClick(int x, int y, MouseButton mouseButton){ - - Config &config= Config::getInstance(); - CoreData &coreData= CoreData::getInstance(); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - - - - if(mainMessageBox.getEnabled()) { - int button= 0; - - if(mainMessageBox.mouseClick(x, y, button)) { - soundRenderer.playFx(coreData.getClickSoundA()); - if(button == 0) { - if(mainMessageBoxState == 1) { - mainMessageBoxState=0; - mainMessageBox.setEnabled(false); - saveConfig(); - - Lang &lang= Lang::getInstance(); - mainMessageBox.init(lang.getString("Ok")); - //mainMenu->setState(new MenuStateOptions(program, mainMenu)); - } - else { - mainMessageBox.setEnabled(false); - - Lang &lang= Lang::getInstance(); - mainMessageBox.init(lang.getString("Ok")); - } - } - else { - if(mainMessageBoxState == 1) { - mainMessageBoxState=0; - mainMessageBox.setEnabled(false); - - Lang &lang= Lang::getInstance(); - mainMessageBox.init(lang.getString("Ok")); - - revertScreenMode(); - } - } - } - } - else if(buttonOk.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - Lang &lang= Lang::getInstance(); - bool selectedFullscreenWindowed = checkBoxFullscreenWindowed.getValue(); - string currentResolution=config.getString("ScreenWidth")+"x"+config.getString("ScreenHeight")+"-"+intToStr(config.getInt("ColorBits")); - string selectedResolution=listBoxScreenModes.getSelectedItem(); - bool currentFullscreenWindowed=config.getBool("Windowed"); - if(currentResolution != selectedResolution || currentFullscreenWindowed != selectedFullscreenWindowed){ - - changeVideoModeFullScreen(!selectedFullscreenWindowed); - const ModeInfo *selectedMode = NULL; - for(vector::const_iterator it= modeInfos.begin(); it!=modeInfos.end(); ++it) { - if((*it).getString() == selectedResolution) { - //config.setInt("ScreenWidth",(*it).width); - //config.setInt("ScreenHeight",(*it).height); - //config.setInt("ColorBits",(*it).depth); - selectedMode = &(*it); - } - } - if(selectedMode == NULL) { // if we cannot find the selectedResolution we try it with current one - for(vector::const_iterator it= modeInfos.begin(); it!=modeInfos.end(); ++it) { - if((*it).getString() == currentResolution) { - //config.setInt("ScreenWidth",(*it).width); - //config.setInt("ScreenHeight",(*it).height); - //config.setInt("ColorBits",(*it).depth); - selectedMode = &(*it); - } - } - } - if(selectedMode == NULL) { - throw megaglest_runtime_error("selectedMode == NULL"); - } +void MenuStateOptionsGraphics::mouseClick(int x, int y, + MouseButton mouseButton) { + + Config &config = Config::getInstance(); + CoreData &coreData = CoreData::getInstance(); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + + if (mainMessageBox.getEnabled()) { + int button = 0; + + if (mainMessageBox.mouseClick(x, y, button)) { + soundRenderer.playFx(coreData.getClickSoundA()); + if (button == 0) { + if (mainMessageBoxState == 1) { + mainMessageBoxState = 0; + mainMessageBox.setEnabled(false); + saveConfig(); + + Lang &lang = Lang::getInstance(); + mainMessageBox.init(lang.getString("Ok")); + // mainMenu->setState(new MenuStateOptions(program, mainMenu)); + } else { + mainMessageBox.setEnabled(false); + + Lang &lang = Lang::getInstance(); + mainMessageBox.init(lang.getString("Ok")); + } + } else { + if (mainMessageBoxState == 1) { + mainMessageBoxState = 0; + mainMessageBox.setEnabled(false); + + Lang &lang = Lang::getInstance(); + mainMessageBox.init(lang.getString("Ok")); + + revertScreenMode(); + } + } + } + } else if (buttonOk.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + Lang &lang = Lang::getInstance(); + bool selectedFullscreenWindowed = checkBoxFullscreenWindowed.getValue(); + string currentResolution = config.getString("ScreenWidth") + "x" + + config.getString("ScreenHeight") + "-" + + intToStr(config.getInt("ColorBits")); + string selectedResolution = listBoxScreenModes.getSelectedItem(); + bool currentFullscreenWindowed = config.getBool("Windowed"); + if (currentResolution != selectedResolution || + currentFullscreenWindowed != selectedFullscreenWindowed) { + + changeVideoModeFullScreen(!selectedFullscreenWindowed); + const ModeInfo *selectedMode = NULL; + for (vector::const_iterator it = modeInfos.begin(); + it != modeInfos.end(); ++it) { + if ((*it).getString() == selectedResolution) { + // config.setInt("ScreenWidth",(*it).width); + // config.setInt("ScreenHeight",(*it).height); + // config.setInt("ColorBits",(*it).depth); + selectedMode = &(*it); + } + } + if (selectedMode == NULL) { // if we cannot find the selectedResolution we + // try it with current one + for (vector::const_iterator it = modeInfos.begin(); + it != modeInfos.end(); ++it) { + if ((*it).getString() == currentResolution) { + // config.setInt("ScreenWidth",(*it).width); + // config.setInt("ScreenHeight",(*it).height); + // config.setInt("ColorBits",(*it).depth); + selectedMode = &(*it); + } + } + } + if (selectedMode == NULL) { + throw megaglest_runtime_error("selectedMode == NULL"); + } #if defined(__APPLE__) - mainMessageBoxState=1; - mainMessageBox.init(lang.getString("Ok"),lang.getString("Cancel")); - screenModeChangedTimer= time(NULL); + mainMessageBoxState = 1; + mainMessageBox.init(lang.getString("Ok"), lang.getString("Cancel")); + screenModeChangedTimer = time(NULL); - showMessageBox(lang.getString("RestartNeeded"), lang.getString("ResolutionChanged"), false); + showMessageBox(lang.getString("RestartNeeded"), + lang.getString("ResolutionChanged"), false); #else - WindowGl *window = this->program->getWindow(); - window->ChangeVideoMode(true, - selectedMode->width, - selectedMode->height, - !selectedFullscreenWindowed, - selectedMode->depth, - config.getInt("DepthBits"), - config.getInt("StencilBits"), - config.getBool("HardwareAcceleration","false"), - config.getBool("FullScreenAntiAliasing","false"), - strToFloat(listBoxGammaCorrection.getSelectedItem())); - - Metrics::reload(this->program->getWindow()->getScreenWidth(), - this->program->getWindow()->getScreenHeight()); - - this->mainMenu->init(); - - mainMessageBoxState=1; - mainMessageBox.init(lang.getString("Ok"),lang.getString("Cancel")); - screenModeChangedTimer= time(NULL); - - showMessageBox(lang.getString("ResolutionChanged"), lang.getString("Notice"), false); + WindowGl *window = this->program->getWindow(); + window->ChangeVideoMode( + true, selectedMode->width, selectedMode->height, + !selectedFullscreenWindowed, selectedMode->depth, + config.getInt("DepthBits"), config.getInt("StencilBits"), + config.getBool("HardwareAcceleration", "false"), + config.getBool("FullScreenAntiAliasing", "false"), + strToFloat(listBoxGammaCorrection.getSelectedItem())); + + Metrics::reload(this->program->getWindow()->getScreenWidth(), + this->program->getWindow()->getScreenHeight()); + + this->mainMenu->init(); + + mainMessageBoxState = 1; + mainMessageBox.init(lang.getString("Ok"), lang.getString("Cancel")); + screenModeChangedTimer = time(NULL); + + showMessageBox(lang.getString("ResolutionChanged"), + lang.getString("Notice"), false); #endif - //No saveConfig() here! this is done by the messageBox - return; - } - saveConfig(); - return; + // No saveConfig() here! this is done by the messageBox + return; + } + saveConfig(); + return; + } else if (buttonReturn.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + + // reset the gamma to former value + string currentGammaCorrection = config.getString("GammaValue", "1.0"); + string selectedGammaCorrection = listBoxGammaCorrection.getSelectedItem(); + if (currentGammaCorrection != selectedGammaCorrection) { + float gammaValue = strToFloat(currentGammaCorrection); + if (gammaValue == 0.0f) + gammaValue = 1.0f; + if (gammaValue != 0.0) { + program->getWindow()->setGamma(gammaValue); + } } - else if(buttonReturn.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - - // reset the gamma to former value - string currentGammaCorrection=config.getString("GammaValue","1.0"); - string selectedGammaCorrection=listBoxGammaCorrection.getSelectedItem(); - if(currentGammaCorrection!=selectedGammaCorrection){ - float gammaValue=strToFloat(currentGammaCorrection); - if(gammaValue==0.0f) gammaValue=1.0f; - if(gammaValue!=0.0){ - program->getWindow()->setGamma(gammaValue); - } - } - if(this->parentUI != NULL) { - *this->parentUI = NULL; - delete *this->parentUI; - } - mainMenu->setState(new MenuStateRoot(program, mainMenu)); - return; + if (this->parentUI != NULL) { + *this->parentUI = NULL; + delete *this->parentUI; } - else if(buttonKeyboardSetup.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - //mainMenu->setState(new MenuStateKeysetup(program, mainMenu)); // open keyboard shortcuts setup screen - //mainMenu->setState(new MenuStateOptionsGraphics(program, mainMenu)); // open keyboard shortcuts setup screen - //mainMenu->setState(new MenuStateOptionsNetwork(program, mainMenu)); // open keyboard shortcuts setup screen - mainMenu->setState(new MenuStateKeysetup(program, mainMenu,this->parentUI)); // open keyboard shortcuts setup screen - //showMessageBox("Not implemented yet", "Keyboard setup", false); - return; - } - else if(buttonAudioSection.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - mainMenu->setState(new MenuStateOptionsSound(program, mainMenu,this->parentUI)); // open keyboard shortcuts setup screen - return; - } - else if(buttonNetworkSettings.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - mainMenu->setState(new MenuStateOptionsNetwork(program, mainMenu,this->parentUI)); // open keyboard shortcuts setup screen - return; - } - else if(buttonMiscSection.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - mainMenu->setState(new MenuStateOptions(program, mainMenu,this->parentUI)); // open keyboard shortcuts setup screen - return; - } - else if(buttonVideoSection.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - //mainMenu->setState(new MenuStateOptionsGraphics(program, mainMenu,this->parentUI)); // open keyboard shortcuts setup screen - return; - } - else if(buttonAutoConfig.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - Renderer::getInstance().autoConfig(); - //saveConfig(); - mainMenu->setState(new MenuStateOptionsGraphics(program, mainMenu)); - return; - } - else if(buttonVideoInfo.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - mainMenu->setState(new MenuStateGraphicInfo(program, mainMenu)); - return; - } - else - { - listBoxSelectionType.mouseClick(x, y); - listBoxShadows.mouseClick(x, y); - listBoxAnimatedTilesetObjects.mouseClick(x, y); - listBoxShadowTextureSize.mouseClick(x, y); - listBoxShadowIntensity.mouseClick(x, y); - listBoxFilter.mouseClick(x, y); - listBoxFilterMaxAnisotropy.mouseClick(x, y); - if(listBoxGammaCorrection.mouseClick(x, y)){ - float gammaValue=strToFloat(listBoxGammaCorrection.getSelectedItem()); - if(gammaValue!=0.0){ - program->getWindow()->setGamma(gammaValue); - } - } - checkBoxTextures3D.mouseClick(x, y); - checkBoxUnitParticles.mouseClick(x, y); - checkBoxTilesetParticles.mouseClick(x, y); - checkBoxMapPreview.mouseClick(x, y); - listBoxLights.mouseClick(x, y); - listBoxScreenModes.mouseClick(x, y); - checkBoxFullscreenWindowed.mouseClick(x, y); - checkBoxEnableTextureCompression.mouseClick(x, y); - checkBoxRainEffect.mouseClick(x,y); - checkBoxRainEffectMenu.mouseClick(x,y); - - checkBoxVideos.mouseClick(x,y); - } + mainMenu->setState(new MenuStateRoot(program, mainMenu)); + return; + } else if (buttonKeyboardSetup.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + // mainMenu->setState(new MenuStateKeysetup(program, mainMenu)); // open + // keyboard shortcuts setup screen mainMenu->setState(new + // MenuStateOptionsGraphics(program, mainMenu)); // open keyboard shortcuts + // setup screen mainMenu->setState(new MenuStateOptionsNetwork(program, + // mainMenu)); // open keyboard shortcuts setup screen + mainMenu->setState(new MenuStateKeysetup( + program, mainMenu, + this->parentUI)); // open keyboard shortcuts setup screen + // showMessageBox("Not implemented yet", "Keyboard setup", false); + return; + } else if (buttonAudioSection.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + mainMenu->setState(new MenuStateOptionsSound( + program, mainMenu, + this->parentUI)); // open keyboard shortcuts setup screen + return; + } else if (buttonNetworkSettings.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + mainMenu->setState(new MenuStateOptionsNetwork( + program, mainMenu, + this->parentUI)); // open keyboard shortcuts setup screen + return; + } else if (buttonMiscSection.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + mainMenu->setState(new MenuStateOptions( + program, mainMenu, + this->parentUI)); // open keyboard shortcuts setup screen + return; + } else if (buttonVideoSection.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + // mainMenu->setState(new MenuStateOptionsGraphics(program, + // mainMenu,this->parentUI)); // open keyboard shortcuts setup screen + return; + } else if (buttonAutoConfig.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + Renderer::getInstance().autoConfig(); + // saveConfig(); + mainMenu->setState(new MenuStateOptionsGraphics(program, mainMenu)); + return; + } else if (buttonVideoInfo.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + mainMenu->setState(new MenuStateGraphicInfo(program, mainMenu)); + return; + } else { + listBoxSelectionType.mouseClick(x, y); + listBoxShadows.mouseClick(x, y); + listBoxAnimatedTilesetObjects.mouseClick(x, y); + listBoxShadowTextureSize.mouseClick(x, y); + listBoxShadowIntensity.mouseClick(x, y); + listBoxFilter.mouseClick(x, y); + listBoxFilterMaxAnisotropy.mouseClick(x, y); + if (listBoxGammaCorrection.mouseClick(x, y)) { + float gammaValue = strToFloat(listBoxGammaCorrection.getSelectedItem()); + if (gammaValue != 0.0) { + program->getWindow()->setGamma(gammaValue); + } + } + checkBoxTextures3D.mouseClick(x, y); + checkBoxUnitParticles.mouseClick(x, y); + checkBoxTilesetParticles.mouseClick(x, y); + checkBoxMapPreview.mouseClick(x, y); + listBoxLights.mouseClick(x, y); + listBoxScreenModes.mouseClick(x, y); + checkBoxFullscreenWindowed.mouseClick(x, y); + checkBoxEnableTextureCompression.mouseClick(x, y); + checkBoxRainEffect.mouseClick(x, y); + checkBoxRainEffectMenu.mouseClick(x, y); + + checkBoxVideos.mouseClick(x, y); + } } -void MenuStateOptionsGraphics::mouseMove(int x, int y, const MouseState *ms){ - if (mainMessageBox.getEnabled()) { - mainMessageBox.mouseMove(x, y); - } - - buttonOk.mouseMove(x, y); - buttonReturn.mouseMove(x, y); - buttonKeyboardSetup.mouseMove(x, y); - buttonAudioSection.mouseMove(x, y); - buttonNetworkSettings.mouseMove(x, y); - buttonMiscSection.mouseMove(x, y); - buttonVideoSection.mouseMove(x, y); - buttonAutoConfig.mouseMove(x, y); - buttonVideoInfo.mouseMove(x, y); - listBoxFilter.mouseMove(x, y); - listBoxFilterMaxAnisotropy.mouseMove(x, y); - listBoxGammaCorrection.mouseMove(x, y); - listBoxShadowIntensity.mouseMove(x, y); - listBoxSelectionType.mouseMove(x, y); - listBoxShadows.mouseMove(x, y); - checkBoxTextures3D.mouseMove(x, y); - checkBoxUnitParticles.mouseMove(x, y); - checkBoxTilesetParticles.mouseMove(x, y); - labelAnimatedTilesetObjects.mouseMove(x, y); - listBoxAnimatedTilesetObjects.mouseMove(x, y); - checkBoxTilesetParticles.mouseMove(x, y); - checkBoxMapPreview.mouseMove(x, y); - listBoxLights.mouseMove(x, y); - listBoxScreenModes.mouseMove(x, y); - checkBoxFullscreenWindowed.mouseMove(x, y); - checkBoxEnableTextureCompression.mouseMove(x, y); - - checkBoxRainEffect.mouseMove(x, y); - checkBoxRainEffectMenu.mouseMove(x, y); - - checkBoxVideos.mouseMove(x, y); +void MenuStateOptionsGraphics::mouseMove(int x, int y, const MouseState *ms) { + if (mainMessageBox.getEnabled()) { + mainMessageBox.mouseMove(x, y); + } + + buttonOk.mouseMove(x, y); + buttonReturn.mouseMove(x, y); + buttonKeyboardSetup.mouseMove(x, y); + buttonAudioSection.mouseMove(x, y); + buttonNetworkSettings.mouseMove(x, y); + buttonMiscSection.mouseMove(x, y); + buttonVideoSection.mouseMove(x, y); + buttonAutoConfig.mouseMove(x, y); + buttonVideoInfo.mouseMove(x, y); + listBoxFilter.mouseMove(x, y); + listBoxFilterMaxAnisotropy.mouseMove(x, y); + listBoxGammaCorrection.mouseMove(x, y); + listBoxShadowIntensity.mouseMove(x, y); + listBoxSelectionType.mouseMove(x, y); + listBoxShadows.mouseMove(x, y); + checkBoxTextures3D.mouseMove(x, y); + checkBoxUnitParticles.mouseMove(x, y); + checkBoxTilesetParticles.mouseMove(x, y); + labelAnimatedTilesetObjects.mouseMove(x, y); + listBoxAnimatedTilesetObjects.mouseMove(x, y); + checkBoxTilesetParticles.mouseMove(x, y); + checkBoxMapPreview.mouseMove(x, y); + listBoxLights.mouseMove(x, y); + listBoxScreenModes.mouseMove(x, y); + checkBoxFullscreenWindowed.mouseMove(x, y); + checkBoxEnableTextureCompression.mouseMove(x, y); + + checkBoxRainEffect.mouseMove(x, y); + checkBoxRainEffectMenu.mouseMove(x, y); + + checkBoxVideos.mouseMove(x, y); } -//bool MenuStateOptionsGraphics::isInSpecialKeyCaptureEvent() { +// bool MenuStateOptionsGraphics::isInSpecialKeyCaptureEvent() { // return (activeInputLabel != NULL); -//} +// } // -//void MenuStateOptionsGraphics::keyDown(SDL_KeyboardEvent key) { +// void MenuStateOptionsGraphics::keyDown(SDL_KeyboardEvent key) { // if(activeInputLabel != NULL) { // keyDownEditLabel(key, &activeInputLabel); // } -//} +// } void MenuStateOptionsGraphics::keyPress(SDL_KeyboardEvent c) { -// if(activeInputLabel != NULL) { -// //printf("[%d]\n",c); fflush(stdout); -// if( &labelPlayerName == activeInputLabel || -// &labelTransifexUser == activeInputLabel || -// &labelTransifexPwd == activeInputLabel || -// &labelTransifexI18N == activeInputLabel) { -// textInputEditLabel(c, &activeInputLabel); -// } -// } -// else { - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - if(isKeyPressed(configKeys.getSDLKey("SaveGUILayout"),c) == true) { - GraphicComponent::saveAllCustomProperties(containerName); - //Lang &lang= Lang::getInstance(); - //console.addLine(lang.getString("GUILayoutSaved") + " [" + (saved ? lang.getString("Yes") : lang.getString("No"))+ "]"); - } -// } + // if(activeInputLabel != NULL) { + // //printf("[%d]\n",c); fflush(stdout); + // if( &labelPlayerName == activeInputLabel || + // &labelTransifexUser == activeInputLabel || + // &labelTransifexPwd == activeInputLabel || + // &labelTransifexI18N == activeInputLabel) { + // textInputEditLabel(c, &activeInputLabel); + // } + // } + // else { + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + if (isKeyPressed(configKeys.getSDLKey("SaveGUILayout"), c) == true) { + GraphicComponent::saveAllCustomProperties(containerName); + // Lang &lang= Lang::getInstance(); + // console.addLine(lang.getString("GUILayoutSaved") + " [" + (saved ? + // lang.getString("Yes") : lang.getString("No"))+ "]"); + } + // } } -void MenuStateOptionsGraphics::render(){ - Renderer &renderer= Renderer::getInstance(); - - if(mainMessageBox.getEnabled()){ - renderer.renderMessageBox(&mainMessageBox); - } - else - { - renderer.renderButton(&buttonOk); - renderer.renderButton(&buttonReturn); - renderer.renderButton(&buttonKeyboardSetup); - renderer.renderButton(&buttonVideoSection); - renderer.renderButton(&buttonAudioSection); - renderer.renderButton(&buttonMiscSection); - renderer.renderButton(&buttonNetworkSettings); - renderer.renderButton(&buttonAutoConfig); - renderer.renderButton(&buttonVideoInfo); - renderer.renderListBox(&listBoxShadows); - renderer.renderCheckBox(&checkBoxTextures3D); - renderer.renderCheckBox(&checkBoxUnitParticles); - renderer.renderCheckBox(&checkBoxTilesetParticles); - renderer.renderCheckBox(&checkBoxMapPreview); - renderer.renderListBox(&listBoxLights); - renderer.renderListBox(&listBoxFilter); - renderer.renderListBox(&listBoxFilterMaxAnisotropy); - renderer.renderListBox(&listBoxGammaCorrection); - renderer.renderListBox(&listBoxShadowIntensity); - renderer.renderLabel(&labelShadows); - renderer.renderLabel(&labelTextures3D); - renderer.renderLabel(&labelUnitParticles); - renderer.renderLabel(&labelTilesetParticles); - renderer.renderListBox(&listBoxAnimatedTilesetObjects); - renderer.renderLabel(&labelAnimatedTilesetObjects); - renderer.renderLabel(&labelMapPreview); - renderer.renderLabel(&labelLights); - renderer.renderLabel(&labelFilter); - renderer.renderLabel(&labelFilterMaxAnisotropy); - renderer.renderLabel(&labelGammaCorrection); - renderer.renderLabel(&labelShadowIntensity); - renderer.renderLabel(&labelScreenModes); - renderer.renderListBox(&listBoxScreenModes); - renderer.renderLabel(&labelFullscreenWindowed); - renderer.renderCheckBox(&checkBoxFullscreenWindowed); - - renderer.renderLabel(&labelEnableTextureCompression); - renderer.renderCheckBox(&checkBoxEnableTextureCompression); - - renderer.renderLabel(&labelRainEffect); - renderer.renderCheckBox(&checkBoxRainEffect); - renderer.renderLabel(&labelRainEffectSeparator); - renderer.renderCheckBox(&checkBoxRainEffectMenu); - - renderer.renderLabel(&labelShadowTextureSize); - renderer.renderListBox(&listBoxShadowTextureSize); - - renderer.renderLabel(&labelSelectionType); - renderer.renderListBox(&listBoxSelectionType); - - renderer.renderLabel(&labelVideos); - renderer.renderCheckBox(&checkBoxVideos); - } - - renderer.renderConsole(&console); - if(program != NULL) program->renderProgramMsgBox(); +void MenuStateOptionsGraphics::render() { + Renderer &renderer = Renderer::getInstance(); + + if (mainMessageBox.getEnabled()) { + renderer.renderMessageBox(&mainMessageBox); + } else { + renderer.renderButton(&buttonOk); + renderer.renderButton(&buttonReturn); + renderer.renderButton(&buttonKeyboardSetup); + renderer.renderButton(&buttonVideoSection); + renderer.renderButton(&buttonAudioSection); + renderer.renderButton(&buttonMiscSection); + renderer.renderButton(&buttonNetworkSettings); + renderer.renderButton(&buttonAutoConfig); + renderer.renderButton(&buttonVideoInfo); + renderer.renderListBox(&listBoxShadows); + renderer.renderCheckBox(&checkBoxTextures3D); + renderer.renderCheckBox(&checkBoxUnitParticles); + renderer.renderCheckBox(&checkBoxTilesetParticles); + renderer.renderCheckBox(&checkBoxMapPreview); + renderer.renderListBox(&listBoxLights); + renderer.renderListBox(&listBoxFilter); + renderer.renderListBox(&listBoxFilterMaxAnisotropy); + renderer.renderListBox(&listBoxGammaCorrection); + renderer.renderListBox(&listBoxShadowIntensity); + renderer.renderLabel(&labelShadows); + renderer.renderLabel(&labelTextures3D); + renderer.renderLabel(&labelUnitParticles); + renderer.renderLabel(&labelTilesetParticles); + renderer.renderListBox(&listBoxAnimatedTilesetObjects); + renderer.renderLabel(&labelAnimatedTilesetObjects); + renderer.renderLabel(&labelMapPreview); + renderer.renderLabel(&labelLights); + renderer.renderLabel(&labelFilter); + renderer.renderLabel(&labelFilterMaxAnisotropy); + renderer.renderLabel(&labelGammaCorrection); + renderer.renderLabel(&labelShadowIntensity); + renderer.renderLabel(&labelScreenModes); + renderer.renderListBox(&listBoxScreenModes); + renderer.renderLabel(&labelFullscreenWindowed); + renderer.renderCheckBox(&checkBoxFullscreenWindowed); + + renderer.renderLabel(&labelEnableTextureCompression); + renderer.renderCheckBox(&checkBoxEnableTextureCompression); + + renderer.renderLabel(&labelRainEffect); + renderer.renderCheckBox(&checkBoxRainEffect); + renderer.renderLabel(&labelRainEffectSeparator); + renderer.renderCheckBox(&checkBoxRainEffectMenu); + + renderer.renderLabel(&labelShadowTextureSize); + renderer.renderListBox(&listBoxShadowTextureSize); + + renderer.renderLabel(&labelSelectionType); + renderer.renderListBox(&listBoxSelectionType); + + renderer.renderLabel(&labelVideos); + renderer.renderCheckBox(&checkBoxVideos); + } + + renderer.renderConsole(&console); + if (program != NULL) + program->renderProgramMsgBox(); } -void MenuStateOptionsGraphics::saveConfig(){ - Config &config= Config::getInstance(); - Lang &lang= Lang::getInstance(); - //setActiveInputLable(NULL); - - int selectionTypeindex= listBoxSelectionType.getSelectedItemIndex(); - if(selectionTypeindex==0){ - config.setString("SelectionType",Config::selectBufPicking); - } - else if (selectionTypeindex==1){ - config.setString("SelectionType",Config::colorPicking); - } - else if (selectionTypeindex==2){ - config.setString("SelectionType",Config::frustumPicking); - } - - int index= listBoxShadows.getSelectedItemIndex(); - config.setString("Shadows", Renderer::shadowsToStr(static_cast(index))); - - string texSizeString= listBoxShadowTextureSize.getSelectedItem(); - config.setInt("ShadowTextureSize",strToInt(texSizeString) ); - - config.setBool("Windowed", checkBoxFullscreenWindowed.getValue()); - config.setString("Filter", listBoxFilter.getSelectedItem()); - config.setInt("FilterMaxAnisotropy", strToInt(listBoxFilterMaxAnisotropy.getSelectedItem())); - config.setFloat("GammaValue", strToFloat(listBoxGammaCorrection.getSelectedItem())); - config.setFloat("ShadowIntensity", strToFloat(listBoxShadowIntensity.getSelectedItem())); - config.setBool("Textures3D", checkBoxTextures3D.getValue()); - config.setBool("UnitParticles", (checkBoxUnitParticles.getValue())); - config.setBool("TilesetParticles", (checkBoxTilesetParticles.getValue())); - config.setBool("MapPreview", checkBoxMapPreview.getValue()); - config.setInt("MaxLights", listBoxLights.getSelectedItemIndex()+1); - - if (listBoxAnimatedTilesetObjects.getSelectedItem()=="∞") { - config.setInt("AnimatedTilesetObjects", -1); - } else { - config.setInt("AnimatedTilesetObjects", atoi(listBoxAnimatedTilesetObjects.getSelectedItem().c_str())); - } - - config.setBool("RainEffect", checkBoxRainEffect.getValue()); - config.setBool("RainEffectMenu", checkBoxRainEffectMenu.getValue()); - - config.setBool("EnableTextureCompression", checkBoxEnableTextureCompression.getValue()); - - config.setBool("EnableVideos", checkBoxVideos.getValue()); - - string currentResolution=config.getString("ScreenWidth")+"x"+config.getString("ScreenHeight"); - string selectedResolution=listBoxScreenModes.getSelectedItem(); - if(currentResolution!=selectedResolution){ - for(vector::const_iterator it= modeInfos.begin(); it!=modeInfos.end(); ++it){ - if((*it).getString()==selectedResolution) - { - config.setInt("ScreenWidth",(*it).width); - config.setInt("ScreenHeight",(*it).height); - config.setInt("ColorBits",(*it).depth); - } - } - } - - config.save(); - - if(config.getBool("DisableLuaSandbox","false") == true) { - LuaScript::setDisableSandbox(true); - } - - Renderer::getInstance().loadConfig(); - console.addLine(lang.getString("SettingsSaved")); +void MenuStateOptionsGraphics::saveConfig() { + Config &config = Config::getInstance(); + Lang &lang = Lang::getInstance(); + // setActiveInputLable(NULL); + + int selectionTypeindex = listBoxSelectionType.getSelectedItemIndex(); + if (selectionTypeindex == 0) { + config.setString("SelectionType", Config::selectBufPicking); + } else if (selectionTypeindex == 1) { + config.setString("SelectionType", Config::colorPicking); + } else if (selectionTypeindex == 2) { + config.setString("SelectionType", Config::frustumPicking); + } + + int index = listBoxShadows.getSelectedItemIndex(); + config.setString( + "Shadows", Renderer::shadowsToStr(static_cast(index))); + + string texSizeString = listBoxShadowTextureSize.getSelectedItem(); + config.setInt("ShadowTextureSize", strToInt(texSizeString)); + + config.setBool("Windowed", checkBoxFullscreenWindowed.getValue()); + config.setString("Filter", listBoxFilter.getSelectedItem()); + config.setInt("FilterMaxAnisotropy", + strToInt(listBoxFilterMaxAnisotropy.getSelectedItem())); + config.setFloat("GammaValue", + strToFloat(listBoxGammaCorrection.getSelectedItem())); + config.setFloat("ShadowIntensity", + strToFloat(listBoxShadowIntensity.getSelectedItem())); + config.setBool("Textures3D", checkBoxTextures3D.getValue()); + config.setBool("UnitParticles", (checkBoxUnitParticles.getValue())); + config.setBool("TilesetParticles", (checkBoxTilesetParticles.getValue())); + config.setBool("MapPreview", checkBoxMapPreview.getValue()); + config.setInt("MaxLights", listBoxLights.getSelectedItemIndex() + 1); + + if (listBoxAnimatedTilesetObjects.getSelectedItem() == "∞") { + config.setInt("AnimatedTilesetObjects", -1); + } else { + config.setInt( + "AnimatedTilesetObjects", + atoi(listBoxAnimatedTilesetObjects.getSelectedItem().c_str())); + } + + config.setBool("RainEffect", checkBoxRainEffect.getValue()); + config.setBool("RainEffectMenu", checkBoxRainEffectMenu.getValue()); + + config.setBool("EnableTextureCompression", + checkBoxEnableTextureCompression.getValue()); + + config.setBool("EnableVideos", checkBoxVideos.getValue()); + + string currentResolution = + config.getString("ScreenWidth") + "x" + config.getString("ScreenHeight"); + string selectedResolution = listBoxScreenModes.getSelectedItem(); + if (currentResolution != selectedResolution) { + for (vector::const_iterator it = modeInfos.begin(); + it != modeInfos.end(); ++it) { + if ((*it).getString() == selectedResolution) { + config.setInt("ScreenWidth", (*it).width); + config.setInt("ScreenHeight", (*it).height); + config.setInt("ColorBits", (*it).depth); + } + } + } + + config.save(); + + if (config.getBool("DisableLuaSandbox", "false") == true) { + LuaScript::setDisableSandbox(true); + } + + Renderer::getInstance().loadConfig(); + console.addLine(lang.getString("SettingsSaved")); } -//void MenuStateOptionsGraphics::setActiveInputLable(GraphicLabel *newLable) { +// void MenuStateOptionsGraphics::setActiveInputLable(GraphicLabel *newLable) { // MenuState::setActiveInputLabel(newLable,&activeInputLabel); // // if(newLable == &labelTransifexPwd) { @@ -951,6 +985,7 @@ void MenuStateOptionsGraphics::saveConfig(){ // else { // labelTransifexPwd.setIsPassword(true); // } -//} +// } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/menu/menu_state_options_graphics.h b/source/glest_game/menu/menu_state_options_graphics.h index 1b18469b3..94a2565bc 100644 --- a/source/glest_game/menu/menu_state_options_graphics.h +++ b/source/glest_game/menu/menu_state_options_graphics.h @@ -12,112 +12,111 @@ #ifndef _GLEST_GAME_MENUSTATEOPTIONS_GRAPHICS_H_ #define _GLEST_GAME_MENUSTATEOPTIONS_GRAPHICS_H_ -#include "main_menu.h" #include "leak_dumper.h" +#include "main_menu.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // =============================== // class MenuStateOptionsGraphics // =============================== -class MenuStateOptionsGraphics: public MenuState{ +class MenuStateOptionsGraphics : public MenuState { private: + GraphicButton buttonOk; + GraphicButton buttonReturn; + GraphicButton buttonAutoConfig; + GraphicButton buttonVideoInfo; - GraphicButton buttonOk; - GraphicButton buttonReturn; - GraphicButton buttonAutoConfig; - GraphicButton buttonVideoInfo; - - GraphicButton buttonKeyboardSetup; // configure the keyboard - GraphicButton buttonVideoSection; - GraphicButton buttonAudioSection; - GraphicButton buttonMiscSection; - GraphicButton buttonNetworkSettings; + GraphicButton buttonKeyboardSetup; // configure the keyboard + GraphicButton buttonVideoSection; + GraphicButton buttonAudioSection; + GraphicButton buttonMiscSection; + GraphicButton buttonNetworkSettings; - GraphicLabel labelShadows; - GraphicListBox listBoxShadows; - GraphicLabel labelFilter; - GraphicListBox listBoxFilter; - GraphicLabel labelFilterMaxAnisotropy; - GraphicListBox listBoxFilterMaxAnisotropy; + GraphicLabel labelShadows; + GraphicListBox listBoxShadows; + GraphicLabel labelFilter; + GraphicListBox listBoxFilter; + GraphicLabel labelFilterMaxAnisotropy; + GraphicListBox listBoxFilterMaxAnisotropy; - GraphicLabel labelTextures3D; - GraphicCheckBox checkBoxTextures3D; - GraphicLabel labelLights; - GraphicListBox listBoxLights; - GraphicLabel labelUnitParticles; - GraphicCheckBox checkBoxUnitParticles; + GraphicLabel labelTextures3D; + GraphicCheckBox checkBoxTextures3D; + GraphicLabel labelLights; + GraphicListBox listBoxLights; + GraphicLabel labelUnitParticles; + GraphicCheckBox checkBoxUnitParticles; - GraphicLabel labelTilesetParticles; - GraphicCheckBox checkBoxTilesetParticles; - GraphicLabel labelAnimatedTilesetObjects; - GraphicListBox listBoxAnimatedTilesetObjects; + GraphicLabel labelTilesetParticles; + GraphicCheckBox checkBoxTilesetParticles; + GraphicLabel labelAnimatedTilesetObjects; + GraphicListBox listBoxAnimatedTilesetObjects; + GraphicLabel labelScreenModes; + GraphicListBox listBoxScreenModes; + vector modeInfos; - GraphicLabel labelScreenModes; - GraphicListBox listBoxScreenModes; - vector modeInfos; + GraphicLabel labelFullscreenWindowed; + GraphicCheckBox checkBoxFullscreenWindowed; - GraphicLabel labelFullscreenWindowed; - GraphicCheckBox checkBoxFullscreenWindowed; + GraphicLabel labelMapPreview; + GraphicCheckBox checkBoxMapPreview; + GraphicMessageBox mainMessageBox; + int mainMessageBoxState; - GraphicLabel labelMapPreview; - GraphicCheckBox checkBoxMapPreview; + GraphicLabel labelEnableTextureCompression; + GraphicCheckBox checkBoxEnableTextureCompression; - GraphicMessageBox mainMessageBox; - int mainMessageBoxState; + GraphicLabel labelRainEffect; + GraphicLabel labelRainEffectSeparator; + GraphicCheckBox checkBoxRainEffect; + GraphicCheckBox checkBoxRainEffectMenu; - GraphicLabel labelEnableTextureCompression; - GraphicCheckBox checkBoxEnableTextureCompression; + GraphicLabel labelGammaCorrection; + GraphicListBox listBoxGammaCorrection; - GraphicLabel labelRainEffect; - GraphicLabel labelRainEffectSeparator; - GraphicCheckBox checkBoxRainEffect; - GraphicCheckBox checkBoxRainEffectMenu; + GraphicLabel labelShadowIntensity; + GraphicListBox listBoxShadowIntensity; - GraphicLabel labelGammaCorrection; - GraphicListBox listBoxGammaCorrection; + GraphicLabel labelShadowTextureSize; + GraphicListBox listBoxShadowTextureSize; - GraphicLabel labelShadowIntensity; - GraphicListBox listBoxShadowIntensity; + GraphicLabel labelVideos; + GraphicCheckBox checkBoxVideos; - GraphicLabel labelShadowTextureSize; - GraphicListBox listBoxShadowTextureSize; + GraphicLabel labelSelectionType; + GraphicListBox listBoxSelectionType; - GraphicLabel labelVideos; - GraphicCheckBox checkBoxVideos; - - GraphicLabel labelSelectionType; - GraphicListBox listBoxSelectionType; - - ProgramState **parentUI; - time_t screenModeChangedTimer; + ProgramState **parentUI; + time_t screenModeChangedTimer; public: - MenuStateOptionsGraphics(Program *program, MainMenu *mainMenu, ProgramState **parentUI=NULL); - - void mouseClick(int x, int y, MouseButton mouseButton); - void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; - void mouseMove(int x, int y, const MouseState *mouseState); - void render(); - //virtual void keyDown(SDL_KeyboardEvent key); - virtual void keyPress(SDL_KeyboardEvent c); - //virtual bool isInSpecialKeyCaptureEvent(); + MenuStateOptionsGraphics(Program *program, MainMenu *mainMenu, + ProgramState **parentUI = NULL); - virtual void reloadUI(); + void mouseClick(int x, int y, MouseButton mouseButton); + void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; + void mouseMove(int x, int y, const MouseState *mouseState); + void render(); + // virtual void keyDown(SDL_KeyboardEvent key); + virtual void keyPress(SDL_KeyboardEvent c); + // virtual bool isInSpecialKeyCaptureEvent(); + virtual void reloadUI(); private: - void saveConfig(); - void setActiveInputLable(GraphicLabel* newLable); - void showMessageBox(const string &text, const string &header, bool toggle); - void revertScreenMode(); - void setupTransifexUI(); - virtual void update(); + void saveConfig(); + void setActiveInputLable(GraphicLabel *newLable); + void showMessageBox(const string &text, const string &header, bool toggle); + void revertScreenMode(); + void setupTransifexUI(); + virtual void update(); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/menu/menu_state_options_network.cpp b/source/glest_game/menu/menu_state_options_network.cpp index 611b8b701..404ace151 100644 --- a/source/glest_game/menu/menu_state_options_network.cpp +++ b/source/glest_game/menu/menu_state_options_network.cpp @@ -11,489 +11,517 @@ #include "menu_state_options_network.h" -#include "renderer.h" -#include "game.h" -#include "program.h" -#include "sound_renderer.h" -#include "core_data.h" #include "config.h" -#include "menu_state_root.h" -#include "menu_state_options.h" -#include "util.h" +#include "core_data.h" +#include "game.h" +#include "leak_dumper.h" #include "menu_state_keysetup.h" +#include "menu_state_options.h" #include "menu_state_options_graphics.h" #include "menu_state_options_network.h" #include "menu_state_options_sound.h" -#include "string_utils.h" +#include "menu_state_root.h" #include "metrics.h" -#include "leak_dumper.h" +#include "program.h" +#include "renderer.h" +#include "sound_renderer.h" +#include "string_utils.h" +#include "util.h" using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class MenuStateOptions // ===================================================== -MenuStateOptionsNetwork::MenuStateOptionsNetwork(Program *program, MainMenu *mainMenu, ProgramState **parentUI) : - MenuState(program, mainMenu, "config"), - buttonOk("Options_Network","buttonOk"), - buttonReturn("Options_Network","buttonReturn"), +MenuStateOptionsNetwork::MenuStateOptionsNetwork(Program *program, + MainMenu *mainMenu, + ProgramState **parentUI) + : MenuState(program, mainMenu, "config"), + buttonOk("Options_Network", "buttonOk"), + buttonReturn("Options_Network", "buttonReturn"), - buttonKeyboardSetup("Options_Network","buttonKeyboardSetup"), - buttonVideoSection("Options_Network","buttonVideoSection"), - buttonAudioSection("Options_Network","buttonAudioSection"), - buttonMiscSection("Options_Network","buttonMiscSection"), - buttonNetworkSettings("Options_Network","buttonNetworkSettings"), + buttonKeyboardSetup("Options_Network", "buttonKeyboardSetup"), + buttonVideoSection("Options_Network", "buttonVideoSection"), + buttonAudioSection("Options_Network", "buttonAudioSection"), + buttonMiscSection("Options_Network", "buttonMiscSection"), + buttonNetworkSettings("Options_Network", "buttonNetworkSettings"), - mainMessageBox("Options_Network","mainMessageBox"), + mainMessageBox("Options_Network", "mainMessageBox"), - labelExternalPort("Options_Network","labelExternalPort"), - labelServerPortLabel("Options_Network","labelServerPortLabel"), + labelExternalPort("Options_Network", "labelExternalPort"), + labelServerPortLabel("Options_Network", "labelServerPortLabel"), - labelPublishServerExternalPort("Options_Network","labelPublishServerExternalPort"), - listBoxServerPort("Options_Network","listBoxServerPort"), + labelPublishServerExternalPort("Options_Network", + "labelPublishServerExternalPort"), + listBoxServerPort("Options_Network", "listBoxServerPort"), - labelEnableFTP("Options_Network","labelEnableFTP"), - checkBoxEnableFTP("Options_Network","checkBoxEnableFTP"), + labelEnableFTP("Options_Network", "labelEnableFTP"), + checkBoxEnableFTP("Options_Network", "checkBoxEnableFTP"), - labelEnableFTPServer("Options_Network","labelEnableFTPServer"), - checkBoxEnableFTPServer("Options_Network","checkBoxEnableFTPServer"), + labelEnableFTPServer("Options_Network", "labelEnableFTPServer"), + checkBoxEnableFTPServer("Options_Network", "checkBoxEnableFTPServer"), - labelFTPServerPortLabel("Options_Network","labelFTPServerPortLabel"), - labelFTPServerPort("Options_Network","labelFTPServerPort"), + labelFTPServerPortLabel("Options_Network", "labelFTPServerPortLabel"), + labelFTPServerPort("Options_Network", "labelFTPServerPort"), - labelFTPServerDataPortsLabel("Options_Network","labelFTPServerDataPortsLabel"), - labelFTPServerDataPorts("Options_Network","labelFTPServerDataPorts"), + labelFTPServerDataPortsLabel("Options_Network", + "labelFTPServerDataPortsLabel"), + labelFTPServerDataPorts("Options_Network", "labelFTPServerDataPorts"), - labelEnableFTPServerInternetTilesetXfer("Options_Network","labelEnableFTPServerInternetTilesetXfer"), - checkBoxEnableFTPServerInternetTilesetXfer("Options_Network","checkBoxEnableFTPServerInternetTilesetXfer"), + labelEnableFTPServerInternetTilesetXfer( + "Options_Network", "labelEnableFTPServerInternetTilesetXfer"), + checkBoxEnableFTPServerInternetTilesetXfer( + "Options_Network", "checkBoxEnableFTPServerInternetTilesetXfer"), - labelEnableFTPServerInternetTechtreeXfer("Options_Network","labelEnableFTPServerInternetTechtreeXfer"), - checkBoxEnableFTPServerInternetTechtreeXfer("Options_Network","checkBoxEnableFTPServerInternetTechtreeXfer"), + labelEnableFTPServerInternetTechtreeXfer( + "Options_Network", "labelEnableFTPServerInternetTechtreeXfer"), + checkBoxEnableFTPServerInternetTechtreeXfer( + "Options_Network", "checkBoxEnableFTPServerInternetTechtreeXfer"), - labelEnablePrivacy("Options_Network","labelEnablePrivacy"), - checkBoxEnablePrivacy("Options_Network","checkBoxEnablePrivacy") + labelEnablePrivacy("Options_Network", "labelEnablePrivacy"), + checkBoxEnablePrivacy("Options_Network", "checkBoxEnablePrivacy") { - try { - containerName = "Options_Network"; - Lang &lang= Lang::getInstance(); - Config &config= Config::getInstance(); - this->parentUI=parentUI; - this->console.setOnlyChatMessagesInStoredLines(false); - - int leftLabelStart=100; - int leftColumnStart=leftLabelStart+300; - int buttonRowPos=50; - int buttonStartPos=170; - int lineOffset=30; - int tabButtonWidth=200; - int tabButtonHeight=30; - - mainMessageBox.init(lang.getString("Ok")); - mainMessageBox.setEnabled(false); - mainMessageBoxState=0; - - buttonAudioSection.init(0, 720,tabButtonWidth,tabButtonHeight); - buttonAudioSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonAudioSection.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonAudioSection.setText(lang.getString("Audio")); - // Video Section - buttonVideoSection.init(200, 720,tabButtonWidth,tabButtonHeight); - buttonVideoSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonVideoSection.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonVideoSection.setText(lang.getString("Video")); - //currentLine-=lineOffset; - //MiscSection - buttonMiscSection.init(400, 720,tabButtonWidth,tabButtonHeight); - buttonMiscSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonMiscSection.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonMiscSection.setText(lang.getString("Misc")); - //NetworkSettings - buttonNetworkSettings.init(600, 700,tabButtonWidth,tabButtonHeight+20); - buttonNetworkSettings.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonNetworkSettings.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonNetworkSettings.setText(lang.getString("Network")); - - //KeyboardSetup - buttonKeyboardSetup.init(800, 720,tabButtonWidth,tabButtonHeight); - buttonKeyboardSetup.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonKeyboardSetup.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonKeyboardSetup.setText(lang.getString("Keyboardsetup")); - - int currentLine=650; // reset line pos - int currentLabelStart=leftLabelStart; // set to right side - int currentColumnStart=leftColumnStart; // set to right side - - - // external server port - labelPublishServerExternalPort.init(currentLabelStart, currentLine, 150); - labelPublishServerExternalPort.setText(lang.getString("PublishServerExternalPort")); - - labelExternalPort.init(currentColumnStart,currentLine); - string extPort= config.getString("PortExternal","not set"); - if(extPort == "not set" || extPort == "0"){ - extPort=" --- "; - } - else{ - extPort="!!! "+extPort+" !!!"; - } - labelExternalPort.setText(extPort); - - currentLine-=lineOffset; - // server port - labelServerPortLabel.init(currentLabelStart,currentLine); - labelServerPortLabel.setText(lang.getString("ServerPort")); - - listBoxServerPort.init(currentColumnStart, currentLine, 160); - - string portListString = config.getString("PortList",intToStr(GameConstants::serverPort).c_str()); - std::vector portList; - Tokenize(portListString,portList,","); - - string currentPort=config.getString("PortServer", intToStr(GameConstants::serverPort).c_str()); - int portSelectionIndex=0; - for(int idx = 0; idx < (int)portList.size(); idx++) { - if(portList[idx] != "" && IsNumeric(portList[idx].c_str(),false)) { - listBoxServerPort.pushBackItem(portList[idx]); - if(currentPort==portList[idx]) - { - portSelectionIndex=idx; - } - } - } - listBoxServerPort.setSelectedItemIndex(portSelectionIndex); - - currentLine-=lineOffset; - labelFTPServerPortLabel.init(currentLabelStart ,currentLine ); - labelFTPServerPortLabel.setText(lang.getString("FTPServerPort")); - - int FTPPort = config.getInt("FTPServerPort",intToStr(ServerSocket::getFTPServerPort()).c_str()); - labelFTPServerPort.init(currentColumnStart ,currentLine ); - labelFTPServerPort.setText(intToStr(FTPPort)); - currentLine-=lineOffset; - labelFTPServerDataPortsLabel.init(currentLabelStart ,currentLine ); - labelFTPServerDataPortsLabel.setText(lang.getString("FTPServerDataPort")); - - char szBuf[8096]=""; - snprintf(szBuf,8096,"%d - %d",FTPPort + 1, FTPPort + GameConstants::maxPlayers); - - labelFTPServerDataPorts.init(currentColumnStart,currentLine ); - labelFTPServerDataPorts.setText(szBuf); - currentLine-=lineOffset; - labelEnableFTPServer.init(currentLabelStart ,currentLine); - labelEnableFTPServer.setText(lang.getString("EnableFTPServer")); - - checkBoxEnableFTPServer.init(currentColumnStart ,currentLine ); - checkBoxEnableFTPServer.setValue(config.getBool("EnableFTPServer","true")); - currentLine-=lineOffset; - // FTP Config - start - labelEnableFTP.init(currentLabelStart ,currentLine); - labelEnableFTP.setText(lang.getString("EnableFTP")); - - checkBoxEnableFTP.init(currentColumnStart ,currentLine ); - checkBoxEnableFTP.setValue(config.getBool("EnableFTPXfer","true")); - currentLine-=lineOffset; - - labelEnableFTPServerInternetTilesetXfer.init(currentLabelStart ,currentLine ); - labelEnableFTPServerInternetTilesetXfer.setText(lang.getString("EnableFTPServerInternetTilesetXfer")); - - checkBoxEnableFTPServerInternetTilesetXfer.init(currentColumnStart ,currentLine ); - checkBoxEnableFTPServerInternetTilesetXfer.setValue(config.getBool("EnableFTPServerInternetTilesetXfer","true")); - - currentLine-=lineOffset; - - labelEnableFTPServerInternetTechtreeXfer.init(currentLabelStart ,currentLine ); - labelEnableFTPServerInternetTechtreeXfer.setText(lang.getString("EnableFTPServerInternetTechtreeXfer")); - - checkBoxEnableFTPServerInternetTechtreeXfer.init(currentColumnStart ,currentLine ); - checkBoxEnableFTPServerInternetTechtreeXfer.setValue(config.getBool("EnableFTPServerInternetTechtreeXfer","true")); - - currentLine-=lineOffset; - - - // FTP config end - - // Privacy flag - labelEnablePrivacy.init(currentLabelStart ,currentLine); - labelEnablePrivacy.setText(lang.getString("PrivacyPlease")); - - checkBoxEnablePrivacy.init(currentColumnStart ,currentLine ); - checkBoxEnablePrivacy.setValue(config.getBool("PrivacyPlease","false")); - //currentLine-=lineOffset; - // end - - // buttons - buttonOk.init(buttonStartPos, buttonRowPos, 100); - buttonOk.setText(lang.getString("Save")); - - buttonReturn.setText(lang.getString("Return")); - buttonReturn.init(buttonStartPos+110, buttonRowPos, 100); - - GraphicComponent::applyAllCustomProperties(containerName); - } - catch(exception &e) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error loading options: %s\n",__FILE__,__FUNCTION__,__LINE__,e.what()); - throw megaglest_runtime_error(string("Error loading options msg: ") + e.what()); - } + try { + containerName = "Options_Network"; + Lang &lang = Lang::getInstance(); + Config &config = Config::getInstance(); + this->parentUI = parentUI; + this->console.setOnlyChatMessagesInStoredLines(false); + + int leftLabelStart = 100; + int leftColumnStart = leftLabelStart + 300; + int buttonRowPos = 50; + int buttonStartPos = 170; + int lineOffset = 30; + int tabButtonWidth = 200; + int tabButtonHeight = 30; + + mainMessageBox.init(lang.getString("Ok")); + mainMessageBox.setEnabled(false); + mainMessageBoxState = 0; + + buttonAudioSection.init(0, 720, tabButtonWidth, tabButtonHeight); + buttonAudioSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); + buttonAudioSection.setFont3D( + CoreData::getInstance().getMenuFontVeryBig3D()); + buttonAudioSection.setText(lang.getString("Audio")); + // Video Section + buttonVideoSection.init(200, 720, tabButtonWidth, tabButtonHeight); + buttonVideoSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); + buttonVideoSection.setFont3D( + CoreData::getInstance().getMenuFontVeryBig3D()); + buttonVideoSection.setText(lang.getString("Video")); + // currentLine-=lineOffset; + // MiscSection + buttonMiscSection.init(400, 720, tabButtonWidth, tabButtonHeight); + buttonMiscSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); + buttonMiscSection.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); + buttonMiscSection.setText(lang.getString("Misc")); + // NetworkSettings + buttonNetworkSettings.init(600, 700, tabButtonWidth, tabButtonHeight + 20); + buttonNetworkSettings.setFont(CoreData::getInstance().getMenuFontVeryBig()); + buttonNetworkSettings.setFont3D( + CoreData::getInstance().getMenuFontVeryBig3D()); + buttonNetworkSettings.setText(lang.getString("Network")); + + // KeyboardSetup + buttonKeyboardSetup.init(800, 720, tabButtonWidth, tabButtonHeight); + buttonKeyboardSetup.setFont(CoreData::getInstance().getMenuFontVeryBig()); + buttonKeyboardSetup.setFont3D( + CoreData::getInstance().getMenuFontVeryBig3D()); + buttonKeyboardSetup.setText(lang.getString("Keyboardsetup")); + + int currentLine = 650; // reset line pos + int currentLabelStart = leftLabelStart; // set to right side + int currentColumnStart = leftColumnStart; // set to right side + + // external server port + labelPublishServerExternalPort.init(currentLabelStart, currentLine, 150); + labelPublishServerExternalPort.setText( + lang.getString("PublishServerExternalPort")); + + labelExternalPort.init(currentColumnStart, currentLine); + string extPort = config.getString("PortExternal", "not set"); + if (extPort == "not set" || extPort == "0") { + extPort = " --- "; + } else { + extPort = "!!! " + extPort + " !!!"; + } + labelExternalPort.setText(extPort); + + currentLine -= lineOffset; + // server port + labelServerPortLabel.init(currentLabelStart, currentLine); + labelServerPortLabel.setText(lang.getString("ServerPort")); + + listBoxServerPort.init(currentColumnStart, currentLine, 160); + + string portListString = config.getString( + "PortList", intToStr(GameConstants::serverPort).c_str()); + std::vector portList; + Tokenize(portListString, portList, ","); + + string currentPort = config.getString( + "PortServer", intToStr(GameConstants::serverPort).c_str()); + int portSelectionIndex = 0; + for (int idx = 0; idx < (int)portList.size(); idx++) { + if (portList[idx] != "" && IsNumeric(portList[idx].c_str(), false)) { + listBoxServerPort.pushBackItem(portList[idx]); + if (currentPort == portList[idx]) { + portSelectionIndex = idx; + } + } + } + listBoxServerPort.setSelectedItemIndex(portSelectionIndex); + + currentLine -= lineOffset; + labelFTPServerPortLabel.init(currentLabelStart, currentLine); + labelFTPServerPortLabel.setText(lang.getString("FTPServerPort")); + + int FTPPort = config.getInt( + "FTPServerPort", intToStr(ServerSocket::getFTPServerPort()).c_str()); + labelFTPServerPort.init(currentColumnStart, currentLine); + labelFTPServerPort.setText(intToStr(FTPPort)); + currentLine -= lineOffset; + labelFTPServerDataPortsLabel.init(currentLabelStart, currentLine); + labelFTPServerDataPortsLabel.setText(lang.getString("FTPServerDataPort")); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "%d - %d", FTPPort + 1, + FTPPort + GameConstants::maxPlayers); + + labelFTPServerDataPorts.init(currentColumnStart, currentLine); + labelFTPServerDataPorts.setText(szBuf); + currentLine -= lineOffset; + labelEnableFTPServer.init(currentLabelStart, currentLine); + labelEnableFTPServer.setText(lang.getString("EnableFTPServer")); + + checkBoxEnableFTPServer.init(currentColumnStart, currentLine); + checkBoxEnableFTPServer.setValue(config.getBool("EnableFTPServer", "true")); + currentLine -= lineOffset; + // FTP Config - start + labelEnableFTP.init(currentLabelStart, currentLine); + labelEnableFTP.setText(lang.getString("EnableFTP")); + + checkBoxEnableFTP.init(currentColumnStart, currentLine); + checkBoxEnableFTP.setValue(config.getBool("EnableFTPXfer", "true")); + currentLine -= lineOffset; + + labelEnableFTPServerInternetTilesetXfer.init(currentLabelStart, + currentLine); + labelEnableFTPServerInternetTilesetXfer.setText( + lang.getString("EnableFTPServerInternetTilesetXfer")); + + checkBoxEnableFTPServerInternetTilesetXfer.init(currentColumnStart, + currentLine); + checkBoxEnableFTPServerInternetTilesetXfer.setValue( + config.getBool("EnableFTPServerInternetTilesetXfer", "true")); + + currentLine -= lineOffset; + + labelEnableFTPServerInternetTechtreeXfer.init(currentLabelStart, + currentLine); + labelEnableFTPServerInternetTechtreeXfer.setText( + lang.getString("EnableFTPServerInternetTechtreeXfer")); + + checkBoxEnableFTPServerInternetTechtreeXfer.init(currentColumnStart, + currentLine); + checkBoxEnableFTPServerInternetTechtreeXfer.setValue( + config.getBool("EnableFTPServerInternetTechtreeXfer", "true")); + + currentLine -= lineOffset; + + // FTP config end + + // Privacy flag + labelEnablePrivacy.init(currentLabelStart, currentLine); + labelEnablePrivacy.setText(lang.getString("PrivacyPlease")); + + checkBoxEnablePrivacy.init(currentColumnStart, currentLine); + checkBoxEnablePrivacy.setValue(config.getBool("PrivacyPlease", "false")); + // currentLine-=lineOffset; + // end + + // buttons + buttonOk.init(buttonStartPos, buttonRowPos, 100); + buttonOk.setText(lang.getString("Save")); + + buttonReturn.setText(lang.getString("Return")); + buttonReturn.init(buttonStartPos + 110, buttonRowPos, 100); + + GraphicComponent::applyAllCustomProperties(containerName); + } catch (exception &e) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error loading options: %s\n", + __FILE__, __FUNCTION__, __LINE__, e.what()); + throw megaglest_runtime_error(string("Error loading options msg: ") + + e.what()); + } } void MenuStateOptionsNetwork::reloadUI() { - Lang &lang= Lang::getInstance(); - - mainMessageBox.init(lang.getString("Ok")); - - buttonAudioSection.setText(lang.getString("Audio")); - buttonVideoSection.setText(lang.getString("Video")); - buttonMiscSection.setText(lang.getString("Misc")); - buttonNetworkSettings.setText(lang.getString("Network")); - - std::vector listboxData; - listboxData.push_back("None"); - listboxData.push_back("OpenAL"); - - listboxData.clear(); - listboxData.push_back("Bilinear"); - listboxData.push_back("Trilinear"); - - listboxData.clear(); - for (float f=0.0;f<2.1f;f=f+0.1f) { - listboxData.push_back(floatToStr(f)); - } - listboxData.clear(); - for(int i= 0; i(i)))); - } - - - labelServerPortLabel.setText(lang.getString("ServerPort")); - labelPublishServerExternalPort.setText(lang.getString("PublishServerExternalPort")); - labelEnableFTP.setText(lang.getString("EnableFTP")); - labelEnableFTPServer.setText(lang.getString("EnableFTPServer")); - labelFTPServerPortLabel.setText(lang.getString("FTPServerPort")); - labelFTPServerDataPortsLabel.setText(lang.getString("FTPServerDataPort")); - labelEnableFTPServerInternetTilesetXfer.setText(lang.getString("EnableFTPServerInternetTilesetXfer")); - labelEnableFTPServerInternetTechtreeXfer.setText(lang.getString("EnableFTPServerInternetTechtreeXfer")); - labelEnablePrivacy.setText(lang.getString("PrivacyPlease")); - buttonOk.setText(lang.getString("Save")); - buttonReturn.setText(lang.getString("Return")); + Lang &lang = Lang::getInstance(); + + mainMessageBox.init(lang.getString("Ok")); + + buttonAudioSection.setText(lang.getString("Audio")); + buttonVideoSection.setText(lang.getString("Video")); + buttonMiscSection.setText(lang.getString("Misc")); + buttonNetworkSettings.setText(lang.getString("Network")); + + std::vector listboxData; + listboxData.push_back("None"); + listboxData.push_back("OpenAL"); + + listboxData.clear(); + listboxData.push_back("Bilinear"); + listboxData.push_back("Trilinear"); + + listboxData.clear(); + for (float f = 0.0; f < 2.1f; f = f + 0.1f) { + listboxData.push_back(floatToStr(f)); + } + listboxData.clear(); + for (int i = 0; i < Renderer::sCount; ++i) { + listboxData.push_back(lang.getString( + Renderer::shadowsToStr(static_cast(i)))); + } + + labelServerPortLabel.setText(lang.getString("ServerPort")); + labelPublishServerExternalPort.setText( + lang.getString("PublishServerExternalPort")); + labelEnableFTP.setText(lang.getString("EnableFTP")); + labelEnableFTPServer.setText(lang.getString("EnableFTPServer")); + labelFTPServerPortLabel.setText(lang.getString("FTPServerPort")); + labelFTPServerDataPortsLabel.setText(lang.getString("FTPServerDataPort")); + labelEnableFTPServerInternetTilesetXfer.setText( + lang.getString("EnableFTPServerInternetTilesetXfer")); + labelEnableFTPServerInternetTechtreeXfer.setText( + lang.getString("EnableFTPServerInternetTechtreeXfer")); + labelEnablePrivacy.setText(lang.getString("PrivacyPlease")); + buttonOk.setText(lang.getString("Save")); + buttonReturn.setText(lang.getString("Return")); } -void MenuStateOptionsNetwork::mouseClick(int x, int y, MouseButton mouseButton) { - CoreData &coreData= CoreData::getInstance(); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - - if(mainMessageBox.getEnabled()) { - int button= 0; - if(mainMessageBox.mouseClick(x, y, button)) { - soundRenderer.playFx(coreData.getClickSoundA()); - if(button == 0) { - if(mainMessageBoxState == 1) { - mainMessageBoxState=0; - mainMessageBox.setEnabled(false); - saveConfig(); - - Lang &lang= Lang::getInstance(); - mainMessageBox.init(lang.getString("Ok")); - mainMenu->setState(new MenuStateOptions(program, mainMenu)); - } - else { - mainMessageBox.setEnabled(false); - - Lang &lang= Lang::getInstance(); - mainMessageBox.init(lang.getString("Ok")); - } - } - - } - } - else if(buttonOk.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - saveConfig(); - //mainMenu->setState(new MenuStateOptions(program, mainMenu,this->parentUI)); - return; +void MenuStateOptionsNetwork::mouseClick(int x, int y, + MouseButton mouseButton) { + CoreData &coreData = CoreData::getInstance(); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + + if (mainMessageBox.getEnabled()) { + int button = 0; + if (mainMessageBox.mouseClick(x, y, button)) { + soundRenderer.playFx(coreData.getClickSoundA()); + if (button == 0) { + if (mainMessageBoxState == 1) { + mainMessageBoxState = 0; + mainMessageBox.setEnabled(false); + saveConfig(); + + Lang &lang = Lang::getInstance(); + mainMessageBox.init(lang.getString("Ok")); + mainMenu->setState(new MenuStateOptions(program, mainMenu)); + } else { + mainMessageBox.setEnabled(false); + + Lang &lang = Lang::getInstance(); + mainMessageBox.init(lang.getString("Ok")); + } + } } - else if(buttonReturn.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - if(this->parentUI != NULL) { - *this->parentUI = NULL; - delete *this->parentUI; - } - mainMenu->setState(new MenuStateRoot(program, mainMenu)); - return; + } else if (buttonOk.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + saveConfig(); + // mainMenu->setState(new MenuStateOptions(program, + // mainMenu,this->parentUI)); + return; + } else if (buttonReturn.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + if (this->parentUI != NULL) { + *this->parentUI = NULL; + delete *this->parentUI; } - else if(buttonAudioSection.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - mainMenu->setState(new MenuStateOptionsSound(program, mainMenu,this->parentUI)); // open keyboard shortcuts setup screen - return; - } - else if(buttonNetworkSettings.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - //mainMenu->setState(new MenuStateOptionsNetwork(program, mainMenu,this->parentUI)); // open keyboard shortcuts setup screen - return; - } - else if(buttonMiscSection.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - mainMenu->setState(new MenuStateOptions(program, mainMenu,this->parentUI)); // open keyboard shortcuts setup screen - return; - } - else if(buttonVideoSection.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - mainMenu->setState(new MenuStateOptionsGraphics(program, mainMenu,this->parentUI)); // open keyboard shortcuts setup screen - return; - } - else if(buttonKeyboardSetup.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - mainMenu->setState(new MenuStateKeysetup(program, mainMenu,this->parentUI)); // open keyboard shortcuts setup screen - //showMessageBox("Not implemented yet", "Keyboard setup", false); - return; - } - else - { - if(listBoxServerPort.mouseClick(x, y)){ - int selectedPort=strToInt(listBoxServerPort.getSelectedItem()); - if(selectedPort<10000){ - selectedPort=GameConstants::serverPort; - } - // use the following ports for ftp - char szBuf[8096]=""; - snprintf(szBuf,8096,"%d - %d",selectedPort + 2, selectedPort + 1 + GameConstants::maxPlayers); - labelFTPServerPort.setText(intToStr(selectedPort+1)); - labelFTPServerDataPorts.setText(szBuf); - } - - checkBoxEnableFTP.mouseClick(x, y); - checkBoxEnableFTPServer.mouseClick(x, y); - - checkBoxEnableFTPServerInternetTilesetXfer.mouseClick(x, y); - checkBoxEnableFTPServerInternetTechtreeXfer.mouseClick(x, y); - - checkBoxEnablePrivacy.mouseClick(x, y); - } + mainMenu->setState(new MenuStateRoot(program, mainMenu)); + return; + } else if (buttonAudioSection.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + mainMenu->setState(new MenuStateOptionsSound( + program, mainMenu, + this->parentUI)); // open keyboard shortcuts setup screen + return; + } else if (buttonNetworkSettings.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + // mainMenu->setState(new MenuStateOptionsNetwork(program, + // mainMenu,this->parentUI)); // open keyboard shortcuts setup screen + return; + } else if (buttonMiscSection.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + mainMenu->setState(new MenuStateOptions( + program, mainMenu, + this->parentUI)); // open keyboard shortcuts setup screen + return; + } else if (buttonVideoSection.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + mainMenu->setState(new MenuStateOptionsGraphics( + program, mainMenu, + this->parentUI)); // open keyboard shortcuts setup screen + return; + } else if (buttonKeyboardSetup.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + mainMenu->setState(new MenuStateKeysetup( + program, mainMenu, + this->parentUI)); // open keyboard shortcuts setup screen + // showMessageBox("Not implemented yet", "Keyboard setup", false); + return; + } else { + if (listBoxServerPort.mouseClick(x, y)) { + int selectedPort = strToInt(listBoxServerPort.getSelectedItem()); + if (selectedPort < 10000) { + selectedPort = GameConstants::serverPort; + } + // use the following ports for ftp + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "%d - %d", selectedPort + 2, + selectedPort + 1 + GameConstants::maxPlayers); + labelFTPServerPort.setText(intToStr(selectedPort + 1)); + labelFTPServerDataPorts.setText(szBuf); + } + + checkBoxEnableFTP.mouseClick(x, y); + checkBoxEnableFTPServer.mouseClick(x, y); + + checkBoxEnableFTPServerInternetTilesetXfer.mouseClick(x, y); + checkBoxEnableFTPServerInternetTechtreeXfer.mouseClick(x, y); + + checkBoxEnablePrivacy.mouseClick(x, y); + } } -void MenuStateOptionsNetwork::mouseMove(int x, int y, const MouseState *ms){ - if (mainMessageBox.getEnabled()) { - mainMessageBox.mouseMove(x, y); - } - - buttonOk.mouseMove(x, y); - buttonReturn.mouseMove(x, y); - buttonKeyboardSetup.mouseMove(x, y); - buttonAudioSection.mouseMove(x, y); - buttonNetworkSettings.mouseMove(x, y); - buttonMiscSection.mouseMove(x, y); - buttonVideoSection.mouseMove(x, y); - listBoxServerPort.mouseMove(x, y); - checkBoxEnableFTP.mouseMove(x, y); - checkBoxEnableFTPServer.mouseMove(x, y); - checkBoxEnableFTPServerInternetTilesetXfer.mouseMove(x, y); - checkBoxEnableFTPServerInternetTechtreeXfer.mouseMove(x, y); - checkBoxEnablePrivacy.mouseMove(x, y); +void MenuStateOptionsNetwork::mouseMove(int x, int y, const MouseState *ms) { + if (mainMessageBox.getEnabled()) { + mainMessageBox.mouseMove(x, y); + } + + buttonOk.mouseMove(x, y); + buttonReturn.mouseMove(x, y); + buttonKeyboardSetup.mouseMove(x, y); + buttonAudioSection.mouseMove(x, y); + buttonNetworkSettings.mouseMove(x, y); + buttonMiscSection.mouseMove(x, y); + buttonVideoSection.mouseMove(x, y); + listBoxServerPort.mouseMove(x, y); + checkBoxEnableFTP.mouseMove(x, y); + checkBoxEnableFTPServer.mouseMove(x, y); + checkBoxEnableFTPServerInternetTilesetXfer.mouseMove(x, y); + checkBoxEnableFTPServerInternetTechtreeXfer.mouseMove(x, y); + checkBoxEnablePrivacy.mouseMove(x, y); } -//bool MenuStateOptionsNetwork::isInSpecialKeyCaptureEvent() { +// bool MenuStateOptionsNetwork::isInSpecialKeyCaptureEvent() { // return (activeInputLabel != NULL); -//} +// } // -//void MenuStateOptionsNetwork::keyDown(SDL_KeyboardEvent key) { +// void MenuStateOptionsNetwork::keyDown(SDL_KeyboardEvent key) { // if(activeInputLabel != NULL) { // keyDownEditLabel(key, &activeInputLabel); // } -//} +// } void MenuStateOptionsNetwork::keyPress(SDL_KeyboardEvent c) { -// if(activeInputLabel != NULL) { -// //printf("[%d]\n",c); fflush(stdout); -// if( &labelPlayerName == activeInputLabel || -// &labelTransifexUser == activeInputLabel || -// &labelTransifexPwd == activeInputLabel || -// &labelTransifexI18N == activeInputLabel) { -// textInputEditLabel(c, &activeInputLabel); -// } -// } -// else { - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - if(isKeyPressed(configKeys.getSDLKey("SaveGUILayout"),c) == true) { - GraphicComponent::saveAllCustomProperties(containerName); - //Lang &lang= Lang::getInstance(); - //console.addLine(lang.getString("GUILayoutSaved") + " [" + (saved ? lang.getString("Yes") : lang.getString("No"))+ "]"); - } -// } + // if(activeInputLabel != NULL) { + // //printf("[%d]\n",c); fflush(stdout); + // if( &labelPlayerName == activeInputLabel || + // &labelTransifexUser == activeInputLabel || + // &labelTransifexPwd == activeInputLabel || + // &labelTransifexI18N == activeInputLabel) { + // textInputEditLabel(c, &activeInputLabel); + // } + // } + // else { + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + if (isKeyPressed(configKeys.getSDLKey("SaveGUILayout"), c) == true) { + GraphicComponent::saveAllCustomProperties(containerName); + // Lang &lang= Lang::getInstance(); + // console.addLine(lang.getString("GUILayoutSaved") + " [" + (saved ? + // lang.getString("Yes") : lang.getString("No"))+ "]"); + } + // } } -void MenuStateOptionsNetwork::render(){ - Renderer &renderer= Renderer::getInstance(); - - if(mainMessageBox.getEnabled()){ - renderer.renderMessageBox(&mainMessageBox); - } - else - { - renderer.renderButton(&buttonOk); - renderer.renderButton(&buttonReturn); - renderer.renderButton(&buttonKeyboardSetup); - renderer.renderButton(&buttonVideoSection); - renderer.renderButton(&buttonAudioSection); - renderer.renderButton(&buttonMiscSection); - renderer.renderButton(&buttonNetworkSettings); - renderer.renderLabel(&labelServerPortLabel); - renderer.renderLabel(&labelExternalPort); - renderer.renderLabel(&labelPublishServerExternalPort); - renderer.renderListBox(&listBoxServerPort); - - - renderer.renderLabel(&labelEnableFTP); - renderer.renderCheckBox(&checkBoxEnableFTP); - - renderer.renderLabel(&labelEnableFTPServer); - renderer.renderCheckBox(&checkBoxEnableFTPServer); - - renderer.renderLabel(&labelFTPServerPortLabel); - renderer.renderLabel(&labelFTPServerPort); - renderer.renderLabel(&labelFTPServerDataPortsLabel); - renderer.renderLabel(&labelFTPServerDataPorts); - - renderer.renderLabel(&labelEnableFTPServerInternetTilesetXfer); - renderer.renderCheckBox(&checkBoxEnableFTPServerInternetTilesetXfer); - renderer.renderLabel(&labelEnableFTPServerInternetTechtreeXfer); - renderer.renderCheckBox(&checkBoxEnableFTPServerInternetTechtreeXfer); - - renderer.renderLabel(&labelEnablePrivacy); - renderer.renderCheckBox(&checkBoxEnablePrivacy); - - } - - renderer.renderConsole(&console); - if(program != NULL) program->renderProgramMsgBox(); +void MenuStateOptionsNetwork::render() { + Renderer &renderer = Renderer::getInstance(); + + if (mainMessageBox.getEnabled()) { + renderer.renderMessageBox(&mainMessageBox); + } else { + renderer.renderButton(&buttonOk); + renderer.renderButton(&buttonReturn); + renderer.renderButton(&buttonKeyboardSetup); + renderer.renderButton(&buttonVideoSection); + renderer.renderButton(&buttonAudioSection); + renderer.renderButton(&buttonMiscSection); + renderer.renderButton(&buttonNetworkSettings); + renderer.renderLabel(&labelServerPortLabel); + renderer.renderLabel(&labelExternalPort); + renderer.renderLabel(&labelPublishServerExternalPort); + renderer.renderListBox(&listBoxServerPort); + + renderer.renderLabel(&labelEnableFTP); + renderer.renderCheckBox(&checkBoxEnableFTP); + + renderer.renderLabel(&labelEnableFTPServer); + renderer.renderCheckBox(&checkBoxEnableFTPServer); + + renderer.renderLabel(&labelFTPServerPortLabel); + renderer.renderLabel(&labelFTPServerPort); + renderer.renderLabel(&labelFTPServerDataPortsLabel); + renderer.renderLabel(&labelFTPServerDataPorts); + + renderer.renderLabel(&labelEnableFTPServerInternetTilesetXfer); + renderer.renderCheckBox(&checkBoxEnableFTPServerInternetTilesetXfer); + renderer.renderLabel(&labelEnableFTPServerInternetTechtreeXfer); + renderer.renderCheckBox(&checkBoxEnableFTPServerInternetTechtreeXfer); + + renderer.renderLabel(&labelEnablePrivacy); + renderer.renderCheckBox(&checkBoxEnablePrivacy); + } + + renderer.renderConsole(&console); + if (program != NULL) + program->renderProgramMsgBox(); } -void MenuStateOptionsNetwork::saveConfig(){ - Config &config= Config::getInstance(); - Lang &lang= Lang::getInstance(); - setActiveInputLable(NULL); - +void MenuStateOptionsNetwork::saveConfig() { + Config &config = Config::getInstance(); + Lang &lang = Lang::getInstance(); + setActiveInputLable(NULL); - lang.loadGameStrings(config.getString("Lang")); + lang.loadGameStrings(config.getString("Lang")); - config.setString("PortServer", listBoxServerPort.getSelectedItem()); - config.setInt("FTPServerPort",config.getInt("PortServer")+1); - config.setBool("EnableFTPXfer", checkBoxEnableFTP.getValue()); - config.setBool("EnableFTPServer", checkBoxEnableFTPServer.getValue()); + config.setString("PortServer", listBoxServerPort.getSelectedItem()); + config.setInt("FTPServerPort", config.getInt("PortServer") + 1); + config.setBool("EnableFTPXfer", checkBoxEnableFTP.getValue()); + config.setBool("EnableFTPServer", checkBoxEnableFTPServer.getValue()); - config.setBool("EnableFTPServerInternetTilesetXfer", checkBoxEnableFTPServerInternetTilesetXfer.getValue()); - config.setBool("EnableFTPServerInternetTechtreeXfer", checkBoxEnableFTPServerInternetTechtreeXfer.getValue()); + config.setBool("EnableFTPServerInternetTilesetXfer", + checkBoxEnableFTPServerInternetTilesetXfer.getValue()); + config.setBool("EnableFTPServerInternetTechtreeXfer", + checkBoxEnableFTPServerInternetTechtreeXfer.getValue()); - config.setBool("PrivacyPlease", checkBoxEnablePrivacy.getValue()); + config.setBool("PrivacyPlease", checkBoxEnablePrivacy.getValue()); - config.save(); + config.save(); - Renderer::getInstance().loadConfig(); - console.addLine(lang.getString("SettingsSaved")); + Renderer::getInstance().loadConfig(); + console.addLine(lang.getString("SettingsSaved")); } -void MenuStateOptionsNetwork::setActiveInputLable(GraphicLabel *newLable) { -} +void MenuStateOptionsNetwork::setActiveInputLable(GraphicLabel *newLable) {} -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/menu/menu_state_options_network.h b/source/glest_game/menu/menu_state_options_network.h index c518a756a..533bb98df 100644 --- a/source/glest_game/menu/menu_state_options_network.h +++ b/source/glest_game/menu/menu_state_options_network.h @@ -12,80 +12,80 @@ #ifndef _GLEST_GAME_MENUSTATEOPTIONS_NETWORK_H_ #define _GLEST_GAME_MENUSTATEOPTIONS_NETWORK_H_ -#include "main_menu.h" #include "leak_dumper.h" +#include "main_menu.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // =============================== // class MenuStateOptionsNetwork // =============================== -class MenuStateOptionsNetwork: public MenuState{ +class MenuStateOptionsNetwork : public MenuState { private: + GraphicButton buttonOk; + GraphicButton buttonReturn; - GraphicButton buttonOk; - GraphicButton buttonReturn; - - GraphicButton buttonKeyboardSetup; // configure the keyboard - GraphicButton buttonVideoSection; - GraphicButton buttonAudioSection; - GraphicButton buttonMiscSection; - GraphicButton buttonNetworkSettings; + GraphicButton buttonKeyboardSetup; // configure the keyboard + GraphicButton buttonVideoSection; + GraphicButton buttonAudioSection; + GraphicButton buttonMiscSection; + GraphicButton buttonNetworkSettings; + GraphicMessageBox mainMessageBox; + int mainMessageBoxState; - GraphicMessageBox mainMessageBox; - int mainMessageBoxState; + GraphicLabel labelExternalPort; + GraphicLabel labelServerPortLabel; - GraphicLabel labelExternalPort; - GraphicLabel labelServerPortLabel; + GraphicLabel labelPublishServerExternalPort; + GraphicListBox listBoxServerPort; - GraphicLabel labelPublishServerExternalPort; - GraphicListBox listBoxServerPort; + GraphicLabel labelEnableFTP; + GraphicCheckBox checkBoxEnableFTP; - GraphicLabel labelEnableFTP; - GraphicCheckBox checkBoxEnableFTP; + GraphicLabel labelEnableFTPServer; + GraphicCheckBox checkBoxEnableFTPServer; - GraphicLabel labelEnableFTPServer; - GraphicCheckBox checkBoxEnableFTPServer; + GraphicLabel labelFTPServerPortLabel; + GraphicLabel labelFTPServerPort; - GraphicLabel labelFTPServerPortLabel; - GraphicLabel labelFTPServerPort; + GraphicLabel labelFTPServerDataPortsLabel; + GraphicLabel labelFTPServerDataPorts; - GraphicLabel labelFTPServerDataPortsLabel; - GraphicLabel labelFTPServerDataPorts; + GraphicLabel labelEnableFTPServerInternetTilesetXfer; + GraphicCheckBox checkBoxEnableFTPServerInternetTilesetXfer; - GraphicLabel labelEnableFTPServerInternetTilesetXfer; - GraphicCheckBox checkBoxEnableFTPServerInternetTilesetXfer; + GraphicLabel labelEnableFTPServerInternetTechtreeXfer; + GraphicCheckBox checkBoxEnableFTPServerInternetTechtreeXfer; - GraphicLabel labelEnableFTPServerInternetTechtreeXfer; - GraphicCheckBox checkBoxEnableFTPServerInternetTechtreeXfer; + GraphicLabel labelEnablePrivacy; + GraphicCheckBox checkBoxEnablePrivacy; - GraphicLabel labelEnablePrivacy; - GraphicCheckBox checkBoxEnablePrivacy; - - ProgramState **parentUI; + ProgramState **parentUI; public: - MenuStateOptionsNetwork(Program *program, MainMenu *mainMenu, ProgramState **parentUI=NULL); - - void mouseClick(int x, int y, MouseButton mouseButton); - void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; - void mouseMove(int x, int y, const MouseState *mouseState); - void render(); - //virtual void keyDown(SDL_KeyboardEvent key); - virtual void keyPress(SDL_KeyboardEvent c); - //virtual bool isInSpecialKeyCaptureEvent(); + MenuStateOptionsNetwork(Program *program, MainMenu *mainMenu, + ProgramState **parentUI = NULL); - virtual void reloadUI(); + void mouseClick(int x, int y, MouseButton mouseButton); + void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; + void mouseMove(int x, int y, const MouseState *mouseState); + void render(); + // virtual void keyDown(SDL_KeyboardEvent key); + virtual void keyPress(SDL_KeyboardEvent c); + // virtual bool isInSpecialKeyCaptureEvent(); + virtual void reloadUI(); private: - void saveConfig(); - void setActiveInputLable(GraphicLabel* newLable); - //void showMessageBox(const string &text, const string &header, bool toggle); + void saveConfig(); + void setActiveInputLable(GraphicLabel *newLable); + // void showMessageBox(const string &text, const string &header, bool toggle); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/menu/menu_state_options_sound.cpp b/source/glest_game/menu/menu_state_options_sound.cpp index 40835a1eb..28690339d 100644 --- a/source/glest_game/menu/menu_state_options_sound.cpp +++ b/source/glest_game/menu/menu_state_options_sound.cpp @@ -11,424 +11,426 @@ #include "menu_state_options_sound.h" -#include "renderer.h" -#include "game.h" -#include "program.h" -#include "sound_renderer.h" -#include "core_data.h" #include "config.h" -#include "menu_state_root.h" -#include "menu_state_options.h" -#include "util.h" +#include "core_data.h" +#include "game.h" +#include "leak_dumper.h" #include "menu_state_keysetup.h" +#include "menu_state_options.h" #include "menu_state_options_graphics.h" #include "menu_state_options_network.h" #include "menu_state_options_sound.h" -#include "string_utils.h" +#include "menu_state_root.h" #include "metrics.h" -#include "leak_dumper.h" +#include "program.h" +#include "renderer.h" +#include "sound_renderer.h" +#include "string_utils.h" +#include "util.h" using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class MenuStateOptions // ===================================================== -MenuStateOptionsSound::MenuStateOptionsSound(Program *program, MainMenu *mainMenu, ProgramState **parentUI) : - MenuState(program, mainMenu, "config"), - buttonOk("Options_Sound","buttonOk"), - buttonReturn("Options_Sound","buttonReturn"), - - buttonKeyboardSetup("Options_Sound","buttonKeyboardSetup"), - buttonVideoSection("Options_Sound","buttonVideoSection"), - buttonAudioSection("Options_Sound","buttonAudioSection"), - buttonMiscSection("Options_Sound","buttonMiscSection"), - buttonNetworkSettings("Options_Sound","buttonNetworkSettings"), - - labelSoundFactory("Options_Sound","labelSoundFactory"), - listBoxSoundFactory("Options_Sound","listBoxSoundFactory"), - - labelVolumeFx("Options_Sound","labelVolumeFx"), - listBoxVolumeFx("Options_Sound","listBoxVolumeFx"), - - labelVolumeAmbient("Options_Sound","labelVolumeAmbient"), - listBoxVolumeAmbient("Options_Sound","listBoxVolumeAmbient"), - - labelVolumeMusic("Options_Sound","labelVolumeMusic"), - listBoxVolumeMusic("Options_Sound","listBoxVolumeMusic"), - - mainMessageBox("Options_Sound","mainMessageBox") -{ - try { - containerName = "Options_Sound"; - this->parentUI=parentUI; - Lang &lang= Lang::getInstance(); - Config &config= Config::getInstance(); - this->console.setOnlyChatMessagesInStoredLines(false); - - int leftLabelStart=100; - int leftColumnStart=leftLabelStart+300; - int buttonRowPos=50; - int buttonStartPos=170; - int lineOffset=30; - int tabButtonWidth=200; - int tabButtonHeight=30; - - mainMessageBox.init(lang.getString("Ok")); - mainMessageBox.setEnabled(false); - mainMessageBoxState=0; - - buttonAudioSection.init(0, 700,tabButtonWidth,tabButtonHeight+20); - buttonAudioSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonAudioSection.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonAudioSection.setText(lang.getString("Audio")); - // Video Section - buttonVideoSection.init(200, 720,tabButtonWidth,tabButtonHeight); - buttonVideoSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonVideoSection.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonVideoSection.setText(lang.getString("Video")); - //currentLine-=lineOffset; - //MiscSection - buttonMiscSection.init(400, 720,tabButtonWidth,tabButtonHeight); - buttonMiscSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonMiscSection.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonMiscSection.setText(lang.getString("Misc")); - //NetworkSettings - buttonNetworkSettings.init(600, 720,tabButtonWidth,tabButtonHeight); - buttonNetworkSettings.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonNetworkSettings.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonNetworkSettings.setText(lang.getString("Network")); - - //KeyboardSetup - buttonKeyboardSetup.init(800, 720,tabButtonWidth,tabButtonHeight); - buttonKeyboardSetup.setFont(CoreData::getInstance().getMenuFontVeryBig()); - buttonKeyboardSetup.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); - buttonKeyboardSetup.setText(lang.getString("Keyboardsetup")); - - int currentLine=650; // reset line pos - int currentLabelStart=leftLabelStart; // set to right side - int currentColumnStart=leftColumnStart; // set to right side - - //soundboxes - labelSoundFactory.init(currentLabelStart, currentLine); - labelSoundFactory.setText(lang.getString("SoundAndMusic2")); - - listBoxSoundFactory.init(currentColumnStart, currentLine, 175); - listBoxSoundFactory.pushBackItem(lang.getString("None")); - listBoxSoundFactory.pushBackItem("OpenAL"); - - string FSoundMode=config.getString("FactorySound"); - string FSoundModeT=lang.getString(config.getString("FactorySound")); - if(FSoundModeT != "???" + FSoundMode + "???") { - FSoundMode=FSoundModeT; - } - listBoxSoundFactory.setSelectedItem(FSoundMode); - currentLine-=lineOffset; - - labelVolumeFx.init(currentLabelStart, currentLine); - labelVolumeFx.setText(lang.getString("FxVolume")); - - listBoxVolumeFx.init(currentColumnStart, currentLine, 80); - currentLine-=lineOffset; - - labelVolumeAmbient.init(currentLabelStart, currentLine); - - listBoxVolumeAmbient.init(currentColumnStart, currentLine, 80); - labelVolumeAmbient.setText(lang.getString("AmbientVolume")); - currentLine-=lineOffset; - - labelVolumeMusic.init(currentLabelStart, currentLine); - - listBoxVolumeMusic.init(currentColumnStart, currentLine, 80); - labelVolumeMusic.setText(lang.getString("MusicVolume")); - //currentLine-=lineOffset; - - for(int i=0; i<=100; i+=5){ - listBoxVolumeFx.pushBackItem(intToStr(i)); - listBoxVolumeAmbient.pushBackItem(intToStr(i)); - listBoxVolumeMusic.pushBackItem(intToStr(i)); - } - listBoxVolumeFx.setSelectedItem(intToStr(config.getInt("SoundVolumeFx")/5*5)); - listBoxVolumeAmbient.setSelectedItem(intToStr(config.getInt("SoundVolumeAmbient")/5*5)); - listBoxVolumeMusic.setSelectedItem(intToStr(config.getInt("SoundVolumeMusic")/5*5)); - - //currentLine-=lineOffset/2; - - - - ////////////////////////////////////////////////////////////////// - ///////// RIGHT SIDE - ////////////////////////////////////////////////////////////////// - - //currentLine=700; // reset line pos - //currentLabelStart=rightLabelStart; // set to right side - //currentColumnStart=rightColumnStart; // set to right side - - - // buttons - buttonOk.init(buttonStartPos, buttonRowPos, 100); - buttonOk.setText(lang.getString("Save")); - buttonReturn.setText(lang.getString("Return")); - - buttonReturn.init(buttonStartPos+110, buttonRowPos, 100); - - GraphicComponent::applyAllCustomProperties(containerName); - } - catch(exception &e) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error loading options: %s\n",__FILE__,__FUNCTION__,__LINE__,e.what()); - throw megaglest_runtime_error(string("Error loading options msg: ") + e.what()); - } +MenuStateOptionsSound::MenuStateOptionsSound(Program *program, + MainMenu *mainMenu, + ProgramState **parentUI) + : MenuState(program, mainMenu, "config"), + buttonOk("Options_Sound", "buttonOk"), + buttonReturn("Options_Sound", "buttonReturn"), + + buttonKeyboardSetup("Options_Sound", "buttonKeyboardSetup"), + buttonVideoSection("Options_Sound", "buttonVideoSection"), + buttonAudioSection("Options_Sound", "buttonAudioSection"), + buttonMiscSection("Options_Sound", "buttonMiscSection"), + buttonNetworkSettings("Options_Sound", "buttonNetworkSettings"), + + labelSoundFactory("Options_Sound", "labelSoundFactory"), + listBoxSoundFactory("Options_Sound", "listBoxSoundFactory"), + + labelVolumeFx("Options_Sound", "labelVolumeFx"), + listBoxVolumeFx("Options_Sound", "listBoxVolumeFx"), + + labelVolumeAmbient("Options_Sound", "labelVolumeAmbient"), + listBoxVolumeAmbient("Options_Sound", "listBoxVolumeAmbient"), + + labelVolumeMusic("Options_Sound", "labelVolumeMusic"), + listBoxVolumeMusic("Options_Sound", "listBoxVolumeMusic"), + + mainMessageBox("Options_Sound", "mainMessageBox") { + try { + containerName = "Options_Sound"; + this->parentUI = parentUI; + Lang &lang = Lang::getInstance(); + Config &config = Config::getInstance(); + this->console.setOnlyChatMessagesInStoredLines(false); + + int leftLabelStart = 100; + int leftColumnStart = leftLabelStart + 300; + int buttonRowPos = 50; + int buttonStartPos = 170; + int lineOffset = 30; + int tabButtonWidth = 200; + int tabButtonHeight = 30; + + mainMessageBox.init(lang.getString("Ok")); + mainMessageBox.setEnabled(false); + mainMessageBoxState = 0; + + buttonAudioSection.init(0, 700, tabButtonWidth, tabButtonHeight + 20); + buttonAudioSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); + buttonAudioSection.setFont3D( + CoreData::getInstance().getMenuFontVeryBig3D()); + buttonAudioSection.setText(lang.getString("Audio")); + // Video Section + buttonVideoSection.init(200, 720, tabButtonWidth, tabButtonHeight); + buttonVideoSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); + buttonVideoSection.setFont3D( + CoreData::getInstance().getMenuFontVeryBig3D()); + buttonVideoSection.setText(lang.getString("Video")); + // currentLine-=lineOffset; + // MiscSection + buttonMiscSection.init(400, 720, tabButtonWidth, tabButtonHeight); + buttonMiscSection.setFont(CoreData::getInstance().getMenuFontVeryBig()); + buttonMiscSection.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D()); + buttonMiscSection.setText(lang.getString("Misc")); + // NetworkSettings + buttonNetworkSettings.init(600, 720, tabButtonWidth, tabButtonHeight); + buttonNetworkSettings.setFont(CoreData::getInstance().getMenuFontVeryBig()); + buttonNetworkSettings.setFont3D( + CoreData::getInstance().getMenuFontVeryBig3D()); + buttonNetworkSettings.setText(lang.getString("Network")); + + // KeyboardSetup + buttonKeyboardSetup.init(800, 720, tabButtonWidth, tabButtonHeight); + buttonKeyboardSetup.setFont(CoreData::getInstance().getMenuFontVeryBig()); + buttonKeyboardSetup.setFont3D( + CoreData::getInstance().getMenuFontVeryBig3D()); + buttonKeyboardSetup.setText(lang.getString("Keyboardsetup")); + + int currentLine = 650; // reset line pos + int currentLabelStart = leftLabelStart; // set to right side + int currentColumnStart = leftColumnStart; // set to right side + + // soundboxes + labelSoundFactory.init(currentLabelStart, currentLine); + labelSoundFactory.setText(lang.getString("SoundAndMusic2")); + + listBoxSoundFactory.init(currentColumnStart, currentLine, 175); + listBoxSoundFactory.pushBackItem(lang.getString("None")); + listBoxSoundFactory.pushBackItem("OpenAL"); + + string FSoundMode = config.getString("FactorySound"); + string FSoundModeT = lang.getString(config.getString("FactorySound")); + if (FSoundModeT != "???" + FSoundMode + "???") { + FSoundMode = FSoundModeT; + } + listBoxSoundFactory.setSelectedItem(FSoundMode); + currentLine -= lineOffset; + + labelVolumeFx.init(currentLabelStart, currentLine); + labelVolumeFx.setText(lang.getString("FxVolume")); + + listBoxVolumeFx.init(currentColumnStart, currentLine, 80); + currentLine -= lineOffset; + + labelVolumeAmbient.init(currentLabelStart, currentLine); + + listBoxVolumeAmbient.init(currentColumnStart, currentLine, 80); + labelVolumeAmbient.setText(lang.getString("AmbientVolume")); + currentLine -= lineOffset; + + labelVolumeMusic.init(currentLabelStart, currentLine); + + listBoxVolumeMusic.init(currentColumnStart, currentLine, 80); + labelVolumeMusic.setText(lang.getString("MusicVolume")); + // currentLine-=lineOffset; + + for (int i = 0; i <= 100; i += 5) { + listBoxVolumeFx.pushBackItem(intToStr(i)); + listBoxVolumeAmbient.pushBackItem(intToStr(i)); + listBoxVolumeMusic.pushBackItem(intToStr(i)); + } + listBoxVolumeFx.setSelectedItem( + intToStr(config.getInt("SoundVolumeFx") / 5 * 5)); + listBoxVolumeAmbient.setSelectedItem( + intToStr(config.getInt("SoundVolumeAmbient") / 5 * 5)); + listBoxVolumeMusic.setSelectedItem( + intToStr(config.getInt("SoundVolumeMusic") / 5 * 5)); + + // currentLine-=lineOffset/2; + + ////////////////////////////////////////////////////////////////// + ///////// RIGHT SIDE + ////////////////////////////////////////////////////////////////// + + // currentLine=700; // reset line pos + // currentLabelStart=rightLabelStart; // set to right side + // currentColumnStart=rightColumnStart; // set to right side + + // buttons + buttonOk.init(buttonStartPos, buttonRowPos, 100); + buttonOk.setText(lang.getString("Save")); + buttonReturn.setText(lang.getString("Return")); + + buttonReturn.init(buttonStartPos + 110, buttonRowPos, 100); + + GraphicComponent::applyAllCustomProperties(containerName); + } catch (exception &e) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error loading options: %s\n", + __FILE__, __FUNCTION__, __LINE__, e.what()); + throw megaglest_runtime_error(string("Error loading options msg: ") + + e.what()); + } } void MenuStateOptionsSound::reloadUI() { - Lang &lang= Lang::getInstance(); + Lang &lang = Lang::getInstance(); - mainMessageBox.init(lang.getString("Ok")); + mainMessageBox.init(lang.getString("Ok")); - buttonAudioSection.setText(lang.getString("Audio")); - buttonVideoSection.setText(lang.getString("Video")); - buttonMiscSection.setText(lang.getString("Misc")); - buttonNetworkSettings.setText(lang.getString("Network")); - labelSoundFactory.setText(lang.getString("SoundAndMusic2")); + buttonAudioSection.setText(lang.getString("Audio")); + buttonVideoSection.setText(lang.getString("Video")); + buttonMiscSection.setText(lang.getString("Misc")); + buttonNetworkSettings.setText(lang.getString("Network")); + labelSoundFactory.setText(lang.getString("SoundAndMusic2")); - std::vector listboxData; - listboxData.push_back(lang.getString("None")); - listboxData.push_back("OpenAL"); + std::vector listboxData; + listboxData.push_back(lang.getString("None")); + listboxData.push_back("OpenAL"); - listBoxSoundFactory.setItems(listboxData); + listBoxSoundFactory.setItems(listboxData); - labelVolumeFx.setText(lang.getString("FxVolume")); - labelVolumeAmbient.setText(lang.getString("AmbientVolume")); - labelVolumeMusic.setText(lang.getString("MusicVolume")); + labelVolumeFx.setText(lang.getString("FxVolume")); + labelVolumeAmbient.setText(lang.getString("AmbientVolume")); + labelVolumeMusic.setText(lang.getString("MusicVolume")); - listboxData.clear(); + listboxData.clear(); - buttonOk.setText(lang.getString("Save")); - buttonReturn.setText(lang.getString("Return")); + buttonOk.setText(lang.getString("Save")); + buttonReturn.setText(lang.getString("Return")); } -void MenuStateOptionsSound::mouseClick(int x, int y, MouseButton mouseButton){ - - //Config &config= Config::getInstance(); - CoreData &coreData= CoreData::getInstance(); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - - if(mainMessageBox.getEnabled()) { - int button= 0; - if(mainMessageBox.mouseClick(x, y, button)) { - soundRenderer.playFx(coreData.getClickSoundA()); - if(button == 0) { - if(mainMessageBoxState == 1) { - mainMessageBoxState=0; - mainMessageBox.setEnabled(false); - saveConfig(); - - Lang &lang= Lang::getInstance(); - mainMessageBox.init(lang.getString("Ok")); - mainMenu->setState(new MenuStateOptions(program, mainMenu)); - } - else { - mainMessageBox.setEnabled(false); - - Lang &lang= Lang::getInstance(); - mainMessageBox.init(lang.getString("Ok")); - } - } - else { - if(mainMessageBoxState == 1) { - mainMessageBoxState=0; - mainMessageBox.setEnabled(false); - - Lang &lang= Lang::getInstance(); - mainMessageBox.init(lang.getString("Ok")); - - - this->mainMenu->init(); - } - } - } - } - else if(buttonOk.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - saveConfig(); - //mainMenu->setState(new MenuStateOptions(program, mainMenu)); - return; +void MenuStateOptionsSound::mouseClick(int x, int y, MouseButton mouseButton) { + + // Config &config= Config::getInstance(); + CoreData &coreData = CoreData::getInstance(); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + + if (mainMessageBox.getEnabled()) { + int button = 0; + if (mainMessageBox.mouseClick(x, y, button)) { + soundRenderer.playFx(coreData.getClickSoundA()); + if (button == 0) { + if (mainMessageBoxState == 1) { + mainMessageBoxState = 0; + mainMessageBox.setEnabled(false); + saveConfig(); + + Lang &lang = Lang::getInstance(); + mainMessageBox.init(lang.getString("Ok")); + mainMenu->setState(new MenuStateOptions(program, mainMenu)); + } else { + mainMessageBox.setEnabled(false); + + Lang &lang = Lang::getInstance(); + mainMessageBox.init(lang.getString("Ok")); + } + } else { + if (mainMessageBoxState == 1) { + mainMessageBoxState = 0; + mainMessageBox.setEnabled(false); + + Lang &lang = Lang::getInstance(); + mainMessageBox.init(lang.getString("Ok")); + + this->mainMenu->init(); + } + } } - else if(buttonReturn.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - if(this->parentUI != NULL) { - *this->parentUI = NULL; - delete *this->parentUI; - } - mainMenu->setState(new MenuStateRoot(program, mainMenu)); - return; + } else if (buttonOk.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + saveConfig(); + // mainMenu->setState(new MenuStateOptions(program, mainMenu)); + return; + } else if (buttonReturn.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + if (this->parentUI != NULL) { + *this->parentUI = NULL; + delete *this->parentUI; } - else if(buttonKeyboardSetup.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - //mainMenu->setState(new MenuStateKeysetup(program, mainMenu)); // open keyboard shortcuts setup screen - //mainMenu->setState(new MenuStateOptionsGraphics(program, mainMenu)); // open keyboard shortcuts setup screen - //mainMenu->setState(new MenuStateOptionsNetwork(program, mainMenu)); // open keyboard shortcuts setup screen - mainMenu->setState(new MenuStateKeysetup(program, mainMenu)); // open keyboard shortcuts setup screen - //showMessageBox("Not implemented yet", "Keyboard setup", false); - return; - } - else if(buttonAudioSection.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - //mainMenu->setState(new MenuStateOptionsSound(program, mainMenu)); // open keyboard shortcuts setup screen - return; - } - else if(buttonNetworkSettings.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - mainMenu->setState(new MenuStateOptionsNetwork(program, mainMenu)); // open keyboard shortcuts setup screen - return; - } - else if(buttonMiscSection.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - mainMenu->setState(new MenuStateOptions(program, mainMenu)); // open keyboard shortcuts setup screen - return; - } - else if(buttonVideoSection.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - mainMenu->setState(new MenuStateOptionsGraphics(program, mainMenu)); // open keyboard shortcuts setup screen - return; - } - else - { - listBoxSoundFactory.mouseClick(x, y); - listBoxVolumeFx.mouseClick(x, y); - listBoxVolumeAmbient.mouseClick(x, y); - listBoxVolumeMusic.mouseClick(x, y); - } + mainMenu->setState(new MenuStateRoot(program, mainMenu)); + return; + } else if (buttonKeyboardSetup.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + // mainMenu->setState(new MenuStateKeysetup(program, mainMenu)); // open + // keyboard shortcuts setup screen mainMenu->setState(new + // MenuStateOptionsGraphics(program, mainMenu)); // open keyboard shortcuts + // setup screen mainMenu->setState(new MenuStateOptionsNetwork(program, + // mainMenu)); // open keyboard shortcuts setup screen + mainMenu->setState(new MenuStateKeysetup( + program, mainMenu)); // open keyboard shortcuts setup screen + // showMessageBox("Not implemented yet", "Keyboard setup", false); + return; + } else if (buttonAudioSection.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + // mainMenu->setState(new MenuStateOptionsSound(program, mainMenu)); // open + // keyboard shortcuts setup screen + return; + } else if (buttonNetworkSettings.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + mainMenu->setState(new MenuStateOptionsNetwork( + program, mainMenu)); // open keyboard shortcuts setup screen + return; + } else if (buttonMiscSection.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + mainMenu->setState(new MenuStateOptions( + program, mainMenu)); // open keyboard shortcuts setup screen + return; + } else if (buttonVideoSection.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + mainMenu->setState(new MenuStateOptionsGraphics( + program, mainMenu)); // open keyboard shortcuts setup screen + return; + } else { + listBoxSoundFactory.mouseClick(x, y); + listBoxVolumeFx.mouseClick(x, y); + listBoxVolumeAmbient.mouseClick(x, y); + listBoxVolumeMusic.mouseClick(x, y); + } } -void MenuStateOptionsSound::mouseMove(int x, int y, const MouseState *ms){ - if (mainMessageBox.getEnabled()) { - mainMessageBox.mouseMove(x, y); - } - buttonOk.mouseMove(x, y); - buttonReturn.mouseMove(x, y); - buttonKeyboardSetup.mouseMove(x, y); - buttonAudioSection.mouseMove(x, y); - buttonNetworkSettings.mouseMove(x, y); - buttonMiscSection.mouseMove(x, y); - buttonVideoSection.mouseMove(x, y); - - listBoxSoundFactory.mouseMove(x, y); - listBoxVolumeFx.mouseMove(x, y); - listBoxVolumeAmbient.mouseMove(x, y); - listBoxVolumeMusic.mouseMove(x, y); +void MenuStateOptionsSound::mouseMove(int x, int y, const MouseState *ms) { + if (mainMessageBox.getEnabled()) { + mainMessageBox.mouseMove(x, y); + } + buttonOk.mouseMove(x, y); + buttonReturn.mouseMove(x, y); + buttonKeyboardSetup.mouseMove(x, y); + buttonAudioSection.mouseMove(x, y); + buttonNetworkSettings.mouseMove(x, y); + buttonMiscSection.mouseMove(x, y); + buttonVideoSection.mouseMove(x, y); + + listBoxSoundFactory.mouseMove(x, y); + listBoxVolumeFx.mouseMove(x, y); + listBoxVolumeAmbient.mouseMove(x, y); + listBoxVolumeMusic.mouseMove(x, y); } -//bool MenuStateOptionsSound::isInSpecialKeyCaptureEvent() { +// bool MenuStateOptionsSound::isInSpecialKeyCaptureEvent() { // return (activeInputLabel != NULL); -//} +// } // -//void MenuStateOptionsSound::keyDown(SDL_KeyboardEvent key) { +// void MenuStateOptionsSound::keyDown(SDL_KeyboardEvent key) { // if(activeInputLabel != NULL) { // keyDownEditLabel(key, &activeInputLabel); // } -//} +// } void MenuStateOptionsSound::keyPress(SDL_KeyboardEvent c) { -// if(activeInputLabel != NULL) { -// //printf("[%d]\n",c); fflush(stdout); -// if( &labelPlayerName == activeInputLabel || -// &labelTransifexUser == activeInputLabel || -// &labelTransifexPwd == activeInputLabel || -// &labelTransifexI18N == activeInputLabel) { -// textInputEditLabel(c, &activeInputLabel); -// } -// } -// else { - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - if(isKeyPressed(configKeys.getSDLKey("SaveGUILayout"),c) == true) { - GraphicComponent::saveAllCustomProperties(containerName); - //Lang &lang= Lang::getInstance(); - //console.addLine(lang.getString("GUILayoutSaved") + " [" + (saved ? lang.getString("Yes") : lang.getString("No"))+ "]"); - } -// } + // if(activeInputLabel != NULL) { + // //printf("[%d]\n",c); fflush(stdout); + // if( &labelPlayerName == activeInputLabel || + // &labelTransifexUser == activeInputLabel || + // &labelTransifexPwd == activeInputLabel || + // &labelTransifexI18N == activeInputLabel) { + // textInputEditLabel(c, &activeInputLabel); + // } + // } + // else { + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + if (isKeyPressed(configKeys.getSDLKey("SaveGUILayout"), c) == true) { + GraphicComponent::saveAllCustomProperties(containerName); + // Lang &lang= Lang::getInstance(); + // console.addLine(lang.getString("GUILayoutSaved") + " [" + (saved ? + // lang.getString("Yes") : lang.getString("No"))+ "]"); + } + // } } -void MenuStateOptionsSound::render(){ - Renderer &renderer= Renderer::getInstance(); - - if(mainMessageBox.getEnabled()){ - renderer.renderMessageBox(&mainMessageBox); - } - else - { - renderer.renderButton(&buttonOk); - renderer.renderButton(&buttonReturn); - renderer.renderButton(&buttonKeyboardSetup); - renderer.renderButton(&buttonVideoSection); - renderer.renderButton(&buttonAudioSection); - renderer.renderButton(&buttonMiscSection); - renderer.renderButton(&buttonNetworkSettings); - renderer.renderListBox(&listBoxSoundFactory); - renderer.renderLabel(&labelSoundFactory); - - - renderer.renderListBox(&listBoxVolumeFx); - renderer.renderLabel(&labelVolumeFx); - renderer.renderListBox(&listBoxVolumeAmbient); - renderer.renderLabel(&labelVolumeAmbient); - renderer.renderListBox(&listBoxVolumeMusic); - renderer.renderLabel(&labelVolumeMusic); - - - - } - - renderer.renderConsole(&console); - if(program != NULL) program->renderProgramMsgBox(); +void MenuStateOptionsSound::render() { + Renderer &renderer = Renderer::getInstance(); + + if (mainMessageBox.getEnabled()) { + renderer.renderMessageBox(&mainMessageBox); + } else { + renderer.renderButton(&buttonOk); + renderer.renderButton(&buttonReturn); + renderer.renderButton(&buttonKeyboardSetup); + renderer.renderButton(&buttonVideoSection); + renderer.renderButton(&buttonAudioSection); + renderer.renderButton(&buttonMiscSection); + renderer.renderButton(&buttonNetworkSettings); + renderer.renderListBox(&listBoxSoundFactory); + renderer.renderLabel(&labelSoundFactory); + + renderer.renderListBox(&listBoxVolumeFx); + renderer.renderLabel(&labelVolumeFx); + renderer.renderListBox(&listBoxVolumeAmbient); + renderer.renderLabel(&labelVolumeAmbient); + renderer.renderListBox(&listBoxVolumeMusic); + renderer.renderLabel(&labelVolumeMusic); + } + + renderer.renderConsole(&console); + if (program != NULL) + program->renderProgramMsgBox(); } -void MenuStateOptionsSound::saveConfig(){ - Config &config= Config::getInstance(); - Lang &lang= Lang::getInstance(); - setActiveInputLable(NULL); - - int FSoundIndex=listBoxSoundFactory.getSelectedItemIndex(); - string FSoundMode; - switch (FSoundIndex) { - case 0: - FSoundMode = "None"; - break; - case 1: - FSoundMode = "OpenAL"; - break; - } - config.setString("FactorySound",FSoundMode); - - config.setString("SoundVolumeFx", listBoxVolumeFx.getSelectedItem()); - config.setString("SoundVolumeAmbient", listBoxVolumeAmbient.getSelectedItem()); - CoreData::getInstance().getMenuMusic()->setVolume(strToInt(listBoxVolumeMusic.getSelectedItem())/100.f); - config.setString("SoundVolumeMusic", listBoxVolumeMusic.getSelectedItem()); - - config.save(); - - if(config.getBool("DisableLuaSandbox","false") == true) { - LuaScript::setDisableSandbox(true); - } - - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - soundRenderer.stopAllSounds(); - program->stopSoundSystem(); - soundRenderer.init(program->getWindow()); - soundRenderer.loadConfig(); - soundRenderer.setMusicVolume(CoreData::getInstance().getMenuMusic()); - program->startSoundSystem(); - - if(CoreData::getInstance().hasMainMenuVideoFilename() == false) { - soundRenderer.playMusic(CoreData::getInstance().getMenuMusic()); - } - - Renderer::getInstance().loadConfig(); - console.addLine(lang.getString("SettingsSaved")); +void MenuStateOptionsSound::saveConfig() { + Config &config = Config::getInstance(); + Lang &lang = Lang::getInstance(); + setActiveInputLable(NULL); + + int FSoundIndex = listBoxSoundFactory.getSelectedItemIndex(); + string FSoundMode; + switch (FSoundIndex) { + case 0: + FSoundMode = "None"; + break; + case 1: + FSoundMode = "OpenAL"; + break; + } + config.setString("FactorySound", FSoundMode); + + config.setString("SoundVolumeFx", listBoxVolumeFx.getSelectedItem()); + config.setString("SoundVolumeAmbient", + listBoxVolumeAmbient.getSelectedItem()); + CoreData::getInstance().getMenuMusic()->setVolume( + strToInt(listBoxVolumeMusic.getSelectedItem()) / 100.f); + config.setString("SoundVolumeMusic", listBoxVolumeMusic.getSelectedItem()); + + config.save(); + + if (config.getBool("DisableLuaSandbox", "false") == true) { + LuaScript::setDisableSandbox(true); + } + + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + soundRenderer.stopAllSounds(); + program->stopSoundSystem(); + soundRenderer.init(program->getWindow()); + soundRenderer.loadConfig(); + soundRenderer.setMusicVolume(CoreData::getInstance().getMenuMusic()); + program->startSoundSystem(); + + if (CoreData::getInstance().hasMainMenuVideoFilename() == false) { + soundRenderer.playMusic(CoreData::getInstance().getMenuMusic()); + } + + Renderer::getInstance().loadConfig(); + console.addLine(lang.getString("SettingsSaved")); } -void MenuStateOptionsSound::setActiveInputLable(GraphicLabel *newLable) { -} +void MenuStateOptionsSound::setActiveInputLable(GraphicLabel *newLable) {} -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/menu/menu_state_options_sound.h b/source/glest_game/menu/menu_state_options_sound.h index 05c2f3b95..5a3c759b4 100644 --- a/source/glest_game/menu/menu_state_options_sound.h +++ b/source/glest_game/menu/menu_state_options_sound.h @@ -12,64 +12,65 @@ #ifndef _GLEST_GAME_MENUSTATEOPTIONS_SOUND_H_ #define _GLEST_GAME_MENUSTATEOPTIONS_SOUND_H_ -#include "main_menu.h" #include "leak_dumper.h" +#include "main_menu.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // =============================== // class MenuStateOptionsSound // =============================== -class MenuStateOptionsSound: public MenuState{ +class MenuStateOptionsSound : public MenuState { private: + GraphicButton buttonOk; + GraphicButton buttonReturn; - GraphicButton buttonOk; - GraphicButton buttonReturn; + GraphicButton buttonKeyboardSetup; // configure the keyboard + GraphicButton buttonVideoSection; + GraphicButton buttonAudioSection; + GraphicButton buttonMiscSection; + GraphicButton buttonNetworkSettings; - GraphicButton buttonKeyboardSetup; // configure the keyboard - GraphicButton buttonVideoSection; - GraphicButton buttonAudioSection; - GraphicButton buttonMiscSection; - GraphicButton buttonNetworkSettings; + GraphicLabel labelSoundFactory; + GraphicListBox listBoxSoundFactory; - GraphicLabel labelSoundFactory; - GraphicListBox listBoxSoundFactory; + GraphicLabel labelVolumeFx; + GraphicListBox listBoxVolumeFx; - GraphicLabel labelVolumeFx; - GraphicListBox listBoxVolumeFx; + GraphicLabel labelVolumeAmbient; + GraphicListBox listBoxVolumeAmbient; - GraphicLabel labelVolumeAmbient; - GraphicListBox listBoxVolumeAmbient; + GraphicLabel labelVolumeMusic; + GraphicListBox listBoxVolumeMusic; - GraphicLabel labelVolumeMusic; - GraphicListBox listBoxVolumeMusic; + GraphicMessageBox mainMessageBox; + int mainMessageBoxState; - GraphicMessageBox mainMessageBox; - int mainMessageBoxState; - - ProgramState **parentUI; + ProgramState **parentUI; public: - MenuStateOptionsSound(Program *program, MainMenu *mainMenu, ProgramState **parentUI=NULL); - - void mouseClick(int x, int y, MouseButton mouseButton); - void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; - void mouseMove(int x, int y, const MouseState *mouseState); - void render(); - //virtual void keyDown(SDL_KeyboardEvent key); - virtual void keyPress(SDL_KeyboardEvent c); - //virtual bool isInSpecialKeyCaptureEvent(); + MenuStateOptionsSound(Program *program, MainMenu *mainMenu, + ProgramState **parentUI = NULL); - virtual void reloadUI(); + void mouseClick(int x, int y, MouseButton mouseButton); + void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; + void mouseMove(int x, int y, const MouseState *mouseState); + void render(); + // virtual void keyDown(SDL_KeyboardEvent key); + virtual void keyPress(SDL_KeyboardEvent c); + // virtual bool isInSpecialKeyCaptureEvent(); + virtual void reloadUI(); private: - void saveConfig(); - void setActiveInputLable(GraphicLabel* newLable); - //void showMessageBox(const string &text, const string &header, bool toggle); + void saveConfig(); + void setActiveInputLable(GraphicLabel *newLable); + // void showMessageBox(const string &text, const string &header, bool toggle); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/menu/menu_state_root.cpp b/source/glest_game/menu/menu_state_root.cpp index d711ec846..aab611a0d 100644 --- a/source/glest_game/menu/menu_state_root.cpp +++ b/source/glest_game/menu/menu_state_root.cpp @@ -11,27 +11,28 @@ #include "menu_state_root.h" -#include "renderer.h" -#include "sound_renderer.h" -#include "core_data.h" +#include "auto_test.h" +#include "cache_manager.h" #include "config.h" -#include "menu_state_new_game.h" -#include "menu_state_load_game.h" -#include "menu_state_options.h" +#include "core_data.h" #include "menu_state_about.h" +#include "menu_state_load_game.h" #include "menu_state_mods.h" +#include "menu_state_new_game.h" +#include "menu_state_options.h" #include "metrics.h" #include "network_manager.h" #include "network_message.h" +#include "renderer.h" #include "socket.h" -#include "auto_test.h" -#include "cache_manager.h" +#include "sound_renderer.h" #include "steam.h" #include #include "leak_dumper.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class MenuStateRoot @@ -39,783 +40,921 @@ namespace Glest{ namespace Game{ bool MenuStateRoot::gameUpdateChecked = false; -MenuStateRoot::MenuStateRoot(Program *program, MainMenu *mainMenu) : - MenuState(program, mainMenu, "root"), updatesHttpServerThread(NULL), - buttonNewGame("MainMenu","buttonNewGame"), - buttonLoadGame("MainMenu","buttonLoadGame"), - buttonMods("MainMenu","buttonMods"), - buttonOptions("MainMenu","buttonOptions"), - buttonAbout("MainMenu","buttonAbout"), - buttonExit("MainMenu","buttonExit"), - labelVersion("MainMenu","labelVersion"), - labelGreeting("MainMenu","labelGreeting"), +MenuStateRoot::MenuStateRoot(Program *program, MainMenu *mainMenu) + : MenuState(program, mainMenu, "root"), updatesHttpServerThread(NULL), + buttonNewGame("MainMenu", "buttonNewGame"), + buttonLoadGame("MainMenu", "buttonLoadGame"), + buttonMods("MainMenu", "buttonMods"), + buttonOptions("MainMenu", "buttonOptions"), + buttonAbout("MainMenu", "buttonAbout"), + buttonExit("MainMenu", "buttonExit"), + labelVersion("MainMenu", "labelVersion"), + labelGreeting("MainMenu", "labelGreeting"), - mainMessageBox("MainMenu","mainMessageBox"), - errorMessageBox("MainMenu","errorMessageBox"), - ftpMessageBox("MainMenu","ftpMessageBox"), + mainMessageBox("MainMenu", "mainMessageBox"), + errorMessageBox("MainMenu", "errorMessageBox"), + ftpMessageBox("MainMenu", "ftpMessageBox"), - popupMenu("MainMenu","popupMenu") + popupMenu("MainMenu", "popupMenu") { - containerName = "MainMenu"; - - ftpClientThread = NULL; - lastDownloadProgress = 0; - - Lang &lang= Lang::getInstance(); - int yPos=440; - int buttonWidth = 200; - int buttonXPosition = (1000 - buttonWidth) / 2; - - - //labelVersion.registerGraphicComponent(containerName,"labelVersion"); - if(EndsWith(glestVersionString, "-dev") == false){ - labelVersion.init(525, yPos); - labelVersion.setText(glestVersionString); - } - else { - labelVersion.init(buttonXPosition, yPos); - //labelVersion.setText(glestVersionString + " [" + getCompileDateTime() + ", " + getGITRevisionString() + "]"); - labelVersion.setText(glestVersionString + " [" + getGITRevisionString() + "]"); - } - - labelGreeting.init(labelVersion.getX(), labelVersion.getY()-16); - labelGreeting.setText(""); - - Steam *steamInstance = CacheManager::getCachedItem< Steam *>(GameConstants::steamCacheInstanceKey); - if(steamInstance != NULL) { - string steamPlayerName = steamInstance->userName(); - labelGreeting.setText("Welcome Steam Player: " + steamPlayerName); - } - - yPos-=55; - //buttonNewGame.registerGraphicComponent(containerName,"buttonNewGame"); - buttonNewGame.init(buttonXPosition, yPos, buttonWidth); - yPos-=40; - //buttonLoadGame.registerGraphicComponent(containerName,"buttonLoadGame"); - buttonLoadGame.init(buttonXPosition, yPos, buttonWidth); - yPos-=40; - //buttonMods.registerGraphicComponent(containerName,"buttonMods"); - buttonMods.init(buttonXPosition, yPos, buttonWidth); - yPos-=40; - //buttonOptions.registerGraphicComponent(containerName,"buttonOptions"); - buttonOptions.init(buttonXPosition, yPos, buttonWidth); - yPos-=40; - //buttonAbout.registerGraphicComponent(containerName,"buttonAbout"); - buttonAbout.init(buttonXPosition, yPos , buttonWidth); - yPos-=40; - //buttonExit.registerGraphicComponent(containerName,"buttonExit"); - buttonExit.init(buttonXPosition, yPos, buttonWidth); - - buttonNewGame.setText(lang.getString("NewGame")); - buttonLoadGame.setText(lang.getString("LoadGame")); - buttonMods.setText(lang.getString("Mods")); - buttonOptions.setText(lang.getString("Options")); - buttonAbout.setText(lang.getString("About")); - buttonExit.setText(lang.getString("Exit")); - - //mesage box - //mainMessageBox.registerGraphicComponent(containerName,"mainMessageBox"); - mainMessageBox.init(lang.getString("Yes"), lang.getString("No")); - mainMessageBox.setEnabled(false); - - //errorMessageBox.registerGraphicComponent(containerName,"errorMessageBox"); - errorMessageBox.init(lang.getString("Ok")); - errorMessageBox.setEnabled(false); - - //ftpMessageBox.registerGraphicComponent(containerName,"ftpMessageBox"); - ftpMessageBox.init(lang.getString("Yes"), lang.getString("No")); - ftpMessageBox.setEnabled(false); - - //PopupMenu popupMenu; - std::vector menuItems; - menuItems.push_back("1"); - menuItems.push_back("2"); - menuItems.push_back("3"); - //popupMenu.registerGraphicComponentOnlyFontCallbacks(containerName, "popupMenu"); - popupMenu.setW(100); - popupMenu.setH(100); - popupMenu.init("Test Menu",menuItems); - popupMenu.setEnabled(false); - popupMenu.setVisible(false); - - GraphicComponent::applyAllCustomProperties(containerName); + containerName = "MainMenu"; + + ftpClientThread = NULL; + lastDownloadProgress = 0; + + Lang &lang = Lang::getInstance(); + int yPos = 440; + int buttonWidth = 200; + int buttonXPosition = (1000 - buttonWidth) / 2; + + // labelVersion.registerGraphicComponent(containerName,"labelVersion"); + if (EndsWith(glestVersionString, "-dev") == false) { + labelVersion.init(525, yPos); + labelVersion.setText(glestVersionString); + } else { + labelVersion.init(buttonXPosition, yPos); + // labelVersion.setText(glestVersionString + " [" + getCompileDateTime() + + // ", " + getGITRevisionString() + "]"); + labelVersion.setText(glestVersionString + " [" + getGITRevisionString() + + "]"); + } + + labelGreeting.init(labelVersion.getX(), labelVersion.getY() - 16); + labelGreeting.setText(""); + + Steam *steamInstance = CacheManager::getCachedItem( + GameConstants::steamCacheInstanceKey); + if (steamInstance != NULL) { + string steamPlayerName = steamInstance->userName(); + labelGreeting.setText("Welcome Steam Player: " + steamPlayerName); + } + + yPos -= 55; + // buttonNewGame.registerGraphicComponent(containerName,"buttonNewGame"); + buttonNewGame.init(buttonXPosition, yPos, buttonWidth); + yPos -= 40; + // buttonLoadGame.registerGraphicComponent(containerName,"buttonLoadGame"); + buttonLoadGame.init(buttonXPosition, yPos, buttonWidth); + yPos -= 40; + // buttonMods.registerGraphicComponent(containerName,"buttonMods"); + buttonMods.init(buttonXPosition, yPos, buttonWidth); + yPos -= 40; + // buttonOptions.registerGraphicComponent(containerName,"buttonOptions"); + buttonOptions.init(buttonXPosition, yPos, buttonWidth); + yPos -= 40; + // buttonAbout.registerGraphicComponent(containerName,"buttonAbout"); + buttonAbout.init(buttonXPosition, yPos, buttonWidth); + yPos -= 40; + // buttonExit.registerGraphicComponent(containerName,"buttonExit"); + buttonExit.init(buttonXPosition, yPos, buttonWidth); + + buttonNewGame.setText(lang.getString("NewGame")); + buttonLoadGame.setText(lang.getString("LoadGame")); + buttonMods.setText(lang.getString("Mods")); + buttonOptions.setText(lang.getString("Options")); + buttonAbout.setText(lang.getString("About")); + buttonExit.setText(lang.getString("Exit")); + + // mesage box + // mainMessageBox.registerGraphicComponent(containerName,"mainMessageBox"); + mainMessageBox.init(lang.getString("Yes"), lang.getString("No")); + mainMessageBox.setEnabled(false); + + // errorMessageBox.registerGraphicComponent(containerName,"errorMessageBox"); + errorMessageBox.init(lang.getString("Ok")); + errorMessageBox.setEnabled(false); + + // ftpMessageBox.registerGraphicComponent(containerName,"ftpMessageBox"); + ftpMessageBox.init(lang.getString("Yes"), lang.getString("No")); + ftpMessageBox.setEnabled(false); + + // PopupMenu popupMenu; + std::vector menuItems; + menuItems.push_back("1"); + menuItems.push_back("2"); + menuItems.push_back("3"); + // popupMenu.registerGraphicComponentOnlyFontCallbacks(containerName, + // "popupMenu"); + popupMenu.setW(100); + popupMenu.setH(100); + popupMenu.init("Test Menu", menuItems); + popupMenu.setEnabled(false); + popupMenu.setVisible(false); + + GraphicComponent::applyAllCustomProperties(containerName); } MenuStateRoot::~MenuStateRoot() { - if(updatesHttpServerThread != NULL) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - updatesHttpServerThread->setSimpleTaskInterfaceValid(false); - updatesHttpServerThread->signalQuit(); - updatesHttpServerThread->setThreadOwnerValid(false); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - if( updatesHttpServerThread->canShutdown(true) == true && - updatesHttpServerThread->shutdownAndWait() == true) { - delete updatesHttpServerThread; - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - updatesHttpServerThread = NULL; - } - - if(ftpClientThread != NULL) { - ftpClientThread->setCallBackObject(NULL); - ftpClientThread->signalQuit(); - sleep(0); - if(ftpClientThread->canShutdown(true) == true && - ftpClientThread->shutdownAndWait() == true) { - delete ftpClientThread; - } - else { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] Error cannot shutdown ftpClientThread\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s",szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - - //publishToMasterserverThread->cleanup(); - } - ftpClientThread = NULL; - -// ftpClientThread->signalQuit(); -// ftpClientThread->setCallBackObject(NULL); -// if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); -// if( ftpClientThread->shutdownAndWait() == true) { -// if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); -// delete ftpClientThread; -// } -// ftpClientThread = NULL; -// if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - } - + if (updatesHttpServerThread != NULL) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + updatesHttpServerThread->setSimpleTaskInterfaceValid(false); + updatesHttpServerThread->signalQuit(); + updatesHttpServerThread->setThreadOwnerValid(false); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, + __LINE__); + if (updatesHttpServerThread->canShutdown(true) == true && + updatesHttpServerThread->shutdownAndWait() == true) { + delete updatesHttpServerThread; + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + updatesHttpServerThread = NULL; + } + + if (ftpClientThread != NULL) { + ftpClientThread->setCallBackObject(NULL); + ftpClientThread->signalQuit(); + sleep(0); + if (ftpClientThread->canShutdown(true) == true && + ftpClientThread->shutdownAndWait() == true) { + delete ftpClientThread; + } else { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s %d] Error cannot shutdown ftpClientThread\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + // SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("%s", szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + // publishToMasterserverThread->cleanup(); + } + ftpClientThread = NULL; + + // ftpClientThread->signalQuit(); + // ftpClientThread->setCallBackObject(NULL); + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line + //%d]\n",__FILE__,__FUNCTION__,__LINE__); if( + // ftpClientThread->shutdownAndWait() == true) { + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line + //%d]\n",__FILE__,__FUNCTION__,__LINE__); + // delete ftpClientThread; + // } + // ftpClientThread = NULL; + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line + //%d]\n",__FILE__,__FUNCTION__,__LINE__); + } } void MenuStateRoot::reloadUI() { - Lang &lang= Lang::getInstance(); + Lang &lang = Lang::getInstance(); - console.resetFonts(); + console.resetFonts(); - if(EndsWith(glestVersionString, "-dev") == false){ - labelVersion.setText(glestVersionString); - } - else { - //labelVersion.setText(glestVersionString + " [" + getCompileDateTime() + ", " + getGITRevisionString() + "]"); - labelVersion.setText(glestVersionString + " [" + getGITRevisionString() + "]"); - } + if (EndsWith(glestVersionString, "-dev") == false) { + labelVersion.setText(glestVersionString); + } else { + // labelVersion.setText(glestVersionString + " [" + getCompileDateTime() + + // ", " + getGITRevisionString() + "]"); + labelVersion.setText(glestVersionString + " [" + getGITRevisionString() + + "]"); + } - buttonNewGame.setText(lang.getString("NewGame")); - buttonLoadGame.setText(lang.getString("LoadGame")); - buttonMods.setText(lang.getString("Mods")); - buttonOptions.setText(lang.getString("Options")); - buttonAbout.setText(lang.getString("About")); - buttonExit.setText(lang.getString("Exit")); + buttonNewGame.setText(lang.getString("NewGame")); + buttonLoadGame.setText(lang.getString("LoadGame")); + buttonMods.setText(lang.getString("Mods")); + buttonOptions.setText(lang.getString("Options")); + buttonAbout.setText(lang.getString("About")); + buttonExit.setText(lang.getString("Exit")); - mainMessageBox.init(lang.getString("Yes"), lang.getString("No")); - errorMessageBox.init(lang.getString("Ok")); - ftpMessageBox.init(lang.getString("Yes"), lang.getString("No")); + mainMessageBox.init(lang.getString("Yes"), lang.getString("No")); + errorMessageBox.init(lang.getString("Ok")); + ftpMessageBox.init(lang.getString("Yes"), lang.getString("No")); - console.resetFonts(); + console.resetFonts(); - GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); + GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); } -void MenuStateRoot::mouseClick(int x, int y, MouseButton mouseButton){ - try { - CoreData &coreData= CoreData::getInstance(); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - - if(popupMenu.mouseClick(x, y)) { - //std::pair result = popupMenu.mouseClickedMenuItem(x, y); - popupMenu.mouseClickedMenuItem(x, y); - - //printf("In popup callback menuItemSelected [%s] menuIndexSelected = %d\n",result.second.c_str(),result.first); - } - //exit message box, has to be the last thing to do in this function - else if(mainMessageBox.getEnabled()){ - int button= 0; - if(mainMessageBox.mouseClick(x, y, button)) { - if(button==0) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - soundRenderer.playFx(coreData.getClickSoundA()); - program->exit(); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - //close message box - mainMessageBox.setEnabled(false); - } - } - } - //exit message box, has to be the last thing to do in this function - else if(errorMessageBox.getEnabled()){ - int button= 0; - if(mainMessageBox.mouseClick(x, y, button)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - //close message box - errorMessageBox.setEnabled(false); - } - } - - else if(ftpMessageBox.getEnabled()) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - int button= 0; - if(ftpMessageBox.mouseClick(x, y, button)) { - ftpMessageBox.setEnabled(false); - if(button == 0) { - startFTPClientIfRequired(); - - lastDownloadProgress = 0; - printf("Adding ftpFileName [%s] ftpFileURL [%s]\n",ftpFileName.c_str(),ftpFileURL.c_str()); - if(ftpClientThread != NULL) ftpClientThread->addTempFileToRequests(ftpFileName,ftpFileURL); - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),mutexOwnerId); - if(ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); - fileFTPProgressList[ftpFileName] = pair(0,""); - safeMutexFTPProgress.ReleaseLock(); - } - } - } - else if(mainMessageBox.getEnabled() == false && buttonNewGame.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundB()); - mainMenu->setState(new MenuStateNewGame(program, mainMenu)); - } - else if(mainMessageBox.getEnabled() == false && buttonLoadGame.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundB()); - mainMenu->setState(new MenuStateLoadGame(program, mainMenu)); - } - else if(mainMessageBox.getEnabled() == false && buttonMods.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundB()); - mainMenu->setState(new MenuStateMods(program, mainMenu)); - } - else if(mainMessageBox.getEnabled() == false && buttonOptions.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundB()); - mainMenu->setState(new MenuStateOptions(program, mainMenu)); - } - else if(mainMessageBox.getEnabled() == false && buttonAbout.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundB()); - mainMenu->setState(new MenuStateAbout(program, mainMenu)); - } - else if(buttonExit.mouseClick(x, y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - program->exit(); - } - } - catch(exception &e) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d]\nError in menu event:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - showErrorMessageBox(szBuf, "", true); - } -} +void MenuStateRoot::mouseClick(int x, int y, MouseButton mouseButton) { + try { + CoreData &coreData = CoreData::getInstance(); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); -void MenuStateRoot::startFTPClientIfRequired() { - if(ftpClientThread == NULL) { - // Setup File Transfer thread - Config &config = Config::getInstance(); - - vector tilesetFiles; - vector tilesetFilesUserData; - - vector techTreeFiles; - vector techTreeFilesUserData; - - - findDirs(config.getPathListForType(ptTilesets), tilesetFiles); - findDirs(config.getPathListForType(ptTechs), techTreeFiles); - - vector mapPathList = config.getPathListForType(ptMaps); - std::pair mapsPath; - if(mapPathList.empty() == false) { - mapsPath.first = mapPathList[0]; - } - if(mapPathList.size() > 1) { - mapsPath.second = mapPathList[1]; - } - std::pair tilesetsPath; - vector tilesetsList = Config::getInstance().getPathListForType(ptTilesets); - if(tilesetsList.empty() == false) { - tilesetsPath.first = tilesetsList[0]; - if(tilesetsList.size() > 1) { - tilesetsPath.second = tilesetsList[1]; - } - } - - std::pair techtreesPath; - vector techtreesList = Config::getInstance().getPathListForType(ptTechs); - if(techtreesList.empty() == false) { - techtreesPath.first = techtreesList[0]; - if(techtreesList.size() > 1) { - techtreesPath.second = techtreesList[1]; - } - } - - std::pair scenariosPath; - vector scenariosList = Config::getInstance().getPathListForType(ptScenarios); - if(scenariosList.empty() == false) { - scenariosPath.first = scenariosList[0]; - if(scenariosList.size() > 1) { - scenariosPath.second = scenariosList[1]; - } - } - - string fileArchiveExtension = config.getString("FileArchiveExtension",""); - string fileArchiveExtractCommand = config.getString("FileArchiveExtractCommand",""); - string fileArchiveExtractCommandParameters = config.getString("FileArchiveExtractCommandParameters",""); - int32 fileArchiveExtractCommandSuccessResult = config.getInt("FileArchiveExtractCommandSuccessResult","0"); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - console.setOnlyChatMessagesInStoredLines(false); - - // Get path to temp files - string tempFilePath = "temp/"; - if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - tempFilePath = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + tempFilePath; - } - else { - string userData = config.getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - tempFilePath = userData + tempFilePath; - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Temp files path [%s]\n",tempFilePath.c_str()); - - ftpClientThread = new FTPClientThread(-1,"", - mapsPath,tilesetsPath,techtreesPath,scenariosPath, - this,fileArchiveExtension,fileArchiveExtractCommand, - fileArchiveExtractCommandParameters, - fileArchiveExtractCommandSuccessResult, - tempFilePath); - ftpClientThread->start(); - - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - } -} + if (popupMenu.mouseClick(x, y)) { + // std::pair result = popupMenu.mouseClickedMenuItem(x, y); + popupMenu.mouseClickedMenuItem(x, y); -void MenuStateRoot::FTPClient_CallbackEvent(string itemName, - FTP_Client_CallbackType type, pair result,void *userdata) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - Lang &lang= Lang::getInstance(); - if(type == ftp_cct_DownloadProgress) { - FTPClientCallbackInterface::FtpProgressStats *stats = (FTPClientCallbackInterface::FtpProgressStats *)userdata; - if(stats != NULL) { - int fileProgress = 0; - if(stats->download_total > 0) { - fileProgress = ((stats->download_now / stats->download_total) * 100.0); - } - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Got FTP Callback for [%s] current file [%s] fileProgress = %d [now = %f, total = %f]\n",itemName.c_str(),stats->currentFilename.c_str(), fileProgress,stats->download_now,stats->download_total); - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),mutexOwnerId); - if(ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); - pair lastProgress = fileFTPProgressList[itemName]; - fileFTPProgressList[itemName] = pair(fileProgress,stats->currentFilename); - safeMutexFTPProgress.ReleaseLock(); - - if(itemName != "" && (lastDownloadProgress < fileProgress && fileProgress % 25 == 0)) { - lastDownloadProgress = fileProgress; - - char szBuf[8096]=""; - snprintf(szBuf,8096,"Downloaded %d%% of file: %s",fileProgress,itemName.c_str()); - console.addLine(szBuf); - } + // printf("In popup callback menuItemSelected [%s] menuIndexSelected = + // %d\n",result.second.c_str(),result.first); + } + // exit message box, has to be the last thing to do in this function + else if (mainMessageBox.getEnabled()) { + int button = 0; + if (mainMessageBox.mouseClick(x, y, button)) { + if (button == 0) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + soundRenderer.playFx(coreData.getClickSoundA()); + program->exit(); + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + // close message box + mainMessageBox.setEnabled(false); } + } } - else if(type == ftp_cct_ExtractProgress) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Got FTP extract Callback for [%s] result = %d [%s]\n",itemName.c_str(),result.first,result.second.c_str()); - printf("Got FTP extract Callback for [%s] result = %d [%s]\n",itemName.c_str(),result.first,result.second.c_str()); - - if(userdata == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,lang.getString("DataMissingExtractDownloadMod").c_str(),itemName.c_str()); - //printf("%s\n",szBuf); - console.addLine(szBuf,true); - } - else { - char *szBuf = (char *)userdata; - //printf("%s\n",szBuf); - console.addLine(szBuf); - } + // exit message box, has to be the last thing to do in this function + else if (errorMessageBox.getEnabled()) { + int button = 0; + if (mainMessageBox.mouseClick(x, y, button)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + // close message box + errorMessageBox.setEnabled(false); + } } - else if(type == ftp_cct_TempFile) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Got FTP Callback for [%s] result = %d [%s]\n",itemName.c_str(),result.first,result.second.c_str()); - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexFTPProgress((ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL),mutexOwnerId); - if(ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); - fileFTPProgressList.erase(itemName); - safeMutexFTPProgress.ReleaseLock(); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("### downloaded TEMP file [%s] result = %d\n",itemName.c_str(),result.first); - - if(result.first == ftp_crt_SUCCESS) { - // Get path to temp files - string tempFilePath = "temp/"; - if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - tempFilePath = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + tempFilePath; - } - else { - Config &config = Config::getInstance(); - string userData = config.getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - tempFilePath = userData + tempFilePath; - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Temp files path [%s]\n",tempFilePath.c_str()); - - // Delete the downloaded archive - if(fileExists(tempFilePath + itemName)) { - removeFile(tempFilePath + itemName); - } - - bool result = upgradeFilesInTemp(); - if(result == false) { - string binaryName = Properties::getApplicationPath() + extractFileFromDirectoryPath(PlatformExceptionHandler::application_binary); - string binaryNameOld = Properties::getApplicationPath() + extractFileFromDirectoryPath(PlatformExceptionHandler::application_binary) + "__REMOVE"; - bool resultRename = renameFile(binaryName,binaryNameOld); - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Rename: [%s] to [%s] result = %d\n",binaryName.c_str(),binaryNameOld.c_str(),resultRename); - printf("#1 Rename: [%s] to [%s] result = %d errno = %d\n",binaryName.c_str(),binaryNameOld.c_str(),resultRename, errno); - - //result = upgradeFilesInTemp(); - binaryName = Properties::getApplicationPath() + extractFileFromDirectoryPath(PlatformExceptionHandler::application_binary); - binaryNameOld = tempFilePath + extractFileFromDirectoryPath(PlatformExceptionHandler::application_binary); - resultRename = renameFile(binaryNameOld, binaryName); - - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Rename: [%s] to [%s] result = %d\n",binaryName.c_str(),binaryNameOld.c_str(),resultRename); - printf("#2 Rename: [%s] to [%s] result = %d errno = %d\n",binaryNameOld.c_str(),binaryName.c_str(),resultRename, errno); - } - - console.addLine("Successfully updated, please restart!",true); - } - else { - curl_version_info_data *curlVersion= curl_version_info(CURLVERSION_NOW); - char szBuf[8096]=""; - snprintf(szBuf,8096,"FAILED to download the updates: [%s] using CURL version [%s] [%s]",itemName.c_str(),curlVersion->version,result.second.c_str()); - console.addLine(szBuf,true); - showErrorMessageBox(szBuf, "ERROR", false); + else if (ftpMessageBox.getEnabled()) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + int button = 0; + if (ftpMessageBox.mouseClick(x, y, button)) { + ftpMessageBox.setEnabled(false); + if (button == 0) { + startFTPClientIfRequired(); + + lastDownloadProgress = 0; + printf("Adding ftpFileName [%s] ftpFileURL [%s]\n", + ftpFileName.c_str(), ftpFileURL.c_str()); + if (ftpClientThread != NULL) + ftpClientThread->addTempFileToRequests(ftpFileName, ftpFileURL); + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + mutexOwnerId); + if (ftpClientThread != NULL && + ftpClientThread->getProgressMutex() != NULL) + ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); + fileFTPProgressList[ftpFileName] = pair(0, ""); + safeMutexFTPProgress.ReleaseLock(); } + } + } else if (mainMessageBox.getEnabled() == false && + buttonNewGame.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundB()); + mainMenu->setState(new MenuStateNewGame(program, mainMenu)); + } else if (mainMessageBox.getEnabled() == false && + buttonLoadGame.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundB()); + mainMenu->setState(new MenuStateLoadGame(program, mainMenu)); + } else if (mainMessageBox.getEnabled() == false && + buttonMods.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundB()); + mainMenu->setState(new MenuStateMods(program, mainMenu)); + } else if (mainMessageBox.getEnabled() == false && + buttonOptions.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundB()); + mainMenu->setState(new MenuStateOptions(program, mainMenu)); + } else if (mainMessageBox.getEnabled() == false && + buttonAbout.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundB()); + mainMenu->setState(new MenuStateAbout(program, mainMenu)); + } else if (buttonExit.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + program->exit(); } + } catch (exception &e) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s Line: %d]\nError in menu event:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, e.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + showErrorMessageBox(szBuf, "", true); + } } +void MenuStateRoot::startFTPClientIfRequired() { + if (ftpClientThread == NULL) { + // Setup File Transfer thread + Config &config = Config::getInstance(); + + vector tilesetFiles; + vector tilesetFilesUserData; + + vector techTreeFiles; + vector techTreeFilesUserData; + + findDirs(config.getPathListForType(ptTilesets), tilesetFiles); + findDirs(config.getPathListForType(ptTechs), techTreeFiles); -void MenuStateRoot::mouseMove(int x, int y, const MouseState *ms){ - popupMenu.mouseMove(x, y); - buttonNewGame.mouseMove(x, y); - buttonLoadGame.mouseMove(x, y); - buttonMods.mouseMove(x, y); - buttonOptions.mouseMove(x, y); - buttonAbout.mouseMove(x, y); - buttonExit.mouseMove(x,y); - if (mainMessageBox.getEnabled()) { - mainMessageBox.mouseMove(x, y); - } - if (errorMessageBox.getEnabled()) { - errorMessageBox.mouseMove(x, y); - } - if (ftpMessageBox.getEnabled()) { - ftpMessageBox.mouseMove(x, y); - } + vector mapPathList = config.getPathListForType(ptMaps); + std::pair mapsPath; + if (mapPathList.empty() == false) { + mapsPath.first = mapPathList[0]; + } + if (mapPathList.size() > 1) { + mapsPath.second = mapPathList[1]; + } + std::pair tilesetsPath; + vector tilesetsList = + Config::getInstance().getPathListForType(ptTilesets); + if (tilesetsList.empty() == false) { + tilesetsPath.first = tilesetsList[0]; + if (tilesetsList.size() > 1) { + tilesetsPath.second = tilesetsList[1]; + } + } + + std::pair techtreesPath; + vector techtreesList = + Config::getInstance().getPathListForType(ptTechs); + if (techtreesList.empty() == false) { + techtreesPath.first = techtreesList[0]; + if (techtreesList.size() > 1) { + techtreesPath.second = techtreesList[1]; + } + } + + std::pair scenariosPath; + vector scenariosList = + Config::getInstance().getPathListForType(ptScenarios); + if (scenariosList.empty() == false) { + scenariosPath.first = scenariosList[0]; + if (scenariosList.size() > 1) { + scenariosPath.second = scenariosList[1]; + } + } + + string fileArchiveExtension = config.getString("FileArchiveExtension", ""); + string fileArchiveExtractCommand = + config.getString("FileArchiveExtractCommand", ""); + string fileArchiveExtractCommandParameters = + config.getString("FileArchiveExtractCommandParameters", ""); + int32 fileArchiveExtractCommandSuccessResult = + config.getInt("FileArchiveExtractCommandSuccessResult", "0"); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + console.setOnlyChatMessagesInStoredLines(false); + + // Get path to temp files + string tempFilePath = "temp/"; + if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { + tempFilePath = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + + tempFilePath; + } else { + string userData = config.getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + tempFilePath = userData + tempFilePath; + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Temp files path [%s]\n", tempFilePath.c_str()); + + ftpClientThread = new FTPClientThread( + -1, "", mapsPath, tilesetsPath, techtreesPath, scenariosPath, this, + fileArchiveExtension, fileArchiveExtractCommand, + fileArchiveExtractCommandParameters, + fileArchiveExtractCommandSuccessResult, tempFilePath); + ftpClientThread->start(); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + } +} + +void MenuStateRoot::FTPClient_CallbackEvent( + string itemName, FTP_Client_CallbackType type, + pair result, void *userdata) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + Lang &lang = Lang::getInstance(); + if (type == ftp_cct_DownloadProgress) { + FTPClientCallbackInterface::FtpProgressStats *stats = + (FTPClientCallbackInterface::FtpProgressStats *)userdata; + if (stats != NULL) { + int fileProgress = 0; + if (stats->download_total > 0) { + fileProgress = ((stats->download_now / stats->download_total) * 100.0); + } + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Got FTP Callback for [%s] + // current file [%s] fileProgress = %d [now = %f, total = + // %f]\n",itemName.c_str(),stats->currentFilename.c_str(), + // fileProgress,stats->download_now,stats->download_total); + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() + : NULL), + mutexOwnerId); + if (ftpClientThread != NULL && + ftpClientThread->getProgressMutex() != NULL) + ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); + pair lastProgress = fileFTPProgressList[itemName]; + fileFTPProgressList[itemName] = + pair(fileProgress, stats->currentFilename); + safeMutexFTPProgress.ReleaseLock(); + + if (itemName != "" && + (lastDownloadProgress < fileProgress && fileProgress % 25 == 0)) { + lastDownloadProgress = fileProgress; + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "Downloaded %d%% of file: %s", fileProgress, + itemName.c_str()); + console.addLine(szBuf); + } + } + } else if (type == ftp_cct_ExtractProgress) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Got FTP extract Callback for [%s] result = %d [%s]\n", + itemName.c_str(), result.first, result.second.c_str()); + printf("Got FTP extract Callback for [%s] result = %d [%s]\n", + itemName.c_str(), result.first, result.second.c_str()); + + if (userdata == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + lang.getString("DataMissingExtractDownloadMod").c_str(), + itemName.c_str()); + // printf("%s\n",szBuf); + console.addLine(szBuf, true); + } else { + char *szBuf = (char *)userdata; + // printf("%s\n",szBuf); + console.addLine(szBuf); + } + } else if (type == ftp_cct_TempFile) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Got FTP Callback for [%s] result = %d [%s]\n", itemName.c_str(), + result.first, result.second.c_str()); + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexFTPProgress( + (ftpClientThread != NULL ? ftpClientThread->getProgressMutex() : NULL), + mutexOwnerId); + if (ftpClientThread != NULL && ftpClientThread->getProgressMutex() != NULL) + ftpClientThread->getProgressMutex()->setOwnerId(mutexOwnerId); + fileFTPProgressList.erase(itemName); + safeMutexFTPProgress.ReleaseLock(); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("### downloaded TEMP file [%s] result = %d\n", itemName.c_str(), + result.first); + + if (result.first == ftp_crt_SUCCESS) { + // Get path to temp files + string tempFilePath = "temp/"; + if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { + tempFilePath = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + + tempFilePath; + } else { + Config &config = Config::getInstance(); + string userData = config.getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + tempFilePath = userData + tempFilePath; + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Temp files path [%s]\n", tempFilePath.c_str()); + + // Delete the downloaded archive + if (fileExists(tempFilePath + itemName)) { + removeFile(tempFilePath + itemName); + } + + bool result = upgradeFilesInTemp(); + if (result == false) { + string binaryName = Properties::getApplicationPath() + + extractFileFromDirectoryPath( + PlatformExceptionHandler::application_binary); + string binaryNameOld = + Properties::getApplicationPath() + + extractFileFromDirectoryPath( + PlatformExceptionHandler::application_binary) + + "__REMOVE"; + bool resultRename = renameFile(binaryName, binaryNameOld); + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Rename: [%s] to [%s] + // result = + // %d\n",binaryName.c_str(),binaryNameOld.c_str(),resultRename); + printf("#1 Rename: [%s] to [%s] result = %d errno = %d\n", + binaryName.c_str(), binaryNameOld.c_str(), resultRename, errno); + + // result = upgradeFilesInTemp(); + binaryName = Properties::getApplicationPath() + + extractFileFromDirectoryPath( + PlatformExceptionHandler::application_binary); + binaryNameOld = + tempFilePath + extractFileFromDirectoryPath( + PlatformExceptionHandler::application_binary); + resultRename = renameFile(binaryNameOld, binaryName); + + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Rename: [%s] to [%s] + // result = + // %d\n",binaryName.c_str(),binaryNameOld.c_str(),resultRename); + printf("#2 Rename: [%s] to [%s] result = %d errno = %d\n", + binaryNameOld.c_str(), binaryName.c_str(), resultRename, errno); + } + + console.addLine("Successfully updated, please restart!", true); + } else { + curl_version_info_data *curlVersion = curl_version_info(CURLVERSION_NOW); + + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "FAILED to download the updates: [%s] using CURL version [%s] [%s]", + itemName.c_str(), curlVersion->version, result.second.c_str()); + console.addLine(szBuf, true); + showErrorMessageBox(szBuf, "ERROR", false); + } + } +} + +void MenuStateRoot::mouseMove(int x, int y, const MouseState *ms) { + popupMenu.mouseMove(x, y); + buttonNewGame.mouseMove(x, y); + buttonLoadGame.mouseMove(x, y); + buttonMods.mouseMove(x, y); + buttonOptions.mouseMove(x, y); + buttonAbout.mouseMove(x, y); + buttonExit.mouseMove(x, y); + if (mainMessageBox.getEnabled()) { + mainMessageBox.mouseMove(x, y); + } + if (errorMessageBox.getEnabled()) { + errorMessageBox.mouseMove(x, y); + } + if (ftpMessageBox.getEnabled()) { + ftpMessageBox.mouseMove(x, y); + } } bool MenuStateRoot::isMasterserverMode() const { - return GlobalStaticFlags::getIsNonGraphicalModeEnabled(); + return GlobalStaticFlags::getIsNonGraphicalModeEnabled(); } void MenuStateRoot::render() { - if(isMasterserverMode() == true) { - return; - } - Renderer &renderer= Renderer::getInstance(); - CoreData &coreData= CoreData::getInstance(); - const Metrics &metrics= Metrics::getInstance(); - - int w= 400; - int h= 200; - int yPos= 510; - - int logoMainX = (metrics.getVirtualW()-w)/2; - int logoMainY = yPos-h/2; - int logoMainW = w; - int logoMainH = h; - logoMainX = Config::getInstance().getInt(string(containerName) + "_MainLogo_x",intToStr(logoMainX).c_str()); - logoMainY = Config::getInstance().getInt(string(containerName) + "_MainLogo_y",intToStr(logoMainY).c_str()); - logoMainW = Config::getInstance().getInt(string(containerName) + "_MainLogo_w",intToStr(logoMainW).c_str()); - logoMainH = Config::getInstance().getInt(string(containerName) + "_MainLogo_h",intToStr(logoMainH).c_str()); - - renderer.renderTextureQuad( - logoMainX, logoMainY, logoMainW, logoMainH, - coreData.getLogoTexture(), GraphicComponent::getFade()); - - int maxLogoWidth=0; - for(int idx = 0; idx < (int)coreData.getLogoTextureExtraCount(); ++idx) { - Texture2D *extraLogo = coreData.getLogoTextureExtra(idx); - maxLogoWidth += extraLogo->getPixmap()->getW(); - } - - int currentX = (metrics.getVirtualW()-maxLogoWidth)/2; - int currentY = 50; - for(int idx = 0; idx < (int)coreData.getLogoTextureExtraCount(); ++idx) { - Texture2D *extraLogo = coreData.getLogoTextureExtra(idx); - - logoMainX = currentX; - logoMainY = currentY; - logoMainW = extraLogo->getPixmap()->getW(); - logoMainH = extraLogo->getPixmap()->getH(); - - string logoTagName = string(containerName) + "_ExtraLogo" + intToStr(idx+1) + "_"; - logoMainX = Config::getInstance().getInt(logoTagName + "x",intToStr(logoMainX).c_str()); - logoMainY = Config::getInstance().getInt(logoTagName + "y",intToStr(logoMainY).c_str()); - logoMainW = Config::getInstance().getInt(logoTagName + "w",intToStr(logoMainW).c_str()); - logoMainH = Config::getInstance().getInt(logoTagName + "h",intToStr(logoMainH).c_str()); - - renderer.renderTextureQuad( - logoMainX, logoMainY, - logoMainW, logoMainH, - extraLogo, GraphicComponent::getFade()); - - currentX += extraLogo->getPixmap()->getW(); - } - - renderer.renderButton(&buttonNewGame); - renderer.renderButton(&buttonLoadGame); - renderer.renderButton(&buttonMods); - renderer.renderButton(&buttonOptions); - renderer.renderButton(&buttonAbout); - renderer.renderButton(&buttonExit); - renderer.renderLabel(&labelVersion); - renderer.renderLabel(&labelGreeting); - - renderer.renderConsole(&console); - - renderer.renderPopupMenu(&popupMenu); - - //exit message box - if(mainMessageBox.getEnabled()) { - renderer.renderMessageBox(&mainMessageBox); - } - if(errorMessageBox.getEnabled()) { - renderer.renderMessageBox(&errorMessageBox); - } - if(ftpMessageBox.getEnabled()) { - renderer.renderMessageBox(&ftpMessageBox); - } - - if(program != NULL) program->renderProgramMsgBox(); + if (isMasterserverMode() == true) { + return; + } + Renderer &renderer = Renderer::getInstance(); + CoreData &coreData = CoreData::getInstance(); + const Metrics &metrics = Metrics::getInstance(); + + int w = 400; + int h = 200; + int yPos = 510; + + int logoMainX = (metrics.getVirtualW() - w) / 2; + int logoMainY = yPos - h / 2; + int logoMainW = w; + int logoMainH = h; + logoMainX = Config::getInstance().getInt( + string(containerName) + "_MainLogo_x", intToStr(logoMainX).c_str()); + logoMainY = Config::getInstance().getInt( + string(containerName) + "_MainLogo_y", intToStr(logoMainY).c_str()); + logoMainW = Config::getInstance().getInt( + string(containerName) + "_MainLogo_w", intToStr(logoMainW).c_str()); + logoMainH = Config::getInstance().getInt( + string(containerName) + "_MainLogo_h", intToStr(logoMainH).c_str()); + + renderer.renderTextureQuad(logoMainX, logoMainY, logoMainW, logoMainH, + coreData.getLogoTexture(), + GraphicComponent::getFade()); + + int maxLogoWidth = 0; + for (int idx = 0; idx < (int)coreData.getLogoTextureExtraCount(); ++idx) { + Texture2D *extraLogo = coreData.getLogoTextureExtra(idx); + maxLogoWidth += extraLogo->getPixmap()->getW(); + } + + int currentX = (metrics.getVirtualW() - maxLogoWidth) / 2; + int currentY = 50; + for (int idx = 0; idx < (int)coreData.getLogoTextureExtraCount(); ++idx) { + Texture2D *extraLogo = coreData.getLogoTextureExtra(idx); + + logoMainX = currentX; + logoMainY = currentY; + logoMainW = extraLogo->getPixmap()->getW(); + logoMainH = extraLogo->getPixmap()->getH(); + + string logoTagName = + string(containerName) + "_ExtraLogo" + intToStr(idx + 1) + "_"; + logoMainX = Config::getInstance().getInt(logoTagName + "x", + intToStr(logoMainX).c_str()); + logoMainY = Config::getInstance().getInt(logoTagName + "y", + intToStr(logoMainY).c_str()); + logoMainW = Config::getInstance().getInt(logoTagName + "w", + intToStr(logoMainW).c_str()); + logoMainH = Config::getInstance().getInt(logoTagName + "h", + intToStr(logoMainH).c_str()); + + renderer.renderTextureQuad(logoMainX, logoMainY, logoMainW, logoMainH, + extraLogo, GraphicComponent::getFade()); + + currentX += extraLogo->getPixmap()->getW(); + } + + renderer.renderButton(&buttonNewGame); + renderer.renderButton(&buttonLoadGame); + renderer.renderButton(&buttonMods); + renderer.renderButton(&buttonOptions); + renderer.renderButton(&buttonAbout); + renderer.renderButton(&buttonExit); + renderer.renderLabel(&labelVersion); + renderer.renderLabel(&labelGreeting); + + renderer.renderConsole(&console); + + renderer.renderPopupMenu(&popupMenu); + + // exit message box + if (mainMessageBox.getEnabled()) { + renderer.renderMessageBox(&mainMessageBox); + } + if (errorMessageBox.getEnabled()) { + renderer.renderMessageBox(&errorMessageBox); + } + if (ftpMessageBox.getEnabled()) { + renderer.renderMessageBox(&ftpMessageBox); + } + + if (program != NULL) + program->renderProgramMsgBox(); } void MenuStateRoot::update() { - if(Config::getInstance().getBool("AutoTest")) { - if(AutoTest::getInstance().mustExitGame() == false) { - AutoTest::getInstance().updateRoot(program, mainMenu); - } - else { - program->exit(); - } - return; - } - - if(gameUpdateChecked == false) { - gameUpdateChecked = true; - - string updateCheckURL = Config::getInstance().getString("UpdateCheckURL",""); - if(updateCheckURL != "") { - static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); - updatesHttpServerThread = new SimpleTaskThread(this,1,200); - updatesHttpServerThread->setUniqueID(mutexOwnerId); - updatesHttpServerThread->start(); - } - } - - console.update(); + if (Config::getInstance().getBool("AutoTest")) { + if (AutoTest::getInstance().mustExitGame() == false) { + AutoTest::getInstance().updateRoot(program, mainMenu); + } else { + program->exit(); + } + return; + } + + if (gameUpdateChecked == false) { + gameUpdateChecked = true; + + string updateCheckURL = + Config::getInstance().getString("UpdateCheckURL", ""); + if (updateCheckURL != "") { + static string mutexOwnerId = + string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + + intToStr(__LINE__); + updatesHttpServerThread = new SimpleTaskThread(this, 1, 200); + updatesHttpServerThread->setUniqueID(mutexOwnerId); + updatesHttpServerThread->start(); + } + } + + console.update(); } -void MenuStateRoot::simpleTask(BaseThread *callingThread,void *userdata) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); +void MenuStateRoot::simpleTask(BaseThread *callingThread, void *userdata) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutexThreadOwner( + callingThread->getMutexThreadOwnerValid(), mutexOwnerId); + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; + } + + callingThread->getMutexThreadOwnerValid()->setOwnerId(mutexOwnerId); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + + string updateCheckURL = Config::getInstance().getString("UpdateCheckURL", ""); + if (updateCheckURL != "") { + + string baseURL = updateCheckURL; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d] About to call first http url, base [%s]..\n", + __FILE__, __FUNCTION__, __LINE__, baseURL.c_str()); + + CURL *handle = SystemFlags::initHTTP(); + CURLcode curlResult = CURLE_OK; + string updateMetaData = + SystemFlags::getHTTP(baseURL, handle, -1, &curlResult); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("techsMetaData [%s] curlResult = %d\n", updateMetaData.c_str(), + curlResult); + + if (callingThread->getQuitStatus() == true || + safeMutexThreadOwner.isValidMutex() == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d]\n", __FILE__, __FUNCTION__, __LINE__); + return; + } + + if (curlResult != CURLE_OK) { + string curlError = curl_easy_strerror(curlResult); - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutexThreadOwner(callingThread->getMutexThreadOwnerValid(),mutexOwnerId); - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d] curlError [%s]..\n", __FILE__, __FUNCTION__, + __LINE__, curlError.c_str()); + + char szMsg[8096] = ""; + snprintf(szMsg, 8096, + "An error was detected while checking for new updates\n%s", + curlError.c_str()); + showErrorMessageBox(szMsg, "ERROR", false); } - callingThread->getMutexThreadOwnerValid()->setOwnerId(mutexOwnerId); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - - - string updateCheckURL = Config::getInstance().getString("UpdateCheckURL",""); - if(updateCheckURL != "") { - - string baseURL = updateCheckURL; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d] About to call first http url, base [%s]..\n",__FILE__,__FUNCTION__,__LINE__,baseURL.c_str()); - - CURL *handle = SystemFlags::initHTTP(); - CURLcode curlResult = CURLE_OK; - string updateMetaData = SystemFlags::getHTTP(baseURL,handle,-1,&curlResult); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("techsMetaData [%s] curlResult = %d\n",updateMetaData.c_str(),curlResult); - - if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); - return; - } - - if(curlResult != CURLE_OK) { - string curlError = curl_easy_strerror(curlResult); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d] curlError [%s]..\n",__FILE__,__FUNCTION__,__LINE__,curlError.c_str()); - - char szMsg[8096]=""; - snprintf(szMsg,8096,"An error was detected while checking for new updates\n%s",curlError.c_str()); - showErrorMessageBox(szMsg, "ERROR", false); - } - - if(curlResult == CURLE_OK || - (curlResult != CURLE_COULDNT_RESOLVE_HOST && - curlResult != CURLE_COULDNT_CONNECT)) { - - Properties props; - props.loadFromText(updateMetaData); - - int compareResult = compareMajorMinorVersion(glestVersionString, props.getString("LatestGameVersion","")); - if(compareResult==0) { - if(glestVersionString != props.getString("LatestGameVersion","")) { - compareResult = -1; - } - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("compareResult = %d local [%s] remote [%s]\n",compareResult,glestVersionString.c_str(),props.getString("LatestGameVersion","").c_str()); - - if(compareResult < 0) { - - string downloadBinaryKey = "LatestGameBinaryUpdateArchiveURL-" + getPlatformTypeNameString() + getPlatformArchTypeNameString(); - if(props.hasString(downloadBinaryKey)) { - ftpFileName = extractFileFromDirectoryPath(props.getString(downloadBinaryKey)); - ftpFileURL = props.getString(downloadBinaryKey); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Checking update key downloadBinaryKey [%s] ftpFileURL [%s]\n",downloadBinaryKey.c_str(),ftpFileURL.c_str()); - - if(props.getBool("AllowUpdateDownloads","false") == false || ftpFileURL == "") { - char szMsg[8096]=""; - snprintf(szMsg,8096,"A new update was detected: %s\nUpdate Date: %s\nPlease visit megaglest.org for details!", - props.getString("LatestGameVersion","?").c_str(), - props.getString("LatestGameVersionReleaseDate","?").c_str()); - showFTPMessageBox(szMsg, "Update", false, true); - } - else { - char szMsg[8096]=""; - snprintf(szMsg,8096,"A new update was detected: %s\nUpdate Date: %s\nDownload update now?", - props.getString("LatestGameVersion","?").c_str(), - props.getString("LatestGameVersionReleaseDate","?").c_str()); - showFTPMessageBox(szMsg, "Update", false, false); - } - } - } - SystemFlags::cleanupHTTP(&handle); - } -} + if (curlResult == CURLE_OK || (curlResult != CURLE_COULDNT_RESOLVE_HOST && + curlResult != CURLE_COULDNT_CONNECT)) { -void MenuStateRoot::keyDown(SDL_KeyboardEvent key) { + Properties props; + props.loadFromText(updateMetaData); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] key = [%c] [%d]\n",__FILE__,__FUNCTION__,__LINE__,key.keysym.sym,key.keysym.sym); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf ("In [%s::%s Line: %d] key = [%d - %c]\n",__FILE__,__FUNCTION__,__LINE__,key.keysym.sym,key.keysym.sym); - - //printf("\n\n\nIN MENU STATE ROOT KEYDOWN!!!\n\n\n"); - - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - //exit - //if(key == configKeys.getCharKey("ExitKey")) { - //printf("Check Root menu exit key!\n"); - if(isKeyPressed(configKeys.getSDLKey("ExitKey"),key) == true) { - Lang &lang= Lang::getInstance(); - showMessageBox(lang.getString("ExitGameQuestion"), "", true); - } - //else if(mainMessageBox.getEnabled() == true && key == vkReturn) { - else if(mainMessageBox.getEnabled() == true && isKeyPressed(SDLK_RETURN,key) == true) { - //SDL_keysym keystate = Window::getKeystate(); - SDL_keysym keystate = key.keysym; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] keystate.mod [%d]\n",__FILE__,__FUNCTION__,__LINE__,keystate.mod); - - //printf("---> keystate.mod [%d]\n",keystate.mod); - if(keystate.mod & (KMOD_LALT | KMOD_RALT)) { - } - else { - //printf("EXITING ---> keystate.mod [%d]\n",keystate.mod); - program->exit(); - } - } - //else if(key == configKeys.getCharKey("SaveGUILayout")) { - else if(isKeyPressed(configKeys.getSDLKey("SaveGUILayout"),key) == true) { - GraphicComponent::saveAllCustomProperties(containerName); - //Lang &lang= Lang::getInstance(); - //console.addLine(lang.getString("GUILayoutSaved") + " [" + (saved ? lang.getString("Yes") : lang.getString("No"))+ "]"); - } + int compareResult = compareMajorMinorVersion( + glestVersionString, props.getString("LatestGameVersion", "")); + if (compareResult == 0) { + if (glestVersionString != props.getString("LatestGameVersion", "")) { + compareResult = -1; + } + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("compareResult = %d local [%s] remote [%s]\n", compareResult, + glestVersionString.c_str(), + props.getString("LatestGameVersion", "").c_str()); + + if (compareResult < 0) { + + string downloadBinaryKey = "LatestGameBinaryUpdateArchiveURL-" + + getPlatformTypeNameString() + + getPlatformArchTypeNameString(); + if (props.hasString(downloadBinaryKey)) { + ftpFileName = + extractFileFromDirectoryPath(props.getString(downloadBinaryKey)); + ftpFileURL = props.getString(downloadBinaryKey); + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Checking update key downloadBinaryKey [%s] ftpFileURL [%s]\n", + downloadBinaryKey.c_str(), ftpFileURL.c_str()); + + if (props.getBool("AllowUpdateDownloads", "false") == false || + ftpFileURL == "") { + char szMsg[8096] = ""; + snprintf( + szMsg, 8096, + "A new update was detected: %s\nUpdate Date: %s\nPlease visit " + "megaglest.org for details!", + props.getString("LatestGameVersion", "?").c_str(), + props.getString("LatestGameVersionReleaseDate", "?").c_str()); + showFTPMessageBox(szMsg, "Update", false, true); + } else { + char szMsg[8096] = ""; + snprintf( + szMsg, 8096, + "A new update was detected: %s\nUpdate Date: %s\nDownload update " + "now?", + props.getString("LatestGameVersion", "?").c_str(), + props.getString("LatestGameVersionReleaseDate", "?").c_str()); + showFTPMessageBox(szMsg, "Update", false, false); + } + } + } + SystemFlags::cleanupHTTP(&handle); + } } -void MenuStateRoot::showMessageBox(const string &text, const string &header, bool toggle) { - if(toggle == false) { - mainMessageBox.setEnabled(false); - } - - if(mainMessageBox.getEnabled() == false) { - mainMessageBox.setText(text); - mainMessageBox.setHeader(header); - mainMessageBox.setEnabled(true); - } - else { - mainMessageBox.setEnabled(false); - } +void MenuStateRoot::keyDown(SDL_KeyboardEvent key) { + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, "In [%s::%s Line: %d] key = [%c] [%d]\n", + __FILE__, __FUNCTION__, __LINE__, key.keysym.sym, key.keysym.sym); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] key = [%d - %c]\n", __FILE__, __FUNCTION__, + __LINE__, key.keysym.sym, key.keysym.sym); + + // printf("\n\n\nIN MENU STATE ROOT KEYDOWN!!!\n\n\n"); + + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + // exit + // if(key == configKeys.getCharKey("ExitKey")) { + // printf("Check Root menu exit key!\n"); + if (isKeyPressed(configKeys.getSDLKey("ExitKey"), key) == true) { + Lang &lang = Lang::getInstance(); + showMessageBox(lang.getString("ExitGameQuestion"), "", true); + } + // else if(mainMessageBox.getEnabled() == true && key == vkReturn) { + else if (mainMessageBox.getEnabled() == true && + isKeyPressed(SDLK_RETURN, key) == true) { + // SDL_keysym keystate = Window::getKeystate(); + SDL_keysym keystate = key.keysym; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] keystate.mod [%d]\n", + __FILE__, __FUNCTION__, __LINE__, keystate.mod); + + // printf("---> keystate.mod [%d]\n",keystate.mod); + if (keystate.mod & (KMOD_LALT | KMOD_RALT)) { + } else { + // printf("EXITING ---> keystate.mod [%d]\n",keystate.mod); + program->exit(); + } + } + // else if(key == configKeys.getCharKey("SaveGUILayout")) { + else if (isKeyPressed(configKeys.getSDLKey("SaveGUILayout"), key) == true) { + GraphicComponent::saveAllCustomProperties(containerName); + // Lang &lang= Lang::getInstance(); + // console.addLine(lang.getString("GUILayoutSaved") + " [" + (saved ? + // lang.getString("Yes") : lang.getString("No"))+ "]"); + } } -void MenuStateRoot::showErrorMessageBox(const string &text, const string &header, bool toggle) { - if(toggle == false) { - errorMessageBox.setEnabled(false); - } - - if(errorMessageBox.getEnabled() == false) { - errorMessageBox.setText(text); - errorMessageBox.setHeader(header); - errorMessageBox.setEnabled(true); - } - else { - errorMessageBox.setEnabled(false); - } +void MenuStateRoot::showMessageBox(const string &text, const string &header, + bool toggle) { + if (toggle == false) { + mainMessageBox.setEnabled(false); + } + + if (mainMessageBox.getEnabled() == false) { + mainMessageBox.setText(text); + mainMessageBox.setHeader(header); + mainMessageBox.setEnabled(true); + } else { + mainMessageBox.setEnabled(false); + } } -void MenuStateRoot::showFTPMessageBox(const string &text, const string &header, bool toggle, bool okOnly) { - if(toggle == false) { - ftpMessageBox.setEnabled(false); - } - - Lang &lang= Lang::getInstance(); - if(okOnly) { - ftpMessageBox.init(lang.getString("Ok")); - } - else { - ftpMessageBox.init(lang.getString("Yes"), lang.getString("No")); - } - - if(ftpMessageBox.getEnabled() == false) { - ftpMessageBox.setText(text); - ftpMessageBox.setHeader(header); - ftpMessageBox.setEnabled(true); - } - else { - ftpMessageBox.setEnabled(false); - } +void MenuStateRoot::showErrorMessageBox(const string &text, + const string &header, bool toggle) { + if (toggle == false) { + errorMessageBox.setEnabled(false); + } + + if (errorMessageBox.getEnabled() == false) { + errorMessageBox.setText(text); + errorMessageBox.setHeader(header); + errorMessageBox.setEnabled(true); + } else { + errorMessageBox.setEnabled(false); + } } +void MenuStateRoot::showFTPMessageBox(const string &text, const string &header, + bool toggle, bool okOnly) { + if (toggle == false) { + ftpMessageBox.setEnabled(false); + } + + Lang &lang = Lang::getInstance(); + if (okOnly) { + ftpMessageBox.init(lang.getString("Ok")); + } else { + ftpMessageBox.init(lang.getString("Yes"), lang.getString("No")); + } + + if (ftpMessageBox.getEnabled() == false) { + ftpMessageBox.setText(text); + ftpMessageBox.setHeader(header); + ftpMessageBox.setEnabled(true); + } else { + ftpMessageBox.setEnabled(false); + } +} -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/menu/menu_state_root.h b/source/glest_game/menu/menu_state_root.h index 9be5fbfd7..b460c3f07 100644 --- a/source/glest_game/menu/menu_state_root.h +++ b/source/glest_game/menu/menu_state_root.h @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,70 +13,77 @@ #define _GLEST_GAME_MENUSTATEROOT_H_ #include "main_menu.h" -#include "simple_threads.h" #include "miniftpclient.h" +#include "simple_threads.h" #include "leak_dumper.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // =============================== -// class MenuStateRoot +// class MenuStateRoot // =============================== class GraphicMessageBox; class PopupMenu; -class MenuStateRoot: public MenuState, public SimpleTaskCallbackInterface, public FTPClientCallbackInterface { +class MenuStateRoot : public MenuState, + public SimpleTaskCallbackInterface, + public FTPClientCallbackInterface { private: - GraphicButton buttonNewGame; - GraphicButton buttonLoadGame; - GraphicButton buttonMods; - GraphicButton buttonOptions; - GraphicButton buttonAbout; - GraphicButton buttonExit; - GraphicLabel labelVersion; - GraphicLabel labelGreeting; - - GraphicMessageBox mainMessageBox; - GraphicMessageBox errorMessageBox; - GraphicMessageBox ftpMessageBox; - - PopupMenu popupMenu; - - static bool gameUpdateChecked; - SimpleTaskThread *updatesHttpServerThread; - FTPClientThread *ftpClientThread; - std::map > fileFTPProgressList; - string ftpFileName; - string ftpFileURL; - int lastDownloadProgress; - - virtual void simpleTask(BaseThread *callingThread,void *userdata); - void startFTPClientIfRequired(); - virtual void FTPClient_CallbackEvent(string itemName, - FTP_Client_CallbackType type, pair result,void *userdata); + GraphicButton buttonNewGame; + GraphicButton buttonLoadGame; + GraphicButton buttonMods; + GraphicButton buttonOptions; + GraphicButton buttonAbout; + GraphicButton buttonExit; + GraphicLabel labelVersion; + GraphicLabel labelGreeting; + + GraphicMessageBox mainMessageBox; + GraphicMessageBox errorMessageBox; + GraphicMessageBox ftpMessageBox; + + PopupMenu popupMenu; + + static bool gameUpdateChecked; + SimpleTaskThread *updatesHttpServerThread; + FTPClientThread *ftpClientThread; + std::map> fileFTPProgressList; + string ftpFileName; + string ftpFileURL; + int lastDownloadProgress; + + virtual void simpleTask(BaseThread *callingThread, void *userdata); + void startFTPClientIfRequired(); + virtual void + FTPClient_CallbackEvent(string itemName, FTP_Client_CallbackType type, + pair result, + void *userdata); public: - MenuStateRoot(Program *program, MainMenu *mainMenu); - virtual ~MenuStateRoot(); - - void mouseClick(int x, int y, MouseButton mouseButton); - void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; - void mouseMove(int x, int y, const MouseState *mouseState); - void render(); - void update(); - virtual void keyDown(SDL_KeyboardEvent key); - - void showMessageBox(const string &text, const string &header, bool toggle); - void showErrorMessageBox(const string &text, const string &header, bool toggle); - void showFTPMessageBox(const string &text, const string &header, bool toggle, bool okOnly); - - virtual bool isMasterserverMode() const; - virtual void reloadUI(); + MenuStateRoot(Program *program, MainMenu *mainMenu); + virtual ~MenuStateRoot(); + + void mouseClick(int x, int y, MouseButton mouseButton); + void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; + void mouseMove(int x, int y, const MouseState *mouseState); + void render(); + void update(); + virtual void keyDown(SDL_KeyboardEvent key); + + void showMessageBox(const string &text, const string &header, bool toggle); + void showErrorMessageBox(const string &text, const string &header, + bool toggle); + void showFTPMessageBox(const string &text, const string &header, bool toggle, + bool okOnly); + + virtual bool isMasterserverMode() const; + virtual void reloadUI(); }; - -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/menu/menu_state_scenario.cpp b/source/glest_game/menu/menu_state_scenario.cpp index dd63ff2da..322d42a0b 100644 --- a/source/glest_game/menu/menu_state_scenario.cpp +++ b/source/glest_game/menu/menu_state_scenario.cpp @@ -11,493 +11,587 @@ #include "menu_state_scenario.h" -#include "renderer.h" -#include "menu_state_new_game.h" -#include "sound_renderer.h" +#include "auto_test.h" +#include "config.h" #include "core_data.h" +#include "game.h" +#include "menu_state_new_game.h" #include "menu_state_options.h" #include "network_manager.h" -#include "config.h" -#include "auto_test.h" -#include "game.h" +#include "renderer.h" +#include "sound_renderer.h" #include "leak_dumper.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { -using namespace ::Shared::Xml; +using namespace ::Shared::Xml; // ===================================================== // class MenuStateScenario // ===================================================== MenuStateScenario::MenuStateScenario(Program *program, MainMenu *mainMenu, - bool isTutorialMode, const vector &dirList, string autoloadScenarioName) : - MenuState(program, mainMenu, "scenario") -{ - containerName = "Scenario"; - this->isTutorialMode = isTutorialMode; - - enableScenarioTexturePreview = Config::getInstance().getBool("EnableScenarioTexturePreview","true"); - scenarioLogoTexture=NULL; - previewLoadDelayTimer=time(NULL); - needToLoadTextures=true; - - Lang &lang= Lang::getInstance(); - NetworkManager &networkManager= NetworkManager::getInstance(); - try { - networkManager.init(nrServer); + bool isTutorialMode, + const vector &dirList, + string autoloadScenarioName) + : MenuState(program, mainMenu, "scenario") { + containerName = "Scenario"; + this->isTutorialMode = isTutorialMode; + + enableScenarioTexturePreview = + Config::getInstance().getBool("EnableScenarioTexturePreview", "true"); + scenarioLogoTexture = NULL; + previewLoadDelayTimer = time(NULL); + needToLoadTextures = true; + + Lang &lang = Lang::getInstance(); + NetworkManager &networkManager = NetworkManager::getInstance(); + try { + networkManager.init(nrServer); + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] Error detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + mainMessageBoxState = 1; + showMessageBox("Error: " + string(ex.what()), "Error detected", false); + } + + mainMessageBox.registerGraphicComponent(containerName, "mainMessageBox"); + mainMessageBox.init(lang.getString("Ok")); + mainMessageBox.setEnabled(false); + mainMessageBoxState = 0; + + this->autoloadScenarioName = autoloadScenarioName; + vector results; + + this->dirList = dirList; + + int buttonStartY = 50; + int buttonStartX = 50; + + buttonReturn.registerGraphicComponent(containerName, "buttonReturn"); + buttonReturn.init(buttonStartX, buttonStartY, 125); + buttonReturn.setText(lang.getString("Return")); + + buttonPlayNow.registerGraphicComponent(containerName, "buttonPlayNow"); + buttonPlayNow.init(buttonStartX + 150, buttonStartY, 125); + buttonPlayNow.setText(lang.getString("PlayNow")); + + int startY = 700; + int startX = 50; + + labelScenario.registerGraphicComponent(containerName, "labelScenario"); + labelScenario.init(startX, startY); + + comboBoxScenario.registerGraphicComponent(containerName, "listBoxScenario"); + comboBoxScenario.init(startX, startY - 20, 290); + comboBoxScenario.setPopupLineCount(30); + + labelScenarioName.registerGraphicComponent(containerName, + "labelScenarioName"); + labelScenarioName.init(500, startY); + labelScenarioName.setFont(CoreData::getInstance().getMenuFontBig()); + labelScenarioName.setFont3D(CoreData::getInstance().getMenuFontBig3D()); + + labelInfo.registerGraphicComponent(containerName, "labelInfo"); + labelInfo.init(500, startY - 30); + labelInfo.setFont(CoreData::getInstance().getMenuFontNormal()); + labelInfo.setFont3D(CoreData::getInstance().getMenuFontNormal3D()); + + if (this->isTutorialMode == true) { + labelScenario.setText(lang.getString("Tutorial")); + } else { + labelScenario.setText(lang.getString("Scenario")); + } + + // scenario listbox + findDirs(dirList, results); + scenarioFiles = results; + // printf("scenarioFiles[0] [%s]\n",scenarioFiles[0].c_str()); + + if (results.empty() == true) { + // throw megaglest_runtime_error("There are no scenarios found to load"); + mainMessageBoxState = 1; + if (this->isTutorialMode == true) { + showMessageBox("Error: There are no tutorials found to load", + "Error detected", false); + } else { + showMessageBox("Error: There are no scenarios found to load", + "Error detected", false); + } + } + + std::map scenarioErrors; + for (int i = 0; i < (int)results.size(); ++i) { + results[i] = formatString(results[i]); + } + comboBoxScenario.setItems(results); + + try { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] listBoxScenario.getSelectedItemIndex() = %d " + "scenarioFiles.size() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, comboBoxScenario.getSelectedItemIndex(), + (int)scenarioFiles.size()); + + if (comboBoxScenario.getItemCount() > 0 && + comboBoxScenario.getSelectedItemIndex() >= 0 && + comboBoxScenario.getSelectedItemIndex() < (int)scenarioFiles.size()) { + string scenarioPath = Scenario::getScenarioPath( + dirList, scenarioFiles[comboBoxScenario.getSelectedItemIndex()]); + // printf("scenarioPath [%s]\n",scenarioPath.c_str()); + + loadScenarioInfo(scenarioPath, &scenarioInfo); + labelInfo.setText(scenarioInfo.desc); + if (scenarioInfo.namei18n != "") { + labelScenarioName.setText(scenarioInfo.namei18n); + } else { + labelScenarioName.setText(comboBoxScenario.getSelectedItem()); + } } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] Error detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - - mainMessageBoxState=1; - showMessageBox( "Error: " + string(ex.what()), "Error detected", false); - } - - mainMessageBox.registerGraphicComponent(containerName,"mainMessageBox"); - mainMessageBox.init(lang.getString("Ok")); - mainMessageBox.setEnabled(false); - mainMessageBoxState=0; - - this->autoloadScenarioName = autoloadScenarioName; - vector results; - - this->dirList = dirList; - - int buttonStartY=50; - int buttonStartX=50; - - buttonReturn.registerGraphicComponent(containerName,"buttonReturn"); - buttonReturn.init(buttonStartX, buttonStartY, 125); - buttonReturn.setText(lang.getString("Return")); - - buttonPlayNow.registerGraphicComponent(containerName,"buttonPlayNow"); - buttonPlayNow.init(buttonStartX+150, buttonStartY, 125); - buttonPlayNow.setText(lang.getString("PlayNow")); - - int startY=700; - int startX=50; - - labelScenario.registerGraphicComponent(containerName,"labelScenario"); - labelScenario.init(startX, startY); - - comboBoxScenario.registerGraphicComponent(containerName,"listBoxScenario"); - comboBoxScenario.init(startX, startY-20, 290); - comboBoxScenario.setPopupLineCount(30); - - labelScenarioName.registerGraphicComponent(containerName,"labelScenarioName"); - labelScenarioName.init(500, startY); - labelScenarioName.setFont(CoreData::getInstance().getMenuFontBig()); - labelScenarioName.setFont3D(CoreData::getInstance().getMenuFontBig3D()); - - labelInfo.registerGraphicComponent(containerName,"labelInfo"); - labelInfo.init(500, startY-30); - labelInfo.setFont(CoreData::getInstance().getMenuFontNormal()); - labelInfo.setFont3D(CoreData::getInstance().getMenuFontNormal3D()); - - if(this->isTutorialMode == true) { - labelScenario.setText(lang.getString("Tutorial")); - } - else { - labelScenario.setText(lang.getString("Scenario")); - } - - //scenario listbox - findDirs(dirList, results); - scenarioFiles = results; - //printf("scenarioFiles[0] [%s]\n",scenarioFiles[0].c_str()); - - if(results.empty() == true) { - //throw megaglest_runtime_error("There are no scenarios found to load"); - mainMessageBoxState=1; - if(this->isTutorialMode == true) { - showMessageBox( "Error: There are no tutorials found to load", "Error detected", false); - } - else { - showMessageBox( "Error: There are no scenarios found to load", "Error detected", false); - } - } - - std::map scenarioErrors; - for(int i= 0; i < (int)results.size(); ++i){ - results[i] = formatString(results[i]); - } - comboBoxScenario.setItems(results); - try { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] listBoxScenario.getSelectedItemIndex() = %d scenarioFiles.size() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,comboBoxScenario.getSelectedItemIndex(),(int)scenarioFiles.size()); - - if(comboBoxScenario.getItemCount() > 0 && comboBoxScenario.getSelectedItemIndex() >= 0 && comboBoxScenario.getSelectedItemIndex() < (int)scenarioFiles.size()) { - string scenarioPath = Scenario::getScenarioPath(dirList, scenarioFiles[comboBoxScenario.getSelectedItemIndex()]); - //printf("scenarioPath [%s]\n",scenarioPath.c_str()); - - loadScenarioInfo(scenarioPath, &scenarioInfo ); - labelInfo.setText(scenarioInfo.desc); - if(scenarioInfo.namei18n != "") { - labelScenarioName.setText(scenarioInfo.namei18n); - } - else { - labelScenarioName.setText(comboBoxScenario.getSelectedItem()); - } - } - - GraphicComponent::applyAllCustomProperties(containerName); + GraphicComponent::applyAllCustomProperties(containerName); + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] Error detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + mainMessageBoxState = 1; + showMessageBox("Error: " + string(ex.what()), "Error detected", false); + } + + if (scenarioErrors.empty() == false) { + mainMessageBoxState = 1; + + string errorMsg = ""; + for (std::map::iterator iterMap = scenarioErrors.begin(); + iterMap != scenarioErrors.end(); ++iterMap) { + errorMsg += "scenario: " + iterMap->first + + " error text: " + iterMap->second.substr(0, 400) + "\n"; } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] Error detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - - mainMessageBoxState=1; - showMessageBox( "Error: " + string(ex.what()), "Error detected", false); - } - - if(scenarioErrors.empty() == false) { - mainMessageBoxState=1; - - string errorMsg = ""; - for(std::map::iterator iterMap = scenarioErrors.begin(); - iterMap != scenarioErrors.end(); ++iterMap) { - errorMsg += "scenario: " + iterMap->first + " error text: " + iterMap->second.substr(0,400) + "\n"; - } - showMessageBox( "Error loading scenario(s): " + errorMsg, "Error detected", false); - } + showMessageBox("Error loading scenario(s): " + errorMsg, "Error detected", + false); + } } void MenuStateScenario::reloadUI() { - Lang &lang= Lang::getInstance(); + Lang &lang = Lang::getInstance(); - console.resetFonts(); - mainMessageBox.init(lang.getString("Ok")); - labelInfo.setFont(CoreData::getInstance().getMenuFontNormal()); - labelInfo.setFont3D(CoreData::getInstance().getMenuFontNormal3D()); + console.resetFonts(); + mainMessageBox.init(lang.getString("Ok")); + labelInfo.setFont(CoreData::getInstance().getMenuFontNormal()); + labelInfo.setFont3D(CoreData::getInstance().getMenuFontNormal3D()); - labelScenarioName.setFont(CoreData::getInstance().getMenuFontNormal()); - labelScenarioName.setFont3D(CoreData::getInstance().getMenuFontNormal3D()); + labelScenarioName.setFont(CoreData::getInstance().getMenuFontNormal()); + labelScenarioName.setFont3D(CoreData::getInstance().getMenuFontNormal3D()); - buttonReturn.setText(lang.getString("Return")); - buttonPlayNow.setText(lang.getString("PlayNow")); + buttonReturn.setText(lang.getString("Return")); + buttonPlayNow.setText(lang.getString("PlayNow")); - labelScenario.setText(lang.getString("Scenario")); + labelScenario.setText(lang.getString("Scenario")); - GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); + GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); } -MenuStateScenario::~MenuStateScenario() { - cleanupPreviewTexture(); -} +MenuStateScenario::~MenuStateScenario() { cleanupPreviewTexture(); } void MenuStateScenario::cleanupPreviewTexture() { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] scenarioLogoTexture [%p]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,scenarioLogoTexture); - - if(scenarioLogoTexture != NULL) { - Renderer::getInstance().endTexture(rsGlobal, scenarioLogoTexture, false); - } - scenarioLogoTexture = NULL; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] scenarioLogoTexture [%p]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, scenarioLogoTexture); + + if (scenarioLogoTexture != NULL) { + Renderer::getInstance().endTexture(rsGlobal, scenarioLogoTexture, false); + } + scenarioLogoTexture = NULL; } void MenuStateScenario::mouseClick(int x, int y, MouseButton mouseButton) { - CoreData &coreData= CoreData::getInstance(); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - - if(mainMessageBox.getEnabled()){ - int button= 0; - if(mainMessageBox.mouseClick(x, y, button)) { - soundRenderer.playFx(coreData.getClickSoundA()); - if(button==0) { - mainMessageBox.setEnabled(false); - - if(scenarioFiles.empty() == true && mainMessageBoxState ==1) { - mainMenu->setState(new MenuStateNewGame(program, mainMenu)); - return; - } - } - } - return; - } - - if(buttonReturn.mouseClick(x,y)){ - soundRenderer.playFx(coreData.getClickSoundA()); - mainMenu->setState(new MenuStateNewGame(program, mainMenu)); - return; - } - else if(buttonPlayNow.mouseClick(x,y)){ - soundRenderer.playFx(coreData.getClickSoundC()); - launchGame(); - return; - } - else if(comboBoxScenario.mouseClick(x, y)){ - try { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] listBoxScenario.getSelectedItemIndex() = %d scenarioFiles.size() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,comboBoxScenario.getSelectedItemIndex(),(int)scenarioFiles.size()); - - if(comboBoxScenario.getItemCount() > 0 && comboBoxScenario.getSelectedItemIndex() >= 0 && comboBoxScenario.getSelectedItemIndex() < (int)scenarioFiles.size()) { - loadScenarioInfo(Scenario::getScenarioPath(dirList, scenarioFiles[comboBoxScenario.getSelectedItemIndex()]), &scenarioInfo); - labelInfo.setText(scenarioInfo.desc); - if(scenarioInfo.namei18n != "") { - labelScenarioName.setText(scenarioInfo.namei18n); - } - else { - labelScenarioName.setText(comboBoxScenario.getSelectedItem()); - } - } + CoreData &coreData = CoreData::getInstance(); + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + + if (mainMessageBox.getEnabled()) { + int button = 0; + if (mainMessageBox.mouseClick(x, y, button)) { + soundRenderer.playFx(coreData.getClickSoundA()); + if (button == 0) { + mainMessageBox.setEnabled(false); + + if (scenarioFiles.empty() == true && mainMessageBoxState == 1) { + mainMenu->setState(new MenuStateNewGame(program, mainMenu)); + return; } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] Error detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - - mainMessageBoxState=1; - showMessageBox( "Error: " + string(ex.what()), "Error detected", false); + } + } + return; + } + + if (buttonReturn.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundA()); + mainMenu->setState(new MenuStateNewGame(program, mainMenu)); + return; + } else if (buttonPlayNow.mouseClick(x, y)) { + soundRenderer.playFx(coreData.getClickSoundC()); + launchGame(); + return; + } else if (comboBoxScenario.mouseClick(x, y)) { + try { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] listBoxScenario.getSelectedItemIndex() = " + "%d scenarioFiles.size() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, comboBoxScenario.getSelectedItemIndex(), + (int)scenarioFiles.size()); + + if (comboBoxScenario.getItemCount() > 0 && + comboBoxScenario.getSelectedItemIndex() >= 0 && + comboBoxScenario.getSelectedItemIndex() < (int)scenarioFiles.size()) { + loadScenarioInfo( + Scenario::getScenarioPath( + dirList, + scenarioFiles[comboBoxScenario.getSelectedItemIndex()]), + &scenarioInfo); + labelInfo.setText(scenarioInfo.desc); + if (scenarioInfo.namei18n != "") { + labelScenarioName.setText(scenarioInfo.namei18n); + } else { + labelScenarioName.setText(comboBoxScenario.getSelectedItem()); } - } + } + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] Error detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + mainMessageBoxState = 1; + showMessageBox("Error: " + string(ex.what()), "Error detected", false); + } + } } -void MenuStateScenario::mouseMove(int x, int y, const MouseState *ms){ - - if (mainMessageBox.getEnabled()) { - mainMessageBox.mouseMove(x, y); - } - - if (ms->get(mbLeft)) { - comboBoxScenario.mouseDown(x, y); - } - if (comboBoxScenario.isDropDownShowing()) { - comboBoxScenario.mouseMove(x, y); - if(comboBoxScenario.getItemCount() > 0 && comboBoxScenario.getPreselectedItemIndex() >= 0 && comboBoxScenario.getPreselectedItemIndex() < (int)scenarioFiles.size()) { - loadScenarioInfo(Scenario::getScenarioPath(dirList, scenarioFiles[comboBoxScenario.getPreselectedItemIndex()]), &scenarioInfo); - labelInfo.setText(scenarioInfo.desc); - if (scenarioInfo.namei18n != "") { - labelScenarioName.setText(scenarioInfo.namei18n); - } else { - labelScenarioName.setText(comboBoxScenario.getPreselectedItem()); - } - } - } - - buttonReturn.mouseMove(x, y); - buttonPlayNow.mouseMove(x, y); +void MenuStateScenario::mouseMove(int x, int y, const MouseState *ms) { + + if (mainMessageBox.getEnabled()) { + mainMessageBox.mouseMove(x, y); + } + + if (ms->get(mbLeft)) { + comboBoxScenario.mouseDown(x, y); + } + if (comboBoxScenario.isDropDownShowing()) { + comboBoxScenario.mouseMove(x, y); + if (comboBoxScenario.getItemCount() > 0 && + comboBoxScenario.getPreselectedItemIndex() >= 0 && + comboBoxScenario.getPreselectedItemIndex() < + (int)scenarioFiles.size()) { + loadScenarioInfo( + Scenario::getScenarioPath( + dirList, + scenarioFiles[comboBoxScenario.getPreselectedItemIndex()]), + &scenarioInfo); + labelInfo.setText(scenarioInfo.desc); + if (scenarioInfo.namei18n != "") { + labelScenarioName.setText(scenarioInfo.namei18n); + } else { + labelScenarioName.setText(comboBoxScenario.getPreselectedItem()); + } + } + } + + buttonReturn.mouseMove(x, y); + buttonPlayNow.mouseMove(x, y); } -void MenuStateScenario::eventMouseWheel(int x, int y,int zDelta) { - comboBoxScenario.eventMouseWheel(x,y,zDelta); +void MenuStateScenario::eventMouseWheel(int x, int y, int zDelta) { + comboBoxScenario.eventMouseWheel(x, y, zDelta); } -void MenuStateScenario::render(){ +void MenuStateScenario::render() { - Renderer &renderer= Renderer::getInstance(); + Renderer &renderer = Renderer::getInstance(); - if(scenarioLogoTexture != NULL) { - renderer.renderTextureQuad(450,200,533,400,scenarioLogoTexture,1.0f); - //renderer.renderBackground(scenarioLogoTexture); - } + if (scenarioLogoTexture != NULL) { + renderer.renderTextureQuad(450, 200, 533, 400, scenarioLogoTexture, 1.0f); + // renderer.renderBackground(scenarioLogoTexture); + } - if(mainMessageBox.getEnabled()) { - renderer.renderMessageBox(&mainMessageBox); - } - else { - renderer.renderLabel(&labelInfo); - renderer.renderLabel(&labelScenarioName); + if (mainMessageBox.getEnabled()) { + renderer.renderMessageBox(&mainMessageBox); + } else { + renderer.renderLabel(&labelInfo); + renderer.renderLabel(&labelScenarioName); - renderer.renderLabel(&labelScenario); - renderer.renderComboBox(&comboBoxScenario); + renderer.renderLabel(&labelScenario); + renderer.renderComboBox(&comboBoxScenario); - renderer.renderButton(&buttonReturn); - renderer.renderButton(&buttonPlayNow); - } - renderer.renderConsole(&console); - if(program != NULL) program->renderProgramMsgBox(); + renderer.renderButton(&buttonReturn); + renderer.renderButton(&buttonPlayNow); + } + renderer.renderConsole(&console); + if (program != NULL) + program->renderProgramMsgBox(); } void MenuStateScenario::update() { - if(Config::getInstance().getBool("AutoTest")) { - AutoTest::getInstance().updateScenario(this); - return; - } - if(this->autoloadScenarioName != "") { - string scenarioPath = Scenario::getScenarioPath(dirList, this->autoloadScenarioName); - - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("[%s:%s] Line: %d this->autoloadScenarioName [%s] scenarioPath [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->autoloadScenarioName.c_str(),scenarioPath.c_str()); - printf("[%s:%s] Line: %d this->autoloadScenarioName [%s] scenarioPath [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->autoloadScenarioName.c_str(),scenarioPath.c_str()); - - loadScenarioInfo(scenarioPath, &scenarioInfo ); - //if(scenarioInfo.namei18n != "") { - // this->autoloadScenarioName = scenarioInfo.namei18n; - //} - //else { - this->autoloadScenarioName = formatString(this->autoloadScenarioName); - //} - - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("[%s:%s] Line: %d this->autoloadScenarioName [%s] scenarioPath [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->autoloadScenarioName.c_str(),scenarioPath.c_str()); - printf("[%s:%s] Line: %d this->autoloadScenarioName [%s] scenarioPath [%s] file [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->autoloadScenarioName.c_str(),scenarioPath.c_str(),scenarioInfo.file.c_str()); - - comboBoxScenario.setSelectedItem(this->autoloadScenarioName,false); - - if(comboBoxScenario.getSelectedItem() != this->autoloadScenarioName) { - mainMessageBoxState=1; - showMessageBox( "Could not find scenario name: " + this->autoloadScenarioName, "Scenario Missing", false); - this->autoloadScenarioName = ""; - } - else { - try { - this->autoloadScenarioName = ""; - if(comboBoxScenario.getItemCount() > 0 && comboBoxScenario.getSelectedItemIndex() >= 0 && - comboBoxScenario.getSelectedItemIndex() < (int)scenarioFiles.size()) { - - printf("[%s:%s] Line: %d scenarioFiles[listBoxScenario.getSelectedItemIndex()] [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,scenarioFiles[comboBoxScenario.getSelectedItemIndex()].c_str()); - - loadScenarioInfo(Scenario::getScenarioPath(dirList, scenarioFiles[comboBoxScenario.getSelectedItemIndex()]), &scenarioInfo); - - printf("[%s:%s] Line: %d scenarioInfo.file [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,scenarioInfo.file.c_str()); - - labelInfo.setText(scenarioInfo.desc); - if(scenarioInfo.namei18n != "") { - labelScenarioName.setText(scenarioInfo.namei18n); - } - else { - labelScenarioName.setText(comboBoxScenario.getSelectedItem()); - } - - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); - CoreData &coreData= CoreData::getInstance(); - soundRenderer.playFx(coreData.getClickSoundC()); - launchGame(); - return; - } - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] Error detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - - mainMessageBoxState=1; - showMessageBox( "Error: " + string(ex.what()), "Error detected", false); - } - } - } - - if(needToLoadTextures) { - // this delay is done to make it possible to switch faster - if(difftime(time(NULL), previewLoadDelayTimer) >= 2){ - loadScenarioPreviewTexture(); - needToLoadTextures= false; - } - } - console.update(); + if (Config::getInstance().getBool("AutoTest")) { + AutoTest::getInstance().updateScenario(this); + return; + } + if (this->autoloadScenarioName != "") { + string scenarioPath = + Scenario::getScenarioPath(dirList, this->autoloadScenarioName); + + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("[%s:%s] Line: %d + // this->autoloadScenarioName [%s] scenarioPath + // [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->autoloadScenarioName.c_str(),scenarioPath.c_str()); + printf( + "[%s:%s] Line: %d this->autoloadScenarioName [%s] scenarioPath [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + this->autoloadScenarioName.c_str(), scenarioPath.c_str()); + + loadScenarioInfo(scenarioPath, &scenarioInfo); + // if(scenarioInfo.namei18n != "") { + // this->autoloadScenarioName = scenarioInfo.namei18n; + // } + // else { + this->autoloadScenarioName = formatString(this->autoloadScenarioName); + //} + + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("[%s:%s] Line: %d + // this->autoloadScenarioName [%s] scenarioPath + // [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->autoloadScenarioName.c_str(),scenarioPath.c_str()); + printf("[%s:%s] Line: %d this->autoloadScenarioName [%s] scenarioPath [%s] " + "file [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->autoloadScenarioName.c_str(), scenarioPath.c_str(), + scenarioInfo.file.c_str()); + + comboBoxScenario.setSelectedItem(this->autoloadScenarioName, false); + + if (comboBoxScenario.getSelectedItem() != this->autoloadScenarioName) { + mainMessageBoxState = 1; + showMessageBox("Could not find scenario name: " + + this->autoloadScenarioName, + "Scenario Missing", false); + this->autoloadScenarioName = ""; + } else { + try { + this->autoloadScenarioName = ""; + if (comboBoxScenario.getItemCount() > 0 && + comboBoxScenario.getSelectedItemIndex() >= 0 && + comboBoxScenario.getSelectedItemIndex() < + (int)scenarioFiles.size()) { + + printf( + "[%s:%s] Line: %d " + "scenarioFiles[listBoxScenario.getSelectedItemIndex()] [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, + scenarioFiles[comboBoxScenario.getSelectedItemIndex()].c_str()); + + loadScenarioInfo( + Scenario::getScenarioPath( + dirList, + scenarioFiles[comboBoxScenario.getSelectedItemIndex()]), + &scenarioInfo); + + printf("[%s:%s] Line: %d scenarioInfo.file [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, scenarioInfo.file.c_str()); + + labelInfo.setText(scenarioInfo.desc); + if (scenarioInfo.namei18n != "") { + labelScenarioName.setText(scenarioInfo.namei18n); + } else { + labelScenarioName.setText(comboBoxScenario.getSelectedItem()); + } + + SoundRenderer &soundRenderer = SoundRenderer::getInstance(); + CoreData &coreData = CoreData::getInstance(); + soundRenderer.playFx(coreData.getClickSoundC()); + launchGame(); + return; + } + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] Error detected:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + mainMessageBoxState = 1; + showMessageBox("Error: " + string(ex.what()), "Error detected", false); + } + } + } + + if (needToLoadTextures) { + // this delay is done to make it possible to switch faster + if (difftime(time(NULL), previewLoadDelayTimer) >= 2) { + loadScenarioPreviewTexture(); + needToLoadTextures = false; + } + } + console.update(); } void MenuStateScenario::launchGame() { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] scenarioInfo.file [%s] [%s][%s][%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,scenarioInfo.file.c_str(),scenarioInfo.tilesetName.c_str(),scenarioInfo.mapName.c_str(),scenarioInfo.techTreeName.c_str()); - - if(scenarioInfo.file != "" && scenarioInfo.tilesetName != "" && scenarioInfo.mapName != "" && scenarioInfo.techTreeName != "") { - GameSettings gameSettings; - loadGameSettings(&scenarioInfo, &gameSettings); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] gameSettings.getScenarioDir() [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,gameSettings.getScenarioDir().c_str()); - - const vector pathTechList = Config::getInstance().getPathListForType(ptTechs,gameSettings.getScenarioDir()); - if(TechTree::exists(gameSettings.getTech(), pathTechList) == false) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Line ref: %d Error: cannot find techtree [%s]\n",__LINE__,scenarioInfo.techTreeName.c_str()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - - mainMessageBoxState=1; - showMessageBox( szBuf, "Error detected", false); - - return; - } - program->setState(new Game(program, &gameSettings, false)); - return; - } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] scenarioInfo.file [%s] [%s][%s][%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, scenarioInfo.file.c_str(), + scenarioInfo.tilesetName.c_str(), scenarioInfo.mapName.c_str(), + scenarioInfo.techTreeName.c_str()); + + if (scenarioInfo.file != "" && scenarioInfo.tilesetName != "" && + scenarioInfo.mapName != "" && scenarioInfo.techTreeName != "") { + GameSettings gameSettings; + loadGameSettings(&scenarioInfo, &gameSettings); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] gameSettings.getScenarioDir() [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, gameSettings.getScenarioDir().c_str()); + + const vector pathTechList = + Config::getInstance().getPathListForType(ptTechs, + gameSettings.getScenarioDir()); + if (TechTree::exists(gameSettings.getTech(), pathTechList) == false) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "Line ref: %d Error: cannot find techtree [%s]\n", + __LINE__, scenarioInfo.techTreeName.c_str()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + + mainMessageBoxState = 1; + showMessageBox(szBuf, "Error detected", false); + + return; + } + program->setState(new Game(program, &gameSettings, false)); + return; + } } void MenuStateScenario::setScenario(int i) { - comboBoxScenario.setSelectedItemIndex(i); - loadScenarioInfo(Scenario::getScenarioPath(dirList, scenarioFiles[comboBoxScenario.getSelectedItemIndex()]), &scenarioInfo); + comboBoxScenario.setSelectedItemIndex(i); + loadScenarioInfo( + Scenario::getScenarioPath( + dirList, scenarioFiles[comboBoxScenario.getSelectedItemIndex()]), + &scenarioInfo); } -void MenuStateScenario::loadScenarioInfo(string file, ScenarioInfo *scenarioInfo) { - bool isTutorial = Scenario::isGameTutorial(file); - if( file==""){ - scenarioInfo->desc="Error: scenario broken! Xml-File Not Found"; - return; - } - //printf("[%s:%s] Line: %d file [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,file.c_str()); - - Scenario::loadScenarioInfo(file, scenarioInfo, isTutorial); - - cleanupPreviewTexture(); - previewLoadDelayTimer=time(NULL); - needToLoadTextures=true; +void MenuStateScenario::loadScenarioInfo(string file, + ScenarioInfo *scenarioInfo) { + bool isTutorial = Scenario::isGameTutorial(file); + if (file == "") { + scenarioInfo->desc = "Error: scenario broken! Xml-File Not Found"; + return; + } + // printf("[%s:%s] Line: %d file + // [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,file.c_str()); + + Scenario::loadScenarioInfo(file, scenarioInfo, isTutorial); + + cleanupPreviewTexture(); + previewLoadDelayTimer = time(NULL); + needToLoadTextures = true; } -void MenuStateScenario::loadScenarioPreviewTexture(){ - if(enableScenarioTexturePreview == true) { - //if(listBoxScenario.getSelectedItemIndex() >= 0) { - if(comboBoxScenario.getItemCount() > 0 && comboBoxScenario.getSelectedItemIndex() >= 0 && comboBoxScenario.getSelectedItemIndex() < (int)scenarioFiles.size()) { - GameSettings gameSettings; - loadGameSettings(&scenarioInfo, &gameSettings); - - string scenarioLogo = ""; - bool loadingImageUsed = false; - - Game::extractScenarioLogoFile(&gameSettings, scenarioLogo, loadingImageUsed); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] scenarioLogo [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,scenarioLogo.c_str()); - - if(scenarioLogo != "") { - cleanupPreviewTexture(); - scenarioLogoTexture = Renderer::findTexture(scenarioLogo); - } - else { - cleanupPreviewTexture(); - scenarioLogoTexture = NULL; - } - } - } +void MenuStateScenario::loadScenarioPreviewTexture() { + if (enableScenarioTexturePreview == true) { + // if(listBoxScenario.getSelectedItemIndex() >= 0) { + if (comboBoxScenario.getItemCount() > 0 && + comboBoxScenario.getSelectedItemIndex() >= 0 && + comboBoxScenario.getSelectedItemIndex() < (int)scenarioFiles.size()) { + GameSettings gameSettings; + loadGameSettings(&scenarioInfo, &gameSettings); + + string scenarioLogo = ""; + bool loadingImageUsed = false; + + Game::extractScenarioLogoFile(&gameSettings, scenarioLogo, + loadingImageUsed); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] scenarioLogo [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, scenarioLogo.c_str()); + + if (scenarioLogo != "") { + cleanupPreviewTexture(); + scenarioLogoTexture = Renderer::findTexture(scenarioLogo); + } else { + cleanupPreviewTexture(); + scenarioLogoTexture = NULL; + } + } + } } -void MenuStateScenario::loadGameSettings(const ScenarioInfo *scenarioInfo, GameSettings *gameSettings){ - if(comboBoxScenario.getSelectedItemIndex() < 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"listBoxScenario.getSelectedItemIndex() < 0, = %d",comboBoxScenario.getSelectedItemIndex()); - throw megaglest_runtime_error(szBuf); - } - else if(comboBoxScenario.getSelectedItemIndex() >= (int)scenarioFiles.size()) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"listBoxScenario.getSelectedItemIndex() >= scenarioFiles.size(), = [%d][%d]",comboBoxScenario.getSelectedItemIndex(),(int)scenarioFiles.size()); - throw megaglest_runtime_error(szBuf); - } - - Scenario::loadGameSettings(dirList,scenarioInfo, gameSettings, formatString(scenarioFiles[comboBoxScenario.getSelectedItemIndex()])); +void MenuStateScenario::loadGameSettings(const ScenarioInfo *scenarioInfo, + GameSettings *gameSettings) { + if (comboBoxScenario.getSelectedItemIndex() < 0) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "listBoxScenario.getSelectedItemIndex() < 0, = %d", + comboBoxScenario.getSelectedItemIndex()); + throw megaglest_runtime_error(szBuf); + } else if (comboBoxScenario.getSelectedItemIndex() >= + (int)scenarioFiles.size()) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "listBoxScenario.getSelectedItemIndex() >= scenarioFiles.size(), " + "= [%d][%d]", + comboBoxScenario.getSelectedItemIndex(), + (int)scenarioFiles.size()); + throw megaglest_runtime_error(szBuf); + } + + Scenario::loadGameSettings( + dirList, scenarioInfo, gameSettings, + formatString(scenarioFiles[comboBoxScenario.getSelectedItemIndex()])); } -void MenuStateScenario::showMessageBox(const string &text, const string &header, bool toggle){ - if(!toggle){ - mainMessageBox.setEnabled(false); - } - - if(!mainMessageBox.getEnabled()){ - mainMessageBox.setText(text); - mainMessageBox.setHeader(header); - mainMessageBox.setEnabled(true); - } - else{ - mainMessageBox.setEnabled(false); - } +void MenuStateScenario::showMessageBox(const string &text, const string &header, + bool toggle) { + if (!toggle) { + mainMessageBox.setEnabled(false); + } + + if (!mainMessageBox.getEnabled()) { + mainMessageBox.setText(text); + mainMessageBox.setHeader(header); + mainMessageBox.setEnabled(true); + } else { + mainMessageBox.setEnabled(false); + } } void MenuStateScenario::keyDown(SDL_KeyboardEvent key) { - Config &configKeys = Config::getInstance(std::pair(cfgMainKeys,cfgUserKeys)); - if(isKeyPressed(configKeys.getSDLKey("SaveGUILayout"),key) == true) { - GraphicComponent::saveAllCustomProperties(containerName); - } + Config &configKeys = Config::getInstance( + std::pair(cfgMainKeys, cfgUserKeys)); + if (isKeyPressed(configKeys.getSDLKey("SaveGUILayout"), key) == true) { + GraphicComponent::saveAllCustomProperties(containerName); + } } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/menu/menu_state_scenario.h b/source/glest_game/menu/menu_state_scenario.h index 5a2a92449..a96dd1e71 100644 --- a/source/glest_game/menu/menu_state_scenario.h +++ b/source/glest_game/menu/menu_state_scenario.h @@ -12,76 +12,77 @@ #ifndef _GLEST_GAME_MENUSTATESCENARIO_H_ #define _GLEST_GAME_MENUSTATESCENARIO_H_ -#include "main_menu.h" #include "leak_dumper.h" +#include "main_menu.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // =============================== // class MenuStateScenario // =============================== -class MenuStateScenario: public MenuState { +class MenuStateScenario : public MenuState { private: + GraphicButton buttonReturn; + GraphicButton buttonPlayNow; - GraphicButton buttonReturn; - GraphicButton buttonPlayNow; - - GraphicLabel labelInfo; - GraphicLabel labelScenario; - GraphicComboBox comboBoxScenario; - GraphicLabel labelScenarioName; - + GraphicLabel labelInfo; + GraphicLabel labelScenario; + GraphicComboBox comboBoxScenario; + GraphicLabel labelScenarioName; - vector scenarioFiles; + vector scenarioFiles; - ScenarioInfo scenarioInfo; - vector dirList; + ScenarioInfo scenarioInfo; + vector dirList; - GraphicMessageBox mainMessageBox; - int mainMessageBoxState; + GraphicMessageBox mainMessageBox; + int mainMessageBoxState; - string autoloadScenarioName; + string autoloadScenarioName; - time_t previewLoadDelayTimer; - bool needToLoadTextures; + time_t previewLoadDelayTimer; + bool needToLoadTextures; - bool enableScenarioTexturePreview; - Texture2D *scenarioLogoTexture; + bool enableScenarioTexturePreview; + Texture2D *scenarioLogoTexture; - bool isTutorialMode; + bool isTutorialMode; public: - MenuStateScenario(Program *program, MainMenu *mainMenu, bool isTutorialMode, const vector &dirList, string autoloadScenarioName=""); - virtual ~MenuStateScenario(); + MenuStateScenario(Program *program, MainMenu *mainMenu, bool isTutorialMode, + const vector &dirList, + string autoloadScenarioName = ""); + virtual ~MenuStateScenario(); - void mouseClick(int x, int y, MouseButton mouseButton); - void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; - void mouseMove(int x, int y, const MouseState *mouseState); - void eventMouseWheel(int x, int y,int zDelta); - void render(); - void update(); + void mouseClick(int x, int y, MouseButton mouseButton); + void mouseDoubleClick(int x, int y, MouseButton mouseButton){}; + void mouseMove(int x, int y, const MouseState *mouseState); + void eventMouseWheel(int x, int y, int zDelta); + void render(); + void update(); - void launchGame(); - void setScenario(int i); - int getScenarioCount() const { return comboBoxScenario.getItemCount(); } + void launchGame(); + void setScenario(int i); + int getScenarioCount() const { return comboBoxScenario.getItemCount(); } - virtual void keyDown(SDL_KeyboardEvent key); + virtual void keyDown(SDL_KeyboardEvent key); - virtual void reloadUI(); + virtual void reloadUI(); private: - - void loadScenarioInfo(string file, ScenarioInfo *scenarioInfo); - void loadGameSettings(const ScenarioInfo *scenarioInfo, GameSettings *gameSettings); - void loadScenarioPreviewTexture(); - Difficulty computeDifficulty(const ScenarioInfo *scenarioInfo); - void showMessageBox(const string &text, const string &header, bool toggle); - - void cleanupPreviewTexture(); + void loadScenarioInfo(string file, ScenarioInfo *scenarioInfo); + void loadGameSettings(const ScenarioInfo *scenarioInfo, + GameSettings *gameSettings); + void loadScenarioPreviewTexture(); + Difficulty computeDifficulty(const ScenarioInfo *scenarioInfo); + void showMessageBox(const string &text, const string &header, bool toggle); + + void cleanupPreviewTexture(); }; - -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/menu/server_line.cpp b/source/glest_game/menu/server_line.cpp index 554c64f7d..2386062bb 100644 --- a/source/glest_game/menu/server_line.cpp +++ b/source/glest_game/menu/server_line.cpp @@ -9,15 +9,14 @@ // License, or (at your option) any later version // ============================================================== - #include "server_line.h" -#include "renderer.h" -#include "core_data.h" -#include "config.h" -#include "metrics.h" #include "auto_test.h" +#include "config.h" +#include "core_data.h" #include "masterserver_info.h" +#include "metrics.h" +#include "renderer.h" #include "leak_dumper.h" @@ -28,268 +27,289 @@ namespace Game { // class ServerLine // ===================================================== -ServerLine::ServerLine(MasterServerInfo *mServerInfo, int lineIndex, int baseY, int lineHeight, - const char * containerName){ - this->containerName= containerName; - this->countryTexture= NULL; - Lang &lang= Lang::getInstance(); - - this->lineHeight= lineHeight; - int lineOffset= lineHeight * lineIndex; - masterServerInfo= *mServerInfo; - int i= 5; - this->baseY= baseY; - Vec3f color=Vec3f(1.0f,1.0f,1.0f); - - if(masterServerInfo.getConnectedClients()==0){ - color=Vec3f(0.6f,0.7f,1.0f); - } - - - //general info: - //i+= 10; - glestVersionLabel.init(i, baseY - lineOffset); - glestVersionLabel.setRenderBackground(true); - glestVersionLabel.setMaxEditRenderWidth(970); // use background for whole line - glestVersionLabel.setTextColor(color); - glestVersionLabel.setText(" " + masterServerInfo.getGlestVersion()); - glestVersionLabel.setFont(CoreData::getInstance().getDisplayFontSmall()); - glestVersionLabel.setFont3D(CoreData::getInstance().getDisplayFontSmall3D()); - - i+= 80; - string platform=masterServerInfo.getPlatform(); - size_t revOffset = platform.find("-Rev"); - if(revOffset != platform.npos) { - platform = platform.substr(0,revOffset); - } - - platformLabel.init(i, baseY - lineOffset); - platformLabel.setTextColor(color); - platformLabel.setText(platform); - platformLabel.setFont(CoreData::getInstance().getDisplayFontSmall()); - platformLabel.setFont3D(CoreData::getInstance().getDisplayFontSmall3D()); - - // i+=50; - // registeredObjNameList.push_back("binaryCompileDateLabel" + intToStr(lineIndex)); - // binaryCompileDateLabel.registerGraphicComponent(containerName,"binaryCompileDateLabel" + intToStr(lineIndex)); - // binaryCompileDateLabel.init(i,baseY-lineOffset); - // binaryCompileDateLabel.setText(masterServerInfo.getBinaryCompileDate()); - - //game info: - i+= 120; - serverTitleLabel.init(i, baseY - lineOffset); - serverTitleLabel.setTextColor(color); - serverTitleLabel.setText(masterServerInfo.getServerTitle()); - - i+= 170; - country.init(i, baseY - lineOffset); - country.setTextColor(color); - country.setText(masterServerInfo.getCountry()); - - string data_path= getGameReadWritePath(GameConstants::path_data_CacheLookupKey); - string countryLogoPath= data_path + "data/core/misc_textures/flags"; - - Config &config= Config::getInstance(); - if(config.getString("CountryTexturePath", "") != ""){ - countryLogoPath = config.getString("CountryTexturePath", ""); - } - endPathWithSlash(countryLogoPath); - - string logoFile= countryLogoPath + toLower(masterServerInfo.getCountry()) + ".png"; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] logoFile [%s]\n",__FILE__,__FUNCTION__,__LINE__,logoFile.c_str()); - - if(fileExists(logoFile) == true){ - countryTexture= GraphicsInterface::getInstance().getFactory()->newTexture2D(); - //loadingTexture = renderer.newTexture2D(rsGlobal); - countryTexture->setMipmap(true); - //loadingTexture->getPixmap()->load(filepath); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] logoFile [%s]\n",__FILE__,__FUNCTION__,__LINE__,logoFile.c_str()); - countryTexture->load(logoFile); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - Renderer &renderer= Renderer::getInstance(); - renderer.initTexture(rsGlobal, countryTexture); - } - - i+= 60; - // ipAddressLabel.init(i,baseY-lineOffset); - // ipAddressLabel.setText(masterServerInfo.getIpAddress()); - // i+=100; - - wrongVersionLabel.init(i, baseY - lineOffset); - wrongVersionLabel.setTextColor(Vec3f(1.0f,0.0f,0.0f)); - wrongVersionLabel.setText(lang.getString("IncompatibleVersion")); - - //game setup info: - techLabel.init(i, baseY - lineOffset); - techLabel.setTextColor(color); - techLabel.setText(masterServerInfo.getTech()); - - i+= 130; - mapLabel.init(i, baseY - lineOffset); - mapLabel.setTextColor(color); - mapLabel.setText(masterServerInfo.getMap()); - i+= 130; - - // tilesetLabel.init(i,baseY-lineOffset); - // tilesetLabel.setText(masterServerInfo.getTileset()); - // i+=100; - - activeSlotsLabel.init(i, baseY - lineOffset); - activeSlotsLabel.setTextColor(color); - activeSlotsLabel.setText(intToStr(masterServerInfo.getActiveSlots()) + "/" + intToStr( - masterServerInfo.getNetworkSlots()) + "/" + intToStr(masterServerInfo.getConnectedClients())); - - i+= 50; - //externalConnectPort.init(i, baseY - lineOffset); - //externalConnectPort.setTextColor(color); - //externalConnectPort.setText(intToStr(masterServerInfo.getExternalConnectPort())); - - i+= 30; - status.init(i-10, baseY - lineOffset); - status.setTextColor(color); - status.setText(lang.getString("MGGameStatus" + intToStr(masterServerInfo.getStatus()))); - - i+= 130; - selectButton.init(i+25, baseY - lineOffset, 35, lineHeight - 5); - selectButton.setText(">"); - selectButton.setAlwaysLighted(true); - - //printf("glestVersionString [%s] masterServerInfo->getGlestVersion() [%s]\n",glestVersionString.c_str(),masterServerInfo->getGlestVersion().c_str()); - compatible= checkVersionComptability(glestVersionString, masterServerInfo.getGlestVersion()); - selectButton.setEnabled(compatible); - selectButton.setEditable(compatible); - +ServerLine::ServerLine(MasterServerInfo *mServerInfo, int lineIndex, int baseY, + int lineHeight, const char *containerName) { + this->containerName = containerName; + this->countryTexture = NULL; + Lang &lang = Lang::getInstance(); + + this->lineHeight = lineHeight; + int lineOffset = lineHeight * lineIndex; + masterServerInfo = *mServerInfo; + int i = 5; + this->baseY = baseY; + Vec3f color = Vec3f(1.0f, 1.0f, 1.0f); + + if (masterServerInfo.getConnectedClients() == 0) { + color = Vec3f(0.6f, 0.7f, 1.0f); + } + + // general info: + // i+= 10; + glestVersionLabel.init(i, baseY - lineOffset); + glestVersionLabel.setRenderBackground(true); + glestVersionLabel.setMaxEditRenderWidth(970); // use background for whole line + glestVersionLabel.setTextColor(color); + glestVersionLabel.setText(" " + masterServerInfo.getGlestVersion()); + glestVersionLabel.setFont(CoreData::getInstance().getDisplayFontSmall()); + glestVersionLabel.setFont3D(CoreData::getInstance().getDisplayFontSmall3D()); + + i += 80; + string platform = masterServerInfo.getPlatform(); + size_t revOffset = platform.find("-Rev"); + if (revOffset != platform.npos) { + platform = platform.substr(0, revOffset); + } + + platformLabel.init(i, baseY - lineOffset); + platformLabel.setTextColor(color); + platformLabel.setText(platform); + platformLabel.setFont(CoreData::getInstance().getDisplayFontSmall()); + platformLabel.setFont3D(CoreData::getInstance().getDisplayFontSmall3D()); + + // i+=50; + // registeredObjNameList.push_back("binaryCompileDateLabel" + + // intToStr(lineIndex)); + // binaryCompileDateLabel.registerGraphicComponent(containerName,"binaryCompileDateLabel" + //+ intToStr(lineIndex)); binaryCompileDateLabel.init(i,baseY-lineOffset); + // binaryCompileDateLabel.setText(masterServerInfo.getBinaryCompileDate()); + + // game info: + i += 120; + serverTitleLabel.init(i, baseY - lineOffset); + serverTitleLabel.setTextColor(color); + serverTitleLabel.setText(masterServerInfo.getServerTitle()); + + i += 170; + country.init(i, baseY - lineOffset); + country.setTextColor(color); + country.setText(masterServerInfo.getCountry()); + + string data_path = + getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + string countryLogoPath = data_path + "data/core/misc_textures/flags"; + + Config &config = Config::getInstance(); + if (config.getString("CountryTexturePath", "") != "") { + countryLogoPath = config.getString("CountryTexturePath", ""); + } + endPathWithSlash(countryLogoPath); + + string logoFile = + countryLogoPath + toLower(masterServerInfo.getCountry()) + ".png"; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] logoFile [%s]\n", __FILE__, + __FUNCTION__, __LINE__, logoFile.c_str()); + + if (fileExists(logoFile) == true) { + countryTexture = + GraphicsInterface::getInstance().getFactory()->newTexture2D(); + // loadingTexture = renderer.newTexture2D(rsGlobal); + countryTexture->setMipmap(true); + // loadingTexture->getPixmap()->load(filepath); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] logoFile [%s]\n", __FILE__, + __FUNCTION__, __LINE__, logoFile.c_str()); + countryTexture->load(logoFile); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + Renderer &renderer = Renderer::getInstance(); + renderer.initTexture(rsGlobal, countryTexture); + } + + i += 60; + // ipAddressLabel.init(i,baseY-lineOffset); + // ipAddressLabel.setText(masterServerInfo.getIpAddress()); + // i+=100; + + wrongVersionLabel.init(i, baseY - lineOffset); + wrongVersionLabel.setTextColor(Vec3f(1.0f, 0.0f, 0.0f)); + wrongVersionLabel.setText(lang.getString("IncompatibleVersion")); + + // game setup info: + techLabel.init(i, baseY - lineOffset); + techLabel.setTextColor(color); + techLabel.setText(masterServerInfo.getTech()); + + i += 130; + mapLabel.init(i, baseY - lineOffset); + mapLabel.setTextColor(color); + mapLabel.setText(masterServerInfo.getMap()); + i += 130; + + // tilesetLabel.init(i,baseY-lineOffset); + // tilesetLabel.setText(masterServerInfo.getTileset()); + // i+=100; + + activeSlotsLabel.init(i, baseY - lineOffset); + activeSlotsLabel.setTextColor(color); + activeSlotsLabel.setText(intToStr(masterServerInfo.getActiveSlots()) + "/" + + intToStr(masterServerInfo.getNetworkSlots()) + "/" + + intToStr(masterServerInfo.getConnectedClients())); + + i += 50; + // externalConnectPort.init(i, baseY - lineOffset); + // externalConnectPort.setTextColor(color); + // externalConnectPort.setText(intToStr(masterServerInfo.getExternalConnectPort())); + + i += 30; + status.init(i - 10, baseY - lineOffset); + status.setTextColor(color); + status.setText( + lang.getString("MGGameStatus" + intToStr(masterServerInfo.getStatus()))); + + i += 130; + selectButton.init(i + 25, baseY - lineOffset, 35, lineHeight - 5); + selectButton.setText(">"); + selectButton.setAlwaysLighted(true); + + // printf("glestVersionString [%s] masterServerInfo->getGlestVersion() + // [%s]\n",glestVersionString.c_str(),masterServerInfo->getGlestVersion().c_str()); + compatible = checkVersionComptability(glestVersionString, + masterServerInfo.getGlestVersion()); + selectButton.setEnabled(compatible); + selectButton.setEditable(compatible); } void ServerLine::reloadUI() { - Lang &lang= Lang::getInstance(); + Lang &lang = Lang::getInstance(); - glestVersionLabel.setText(masterServerInfo.getGlestVersion()); + glestVersionLabel.setText(masterServerInfo.getGlestVersion()); - string platform = masterServerInfo.getPlatform(); - size_t revOffset = platform.find("-Rev"); - if(revOffset != platform.npos) { - platform = platform.substr(0,revOffset); - } + string platform = masterServerInfo.getPlatform(); + size_t revOffset = platform.find("-Rev"); + if (revOffset != platform.npos) { + platform = platform.substr(0, revOffset); + } - platformLabel.setText(platform); + platformLabel.setText(platform); - serverTitleLabel.setText(masterServerInfo.getServerTitle()); + serverTitleLabel.setText(masterServerInfo.getServerTitle()); - country.setText(masterServerInfo.getCountry()); + country.setText(masterServerInfo.getCountry()); - wrongVersionLabel.setText(lang.getString("IncompatibleVersion")); + wrongVersionLabel.setText(lang.getString("IncompatibleVersion")); - techLabel.setText(masterServerInfo.getTech()); + techLabel.setText(masterServerInfo.getTech()); - mapLabel.setText(masterServerInfo.getMap()); - activeSlotsLabel.setText(intToStr(masterServerInfo.getActiveSlots()) + "/" + intToStr( - masterServerInfo.getNetworkSlots()) + "/" + intToStr(masterServerInfo.getConnectedClients())); + mapLabel.setText(masterServerInfo.getMap()); + activeSlotsLabel.setText(intToStr(masterServerInfo.getActiveSlots()) + "/" + + intToStr(masterServerInfo.getNetworkSlots()) + "/" + + intToStr(masterServerInfo.getConnectedClients())); - //externalConnectPort.setText(intToStr(masterServerInfo.getExternalConnectPort())); + // externalConnectPort.setText(intToStr(masterServerInfo.getExternalConnectPort())); - status.setText(lang.getString("MGGameStatus" + intToStr(masterServerInfo.getStatus()))); + status.setText( + lang.getString("MGGameStatus" + intToStr(masterServerInfo.getStatus()))); - GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); + GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName); } -ServerLine::~ServerLine(){ - //delete masterServerInfo; +ServerLine::~ServerLine() { + // delete masterServerInfo; - if(countryTexture != NULL){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (countryTexture != NULL) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); - countryTexture->end(); - delete countryTexture; + countryTexture->end(); + delete countryTexture; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); - //delete loadingTexture; - countryTexture= NULL; - } + // delete loadingTexture; + countryTexture = NULL; + } } -bool ServerLine::buttonMouseClick(int x, int y){ - return selectButton.mouseClick(x, y); +bool ServerLine::buttonMouseClick(int x, int y) { + return selectButton.mouseClick(x, y); } -bool ServerLine::buttonMouseMove(int x, int y){ - return selectButton.mouseMove(x, y); +bool ServerLine::buttonMouseMove(int x, int y) { + return selectButton.mouseMove(x, y); } -void ServerLine::render(){ - Renderer &renderer= Renderer::getInstance(); - //general info: - renderer.renderLabel(&glestVersionLabel); - renderer.renderLabel(&platformLabel); - //renderer.renderLabel(&binaryCompileDateLabel); - - - //game info: - renderer.renderLabel(&serverTitleLabel); - if(countryTexture != NULL){ - renderer.renderTextureQuad(country.getX()+1, country.getY()+4, countryTexture->getTextureWidth(), - countryTexture->getTextureHeight(), countryTexture, 0.7f); - } - else{ - renderer.renderLabel(&country); - } - if(compatible){ - if(selectButton.getEnabled() == true){ - //renderer.renderLabel(&ipAddressLabel); - //game setup info: - renderer.renderLabel(&techLabel); - renderer.renderLabel(&mapLabel); - //renderer.renderLabel(&tilesetLabel); - renderer.renderLabel(&activeSlotsLabel); - //renderer.renderLabel(&externalConnectPort); - renderer.renderLabel(&status); - } - } - else{ - renderer.renderLabel(&wrongVersionLabel); - } - renderer.renderLabel(&status); - - bool joinEnabled= (masterServerInfo.getNetworkSlots() > masterServerInfo.getConnectedClients()); - if(joinEnabled == true){ - if(compatible){ - selectButton.setEnabled(true); - selectButton.setVisible(true); - renderer.renderButton(&selectButton); - } - } - else{ - selectButton.setEnabled(false); - selectButton.setVisible(false); - } +void ServerLine::render() { + Renderer &renderer = Renderer::getInstance(); + // general info: + renderer.renderLabel(&glestVersionLabel); + renderer.renderLabel(&platformLabel); + // renderer.renderLabel(&binaryCompileDateLabel); + + // game info: + renderer.renderLabel(&serverTitleLabel); + if (countryTexture != NULL) { + renderer.renderTextureQuad(country.getX() + 1, country.getY() + 4, + countryTexture->getTextureWidth(), + countryTexture->getTextureHeight(), + countryTexture, 0.7f); + } else { + renderer.renderLabel(&country); + } + if (compatible) { + if (selectButton.getEnabled() == true) { + // renderer.renderLabel(&ipAddressLabel); + // game setup info: + renderer.renderLabel(&techLabel); + renderer.renderLabel(&mapLabel); + // renderer.renderLabel(&tilesetLabel); + renderer.renderLabel(&activeSlotsLabel); + // renderer.renderLabel(&externalConnectPort); + renderer.renderLabel(&status); + } + } else { + renderer.renderLabel(&wrongVersionLabel); + } + renderer.renderLabel(&status); + + bool joinEnabled = (masterServerInfo.getNetworkSlots() > + masterServerInfo.getConnectedClients()); + if (joinEnabled == true) { + if (compatible) { + selectButton.setEnabled(true); + selectButton.setVisible(true); + renderer.renderButton(&selectButton); + } + } else { + selectButton.setEnabled(false); + selectButton.setVisible(false); + } } -void ServerLine::setY(int y){ - selectButton.setY(y); - - //general info: - glestVersionLabel.setY(y); - platformLabel.setY(y); - //binaryCompileDateLabel.setY(y); +void ServerLine::setY(int y) { + selectButton.setY(y); - //game info: - serverTitleLabel.setY(y); - country.setY(y); - status.setY(y); - //ipAddressLabel.setY(y); + // general info: + glestVersionLabel.setY(y); + platformLabel.setY(y); + // binaryCompileDateLabel.setY(y); - //game setup info: - techLabel.setY(y); - mapLabel.setY(y); - //tilesetLabel.setY(y); - activeSlotsLabel.setY(y); + // game info: + serverTitleLabel.setY(y); + country.setY(y); + status.setY(y); + // ipAddressLabel.setY(y); - //externalConnectPort.setY(y); + // game setup info: + techLabel.setY(y); + mapLabel.setY(y); + // tilesetLabel.setY(y); + activeSlotsLabel.setY(y); + // externalConnectPort.setY(y); } -} -}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/menu/server_line.h b/source/glest_game/menu/server_line.h index 841b1b637..24a336cca 100644 --- a/source/glest_game/menu/server_line.h +++ b/source/glest_game/menu/server_line.h @@ -13,18 +13,19 @@ #define _GLEST_GAME_SERVERLINE_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include "masterserver_info.h" #include "components.h" #include "lang.h" +#include "masterserver_info.h" #include "world.h" #include "leak_dumper.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // =============================== // ServerLine @@ -32,52 +33,53 @@ namespace Glest{ namespace Game{ class ServerLine { private: + MasterServerInfo masterServerInfo; + int lineHeight; + int baseY; + bool compatible; + GraphicButton selectButton; + GraphicLabel wrongVersionLabel; - MasterServerInfo masterServerInfo; - int lineHeight; - int baseY; - bool compatible; - GraphicButton selectButton; - GraphicLabel wrongVersionLabel; - - //general info: - GraphicLabel glestVersionLabel; - GraphicLabel platformLabel; - //GraphicLabel binaryCompileDateLabel; + // general info: + GraphicLabel glestVersionLabel; + GraphicLabel platformLabel; + // GraphicLabel binaryCompileDateLabel; - //game info: - GraphicLabel serverTitleLabel; - GraphicLabel ipAddressLabel; + // game info: + GraphicLabel serverTitleLabel; + GraphicLabel ipAddressLabel; - //game setup info: - GraphicLabel techLabel; - GraphicLabel mapLabel; - GraphicLabel tilesetLabel; - GraphicLabel activeSlotsLabel; + // game setup info: + GraphicLabel techLabel; + GraphicLabel mapLabel; + GraphicLabel tilesetLabel; + GraphicLabel activeSlotsLabel; - GraphicLabel externalConnectPort; + GraphicLabel externalConnectPort; - GraphicLabel country; - GraphicLabel status; + GraphicLabel country; + GraphicLabel status; - Texture2D *countryTexture; + Texture2D *countryTexture; - const char * containerName; + const char *containerName; public: - ServerLine( MasterServerInfo *mServerInfo, int lineIndex, int baseY, int lineHeight, const char *containerName); - virtual ~ServerLine(); - MasterServerInfo *getMasterServerInfo() {return &masterServerInfo;} - const int getLineHeight() const {return lineHeight;} - bool buttonMouseClick(int x, int y); - bool buttonMouseMove(int x, int y); - void setY(int y); - //void setIndex(int value); - void render(); - - virtual void reloadUI(); + ServerLine(MasterServerInfo *mServerInfo, int lineIndex, int baseY, + int lineHeight, const char *containerName); + virtual ~ServerLine(); + MasterServerInfo *getMasterServerInfo() { return &masterServerInfo; } + const int getLineHeight() const { return lineHeight; } + bool buttonMouseClick(int x, int y); + bool buttonMouseMove(int x, int y); + void setY(int y); + // void setIndex(int value); + void render(); + + virtual void reloadUI(); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/network/client_interface.cpp b/source/glest_game/network/client_interface.cpp index f7e14d2dd..52e085303 100644 --- a/source/glest_game/network/client_interface.cpp +++ b/source/glest_game/network/client_interface.cpp @@ -14,14 +14,13 @@ #include "logger.h" #include "window.h" -#include "platform_util.h" -#include "game_util.h" -#include "conversion.h" #include "config.h" +#include "conversion.h" +#include "game_util.h" #include "lang.h" -#include "config.h" -#include +#include "platform_util.h" #include +#include #include "leak_dumper.h" @@ -35,145 +34,185 @@ using namespace Shared::Util; #endif -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { const bool debugClientInterfacePerf = false; -const int ClientInterface::messageWaitTimeout = 10000; //10 seconds -const int ClientInterface::waitSleepTime = 10; -const int ClientInterface::maxNetworkCommandListSendTimeWait = 5; +const int ClientInterface::messageWaitTimeout = 10000; // 10 seconds +const int ClientInterface::waitSleepTime = 10; +const int ClientInterface::maxNetworkCommandListSendTimeWait = 5; // ===================================================== // class ClientInterfaceThread // ===================================================== -ClientInterfaceThread::ClientInterfaceThread(ClientInterface *client) : BaseThread() { - this->clientInterface = client; - this->uniqueID = "ClientInterfaceThread"; +ClientInterfaceThread::ClientInterfaceThread(ClientInterface *client) + : BaseThread() { + this->clientInterface = client; + this->uniqueID = "ClientInterfaceThread"; } ClientInterfaceThread::~ClientInterfaceThread() { - this->clientInterface = NULL; + this->clientInterface = NULL; } void ClientInterfaceThread::setQuitStatus(bool value) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d value = %d\n",__FILE__,__FUNCTION__,__LINE__,value); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s] Line: %d value = %d\n", __FILE__, + __FUNCTION__, __LINE__, value); - BaseThread::setQuitStatus(value); + BaseThread::setQuitStatus(value); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] Line: %d\n", + __FILE__, __FUNCTION__, __LINE__); } bool ClientInterfaceThread::canShutdown(bool deleteSelfIfShutdownDelayed) { - bool ret = (getExecutingTask() == false); - if(ret == false && deleteSelfIfShutdownDelayed == true) { - setDeleteSelfOnExecutionDone(deleteSelfIfShutdownDelayed); - deleteSelfIfRequired(); - signalQuit(); - } - - return ret; + bool ret = (getExecutingTask() == false); + if (ret == false && deleteSelfIfShutdownDelayed == true) { + setDeleteSelfOnExecutionDone(deleteSelfIfShutdownDelayed); + deleteSelfIfRequired(); + signalQuit(); + } + + return ret; } void ClientInterfaceThread::execute() { - RunningStatusSafeWrapper runningStatus(this); - try { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] ****************** STARTING worker thread this = %p\n",__FILE__,__FUNCTION__,__LINE__,this); - - // Set socket to non blocking - if(clientInterface != NULL && clientInterface->getSocket(true) != NULL) { - clientInterface->getSocket(true)->setBlock(false); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("ClientInterfaceThread::exec Line: %d\n",__LINE__); - - time_t clientSimulationLagStartTime = 0; - Chrono chrono; - for(;this->clientInterface != NULL;) { - - if(getQuitStatus() == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - break; - } - - ExecutingTaskSafeWrapper safeExecutingTaskMutex(this); - - if(debugClientInterfacePerf == true) printf("START === Client thread\n"); - - //printf("ClientInterfaceThread::exec Line: %d\n",__LINE__); - - uint64 loopCount = 0; - if(debugClientInterfacePerf == true) { - chrono.start(); - } - while( this->getQuitStatus() == false && - clientInterface != NULL) { - //printf("ClientInterfaceThread::exec Line: %d this->getQuitStatus(): %d\n",__LINE__,this->getQuitStatus()); - - // START: Test simulating lag for the client - int simulateLag = Config::getInstance().getInt("SimulateClientLag","0"); - if(simulateLag > 0) { - if(clientSimulationLagStartTime == 0) { - clientSimulationLagStartTime = time(NULL); - } - if(difftime((long int)time(NULL),clientSimulationLagStartTime) <= Config::getInstance().getInt("SimulateClientLagDurationSeconds","0")) { - sleep(simulateLag); - } - } - // END: Test simulating lag for the client - - clientInterface->updateNetworkFrame(); - - //printf("ClientInterfaceThread::exec Line: %d this->getQuitStatus(): %d\n",__LINE__,this->getQuitStatus()); - - if(debugClientInterfacePerf == true) { - loopCount++; - if(chrono.getMillis() >= 1000) { - printf("Client thread loopCount = %llu\n",(long long unsigned int)loopCount); - - loopCount = 0; - //sleep(0); - chrono.start(); - } - } - } - - if(debugClientInterfacePerf == true) { - printf("END === Client thread\n"); - } - - //printf("ClientInterfaceThread::exec Line: %d\n",__LINE__); - - if(getQuitStatus() == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - break; - } - - //printf("ClientInterfaceThread::exec Line: %d\n",__LINE__); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("ClientInterfaceThread::exec Line: %d\n",__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] ****************** ENDING worker thread this = %p\n",__FILE__,__FUNCTION__,__LINE__,this); - } - catch(const exception &ex) { - - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(clientInterface == NULL || clientInterface->getSocket(true) == NULL || clientInterface->getSocket(true)->isConnected() == true) { - throw megaglest_runtime_error(ex.what()); - } - } - catch(...) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] UNKNOWN error\n",__FILE__,__FUNCTION__,__LINE__); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - throw megaglest_runtime_error(szBuf); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); + RunningStatusSafeWrapper runningStatus(this); + try { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] ****************** STARTING worker thread " + "this = %p\n", + __FILE__, __FUNCTION__, __LINE__, this); + + // Set socket to non blocking + if (clientInterface != NULL && clientInterface->getSocket(true) != NULL) { + clientInterface->getSocket(true)->setBlock(false); + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("ClientInterfaceThread::exec Line: %d\n", __LINE__); + + time_t clientSimulationLagStartTime = 0; + Chrono chrono; + for (; this->clientInterface != NULL;) { + + if (getQuitStatus() == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + break; + } + + ExecutingTaskSafeWrapper safeExecutingTaskMutex(this); + + if (debugClientInterfacePerf == true) + printf("START === Client thread\n"); + + // printf("ClientInterfaceThread::exec Line: %d\n",__LINE__); + + uint64 loopCount = 0; + if (debugClientInterfacePerf == true) { + chrono.start(); + } + while (this->getQuitStatus() == false && clientInterface != NULL) { + // printf("ClientInterfaceThread::exec Line: %d this->getQuitStatus(): + // %d\n",__LINE__,this->getQuitStatus()); + + // START: Test simulating lag for the client + int simulateLag = + Config::getInstance().getInt("SimulateClientLag", "0"); + if (simulateLag > 0) { + if (clientSimulationLagStartTime == 0) { + clientSimulationLagStartTime = time(NULL); + } + if (difftime((long int)time(NULL), clientSimulationLagStartTime) <= + Config::getInstance().getInt("SimulateClientLagDurationSeconds", + "0")) { + sleep(simulateLag); + } + } + // END: Test simulating lag for the client + + clientInterface->updateNetworkFrame(); + + // printf("ClientInterfaceThread::exec Line: %d this->getQuitStatus(): + // %d\n",__LINE__,this->getQuitStatus()); + + if (debugClientInterfacePerf == true) { + loopCount++; + if (chrono.getMillis() >= 1000) { + printf("Client thread loopCount = %llu\n", + (long long unsigned int)loopCount); + + loopCount = 0; + // sleep(0); + chrono.start(); + } + } + } + + if (debugClientInterfacePerf == true) { + printf("END === Client thread\n"); + } + + // printf("ClientInterfaceThread::exec Line: %d\n",__LINE__); + + if (getQuitStatus() == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + break; + } + + // printf("ClientInterfaceThread::exec Line: %d\n",__LINE__); + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("ClientInterfaceThread::exec Line: %d\n", __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] ****************** ENDING worker thread " + "this = %p\n", + __FILE__, __FUNCTION__, __LINE__, this); + } catch (const exception &ex) { + + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", __FILE__, + __FUNCTION__, __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + if (clientInterface == NULL || clientInterface->getSocket(true) == NULL || + clientInterface->getSocket(true)->isConnected() == true) { + throw megaglest_runtime_error(ex.what()); + } + } catch (...) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] UNKNOWN error\n", __FILE__, + __FUNCTION__, __LINE__); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + throw megaglest_runtime_error(szBuf); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] Line: %d\n", + __FILE__, __FUNCTION__, __LINE__); } // ===================================================== @@ -181,2111 +220,2942 @@ void ClientInterfaceThread::execute() { // ===================================================== ClientInterface::ClientInterface() : GameNetworkInterface() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] constructor for %p\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this); - - networkCommandListThreadAccessor = new Mutex(CODE_AT_LINE); - networkCommandListThread = NULL; - cachedPendingCommandsIndex = 0; - cachedLastPendingFrameCount = 0; - timeClientWaitedForLastMessage = 0; - - flagAccessor = new Mutex(CODE_AT_LINE); - - clientSocket = NULL; - sessionKey = 0; - launchGame = false; - introDone = false; - - this->joinGameInProgress = false; - this->joinGameInProgressLaunch = false; - this->readyForInGameJoin = false; - this->resumeInGameJoin = false; - - quitThreadAccessor = new Mutex(CODE_AT_LINE); - setQuitThread(false); - - playerIndex = -1; - gameSettingsReceivedCount = 0; - setGameSettingsReceived(false); - gameSettingsReceivedCount = 0; - connectedTime = 0; - port = 0; - serverFTPPort = 0; - - gotIntro = false; - lastNetworkCommandListSendTime = 0; - currentFrameCount = 0; - lastSentFrameCount = 0; - clientSimulationLagStartTime = 0; - - networkGameDataSynchCheckOkMap = false; - networkGameDataSynchCheckOkTile = false; - networkGameDataSynchCheckOkTech = false; - this->setNetworkGameDataSynchCheckTechMismatchReport(""); - this->setReceivedDataSynchCheck(false); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] constructor for %p\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, this); + + networkCommandListThreadAccessor = new Mutex(CODE_AT_LINE); + networkCommandListThread = NULL; + cachedPendingCommandsIndex = 0; + cachedLastPendingFrameCount = 0; + timeClientWaitedForLastMessage = 0; + + flagAccessor = new Mutex(CODE_AT_LINE); + + clientSocket = NULL; + sessionKey = 0; + launchGame = false; + introDone = false; + + this->joinGameInProgress = false; + this->joinGameInProgressLaunch = false; + this->readyForInGameJoin = false; + this->resumeInGameJoin = false; + + quitThreadAccessor = new Mutex(CODE_AT_LINE); + setQuitThread(false); + + playerIndex = -1; + gameSettingsReceivedCount = 0; + setGameSettingsReceived(false); + gameSettingsReceivedCount = 0; + connectedTime = 0; + port = 0; + serverFTPPort = 0; + + gotIntro = false; + lastNetworkCommandListSendTime = 0; + currentFrameCount = 0; + lastSentFrameCount = 0; + clientSimulationLagStartTime = 0; + + networkGameDataSynchCheckOkMap = false; + networkGameDataSynchCheckOkTile = false; + networkGameDataSynchCheckOkTech = false; + this->setNetworkGameDataSynchCheckTechMismatchReport(""); + this->setReceivedDataSynchCheck(false); } -void ClientInterface::shutdownNetworkCommandListThread(MutexSafeWrapper &safeMutexWrapper) { - if(networkCommandListThread != NULL) { - //printf("START === shutdownNetworkCommandListThread\n"); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n",__FUNCTION__,__LINE__); - - setQuitThread(true); - networkCommandListThread->signalQuit(); - safeMutexWrapper.ReleaseLock(true); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n",__FUNCTION__,__LINE__); - - Chrono chronoElapsed(true); - for(;chronoElapsed.getMillis() <= 10000;) { - safeMutexWrapper.Lock(); - if(networkCommandListThread != NULL && - networkCommandListThread->canShutdown(false) == false && - networkCommandListThread->getRunningStatus() == true) { - - safeMutexWrapper.ReleaseLock(true); - if(chronoElapsed.getMillis() % 1000 == 0) { - sleep(1); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n",__FUNCTION__,__LINE__); - } - } - else { - safeMutexWrapper.ReleaseLock(true); - break; - } - //printf("%s Line: %d\n",__FUNCTION__,__LINE__); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n chronoElapsed.getMillis(): %lld",__FUNCTION__,__LINE__,(long long int)chronoElapsed.getMillis()); - //printf("A === shutdownNetworkCommandListThread\n"); - - safeMutexWrapper.Lock(); - if(networkCommandListThread != NULL && - networkCommandListThread->canShutdown(true)) { - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n",__FUNCTION__,__LINE__); - - delete networkCommandListThread; - networkCommandListThread = NULL; - } - else { - networkCommandListThread = NULL; - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n",__FUNCTION__,__LINE__); - //printf("END === shutdownNetworkCommandListThread\n"); - } +void ClientInterface::shutdownNetworkCommandListThread( + MutexSafeWrapper &safeMutexWrapper) { + if (networkCommandListThread != NULL) { + // printf("START === shutdownNetworkCommandListThread\n"); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("%s Line: %d\n", __FUNCTION__, __LINE__); + + setQuitThread(true); + networkCommandListThread->signalQuit(); + safeMutexWrapper.ReleaseLock(true); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("%s Line: %d\n", __FUNCTION__, __LINE__); + + Chrono chronoElapsed(true); + for (; chronoElapsed.getMillis() <= 10000;) { + safeMutexWrapper.Lock(); + if (networkCommandListThread != NULL && + networkCommandListThread->canShutdown(false) == false && + networkCommandListThread->getRunningStatus() == true) { + + safeMutexWrapper.ReleaseLock(true); + if (chronoElapsed.getMillis() % 1000 == 0) { + sleep(1); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("%s Line: %d\n", __FUNCTION__, __LINE__); + } + } else { + safeMutexWrapper.ReleaseLock(true); + break; + } + // printf("%s Line: %d\n",__FUNCTION__,__LINE__); + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("%s Line: %d\n chronoElapsed.getMillis(): %lld", __FUNCTION__, + __LINE__, (long long int)chronoElapsed.getMillis()); + // printf("A === shutdownNetworkCommandListThread\n"); + + safeMutexWrapper.Lock(); + if (networkCommandListThread != NULL && + networkCommandListThread->canShutdown(true)) { + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("%s Line: %d\n", __FUNCTION__, __LINE__); + + delete networkCommandListThread; + networkCommandListThread = NULL; + } else { + networkCommandListThread = NULL; + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("%s Line: %d\n", __FUNCTION__, __LINE__); + // printf("END === shutdownNetworkCommandListThread\n"); + } } ClientInterface::~ClientInterface() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] destructor for %p\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this); - //printf("START === Client destructor\n"); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] destructor for %p\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, this); + // printf("START === Client destructor\n"); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n",__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("%s Line: %d\n", __FUNCTION__, __LINE__); - MutexSafeWrapper safeMutex(networkCommandListThreadAccessor,CODE_AT_LINE); + MutexSafeWrapper safeMutex(networkCommandListThreadAccessor, CODE_AT_LINE); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n",__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("%s Line: %d\n", __FUNCTION__, __LINE__); - shutdownNetworkCommandListThread(safeMutex); - //printf("A === Client destructor\n"); + shutdownNetworkCommandListThread(safeMutex); + // printf("A === Client destructor\n"); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n",__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("%s Line: %d\n", __FUNCTION__, __LINE__); - if(clientSocket != NULL && - clientSocket->isConnected() == true) { + if (clientSocket != NULL && clientSocket->isConnected() == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n",__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("%s Line: %d\n", __FUNCTION__, __LINE__); - Lang &lang= Lang::getInstance(); - const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); - for(unsigned int langIndex = 0; langIndex < languageList.size(); ++langIndex) { + Lang &lang = Lang::getInstance(); + const vector languageList = + this->gameSettings.getUniqueNetworkPlayerLanguages(); + for (unsigned int langIndex = 0; langIndex < languageList.size(); + ++langIndex) { - string sQuitText = "has chosen to leave the game!"; - if(lang.hasString("PlayerLeftGame",languageList[langIndex]) == true) { - sQuitText = lang.getString("PlayerLeftGame",languageList[langIndex]); - } + string sQuitText = "has chosen to leave the game!"; + if (lang.hasString("PlayerLeftGame", languageList[langIndex]) == true) { + sQuitText = lang.getString("PlayerLeftGame", languageList[langIndex]); + } - if(clientSocket != NULL && clientSocket->isConnected() == true) { - sendTextMessage(sQuitText,-1,false,languageList[langIndex]); - } - } + if (clientSocket != NULL && clientSocket->isConnected() == true) { + sendTextMessage(sQuitText, -1, false, languageList[langIndex]); + } } + } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n",__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("%s Line: %d\n", __FUNCTION__, __LINE__); - //printf("B === Client destructor\n"); + // printf("B === Client destructor\n"); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); - close(false); + close(false); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n",__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("%s Line: %d\n", __FUNCTION__, __LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n",__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("%s Line: %d\n", __FUNCTION__, __LINE__); - //printf("C === Client destructor\n"); + // printf("C === Client destructor\n"); - networkCommandListThreadAccessor = NULL; - safeMutex.ReleaseLock(false,true); + networkCommandListThreadAccessor = NULL; + safeMutex.ReleaseLock(false, true); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n",__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("%s Line: %d\n", __FUNCTION__, __LINE__); - delete flagAccessor; - flagAccessor = NULL; - //printf("END === Client destructor\n"); + delete flagAccessor; + flagAccessor = NULL; + // printf("END === Client destructor\n"); - delete quitThreadAccessor; - quitThreadAccessor = NULL; + delete quitThreadAccessor; + quitThreadAccessor = NULL; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n",__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("%s Line: %d\n", __FUNCTION__, __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); } bool ClientInterface::getQuitThread() { - MutexSafeWrapper safeMutex(quitThreadAccessor,CODE_AT_LINE); - return this->quitThread; + MutexSafeWrapper safeMutex(quitThreadAccessor, CODE_AT_LINE); + return this->quitThread; } void ClientInterface::setQuitThread(bool value) { - MutexSafeWrapper safeMutex(quitThreadAccessor,CODE_AT_LINE); - this->quitThread = value; + MutexSafeWrapper safeMutex(quitThreadAccessor, CODE_AT_LINE); + this->quitThread = value; } bool ClientInterface::getQuit() { - MutexSafeWrapper safeMutex(quitThreadAccessor,CODE_AT_LINE); - return this->quit; + MutexSafeWrapper safeMutex(quitThreadAccessor, CODE_AT_LINE); + return this->quit; } void ClientInterface::setQuit(bool value) { - MutexSafeWrapper safeMutex(quitThreadAccessor,CODE_AT_LINE); - this->quit = value; + MutexSafeWrapper safeMutex(quitThreadAccessor, CODE_AT_LINE); + this->quit = value; } bool ClientInterface::getJoinGameInProgress() { - MutexSafeWrapper safeMutex(flagAccessor,CODE_AT_LINE); - return joinGameInProgress; + MutexSafeWrapper safeMutex(flagAccessor, CODE_AT_LINE); + return joinGameInProgress; } bool ClientInterface::getJoinGameInProgressLaunch() { - MutexSafeWrapper safeMutex(flagAccessor,CODE_AT_LINE); - return joinGameInProgressLaunch; + MutexSafeWrapper safeMutex(flagAccessor, CODE_AT_LINE); + return joinGameInProgressLaunch; } bool ClientInterface::getReadyForInGameJoin() { - MutexSafeWrapper safeMutex(flagAccessor,CODE_AT_LINE); - return readyForInGameJoin; + MutexSafeWrapper safeMutex(flagAccessor, CODE_AT_LINE); + return readyForInGameJoin; } bool ClientInterface::getResumeInGameJoin() { - MutexSafeWrapper safeMutex(flagAccessor,CODE_AT_LINE); - return resumeInGameJoin; + MutexSafeWrapper safeMutex(flagAccessor, CODE_AT_LINE); + return resumeInGameJoin; } void ClientInterface::connect(const Ip &ip, int port) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] START\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, "In [%s::%s] START\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__); - this->ip = ip; - this->port = port; + this->ip = ip; + this->port = port; - MutexSafeWrapper safeMutex(networkCommandListThreadAccessor,CODE_AT_LINE); - shutdownNetworkCommandListThread(safeMutex); + MutexSafeWrapper safeMutex(networkCommandListThreadAccessor, CODE_AT_LINE); + shutdownNetworkCommandListThread(safeMutex); - delete clientSocket; - clientSocket = NULL; + delete clientSocket; + clientSocket = NULL; - safeMutex.ReleaseLock(); + safeMutex.ReleaseLock(); - clientSocket = new ClientSocket(); - clientSocket->setBlock(false); - clientSocket->connect(ip, port); - connectedTime = time(NULL); - //clientSocket->setBlock(true); + clientSocket = new ClientSocket(); + clientSocket->setBlock(false); + clientSocket->connect(ip, port); + connectedTime = time(NULL); + // clientSocket->setBlock(true); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] END - socket = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,clientSocket->getSocketId()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s] END - socket = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, clientSocket->getSocketId()); } void ClientInterface::reset() { - if(getSocket() != NULL) { - Lang &lang= Lang::getInstance(); - const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); - for(unsigned int langIndex = 0; langIndex < languageList.size(); ++langIndex) { - - string sQuitText = "has chosen to leave the game!"; - if(lang.hasString("PlayerLeftGame",languageList[langIndex]) == true) { - sQuitText = lang.getString("PlayerLeftGame",languageList[langIndex]); - } - sendTextMessage(sQuitText,-1,false,languageList[langIndex]); - } - close(); + if (getSocket() != NULL) { + Lang &lang = Lang::getInstance(); + const vector languageList = + this->gameSettings.getUniqueNetworkPlayerLanguages(); + for (unsigned int langIndex = 0; langIndex < languageList.size(); + ++langIndex) { + + string sQuitText = "has chosen to leave the game!"; + if (lang.hasString("PlayerLeftGame", languageList[langIndex]) == true) { + sQuitText = lang.getString("PlayerLeftGame", languageList[langIndex]); + } + sendTextMessage(sQuitText, -1, false, languageList[langIndex]); } + close(); + } } void ClientInterface::update() { - bool wasConnected = this->isConnected(); - if(gotIntro == true && - wasConnected == false) { - string playerNameStr = getHumanPlayerName(); - - Lang &lang= Lang::getInstance(); - - char szBuf1[8096]=""; - string statusTextFormat= lang.getString("PlayerDisconnected"); - snprintf(szBuf1,8096,statusTextFormat.c_str(),playerNameStr.c_str()); - - DisplayErrorMessage(szBuf1); - setQuit(true); - return; - } - - try { - NetworkMessageCommandList networkMessageCommandList(currentFrameCount); - for(int index = 0; index < GameConstants::maxPlayers; ++index) { - networkMessageCommandList.setNetworkPlayerFactionCRC(index,this->getNetworkPlayerFactionCRC(index)); - } - - //send as many commands as we can - while(requestedCommands.empty() == false) { - if(networkMessageCommandList.addCommand(&requestedCommands.back())) { - requestedCommands.pop_back(); - } - else { - break; - } - } - - double lastSendElapsed = difftime((long int)time(NULL),lastNetworkCommandListSendTime); - - // If we are on a frame that should send packets or we have commands - // to send now, send it now. - if((currentFrameCount >= this->gameSettings.getNetworkFramePeriod() && - currentFrameCount % this->gameSettings.getNetworkFramePeriod() == 0) || - networkMessageCommandList.getCommandCount() > 0) { - - if(lastSentFrameCount < currentFrameCount || - networkMessageCommandList.getCommandCount() > 0) { - - lastSentFrameCount = currentFrameCount; - sendMessage(&networkMessageCommandList); - - lastNetworkCommandListSendTime = time(NULL); - lastSendElapsed = 0; - } - } - - // If we have not sent anything for maxNetworkCommandListSendTimeWait - // seconds, send one now. - if(lastNetworkCommandListSendTime > 0 && - lastSendElapsed >= ClientInterface::maxNetworkCommandListSendTimeWait) { - - lastSentFrameCount = currentFrameCount; - sendMessage(&networkMessageCommandList); - lastNetworkCommandListSendTime = time(NULL); - } - - // Possible cause of out of synch since we have more commands that need - // to be sent in this frame - if(requestedCommands.empty() == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] WARNING / ERROR, requestedCommands.size() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,requestedCommands.size()); - - string sMsg = "may go out of synch: client requestedCommands.size() = " + intToStr(requestedCommands.size()); - sendTextMessage(sMsg,-1, true,""); - sleep(1); - } - } - catch(const megaglest_runtime_error &ex) { - SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - - if(this->isConnected() == false) { - if(gotIntro == false || wasConnected == false) { - string sErr = string(extractFileFromDirectoryPath(__FILE__).c_str()) + "::" + string(__FUNCTION__) + " network error: " + string(ex.what()); - DisplayErrorMessage(sErr); - } - - setQuit(true); - } - else { - throw megaglest_runtime_error(ex.what()); - } - } -} + bool wasConnected = this->isConnected(); + if (gotIntro == true && wasConnected == false) { + string playerNameStr = getHumanPlayerName(); -std::string ClientInterface::getIpAddress(bool mutexLock) { - string result = ""; - //MutexSafeWrapper safeMutexSlot((mutexLock == true ? mutexSocket : NULL),CODE_AT_LINE); - if(clientSocket != NULL) { - result = clientSocket->getIpAddress(); - } - return result; -} + Lang &lang = Lang::getInstance(); -std::string ClientInterface::getServerIpAddress() { - return this->ip.getString(); -} + char szBuf1[8096] = ""; + string statusTextFormat = lang.getString("PlayerDisconnected"); + snprintf(szBuf1, 8096, statusTextFormat.c_str(), playerNameStr.c_str()); -void ClientInterface::updateLobby() { - Chrono chrono; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); + DisplayErrorMessage(szBuf1); + setQuit(true); + return; + } - NetworkMessageType networkMessageType = getNextMessageType(); + try { + NetworkMessageCommandList networkMessageCommandList(currentFrameCount); + for (int index = 0; index < GameConstants::maxPlayers; ++index) { + networkMessageCommandList.setNetworkPlayerFactionCRC( + index, this->getNetworkPlayerFactionCRC(index)); + } - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - switch(networkMessageType) - { - case nmtInvalid: - break; - - case nmtIntro: - { - NetworkMessageIntro networkMessageIntro; - if(receiveMessage(&networkMessageIntro)) { - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - gotIntro = true; - sessionKey = networkMessageIntro.getSessionId(); - versionString = networkMessageIntro.getVersionString(); - playerIndex = networkMessageIntro.getPlayerIndex(); - serverName = networkMessageIntro.getName(); - serverUUID = networkMessageIntro.getPlayerUUID(); - serverPlatform = networkMessageIntro.getPlayerPlatform(); - serverFTPPort = networkMessageIntro.getFtpPort(); - - if(playerIndex < 0 || playerIndex >= GameConstants::maxPlayers) { - throw megaglest_runtime_error("playerIndex < 0 || playerIndex >= GameConstants::maxPlayers"); - } - - MutexSafeWrapper safeMutexFlags(flagAccessor,CODE_AT_LINE); - this->joinGameInProgress = (networkMessageIntro.getGameInProgress() != 0); - this->joinGameInProgressLaunch = false; - safeMutexFlags.ReleaseLock(); - - //printf("Client got intro playerIndex = %d\n",playerIndex); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] got NetworkMessageIntro, networkMessageIntro.getGameState() = %d, versionString [%s], sessionKey = %d, playerIndex = %d, serverFTPPort = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageIntro.getGameState(),versionString.c_str(),sessionKey,playerIndex,serverFTPPort); - - //check consistency - bool compatible = checkVersionComptability(networkMessageIntro.getVersionString(), getNetworkVersionGITString()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] got NetworkMessageIntro, networkMessageIntro.getGameState() = %d, versionString [%s], sessionKey = %d, playerIndex = %d, serverFTPPort = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageIntro.getGameState(),versionString.c_str(),sessionKey,playerIndex,serverFTPPort); - - if(compatible == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - bool versionMatched = false; - string platformFreeVersion = getNetworkPlatformFreeVersionString(); - string sErr = ""; - - if(strncmp(platformFreeVersion.c_str(),networkMessageIntro.getVersionString().c_str(),strlen(platformFreeVersion.c_str())) != 0) { - string playerNameStr = getHumanPlayerName(); - sErr = "Server and client binary mismatch!\nYou have to use the exactly same binaries!\n\nServer: " + networkMessageIntro.getVersionString() + - "\nClient: " + getNetworkVersionGITString() + " player [" + playerNameStr + "]"; - printf("%s\n",sErr.c_str()); - - sendTextMessage("Server and client binary mismatch!!",-1, true,""); - sendTextMessage(" Server:" + networkMessageIntro.getVersionString(),-1, true,""); - sendTextMessage(" Client: "+ getNetworkVersionGITString(),-1, true,""); - sendTextMessage(" Client player [" + playerNameStr + "]",-1, true,""); - } - else { - versionMatched = true; - string playerNameStr = getHumanPlayerName(); - sErr = "Warning, Server and client are using the same version but different platforms.\n\nServer: " + networkMessageIntro.getVersionString() + - "\nClient: " + getNetworkVersionGITString() + " player [" + playerNameStr + "]"; - //printf("%s\n",sErr.c_str()); - } - - // error message and disconnect only if checked - if(Config::getInstance().getBool("PlatformConsistencyChecks","true") && - versionMatched == false) { - - DisplayErrorMessage(sErr); - sleep(1); - - setQuit(true); - close(); - return; - } - } + // send as many commands as we can + while (requestedCommands.empty() == false) { + if (networkMessageCommandList.addCommand(&requestedCommands.back())) { + requestedCommands.pop_back(); + } else { + break; + } + } - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); + double lastSendElapsed = + difftime((long int)time(NULL), lastNetworkCommandListSendTime); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // If we are on a frame that should send packets or we have commands + // to send now, send it now. + if ((currentFrameCount >= this->gameSettings.getNetworkFramePeriod() && + currentFrameCount % this->gameSettings.getNetworkFramePeriod() == 0) || + networkMessageCommandList.getCommandCount() > 0) { - if(networkMessageIntro.getGameState() == nmgstOk) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (lastSentFrameCount < currentFrameCount || + networkMessageCommandList.getCommandCount() > 0) { - //send intro message - Lang &lang= Lang::getInstance(); - NetworkMessageIntro sendNetworkMessageIntro( - sessionKey,getNetworkVersionGITString(), - getHumanPlayerName(), - -1, - nmgstOk, - this->getSocket()->getConnectedIPAddress(), - serverFTPPort, - lang.getLanguage(), - networkMessageIntro.getGameInProgress(), - Config::getInstance().getString("PlayerId",""), - getPlatformNameString()); - sendMessage(&sendNetworkMessageIntro); + lastSentFrameCount = currentFrameCount; + sendMessage(&networkMessageCommandList); - //printf("Got intro sending client details to server\n"); + lastNetworkCommandListSendTime = time(NULL); + lastSendElapsed = 0; + } + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // If we have not sent anything for maxNetworkCommandListSendTimeWait + // seconds, send one now. + if (lastNetworkCommandListSendTime > 0 && + lastSendElapsed >= ClientInterface::maxNetworkCommandListSendTimeWait) { - if(clientSocket == NULL || - clientSocket->isConnected() == false) { + lastSentFrameCount = currentFrameCount; + sendMessage(&networkMessageCommandList); + lastNetworkCommandListSendTime = time(NULL); + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // Possible cause of out of synch since we have more commands that need + // to be sent in this frame + if (requestedCommands.empty() == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] WARNING / ERROR, " + "requestedCommands.size() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, + requestedCommands.size()); + + string sMsg = "may go out of synch: client requestedCommands.size() = " + + intToStr(requestedCommands.size()); + sendTextMessage(sMsg, -1, true, ""); + sleep(1); + } + } catch (const megaglest_runtime_error &ex) { + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + + if (this->isConnected() == false) { + if (gotIntro == false || wasConnected == false) { + string sErr = string(extractFileFromDirectoryPath(__FILE__).c_str()) + + "::" + string(__FUNCTION__) + + " network error: " + string(ex.what()); + DisplayErrorMessage(sErr); + } + + setQuit(true); + } else { + throw megaglest_runtime_error(ex.what()); + } + } +} - string sErr = "Disconnected from server during intro handshake."; - DisplayErrorMessage(sErr); - setQuit(true); - close(); +std::string ClientInterface::getIpAddress(bool mutexLock) { + string result = ""; + // MutexSafeWrapper safeMutexSlot((mutexLock == true ? mutexSocket : + // NULL),CODE_AT_LINE); + if (clientSocket != NULL) { + result = clientSocket->getIpAddress(); + } + return result; +} - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - return; - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +std::string ClientInterface::getServerIpAddress() { + return this->ip.getString(); +} - introDone = true; - } - } - else if(networkMessageIntro.getGameState() == nmgstNoSlots) { - string sErr = "Cannot join the server because there are no open slots for new players."; - DisplayErrorMessage(sErr); - setQuit(true); - close(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - return; - } - else { - string sErr = "Unknown response from server: " + intToStr(networkMessageIntro.getGameState()); - DisplayErrorMessage(sErr); - setQuit(true); - close(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - return; - } - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - } +void ClientInterface::updateLobby() { + Chrono chrono; + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) + chrono.start(); + + NetworkMessageType networkMessageType = getNextMessageType(); + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + switch (networkMessageType) { + case nmtInvalid: + break; + + case nmtIntro: { + NetworkMessageIntro networkMessageIntro; + if (receiveMessage(&networkMessageIntro)) { + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + gotIntro = true; + sessionKey = networkMessageIntro.getSessionId(); + versionString = networkMessageIntro.getVersionString(); + playerIndex = networkMessageIntro.getPlayerIndex(); + serverName = networkMessageIntro.getName(); + serverUUID = networkMessageIntro.getPlayerUUID(); + serverPlatform = networkMessageIntro.getPlayerPlatform(); + serverFTPPort = networkMessageIntro.getFtpPort(); + + if (playerIndex < 0 || playerIndex >= GameConstants::maxPlayers) { + throw megaglest_runtime_error( + "playerIndex < 0 || playerIndex >= GameConstants::maxPlayers"); + } + + MutexSafeWrapper safeMutexFlags(flagAccessor, CODE_AT_LINE); + this->joinGameInProgress = (networkMessageIntro.getGameInProgress() != 0); + this->joinGameInProgressLaunch = false; + safeMutexFlags.ReleaseLock(); + + // printf("Client got intro playerIndex = %d\n",playerIndex); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] got NetworkMessageIntro, " + "networkMessageIntro.getGameState() = %d, versionString [%s], " + "sessionKey = %d, playerIndex = %d, serverFTPPort = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, networkMessageIntro.getGameState(), versionString.c_str(), + sessionKey, playerIndex, serverFTPPort); + + // check consistency + bool compatible = checkVersionComptability( + networkMessageIntro.getVersionString(), getNetworkVersionGITString()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] got NetworkMessageIntro, " + "networkMessageIntro.getGameState() = %d, versionString [%s], " + "sessionKey = %d, playerIndex = %d, serverFTPPort = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, networkMessageIntro.getGameState(), versionString.c_str(), + sessionKey, playerIndex, serverFTPPort); + + if (compatible == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + bool versionMatched = false; + string platformFreeVersion = getNetworkPlatformFreeVersionString(); + string sErr = ""; + + if (strncmp(platformFreeVersion.c_str(), + networkMessageIntro.getVersionString().c_str(), + strlen(platformFreeVersion.c_str())) != 0) { + string playerNameStr = getHumanPlayerName(); + sErr = "Server and client binary mismatch!\nYou have to use the " + "exactly same binaries!\n\nServer: " + + networkMessageIntro.getVersionString() + + "\nClient: " + getNetworkVersionGITString() + " player [" + + playerNameStr + "]"; + printf("%s\n", sErr.c_str()); + + sendTextMessage("Server and client binary mismatch!!", -1, true, ""); + sendTextMessage(" Server:" + networkMessageIntro.getVersionString(), + -1, true, ""); + sendTextMessage(" Client: " + getNetworkVersionGITString(), -1, true, + ""); + sendTextMessage(" Client player [" + playerNameStr + "]", -1, true, + ""); + } else { + versionMatched = true; + string playerNameStr = getHumanPlayerName(); + sErr = "Warning, Server and client are using the same version but " + "different platforms.\n\nServer: " + + networkMessageIntro.getVersionString() + + "\nClient: " + getNetworkVersionGITString() + " player [" + + playerNameStr + "]"; + // printf("%s\n",sErr.c_str()); } - break; - case nmtPing: - { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] got nmtPing\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); + // error message and disconnect only if checked + if (Config::getInstance().getBool("PlatformConsistencyChecks", + "true") && + versionMatched == false) { - NetworkMessagePing networkMessagePing; - if(receiveMessage(&networkMessagePing)) { - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); + DisplayErrorMessage(sErr); + sleep(1); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - this->setLastPingInfo(networkMessagePing); - } - } - break; - - case nmtSynchNetworkGameData: - { - NetworkMessageSynchNetworkGameData networkMessageSynchNetworkGameData; - - if(receiveMessage(&networkMessageSynchNetworkGameData)) { - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] got NetworkMessageSynchNetworkGameData, getTechCRCFileCount() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageSynchNetworkGameData.getTechCRCFileCount()); + setQuit(true); + close(); + return; + } + } + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (networkMessageIntro.getGameState() == nmgstOk) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + // send intro message + Lang &lang = Lang::getInstance(); + NetworkMessageIntro sendNetworkMessageIntro( + sessionKey, getNetworkVersionGITString(), getHumanPlayerName(), -1, + nmgstOk, this->getSocket()->getConnectedIPAddress(), serverFTPPort, + lang.getLanguage(), networkMessageIntro.getGameInProgress(), + Config::getInstance().getString("PlayerId", ""), + getPlatformNameString()); + sendMessage(&sendNetworkMessageIntro); + + // printf("Got intro sending client details to server\n"); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + if (clientSocket == NULL || clientSocket->isConnected() == false) { + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + string sErr = "Disconnected from server during intro handshake."; + DisplayErrorMessage(sErr); + setQuit(true); + close(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + return; + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + introDone = true; + } + } else if (networkMessageIntro.getGameState() == nmgstNoSlots) { + string sErr = "Cannot join the server because there are no open slots " + "for new players."; + DisplayErrorMessage(sErr); + setQuit(true); + close(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + return; + } else { + string sErr = "Unknown response from server: " + + intToStr(networkMessageIntro.getGameState()); + DisplayErrorMessage(sErr); + setQuit(true); + close(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + return; + } + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + } + } break; + + case nmtPing: { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] got nmtPing\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__); + + NetworkMessagePing networkMessagePing; + if (receiveMessage(&networkMessagePing)) { + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + this->setLastPingInfo(networkMessagePing); + } + } break; + + case nmtSynchNetworkGameData: { + NetworkMessageSynchNetworkGameData networkMessageSynchNetworkGameData; + + if (receiveMessage(&networkMessageSynchNetworkGameData)) { + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] got NetworkMessageSynchNetworkGameData, " + "getTechCRCFileCount() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, networkMessageSynchNetworkGameData.getTechCRCFileCount()); + + this->setLastPingInfoToNow(); + + networkGameDataSynchCheckOkMap = false; + networkGameDataSynchCheckOkTile = false; + networkGameDataSynchCheckOkTech = false; + this->setNetworkGameDataSynchCheckTechMismatchReport(""); + this->setReceivedDataSynchCheck(false); + + uint32 tilesetCRC = 0; + uint32 techCRC = 0; + uint32 mapCRC = 0; + vector> vctFileList; + + try { + Config &config = Config::getInstance(); + string scenarioDir = ""; + if (gameSettings.getScenarioDir() != "") { + + scenarioDir = gameSettings.getScenarioDir(); + if (EndsWith(scenarioDir, ".xml") == true) { + scenarioDir = scenarioDir.erase(scenarioDir.size() - 4, 4); + scenarioDir = scenarioDir.erase( + scenarioDir.size() - gameSettings.getScenario().size(), + gameSettings.getScenario().size() + 1); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] gameSettings.getScenarioDir() = [%s] " + "gameSettings.getScenario() = [%s] scenarioDir = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, gameSettings.getScenarioDir().c_str(), + gameSettings.getScenario().c_str(), scenarioDir.c_str()); + } - this->setLastPingInfoToNow(); + // check the checksum's + tilesetCRC = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTilesets, scenarioDir), + string("/") + networkMessageSynchNetworkGameData.getTileset() + + string("/*"), + ".xml", NULL); + + this->setNetworkGameDataSynchCheckOkTile( + (tilesetCRC == networkMessageSynchNetworkGameData.getTilesetCRC())); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] tilesetCRC info, local = %d, remote = %d, " + "networkMessageSynchNetworkGameData.getTileset() = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, tilesetCRC, + networkMessageSynchNetworkGameData.getTilesetCRC(), + networkMessageSynchNetworkGameData.getTileset().c_str()); + + // tech, load before map because of resources + techCRC = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTechs, scenarioDir), + string("/") + networkMessageSynchNetworkGameData.getTech() + + string("/*"), + ".xml", NULL); + + this->setNetworkGameDataSynchCheckOkTech( + (techCRC == networkMessageSynchNetworkGameData.getTechCRC())); + + if (this->getNetworkGameDataSynchCheckOkTech() == false) { + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + string pathSearchString = + "/" + networkMessageSynchNetworkGameData.getTech() + "/*"; + vctFileList = getFolderTreeContentsCheckSumListRecursively( + config.getPathListForType(ptTechs, scenarioDir), pathSearchString, + ".xml", NULL); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + string report = + networkMessageSynchNetworkGameData.getTechCRCFileMismatchReport( + vctFileList); + this->setNetworkGameDataSynchCheckTechMismatchReport(report); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s] techCRC info, local = %d, remote = %d, " + "networkMessageSynchNetworkGameData.getTech() = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + techCRC, networkMessageSynchNetworkGameData.getTechCRC(), + networkMessageSynchNetworkGameData.getTech().c_str()); + + // map + Checksum checksum; + string file = Config::getMapPath( + networkMessageSynchNetworkGameData.getMap(), scenarioDir, false); + if (file != "") { + checksum.addFile(file); + mapCRC = checksum.getSum(); + } + this->setNetworkGameDataSynchCheckOkMap( + (mapCRC == networkMessageSynchNetworkGameData.getMapCRC())); + this->setReceivedDataSynchCheck(true); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] mapCRC info, local = %d, remote = %d, file " + "= [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, mapCRC, networkMessageSynchNetworkGameData.getMapCRC(), + file.c_str()); + } catch (const runtime_error &ex) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + string sErr = ex.what(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] error during processing, sErr = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, sErr.c_str()); + + DisplayErrorMessage(sErr); + } + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + NetworkMessageSynchNetworkGameDataStatus + sendNetworkMessageSynchNetworkGameDataStatus(mapCRC, tilesetCRC, + techCRC, vctFileList); + sendMessage(&sendNetworkMessageSynchNetworkGameDataStatus); + } + } break; + + case nmtSynchNetworkGameDataFileCRCCheck: { + NetworkMessageSynchNetworkGameDataFileCRCCheck + networkMessageSynchNetworkGameDataFileCRCCheck; + if (receiveMessage(&networkMessageSynchNetworkGameDataFileCRCCheck)) { + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + this->setLastPingInfoToNow(); + + Checksum checksum; + string file = + networkMessageSynchNetworkGameDataFileCRCCheck.getFileName(); + checksum.addFile(file); + uint32 fileCRC = checksum.getSum(); + + if (fileCRC != + networkMessageSynchNetworkGameDataFileCRCCheck.getFileCRC()) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s] got nmtSynchNetworkGameDataFileCRCCheck localCRC = " + "%d, remoteCRC = %d, file [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + fileCRC, + networkMessageSynchNetworkGameDataFileCRCCheck.getFileCRC(), + networkMessageSynchNetworkGameDataFileCRCCheck.getFileName() + .c_str()); + + // Here we initiate a download of missing or mismatched content + + NetworkMessageSynchNetworkGameDataFileGet + sendNetworkMessageSynchNetworkGameDataFileGet( + networkMessageSynchNetworkGameDataFileCRCCheck.getFileName()); + sendMessage(&sendNetworkMessageSynchNetworkGameDataFileGet); + + FileTransferInfo fileInfo; + fileInfo.hostType = eClient; + fileInfo.serverIP = this->ip.getString(); + fileInfo.serverPort = this->port; + fileInfo.fileName = + networkMessageSynchNetworkGameDataFileCRCCheck.getFileName(); + + FileTransferSocketThread *fileXferThread = + new FileTransferSocketThread(fileInfo); + fileXferThread->start(); + } + + if (networkMessageSynchNetworkGameDataFileCRCCheck.getFileIndex() < + networkMessageSynchNetworkGameDataFileCRCCheck.getTotalFileCount()) { + NetworkMessageSynchNetworkGameDataFileCRCCheck + sendNetworkMessageSynchNetworkGameDataFileCRCCheck( + networkMessageSynchNetworkGameDataFileCRCCheck + .getTotalFileCount(), + networkMessageSynchNetworkGameDataFileCRCCheck.getFileIndex() + + 1, + 0, ""); + sendMessage(&sendNetworkMessageSynchNetworkGameDataFileCRCCheck); + } + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + } + } break; + + case nmtText: { + NetworkMessageText networkMessageText; + if (receiveMessage(&networkMessageText)) { + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + this->setLastPingInfoToNow(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] got nmtText\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__); + + ChatMsgInfo msg(networkMessageText.getText().c_str(), + networkMessageText.getTeamIndex(), + networkMessageText.getPlayerIndex(), + networkMessageText.getTargetLanguage()); + this->addChatInfo(msg); + } + } break; + + case nmtMarkCell: { + NetworkMessageMarkCell networkMessageMarkCell; + if (receiveMessage(&networkMessageMarkCell)) { + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + this->setLastPingInfoToNow(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] got nmtMarkCell\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__); + + MarkedCell msg(networkMessageMarkCell.getTarget(), + networkMessageMarkCell.getFactionIndex(), + networkMessageMarkCell.getText().c_str(), + networkMessageMarkCell.getPlayerIndex()); + this->addMarkedCell(msg); + } + } break; + case nmtUnMarkCell: { + NetworkMessageUnMarkCell networkMessageMarkCell; + if (receiveMessage(&networkMessageMarkCell)) { + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + this->setLastPingInfoToNow(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] got nmtMarkCell\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__); + + UnMarkedCell msg(networkMessageMarkCell.getTarget(), + networkMessageMarkCell.getFactionIndex()); + this->addUnMarkedCell(msg); + } + } break; + case nmtHighlightCell: { + NetworkMessageHighlightCell networkMessageHighlightCell; + if (receiveMessage(&networkMessageHighlightCell)) { + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + this->setLastPingInfoToNow(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] got nmtHighlightCell\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__); + + MarkedCell msg(networkMessageHighlightCell.getTarget(), + networkMessageHighlightCell.getFactionIndex(), "none", -1); + this->setHighlightedCell(msg); + } + } break; + + case nmtLaunch: + case nmtBroadCastSetup: { + // printf("#1 Got new game setup playerIndex = %d!\n",playerIndex); + + NetworkMessageLaunch networkMessageLaunch; + if (receiveMessage(&networkMessageLaunch, networkMessageType)) { + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + this->setLastPingInfoToNow(); + + if (networkMessageLaunch.getMessageType() == nmtLaunch) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Lined: %d] got nmtLaunch\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } else if (networkMessageLaunch.getMessageType() == nmtBroadCastSetup) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Lined: %d] got nmtBroadCastSetup\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Lined: %d] got networkMessageLaunch.getMessageType() " + "= %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, networkMessageLaunch.getMessageType()); + + char szBuf[1024] = ""; + snprintf(szBuf, 1023, + "In [%s::%s Line: %d] Invalid " + "networkMessageLaunch.getMessageType() = %d", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, networkMessageLaunch.getMessageType()); + throw megaglest_runtime_error(szBuf); + } + + networkMessageLaunch.buildGameSettings(&gameSettings); + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // printf("Client got game settings playerIndex = %d lookingfor + // match...\n",playerIndex); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Lined: %d] got " + "networkMessageLaunch.getMessageType() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, + networkMessageLaunch.getMessageType()); + // replace server player by network + for (int factionIndex = 0; factionIndex < gameSettings.getFactionCount(); + ++factionIndex) { + + // printf("Faction = %d start location = %d faction name = + // %s\n",i,gameSettings.getStartLocationIndex(factionIndex),gameSettings.getFactionTypeName(factionIndex).c_str()); + + // replace by network + if (gameSettings.getFactionControl(factionIndex) == ctHuman) { + gameSettings.setFactionControl(factionIndex, ctNetwork); + } - networkGameDataSynchCheckOkMap = false; - networkGameDataSynchCheckOkTile = false; - networkGameDataSynchCheckOkTech = false; - this->setNetworkGameDataSynchCheckTechMismatchReport(""); - this->setReceivedDataSynchCheck(false); + // printf("factionIndex = %d + // gameSettings.getStartLocationIndex(factionIndex) = %d playerIndex = + // %d, gameSettings.getFactionControl(factionIndex) = + // %d\n",factionIndex,gameSettings.getStartLocationIndex(factionIndex),playerIndex,gameSettings.getFactionControl(i)); + + // set the faction index + if (gameSettings.getStartLocationIndex(factionIndex) == playerIndex) { + // printf("Setting my factionindex to: %d for playerIndex: + // %d\n",i,playerIndex); + + gameSettings.setThisFactionIndex(factionIndex); + + // printf("Client got game settings playerIndex = %d factionIndex = %d + // control = %d name = + // %s\n",playerIndex,factionIndex,gameSettings.getFactionControl(factionIndex),gameSettings.getFactionTypeName(i).c_str()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] " + "gameSettings.getThisFactionIndex(factionIndex) = %d, " + "playerIndex = %d, factionIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, gameSettings.getThisFactionIndex(), playerIndex, + factionIndex); + } + } + + if (networkMessageLaunch.getMessageType() == nmtLaunch) { + launchGame = true; + } else if (networkMessageLaunch.getMessageType() == nmtBroadCastSetup) { + setGameSettingsReceived(true); + } + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + } + } break; + case nmtPlayerIndexMessage: { + PlayerIndexMessage playerIndexMessage(-1); + if (receiveMessage(&playerIndexMessage)) { + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + this->setLastPingInfoToNow(); + playerIndex = playerIndexMessage.getPlayerIndex(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] got " + "nmtPlayerIndexMessage, playerIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, playerIndex); + } - uint32 tilesetCRC = 0; - uint32 techCRC = 0; - uint32 mapCRC = 0; - vector > vctFileList; + // printf("Got player index changed msg: %d\n",playerIndex); + } break; + + case nmtReady: { + NetworkMessageReady networkMessageReady; + if (receiveMessage(&networkMessageReady)) { + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + this->setLastPingInfoToNow(); + MutexSafeWrapper safeMutexFlags(flagAccessor, CODE_AT_LINE); + this->readyForInGameJoin = true; + } - try { - Config &config = Config::getInstance(); - string scenarioDir = ""; - if(gameSettings.getScenarioDir() != "") { + // printf("ClientInterface got nmtReady this->readyForInGameJoin: + // %d\n",this->readyForInGameJoin); + } break; - scenarioDir = gameSettings.getScenarioDir(); - if(EndsWith(scenarioDir, ".xml") == true) { - scenarioDir = scenarioDir.erase(scenarioDir.size() - 4, 4); - scenarioDir = scenarioDir.erase(scenarioDir.size() - gameSettings.getScenario().size(), gameSettings.getScenario().size() + 1); - } + case nmtCommandList: { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] gameSettings.getScenarioDir() = [%s] gameSettings.getScenario() = [%s] scenarioDir = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,gameSettings.getScenarioDir().c_str(),gameSettings.getScenario().c_str(),scenarioDir.c_str()); - } + // make sure we read the message + // time_t receiveTimeElapsed = time(NULL); + NetworkMessageCommandList networkMessageCommandList; + bool gotCmd = receiveMessage(&networkMessageCommandList); + if (gotCmd == false) { + throw megaglest_runtime_error( + "error retrieving nmtCommandList returned false!"); + } + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + this->setLastPingInfoToNow(); + } break; + + case nmtQuit: { + // time_t receiveTimeElapsed = time(NULL); + NetworkMessageQuit networkMessageQuit; + bool gotCmd = receiveMessage(&networkMessageQuit); + if (gotCmd == false) { + throw megaglest_runtime_error("error retrieving nmtQuit returned false!"); + } + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + this->setLastPingInfoToNow(); + setQuit(true); + close(); + } break; + + case nmtLoadingStatusMessage: { + NetworkMessageLoadingStatus networkMessageLoadingStatus(nmls_NONE); + if (receiveMessage(&networkMessageLoadingStatus)) { + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + this->setLastPingInfoToNow(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + } + } break; + + default: { + string sErr = + string(extractFileFromDirectoryPath(__FILE__).c_str()) + + "::" + string(__FUNCTION__) + + " Unexpected network message: " + intToStr(networkMessageType); + // throw + // megaglest_runtime_error(string(extractFileFromDirectoryPath(__FILE__).c_str()) + // + "::" + string(__FUNCTION__) + " Unexpected network message: " + + // intToStr(networkMessageType)); + sendTextMessage("Unexpected network message: " + + intToStr(networkMessageType), + -1, true, ""); + DisplayErrorMessage(sErr); + sleep(1); + + setQuit(true); + close(); + } + } + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (clientSocket != NULL && clientSocket->isConnected() == true && + gotIntro == false && + difftime((long int)time(NULL), connectedTime) > + GameConstants::maxClientConnectHandshakeSecs) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] difftime(time(NULL),connectedTime) = %f\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, difftime((long int)time(NULL), connectedTime)); + close(); + } + + // 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()); + // if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled + // && chrono.getMillis() > 0) chrono.start(); +} - // check the checksum's - tilesetCRC = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTilesets,scenarioDir), string("/") + networkMessageSynchNetworkGameData.getTileset() + string("/*"), ".xml", NULL); +void ClientInterface::updateNetworkFrame() { this->updateFrame(NULL); } - this->setNetworkGameDataSynchCheckOkTile((tilesetCRC == networkMessageSynchNetworkGameData.getTilesetCRC())); +void ClientInterface::updateFrame(int *checkFrame) { + // printf("#1 ClientInterface::updateFrame\n"); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] tilesetCRC info, local = %d, remote = %d, networkMessageSynchNetworkGameData.getTileset() = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,tilesetCRC,networkMessageSynchNetworkGameData.getTilesetCRC(),networkMessageSynchNetworkGameData.getTileset().c_str()); + // printf("In updateFrame: %d\n",(checkFrame ? *checkFrame : -1)); - //tech, load before map because of resources - techCRC = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,scenarioDir), string("/") + networkMessageSynchNetworkGameData.getTech() + string("/*"), ".xml", NULL); + if (isConnected() == true && getQuitThread() == false) { + // printf("#2 ClientInterface::updateFrame\n"); - this->setNetworkGameDataSynchCheckOkTech((techCRC == networkMessageSynchNetworkGameData.getTechCRC())); + uint64 loopCount = 0; + Chrono chronoPerf; + if (debugClientInterfacePerf == true) { + chronoPerf.start(); + } - if(this->getNetworkGameDataSynchCheckOkTech() == false) { + int waitMicroseconds = (checkFrame == NULL ? 10 : 0); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + bool done = false; + while (done == false && getQuitThread() == false) { + // printf("BEFORE Client get networkMessageType\n"); - string pathSearchString = "/" + networkMessageSynchNetworkGameData.getTech() + "/*"; - vctFileList = getFolderTreeContentsCheckSumListRecursively(config.getPathListForType(ptTechs,scenarioDir),pathSearchString, ".xml", NULL); + // wait for the next message + NetworkMessageType networkMessageType = waitForMessage(waitMicroseconds); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // printf("AFTER Client got networkMessageType = + // %d\n",networkMessageType); - string report = networkMessageSynchNetworkGameData.getTechCRCFileMismatchReport(vctFileList); - this->setNetworkGameDataSynchCheckTechMismatchReport(report); + // check we have an expected message + // NetworkMessageType networkMessageType= getNextMessageType(); - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] techCRC info, local = %d, remote = %d, networkMessageSynchNetworkGameData.getTech() = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,techCRC,networkMessageSynchNetworkGameData.getTechCRC(),networkMessageSynchNetworkGameData.getTech().c_str()); + // printf("Got Network networkMessageType: %d\n",networkMessageType); - //map - Checksum checksum; - string file = Config::getMapPath(networkMessageSynchNetworkGameData.getMap(),scenarioDir, false); - if(file != "") { - checksum.addFile(file); - mapCRC = checksum.getSum(); - } - this->setNetworkGameDataSynchCheckOkMap((mapCRC == networkMessageSynchNetworkGameData.getMapCRC())); - this->setReceivedDataSynchCheck(true); + switch (networkMessageType) { + case nmtCommandList: { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] mapCRC info, local = %d, remote = %d, file = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,mapCRC,networkMessageSynchNetworkGameData.getMapCRC(),file.c_str()); - } - catch(const runtime_error &ex) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - string sErr = ex.what(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] error during processing, sErr = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,sErr.c_str()); + // make sure we read the message + // time_t receiveTimeElapsed = time(NULL); + NetworkMessageCommandList networkMessageCommandList; + bool gotCmd = receiveMessage(&networkMessageCommandList); + if (gotCmd == false) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] error retrieving " + "nmtCommandList returned false!\n", + __FILE__, __FUNCTION__, __LINE__); + if (isConnected() == false) { + setQuit(true); + close(); + return; + } - DisplayErrorMessage(sErr); - } + throw megaglest_runtime_error( + "error retrieving nmtCommandList returned false!"); + } - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); + // printf("Client Thread getFrameCount(): %d getCommandCount(): + // %d\n",networkMessageCommandList.getFrameCount(),networkMessageCommandList.getCommandCount()); + + MutexSafeWrapper safeMutex(networkCommandListThreadAccessor, + CODE_AT_LINE); + cachedLastPendingFrameCount = networkMessageCommandList.getFrameCount(); + // printf("cachedLastPendingFrameCount = %lld\n",(long long + // int)cachedLastPendingFrameCount); + + // check that we are in the right frame + if (checkFrame != NULL) { + if (networkMessageCommandList.getFrameCount() != *checkFrame) { + string sErr = "Player: " + getHumanPlayerName() + + " got a Network synchronization error, frame counts " + "do not match, server frameCount = " + + intToStr(networkMessageCommandList.getFrameCount()) + + ", local frameCount = " + intToStr(*checkFrame); + sendTextMessage(sErr, -1, true, ""); + DisplayErrorMessage(sErr); + sleep(1); - NetworkMessageSynchNetworkGameDataStatus sendNetworkMessageSynchNetworkGameDataStatus(mapCRC,tilesetCRC,techCRC,vctFileList); - sendMessage(&sendNetworkMessageSynchNetworkGameDataStatus); + setQuit(true); + close(); + return; + } + for (int index = 0; index < GameConstants::maxPlayers; ++index) { + printf("Frame: %d faction: %d local CRC: %u Remote CRC: %u\n", + *checkFrame, index, getNetworkPlayerFactionCRC(index), + networkMessageCommandList.getNetworkPlayerFactionCRC(index)); + + if (networkMessageCommandList.getNetworkPlayerFactionCRC(index) != + getNetworkPlayerFactionCRC(index)) { + string sErr = + "Player: " + getHumanPlayerName() + + " got a Network CRC error, CRC's do not match, server CRC " + "= " + + uIntToStr( + networkMessageCommandList.getNetworkPlayerFactionCRC( + index)) + + ", local CRC = " + + uIntToStr(getNetworkPlayerFactionCRC(index)); + sendTextMessage(sErr, -1, true, ""); + DisplayErrorMessage(sErr); + sleep(1); + + setQuit(true); + close(); + return; } + } } - break; - - case nmtSynchNetworkGameDataFileCRCCheck: - { - NetworkMessageSynchNetworkGameDataFileCRCCheck networkMessageSynchNetworkGameDataFileCRCCheck; - if(receiveMessage(&networkMessageSynchNetworkGameDataFileCRCCheck)) { - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - this->setLastPingInfoToNow(); - - Checksum checksum; - string file = networkMessageSynchNetworkGameDataFileCRCCheck.getFileName(); - checksum.addFile(file); - uint32 fileCRC = checksum.getSum(); - - if(fileCRC != networkMessageSynchNetworkGameDataFileCRCCheck.getFileCRC()) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] got nmtSynchNetworkGameDataFileCRCCheck localCRC = %d, remoteCRC = %d, file [%s]\n", - extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,fileCRC, - networkMessageSynchNetworkGameDataFileCRCCheck.getFileCRC(), - networkMessageSynchNetworkGameDataFileCRCCheck.getFileName().c_str()); - // Here we initiate a download of missing or mismatched content - - NetworkMessageSynchNetworkGameDataFileGet sendNetworkMessageSynchNetworkGameDataFileGet(networkMessageSynchNetworkGameDataFileCRCCheck.getFileName()); - sendMessage(&sendNetworkMessageSynchNetworkGameDataFileGet); - - FileTransferInfo fileInfo; - fileInfo.hostType = eClient; - fileInfo.serverIP = this->ip.getString(); - fileInfo.serverPort = this->port; - fileInfo.fileName = networkMessageSynchNetworkGameDataFileCRCCheck.getFileName(); - - FileTransferSocketThread *fileXferThread = new FileTransferSocketThread(fileInfo); - fileXferThread->start(); - } - - if(networkMessageSynchNetworkGameDataFileCRCCheck.getFileIndex() < networkMessageSynchNetworkGameDataFileCRCCheck.getTotalFileCount()) - { - NetworkMessageSynchNetworkGameDataFileCRCCheck sendNetworkMessageSynchNetworkGameDataFileCRCCheck( - networkMessageSynchNetworkGameDataFileCRCCheck.getTotalFileCount(), - networkMessageSynchNetworkGameDataFileCRCCheck.getFileIndex() + 1, - 0, - ""); - sendMessage(&sendNetworkMessageSynchNetworkGameDataFileCRCCheck); - } - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); + cachedPendingCommands[networkMessageCommandList.getFrameCount()] + .reserve(networkMessageCommandList.getCommandCount()); + + // give all commands + for (int i = 0; i < networkMessageCommandList.getCommandCount(); ++i) { + // pendingCommands.push_back(*networkMessageCommandList.getCommand(i)); + + // if(networkMessageCommandList.getCommand(i)->getNetworkCommandType() + // == nctPauseResume) { printf("Network cmd type: %d [%d] frame: + // %d\n",networkMessageCommandList.getCommand(i)->getNetworkCommandType(),nctPauseResume,networkMessageCommandList.getFrameCount()); + //} + + cachedPendingCommands[networkMessageCommandList.getFrameCount()] + .push_back(*networkMessageCommandList.getCommand(i)); + + if (cachedPendingCommandCRCs.find( + networkMessageCommandList.getFrameCount()) == + cachedPendingCommandCRCs.end()) { + cachedPendingCommandCRCs[networkMessageCommandList.getFrameCount()] + .reserve(GameConstants::maxPlayers); + for (int index = 0; index < GameConstants::maxPlayers; ++index) { + cachedPendingCommandCRCs[networkMessageCommandList + .getFrameCount()] + .push_back( + networkMessageCommandList.getNetworkPlayerFactionCRC( + index)); } + } } - break; + safeMutex.ReleaseLock(); + + done = true; + } break; + + case nmtPing: { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] got nmtPing\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__); + + NetworkMessagePing networkMessagePing; + if (receiveMessage(&networkMessagePing)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + this->setLastPingInfo(networkMessagePing); + } + } break; + + case nmtQuit: { + NetworkMessageQuit networkMessageQuit; + bool gotCmd = receiveMessage(&networkMessageQuit); + if (gotCmd == false) { + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d] error retrieving nmtQuit returned false!\n", + __FILE__, __FUNCTION__, __LINE__); + if (isConnected() == false) { + setQuit(true); + close(); + return; + } - case nmtText: - { - NetworkMessageText networkMessageText; - if(receiveMessage(&networkMessageText)) { - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); + // throw megaglest_runtime_error("error retrieving nmtQuit returned + // false!"); + setQuit(true); + done = true; + } + setQuit(true); + done = true; + } break; - this->setLastPingInfoToNow(); + case nmtText: { + NetworkMessageText networkMessageText; + bool gotCmd = receiveMessage(&networkMessageText); + if (gotCmd == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] got nmtText\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d] error retrieving nmtText returned false!\n", + __FILE__, __FUNCTION__, __LINE__); + if (isConnected() == false) { - ChatMsgInfo msg(networkMessageText.getText().c_str(),networkMessageText.getTeamIndex(),networkMessageText.getPlayerIndex(),networkMessageText.getTargetLanguage()); - this->addChatInfo(msg); - } + setQuit(true); + close(); + return; + } + + throw megaglest_runtime_error( + "error retrieving nmtText returned false!"); } - break; - case nmtMarkCell: - { - NetworkMessageMarkCell networkMessageMarkCell; - if(receiveMessage(&networkMessageMarkCell)) { - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - this->setLastPingInfoToNow(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] got nmtMarkCell\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); - - MarkedCell msg(networkMessageMarkCell.getTarget(), - networkMessageMarkCell.getFactionIndex(), - networkMessageMarkCell.getText().c_str(), - networkMessageMarkCell.getPlayerIndex()); - this->addMarkedCell(msg); - } + ChatMsgInfo msg(networkMessageText.getText().c_str(), + networkMessageText.getTeamIndex(), + networkMessageText.getPlayerIndex(), + networkMessageText.getTargetLanguage()); + this->addChatInfo(msg); + } break; + + case nmtMarkCell: { + NetworkMessageMarkCell networkMessageMarkCell; + if (receiveMessage(&networkMessageMarkCell)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] got nmtMarkCell\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__); + + MarkedCell msg(networkMessageMarkCell.getTarget(), + networkMessageMarkCell.getFactionIndex(), + networkMessageMarkCell.getText().c_str(), + networkMessageMarkCell.getPlayerIndex()); + this->addMarkedCell(msg); } - break; - case nmtUnMarkCell: - { - NetworkMessageUnMarkCell networkMessageMarkCell; - if(receiveMessage(&networkMessageMarkCell)) { - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - this->setLastPingInfoToNow(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] got nmtMarkCell\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); - - UnMarkedCell msg(networkMessageMarkCell.getTarget(), - networkMessageMarkCell.getFactionIndex()); - this->addUnMarkedCell(msg); - } + } break; + + case nmtUnMarkCell: { + NetworkMessageUnMarkCell networkMessageMarkCell; + if (receiveMessage(&networkMessageMarkCell)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] got nmtMarkCell\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__); + + UnMarkedCell msg(networkMessageMarkCell.getTarget(), + networkMessageMarkCell.getFactionIndex()); + this->addUnMarkedCell(msg); } - break; - case nmtHighlightCell: - { - NetworkMessageHighlightCell networkMessageHighlightCell; - if(receiveMessage(&networkMessageHighlightCell)) { - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - this->setLastPingInfoToNow(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] got nmtHighlightCell\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); - - MarkedCell msg(networkMessageHighlightCell.getTarget(), - networkMessageHighlightCell.getFactionIndex(), - "none",-1); - this->setHighlightedCell(msg); - } + } break; + case nmtHighlightCell: { + NetworkMessageHighlightCell networkMessageHighlightCell; + if (receiveMessage(&networkMessageHighlightCell)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] got nmtHighlightCell\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__); + + MarkedCell msg(networkMessageHighlightCell.getTarget(), + networkMessageHighlightCell.getFactionIndex(), "none", + -1); + this->setHighlightedCell(msg); } - break; - - case nmtLaunch: - case nmtBroadCastSetup: - { - //printf("#1 Got new game setup playerIndex = %d!\n",playerIndex); - - NetworkMessageLaunch networkMessageLaunch; - if(receiveMessage(&networkMessageLaunch, networkMessageType)) { - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - this->setLastPingInfoToNow(); - - if(networkMessageLaunch.getMessageType() == nmtLaunch) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Lined: %d] got nmtLaunch\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - else if(networkMessageLaunch.getMessageType() == nmtBroadCastSetup) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Lined: %d] got nmtBroadCastSetup\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Lined: %d] got networkMessageLaunch.getMessageType() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageLaunch.getMessageType()); - - char szBuf[1024]=""; - snprintf(szBuf,1023,"In [%s::%s Line: %d] Invalid networkMessageLaunch.getMessageType() = %d",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageLaunch.getMessageType()); - throw megaglest_runtime_error(szBuf); - } - - networkMessageLaunch.buildGameSettings(&gameSettings); - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - //printf("Client got game settings playerIndex = %d lookingfor match...\n",playerIndex); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Lined: %d] got networkMessageLaunch.getMessageType() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageLaunch.getMessageType()); - //replace server player by network - for(int factionIndex = 0; factionIndex 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); + // printf("i = %d gameSettings.getStartLocationIndex(i) = %d + // playerIndex = + // %d!\n",i,gameSettings.getStartLocationIndex(i),playerIndex); + + // set the faction index + if (gameSettings.getStartLocationIndex(i) == playerIndex) { + // printf("Setting my factionindex to: %d for playerIndex: + // %d\n",i,playerIndex); + + gameSettings.setThisFactionIndex(i); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] gameSettings.getThisFactionIndex(i) " + "= %d, playerIndex = %d, i = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, gameSettings.getThisFactionIndex(), + playerIndex, i); } + } } - break; - case nmtPlayerIndexMessage: - { - PlayerIndexMessage playerIndexMessage(-1); - if(receiveMessage(&playerIndexMessage)) { - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); + } break; - this->setLastPingInfoToNow(); - playerIndex= playerIndexMessage.getPlayerIndex(); + case nmtLoadingStatusMessage: + break; - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] got nmtPlayerIndexMessage, playerIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playerIndex); - } + case nmtInvalid: + break; - //printf("Got player index changed msg: %d\n",playerIndex); - } - break; - - case nmtReady: - { - NetworkMessageReady networkMessageReady; - if(receiveMessage(&networkMessageReady)) { - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - this->setLastPingInfoToNow(); - MutexSafeWrapper safeMutexFlags(flagAccessor,CODE_AT_LINE); - this->readyForInGameJoin = true; - } - - //printf("ClientInterface got nmtReady this->readyForInGameJoin: %d\n",this->readyForInGameJoin); - } - break; - - case nmtCommandList: - { - - //make sure we read the message - //time_t receiveTimeElapsed = time(NULL); - NetworkMessageCommandList networkMessageCommandList; - bool gotCmd = receiveMessage(&networkMessageCommandList); - if(gotCmd == false) { - throw megaglest_runtime_error("error retrieving nmtCommandList returned false!"); - } - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - this->setLastPingInfoToNow(); - } - break; - - case nmtQuit: - { - //time_t receiveTimeElapsed = time(NULL); - NetworkMessageQuit networkMessageQuit; - bool gotCmd = receiveMessage(&networkMessageQuit); - if(gotCmd == false) { - throw megaglest_runtime_error("error retrieving nmtQuit returned false!"); - } - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - this->setLastPingInfoToNow(); - setQuit(true); - close(); - } - break; - - case nmtLoadingStatusMessage: - { - NetworkMessageLoadingStatus networkMessageLoadingStatus(nmls_NONE); - if(receiveMessage(&networkMessageLoadingStatus)) { - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - this->setLastPingInfoToNow(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - } - break; - - default: - { - string sErr = string(extractFileFromDirectoryPath(__FILE__).c_str()) + "::" + string(__FUNCTION__) + " Unexpected network message: " + intToStr(networkMessageType); - //throw megaglest_runtime_error(string(extractFileFromDirectoryPath(__FILE__).c_str()) + "::" + string(__FUNCTION__) + " Unexpected network message: " + intToStr(networkMessageType)); - sendTextMessage("Unexpected network message: " + intToStr(networkMessageType),-1, true,""); - DisplayErrorMessage(sErr); - sleep(1); + default: { + sendTextMessage("Unexpected message in client interface: " + + intToStr(networkMessageType), + -1, true, ""); + DisplayErrorMessage( + string(extractFileFromDirectoryPath(__FILE__).c_str()) + "::" + + string(__FUNCTION__) + " Unexpected message in client interface: " + + intToStr(networkMessageType)); + sleep(1); - setQuit(true); - close(); - } + setQuit(true); + close(); + done = true; + } break; + } + + if (isConnected() == false && getQuit() == true) { + done = true; + } + + if (debugClientInterfacePerf == true) { + loopCount++; + if (chronoPerf.getMillis() >= 1000) { + printf("Client updateFrame loopCount = %llu\n", + (long long unsigned int)loopCount); + + loopCount = 0; + // sleep(0); + chronoPerf.start(); + } + } } - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - if( clientSocket != NULL && clientSocket->isConnected() == true && - gotIntro == false && difftime((long int)time(NULL),connectedTime) > GameConstants::maxClientConnectHandshakeSecs) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] difftime(time(NULL),connectedTime) = %f\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,difftime((long int)time(NULL),connectedTime)); - close(); - } - - //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()); - //if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); -} - -void ClientInterface::updateNetworkFrame() { - this->updateFrame(NULL); -} - -void ClientInterface::updateFrame(int *checkFrame) { - //printf("#1 ClientInterface::updateFrame\n"); - - //printf("In updateFrame: %d\n",(checkFrame ? *checkFrame : -1)); - - if(isConnected() == true && getQuitThread() == false) { - //printf("#2 ClientInterface::updateFrame\n"); - - uint64 loopCount = 0; - Chrono chronoPerf; - if(debugClientInterfacePerf == true) { - chronoPerf.start(); - } - - int waitMicroseconds = (checkFrame == NULL ? 10 : 0); - - bool done= false; - while(done == false && getQuitThread() == false) { - //printf("BEFORE Client get networkMessageType\n"); - - - //wait for the next message - NetworkMessageType networkMessageType = waitForMessage(waitMicroseconds); - - //printf("AFTER Client got networkMessageType = %d\n",networkMessageType); - - //check we have an expected message - //NetworkMessageType networkMessageType= getNextMessageType(); - - //printf("Got Network networkMessageType: %d\n",networkMessageType); - - switch(networkMessageType) - { - case nmtCommandList: - { - - //make sure we read the message - //time_t receiveTimeElapsed = time(NULL); - NetworkMessageCommandList networkMessageCommandList; - bool gotCmd = receiveMessage(&networkMessageCommandList); - if(gotCmd == false) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] error retrieving nmtCommandList returned false!\n",__FILE__,__FUNCTION__,__LINE__); - if(isConnected() == false) { - setQuit(true); - close(); - return; - } - - throw megaglest_runtime_error("error retrieving nmtCommandList returned false!"); - } - - //printf("Client Thread getFrameCount(): %d getCommandCount(): %d\n",networkMessageCommandList.getFrameCount(),networkMessageCommandList.getCommandCount()); - - MutexSafeWrapper safeMutex(networkCommandListThreadAccessor,CODE_AT_LINE); - cachedLastPendingFrameCount = networkMessageCommandList.getFrameCount(); - //printf("cachedLastPendingFrameCount = %lld\n",(long long int)cachedLastPendingFrameCount); - - //check that we are in the right frame - if(checkFrame != NULL) { - if(networkMessageCommandList.getFrameCount() != *checkFrame) { - string sErr = "Player: " + getHumanPlayerName() + - " got a Network synchronization error, frame counts do not match, server frameCount = " + - intToStr(networkMessageCommandList.getFrameCount()) + ", local frameCount = " + - intToStr(*checkFrame); - sendTextMessage(sErr,-1, true,""); - DisplayErrorMessage(sErr); - sleep(1); - - setQuit(true); - close(); - return; - } - for(int index = 0; index < GameConstants::maxPlayers; ++index) { - printf("Frame: %d faction: %d local CRC: %u Remote CRC: %u\n",*checkFrame,index,getNetworkPlayerFactionCRC(index),networkMessageCommandList.getNetworkPlayerFactionCRC(index)); - - if(networkMessageCommandList.getNetworkPlayerFactionCRC(index) != getNetworkPlayerFactionCRC(index)) { - string sErr = "Player: " + getHumanPlayerName() + - " got a Network CRC error, CRC's do not match, server CRC = " + - uIntToStr(networkMessageCommandList.getNetworkPlayerFactionCRC(index)) + ", local CRC = " + - uIntToStr(getNetworkPlayerFactionCRC(index)); - sendTextMessage(sErr,-1, true,""); - DisplayErrorMessage(sErr); - sleep(1); - - setQuit(true); - close(); - return; - } - } - } - - cachedPendingCommands[networkMessageCommandList.getFrameCount()].reserve(networkMessageCommandList.getCommandCount()); - - // give all commands - for(int i= 0; i < networkMessageCommandList.getCommandCount(); ++i) { - //pendingCommands.push_back(*networkMessageCommandList.getCommand(i)); - - //if(networkMessageCommandList.getCommand(i)->getNetworkCommandType() == nctPauseResume) { - //printf("Network cmd type: %d [%d] frame: %d\n",networkMessageCommandList.getCommand(i)->getNetworkCommandType(),nctPauseResume,networkMessageCommandList.getFrameCount()); - //} - - cachedPendingCommands[networkMessageCommandList.getFrameCount()].push_back(*networkMessageCommandList.getCommand(i)); - - if(cachedPendingCommandCRCs.find(networkMessageCommandList.getFrameCount()) == cachedPendingCommandCRCs.end()) { - cachedPendingCommandCRCs[networkMessageCommandList.getFrameCount()].reserve(GameConstants::maxPlayers); - for(int index = 0; index < GameConstants::maxPlayers; ++index) { - cachedPendingCommandCRCs[networkMessageCommandList.getFrameCount()].push_back(networkMessageCommandList.getNetworkPlayerFactionCRC(index)); - } - } - } - safeMutex.ReleaseLock(); - - done = true; - } - break; - - case nmtPing: - { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] got nmtPing\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); - - NetworkMessagePing networkMessagePing; - if(receiveMessage(&networkMessagePing)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - this->setLastPingInfo(networkMessagePing); - } - } - break; - - case nmtQuit: - { - NetworkMessageQuit networkMessageQuit; - bool gotCmd = receiveMessage(&networkMessageQuit); - if(gotCmd == false) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] error retrieving nmtQuit returned false!\n",__FILE__,__FUNCTION__,__LINE__); - if(isConnected() == false) { - setQuit(true); - close(); - return; - } - - //throw megaglest_runtime_error("error retrieving nmtQuit returned false!"); - setQuit(true); - done = true; - } - setQuit(true); - done = true; - } - break; - - case nmtText: - { - NetworkMessageText networkMessageText; - bool gotCmd = receiveMessage(&networkMessageText); - if(gotCmd == false) { - - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] error retrieving nmtText returned false!\n",__FILE__,__FUNCTION__,__LINE__); - if(isConnected() == false) { - - setQuit(true); - close(); - return; - } - - throw megaglest_runtime_error("error retrieving nmtText returned false!"); - } - - ChatMsgInfo msg(networkMessageText.getText().c_str(),networkMessageText.getTeamIndex(),networkMessageText.getPlayerIndex(),networkMessageText.getTargetLanguage()); - this->addChatInfo(msg); - } - break; - - case nmtMarkCell: - { - NetworkMessageMarkCell networkMessageMarkCell; - if(receiveMessage(&networkMessageMarkCell)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] got nmtMarkCell\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); - - MarkedCell msg(networkMessageMarkCell.getTarget(), - networkMessageMarkCell.getFactionIndex(), - networkMessageMarkCell.getText().c_str(), - networkMessageMarkCell.getPlayerIndex()); - this->addMarkedCell(msg); - } - } - break; - - case nmtUnMarkCell: - { - NetworkMessageUnMarkCell networkMessageMarkCell; - if(receiveMessage(&networkMessageMarkCell)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] got nmtMarkCell\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); - - UnMarkedCell msg(networkMessageMarkCell.getTarget(), - networkMessageMarkCell.getFactionIndex()); - this->addUnMarkedCell(msg); - } - } - break; - case nmtHighlightCell: - { - NetworkMessageHighlightCell networkMessageHighlightCell; - if(receiveMessage(&networkMessageHighlightCell)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] got nmtHighlightCell\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); - - MarkedCell msg(networkMessageHighlightCell.getTarget(), - networkMessageHighlightCell.getFactionIndex(), - "none",-1); - this->setHighlightedCell(msg); - } - } - break; - - - case nmtLaunch: - case nmtBroadCastSetup: - { - //printf("#2 Got new game setup playerIndex = %d!\n",playerIndex); - - NetworkMessageLaunch networkMessageLaunch; - if(receiveMessage(&networkMessageLaunch,networkMessageType)) { - - if(networkMessageLaunch.getMessageType() == nmtLaunch) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Lined: %d] got nmtLaunch\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - else if(networkMessageLaunch.getMessageType() == nmtBroadCastSetup) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Lined: %d] got nmtBroadCastSetup\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Lined: %d] got networkMessageLaunch.getMessageType() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageLaunch.getMessageType()); - - char szBuf[1024]=""; - snprintf(szBuf,1023,"In [%s::%s Line: %d] Invalid networkMessageLaunch.getMessageType() = %d",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageLaunch.getMessageType()); - throw megaglest_runtime_error(szBuf); - } - - networkMessageLaunch.buildGameSettings(&gameSettings); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Lined: %d] got networkMessageLaunch.getMessageType() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageLaunch.getMessageType()); - //replace server player by network - for(int i= 0; i= 1000) { - printf("Client updateFrame loopCount = %llu\n",(long long unsigned int)loopCount); - - loopCount = 0; - //sleep(0); - chronoPerf.start(); - } - } - } - - if(done == true) { - MutexSafeWrapper safeMutex(networkCommandListThreadAccessor,CODE_AT_LINE); - cachedPendingCommandsIndex++; - } - } - //printf("#3 ClientInterface::updateFrame\n"); + if (done == true) { + MutexSafeWrapper safeMutex(networkCommandListThreadAccessor, + CODE_AT_LINE); + cachedPendingCommandsIndex++; + } + } + // printf("#3 ClientInterface::updateFrame\n"); } uint64 ClientInterface::getCachedLastPendingFrameCount() { - MutexSafeWrapper safeMutex(networkCommandListThreadAccessor,CODE_AT_LINE); - uint64 result = cachedLastPendingFrameCount; - return result; + MutexSafeWrapper safeMutex(networkCommandListThreadAccessor, CODE_AT_LINE); + uint64 result = cachedLastPendingFrameCount; + return result; } int64 ClientInterface::getTimeClientWaitedForLastMessage() { - MutexSafeWrapper safeMutex(networkCommandListThreadAccessor,CODE_AT_LINE); - uint64 result = timeClientWaitedForLastMessage; - return result; + MutexSafeWrapper safeMutex(networkCommandListThreadAccessor, CODE_AT_LINE); + uint64 result = timeClientWaitedForLastMessage; + return result; } -bool ClientInterface::getNetworkCommand(int frameCount, int currentCachedPendingCommandsIndex) { - bool result = false; - bool waitForData = false; - uint64 copyCachedLastPendingFrameCount = 0; - uint64 waitCount = 0; - uint64 frameCountAsUInt64 = frameCount; - timeClientWaitedForLastMessage = 0; - - //printf("In getNetworkCommand: %d [%d]\n",frameCount,currentCachedPendingCommandsIndex); - - if(getQuit() == false && getQuitThread() == false) { - - Chrono chrono; - MutexSafeWrapper safeMutex(NULL,CODE_AT_LINE); - - for(;getQuit() == false && getQuitThread() == false;) { - - if(safeMutex.isValidMutex() == false) { - safeMutex.setMutex(networkCommandListThreadAccessor,CODE_AT_LINE); - } - else { - safeMutex.Lock(); - } - copyCachedLastPendingFrameCount = cachedLastPendingFrameCount; - - if(cachedPendingCommands.find(frameCount) != cachedPendingCommands.end()) { - - Commands &frameCmdList = cachedPendingCommands[frameCount]; - - //printf("In getNetworkCommand frameCmdList.size(): %d\n",(int)frameCmdList.size()); - - if(frameCmdList.empty() == false) { - for(int index = 0; index < (int)frameCmdList.size(); ++index) { - pendingCommands.push_back(frameCmdList[index]); - } - cachedPendingCommands[frameCount].clear(); - - if(frameCount >= 0) { - for(int index = 0; index < GameConstants::maxPlayers; ++index) { - //printf("X**X Frame: %d faction: %d local CRC: %u Remote CRC: %u\n",frameCount,index,getNetworkPlayerFactionCRC(index),cachedPendingCommandCRCs[frameCount][index]); - - if(cachedPendingCommandCRCs[frameCount][index] != getNetworkPlayerFactionCRC(index)) { - - printf("X**X Frame: %d faction: %d local CRC: %u Remote CRC: %u\n",frameCount,index,getNetworkPlayerFactionCRC(index),cachedPendingCommandCRCs[frameCount][index]); - - string sErr = "Player: " + getHumanPlayerName() + - " got a Network CRC error, CRC's do not match, server CRC = " + - uIntToStr(cachedPendingCommandCRCs[frameCount][index]) + ", local CRC = " + - uIntToStr(getNetworkPlayerFactionCRC(index)); - sendTextMessage(sErr,-1, true,""); - DisplayErrorMessage(sErr); - sleep(1); - - setQuit(true); - close(); - } - } - } - cachedPendingCommandCRCs.erase(frameCount); - } - if(waitForData == true) { - timeClientWaitedForLastMessage = chrono.getMillis(); - chrono.stop(); - } - safeMutex.ReleaseLock(true); - - result = true; - break; - } - else { - safeMutex.ReleaseLock(true); - // No data for this frame - if(waitForData == false) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Client waiting for packet for frame: %d, copyCachedLastPendingFrameCount = %lld\n",frameCount,(long long int)copyCachedLastPendingFrameCount); - chrono.start(); - } - if(copyCachedLastPendingFrameCount > frameCountAsUInt64) { - break; - } - - if(waitForData == false) { - waitForData = true; - sleep(0); - } - - waitCount++; - //printf("Client waiting for packet for frame: %d, currentCachedPendingCommandsIndex = %d, cachedPendingCommandsIndex = %lld\n",frameCount,currentCachedPendingCommandsIndex,(long long int)cachedPendingCommandsIndex); - } - } - } - if(waitForData == true) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Client waiting for packet FINISHED for frame: %d, copyCachedLastPendingFrameCount = %lld waitCount = %llu\n",frameCount,(long long int)copyCachedLastPendingFrameCount,(long long unsigned int)waitCount); - } - - return result; +bool ClientInterface::getNetworkCommand(int frameCount, + int currentCachedPendingCommandsIndex) { + bool result = false; + bool waitForData = false; + uint64 copyCachedLastPendingFrameCount = 0; + uint64 waitCount = 0; + uint64 frameCountAsUInt64 = frameCount; + timeClientWaitedForLastMessage = 0; + + // printf("In getNetworkCommand: %d + // [%d]\n",frameCount,currentCachedPendingCommandsIndex); + + if (getQuit() == false && getQuitThread() == false) { + + Chrono chrono; + MutexSafeWrapper safeMutex(NULL, CODE_AT_LINE); + + for (; getQuit() == false && getQuitThread() == false;) { + + if (safeMutex.isValidMutex() == false) { + safeMutex.setMutex(networkCommandListThreadAccessor, CODE_AT_LINE); + } else { + safeMutex.Lock(); + } + copyCachedLastPendingFrameCount = cachedLastPendingFrameCount; + + if (cachedPendingCommands.find(frameCount) != + cachedPendingCommands.end()) { + + Commands &frameCmdList = cachedPendingCommands[frameCount]; + + // printf("In getNetworkCommand frameCmdList.size(): + // %d\n",(int)frameCmdList.size()); + + if (frameCmdList.empty() == false) { + for (int index = 0; index < (int)frameCmdList.size(); ++index) { + pendingCommands.push_back(frameCmdList[index]); + } + cachedPendingCommands[frameCount].clear(); + + if (frameCount >= 0) { + for (int index = 0; index < GameConstants::maxPlayers; ++index) { + // printf("X**X Frame: %d faction: %d local CRC: %u Remote CRC: + // %u\n",frameCount,index,getNetworkPlayerFactionCRC(index),cachedPendingCommandCRCs[frameCount][index]); + + if (cachedPendingCommandCRCs[frameCount][index] != + getNetworkPlayerFactionCRC(index)) { + + printf( + "X**X Frame: %d faction: %d local CRC: %u Remote CRC: %u\n", + frameCount, index, getNetworkPlayerFactionCRC(index), + cachedPendingCommandCRCs[frameCount][index]); + + string sErr = + "Player: " + getHumanPlayerName() + + " got a Network CRC error, CRC's do not match, server CRC " + "= " + + uIntToStr(cachedPendingCommandCRCs[frameCount][index]) + + ", local CRC = " + + uIntToStr(getNetworkPlayerFactionCRC(index)); + sendTextMessage(sErr, -1, true, ""); + DisplayErrorMessage(sErr); + sleep(1); + + setQuit(true); + close(); + } + } + } + cachedPendingCommandCRCs.erase(frameCount); + } + if (waitForData == true) { + timeClientWaitedForLastMessage = chrono.getMillis(); + chrono.stop(); + } + safeMutex.ReleaseLock(true); + + result = true; + break; + } else { + safeMutex.ReleaseLock(true); + // No data for this frame + if (waitForData == false) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Client waiting for packet for frame: %d, " + "copyCachedLastPendingFrameCount = %lld\n", + frameCount, (long long int)copyCachedLastPendingFrameCount); + chrono.start(); + } + if (copyCachedLastPendingFrameCount > frameCountAsUInt64) { + break; + } + + if (waitForData == false) { + waitForData = true; + sleep(0); + } + + waitCount++; + // printf("Client waiting for packet for frame: %d, + // currentCachedPendingCommandsIndex = %d, cachedPendingCommandsIndex = + // %lld\n",frameCount,currentCachedPendingCommandsIndex,(long long + // int)cachedPendingCommandsIndex); + } + } + } + if (waitForData == true) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Client waiting for packet FINISHED for frame: %d, " + "copyCachedLastPendingFrameCount = %lld waitCount = %llu\n", + frameCount, (long long int)copyCachedLastPendingFrameCount, + (long long unsigned int)waitCount); + } + + return result; } void ClientInterface::updateKeyframe(int frameCount) { - currentFrameCount = frameCount; + currentFrameCount = frameCount; - //printf("In updateKeyFrame: %d\n",currentFrameCount); + // printf("In updateKeyFrame: %d\n",currentFrameCount); - if(getQuit() == false && getQuitThread() == false) { - if(networkCommandListThread == NULL) { - static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); - networkCommandListThread = new ClientInterfaceThread(this); - networkCommandListThread->setUniqueID(mutexOwnerId); - networkCommandListThread->start(); + if (getQuit() == false && getQuitThread() == false) { + if (networkCommandListThread == NULL) { + static string mutexOwnerId = + string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + + intToStr(__LINE__); + networkCommandListThread = new ClientInterfaceThread(this); + networkCommandListThread->setUniqueID(mutexOwnerId); + networkCommandListThread->start(); - sleep(0); - } + sleep(0); + } - getNetworkCommand(frameCount,cachedPendingCommandsIndex); - } + getNetworkCommand(frameCount, cachedPendingCommandsIndex); + } } bool ClientInterface::isMasterServerAdminOverride() { - return (gameSettings.getMasterserver_admin() == this->getSessionKey()); + return (gameSettings.getMasterserver_admin() == this->getSessionKey()); } -void ClientInterface::waitUntilReady(Checksum* checksum) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - MutexSafeWrapper safeMutexFlags(flagAccessor,CODE_AT_LINE); - bool signalServerWhenReadyToStartJoinedGame = this->readyForInGameJoin; - this->readyForInGameJoin = false; - safeMutexFlags.ReleaseLock(); - - Logger &logger= Logger::getInstance(); - - Chrono chrono; - chrono.start(); - - // FOR TESTING ONLY - delay to see the client count up while waiting - //sleep(5000); +void ClientInterface::waitUntilReady(Checksum *checksum) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + MutexSafeWrapper safeMutexFlags(flagAccessor, CODE_AT_LINE); + bool signalServerWhenReadyToStartJoinedGame = this->readyForInGameJoin; + this->readyForInGameJoin = false; + safeMutexFlags.ReleaseLock(); + + Logger &logger = Logger::getInstance(); + + Chrono chrono; + chrono.start(); + + // FOR TESTING ONLY - delay to see the client count up while waiting + // sleep(5000); + + // clientSocket->setBlock(true); + // send ready message + NetworkMessageReady networkMessageReady; + sendMessage(&networkMessageReady); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + NetworkMessageLoadingStatus networkMessageLoadingStatus(nmls_NONE); + + Lang &lang = Lang::getInstance(); + + int64 lastMillisCheck = 0; + uint64 waitLoopIterationCount = 0; + uint64 MAX_LOOP_COUNT_BEFORE_SLEEP = 100; + MAX_LOOP_COUNT_BEFORE_SLEEP = Config::getInstance().getInt( + "NetworkClientLoopGameLoadingCap", + intToStr(MAX_LOOP_COUNT_BEFORE_SLEEP).c_str()); + if (MAX_LOOP_COUNT_BEFORE_SLEEP == 0) { + MAX_LOOP_COUNT_BEFORE_SLEEP = 1; + } + int sleepMillis = Config::getInstance().getInt( + "NetworkClientLoopGameLoadingCapSleepMillis", "10"); + + // wait until we get a ready message from the server + while (true) { + // FOR TESTING ONLY - delay to see the client count up while waiting + // sleep(2000); + + waitLoopIterationCount++; + if (waitLoopIterationCount > 0 && + waitLoopIterationCount % MAX_LOOP_COUNT_BEFORE_SLEEP == 0) { + sleep(sleepMillis); + waitLoopIterationCount = 0; + } - //clientSocket->setBlock(true); - //send ready message - NetworkMessageReady networkMessageReady; - sendMessage(&networkMessageReady); + if (isConnected() == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + string sErr = "Error, Server has disconnected!"; + DisplayErrorMessage(sErr); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + setQuit(true); + close(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + return; + } + NetworkMessageType networkMessageType = getNextMessageType(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // consume old messages from the lobby + bool discarded = shouldDiscardNetworkMessage(networkMessageType); + if (discarded == false) { + if (networkMessageType == nmtReady) { + if (receiveMessage(&networkMessageReady)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + break; + } + } else if (networkMessageType == nmtLoadingStatusMessage) { + if (receiveMessage(&networkMessageLoadingStatus)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } + } else if (networkMessageType == nmtQuit) { + NetworkMessageQuit networkMessageQuit; + if (receiveMessage(&networkMessageQuit)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + DisplayErrorMessage(lang.getString("GameCancelledByUser")); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + setQuit(true); + close(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + return; + } + } else if (networkMessageType == nmtCommandList) { + // make sure we read the message + NetworkMessageCommandList networkMessageCommandList; + bool gotCmd = receiveMessage(&networkMessageCommandList); + if (gotCmd == false) { + throw megaglest_runtime_error( + "error retrieving nmtCommandList returned false!"); + } + } else if (networkMessageType == nmtInvalid) { + if (chrono.getMillis() > readyWaitTimeout) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + Lang &lang = Lang::getInstance(); + const vector languageList = + this->gameSettings.getUniqueNetworkPlayerLanguages(); + for (unsigned int i = 0; i < languageList.size(); ++i) { + string sErr = "Timeout waiting for server"; + if (lang.hasString("TimeoutWaitingForServer", languageList[i]) == + true) { + sErr = lang.getString("TimeoutWaitingForServer", languageList[i]); + } + bool echoLocal = lang.isLanguageLocal(lang.getLanguage()); + sendTextMessage(sErr, -1, echoLocal, languageList[i]); - NetworkMessageLoadingStatus networkMessageLoadingStatus(nmls_NONE); + if (echoLocal) { + DisplayErrorMessage(sErr); + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + sleep(1); + setQuit(true); + close(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + return; + } else { + if (chrono.getMillis() % 100 == 0) { + lastMillisCheck = (chrono.getMillis() / 1000); + + char szBuf[8096] = ""; + string updateTextFormat = "Waiting for network: %lld seconds " + "elapsed (maximum wait time: %d seconds)"; + if (lang.hasString("NetworkGameClientLoadStatus") == true) { + updateTextFormat = lang.getString("NetworkGameClientLoadStatus"); + } - Lang &lang= Lang::getInstance(); + string waitForHosts = ""; + if ((networkMessageLoadingStatus.getStatus() & + nmls_PLAYER1_CONNECTED) == nmls_PLAYER1_CONNECTED) { + if ((networkMessageLoadingStatus.getStatus() & + nmls_PLAYER1_READY) != nmls_PLAYER1_READY) { + if (waitForHosts != "") { + waitForHosts += ", "; + } + waitForHosts += + gameSettings.getNetworkPlayerNameByPlayerIndex(0); + } + } + if ((networkMessageLoadingStatus.getStatus() & + nmls_PLAYER2_CONNECTED) == nmls_PLAYER2_CONNECTED) { + if ((networkMessageLoadingStatus.getStatus() & + nmls_PLAYER2_READY) != nmls_PLAYER2_READY) { + if (waitForHosts != "") { + waitForHosts += ", "; + } + waitForHosts += + gameSettings.getNetworkPlayerNameByPlayerIndex(1); + } + } + if ((networkMessageLoadingStatus.getStatus() & + nmls_PLAYER3_CONNECTED) == nmls_PLAYER3_CONNECTED) { + if ((networkMessageLoadingStatus.getStatus() & + nmls_PLAYER3_READY) != nmls_PLAYER3_READY) { + if (waitForHosts != "") { + waitForHosts += ", "; + } + waitForHosts += + gameSettings.getNetworkPlayerNameByPlayerIndex(2); + } + } + if ((networkMessageLoadingStatus.getStatus() & + nmls_PLAYER4_CONNECTED) == nmls_PLAYER4_CONNECTED) { + if ((networkMessageLoadingStatus.getStatus() & + nmls_PLAYER4_READY) != nmls_PLAYER4_READY) { + if (waitForHosts != "") { + waitForHosts += ", "; + } + waitForHosts += + gameSettings.getNetworkPlayerNameByPlayerIndex(3); + } + } + if ((networkMessageLoadingStatus.getStatus() & + nmls_PLAYER5_CONNECTED) == nmls_PLAYER5_CONNECTED) { + if ((networkMessageLoadingStatus.getStatus() & + nmls_PLAYER5_READY) != nmls_PLAYER5_READY) { + if (waitForHosts != "") { + waitForHosts += ", "; + } + waitForHosts += + gameSettings.getNetworkPlayerNameByPlayerIndex(4); + } + } + if ((networkMessageLoadingStatus.getStatus() & + nmls_PLAYER6_CONNECTED) == nmls_PLAYER6_CONNECTED) { + if ((networkMessageLoadingStatus.getStatus() & + nmls_PLAYER6_READY) != nmls_PLAYER6_READY) { + if (waitForHosts != "") { + waitForHosts += ", "; + } + waitForHosts += + gameSettings.getNetworkPlayerNameByPlayerIndex(5); + } + } + if ((networkMessageLoadingStatus.getStatus() & + nmls_PLAYER7_CONNECTED) == nmls_PLAYER7_CONNECTED) { + if ((networkMessageLoadingStatus.getStatus() & + nmls_PLAYER7_READY) != nmls_PLAYER7_READY) { + if (waitForHosts != "") { + waitForHosts += ", "; + } + waitForHosts += + gameSettings.getNetworkPlayerNameByPlayerIndex(6); + } + } + if ((networkMessageLoadingStatus.getStatus() & + nmls_PLAYER8_CONNECTED) == nmls_PLAYER8_CONNECTED) { + if ((networkMessageLoadingStatus.getStatus() & + nmls_PLAYER8_READY) != nmls_PLAYER8_READY) { + if (waitForHosts != "") { + waitForHosts += ", "; + } + waitForHosts += + gameSettings.getNetworkPlayerNameByPlayerIndex(7); + } + } - int64 lastMillisCheck = 0; - uint64 waitLoopIterationCount = 0; - uint64 MAX_LOOP_COUNT_BEFORE_SLEEP = 100; - MAX_LOOP_COUNT_BEFORE_SLEEP = Config::getInstance().getInt("NetworkClientLoopGameLoadingCap",intToStr(MAX_LOOP_COUNT_BEFORE_SLEEP).c_str()); - if(MAX_LOOP_COUNT_BEFORE_SLEEP == 0) { - MAX_LOOP_COUNT_BEFORE_SLEEP = 1; - } - int sleepMillis = Config::getInstance().getInt("NetworkClientLoopGameLoadingCapSleepMillis","10"); + if (waitForHosts == "") { + waitForHosts = lang.getString("Server"); + } + snprintf(szBuf, 8096, updateTextFormat.c_str(), + (long long int)lastMillisCheck, + int(readyWaitTimeout / 1000)); + + char szBuf1[8096] = ""; + string statusTextFormat = "Waiting for players: %s"; + if (lang.hasString("NetworkGameStatusWaiting") == true) { + statusTextFormat = lang.getString("NetworkGameStatusWaiting"); + } + snprintf(szBuf1, 8096, statusTextFormat.c_str(), + waitForHosts.c_str()); - //wait until we get a ready message from the server - while(true) { - // FOR TESTING ONLY - delay to see the client count up while waiting - //sleep(2000); + logger.add(szBuf, true, szBuf1); - waitLoopIterationCount++; - if(waitLoopIterationCount > 0 && - waitLoopIterationCount % MAX_LOOP_COUNT_BEFORE_SLEEP == 0) { - sleep(sleepMillis); - waitLoopIterationCount = 0; - } + sleep(0); + } + } + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + sendTextMessage("Unexpected network message: " + + intToStr(networkMessageType), + -1, true, ""); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + DisplayErrorMessage( + string(extractFileFromDirectoryPath(__FILE__).c_str()) + + "::" + string(__FUNCTION__) + + " Unexpected network message: " + intToStr(networkMessageType)); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + sleep(1); + setQuit(true); + close(); - if(isConnected() == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + return; + } - string sErr = "Error, Server has disconnected!"; - DisplayErrorMessage(sErr); + Shared::Platform::Window::handleEvent(); + // sleep a bit + sleep(waitSleepTime); + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + // check checksum + if (getJoinGameInProgress() == false && + networkMessageReady.getChecksum() != checksum->getSum()) { + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + Lang &lang = Lang::getInstance(); + const vector languageList = + this->gameSettings.getUniqueNetworkPlayerLanguages(); + for (unsigned int langIndex = 0; langIndex < languageList.size(); + ++langIndex) { + + string sErr = + "Checksum error, you don't have the same data as the server"; + if (lang.hasString("CheckSumGameLoadError", languageList[langIndex]) == + true) { + sErr = lang.getString("CheckSumGameLoadError", languageList[langIndex]); + } + bool echoLocal = lang.isLanguageLocal(lang.getLanguage()); + sendTextMessage(sErr, -1, echoLocal, languageList[langIndex]); + + string playerNameStr = "Player with error is: " + getHumanPlayerName(); + if (lang.hasString("CheckSumGameLoadPlayer", languageList[langIndex]) == + true) { + playerNameStr = + lang.getString("CheckSumGameLoadPlayer", languageList[langIndex]) + + " " + getHumanPlayerName(); + } + sendTextMessage(playerNameStr, -1, echoLocal, languageList[langIndex]); + + string sErr1 = "Client Checksum: " + intToStr(checksum->getSum()); + if (lang.hasString("CheckSumGameLoadClient", languageList[langIndex]) == + true) { + sErr1 = + lang.getString("CheckSumGameLoadClient", languageList[langIndex]) + + " " + intToStr(checksum->getSum()); + } + + sendTextMessage(sErr1, -1, echoLocal, languageList[langIndex]); + + string sErr2 = + "Server Checksum: " + intToStr(networkMessageReady.getChecksum()); + if (lang.hasString("CheckSumGameLoadServer", languageList[langIndex]) == + true) { + sErr2 = + lang.getString("CheckSumGameLoadServer", languageList[langIndex]) + + " " + intToStr(networkMessageReady.getChecksum()); + } + sendTextMessage(sErr2, -1, echoLocal, languageList[langIndex]); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d %s %s %s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, sErr.c_str(), sErr1.c_str(), sErr2.c_str()); + + if (echoLocal == true) { + if (Config::getInstance().getBool("NetworkConsistencyChecks")) { + // error message and disconnect only if checked + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + string niceError = sErr + string("\n") + sErr1 + string("\n") + sErr2; + DisplayErrorMessage(niceError); + } + } + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (Config::getInstance().getBool("NetworkConsistencyChecks")) { + // error message and disconnect only if checked + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - setQuit(true); - close(); + sleep(1); + setQuit(true); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - return; - } - NetworkMessageType networkMessageType = getNextMessageType(); - - // consume old messages from the lobby - bool discarded = shouldDiscardNetworkMessage(networkMessageType); - if(discarded == false) { - if(networkMessageType == nmtReady) { - if(receiveMessage(&networkMessageReady)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - break; - } - } - else if(networkMessageType == nmtLoadingStatusMessage) { - if(receiveMessage(&networkMessageLoadingStatus)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - } - else if(networkMessageType == nmtQuit) { - NetworkMessageQuit networkMessageQuit; - if(receiveMessage(&networkMessageQuit)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - DisplayErrorMessage(lang.getString("GameCancelledByUser")); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - setQuit(true); - close(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - return; - - } - } - else if(networkMessageType == nmtCommandList) { - //make sure we read the message - NetworkMessageCommandList networkMessageCommandList; - bool gotCmd = receiveMessage(&networkMessageCommandList); - if(gotCmd == false) { - throw megaglest_runtime_error("error retrieving nmtCommandList returned false!"); - } - } - else if(networkMessageType == nmtInvalid) { - if(chrono.getMillis() > readyWaitTimeout) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - Lang &lang= Lang::getInstance(); - const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - string sErr = "Timeout waiting for server"; - if(lang.hasString("TimeoutWaitingForServer",languageList[i]) == true) { - sErr = lang.getString("TimeoutWaitingForServer",languageList[i]); - } - bool echoLocal = lang.isLanguageLocal(lang.getLanguage()); - sendTextMessage(sErr,-1,echoLocal,languageList[i]); - - if(echoLocal) { - DisplayErrorMessage(sErr); - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - sleep(1); - setQuit(true); - close(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - return; - } - else { - if(chrono.getMillis() % 100 == 0) { - lastMillisCheck = (chrono.getMillis() / 1000); - - char szBuf[8096]=""; - string updateTextFormat = "Waiting for network: %lld seconds elapsed (maximum wait time: %d seconds)"; - if(lang.hasString("NetworkGameClientLoadStatus") == true) { - updateTextFormat = lang.getString("NetworkGameClientLoadStatus"); - } - - string waitForHosts = ""; - if((networkMessageLoadingStatus.getStatus() & nmls_PLAYER1_CONNECTED) == nmls_PLAYER1_CONNECTED) { - if((networkMessageLoadingStatus.getStatus() & nmls_PLAYER1_READY) != nmls_PLAYER1_READY) { - if(waitForHosts != "") { - waitForHosts += ", "; - } - waitForHosts += gameSettings.getNetworkPlayerNameByPlayerIndex(0); - } - } - if((networkMessageLoadingStatus.getStatus() & nmls_PLAYER2_CONNECTED) == nmls_PLAYER2_CONNECTED) { - if((networkMessageLoadingStatus.getStatus() & nmls_PLAYER2_READY) != nmls_PLAYER2_READY) { - if(waitForHosts != "") { - waitForHosts += ", "; - } - waitForHosts += gameSettings.getNetworkPlayerNameByPlayerIndex(1); - } - } - if((networkMessageLoadingStatus.getStatus() & nmls_PLAYER3_CONNECTED) == nmls_PLAYER3_CONNECTED) { - if((networkMessageLoadingStatus.getStatus() & nmls_PLAYER3_READY) != nmls_PLAYER3_READY) { - if(waitForHosts != "") { - waitForHosts += ", "; - } - waitForHosts += gameSettings.getNetworkPlayerNameByPlayerIndex(2); - } - } - if((networkMessageLoadingStatus.getStatus() & nmls_PLAYER4_CONNECTED) == nmls_PLAYER4_CONNECTED) { - if((networkMessageLoadingStatus.getStatus() & nmls_PLAYER4_READY) != nmls_PLAYER4_READY) { - if(waitForHosts != "") { - waitForHosts += ", "; - } - waitForHosts += gameSettings.getNetworkPlayerNameByPlayerIndex(3); - } - } - if((networkMessageLoadingStatus.getStatus() & nmls_PLAYER5_CONNECTED) == nmls_PLAYER5_CONNECTED) { - if((networkMessageLoadingStatus.getStatus() & nmls_PLAYER5_READY) != nmls_PLAYER5_READY) { - if(waitForHosts != "") { - waitForHosts += ", "; - } - waitForHosts += gameSettings.getNetworkPlayerNameByPlayerIndex(4); - } - } - if((networkMessageLoadingStatus.getStatus() & nmls_PLAYER6_CONNECTED) == nmls_PLAYER6_CONNECTED) { - if((networkMessageLoadingStatus.getStatus() & nmls_PLAYER6_READY) != nmls_PLAYER6_READY) { - if(waitForHosts != "") { - waitForHosts += ", "; - } - waitForHosts += gameSettings.getNetworkPlayerNameByPlayerIndex(5); - } - } - if((networkMessageLoadingStatus.getStatus() & nmls_PLAYER7_CONNECTED) == nmls_PLAYER7_CONNECTED) { - if((networkMessageLoadingStatus.getStatus() & nmls_PLAYER7_READY) != nmls_PLAYER7_READY) { - if(waitForHosts != "") { - waitForHosts += ", "; - } - waitForHosts += gameSettings.getNetworkPlayerNameByPlayerIndex(6); - } - } - if((networkMessageLoadingStatus.getStatus() & nmls_PLAYER8_CONNECTED) == nmls_PLAYER8_CONNECTED) { - if((networkMessageLoadingStatus.getStatus() & nmls_PLAYER8_READY) != nmls_PLAYER8_READY) { - if(waitForHosts != "") { - waitForHosts += ", "; - } - waitForHosts += gameSettings.getNetworkPlayerNameByPlayerIndex(7); - } - } - - if(waitForHosts == "") { - waitForHosts = lang.getString("Server"); - } - snprintf(szBuf,8096,updateTextFormat.c_str(),(long long int)lastMillisCheck,int(readyWaitTimeout / 1000)); - - char szBuf1[8096]=""; - string statusTextFormat = "Waiting for players: %s"; - if(lang.hasString("NetworkGameStatusWaiting") == true) { - statusTextFormat = lang.getString("NetworkGameStatusWaiting"); - } - snprintf(szBuf1,8096,statusTextFormat.c_str(),waitForHosts.c_str()); - - logger.add(szBuf, true, szBuf1); - - sleep(0); - } - } - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - sendTextMessage("Unexpected network message: " + intToStr(networkMessageType),-1, true,""); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - DisplayErrorMessage(string(extractFileFromDirectoryPath(__FILE__).c_str()) + "::" + string(__FUNCTION__) + " Unexpected network message: " + intToStr(networkMessageType)); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - sleep(1); - setQuit(true); - close(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - return; - } - - Shared::Platform::Window::handleEvent(); - // sleep a bit - sleep(waitSleepTime); - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //check checksum - if(getJoinGameInProgress() == false && - networkMessageReady.getChecksum() != checksum->getSum()) { - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - Lang &lang= Lang::getInstance(); - const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); - for(unsigned int langIndex = 0; langIndex < languageList.size(); ++langIndex) { - - string sErr = "Checksum error, you don't have the same data as the server"; - if(lang.hasString("CheckSumGameLoadError",languageList[langIndex]) == true) { - sErr = lang.getString("CheckSumGameLoadError",languageList[langIndex]); - } - bool echoLocal = lang.isLanguageLocal(lang.getLanguage()); - sendTextMessage(sErr,-1,echoLocal,languageList[langIndex]); - - string playerNameStr = "Player with error is: " + getHumanPlayerName(); - if(lang.hasString("CheckSumGameLoadPlayer",languageList[langIndex]) == true) { - playerNameStr = lang.getString("CheckSumGameLoadPlayer",languageList[langIndex]) + " " + getHumanPlayerName(); - } - sendTextMessage(playerNameStr,-1,echoLocal,languageList[langIndex]); - - string sErr1 = "Client Checksum: " + intToStr(checksum->getSum()); - if(lang.hasString("CheckSumGameLoadClient",languageList[langIndex]) == true) { - sErr1 = lang.getString("CheckSumGameLoadClient",languageList[langIndex]) + " " + intToStr(checksum->getSum()); - } - - sendTextMessage(sErr1,-1,echoLocal,languageList[langIndex]); - - string sErr2 = "Server Checksum: " + intToStr(networkMessageReady.getChecksum()); - if(lang.hasString("CheckSumGameLoadServer",languageList[langIndex]) == true) { - sErr2 = lang.getString("CheckSumGameLoadServer",languageList[langIndex]) + " " + intToStr(networkMessageReady.getChecksum()); - } - sendTextMessage(sErr2,-1,echoLocal,languageList[langIndex]); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d %s %s %s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,sErr.c_str(),sErr1.c_str(),sErr2.c_str()); - - if(echoLocal == true) { - if(Config::getInstance().getBool("NetworkConsistencyChecks")) { - // error message and disconnect only if checked - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - string niceError = sErr + string("\n") + sErr1 + string("\n") + sErr2; - DisplayErrorMessage(niceError); - } - } - } - - if(Config::getInstance().getBool("NetworkConsistencyChecks")) { - // error message and disconnect only if checked - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - sleep(1); - setQuit(true); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + close(); + } + return; + } + + MutexSafeWrapper safeMutexFlags2(flagAccessor, CODE_AT_LINE); + this->joinGameInProgress = false; + this->joinGameInProgressLaunch = false; + + // printf("Client signalServerWhenReadyToStartJoinedGame = + // %d\n",signalServerWhenReadyToStartJoinedGame); + if (signalServerWhenReadyToStartJoinedGame == true) { + + Lang &lang = Lang::getInstance(); + const vector languageList = + this->gameSettings.getUniqueNetworkPlayerLanguages(); + for (unsigned int langIndex = 0; langIndex < languageList.size(); + ++langIndex) { + + string sText = "Player: %s is joining the game now."; + if (lang.hasString("JoinPlayerToCurrentGameLaunchDone", + languageList[langIndex]) == true) { + sText = lang.getString("JoinPlayerToCurrentGameLaunchDone", + languageList[langIndex]); + } + + if (clientSocket != NULL && clientSocket->isConnected() == true) { + string playerNameStr = getHumanPlayerName(); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, sText.c_str(), playerNameStr.c_str()); + + sendTextMessage(szBuf, -1, false, languageList[langIndex]); + } + } - close(); - } - return; - } - - MutexSafeWrapper safeMutexFlags2(flagAccessor,CODE_AT_LINE); - this->joinGameInProgress = false; - this->joinGameInProgressLaunch = false; - - //printf("Client signalServerWhenReadyToStartJoinedGame = %d\n",signalServerWhenReadyToStartJoinedGame); - if(signalServerWhenReadyToStartJoinedGame == true) { - - Lang &lang= Lang::getInstance(); - const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); - for(unsigned int langIndex = 0; langIndex < languageList.size(); ++langIndex) { - - string sText = "Player: %s is joining the game now."; - if(lang.hasString("JoinPlayerToCurrentGameLaunchDone",languageList[langIndex]) == true) { - sText = lang.getString("JoinPlayerToCurrentGameLaunchDone",languageList[langIndex]); - } - - if(clientSocket != NULL && clientSocket->isConnected() == true) { - string playerNameStr = getHumanPlayerName(); - char szBuf[8096]=""; - snprintf(szBuf,8096,sText.c_str(),playerNameStr.c_str()); - - sendTextMessage(szBuf,-1,false,languageList[langIndex]); - } - } - - this->resumeInGameJoin = true; - safeMutexFlags2.ReleaseLock(); - } - else { - safeMutexFlags2.ReleaseLock(); - // delay the start a bit, so clients have more room to get messages - // This is to ensure clients don't start ahead of the server and thus - // constantly freeze because they are waiting for the server to catch up - sleep(120); - } - - // This triggers LAG update packets to begin as required - lastNetworkCommandListSendTime = time(NULL); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] END\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); + this->resumeInGameJoin = true; + safeMutexFlags2.ReleaseLock(); + } else { + safeMutexFlags2.ReleaseLock(); + // delay the start a bit, so clients have more room to get messages + // This is to ensure clients don't start ahead of the server and thus + // constantly freeze because they are waiting for the server to catch up + sleep(120); + } + + // This triggers LAG update packets to begin as required + lastNetworkCommandListSendTime = time(NULL); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, "In [%s::%s] END\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__); } void ClientInterface::sendResumeGameMessage() { - NetworkMessageReady networkMessageReady; - sendMessage(&networkMessageReady); + NetworkMessageReady networkMessageReady; + sendMessage(&networkMessageReady); } -void ClientInterface::sendTextMessage(const string &text, int teamIndex, bool echoLocal, - string targetLanguage) { - - string humanPlayerName = getHumanPlayerName(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] humanPlayerName = [%s] playerIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,humanPlayerName.c_str(),playerIndex); - - NetworkMessageText networkMessageText(text, teamIndex,playerIndex,targetLanguage); - sendMessage(&networkMessageText); - - if(echoLocal == true) { - ChatMsgInfo msg(networkMessageText.getText().c_str(),networkMessageText.getTeamIndex(),networkMessageText.getPlayerIndex(),targetLanguage); - this->addChatInfo(msg); - } +void ClientInterface::sendTextMessage(const string &text, int teamIndex, + bool echoLocal, string targetLanguage) { + + string humanPlayerName = getHumanPlayerName(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] humanPlayerName = [%s] playerIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + humanPlayerName.c_str(), playerIndex); + + NetworkMessageText networkMessageText(text, teamIndex, playerIndex, + targetLanguage); + sendMessage(&networkMessageText); + + if (echoLocal == true) { + ChatMsgInfo msg(networkMessageText.getText().c_str(), + networkMessageText.getTeamIndex(), + networkMessageText.getPlayerIndex(), targetLanguage); + this->addChatInfo(msg); + } } -void ClientInterface::sendMarkCellMessage(Vec2i targetPos, int factionIndex, string note,int playerIndex) { - string humanPlayerName = getHumanPlayerName(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] humanPlayerName = [%s] playerIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,humanPlayerName.c_str(),playerIndex); - - NetworkMessageMarkCell networkMessageMarkCell(targetPos,factionIndex, note,playerIndex); - sendMessage(&networkMessageMarkCell); +void ClientInterface::sendMarkCellMessage(Vec2i targetPos, int factionIndex, + string note, int playerIndex) { + string humanPlayerName = getHumanPlayerName(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] humanPlayerName = [%s] playerIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + humanPlayerName.c_str(), playerIndex); + + NetworkMessageMarkCell networkMessageMarkCell(targetPos, factionIndex, note, + playerIndex); + sendMessage(&networkMessageMarkCell); } -void ClientInterface::sendHighlightCellMessage(Vec2i targetPos, int factionIndex) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] playerIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playerIndex); - - NetworkMessageHighlightCell networkMessageHighlightCell(targetPos,factionIndex); - sendMessage(&networkMessageHighlightCell); +void ClientInterface::sendHighlightCellMessage(Vec2i targetPos, + int factionIndex) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] playerIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, playerIndex); + + NetworkMessageHighlightCell networkMessageHighlightCell(targetPos, + factionIndex); + sendMessage(&networkMessageHighlightCell); } void ClientInterface::sendUnMarkCellMessage(Vec2i targetPos, int factionIndex) { - string humanPlayerName = getHumanPlayerName(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] humanPlayerName = [%s] playerIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,humanPlayerName.c_str(),playerIndex); - - NetworkMessageUnMarkCell networkMessageMarkCell(targetPos,factionIndex); - sendMessage(&networkMessageMarkCell); + string humanPlayerName = getHumanPlayerName(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] humanPlayerName = [%s] playerIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + humanPlayerName.c_str(), playerIndex); + + NetworkMessageUnMarkCell networkMessageMarkCell(targetPos, factionIndex); + sendMessage(&networkMessageMarkCell); } void ClientInterface::sendPingMessage(int32 pingFrequency, int64 pingTime) { - NetworkMessagePing networkMessagePing(pingFrequency,pingTime); - sendMessage(&networkMessagePing); + NetworkMessagePing networkMessagePing(pingFrequency, pingTime); + sendMessage(&networkMessagePing); } string ClientInterface::getNetworkStatus() { - std::string label = Lang::getInstance().getString("Server") + ": " + serverName; - //float pingTime = getThreadedPingMS(getServerIpAddress().c_str()); - char szBuf[8096]=""; - snprintf(szBuf,8096,"%s",label.c_str()); + std::string label = + Lang::getInstance().getString("Server") + ": " + serverName; + // float pingTime = getThreadedPingMS(getServerIpAddress().c_str()); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "%s", label.c_str()); - return szBuf; + return szBuf; } -NetworkMessageType ClientInterface::waitForMessage(int waitMicroseconds) -{ - // Debug! -/* - sendTextMessage("Timeout waiting for message",-1); - DisplayErrorMessage("Timeout waiting for message"); - quit= true; - close(); - return; -*/ - - uint64 loopCount = 0; - Chrono chronoPerf; - if(debugClientInterfacePerf == true) { - chronoPerf.start(); - } - - Chrono chrono; - chrono.start(); - - NetworkMessageType msg = nmtInvalid; - while( msg == nmtInvalid && - getQuitThread() == false) { - - msg = getNextMessageType(waitMicroseconds); - if(msg == nmtInvalid) { - if(getSocket() == NULL || (chrono.getMillis() % 250 == 0 && isConnected() == false)) { - if(getQuit() == false) { - //throw megaglest_runtime_error("Disconnected"); - //sendTextMessage("Server has Disconnected.",-1); - DisplayErrorMessage("Server has Disconnected."); - setQuit(true); - } - close(); - return msg; - } - - if(chrono.getMillis() > messageWaitTimeout) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - Lang &lang= Lang::getInstance(); - const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); - for(unsigned int langIndex = 0; langIndex < languageList.size(); ++langIndex) { - - string msg = "Timeout waiting for message."; - if(lang.hasString("TimeoutWaitingForMessage",languageList[langIndex]) == true) { - msg = lang.getString("TimeoutWaitingForMessage",languageList[langIndex]); - } - - sendTextMessage(msg,-1, lang.isLanguageLocal(languageList[langIndex]),languageList[langIndex]); - if(lang.isLanguageLocal(languageList[langIndex]) == true) { - DisplayErrorMessage(msg); - } - } - - sleep(1); - setQuit(true); - close(); - return msg; - } - // Sleep every x milli-seconds we wait to let other threads work - else if(chrono.getMillis() % 2 == 0) { - sleep(1); - } - else { - sleep(0); - } - } - - if(debugClientInterfacePerf == true) { - loopCount++; - if(chronoPerf.getMillis() >= 100) { - printf("Client waitForMessage loopCount = %llu\n",(long long unsigned int)loopCount); - - loopCount = 0; - chronoPerf.start(); - } - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] waiting took %lld msecs, msg = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis(),msg); - - return msg; -} - -void ClientInterface::quitGame(bool userManuallyQuit) -{ - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] userManuallyQuit = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,userManuallyQuit); +NetworkMessageType ClientInterface::waitForMessage(int waitMicroseconds) { + // Debug! + /* + sendTextMessage("Timeout waiting for message",-1); + DisplayErrorMessage("Timeout waiting for message"); + quit= true; + close(); + return; + */ + + uint64 loopCount = 0; + Chrono chronoPerf; + if (debugClientInterfacePerf == true) { + chronoPerf.start(); + } + + Chrono chrono; + chrono.start(); + + NetworkMessageType msg = nmtInvalid; + while (msg == nmtInvalid && getQuitThread() == false) { + + msg = getNextMessageType(waitMicroseconds); + if (msg == nmtInvalid) { + if (getSocket() == NULL || + (chrono.getMillis() % 250 == 0 && isConnected() == false)) { + if (getQuit() == false) { + // throw megaglest_runtime_error("Disconnected"); + // sendTextMessage("Server has Disconnected.",-1); + DisplayErrorMessage("Server has Disconnected."); + setQuit(true); + } + close(); + return msg; + } + + if (chrono.getMillis() > messageWaitTimeout) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + Lang &lang = Lang::getInstance(); + const vector languageList = + this->gameSettings.getUniqueNetworkPlayerLanguages(); + for (unsigned int langIndex = 0; langIndex < languageList.size(); + ++langIndex) { + + string msg = "Timeout waiting for message."; + if (lang.hasString("TimeoutWaitingForMessage", + languageList[langIndex]) == true) { + msg = lang.getString("TimeoutWaitingForMessage", + languageList[langIndex]); + } + + sendTextMessage(msg, -1, + lang.isLanguageLocal(languageList[langIndex]), + languageList[langIndex]); + if (lang.isLanguageLocal(languageList[langIndex]) == true) { + DisplayErrorMessage(msg); + } + } - if(clientSocket != NULL && userManuallyQuit == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + sleep(1); + setQuit(true); + close(); + return msg; + } + // Sleep every x milli-seconds we wait to let other threads work + else if (chrono.getMillis() % 2 == 0) { + sleep(1); + } else { + sleep(0); + } + } - Lang &lang= Lang::getInstance(); - const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); - for(unsigned int langIndex = 0; langIndex < languageList.size(); ++langIndex) { + if (debugClientInterfacePerf == true) { + loopCount++; + if (chronoPerf.getMillis() >= 100) { + printf("Client waitForMessage loopCount = %llu\n", + (long long unsigned int)loopCount); - string msg = "has chosen to leave the game!"; - if(lang.hasString("PlayerLeftGame",languageList[langIndex]) == true) { - msg = lang.getString("PlayerLeftGame",languageList[langIndex]); - } + loopCount = 0; + chronoPerf.start(); + } + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 1) + SystemFlags::OutputDebug( + SystemFlags::debugPerformance, + "In [%s::%s Line: %d] waiting took %lld msecs, msg = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + chrono.getMillis(), msg); + + return msg; +} - sendTextMessage(msg,-1, lang.isLanguageLocal(languageList[langIndex]),languageList[langIndex]); - } - sleep(1); - close(); +void ClientInterface::quitGame(bool userManuallyQuit) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] userManuallyQuit = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, userManuallyQuit); + + if (clientSocket != NULL && userManuallyQuit == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + Lang &lang = Lang::getInstance(); + const vector languageList = + this->gameSettings.getUniqueNetworkPlayerLanguages(); + for (unsigned int langIndex = 0; langIndex < languageList.size(); + ++langIndex) { + + string msg = "has chosen to leave the game!"; + if (lang.hasString("PlayerLeftGame", languageList[langIndex]) == true) { + msg = lang.getString("PlayerLeftGame", languageList[langIndex]); + } + + sendTextMessage(msg, -1, lang.isLanguageLocal(languageList[langIndex]), + languageList[langIndex]); } + sleep(1); + close(); + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Lined: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Lined: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); } void ClientInterface::close(bool lockMutex) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] START, clientSocket = %p\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,clientSocket); - - MutexSafeWrapper safeMutex(NULL,CODE_AT_LINE); - if(lockMutex == true) { - safeMutex.setMutex(networkCommandListThreadAccessor,CODE_AT_LINE); - } - shutdownNetworkCommandListThread(safeMutex); - - delete clientSocket; - clientSocket = NULL; - - safeMutex.ReleaseLock(); - - connectedTime = 0; - gotIntro = false; - - MutexSafeWrapper safeMutexFlags(flagAccessor,CODE_AT_LINE); - this->joinGameInProgress = false; - this->joinGameInProgressLaunch = false; - this->readyForInGameJoin = false; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] END\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] START, clientSocket = %p\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, clientSocket); + + MutexSafeWrapper safeMutex(NULL, CODE_AT_LINE); + if (lockMutex == true) { + safeMutex.setMutex(networkCommandListThreadAccessor, CODE_AT_LINE); + } + shutdownNetworkCommandListThread(safeMutex); + + delete clientSocket; + clientSocket = NULL; + + safeMutex.ReleaseLock(); + + connectedTime = 0; + gotIntro = false; + + MutexSafeWrapper safeMutexFlags(flagAccessor, CODE_AT_LINE); + this->joinGameInProgress = false; + this->joinGameInProgressLaunch = false; + this->readyForInGameJoin = false; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d] END\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); } -void ClientInterface::close() { - close(true); -} +void ClientInterface::close() { close(true); } void ClientInterface::discoverServers(DiscoveredServersInterface *cb) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); - ClientSocket::discoverServers(cb); + ClientSocket::discoverServers(cb); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); } void ClientInterface::stopServerDiscovery() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); - ClientSocket::stopBroadCastClientThread(); + ClientSocket::stopBroadCastClientThread(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); } -void ClientInterface::sendSwitchSetupRequest(string selectedFactionName, int8 currentSlotIndex, - int8 toSlotIndex,int8 toTeam, string networkPlayerName, - int8 networkPlayerStatus, int8 flags, - string language) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] networkPlayerName [%s] flags = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkPlayerName.c_str(),flags); - SwitchSetupRequest message = SwitchSetupRequest(selectedFactionName, - currentSlotIndex, toSlotIndex,toTeam,networkPlayerName, - networkPlayerStatus, flags,language); - sendMessage(&message); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void ClientInterface::sendSwitchSetupRequest(string selectedFactionName, + int8 currentSlotIndex, + int8 toSlotIndex, int8 toTeam, + string networkPlayerName, + int8 networkPlayerStatus, + int8 flags, string language) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] networkPlayerName [%s] flags = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + networkPlayerName.c_str(), flags); + SwitchSetupRequest message = SwitchSetupRequest( + selectedFactionName, currentSlotIndex, toSlotIndex, toTeam, + networkPlayerName, networkPlayerStatus, flags, language); + sendMessage(&message); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); } -bool ClientInterface::shouldDiscardNetworkMessage(NetworkMessageType networkMessageType) { - bool discard = false; - - switch(networkMessageType) { - case nmtIntro: - { - discard = true; - NetworkMessageIntro msg = NetworkMessageIntro(); - this->receiveMessage(&msg); - } - break; - case nmtPing: - { - discard = true; - NetworkMessagePing msg = NetworkMessagePing(); - this->receiveMessage(&msg); - this->setLastPingInfo(msg); - } - break; - case nmtLaunch: - { - discard = true; - NetworkMessageLaunch msg = NetworkMessageLaunch(); - this->receiveMessage(&msg); - } - break; - case nmtText: - { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] got nmtText\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - discard = true; - NetworkMessageText netMsg = NetworkMessageText(); - this->receiveMessage(&netMsg); - - ChatMsgInfo msg(netMsg.getText().c_str(),netMsg.getTeamIndex(),netMsg.getPlayerIndex(),netMsg.getTargetLanguage()); - this->addChatInfo(msg); - } - break; - - case nmtMarkCell: - { - discard = true; - NetworkMessageMarkCell networkMessageMarkCell; - receiveMessage(&networkMessageMarkCell); - - MarkedCell msg(networkMessageMarkCell.getTarget(), - networkMessageMarkCell.getFactionIndex(), - networkMessageMarkCell.getText().c_str(), - networkMessageMarkCell.getPlayerIndex()); - this->addMarkedCell(msg); - } - break; - - case nmtUnMarkCell: - { - discard = true; - NetworkMessageUnMarkCell networkMessageMarkCell; - receiveMessage(&networkMessageMarkCell); - - UnMarkedCell msg(networkMessageMarkCell.getTarget(), - networkMessageMarkCell.getFactionIndex()); - this->addUnMarkedCell(msg); - } - break; - - case nmtHighlightCell: - { - discard = true; - NetworkMessageHighlightCell networkMessageHighlightCell; - receiveMessage(&networkMessageHighlightCell); - - MarkedCell msg(networkMessageHighlightCell.getTarget(), - networkMessageHighlightCell.getFactionIndex(), - "none",-1); - this->setHighlightedCell(msg); - } - break; - - case nmtSynchNetworkGameData: - { - discard = true; - NetworkMessageSynchNetworkGameData msg = NetworkMessageSynchNetworkGameData(); - this->receiveMessage(&msg); - } - break; - case nmtSynchNetworkGameDataStatus: - { - discard = true; - NetworkMessageSynchNetworkGameDataStatus msg = NetworkMessageSynchNetworkGameDataStatus(); - this->receiveMessage(&msg); - } - break; - case nmtSynchNetworkGameDataFileCRCCheck: - { - discard = true; - NetworkMessageSynchNetworkGameDataFileCRCCheck msg = NetworkMessageSynchNetworkGameDataFileCRCCheck(); - this->receiveMessage(&msg); - } - break; - case nmtSynchNetworkGameDataFileGet: - { - discard = true; - NetworkMessageSynchNetworkGameDataFileGet msg = NetworkMessageSynchNetworkGameDataFileGet(); - this->receiveMessage(&msg); - } - break; - case nmtSwitchSetupRequest: - { - discard = true; - SwitchSetupRequest msg = SwitchSetupRequest(); - this->receiveMessage(&msg); - } - break; - case nmtBroadCastSetup: - { - discard = true; - NetworkMessageLaunch msg = NetworkMessageLaunch(); - this->receiveMessage(&msg); - } - break; - - case nmtPlayerIndexMessage: - { - discard = true; - PlayerIndexMessage msg = PlayerIndexMessage(0); - this->receiveMessage(&msg); - } - break; - } - - return discard; +bool ClientInterface::shouldDiscardNetworkMessage( + NetworkMessageType networkMessageType) { + bool discard = false; + + switch (networkMessageType) { + case nmtIntro: { + discard = true; + NetworkMessageIntro msg = NetworkMessageIntro(); + this->receiveMessage(&msg); + } break; + case nmtPing: { + discard = true; + NetworkMessagePing msg = NetworkMessagePing(); + this->receiveMessage(&msg); + this->setLastPingInfo(msg); + } break; + case nmtLaunch: { + discard = true; + NetworkMessageLaunch msg = NetworkMessageLaunch(); + this->receiveMessage(&msg); + } break; + case nmtText: { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] got nmtText\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + discard = true; + NetworkMessageText netMsg = NetworkMessageText(); + this->receiveMessage(&netMsg); + + ChatMsgInfo msg(netMsg.getText().c_str(), netMsg.getTeamIndex(), + netMsg.getPlayerIndex(), netMsg.getTargetLanguage()); + this->addChatInfo(msg); + } break; + + case nmtMarkCell: { + discard = true; + NetworkMessageMarkCell networkMessageMarkCell; + receiveMessage(&networkMessageMarkCell); + + MarkedCell msg(networkMessageMarkCell.getTarget(), + networkMessageMarkCell.getFactionIndex(), + networkMessageMarkCell.getText().c_str(), + networkMessageMarkCell.getPlayerIndex()); + this->addMarkedCell(msg); + } break; + + case nmtUnMarkCell: { + discard = true; + NetworkMessageUnMarkCell networkMessageMarkCell; + receiveMessage(&networkMessageMarkCell); + + UnMarkedCell msg(networkMessageMarkCell.getTarget(), + networkMessageMarkCell.getFactionIndex()); + this->addUnMarkedCell(msg); + } break; + + case nmtHighlightCell: { + discard = true; + NetworkMessageHighlightCell networkMessageHighlightCell; + receiveMessage(&networkMessageHighlightCell); + + MarkedCell msg(networkMessageHighlightCell.getTarget(), + networkMessageHighlightCell.getFactionIndex(), "none", -1); + this->setHighlightedCell(msg); + } break; + + case nmtSynchNetworkGameData: { + discard = true; + NetworkMessageSynchNetworkGameData msg = + NetworkMessageSynchNetworkGameData(); + this->receiveMessage(&msg); + } break; + case nmtSynchNetworkGameDataStatus: { + discard = true; + NetworkMessageSynchNetworkGameDataStatus msg = + NetworkMessageSynchNetworkGameDataStatus(); + this->receiveMessage(&msg); + } break; + case nmtSynchNetworkGameDataFileCRCCheck: { + discard = true; + NetworkMessageSynchNetworkGameDataFileCRCCheck msg = + NetworkMessageSynchNetworkGameDataFileCRCCheck(); + this->receiveMessage(&msg); + } break; + case nmtSynchNetworkGameDataFileGet: { + discard = true; + NetworkMessageSynchNetworkGameDataFileGet msg = + NetworkMessageSynchNetworkGameDataFileGet(); + this->receiveMessage(&msg); + } break; + case nmtSwitchSetupRequest: { + discard = true; + SwitchSetupRequest msg = SwitchSetupRequest(); + this->receiveMessage(&msg); + } break; + case nmtBroadCastSetup: { + discard = true; + NetworkMessageLaunch msg = NetworkMessageLaunch(); + this->receiveMessage(&msg); + } break; + + case nmtPlayerIndexMessage: { + discard = true; + PlayerIndexMessage msg = PlayerIndexMessage(0); + this->receiveMessage(&msg); + } break; + } + + return discard; } string ClientInterface::getHumanPlayerName(int index) { - string result = Config::getInstance().getString("NetPlayerName",Socket::getHostName().c_str()); - - if(index >= 0 || gameSettings.getThisFactionIndex() >= 0) { - if(index < 0) { - index = gameSettings.getThisFactionIndex(); - } - if(gameSettings.getNetworkPlayerName(index) != "") { - result = gameSettings.getNetworkPlayerName(index); - } - } - - return result; + string result = Config::getInstance().getString( + "NetPlayerName", Socket::getHostName().c_str()); + + if (index >= 0 || gameSettings.getThisFactionIndex() >= 0) { + if (index < 0) { + index = gameSettings.getThisFactionIndex(); + } + if (gameSettings.getNetworkPlayerName(index) != "") { + result = gameSettings.getNetworkPlayerName(index); + } + } + + return result; } void ClientInterface::setGameSettings(GameSettings *serverGameSettings) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] START\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, "In [%s::%s] START\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__); - gameSettings = *serverGameSettings; + gameSettings = *serverGameSettings; - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] END\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, "In [%s::%s] END\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__); } void ClientInterface::broadcastGameSetup(const GameSettings *gameSettings) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - NetworkMessageLaunch networkMessageLaunch(gameSettings, nmtBroadCastSetup); - sendMessage(&networkMessageLaunch); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + NetworkMessageLaunch networkMessageLaunch(gameSettings, nmtBroadCastSetup); + sendMessage(&networkMessageLaunch); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); } void ClientInterface::broadcastGameStart(const GameSettings *gameSettings) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - MutexSafeWrapper safeMutexFlags(flagAccessor,CODE_AT_LINE); - if(this->joinGameInProgress == true) { - this->joinGameInProgressLaunch = true; - } - safeMutexFlags.ReleaseLock(); - - //printf("Sending game launch joinGameInProgress: %d\n",joinGameInProgress); - - NetworkMessageLaunch networkMessageLaunch(gameSettings, nmtLaunch); - sendMessage(&networkMessageLaunch); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + MutexSafeWrapper safeMutexFlags(flagAccessor, CODE_AT_LINE); + if (this->joinGameInProgress == true) { + this->joinGameInProgressLaunch = true; + } + safeMutexFlags.ReleaseLock(); + + // printf("Sending game launch joinGameInProgress: %d\n",joinGameInProgress); + + NetworkMessageLaunch networkMessageLaunch(gameSettings, nmtLaunch); + sendMessage(&networkMessageLaunch); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); } void ClientInterface::setGameSettingsReceived(bool value) { - //printf("In [%s:%s] Line: %d gameSettingsReceived = %d value = %d, gameSettingsReceivedCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,gameSettingsReceived,value,gameSettingsReceivedCount); - gameSettingsReceived = value; - gameSettingsReceivedCount++; + // printf("In [%s:%s] Line: %d gameSettingsReceived = %d value = %d, + // gameSettingsReceivedCount = + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,gameSettingsReceived,value,gameSettingsReceivedCount); + gameSettingsReceived = value; + gameSettingsReceivedCount++; } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/network/client_interface.h b/source/glest_game/network/client_interface.h index 6190ceb65..bb870608f 100644 --- a/source/glest_game/network/client_interface.h +++ b/source/glest_game/network/client_interface.h @@ -13,194 +13,198 @@ #define _GLEST_GAME_CLIENTINTERFACE_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include +#include "leak_dumper.h" #include "network_interface.h" #include "socket.h" -#include "leak_dumper.h" +#include -using Shared::Platform::Ip; using Shared::Platform::ClientSocket; +using Shared::Platform::Ip; using std::vector; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { class ClientInterface; -class ClientInterfaceThread : public BaseThread, public SlaveThreadControllerInterface { +class ClientInterfaceThread : public BaseThread, + public SlaveThreadControllerInterface { protected: + ClientInterface *clientInterface; - ClientInterface *clientInterface; - - virtual void setQuitStatus(bool value); + virtual void setQuitStatus(bool value); public: - explicit ClientInterfaceThread(ClientInterface *client); - virtual ~ClientInterfaceThread(); - virtual void execute(); + explicit ClientInterfaceThread(ClientInterface *client); + virtual ~ClientInterfaceThread(); + virtual void execute(); - virtual void setMasterController(MasterSlaveThreadController *master) { } - virtual void signalSlave(void *userdata) { } + virtual void setMasterController(MasterSlaveThreadController *master) {} + virtual void signalSlave(void *userdata) {} - virtual bool canShutdown(bool deleteSelfIfShutdownDelayed=false); + virtual bool canShutdown(bool deleteSelfIfShutdownDelayed = false); }; // ===================================================== // class ClientInterface // ===================================================== -class ClientInterface: public GameNetworkInterface { +class ClientInterface : public GameNetworkInterface { private: - static const int messageWaitTimeout; - static const int waitSleepTime; - static const int maxNetworkCommandListSendTimeWait; + static const int messageWaitTimeout; + static const int waitSleepTime; + static const int maxNetworkCommandListSendTimeWait; private: - ClientSocket *clientSocket; - string serverName; - bool introDone; - bool launchGame; - int playerIndex; - bool gameSettingsReceived; - int gameSettingsReceivedCount; - time_t connectedTime; - bool gotIntro; - - Ip ip; - int port; - - int currentFrameCount; - int lastSentFrameCount; - time_t lastNetworkCommandListSendTime; - - time_t clientSimulationLagStartTime; - string versionString; - int sessionKey; - int serverFTPPort; - - string serverUUID; - string serverPlatform; - - ClientInterfaceThread *networkCommandListThread; - - Mutex *networkCommandListThreadAccessor; - std::map cachedPendingCommands; //commands ready to be given - std::map > cachedPendingCommandCRCs; //commands ready to be given - uint64 cachedPendingCommandsIndex; - uint64 cachedLastPendingFrameCount; - int64 timeClientWaitedForLastMessage; - - Mutex *flagAccessor; - bool joinGameInProgress; - bool joinGameInProgressLaunch; - bool readyForInGameJoin; - bool resumeInGameJoin; - - Mutex *quitThreadAccessor; - bool quitThread; - - bool getQuitThread(); - void setQuitThread(bool value); - bool getQuit(); - void setQuit(bool value); + ClientSocket *clientSocket; + string serverName; + bool introDone; + bool launchGame; + int playerIndex; + bool gameSettingsReceived; + int gameSettingsReceivedCount; + time_t connectedTime; + bool gotIntro; + + Ip ip; + int port; + + int currentFrameCount; + int lastSentFrameCount; + time_t lastNetworkCommandListSendTime; + + time_t clientSimulationLagStartTime; + string versionString; + int sessionKey; + int serverFTPPort; + + string serverUUID; + string serverPlatform; + + ClientInterfaceThread *networkCommandListThread; + + Mutex *networkCommandListThreadAccessor; + std::map cachedPendingCommands; // commands ready to be given + std::map> + cachedPendingCommandCRCs; // commands ready to be given + uint64 cachedPendingCommandsIndex; + uint64 cachedLastPendingFrameCount; + int64 timeClientWaitedForLastMessage; + + Mutex *flagAccessor; + bool joinGameInProgress; + bool joinGameInProgressLaunch; + bool readyForInGameJoin; + bool resumeInGameJoin; + + Mutex *quitThreadAccessor; + bool quitThread; + + bool getQuitThread(); + void setQuitThread(bool value); + bool getQuit(); + void setQuit(bool value); public: - ClientInterface(); - virtual ~ClientInterface(); + ClientInterface(); + virtual ~ClientInterface(); - virtual std::string getIpAddress(bool mutexLock=true); - virtual Socket* getSocket(bool mutexLock=true) {return clientSocket;} - virtual void close(); + virtual std::string getIpAddress(bool mutexLock = true); + virtual Socket *getSocket(bool mutexLock = true) { return clientSocket; } + virtual void close(); - bool getJoinGameInProgress(); - bool getJoinGameInProgressLaunch(); + bool getJoinGameInProgress(); + bool getJoinGameInProgressLaunch(); - bool getReadyForInGameJoin(); + bool getReadyForInGameJoin(); - bool getResumeInGameJoin(); - void sendResumeGameMessage(); + bool getResumeInGameJoin(); + void sendResumeGameMessage(); - uint64 getCachedLastPendingFrameCount(); - int64 getTimeClientWaitedForLastMessage(); + uint64 getCachedLastPendingFrameCount(); + int64 getTimeClientWaitedForLastMessage(); - //message processing - virtual void update(); - virtual void updateLobby(); - virtual void updateKeyframe(int frameCount); - virtual void setKeyframe(int frameCount) { currentFrameCount = frameCount; } - virtual void waitUntilReady(Checksum* checksum); + // message processing + virtual void update(); + virtual void updateLobby(); + virtual void updateKeyframe(int frameCount); + virtual void setKeyframe(int frameCount) { currentFrameCount = frameCount; } + virtual void waitUntilReady(Checksum *checksum); - // message sending - virtual void sendTextMessage(const string &text, int teamIndex, bool echoLocal, - string targetLanguage); - virtual void quitGame(bool userManuallyQuit); + // message sending + virtual void sendTextMessage(const string &text, int teamIndex, + bool echoLocal, string targetLanguage); + virtual void quitGame(bool userManuallyQuit); - virtual void sendMarkCellMessage(Vec2i targetPos, int factionIndex, string note,int playerIndex); - virtual void sendUnMarkCellMessage(Vec2i targetPos, int factionIndex); - virtual void sendHighlightCellMessage(Vec2i targetPos, int factionIndex); - //misc - virtual string getNetworkStatus() ; + virtual void sendMarkCellMessage(Vec2i targetPos, int factionIndex, + string note, int playerIndex); + virtual void sendUnMarkCellMessage(Vec2i targetPos, int factionIndex); + virtual void sendHighlightCellMessage(Vec2i targetPos, int factionIndex); + // misc + virtual string getNetworkStatus(); - //accessors - string getServerName() const {return serverName;} - bool getLaunchGame() const {return launchGame;} - bool getIntroDone() const {return introDone;} - bool getGameSettingsReceived() const {return gameSettingsReceived;} - void setGameSettingsReceived(bool value); + // accessors + string getServerName() const { return serverName; } + bool getLaunchGame() const { return launchGame; } + bool getIntroDone() const { return introDone; } + bool getGameSettingsReceived() const { return gameSettingsReceived; } + void setGameSettingsReceived(bool value); - int getGameSettingsReceivedCount() const { return gameSettingsReceivedCount; } + int getGameSettingsReceivedCount() const { return gameSettingsReceivedCount; } - int getPlayerIndex() const {return playerIndex;} + int getPlayerIndex() const { return playerIndex; } - void connect(const Ip &ip, int port); - void reset(); + void connect(const Ip &ip, int port); + void reset(); - void discoverServers(DiscoveredServersInterface *cb); - void stopServerDiscovery(); - - void sendSwitchSetupRequest(string selectedFactionName, int8 currentSlotIndex, - int8 toSlotIndex, int8 toTeam,string networkPlayerName, - int8 networkPlayerStatus, int8 flags, - string language); - virtual bool getConnectHasHandshaked() const { return gotIntro; } - std::string getServerIpAddress(); + void discoverServers(DiscoveredServersInterface *cb); + void stopServerDiscovery(); - int getCurrentFrameCount() const { return currentFrameCount; } + void sendSwitchSetupRequest(string selectedFactionName, int8 currentSlotIndex, + int8 toSlotIndex, int8 toTeam, + string networkPlayerName, + int8 networkPlayerStatus, int8 flags, + string language); + virtual bool getConnectHasHandshaked() const { return gotIntro; } + std::string getServerIpAddress(); - virtual void sendPingMessage(int32 pingFrequency, int64 pingTime); + int getCurrentFrameCount() const { return currentFrameCount; } - const string &getVersionString() const {return versionString;} - virtual string getHumanPlayerName(int index=-1); - virtual int getHumanPlayerIndex() const {return playerIndex;} - int getServerFTPPort() const { return serverFTPPort; } + virtual void sendPingMessage(int32 pingFrequency, int64 pingTime); - int getSessionKey() const { return sessionKey; } - bool isMasterServerAdminOverride(); + const string &getVersionString() const { return versionString; } + virtual string getHumanPlayerName(int index = -1); + virtual int getHumanPlayerIndex() const { return playerIndex; } + int getServerFTPPort() const { return serverFTPPort; } - void setGameSettings(GameSettings *serverGameSettings); - void broadcastGameSetup(const GameSettings *gameSettings); - void broadcastGameStart(const GameSettings *gameSettings); + int getSessionKey() const { return sessionKey; } + bool isMasterServerAdminOverride(); - void updateNetworkFrame(); + void setGameSettings(GameSettings *serverGameSettings); + void broadcastGameSetup(const GameSettings *gameSettings); + void broadcastGameStart(const GameSettings *gameSettings); - virtual void saveGame(XmlNode *rootNode) {}; + void updateNetworkFrame(); -protected: + virtual void saveGame(XmlNode *rootNode){}; - Mutex * getServerSynchAccessor() { return NULL; } - NetworkMessageType waitForMessage(int waitMicroseconds=0); - bool shouldDiscardNetworkMessage(NetworkMessageType networkMessageType); +protected: + Mutex *getServerSynchAccessor() { return NULL; } + NetworkMessageType waitForMessage(int waitMicroseconds = 0); + bool shouldDiscardNetworkMessage(NetworkMessageType networkMessageType); - void updateFrame(int *checkFrame); - void shutdownNetworkCommandListThread(MutexSafeWrapper &safeMutexWrapper); - bool getNetworkCommand(int frameCount, int currentCachedPendingCommandsIndex); + void updateFrame(int *checkFrame); + void shutdownNetworkCommandListThread(MutexSafeWrapper &safeMutexWrapper); + bool getNetworkCommand(int frameCount, int currentCachedPendingCommandsIndex); - void close(bool lockMutex); + void close(bool lockMutex); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/network/connection_slot.cpp b/source/glest_game/network/connection_slot.cpp index 6dc7ad346..5eca627d7 100644 --- a/source/glest_game/network/connection_slot.cpp +++ b/source/glest_game/network/connection_slot.cpp @@ -11,12 +11,12 @@ #include "connection_slot.h" +#include "config.h" #include "conversion.h" #include "game_util.h" -#include "config.h" -#include "server_interface.h" #include "network_message.h" #include "platform_util.h" +#include "server_interface.h" #include #include "leak_dumper.h" @@ -24,1629 +24,2478 @@ using namespace std; using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class ConnectionSlotThread // ===================================================== ConnectionSlotThread::ConnectionSlotThread(int slotIndex) : BaseThread() { - this->masterController = NULL; - this->triggerIdMutex = new Mutex(CODE_AT_LINE); - this->slotIndex = slotIndex; - this->slotInterface = NULL; - uniqueID = "ConnectionSlotThread"; - eventList.clear(); - eventList.reserve(1000); - - triggerGameStarted = new Mutex(CODE_AT_LINE); - gameStarted = false; + this->masterController = NULL; + this->triggerIdMutex = new Mutex(CODE_AT_LINE); + this->slotIndex = slotIndex; + this->slotInterface = NULL; + uniqueID = "ConnectionSlotThread"; + eventList.clear(); + eventList.reserve(1000); + + triggerGameStarted = new Mutex(CODE_AT_LINE); + gameStarted = false; } -ConnectionSlotThread::ConnectionSlotThread(ConnectionSlotCallbackInterface *slotInterface,int slotIndex) : BaseThread() { - this->masterController = NULL; - this->triggerIdMutex = new Mutex(CODE_AT_LINE); - this->slotIndex = slotIndex; - this->slotInterface = slotInterface; - uniqueID = "ConnectionSlotThread"; - eventList.clear(); - - triggerGameStarted = new Mutex(CODE_AT_LINE); - gameStarted = false; +ConnectionSlotThread::ConnectionSlotThread( + ConnectionSlotCallbackInterface *slotInterface, int slotIndex) + : BaseThread() { + this->masterController = NULL; + this->triggerIdMutex = new Mutex(CODE_AT_LINE); + this->slotIndex = slotIndex; + this->slotInterface = slotInterface; + uniqueID = "ConnectionSlotThread"; + eventList.clear(); + + triggerGameStarted = new Mutex(CODE_AT_LINE); + gameStarted = false; } ConnectionSlotThread::~ConnectionSlotThread() { - delete triggerIdMutex; - triggerIdMutex = NULL; + delete triggerIdMutex; + triggerIdMutex = NULL; - delete triggerGameStarted; - triggerGameStarted = NULL; + delete triggerGameStarted; + triggerGameStarted = NULL; } void ConnectionSlotThread::setQuitStatus(bool value) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d value = %d\n",__FILE__,__FUNCTION__,__LINE__,value); - - BaseThread::setQuitStatus(value); - if(value == true) { - signalUpdate(NULL); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s] Line: %d value = %d\n", __FILE__, + __FUNCTION__, __LINE__, value); + + BaseThread::setQuitStatus(value); + if (value == true) { + signalUpdate(NULL); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s] Line: %d\n", __FILE__, __FUNCTION__, + __LINE__); } void ConnectionSlotThread::signalUpdate(ConnectionSlotEvent *event) { - if(event != NULL) { - MutexSafeWrapper safeMutex(triggerIdMutex,CODE_AT_LINE); - eventList.push_back(*event); - } - if(getGameStarted() == true && getQuitStatus() == true) { - return; - } - semTaskSignalled.signal(); + if (event != NULL) { + MutexSafeWrapper safeMutex(triggerIdMutex, CODE_AT_LINE); + eventList.push_back(*event); + } + if (getGameStarted() == true && getQuitStatus() == true) { + return; + } + semTaskSignalled.signal(); } void ConnectionSlotThread::setTaskCompleted(int eventId) { - if(eventId > 0) { - MutexSafeWrapper safeMutex(triggerIdMutex,CODE_AT_LINE); - for(int index = 0; index < (int)eventList.size(); ++index) { - ConnectionSlotEvent &slotEvent = eventList[index]; - if(slotEvent.eventId == eventId) { - slotEvent.eventCompleted = true; - break; - } - } - } + if (eventId > 0) { + MutexSafeWrapper safeMutex(triggerIdMutex, CODE_AT_LINE); + for (int index = 0; index < (int)eventList.size(); ++index) { + ConnectionSlotEvent &slotEvent = eventList[index]; + if (slotEvent.eventId == eventId) { + slotEvent.eventCompleted = true; + break; + } + } + } } -//void ConnectionSlotThread::purgeAllEvents() { -// MutexSafeWrapper safeMutex(triggerIdMutex,CODE_AT_LINE); -// eventList.clear(); -//} +// void ConnectionSlotThread::purgeAllEvents() { +// MutexSafeWrapper safeMutex(triggerIdMutex,CODE_AT_LINE); +// eventList.clear(); +// } void ConnectionSlotThread::setAllEventsCompleted() { - MutexSafeWrapper safeMutex(triggerIdMutex,CODE_AT_LINE); - for(int index = 0; index < (int)eventList.size(); ++index) { - ConnectionSlotEvent &slotEvent = eventList[index]; - if(slotEvent.eventCompleted == false) { - slotEvent.eventCompleted = true; - } + MutexSafeWrapper safeMutex(triggerIdMutex, CODE_AT_LINE); + for (int index = 0; index < (int)eventList.size(); ++index) { + ConnectionSlotEvent &slotEvent = eventList[index]; + if (slotEvent.eventCompleted == false) { + slotEvent.eventCompleted = true; } + } } void ConnectionSlotThread::purgeCompletedEvents() { - MutexSafeWrapper safeMutex(triggerIdMutex,CODE_AT_LINE); - for(int index = (int)eventList.size() - 1; index >= 0; index--) { - ConnectionSlotEvent &slotEvent = eventList[index]; - if(slotEvent.eventCompleted == true) { - eventList.erase(eventList.begin() + index); - } + MutexSafeWrapper safeMutex(triggerIdMutex, CODE_AT_LINE); + for (int index = (int)eventList.size() - 1; index >= 0; index--) { + ConnectionSlotEvent &slotEvent = eventList[index]; + if (slotEvent.eventCompleted == true) { + eventList.erase(eventList.begin() + index); } + } } bool ConnectionSlotThread::canShutdown(bool deleteSelfIfShutdownDelayed) { - bool ret = (getExecutingTask() == false); - if(ret == false && deleteSelfIfShutdownDelayed == true) { - setDeleteSelfOnExecutionDone(deleteSelfIfShutdownDelayed); - deleteSelfIfRequired(); - signalQuit(); - } - - return ret; + bool ret = (getExecutingTask() == false); + if (ret == false && deleteSelfIfShutdownDelayed == true) { + setDeleteSelfOnExecutionDone(deleteSelfIfShutdownDelayed); + deleteSelfIfRequired(); + signalQuit(); + } + + return ret; } bool ConnectionSlotThread::isSignalCompleted(ConnectionSlotEvent *event) { - bool result = false; - if(event != NULL) { - MutexSafeWrapper safeMutex(triggerIdMutex,CODE_AT_LINE); - for(int index = 0; index < (int)eventList.size(); ++index) { - ConnectionSlotEvent &slotEvent = eventList[index]; - if(slotEvent.eventId == event->eventId) { - result = slotEvent.eventCompleted; - break; - } - } + bool result = false; + if (event != NULL) { + MutexSafeWrapper safeMutex(triggerIdMutex, CODE_AT_LINE); + for (int index = 0; index < (int)eventList.size(); ++index) { + ConnectionSlotEvent &slotEvent = eventList[index]; + if (slotEvent.eventId == event->eventId) { + result = slotEvent.eventCompleted; + break; + } } - return result; + } + return result; } void ConnectionSlotThread::slotUpdateTask(ConnectionSlotEvent *event) { - if(event != NULL && event->connectionSlot != NULL) { - if(event->eventType == eSendSocketData) { - event->connectionSlot->sendMessage(event->networkMessage); - } - else if(event->eventType == eReceiveSocketData) { - event->connectionSlot->updateSlot(event); - } - } + if (event != NULL && event->connectionSlot != NULL) { + if (event->eventType == eSendSocketData) { + event->connectionSlot->sendMessage(event->networkMessage); + } else if (event->eventType == eReceiveSocketData) { + event->connectionSlot->updateSlot(event); + } + } } void ConnectionSlotThread::signalSlave(void *userdata) { - std::map *eventList = (std::map *)userdata; - ConnectionSlotEvent &event = (*eventList)[slotIndex]; - signalUpdate(&event); + std::map *eventList = + (std::map *)userdata; + ConnectionSlotEvent &event = (*eventList)[slotIndex]; + signalUpdate(&event); } bool ConnectionSlotThread::getGameStarted() { - MutexSafeWrapper safeMutexGameStarted(triggerGameStarted,CODE_AT_LINE); - return gameStarted; + MutexSafeWrapper safeMutexGameStarted(triggerGameStarted, CODE_AT_LINE); + return gameStarted; } void ConnectionSlotThread::setGameStarted(bool value) { - MutexSafeWrapper safeMutexGameStarted(triggerGameStarted,CODE_AT_LINE); - if(gameStarted != value) { - gameStarted = value; - - if(gameStarted == true) { - semTaskSignalled.signal(); - } - } + MutexSafeWrapper safeMutexGameStarted(triggerGameStarted, CODE_AT_LINE); + if (gameStarted != value) { + gameStarted = value; + + if (gameStarted == true) { + semTaskSignalled.signal(); + } + } } void ConnectionSlotThread::execute() { - RunningStatusSafeWrapper runningStatus(this); - try { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - //printf("Starting client SLOT thread: %d\n",slotIndex); - - for(;this->slotInterface != NULL;) { - if(getQuitStatus() == true) { - SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - break; - } - - // Does this game allow joining in progress play and is this slot - // not already connected to a client? - if( this->slotInterface->getAllowInGameConnections() == true && - this->slotInterface->isClientConnected(slotIndex) == false) { - //printf("#1 Non connected slot: %d waiting for client connection..\n",slotIndex); - sleep(100); - - if(getQuitStatus() == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - break; - } - - //printf("Slot thread slotIndex: %d eventCount: %d\n",slotIndex,eventCount); - - ConnectionSlotEvent eventCopy; - eventCopy.eventType = eReceiveSocketData; - eventCopy.connectionSlot = this->slotInterface->getSlot(slotIndex,true); - - if(getQuitStatus() == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - break; - } - - ExecutingTaskSafeWrapper safeExecutingTaskMutex(this); - this->slotUpdateTask(&eventCopy); - } - else { - // If the game already started? - if(getGameStarted() == true) { - //printf("#A Checking action for slot: %d\n",slotIndex); - - if(getQuitStatus() == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - break; - } - - ExecutingTaskSafeWrapper safeExecutingTaskMutex(this); - - // If the slot or socket are NULL the connection was lost - // so exit the thread - MutexSafeWrapper safeMutex(this->slotInterface->getSlotMutex(slotIndex),CODE_AT_LINE); - ConnectionSlot *slot = this->slotInterface->getSlot(slotIndex,false); - if(slot == NULL) { - break; - } - Socket *socket = slot->getSocket(true); - if(socket == NULL) { - break; - } - - PLATFORM_SOCKET socketId = socket->getSocketId(); - safeMutex.ReleaseLock(); - - // Avoid mutex locking - //bool socketHasReadData = Socket::hasDataToRead(socket->getSocketId()); - bool socketHasReadData = Socket::hasDataToReadWithWait(socketId,150000); - - if(getQuitStatus() == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - break; - } - - ConnectionSlotEvent eventCopy; - eventCopy.eventType = eReceiveSocketData; - eventCopy.connectionSlot = this->slotInterface->getSlot(slotIndex,true); - eventCopy.eventId = slotIndex; - eventCopy.socketTriggered = socketHasReadData; - - if(getQuitStatus() == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - break; - } - - this->slotUpdateTask(&eventCopy); - } - // Game has not yet started - else { - //printf("#1 Checking action for slot: %d\n",slotIndex); - - if(getGameStarted() == true) { - continue; - } - //printf("#2 Checking action for slot: %d\n",slotIndex); - - semTaskSignalled.waitTillSignalled(); - //printf("#3 Checking action for slot: %d\n",slotIndex); - - if(getGameStarted() == true) { - continue; - } - //printf("#4 Checking action for slot: %d\n",slotIndex); - - static string masterSlaveOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MasterSlaveThreadControllerSafeWrapper safeMasterController(masterController,20000,masterSlaveOwnerId); - if(getQuitStatus() == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - break; - } - - MutexSafeWrapper safeMutex(triggerIdMutex,CODE_AT_LINE); - int eventCount = (int)eventList.size(); - - //printf("Slot thread slotIndex: %d eventCount: %d\n",slotIndex,eventCount); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] Slot thread slotIndex: %d eventCount: %d\n",__FILE__,__FUNCTION__,__LINE__,slotIndex,eventCount); - - if(eventCount > 0) { - ConnectionSlotEvent eventCopy; - for(int i = 0; i < (int)eventList.size(); ++i) { - ConnectionSlotEvent &slotEvent = eventList[i]; - if(slotEvent.eventCompleted == false) { - eventCopy = slotEvent; - break; - } - } - safeMutex.ReleaseLock(); - - if(getQuitStatus() == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - break; - } - - if(eventCopy.eventId > 0) { - ExecutingTaskSafeWrapper safeExecutingTaskMutex(this); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] Slot thread slotIndex: %d eventCount: %d eventCopy.eventId: %d\n",__FILE__,__FUNCTION__,__LINE__,slotIndex,eventCount,(int)eventCopy.eventId); - //printf("#1 Slot thread slotIndex: %d eventCount: %d eventCopy.eventId: %d\n",slotIndex,eventCount,(int)eventCopy.eventId); - - this->slotUpdateTask(&eventCopy); - setTaskCompleted(eventCopy.eventId); - - //printf("#2 Slot thread slotIndex: %d eventCount: %d eventCopy.eventId: %d\n",slotIndex,eventCount,(int)eventCopy.eventId); - } - } - } - } - - if(getQuitStatus() == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - break; - } - } - - //printf("Ending client SLOT thread: %d\n",slotIndex); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - } - catch(const exception &ex) { - - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - throw megaglest_runtime_error(ex.what()); - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); + RunningStatusSafeWrapper runningStatus(this); + try { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + // printf("Starting client SLOT thread: %d\n",slotIndex); + + for (; this->slotInterface != NULL;) { + if (getQuitStatus() == true) { + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + break; + } + + // Does this game allow joining in progress play and is this slot + // not already connected to a client? + if (this->slotInterface->getAllowInGameConnections() == true && + this->slotInterface->isClientConnected(slotIndex) == false) { + // printf("#1 Non connected slot: %d waiting for client + // connection..\n",slotIndex); + sleep(100); + + if (getQuitStatus() == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + break; + } + + // printf("Slot thread slotIndex: %d eventCount: + // %d\n",slotIndex,eventCount); + + ConnectionSlotEvent eventCopy; + eventCopy.eventType = eReceiveSocketData; + eventCopy.connectionSlot = + this->slotInterface->getSlot(slotIndex, true); + + if (getQuitStatus() == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + break; + } + + ExecutingTaskSafeWrapper safeExecutingTaskMutex(this); + this->slotUpdateTask(&eventCopy); + } else { + // If the game already started? + if (getGameStarted() == true) { + // printf("#A Checking action for slot: %d\n",slotIndex); + + if (getQuitStatus() == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + break; + } + + ExecutingTaskSafeWrapper safeExecutingTaskMutex(this); + + // If the slot or socket are NULL the connection was lost + // so exit the thread + MutexSafeWrapper safeMutex( + this->slotInterface->getSlotMutex(slotIndex), CODE_AT_LINE); + ConnectionSlot *slot = this->slotInterface->getSlot(slotIndex, false); + if (slot == NULL) { + break; + } + Socket *socket = slot->getSocket(true); + if (socket == NULL) { + break; + } + + PLATFORM_SOCKET socketId = socket->getSocketId(); + safeMutex.ReleaseLock(); + + // Avoid mutex locking + // bool socketHasReadData = + // Socket::hasDataToRead(socket->getSocketId()); + bool socketHasReadData = + Socket::hasDataToReadWithWait(socketId, 150000); + + if (getQuitStatus() == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + break; + } + + ConnectionSlotEvent eventCopy; + eventCopy.eventType = eReceiveSocketData; + eventCopy.connectionSlot = + this->slotInterface->getSlot(slotIndex, true); + eventCopy.eventId = slotIndex; + eventCopy.socketTriggered = socketHasReadData; + + if (getQuitStatus() == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + break; + } + + this->slotUpdateTask(&eventCopy); + } + // Game has not yet started + else { + // printf("#1 Checking action for slot: %d\n",slotIndex); + + if (getGameStarted() == true) { + continue; + } + // printf("#2 Checking action for slot: %d\n",slotIndex); + + semTaskSignalled.waitTillSignalled(); + // printf("#3 Checking action for slot: %d\n",slotIndex); + + if (getGameStarted() == true) { + continue; + } + // printf("#4 Checking action for slot: %d\n",slotIndex); + + static string masterSlaveOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MasterSlaveThreadControllerSafeWrapper safeMasterController( + masterController, 20000, masterSlaveOwnerId); + if (getQuitStatus() == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + break; + } + + MutexSafeWrapper safeMutex(triggerIdMutex, CODE_AT_LINE); + int eventCount = (int)eventList.size(); + + // printf("Slot thread slotIndex: %d eventCount: + // %d\n",slotIndex,eventCount); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] Slot thread " + "slotIndex: %d eventCount: %d\n", + __FILE__, __FUNCTION__, __LINE__, + slotIndex, eventCount); + + if (eventCount > 0) { + ConnectionSlotEvent eventCopy; + for (int i = 0; i < (int)eventList.size(); ++i) { + ConnectionSlotEvent &slotEvent = eventList[i]; + if (slotEvent.eventCompleted == false) { + eventCopy = slotEvent; + break; + } + } + safeMutex.ReleaseLock(); + + if (getQuitStatus() == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + break; + } + + if (eventCopy.eventId > 0) { + ExecutingTaskSafeWrapper safeExecutingTaskMutex(this); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] Slot thread slotIndex: %d " + "eventCount: %d eventCopy.eventId: %d\n", + __FILE__, __FUNCTION__, __LINE__, slotIndex, eventCount, + (int)eventCopy.eventId); + // printf("#1 Slot thread slotIndex: %d eventCount: %d + // eventCopy.eventId: + // %d\n",slotIndex,eventCount,(int)eventCopy.eventId); + + this->slotUpdateTask(&eventCopy); + setTaskCompleted(eventCopy.eventId); + + // printf("#2 Slot thread slotIndex: %d eventCount: %d + // eventCopy.eventId: + // %d\n",slotIndex,eventCount,(int)eventCopy.eventId); + } + } + } + } + + if (getQuitStatus() == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + break; + } + } + + // printf("Ending client SLOT thread: %d\n",slotIndex); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + } catch (const exception &ex) { + + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", __FILE__, + __FUNCTION__, __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + throw megaglest_runtime_error(ex.what()); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s] Line: %d\n", __FILE__, __FUNCTION__, + __LINE__); } // ===================================================== // class ConnectionSlot // ===================================================== -ConnectionSlot::ConnectionSlot(ServerInterface* serverInterface, int playerIndex) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); - - this->mutexSocket = new Mutex(CODE_AT_LINE); - this->socket = NULL; - this->mutexCloseConnection = new Mutex(CODE_AT_LINE); - this->mutexPendingNetworkCommandList = new Mutex(CODE_AT_LINE); - this->socketSynchAccessor = new Mutex(CODE_AT_LINE); - this->connectedRemoteIPAddress = 0; - this->sessionKey = 0; - this->serverInterface = serverInterface; - this->playerIndex = playerIndex; - this->playerStatus = npst_None; - this->playerLanguage = ""; - this->playerUUID = ""; - this->platform = ""; - this->currentFrameCount = 0; - this->currentLagCount = 0; - this->gotLagCountWarning = false; - this->lastReceiveCommandListTime = 0; - this->receivedNetworkGameStatus = false; - - this->autoPauseGameCountForLag = 0; - this->skipLagCheck = false; - this->joinGameInProgress = false; - this->canAcceptConnections = true; - this->startInGameConnectionLaunch = false; - this->pauseForInGameConnection = false; - this->unPauseForInGameConnection = false; - this->sentSavedGameInfo = false; - - this->ready = false; - this->gotIntro = false; - this->connectedTime = 0; - - this->networkGameDataSynchCheckOkMap = false; - this->networkGameDataSynchCheckOkTile = false; - this->networkGameDataSynchCheckOkTech = false; - this->setNetworkGameDataSynchCheckTechMismatchReport(""); - this->setReceivedDataSynchCheck(false); - - this->clearChatInfo(); - - this->setSocket(NULL); - this->slotThreadWorker = NULL; - static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); - this->slotThreadWorker = new ConnectionSlotThread(this->serverInterface,playerIndex); - this->slotThreadWorker->setUniqueID(mutexOwnerId); - this->slotThreadWorker->start(); +ConnectionSlot::ConnectionSlot(ServerInterface *serverInterface, + int playerIndex) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s] Line: %d\n", __FILE__, __FUNCTION__, + __LINE__); + + this->mutexSocket = new Mutex(CODE_AT_LINE); + this->socket = NULL; + this->mutexCloseConnection = new Mutex(CODE_AT_LINE); + this->mutexPendingNetworkCommandList = new Mutex(CODE_AT_LINE); + this->socketSynchAccessor = new Mutex(CODE_AT_LINE); + this->connectedRemoteIPAddress = 0; + this->sessionKey = 0; + this->serverInterface = serverInterface; + this->playerIndex = playerIndex; + this->playerStatus = npst_None; + this->playerLanguage = ""; + this->playerUUID = ""; + this->platform = ""; + this->currentFrameCount = 0; + this->currentLagCount = 0; + this->gotLagCountWarning = false; + this->lastReceiveCommandListTime = 0; + this->receivedNetworkGameStatus = false; + + this->autoPauseGameCountForLag = 0; + this->skipLagCheck = false; + this->joinGameInProgress = false; + this->canAcceptConnections = true; + this->startInGameConnectionLaunch = false; + this->pauseForInGameConnection = false; + this->unPauseForInGameConnection = false; + this->sentSavedGameInfo = false; + + this->ready = false; + this->gotIntro = false; + this->connectedTime = 0; + + this->networkGameDataSynchCheckOkMap = false; + this->networkGameDataSynchCheckOkTile = false; + this->networkGameDataSynchCheckOkTech = false; + this->setNetworkGameDataSynchCheckTechMismatchReport(""); + this->setReceivedDataSynchCheck(false); + + this->clearChatInfo(); + + this->setSocket(NULL); + this->slotThreadWorker = NULL; + static string mutexOwnerId = + string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + + intToStr(__LINE__); + this->slotThreadWorker = + new ConnectionSlotThread(this->serverInterface, playerIndex); + this->slotThreadWorker->setUniqueID(mutexOwnerId); + this->slotThreadWorker->start(); } ConnectionSlot::~ConnectionSlot() { - //printf("===> Destructor for ConnectionSlot = %d\n",playerIndex); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] START\n",__FILE__,__FUNCTION__,__LINE__); - - //printf("Deleting connection slot\n"); - close(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - //printf("#1 Ending client SLOT: %d slotThreadWorker: %p\n",playerIndex,slotThreadWorker); - if(slotThreadWorker != NULL) { - slotThreadWorker->signalQuit(); - } - if( slotThreadWorker != NULL && - slotThreadWorker->canShutdown(false) == true && - slotThreadWorker->getRunningStatus() == false) { - //printf("#2 Ending client SLOT: %d\n",playerIndex); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - delete slotThreadWorker; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - } - else if(slotThreadWorker != NULL && - slotThreadWorker->canShutdown(true) == true) { - - if(slotThreadWorker->getRunningStatus() == false) { - //printf("#3 Ending client SLOT: %d\n",playerIndex); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - delete slotThreadWorker; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - } - else { - slotThreadWorker->setDeleteSelfOnExecutionDone(true); - slotThreadWorker->setDeleteAfterExecute(true); - } - } - //printf("#4 Ending client SLOT: %d\n",playerIndex); - slotThreadWorker = NULL; + // printf("===> Destructor for ConnectionSlot = %d\n",playerIndex); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] START\n", __FILE__, + __FUNCTION__, __LINE__); + + // printf("Deleting connection slot\n"); + close(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + // printf("#1 Ending client SLOT: %d slotThreadWorker: + // %p\n",playerIndex,slotThreadWorker); + if (slotThreadWorker != NULL) { + slotThreadWorker->signalQuit(); + } + if (slotThreadWorker != NULL && + slotThreadWorker->canShutdown(false) == true && + slotThreadWorker->getRunningStatus() == false) { + // printf("#2 Ending client SLOT: %d\n",playerIndex); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + delete slotThreadWorker; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + } else if (slotThreadWorker != NULL && + slotThreadWorker->canShutdown(true) == true) { + + if (slotThreadWorker->getRunningStatus() == false) { + // printf("#3 Ending client SLOT: %d\n",playerIndex); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + + delete slotThreadWorker; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + } else { + slotThreadWorker->setDeleteSelfOnExecutionDone(true); + slotThreadWorker->setDeleteAfterExecute(true); + } + } + // printf("#4 Ending client SLOT: %d\n",playerIndex); + slotThreadWorker = NULL; - delete socketSynchAccessor; - socketSynchAccessor = NULL; + delete socketSynchAccessor; + socketSynchAccessor = NULL; - delete mutexPendingNetworkCommandList; - mutexPendingNetworkCommandList = NULL; + delete mutexPendingNetworkCommandList; + mutexPendingNetworkCommandList = NULL; - delete mutexCloseConnection; - mutexCloseConnection = NULL; + delete mutexCloseConnection; + mutexCloseConnection = NULL; - delete mutexSocket; - mutexSocket = NULL; + delete mutexSocket; + mutexSocket = NULL; - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] END\n",__FILE__,__FUNCTION__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, "In [%s::%s] END\n", + __FILE__, __FUNCTION__); } int ConnectionSlot::getAutoPauseGameCountForLag() { - return autoPauseGameCountForLag; + return autoPauseGameCountForLag; } void ConnectionSlot::incrementAutoPauseGameCountForLag() { - autoPauseGameCountForLag++; + autoPauseGameCountForLag++; } bool ConnectionSlot::getGameStarted() { - bool result = false; - if(this->slotThreadWorker != NULL) { - result = this->slotThreadWorker->getGameStarted(); - } - return result; + bool result = false; + if (this->slotThreadWorker != NULL) { + result = this->slotThreadWorker->getGameStarted(); + } + return result; } void ConnectionSlot::setGameStarted(bool value) { - if(this->slotThreadWorker != NULL) { - this->slotThreadWorker->setGameStarted(value); - } + if (this->slotThreadWorker != NULL) { + this->slotThreadWorker->setGameStarted(value); + } } void ConnectionSlot::setPlayerIndex(int value) { - playerIndex = value; + playerIndex = value; - if(this->slotThreadWorker != NULL) { - this->slotThreadWorker->setSlotIndex(playerIndex); - } + if (this->slotThreadWorker != NULL) { + this->slotThreadWorker->setSlotIndex(playerIndex); + } } -void ConnectionSlot::setReady() { - this->ready= true; - this->skipLagCheck = false; - this->joinGameInProgress = false; - this->sentSavedGameInfo = false; +void ConnectionSlot::setReady() { + this->ready = true; + this->skipLagCheck = false; + this->joinGameInProgress = false; + this->sentSavedGameInfo = false; } void ConnectionSlot::updateSlot(ConnectionSlotEvent *event) { - if(event != NULL) { - bool &socketTriggered = event->socketTriggered; - bool checkForNewClients = - (serverInterface->getGameHasBeenInitiated() == false || - serverInterface->getAllowInGameConnections() == true); - - //if((serverInterface->getGameHasBeenInitiated() == false || - // (serverInterface->getAllowInGameConnections() == true && this->isConnected() == false) || - // socketTriggered == true)) { - if(socketTriggered == true || - ((serverInterface->getGameHasBeenInitiated() == false || - serverInterface->getAllowInGameConnections() == true) && - this->isConnected() == false)) { - - this->update(checkForNewClients,event->triggerId); - } - //} - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (event != NULL) { + bool &socketTriggered = event->socketTriggered; + bool checkForNewClients = + (serverInterface->getGameHasBeenInitiated() == false || + serverInterface->getAllowInGameConnections() == true); + + // if((serverInterface->getGameHasBeenInitiated() == false || + // (serverInterface->getAllowInGameConnections() == true && + // this->isConnected() == false) || socketTriggered == true)) { + if (socketTriggered == true || + ((serverInterface->getGameHasBeenInitiated() == false || + serverInterface->getAllowInGameConnections() == true) && + this->isConnected() == false)) { + + this->update(checkForNewClients, event->triggerId); + } + //} + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); } string ConnectionSlot::getIpAddress(bool mutexLock) { - string result = ""; - MutexSafeWrapper safeMutexSlot((mutexLock == true ? mutexSocket : NULL),CODE_AT_LINE); - if(socket != NULL) { - result = socket->getIpAddress(); - } - return result; + string result = ""; + MutexSafeWrapper safeMutexSlot((mutexLock == true ? mutexSocket : NULL), + CODE_AT_LINE); + if (socket != NULL) { + result = socket->getIpAddress(); + } + return result; } -void ConnectionSlot::update(bool checkForNewClients,int lockedSlotIndex) { - try { - clearThreadErrorList(); - - if(slotThreadWorker != NULL) { - slotThreadWorker->purgeCompletedEvents(); - } - - pair socketInfo = this->getSocketInfo(); - if(socketInfo.second == NULL) { - if(networkGameDataSynchCheckOkMap) networkGameDataSynchCheckOkMap = false; - if(networkGameDataSynchCheckOkTile) networkGameDataSynchCheckOkTile = false; - if(networkGameDataSynchCheckOkTech) networkGameDataSynchCheckOkTech = false; - this->setReceivedDataSynchCheck(false); - - // Is the listener socket ready to be read? - if(checkForNewClients == true && this->canAcceptConnections == true) { - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] BEFORE accept new client connection, serverInterface->getOpenSlotCount() = %d\n",__FILE__,__FUNCTION__,__LINE__,serverInterface->getOpenSlotCount()); - - //printf("Checking for new connections...\n"); - bool hasData = (serverInterface->getServerSocket() != NULL && - serverInterface->getServerSocket()->hasDataToRead() == true); - //printf("Server socket hasData: %d\n",hasData); - - if(hasData == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] about to accept new client connection playerIndex = %d\n",__FILE__,__FUNCTION__,__LINE__,playerIndex); - - Socket *newSocket = serverInterface->getServerSocket()->accept(false); - - //printf("Server socket newSocket: %p\n",newSocket); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] called accept new client connection playerIndex = %d newSocket = %p\n",__FILE__,__FUNCTION__,__LINE__,playerIndex,newSocket); - if(newSocket != NULL) { - // Set Socket as non-blocking - newSocket->setBlock(false); - - MutexSafeWrapper safeMutex(mutexCloseConnection,CODE_AT_LINE); - this->setSocket(newSocket); - safeMutex.ReleaseLock(); - - this->connectedTime = time(NULL); - this->clearChatInfo(); - this->name = ""; - this->playerStatus = npst_PickSettings; - this->playerLanguage = ""; - this->playerUUID = ""; - this->platform = ""; - this->ready = false; - this->vctFileList.clear(); - this->receivedNetworkGameStatus = false; - this->gotIntro = false; - - MutexSafeWrapper safeMutexSlot1(mutexPendingNetworkCommandList,CODE_AT_LINE); - this->vctPendingNetworkCommandList.clear(); - safeMutexSlot1.ReleaseLock(); - - this->currentFrameCount = 0; - this->currentLagCount = 0; - this->lastReceiveCommandListTime = 0; - this->gotLagCountWarning = false; - this->versionString = ""; - - serverInterface->updateListen(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] playerIndex = %d\n",__FILE__,__FUNCTION__,__LINE__,playerIndex); - } - else { - close(); - return; - } - - //send intro message when connected - if(this->isConnected() == true) { - //printf("Server socket newSocket is connected: %d\n",playerIndex); - - Chrono seed(true); - srand((unsigned int)seed.getCurTicks() / (this->playerIndex + 1)); - - sessionKey = rand() % 1000000; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] accepted new client connection, serverInterface->getOpenSlotCount() = %d, sessionKey = %d\n",__FILE__,__FUNCTION__,__LINE__,serverInterface->getOpenSlotCount(),sessionKey); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] client will be assigned to the next open slot\n",__FILE__,__FUNCTION__,__LINE__); - - NetworkMessageIntro networkMessageIntro( - sessionKey, - getNetworkVersionGITString(), - getHostName(), - playerIndex, - nmgstOk, - 0, - ServerSocket::getFTPServerPort(), - "", - serverInterface->getGameHasBeenInitiated(), - Config::getInstance().getString("PlayerId",""), - getPlatformNameString()); - sendMessage(&networkMessageIntro); - - if(this->serverInterface->getGameHasBeenInitiated() == true) { - setGameStarted(true); - } - } - } - } - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(socketInfo.first == true) { - this->clearChatInfo(); - - bool gotTextMsg = true; - bool gotCellMarkerMsg = true; - bool waitForLaggingClient = false; - bool waitedForLaggingClient = false; - - //printf("Update slot: %d this->hasDataToRead(): %d\n",this->playerIndex,this->hasDataToRead()); - - for(;waitForLaggingClient == true || - (this->hasDataToRead() == true && - (gotTextMsg == true || gotCellMarkerMsg == true));) { - - //printf("Server slot checking for waitForLaggingClient = %d this->hasDataToRead() = %d gotTextMsg = %d gotCellMarkerMsg = %d\n",waitForLaggingClient,this->hasDataToRead(),gotTextMsg,gotCellMarkerMsg); - - waitForLaggingClient = false; - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] polling for networkMessageType...\n",__FILE__,__FUNCTION__,__LINE__); - - NetworkMessageType networkMessageType= getNextMessageType(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] networkMessageType = %d\n",__FILE__,__FUNCTION__,__LINE__,networkMessageType); - - gotTextMsg = false; - gotCellMarkerMsg = false; - //process incoming commands - switch(networkMessageType) { - - case nmtInvalid: - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] got nmtInvalid\n",__FILE__,__FUNCTION__,__LINE__); - break; - - case nmtPing: - { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] got nmtPing\n",__FILE__,__FUNCTION__); - - // client REQUIRES a ping before completing intro - // authentication - NetworkMessagePing networkMessagePing; - if(receiveMessage(&networkMessagePing)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - lastPingInfo = networkMessagePing; - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); - this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); - close(); - return; - } - } - break; - - case nmtText: - { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] got nmtText gotIntro = %d\n",__FILE__,__FUNCTION__,__LINE__,gotIntro); - - if(gotIntro == true) { - NetworkMessageText networkMessageText; - if(receiveMessage(&networkMessageText)) { - ChatMsgInfo msg(networkMessageText.getText().c_str(),networkMessageText.getTeamIndex(),networkMessageText.getPlayerIndex(),networkMessageText.getTargetLanguage()); - this->addChatInfo(msg); - gotTextMsg = true; - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); - this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); - close(); - return; - } - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); - this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); - close(); - return; - } - } - break; - - case nmtMarkCell: - { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] got nmtMarkCell gotIntro = %d\n",__FILE__,__FUNCTION__,__LINE__,gotIntro); - - if(gotIntro == true) { - NetworkMessageMarkCell networkMessageMarkCell; - if(receiveMessage(&networkMessageMarkCell)) { - MarkedCell msg(networkMessageMarkCell.getTarget(), - networkMessageMarkCell.getFactionIndex(), - networkMessageMarkCell.getText().c_str(), - networkMessageMarkCell.getPlayerIndex()); - - this->addMarkedCell(msg); - gotCellMarkerMsg = true; - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); - this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); - close(); - return; - } - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); - this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); - close(); - return; - } - } - break; - - case nmtUnMarkCell: - { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] got nmtUnMarkCell gotIntro = %d\n",__FILE__,__FUNCTION__,__LINE__,gotIntro); - - if(gotIntro == true) { - NetworkMessageUnMarkCell networkMessageMarkCell; - if(receiveMessage(&networkMessageMarkCell)) { - UnMarkedCell msg(networkMessageMarkCell.getTarget(), - networkMessageMarkCell.getFactionIndex()); - - this->addUnMarkedCell(msg); - gotCellMarkerMsg = true; - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); - this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); - close(); - return; - } - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); - this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); - close(); - return; - } - } - break; - - case nmtHighlightCell: - { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] got nmtMarkCell gotIntro = %d\n",__FILE__,__FUNCTION__,__LINE__,gotIntro); - - if(gotIntro == true) { - NetworkMessageHighlightCell networkMessageHighlightCell; - if(receiveMessage(&networkMessageHighlightCell)) { - MarkedCell msg(networkMessageHighlightCell.getTarget(), - networkMessageHighlightCell.getFactionIndex(),"none",-1); - - this->setHighlightedCell(msg); - gotCellMarkerMsg = true; - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); - this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); - close(); - return; - } - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); - this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); - close(); - return; - } - } - break; - - //command list - case nmtCommandList: { - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] got nmtCommandList gotIntro = %d\n",__FILE__,__FUNCTION__,__LINE__,gotIntro); - - if(gotIntro == true) { - NetworkMessageCommandList networkMessageCommandList; - if(receiveMessage(&networkMessageCommandList)) { - currentFrameCount = networkMessageCommandList.getFrameCount(); - lastReceiveCommandListTime = time(NULL); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] currentFrameCount = %d\n",__FILE__,__FUNCTION__,__LINE__,currentFrameCount); - - MutexSafeWrapper safeMutexSlot(mutexPendingNetworkCommandList,CODE_AT_LINE); - for(int i = 0; i < networkMessageCommandList.getCommandCount(); ++i) { - vctPendingNetworkCommandList.push_back(*networkMessageCommandList.getCommand(i)); - } - //printf("Got commands from client frame: %d count: %d\n",currentFrameCount,vctPendingNetworkCommandList.size()); - - //printf("#2 Server slot got currentFrameCount = %d\n",currentFrameCount); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); - this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); - close(); - return; - } - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); - this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); - close(); - return; - } - } - break; - - //process intro messages - case nmtIntro: - { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] got nmtIntro\n",__FILE__,__FUNCTION__); - - NetworkMessageIntro networkMessageIntro; - if(receiveMessage(&networkMessageIntro)) { - int32 msgSessionId = networkMessageIntro.getSessionId(); - this->name= networkMessageIntro.getName(); - this->versionString = networkMessageIntro.getVersionString(); - this->connectedRemoteIPAddress = networkMessageIntro.getExternalIp(); - this->playerLanguage = networkMessageIntro.getPlayerLanguage(); - this->playerUUID = networkMessageIntro.getPlayerUUID(); - this->platform = networkMessageIntro.getPlayerPlatform(); - - //printf("Got uuid from client [%s]\n",this->playerUUID.c_str()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] got name [%s] versionString [%s], msgSessionId = %d\n",__FILE__,__FUNCTION__,name.c_str(),versionString.c_str(),msgSessionId); - - if(msgSessionId != sessionKey) { - string playerNameStr = name; - string sErr = "Client gave invalid sessionid for player [" + playerNameStr + "] actual [" + intToStr(msgSessionId) + "] expected [" + intToStr(sessionKey) + "]"; - printf("%s\n",sErr.c_str()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] %s\n",__FILE__,__FUNCTION__,__LINE__,sErr.c_str()); - - close(); - return; - } - else if(this->playerUUID == "") { - string playerNameStr = name; - string sErr = "Client gave an invalid UUID for player [" + playerNameStr + "]"; - printf("%s\n",sErr.c_str()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] %s\n",__FILE__,__FUNCTION__,__LINE__,sErr.c_str()); - - close(); - return; - } - else { - //check consistency - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - bool compatible = checkVersionComptability(getNetworkVersionGITString(), networkMessageIntro.getVersionString()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(compatible == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - bool versionMatched = false; - string platformFreeVersion = getNetworkPlatformFreeVersionString(); - string sErr = ""; - - if(strncmp(platformFreeVersion.c_str(),networkMessageIntro.getVersionString().c_str(),strlen(platformFreeVersion.c_str())) != 0) { - string playerNameStr = name; - sErr = "Server and client binary mismatch!\nYou have to use the exactly same binaries!\n\nServer: " + getNetworkVersionGITString() + - "\nClient: " + networkMessageIntro.getVersionString() + " player [" + playerNameStr + "]"; - printf("%s\n",sErr.c_str()); - - serverInterface->sendTextMessage("Server and client binary mismatch!!",-1, true,"",lockedSlotIndex); - serverInterface->sendTextMessage(" Server:" + getNetworkVersionGITString(),-1, true,"",lockedSlotIndex); - serverInterface->sendTextMessage(" Client: "+ networkMessageIntro.getVersionString(),-1, true,"",lockedSlotIndex); - serverInterface->sendTextMessage(" Client player [" + playerNameStr + "]",-1, true,"",lockedSlotIndex); - } - else { - versionMatched = true; - - string playerNameStr = name; - sErr = "Warning, Server and client are using the same version but different platforms.\n\nServer: " + getNetworkVersionGITString() + - "\nClient: " + networkMessageIntro.getVersionString() + " player [" + playerNameStr + "]"; - //printf("%s\n",sErr.c_str()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] %s\n",__FILE__,__FUNCTION__,__LINE__,sErr.c_str()); - } - - if(Config::getInstance().getBool("PlatformConsistencyChecks","true") && - versionMatched == false) { // error message and disconnect only if checked - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] %s\n",__FILE__,__FUNCTION__,__LINE__,sErr.c_str()); - close(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] %s\n",__FILE__,__FUNCTION__,__LINE__,sErr.c_str()); - return; - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - gotIntro = true; - - int factionIndex = this->serverInterface->gameSettings.getFactionIndexForStartLocation(playerIndex); - this->serverInterface->addClientToServerIPAddress(this->getSocket()->getConnectedIPAddress(this->getSocket()->getIpAddress()),this->connectedRemoteIPAddress); - - this->serverInterface->gameSettings.setNetworkPlayerUUID(factionIndex,this->playerUUID); - this->serverInterface->gameSettings.setNetworkPlayerPlatform(factionIndex,this->platform); - - if(serverInterface->getGameHasBeenInitiated() == true && - serverInterface->getAllowInGameConnections() == true) { - this->serverInterface->gameSettings.setNetworkPlayerStatuses(factionIndex,npst_None); - } - - if(getAllowGameDataSynchCheck() == true && serverInterface->getGameSettings() != NULL) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] sending NetworkMessageSynchNetworkGameData\n",__FILE__,__FUNCTION__,__LINE__); - - NetworkMessageSynchNetworkGameData networkMessageSynchNetworkGameData(serverInterface->getGameSettings()); - sendMessage(&networkMessageSynchNetworkGameData); - } - - if(serverInterface->getGameHasBeenInitiated() == true && - serverInterface->getAllowInGameConnections() == true) { - - ConnectionSlot *slot = serverInterface->findSlotForUUID(this->playerUUID,true); - if(slot != NULL) { - slot->setJoinGameInProgressFlags(); - slot->setPauseForInGameConnection(true); - - serverInterface->switchSlot(this->playerIndex,slot->getPlayerIndex()); - } - else { - setJoinGameInProgressFlags(); - this->setPauseForInGameConnection(true); - } - } - else { - ConnectionSlot *slot = serverInterface->findSlotForUUID(this->playerUUID,true); - if(slot != NULL) { - serverInterface->switchSlot(this->playerIndex,slot->getPlayerIndex()); - } - } - } - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); - this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); - close(); - return; - } - } - break; - - case nmtLaunch: - case nmtBroadCastSetup: - { - if(gotIntro == true) { - if(this->serverInterface->getGameSettings() == NULL || - (joinGameInProgress == false && sessionKey != this->serverInterface->getGameSettings()->getMasterserver_admin())) { - string playerNameStr = name; - string sErr = "Client has invalid admin sessionid for player [" + playerNameStr + "]"; - printf("%s\n",sErr.c_str()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] %s\n",__FILE__,__FUNCTION__,__LINE__,sErr.c_str()); - - close(); - return; - } - - NetworkMessageLaunch networkMessageLaunch; - if(receiveMessage(&networkMessageLaunch,networkMessageType)) { - if(networkMessageLaunch.getMessageType() == nmtLaunch) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Lined: %d] got nmtLaunch\n",__FILE__,__FUNCTION__,__LINE__); - //printf("Got launch request from client joinGameInProgress = %d joinGameInProgress = %d!\n",joinGameInProgress,joinGameInProgress); - } - else if(networkMessageLaunch.getMessageType() == nmtBroadCastSetup) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Lined: %d] got nmtBroadCastSetup\n",__FILE__,__FUNCTION__,__LINE__); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Lined: %d] got networkMessageLaunch.getMessageType() = %d\n",__FILE__,__FUNCTION__,__LINE__,networkMessageLaunch.getMessageType()); - - char szBuf[1024]=""; - snprintf(szBuf,1023,"In [%s::%s Line: %d] Invalid networkMessageLaunch.getMessageType() = %d",__FILE__,__FUNCTION__,__LINE__,networkMessageLaunch.getMessageType()); - throw megaglest_runtime_error(szBuf); - } - - int minHeadLessPlayersRequired = Config::getInstance().getInt("MinHeadlessPlayersRequired","2"); - if(this->joinGameInProgress == false && - networkMessageLaunch.getMessageType() == nmtLaunch && - this->ready == false && - this->serverInterface->getConnectedSlotCount(true) < minHeadLessPlayersRequired) { - - Lang &lang= Lang::getInstance(); - const vector languageList = this->serverInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int index = 0; index < languageList.size(); ++index) { - char szBuf[4096]=""; - string msgTemplate = "You must have have at least %d player(s) connected to start this game!"; - if(lang.hasString("HeadlessAdminRequiresMorePlayers",languageList[index]) == true) { - msgTemplate = lang.getString("HeadlessAdminRequiresMorePlayers",languageList[index]); - } - #ifdef WIN32 - _snprintf(szBuf,4095,msgTemplate.c_str(),minHeadLessPlayersRequired); - #else - snprintf(szBuf,4095,msgTemplate.c_str(),minHeadLessPlayersRequired); - #endif - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] %s\n",__FILE__,__FUNCTION__,__LINE__,szBuf); - - string sMsg = szBuf; - bool echoLocal = lang.isLanguageLocal(languageList[index]); - this->serverInterface->sendTextMessage(sMsg,-1, echoLocal, languageList[index], this->getPlayerIndex()); - } - } - else { - if(this->joinGameInProgress == false) { - GameSettings gameSettingsBuffer; - networkMessageLaunch.buildGameSettings(&gameSettingsBuffer); - - //printf("Connection slot got networkMessageLaunch.getMessageType() = %d, got map [%s]\n",networkMessageLaunch.getMessageType(),gameSettings.getMap().c_str()); - //printf("\n\n\n\n=====Connection slot got settings:\n%s\n",gameSettings.toString().c_str()); - - this->serverInterface->broadcastGameSetup(&gameSettingsBuffer, true); - } - - if(this->joinGameInProgress == false && - networkMessageLaunch.getMessageType() == nmtLaunch) { - - this->serverInterface->setMasterserverAdminRequestLaunch(true); - } - else if(this->joinGameInProgress == true && - networkMessageLaunch.getMessageType() == nmtLaunch) { - //printf("!!! setStartInGameConnectionLaunch for client joinGameInProgress = %d!\n",joinGameInProgress); - - int factionIndex = this->serverInterface->gameSettings.getFactionIndexForStartLocation(playerIndex); - this->serverInterface->gameSettings.setFactionControl(factionIndex,ctNetwork); - this->serverInterface->gameSettings.setNetworkPlayerName(factionIndex,this->name); - this->serverInterface->gameSettings.setNetworkPlayerUUID(factionIndex,this->playerUUID); - this->serverInterface->gameSettings.setNetworkPlayerPlatform(factionIndex,this->platform); - - if(this->serverInterface->gameSettings.getNetworkPlayerStatuses(factionIndex) == npst_Disconnected) { - this->serverInterface->gameSettings.setNetworkPlayerStatuses(factionIndex,npst_None); - } - - this->serverInterface->broadcastGameSetup(&this->serverInterface->gameSettings, true); - - this->setStartInGameConnectionLaunch(true); - } - } - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); - this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); - close(); - return; - } - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); - this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); - close(); - return; - } - } - break; - - //process datasynch messages - case nmtSynchNetworkGameDataStatus: - { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] got nmtSynchNetworkGameDataStatus, gotIntro = %d\n",__FILE__,__FUNCTION__,__LINE__,gotIntro); - - if(gotIntro == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - NetworkMessageSynchNetworkGameDataStatus networkMessageSynchNetworkGameDataStatus; - if(receiveMessage(&networkMessageSynchNetworkGameDataStatus)) { - this->setNetworkGameDataSynchCheckTechMismatchReport(""); - this->setReceivedDataSynchCheck(false); - - Config &config = Config::getInstance(); - string scenarioDir = ""; - if(serverInterface->getGameSettings()->getScenarioDir() != "") { - scenarioDir = serverInterface->getGameSettings()->getScenarioDir(); - if(EndsWith(scenarioDir, ".xml") == true) { - scenarioDir = scenarioDir.erase(scenarioDir.size() - 4, 4); - scenarioDir = scenarioDir.erase(scenarioDir.size() - serverInterface->getGameSettings()->getScenario().size(), serverInterface->getGameSettings()->getScenario().size() + 1); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] gameSettings.getScenarioDir() = [%s] gameSettings.getScenario() = [%s] scenarioDir = [%s]\n",__FILE__,__FUNCTION__,__LINE__,serverInterface->getGameSettings()->getScenarioDir().c_str(),serverInterface->getGameSettings()->getScenario().c_str(),scenarioDir.c_str()); - } - - //tileset - uint32 tilesetCRC = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTilesets,scenarioDir), string("/") + serverInterface->getGameSettings()->getTileset() + string("/*"), ".xml", NULL); - uint32 techCRC = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,scenarioDir), "/" + serverInterface->getGameSettings()->getTech() + "/*", ".xml", NULL); - Checksum checksum; - string file = Config::getMapPath(serverInterface->getGameSettings()->getMap(),scenarioDir,false); - checksum.addFile(file); - uint32 mapCRC = checksum.getSum(); - - networkGameDataSynchCheckOkMap = (networkMessageSynchNetworkGameDataStatus.getMapCRC() == mapCRC); - networkGameDataSynchCheckOkTile = (networkMessageSynchNetworkGameDataStatus.getTilesetCRC() == tilesetCRC); - networkGameDataSynchCheckOkTech = (networkMessageSynchNetworkGameDataStatus.getTechCRC() == techCRC); - - // For testing - //techCRC++; - - if( networkGameDataSynchCheckOkMap == true && - networkGameDataSynchCheckOkTile == true && - networkGameDataSynchCheckOkTech == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] client data synch ok\n",__FILE__,__FUNCTION__); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] mapCRC = %d, remote = %d\n",__FILE__,__FUNCTION__,mapCRC,networkMessageSynchNetworkGameDataStatus.getMapCRC()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] tilesetCRC = %d, remote = %d\n",__FILE__,__FUNCTION__,tilesetCRC,networkMessageSynchNetworkGameDataStatus.getTilesetCRC()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] techCRC = %d, remote = %d\n",__FILE__,__FUNCTION__,techCRC,networkMessageSynchNetworkGameDataStatus.getTechCRC()); - - if(allowDownloadDataSynch == true) { - // Now get all filenames with their CRC values and send to the client - vctFileList.clear(); - - Config &config = Config::getInstance(); - string scenarioDir = ""; - if(serverInterface->getGameSettings()->getScenarioDir() != "") { - scenarioDir = serverInterface->getGameSettings()->getScenarioDir(); - if(EndsWith(scenarioDir, ".xml") == true) { - scenarioDir = scenarioDir.erase(scenarioDir.size() - 4, 4); - scenarioDir = scenarioDir.erase(scenarioDir.size() - serverInterface->getGameSettings()->getScenario().size(), serverInterface->getGameSettings()->getScenario().size() + 1); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] gameSettings.getScenarioDir() = [%s] gameSettings.getScenario() = [%s] scenarioDir = [%s]\n",__FILE__,__FUNCTION__,__LINE__,serverInterface->getGameSettings()->getScenarioDir().c_str(),serverInterface->getGameSettings()->getScenario().c_str(),scenarioDir.c_str()); - } - - if(networkGameDataSynchCheckOkTile == false) { - if(tilesetCRC == 0) { - vctFileList = getFolderTreeContentsCheckSumListRecursively(config.getPathListForType(ptTilesets,scenarioDir), string("/") + serverInterface->getGameSettings()->getTileset() + string("/*"), "", &vctFileList); - } - else { - vctFileList = getFolderTreeContentsCheckSumListRecursively(config.getPathListForType(ptTilesets,scenarioDir), "/" + serverInterface->getGameSettings()->getTileset() + "/*", ".xml", &vctFileList); - } - } - if(networkGameDataSynchCheckOkTech == false) { - if(techCRC == 0) { - vctFileList = getFolderTreeContentsCheckSumListRecursively(config.getPathListForType(ptTechs,scenarioDir),"/" + serverInterface->getGameSettings()->getTech() + "/*", "", &vctFileList); - } - else { - vctFileList = getFolderTreeContentsCheckSumListRecursively(config.getPathListForType(ptTechs,scenarioDir),"/" + serverInterface->getGameSettings()->getTech() + "/*", ".xml", &vctFileList); - } - - string report = networkMessageSynchNetworkGameDataStatus.getTechCRCFileMismatchReport(serverInterface->getGameSettings()->getTech(),vctFileList); - this->setNetworkGameDataSynchCheckTechMismatchReport(report); - } - if(networkGameDataSynchCheckOkMap == false) { - vctFileList.push_back(std::pair(Config::getMapPath(serverInterface->getGameSettings()->getMap(),scenarioDir,false),mapCRC)); - } - - NetworkMessageSynchNetworkGameDataFileCRCCheck networkMessageSynchNetworkGameDataFileCRCCheck((int)vctFileList.size(), 1, vctFileList[0].second, vctFileList[0].first); - sendMessage(&networkMessageSynchNetworkGameDataFileCRCCheck); - } - else { - if(networkGameDataSynchCheckOkTech == false) { - vctFileList = getFolderTreeContentsCheckSumListRecursively(config.getPathListForType(ptTechs,scenarioDir),"/" + serverInterface->getGameSettings()->getTech() + "/*", ".xml", NULL); - - string report = networkMessageSynchNetworkGameDataStatus.getTechCRCFileMismatchReport(serverInterface->getGameSettings()->getTech(),vctFileList); - this->setNetworkGameDataSynchCheckTechMismatchReport(report); - } - } - } - - this->setReceivedDataSynchCheck(true); - receivedNetworkGameStatus = true; - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); - this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); - close(); - return; - } - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); - this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); - close(); - return; - } - } - break; - - case nmtSynchNetworkGameDataFileCRCCheck: - { - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] got nmtSynchNetworkGameDataFileCRCCheck\n",__FILE__,__FUNCTION__); - - if(gotIntro == true) { - NetworkMessageSynchNetworkGameDataFileCRCCheck networkMessageSynchNetworkGameDataFileCRCCheck; - if(receiveMessage(&networkMessageSynchNetworkGameDataFileCRCCheck)) - { - int fileIndex = networkMessageSynchNetworkGameDataFileCRCCheck.getFileIndex(); - NetworkMessageSynchNetworkGameDataFileCRCCheck networkMessageSynchNetworkGameDataFileCRCCheck((int)vctFileList.size(), fileIndex, vctFileList[fileIndex-1].second, vctFileList[fileIndex-1].first); - sendMessage(&networkMessageSynchNetworkGameDataFileCRCCheck); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); - this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); - close(); - return; - } - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); - this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); - close(); - return; - } - } - break; - - case nmtSynchNetworkGameDataFileGet: - { - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] got nmtSynchNetworkGameDataFileGet\n",__FILE__,__FUNCTION__); - - if(gotIntro == true) { - NetworkMessageSynchNetworkGameDataFileGet networkMessageSynchNetworkGameDataFileGet; - if(receiveMessage(&networkMessageSynchNetworkGameDataFileGet)) { - FileTransferInfo fileInfo; - fileInfo.hostType = eServer; - //fileInfo.serverIP = this->ip.getString(); - fileInfo.serverPort = Config::getInstance().getInt("PortServer",intToStr(GameConstants::serverPort).c_str()); - fileInfo.fileName = networkMessageSynchNetworkGameDataFileGet.getFileName(); - - FileTransferSocketThread *fileXferThread = new FileTransferSocketThread(fileInfo); - fileXferThread->start(); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); - this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); - close(); - return; - } - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); - this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); - close(); - return; - } - } - break; - - case nmtSwitchSetupRequest: - { - //printf("Got nmtSwitchSetupRequest A gotIntro = %d\n",gotIntro); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] got nmtSwitchSetupRequest gotIntro = %d\n",__FILE__,__FUNCTION__,__LINE__,gotIntro); - - if(gotIntro == true) { - //printf("Got nmtSwitchSetupRequest B\n"); - - SwitchSetupRequest switchSetupRequest; - if(receiveMessage(&switchSetupRequest)) { - MutexSafeWrapper safeMutex(getServerSynchAccessor(),CODE_AT_LINE); - - int slotIdx = switchSetupRequest.getCurrentSlotIndex(); - //int newSlotIdx = switchSetupRequest.getToSlotIndex(); - //printf("slotIdx = %d newSlotIdx = %d\n",slotIdx,newSlotIdx); - - if(serverInterface->getSwitchSetupRequests(slotIdx) == NULL) { - serverInterface->setSwitchSetupRequests(slotIdx,new SwitchSetupRequest()); - } - *(serverInterface->getSwitchSetupRequests(slotIdx)) = switchSetupRequest; - - //printf("slotIdx = %d newSlotIdx = %d\n",serverInterface->getSwitchSetupRequests(slotIdx)->getCurrentSlotIndex(),serverInterface->getSwitchSetupRequests(slotIdx)->getToSlotIndex()); - - this->playerStatus = switchSetupRequest.getNetworkPlayerStatus(); - this->name = switchSetupRequest.getNetworkPlayerName(); - this->playerLanguage = switchSetupRequest.getNetworkPlayerLanguage(); - - //printf("Got nmtSwitchSetupRequest C\n"); - //printf("In [%s::%s Line %d] networkPlayerName [%s]\n",__FILE__,__FUNCTION__,__LINE__,serverInterface->getSwitchSetupRequests()[factionIdx]->getNetworkPlayerName().c_str()); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d] networkPlayerName [%s]\n",__FILE__,__FUNCTION__,__LINE__,serverInterface->getSwitchSetupRequests()[slotIdx]->getNetworkPlayerName().c_str()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] factionIdx = %d, switchSetupRequest.getNetworkPlayerName() [%s] switchSetupRequest.getNetworkPlayerStatus() = %d, switchSetupRequest.getSwitchFlags() = %d\n",__FILE__,__FUNCTION__,__LINE__,slotIdx,switchSetupRequest.getNetworkPlayerName().c_str(),switchSetupRequest.getNetworkPlayerStatus(),switchSetupRequest.getSwitchFlags()); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); - this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); - close(); - return; - } - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); - this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); - close(); - return; - } - - break; - } - - case nmtReady: - { - NetworkMessageReady networkMessageReady; - this->receiveMessage(&networkMessageReady); - - // its simply ignored here. Probably we are starting a game - //printf("Got ready message from client slot joinGameInProgress = %d\n",joinGameInProgress); - if(joinGameInProgress == true) { - NetworkMessageReady networkMessageReady(0); - this->sendMessage(&networkMessageReady); - this->setGameStarted(true); - - this->currentFrameCount = serverInterface->getCurrentFrameCount(); - //printf("#2 Server slot got currentFrameCount = %d\n",currentFrameCount); - - this->currentLagCount = 0; - this->lastReceiveCommandListTime = time(NULL); - - this->setReady(); - } - // unpause the game - else { - this->setUnPauseForInGameConnection(true); - } - break; - } - case nmtLoadingStatusMessage: - break; - - default: - { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] networkMessageType = %d\n",__FILE__,__FUNCTION__,__LINE__,networkMessageType); - - if(gotIntro == true) { - //throw megaglest_runtime_error("Unexpected message in connection slot: " + intToStr(networkMessageType)); - string sErr = "Unexpected message in connection slot: " + intToStr(networkMessageType); - //sendTextMessage(sErr,-1); - //DisplayErrorMessage(sErr); - threadErrorList.push_back(sErr); - return; - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] got invalid message type before intro, disconnecting socket.\n",__FILE__,__FUNCTION__,__LINE__); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); - this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); - close(); - return; - } - } - } - - //printf("#3 Server slot got currentFrameCount = %d\n",currentFrameCount); - - // This may end up continuously lagging and not disconnecting players who have - // just the 'wrong' amount of lag (but not enough to be horrible for a disconnect) - if(Config::getInstance().getBool("AutoClientLagCorrection","true") == true) { - double LAG_CHECK_GRACE_PERIOD = 15; - - //printf("#4 Server slot got currentFrameCount = %d\n",currentFrameCount); - - if(this->serverInterface->getGameStartTime() > 0 && - difftime((long int)time(NULL),this->serverInterface->getGameStartTime()) >= LAG_CHECK_GRACE_PERIOD && - difftime((long int)time(NULL),this->getConnectedTime()) >= LAG_CHECK_GRACE_PERIOD) { - if(this->isConnected() == true && this->gotIntro == true && this->skipLagCheck == false) { - double clientLag = this->serverInterface->getCurrentFrameCount() - this->getCurrentFrameCount(); - double clientLagCount = (gameSettings.getNetworkFramePeriod() > 0 ? (clientLag / gameSettings.getNetworkFramePeriod()) : 0); - double clientLagTime = difftime((long int)time(NULL),this->getLastReceiveCommandListTime()); - - double maxFrameCountLagAllowed = 10; - double maxClientLagTimeAllowed = 8; - - // New lag check - if((clientLagCount > maxFrameCountLagAllowed) || - (maxClientLagTimeAllowed > 0 && clientLagTime > maxClientLagTimeAllowed)) { - - waitForLaggingClient = true; - if(waitedForLaggingClient == false) { - waitedForLaggingClient = true; - printf("*TESTING*: START Waiting for lagging client playerIndex = %d [%s] clientLagCount = %f [%f]\n",playerIndex,name.c_str(),clientLagCount,clientLagTime); - } - } - } - } - - //printf("#5 Server slot got currentFrameCount = %d\n",currentFrameCount); - } - //printf("#5a Server slot got currentFrameCount = %d\n",currentFrameCount); - } - - //printf("#6 Server slot got currentFrameCount = %d\n",currentFrameCount); - - if(waitedForLaggingClient == true) { - printf("*TESTING*: FINISHED Waiting for lagging client playerIndex = %d [%s]\n",playerIndex,name.c_str()); - } - - //if(chrono.getMillis() > 1) printf("In [%s::%s Line: %d] action running for msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,(long long int)chrono.getMillis()); - - validateConnection(); - - //printf("#7 Server slot got currentFrameCount = %d\n",currentFrameCount); - - //if(chrono.getMillis() > 1) printf("In [%s::%s Line: %d] action running for msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,(long long int)chrono.getMillis()); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] calling close...\n",__FILE__,__FUNCTION__,__LINE__); - - //printf("Closing connection slot socketInfo.first = %d\n",socketInfo.first); - - close(); - - //if(chrono.getMillis() > 1) printf("In [%s::%s Line: %d] action running for msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,(long long int)chrono.getMillis()); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - } - } - catch(const exception &ex) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] error detected [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - - threadErrorList.push_back(ex.what()); - - //if(chrono.getMillis() > 1) printf("In [%s::%s Line: %d] action running for msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,(long long int)chrono.getMillis()); - } - - //printf("#8 Server slot got currentFrameCount = %d\n",currentFrameCount); - //if(chrono.getMillis() > 1) printf("In [%s::%s Line: %d] action running for msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,(long long int)chrono.getMillis()); -} +void ConnectionSlot::update(bool checkForNewClients, int lockedSlotIndex) { + try { + clearThreadErrorList(); -void ConnectionSlot::validateConnection() { - if(this->isConnected() == true && - gotIntro == false && connectedTime > 0 && - difftime((long int)time(NULL),connectedTime) > GameConstants::maxClientConnectHandshakeSecs) { + if (slotThreadWorker != NULL) { + slotThreadWorker->purgeCompletedEvents(); + } - //printf("Closing connection slot timed out!\n"); - close(); - } -} + pair socketInfo = this->getSocketInfo(); + if (socketInfo.second == NULL) { + if (networkGameDataSynchCheckOkMap) + networkGameDataSynchCheckOkMap = false; + if (networkGameDataSynchCheckOkTile) + networkGameDataSynchCheckOkTile = false; + if (networkGameDataSynchCheckOkTech) + networkGameDataSynchCheckOkTech = false; + this->setReceivedDataSynchCheck(false); + + // Is the listener socket ready to be read? + if (checkForNewClients == true && this->canAcceptConnections == true) { + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] BEFORE accept new client connection, " + "serverInterface->getOpenSlotCount() = %d\n", + __FILE__, __FUNCTION__, __LINE__, + serverInterface->getOpenSlotCount()); + + // printf("Checking for new connections...\n"); + bool hasData = + (serverInterface->getServerSocket() != NULL && + serverInterface->getServerSocket()->hasDataToRead() == true); + // printf("Server socket hasData: %d\n",hasData); + + if (hasData == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] about to accept new " + "client connection playerIndex = %d\n", + __FILE__, __FUNCTION__, __LINE__, + playerIndex); + + Socket *newSocket = serverInterface->getServerSocket()->accept(false); + + // printf("Server socket newSocket: %p\n",newSocket); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] called accept new client connection " + "playerIndex = %d newSocket = %p\n", + __FILE__, __FUNCTION__, __LINE__, playerIndex, newSocket); + if (newSocket != NULL) { + // Set Socket as non-blocking + newSocket->setBlock(false); + + MutexSafeWrapper safeMutex(mutexCloseConnection, CODE_AT_LINE); + this->setSocket(newSocket); + safeMutex.ReleaseLock(); + + this->connectedTime = time(NULL); + this->clearChatInfo(); + this->name = ""; + this->playerStatus = npst_PickSettings; + this->playerLanguage = ""; + this->playerUUID = ""; + this->platform = ""; + this->ready = false; + this->vctFileList.clear(); + this->receivedNetworkGameStatus = false; + this->gotIntro = false; + + MutexSafeWrapper safeMutexSlot1(mutexPendingNetworkCommandList, + CODE_AT_LINE); + this->vctPendingNetworkCommandList.clear(); + safeMutexSlot1.ReleaseLock(); + + this->currentFrameCount = 0; + this->currentLagCount = 0; + this->lastReceiveCommandListTime = 0; + this->gotLagCountWarning = false; + this->versionString = ""; + + serverInterface->updateListen(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] playerIndex = %d\n", __FILE__, + __FUNCTION__, __LINE__, playerIndex); + } else { + close(); + return; + } + + // send intro message when connected + if (this->isConnected() == true) { + // printf("Server socket newSocket is connected: %d\n",playerIndex); + + Chrono seed(true); + srand((unsigned int)seed.getCurTicks() / (this->playerIndex + 1)); + + sessionKey = rand() % 1000000; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] accepted new client connection, " + "serverInterface->getOpenSlotCount() = %d, sessionKey = %d\n", + __FILE__, __FUNCTION__, __LINE__, + serverInterface->getOpenSlotCount(), sessionKey); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] client will be " + "assigned to the next open slot\n", + __FILE__, __FUNCTION__, __LINE__); + + NetworkMessageIntro networkMessageIntro( + sessionKey, getNetworkVersionGITString(), getHostName(), + playerIndex, nmgstOk, 0, ServerSocket::getFTPServerPort(), "", + serverInterface->getGameHasBeenInitiated(), + Config::getInstance().getString("PlayerId", ""), + getPlatformNameString()); + sendMessage(&networkMessageIntro); + + if (this->serverInterface->getGameHasBeenInitiated() == true) { + setGameStarted(true); + } + } + } + } + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + + if (socketInfo.first == true) { + this->clearChatInfo(); + + bool gotTextMsg = true; + bool gotCellMarkerMsg = true; + bool waitForLaggingClient = false; + bool waitedForLaggingClient = false; + + // printf("Update slot: %d this->hasDataToRead(): + // %d\n",this->playerIndex,this->hasDataToRead()); + + for (; waitForLaggingClient == true || + (this->hasDataToRead() == true && + (gotTextMsg == true || gotCellMarkerMsg == true));) { + + // printf("Server slot checking for waitForLaggingClient = %d + // this->hasDataToRead() = %d gotTextMsg = %d gotCellMarkerMsg = + // %d\n",waitForLaggingClient,this->hasDataToRead(),gotTextMsg,gotCellMarkerMsg); + + waitForLaggingClient = false; + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] polling for networkMessageType...\n", + __FILE__, __FUNCTION__, __LINE__); + + NetworkMessageType networkMessageType = getNextMessageType(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] networkMessageType = %d\n", __FILE__, + __FUNCTION__, __LINE__, networkMessageType); + + gotTextMsg = false; + gotCellMarkerMsg = false; + // process incoming commands + switch (networkMessageType) { + + case nmtInvalid: + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] got nmtInvalid\n", + __FILE__, __FUNCTION__, __LINE__); + break; + + case nmtPing: { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s] got nmtPing\n", __FILE__, + __FUNCTION__); + + // client REQUIRES a ping before completing intro + // authentication + NetworkMessagePing networkMessagePing; + if (receiveMessage(&networkMessagePing)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + lastPingInfo = networkMessagePing; + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugError) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d]\nInvalid message type before intro " + "handshake [%d]\nDisconnecting socket for slot: %d [%s].\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, networkMessageType, + this->playerIndex, this->getIpAddress().c_str()); + this->serverInterface->notifyBadClientConnectAttempt( + this->getIpAddress()); + close(); + return; + } + } break; + + case nmtText: { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] got nmtText gotIntro = %d\n", __FILE__, + __FUNCTION__, __LINE__, gotIntro); + + if (gotIntro == true) { + NetworkMessageText networkMessageText; + if (receiveMessage(&networkMessageText)) { + ChatMsgInfo msg(networkMessageText.getText().c_str(), + networkMessageText.getTeamIndex(), + networkMessageText.getPlayerIndex(), + networkMessageText.getTargetLanguage()); + this->addChatInfo(msg); + gotTextMsg = true; + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugError) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d]\nInvalid message type before intro " + "handshake [%d]\nDisconnecting socket for slot: %d " + "[%s].\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, networkMessageType, + this->playerIndex, this->getIpAddress().c_str()); + this->serverInterface->notifyBadClientConnectAttempt( + this->getIpAddress()); + close(); + return; + } + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugError) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d]\nInvalid message type before intro " + "handshake [%d]\nDisconnecting socket for slot: %d [%s].\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, networkMessageType, + this->playerIndex, this->getIpAddress().c_str()); + this->serverInterface->notifyBadClientConnectAttempt( + this->getIpAddress()); + close(); + return; + } + } break; + + case nmtMarkCell: { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] got nmtMarkCell gotIntro = %d\n", + __FILE__, __FUNCTION__, __LINE__, gotIntro); + + if (gotIntro == true) { + NetworkMessageMarkCell networkMessageMarkCell; + if (receiveMessage(&networkMessageMarkCell)) { + MarkedCell msg(networkMessageMarkCell.getTarget(), + networkMessageMarkCell.getFactionIndex(), + networkMessageMarkCell.getText().c_str(), + networkMessageMarkCell.getPlayerIndex()); + + this->addMarkedCell(msg); + gotCellMarkerMsg = true; + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugError) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d]\nInvalid message type before intro " + "handshake [%d]\nDisconnecting socket for slot: %d " + "[%s].\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, networkMessageType, + this->playerIndex, this->getIpAddress().c_str()); + this->serverInterface->notifyBadClientConnectAttempt( + this->getIpAddress()); + close(); + return; + } + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugError) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d]\nInvalid message type before intro " + "handshake [%d]\nDisconnecting socket for slot: %d [%s].\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, networkMessageType, + this->playerIndex, this->getIpAddress().c_str()); + this->serverInterface->notifyBadClientConnectAttempt( + this->getIpAddress()); + close(); + return; + } + } break; + + case nmtUnMarkCell: { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] got nmtUnMarkCell gotIntro = %d\n", + __FILE__, __FUNCTION__, __LINE__, gotIntro); + + if (gotIntro == true) { + NetworkMessageUnMarkCell networkMessageMarkCell; + if (receiveMessage(&networkMessageMarkCell)) { + UnMarkedCell msg(networkMessageMarkCell.getTarget(), + networkMessageMarkCell.getFactionIndex()); + + this->addUnMarkedCell(msg); + gotCellMarkerMsg = true; + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugError) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d]\nInvalid message type before intro " + "handshake [%d]\nDisconnecting socket for slot: %d " + "[%s].\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, networkMessageType, + this->playerIndex, this->getIpAddress().c_str()); + this->serverInterface->notifyBadClientConnectAttempt( + this->getIpAddress()); + close(); + return; + } + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugError) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d]\nInvalid message type before intro " + "handshake [%d]\nDisconnecting socket for slot: %d [%s].\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, networkMessageType, + this->playerIndex, this->getIpAddress().c_str()); + this->serverInterface->notifyBadClientConnectAttempt( + this->getIpAddress()); + close(); + return; + } + } break; + + case nmtHighlightCell: { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] got nmtMarkCell gotIntro = %d\n", + __FILE__, __FUNCTION__, __LINE__, gotIntro); + + if (gotIntro == true) { + NetworkMessageHighlightCell networkMessageHighlightCell; + if (receiveMessage(&networkMessageHighlightCell)) { + MarkedCell msg(networkMessageHighlightCell.getTarget(), + networkMessageHighlightCell.getFactionIndex(), + "none", -1); + + this->setHighlightedCell(msg); + gotCellMarkerMsg = true; + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugError) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d]\nInvalid message type before intro " + "handshake [%d]\nDisconnecting socket for slot: %d " + "[%s].\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, networkMessageType, + this->playerIndex, this->getIpAddress().c_str()); + this->serverInterface->notifyBadClientConnectAttempt( + this->getIpAddress()); + close(); + return; + } + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugError) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d]\nInvalid message type before intro " + "handshake [%d]\nDisconnecting socket for slot: %d [%s].\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, networkMessageType, + this->playerIndex, this->getIpAddress().c_str()); + this->serverInterface->notifyBadClientConnectAttempt( + this->getIpAddress()); + close(); + return; + } + } break; + + // command list + case nmtCommandList: { + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] got nmtCommandList gotIntro = %d\n", + __FILE__, __FUNCTION__, __LINE__, gotIntro); + + if (gotIntro == true) { + NetworkMessageCommandList networkMessageCommandList; + if (receiveMessage(&networkMessageCommandList)) { + currentFrameCount = networkMessageCommandList.getFrameCount(); + lastReceiveCommandListTime = time(NULL); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] currentFrameCount = %d\n", __FILE__, + __FUNCTION__, __LINE__, currentFrameCount); + + MutexSafeWrapper safeMutexSlot(mutexPendingNetworkCommandList, + CODE_AT_LINE); + for (int i = 0; i < networkMessageCommandList.getCommandCount(); + ++i) { + vctPendingNetworkCommandList.push_back( + *networkMessageCommandList.getCommand(i)); + } + // printf("Got commands from client frame: %d count: + // %d\n",currentFrameCount,vctPendingNetworkCommandList.size()); + + // printf("#2 Server slot got currentFrameCount = + // %d\n",currentFrameCount); + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugError) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d]\nInvalid message type before intro " + "handshake [%d]\nDisconnecting socket for slot: %d " + "[%s].\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, networkMessageType, + this->playerIndex, this->getIpAddress().c_str()); + this->serverInterface->notifyBadClientConnectAttempt( + this->getIpAddress()); + close(); + return; + } + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugError) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d]\nInvalid message type before intro " + "handshake [%d]\nDisconnecting socket for slot: %d [%s].\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, networkMessageType, + this->playerIndex, this->getIpAddress().c_str()); + this->serverInterface->notifyBadClientConnectAttempt( + this->getIpAddress()); + close(); + return; + } + } break; + + // process intro messages + case nmtIntro: { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s] got nmtIntro\n", __FILE__, + __FUNCTION__); + + NetworkMessageIntro networkMessageIntro; + if (receiveMessage(&networkMessageIntro)) { + int32 msgSessionId = networkMessageIntro.getSessionId(); + this->name = networkMessageIntro.getName(); + this->versionString = networkMessageIntro.getVersionString(); + this->connectedRemoteIPAddress = + networkMessageIntro.getExternalIp(); + this->playerLanguage = networkMessageIntro.getPlayerLanguage(); + this->playerUUID = networkMessageIntro.getPlayerUUID(); + this->platform = networkMessageIntro.getPlayerPlatform(); + + // printf("Got uuid from client [%s]\n",this->playerUUID.c_str()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s] got name [%s] versionString [%s], " + "msgSessionId = %d\n", + __FILE__, __FUNCTION__, name.c_str(), versionString.c_str(), + msgSessionId); + + if (msgSessionId != sessionKey) { + string playerNameStr = name; + string sErr = "Client gave invalid sessionid for player [" + + playerNameStr + "] actual [" + + intToStr(msgSessionId) + "] expected [" + + intToStr(sessionKey) + "]"; + printf("%s\n", sErr.c_str()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d] %s\n", + __FILE__, __FUNCTION__, __LINE__, sErr.c_str()); + + close(); + return; + } else if (this->playerUUID == "") { + string playerNameStr = name; + string sErr = "Client gave an invalid UUID for player [" + + playerNameStr + "]"; + printf("%s\n", sErr.c_str()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d] %s\n", + __FILE__, __FUNCTION__, __LINE__, sErr.c_str()); + + close(); + return; + } else { + // check consistency + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + + bool compatible = checkVersionComptability( + getNetworkVersionGITString(), + networkMessageIntro.getVersionString()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + + if (compatible == false) { + if (SystemFlags::getSystemSettingType( + SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + + bool versionMatched = false; + string platformFreeVersion = + getNetworkPlatformFreeVersionString(); + string sErr = ""; + + if (strncmp(platformFreeVersion.c_str(), + networkMessageIntro.getVersionString().c_str(), + strlen(platformFreeVersion.c_str())) != 0) { + string playerNameStr = name; + sErr = "Server and client binary mismatch!\nYou have to " + "use the exactly same binaries!\n\nServer: " + + getNetworkVersionGITString() + "\nClient: " + + networkMessageIntro.getVersionString() + + " player [" + playerNameStr + "]"; + printf("%s\n", sErr.c_str()); + + serverInterface->sendTextMessage( + "Server and client binary mismatch!!", -1, true, "", + lockedSlotIndex); + serverInterface->sendTextMessage( + " Server:" + getNetworkVersionGITString(), -1, true, "", + lockedSlotIndex); + serverInterface->sendTextMessage( + " Client: " + networkMessageIntro.getVersionString(), + -1, true, "", lockedSlotIndex); + serverInterface->sendTextMessage( + " Client player [" + playerNameStr + "]", -1, true, "", + lockedSlotIndex); + } else { + versionMatched = true; + + string playerNameStr = name; + sErr = "Warning, Server and client are using the same " + "version but different platforms.\n\nServer: " + + getNetworkVersionGITString() + "\nClient: " + + networkMessageIntro.getVersionString() + + " player [" + playerNameStr + "]"; + // printf("%s\n",sErr.c_str()); + if (SystemFlags::getSystemSettingType( + SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] %s\n", + __FILE__, __FUNCTION__, __LINE__, + sErr.c_str()); + } + + if (Config::getInstance().getBool("PlatformConsistencyChecks", + "true") && + versionMatched == false) { // error message and disconnect + // only if checked + if (SystemFlags::getSystemSettingType( + SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] %s\n", + __FILE__, __FUNCTION__, __LINE__, + sErr.c_str()); + close(); + if (SystemFlags::getSystemSettingType( + SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] %s\n", + __FILE__, __FUNCTION__, __LINE__, + sErr.c_str()); + return; + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + gotIntro = true; + + int factionIndex = + this->serverInterface->gameSettings + .getFactionIndexForStartLocation(playerIndex); + this->serverInterface->addClientToServerIPAddress( + this->getSocket()->getConnectedIPAddress( + this->getSocket()->getIpAddress()), + this->connectedRemoteIPAddress); + + this->serverInterface->gameSettings.setNetworkPlayerUUID( + factionIndex, this->playerUUID); + this->serverInterface->gameSettings.setNetworkPlayerPlatform( + factionIndex, this->platform); + + if (serverInterface->getGameHasBeenInitiated() == true && + serverInterface->getAllowInGameConnections() == true) { + this->serverInterface->gameSettings.setNetworkPlayerStatuses( + factionIndex, npst_None); + } + + if (getAllowGameDataSynchCheck() == true && + serverInterface->getGameSettings() != NULL) { + if (SystemFlags::getSystemSettingType( + SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] sending " + "NetworkMessageSynchNetworkGameData\n", + __FILE__, __FUNCTION__, __LINE__); + + NetworkMessageSynchNetworkGameData + networkMessageSynchNetworkGameData( + serverInterface->getGameSettings()); + sendMessage(&networkMessageSynchNetworkGameData); + } + + if (serverInterface->getGameHasBeenInitiated() == true && + serverInterface->getAllowInGameConnections() == true) { + + ConnectionSlot *slot = + serverInterface->findSlotForUUID(this->playerUUID, true); + if (slot != NULL) { + slot->setJoinGameInProgressFlags(); + slot->setPauseForInGameConnection(true); + + serverInterface->switchSlot(this->playerIndex, + slot->getPlayerIndex()); + } else { + setJoinGameInProgressFlags(); + this->setPauseForInGameConnection(true); + } + } else { + ConnectionSlot *slot = + serverInterface->findSlotForUUID(this->playerUUID, true); + if (slot != NULL) { + serverInterface->switchSlot(this->playerIndex, + slot->getPlayerIndex()); + } + } + } + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugError) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d]\nInvalid message type before intro " + "handshake [%d]\nDisconnecting socket for slot: %d [%s].\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, networkMessageType, + this->playerIndex, this->getIpAddress().c_str()); + this->serverInterface->notifyBadClientConnectAttempt( + this->getIpAddress()); + close(); + return; + } + } break; + + case nmtLaunch: + case nmtBroadCastSetup: { + if (gotIntro == true) { + if (this->serverInterface->getGameSettings() == NULL || + (joinGameInProgress == false && + sessionKey != this->serverInterface->getGameSettings() + ->getMasterserver_admin())) { + string playerNameStr = name; + string sErr = + "Client has invalid admin sessionid for player [" + + playerNameStr + "]"; + printf("%s\n", sErr.c_str()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d] %s\n", + __FILE__, __FUNCTION__, __LINE__, sErr.c_str()); + + close(); + return; + } + + NetworkMessageLaunch networkMessageLaunch; + if (receiveMessage(&networkMessageLaunch, networkMessageType)) { + if (networkMessageLaunch.getMessageType() == nmtLaunch) { + if (SystemFlags::getSystemSettingType( + SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Lined: %d] got nmtLaunch\n", __FILE__, + __FUNCTION__, __LINE__); + // printf("Got launch request from client joinGameInProgress = + // %d joinGameInProgress = + // %d!\n",joinGameInProgress,joinGameInProgress); + } else if (networkMessageLaunch.getMessageType() == + nmtBroadCastSetup) { + if (SystemFlags::getSystemSettingType( + SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Lined: %d] got nmtBroadCastSetup\n", + __FILE__, __FUNCTION__, __LINE__); + } else { + if (SystemFlags::getSystemSettingType( + SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Lined: %d] got " + "networkMessageLaunch.getMessageType() = %d\n", + __FILE__, __FUNCTION__, __LINE__, + networkMessageLaunch.getMessageType()); + + char szBuf[1024] = ""; + snprintf(szBuf, 1023, + "In [%s::%s Line: %d] Invalid " + "networkMessageLaunch.getMessageType() = %d", + __FILE__, __FUNCTION__, __LINE__, + networkMessageLaunch.getMessageType()); + throw megaglest_runtime_error(szBuf); + } + + int minHeadLessPlayersRequired = Config::getInstance().getInt( + "MinHeadlessPlayersRequired", "2"); + if (this->joinGameInProgress == false && + networkMessageLaunch.getMessageType() == nmtLaunch && + this->ready == false && + this->serverInterface->getConnectedSlotCount(true) < + minHeadLessPlayersRequired) { + + Lang &lang = Lang::getInstance(); + const vector languageList = + this->serverInterface->getGameSettings() + ->getUniqueNetworkPlayerLanguages(); + for (unsigned int index = 0; index < languageList.size(); + ++index) { + char szBuf[4096] = ""; + string msgTemplate = + "You must have have at least %d player(s) connected to " + "start this game!"; + if (lang.hasString("HeadlessAdminRequiresMorePlayers", + languageList[index]) == true) { + msgTemplate = + lang.getString("HeadlessAdminRequiresMorePlayers", + languageList[index]); + } +#ifdef WIN32 + _snprintf(szBuf, 4095, msgTemplate.c_str(), + minHeadLessPlayersRequired); +#else + snprintf(szBuf, 4095, msgTemplate.c_str(), + minHeadLessPlayersRequired); +#endif + if (SystemFlags::getSystemSettingType( + SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] %s\n", + __FILE__, __FUNCTION__, __LINE__, + szBuf); + + string sMsg = szBuf; + bool echoLocal = lang.isLanguageLocal(languageList[index]); + this->serverInterface->sendTextMessage( + sMsg, -1, echoLocal, languageList[index], + this->getPlayerIndex()); + } + } else { + if (this->joinGameInProgress == false) { + GameSettings gameSettingsBuffer; + networkMessageLaunch.buildGameSettings(&gameSettingsBuffer); + + // printf("Connection slot got + // networkMessageLaunch.getMessageType() = %d, got map + // [%s]\n",networkMessageLaunch.getMessageType(),gameSettings.getMap().c_str()); + // printf("\n\n\n\n=====Connection slot got + // settings:\n%s\n",gameSettings.toString().c_str()); + + this->serverInterface->broadcastGameSetup( + &gameSettingsBuffer, true); + } + + if (this->joinGameInProgress == false && + networkMessageLaunch.getMessageType() == nmtLaunch) { + + this->serverInterface->setMasterserverAdminRequestLaunch( + true); + } else if (this->joinGameInProgress == true && + networkMessageLaunch.getMessageType() == + nmtLaunch) { + // printf("!!! setStartInGameConnectionLaunch for client + // joinGameInProgress = %d!\n",joinGameInProgress); + + int factionIndex = + this->serverInterface->gameSettings + .getFactionIndexForStartLocation(playerIndex); + this->serverInterface->gameSettings.setFactionControl( + factionIndex, ctNetwork); + this->serverInterface->gameSettings.setNetworkPlayerName( + factionIndex, this->name); + this->serverInterface->gameSettings.setNetworkPlayerUUID( + factionIndex, this->playerUUID); + this->serverInterface->gameSettings + .setNetworkPlayerPlatform(factionIndex, this->platform); + + if (this->serverInterface->gameSettings + .getNetworkPlayerStatuses(factionIndex) == + npst_Disconnected) { + this->serverInterface->gameSettings + .setNetworkPlayerStatuses(factionIndex, npst_None); + } + + this->serverInterface->broadcastGameSetup( + &this->serverInterface->gameSettings, true); + + this->setStartInGameConnectionLaunch(true); + } + } + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugError) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d]\nInvalid message type before intro " + "handshake [%d]\nDisconnecting socket for slot: %d " + "[%s].\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, networkMessageType, + this->playerIndex, this->getIpAddress().c_str()); + this->serverInterface->notifyBadClientConnectAttempt( + this->getIpAddress()); + close(); + return; + } + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugError) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d]\nInvalid message type before intro " + "handshake [%d]\nDisconnecting socket for slot: %d [%s].\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, networkMessageType, + this->playerIndex, this->getIpAddress().c_str()); + this->serverInterface->notifyBadClientConnectAttempt( + this->getIpAddress()); + close(); + return; + } + } break; + + // process datasynch messages + case nmtSynchNetworkGameDataStatus: { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] got nmtSynchNetworkGameDataStatus, " + "gotIntro = %d\n", + __FILE__, __FUNCTION__, __LINE__, gotIntro); + + if (gotIntro == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + + NetworkMessageSynchNetworkGameDataStatus + networkMessageSynchNetworkGameDataStatus; + if (receiveMessage(&networkMessageSynchNetworkGameDataStatus)) { + this->setNetworkGameDataSynchCheckTechMismatchReport(""); + this->setReceivedDataSynchCheck(false); + + Config &config = Config::getInstance(); + string scenarioDir = ""; + if (serverInterface->getGameSettings()->getScenarioDir() != + "") { + scenarioDir = + serverInterface->getGameSettings()->getScenarioDir(); + if (EndsWith(scenarioDir, ".xml") == true) { + scenarioDir = scenarioDir.erase(scenarioDir.size() - 4, 4); + scenarioDir = scenarioDir.erase( + scenarioDir.size() - serverInterface->getGameSettings() + ->getScenario() + .size(), + serverInterface->getGameSettings() + ->getScenario() + .size() + + 1); + } + + if (SystemFlags::getSystemSettingType( + SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] gameSettings.getScenarioDir() = " + "[%s] gameSettings.getScenario() = [%s] scenarioDir = " + "[%s]\n", + __FILE__, __FUNCTION__, __LINE__, + serverInterface->getGameSettings() + ->getScenarioDir() + .c_str(), + serverInterface->getGameSettings() + ->getScenario() + .c_str(), + scenarioDir.c_str()); + } + + // tileset + uint32 tilesetCRC = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTilesets, scenarioDir), + string("/") + + serverInterface->getGameSettings()->getTileset() + + string("/*"), + ".xml", NULL); + uint32 techCRC = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTechs, scenarioDir), + "/" + serverInterface->getGameSettings()->getTech() + "/*", + ".xml", NULL); + Checksum checksum; + string file = Config::getMapPath( + serverInterface->getGameSettings()->getMap(), scenarioDir, + false); + checksum.addFile(file); + uint32 mapCRC = checksum.getSum(); + + networkGameDataSynchCheckOkMap = + (networkMessageSynchNetworkGameDataStatus.getMapCRC() == + mapCRC); + networkGameDataSynchCheckOkTile = + (networkMessageSynchNetworkGameDataStatus.getTilesetCRC() == + tilesetCRC); + networkGameDataSynchCheckOkTech = + (networkMessageSynchNetworkGameDataStatus.getTechCRC() == + techCRC); + + // For testing + // techCRC++; + + if (networkGameDataSynchCheckOkMap == true && + networkGameDataSynchCheckOkTile == true && + networkGameDataSynchCheckOkTech == true) { + if (SystemFlags::getSystemSettingType( + SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s] client data synch ok\n", __FILE__, + __FUNCTION__); + } else { + if (SystemFlags::getSystemSettingType( + SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s] mapCRC = %d, remote = %d\n", __FILE__, + __FUNCTION__, mapCRC, + networkMessageSynchNetworkGameDataStatus.getMapCRC()); + if (SystemFlags::getSystemSettingType( + SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s] tilesetCRC = %d, remote = %d\n", __FILE__, + __FUNCTION__, tilesetCRC, + networkMessageSynchNetworkGameDataStatus + .getTilesetCRC()); + if (SystemFlags::getSystemSettingType( + SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s] techCRC = %d, remote = %d\n", __FILE__, + __FUNCTION__, techCRC, + networkMessageSynchNetworkGameDataStatus.getTechCRC()); + + if (allowDownloadDataSynch == true) { + // Now get all filenames with their CRC values and send to + // the client + vctFileList.clear(); + + Config &config = Config::getInstance(); + string scenarioDir = ""; + if (serverInterface->getGameSettings()->getScenarioDir() != + "") { + scenarioDir = + serverInterface->getGameSettings()->getScenarioDir(); + if (EndsWith(scenarioDir, ".xml") == true) { + scenarioDir = + scenarioDir.erase(scenarioDir.size() - 4, 4); + scenarioDir = scenarioDir.erase( + scenarioDir.size() - + serverInterface->getGameSettings() + ->getScenario() + .size(), + serverInterface->getGameSettings() + ->getScenario() + .size() + + 1); + } + + if (SystemFlags::getSystemSettingType( + SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] " + "gameSettings.getScenarioDir() = [%s] " + "gameSettings.getScenario() = [%s] scenarioDir = " + "[%s]\n", + __FILE__, __FUNCTION__, __LINE__, + serverInterface->getGameSettings() + ->getScenarioDir() + .c_str(), + serverInterface->getGameSettings() + ->getScenario() + .c_str(), + scenarioDir.c_str()); + } + + if (networkGameDataSynchCheckOkTile == false) { + if (tilesetCRC == 0) { + vctFileList = + getFolderTreeContentsCheckSumListRecursively( + config.getPathListForType(ptTilesets, + scenarioDir), + string("/") + + serverInterface->getGameSettings() + ->getTileset() + + string("/*"), + "", &vctFileList); + } else { + vctFileList = + getFolderTreeContentsCheckSumListRecursively( + config.getPathListForType(ptTilesets, + scenarioDir), + "/" + + serverInterface->getGameSettings() + ->getTileset() + + "/*", + ".xml", &vctFileList); + } + } + if (networkGameDataSynchCheckOkTech == false) { + if (techCRC == 0) { + vctFileList = + getFolderTreeContentsCheckSumListRecursively( + config.getPathListForType(ptTechs, scenarioDir), + "/" + + serverInterface->getGameSettings() + ->getTech() + + "/*", + "", &vctFileList); + } else { + vctFileList = + getFolderTreeContentsCheckSumListRecursively( + config.getPathListForType(ptTechs, scenarioDir), + "/" + + serverInterface->getGameSettings() + ->getTech() + + "/*", + ".xml", &vctFileList); + } + + string report = + networkMessageSynchNetworkGameDataStatus + .getTechCRCFileMismatchReport( + serverInterface->getGameSettings()->getTech(), + vctFileList); + this->setNetworkGameDataSynchCheckTechMismatchReport( + report); + } + if (networkGameDataSynchCheckOkMap == false) { + vctFileList.push_back(std::pair( + Config::getMapPath( + serverInterface->getGameSettings()->getMap(), + scenarioDir, false), + mapCRC)); + } + + NetworkMessageSynchNetworkGameDataFileCRCCheck + networkMessageSynchNetworkGameDataFileCRCCheck( + (int)vctFileList.size(), 1, vctFileList[0].second, + vctFileList[0].first); + sendMessage( + &networkMessageSynchNetworkGameDataFileCRCCheck); + } else { + if (networkGameDataSynchCheckOkTech == false) { + vctFileList = + getFolderTreeContentsCheckSumListRecursively( + config.getPathListForType(ptTechs, scenarioDir), + "/" + + serverInterface->getGameSettings() + ->getTech() + + "/*", + ".xml", NULL); + + string report = + networkMessageSynchNetworkGameDataStatus + .getTechCRCFileMismatchReport( + serverInterface->getGameSettings()->getTech(), + vctFileList); + this->setNetworkGameDataSynchCheckTechMismatchReport( + report); + } + } + } + + this->setReceivedDataSynchCheck(true); + receivedNetworkGameStatus = true; + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugError) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d]\nInvalid message type before intro " + "handshake [%d]\nDisconnecting socket for slot: %d " + "[%s].\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, networkMessageType, + this->playerIndex, this->getIpAddress().c_str()); + this->serverInterface->notifyBadClientConnectAttempt( + this->getIpAddress()); + close(); + return; + } + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugError) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d]\nInvalid message type before intro " + "handshake [%d]\nDisconnecting socket for slot: %d [%s].\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, networkMessageType, + this->playerIndex, this->getIpAddress().c_str()); + this->serverInterface->notifyBadClientConnectAttempt( + this->getIpAddress()); + close(); + return; + } + } break; + + case nmtSynchNetworkGameDataFileCRCCheck: { + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s] got nmtSynchNetworkGameDataFileCRCCheck\n", + __FILE__, __FUNCTION__); + + if (gotIntro == true) { + NetworkMessageSynchNetworkGameDataFileCRCCheck + networkMessageSynchNetworkGameDataFileCRCCheck; + if (receiveMessage( + &networkMessageSynchNetworkGameDataFileCRCCheck)) { + int fileIndex = networkMessageSynchNetworkGameDataFileCRCCheck + .getFileIndex(); + NetworkMessageSynchNetworkGameDataFileCRCCheck + networkMessageSynchNetworkGameDataFileCRCCheck( + (int)vctFileList.size(), fileIndex, + vctFileList[fileIndex - 1].second, + vctFileList[fileIndex - 1].first); + sendMessage(&networkMessageSynchNetworkGameDataFileCRCCheck); + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugError) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d]\nInvalid message type before intro " + "handshake [%d]\nDisconnecting socket for slot: %d " + "[%s].\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, networkMessageType, + this->playerIndex, this->getIpAddress().c_str()); + this->serverInterface->notifyBadClientConnectAttempt( + this->getIpAddress()); + close(); + return; + } + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugError) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d]\nInvalid message type before intro " + "handshake [%d]\nDisconnecting socket for slot: %d [%s].\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, networkMessageType, + this->playerIndex, this->getIpAddress().c_str()); + this->serverInterface->notifyBadClientConnectAttempt( + this->getIpAddress()); + close(); + return; + } + } break; + + case nmtSynchNetworkGameDataFileGet: { + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s] got nmtSynchNetworkGameDataFileGet\n", __FILE__, + __FUNCTION__); + + if (gotIntro == true) { + NetworkMessageSynchNetworkGameDataFileGet + networkMessageSynchNetworkGameDataFileGet; + if (receiveMessage(&networkMessageSynchNetworkGameDataFileGet)) { + FileTransferInfo fileInfo; + fileInfo.hostType = eServer; + // fileInfo.serverIP = this->ip.getString(); + fileInfo.serverPort = Config::getInstance().getInt( + "PortServer", intToStr(GameConstants::serverPort).c_str()); + fileInfo.fileName = + networkMessageSynchNetworkGameDataFileGet.getFileName(); + + FileTransferSocketThread *fileXferThread = + new FileTransferSocketThread(fileInfo); + fileXferThread->start(); + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugError) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d]\nInvalid message type before intro " + "handshake [%d]\nDisconnecting socket for slot: %d " + "[%s].\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, networkMessageType, + this->playerIndex, this->getIpAddress().c_str()); + this->serverInterface->notifyBadClientConnectAttempt( + this->getIpAddress()); + close(); + return; + } + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugError) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d]\nInvalid message type before intro " + "handshake [%d]\nDisconnecting socket for slot: %d [%s].\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, networkMessageType, + this->playerIndex, this->getIpAddress().c_str()); + this->serverInterface->notifyBadClientConnectAttempt( + this->getIpAddress()); + close(); + return; + } + } break; + + case nmtSwitchSetupRequest: { + // printf("Got nmtSwitchSetupRequest A gotIntro = %d\n",gotIntro); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] got " + "nmtSwitchSetupRequest gotIntro = %d\n", + __FILE__, __FUNCTION__, __LINE__, + gotIntro); + + if (gotIntro == true) { + // printf("Got nmtSwitchSetupRequest B\n"); + + SwitchSetupRequest switchSetupRequest; + if (receiveMessage(&switchSetupRequest)) { + MutexSafeWrapper safeMutex(getServerSynchAccessor(), + CODE_AT_LINE); + + int slotIdx = switchSetupRequest.getCurrentSlotIndex(); + // int newSlotIdx = switchSetupRequest.getToSlotIndex(); + // printf("slotIdx = %d newSlotIdx = %d\n",slotIdx,newSlotIdx); + + if (serverInterface->getSwitchSetupRequests(slotIdx) == NULL) { + serverInterface->setSwitchSetupRequests( + slotIdx, new SwitchSetupRequest()); + } + *(serverInterface->getSwitchSetupRequests(slotIdx)) = + switchSetupRequest; + + // printf("slotIdx = %d newSlotIdx = + // %d\n",serverInterface->getSwitchSetupRequests(slotIdx)->getCurrentSlotIndex(),serverInterface->getSwitchSetupRequests(slotIdx)->getToSlotIndex()); + + this->playerStatus = + switchSetupRequest.getNetworkPlayerStatus(); + this->name = switchSetupRequest.getNetworkPlayerName(); + this->playerLanguage = + switchSetupRequest.getNetworkPlayerLanguage(); + + // printf("Got nmtSwitchSetupRequest C\n"); + // printf("In [%s::%s Line %d] networkPlayerName + // [%s]\n",__FILE__,__FUNCTION__,__LINE__,serverInterface->getSwitchSetupRequests()[factionIdx]->getNetworkPlayerName().c_str()); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d] networkPlayerName [%s]\n", + __FILE__, __FUNCTION__, __LINE__, + serverInterface->getSwitchSetupRequests()[slotIdx] + ->getNetworkPlayerName() + .c_str()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] factionIdx = %d, " + "switchSetupRequest.getNetworkPlayerName() [%s] " + "switchSetupRequest.getNetworkPlayerStatus() = %d, " + "switchSetupRequest.getSwitchFlags() = %d\n", + __FILE__, __FUNCTION__, __LINE__, slotIdx, + switchSetupRequest.getNetworkPlayerName().c_str(), + switchSetupRequest.getNetworkPlayerStatus(), + switchSetupRequest.getSwitchFlags()); + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugError) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d]\nInvalid message type before intro " + "handshake [%d]\nDisconnecting socket for slot: %d " + "[%s].\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, networkMessageType, + this->playerIndex, this->getIpAddress().c_str()); + this->serverInterface->notifyBadClientConnectAttempt( + this->getIpAddress()); + close(); + return; + } + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugError) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d]\nInvalid message type before intro " + "handshake [%d]\nDisconnecting socket for slot: %d [%s].\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, networkMessageType, + this->playerIndex, this->getIpAddress().c_str()); + this->serverInterface->notifyBadClientConnectAttempt( + this->getIpAddress()); + close(); + return; + } -//void ConnectionSlot::resetJoinGameInProgressFlags() { -// this->gotIntro = false; -// this->skipLagCheck = false; -// this->joinGameInProgress = false; -// this->ready = false; -//} + break; + } -void ConnectionSlot::setJoinGameInProgressFlags() { - this->gotIntro = true; - this->skipLagCheck = true; - this->joinGameInProgress = true; - this->ready = false; - this->sentSavedGameInfo = false; -} + case nmtReady: { + NetworkMessageReady networkMessageReady; + this->receiveMessage(&networkMessageReady); -void ConnectionSlot::close() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s LINE: %d]\n",__FILE__,__FUNCTION__,__LINE__); + // its simply ignored here. Probably we are starting a game + // printf("Got ready message from client slot joinGameInProgress = + // %d\n",joinGameInProgress); + if (joinGameInProgress == true) { + NetworkMessageReady networkMessageReady(0); + this->sendMessage(&networkMessageReady); + this->setGameStarted(true); + + this->currentFrameCount = serverInterface->getCurrentFrameCount(); + // printf("#2 Server slot got currentFrameCount = + // %d\n",currentFrameCount); - //printf("Closing slot for playerIndex = %d\n",playerIndex); - //if(serverInterface->getAllowInGameConnections() == true) { - //printf("Closing connection slot!\n"); - //} - //printf("ConnectionSlot::close() #1 this->getSocket() = %p\n",this->getSocket()); + this->currentLagCount = 0; + this->lastReceiveCommandListTime = time(NULL); - this->gotIntro = false; - this->skipLagCheck = false; - this->joinGameInProgress = false; - this->sentSavedGameInfo = false; - this->pauseForInGameConnection = false; - this->unPauseForInGameConnection = false; - this->ready = false; - this->connectedTime = 0; + this->setReady(); + } + // unpause the game + else { + this->setUnPauseForInGameConnection(true); + } + break; + } + case nmtLoadingStatusMessage: + break; + + default: { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] networkMessageType = %d\n", __FILE__, + __FUNCTION__, __LINE__, networkMessageType); + + if (gotIntro == true) { + // throw megaglest_runtime_error("Unexpected message in connection + // slot: " + intToStr(networkMessageType)); + string sErr = "Unexpected message in connection slot: " + + intToStr(networkMessageType); + // sendTextMessage(sErr,-1); + // DisplayErrorMessage(sErr); + threadErrorList.push_back(sErr); + return; + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] got invalid message type before " + "intro, disconnecting socket.\n", + __FILE__, __FUNCTION__, __LINE__); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugError) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d]\nInvalid message type before intro " + "handshake [%d]\nDisconnecting socket for slot: %d [%s].\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, networkMessageType, + this->playerIndex, this->getIpAddress().c_str()); + this->serverInterface->notifyBadClientConnectAttempt( + this->getIpAddress()); + close(); + return; + } + } + } + + // printf("#3 Server slot got currentFrameCount = + // %d\n",currentFrameCount); + + // This may end up continuously lagging and not disconnecting players + // who have just the 'wrong' amount of lag (but not enough to be + // horrible for a disconnect) + if (Config::getInstance().getBool("AutoClientLagCorrection", + "true") == true) { + double LAG_CHECK_GRACE_PERIOD = 15; + + // printf("#4 Server slot got currentFrameCount = + // %d\n",currentFrameCount); + + if (this->serverInterface->getGameStartTime() > 0 && + difftime((long int)time(NULL), + this->serverInterface->getGameStartTime()) >= + LAG_CHECK_GRACE_PERIOD && + difftime((long int)time(NULL), this->getConnectedTime()) >= + LAG_CHECK_GRACE_PERIOD) { + if (this->isConnected() == true && this->gotIntro == true && + this->skipLagCheck == false) { + double clientLag = + this->serverInterface->getCurrentFrameCount() - + this->getCurrentFrameCount(); + double clientLagCount = + (gameSettings.getNetworkFramePeriod() > 0 + ? (clientLag / gameSettings.getNetworkFramePeriod()) + : 0); + double clientLagTime = + difftime((long int)time(NULL), + this->getLastReceiveCommandListTime()); + + double maxFrameCountLagAllowed = 10; + double maxClientLagTimeAllowed = 8; + + // New lag check + if ((clientLagCount > maxFrameCountLagAllowed) || + (maxClientLagTimeAllowed > 0 && + clientLagTime > maxClientLagTimeAllowed)) { + + waitForLaggingClient = true; + if (waitedForLaggingClient == false) { + waitedForLaggingClient = true; + printf("*TESTING*: START Waiting for lagging client " + "playerIndex = %d [%s] clientLagCount = %f [%f]\n", + playerIndex, name.c_str(), clientLagCount, + clientLagTime); + } + } + } + } - if(this->slotThreadWorker != NULL) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - this->slotThreadWorker->setAllEventsCompleted(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - } + // printf("#5 Server slot got currentFrameCount = + // %d\n",currentFrameCount); + } + // printf("#5a Server slot got currentFrameCount = + // %d\n",currentFrameCount); + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + // printf("#6 Server slot got currentFrameCount = + // %d\n",currentFrameCount); - //printf("ConnectionSlot::close() #2 this->getSocket() = %p\n",this->getSocket()); + if (waitedForLaggingClient == true) { + printf("*TESTING*: FINISHED Waiting for lagging client playerIndex = " + "%d [%s]\n", + playerIndex, name.c_str()); + } - MutexSafeWrapper safeMutex(mutexCloseConnection,CODE_AT_LINE); - bool updateServerListener = (this->getSocket() != NULL); + // if(chrono.getMillis() > 1) printf("In [%s::%s Line: %d] action + // running for msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,(long long + // int)chrono.getMillis()); - //printf("ConnectionSlot::close() #3 this->getSocket() = %p updateServerListener = %d\n",this->getSocket(),updateServerListener); + validateConnection(); - this->deleteSocket(); - safeMutex.ReleaseLock(); + // printf("#7 Server slot got currentFrameCount = + // %d\n",currentFrameCount); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s LINE: %d]\n",__FILE__,__FUNCTION__,__LINE__); - //printf("Closing slot for playerIndex = %d updateServerListener = %d ready = %d\n",playerIndex,updateServerListener,ready); + // if(chrono.getMillis() > 1) printf("In [%s::%s Line: %d] action + // running for msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,(long long + // int)chrono.getMillis()); + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] calling close...\n", + __FILE__, __FUNCTION__, __LINE__); - if(updateServerListener == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s LINE: %d]\n",__FILE__,__FUNCTION__,__LINE__); - serverInterface->updateListen(); + // printf("Closing connection slot socketInfo.first = + // %d\n",socketInfo.first); + + close(); + + // if(chrono.getMillis() > 1) printf("In [%s::%s Line: %d] action + // running for msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,(long long + // int)chrono.getMillis()); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); } + } catch (const exception &ex) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", __FILE__, + __FUNCTION__, __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] error detected [%s]\n", + __FILE__, __FUNCTION__, __LINE__, ex.what()); + + threadErrorList.push_back(ex.what()); + + // if(chrono.getMillis() > 1) printf("In [%s::%s Line: %d] action running + // for msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,(long long + // int)chrono.getMillis()); + } + + // printf("#8 Server slot got currentFrameCount = %d\n",currentFrameCount); + // if(chrono.getMillis() > 1) printf("In [%s::%s Line: %d] action running for + // msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,(long long + // int)chrono.getMillis()); +} + +void ConnectionSlot::validateConnection() { + if (this->isConnected() == true && gotIntro == false && connectedTime > 0 && + difftime((long int)time(NULL), connectedTime) > + GameConstants::maxClientConnectHandshakeSecs) { + + // printf("Closing connection slot timed out!\n"); + close(); + } +} + +// void ConnectionSlot::resetJoinGameInProgressFlags() { +// this->gotIntro = false; +// this->skipLagCheck = false; +// this->joinGameInProgress = false; +// this->ready = false; +// } + +void ConnectionSlot::setJoinGameInProgressFlags() { + this->gotIntro = true; + this->skipLagCheck = true; + this->joinGameInProgress = true; + this->ready = false; + this->sentSavedGameInfo = false; +} - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] END\n",__FILE__,__FUNCTION__); +void ConnectionSlot::close() { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s LINE: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + // printf("Closing slot for playerIndex = %d\n",playerIndex); + // if(serverInterface->getAllowInGameConnections() == true) { + // printf("Closing connection slot!\n"); + //} + // printf("ConnectionSlot::close() #1 this->getSocket() = + // %p\n",this->getSocket()); + + this->gotIntro = false; + this->skipLagCheck = false; + this->joinGameInProgress = false; + this->sentSavedGameInfo = false; + this->pauseForInGameConnection = false; + this->unPauseForInGameConnection = false; + this->ready = false; + this->connectedTime = 0; + + if (this->slotThreadWorker != NULL) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + this->slotThreadWorker->setAllEventsCompleted(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + // printf("ConnectionSlot::close() #2 this->getSocket() = + // %p\n",this->getSocket()); + + MutexSafeWrapper safeMutex(mutexCloseConnection, CODE_AT_LINE); + bool updateServerListener = (this->getSocket() != NULL); + + // printf("ConnectionSlot::close() #3 this->getSocket() = %p + // updateServerListener = %d\n",this->getSocket(),updateServerListener); + + this->deleteSocket(); + safeMutex.ReleaseLock(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s LINE: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + // printf("Closing slot for playerIndex = %d updateServerListener = %d ready = + // %d\n",playerIndex,updateServerListener,ready); + + if (updateServerListener == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s LINE: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + serverInterface->updateListen(); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, "In [%s::%s] END\n", + __FILE__, __FUNCTION__); } -Mutex * ConnectionSlot::getServerSynchAccessor() { - return (serverInterface != NULL ? serverInterface->getServerSynchAccessor() : NULL); +Mutex *ConnectionSlot::getServerSynchAccessor() { + return (serverInterface != NULL ? serverInterface->getServerSynchAccessor() + : NULL); } void ConnectionSlot::signalUpdate(ConnectionSlotEvent *event) { - if(slotThreadWorker != NULL) { - slotThreadWorker->signalUpdate(event); - } + if (slotThreadWorker != NULL) { + slotThreadWorker->signalUpdate(event); + } } bool ConnectionSlot::updateCompleted(ConnectionSlotEvent *event) { - bool waitingForThread = (slotThreadWorker != NULL && - slotThreadWorker->isSignalCompleted(event) == false && - slotThreadWorker->getQuitStatus() == false && - slotThreadWorker->getRunningStatus() == true); + bool waitingForThread = + (slotThreadWorker != NULL && + slotThreadWorker->isSignalCompleted(event) == false && + slotThreadWorker->getQuitStatus() == false && + slotThreadWorker->getRunningStatus() == true); - return (waitingForThread == false); + return (waitingForThread == false); } -void ConnectionSlot::sendMessage(NetworkMessage* networkMessage) { - MutexSafeWrapper safeMutex(socketSynchAccessor,CODE_AT_LINE); - - // Skip text messages not intended for the players preferred language - NetworkMessageText *textMsg = dynamic_cast(networkMessage); - if(textMsg != NULL) { - //printf("\n\n\n~~~ SERVER HAS NetworkMessageText target [%s] player [%s] msg[%s]\n\n\n",textMsg->getTargetLanguage().c_str(),this->getNetworkPlayerLanguage().c_str(), textMsg->getText().c_str()); - if(textMsg->getTargetLanguage() != "" && - textMsg->getTargetLanguage() != this->getNetworkPlayerLanguage()) { - return; - } - } +void ConnectionSlot::sendMessage(NetworkMessage *networkMessage) { + MutexSafeWrapper safeMutex(socketSynchAccessor, CODE_AT_LINE); + + // Skip text messages not intended for the players preferred language + NetworkMessageText *textMsg = + dynamic_cast(networkMessage); + if (textMsg != NULL) { + // printf("\n\n\n~~~ SERVER HAS NetworkMessageText target [%s] player [%s] + // msg[%s]\n\n\n",textMsg->getTargetLanguage().c_str(),this->getNetworkPlayerLanguage().c_str(), + // textMsg->getText().c_str()); + if (textMsg->getTargetLanguage() != "" && + textMsg->getTargetLanguage() != this->getNetworkPlayerLanguage()) { + return; + } + } - NetworkInterface::sendMessage(networkMessage); + NetworkInterface::sendMessage(networkMessage); } string ConnectionSlot::getHumanPlayerName(int index) { - return serverInterface->getHumanPlayerName(index); + return serverInterface->getHumanPlayerName(index); } -vector ConnectionSlot::getPendingNetworkCommandList(bool clearList) { - vector ret; - MutexSafeWrapper safeMutexSlot(mutexPendingNetworkCommandList,CODE_AT_LINE); - if(vctPendingNetworkCommandList.empty() == false) { - ret = vctPendingNetworkCommandList; - if(clearList == true) { - vctPendingNetworkCommandList.clear(); - } +vector +ConnectionSlot::getPendingNetworkCommandList(bool clearList) { + vector ret; + MutexSafeWrapper safeMutexSlot(mutexPendingNetworkCommandList, CODE_AT_LINE); + if (vctPendingNetworkCommandList.empty() == false) { + ret = vctPendingNetworkCommandList; + if (clearList == true) { + vctPendingNetworkCommandList.clear(); } + } - return ret; + return ret; } -//void ConnectionSlot::clearPendingNetworkCommandList() { -// MutexSafeWrapper safeMutexSlot(mutexPendingNetworkCommandList,CODE_AT_LINE); +// void ConnectionSlot::clearPendingNetworkCommandList() { +// MutexSafeWrapper +// safeMutexSlot(mutexPendingNetworkCommandList,CODE_AT_LINE); // if(vctPendingNetworkCommandList.empty() == false) { // vctPendingNetworkCommandList.clear(); // } -//} +// } bool ConnectionSlot::hasValidSocketId() { - bool result = false; - MutexSafeWrapper safeMutexSlot(mutexSocket,CODE_AT_LINE); - if(socket != NULL && socket->getSocketId() > 0) { - result = true; - } - return result; - + bool result = false; + MutexSafeWrapper safeMutexSlot(mutexSocket, CODE_AT_LINE); + if (socket != NULL && socket->getSocketId() > 0) { + result = true; + } + return result; } bool ConnectionSlot::isConnected() { - bool result = false; - MutexSafeWrapper safeMutexSlot(mutexSocket,CODE_AT_LINE); - if(socket != NULL && socket->isConnected() == true) { - result = true; - } - return result; + bool result = false; + MutexSafeWrapper safeMutexSlot(mutexSocket, CODE_AT_LINE); + if (socket != NULL && socket->isConnected() == true) { + result = true; + } + return result; } PLATFORM_SOCKET ConnectionSlot::getSocketId() { - PLATFORM_SOCKET result = 0; - MutexSafeWrapper safeMutexSlot(mutexSocket,CODE_AT_LINE); - if(socket != NULL) { - result = socket->getSocketId(); - } - return result; + PLATFORM_SOCKET result = 0; + MutexSafeWrapper safeMutexSlot(mutexSocket, CODE_AT_LINE); + if (socket != NULL) { + result = socket->getSocketId(); + } + return result; } -pair ConnectionSlot::getSocketInfo() { - pair result; - MutexSafeWrapper safeMutexSlot(mutexSocket,CODE_AT_LINE); - result.first = (socket != NULL && socket->isConnected()); - result.second = socket; - - return result; +pair ConnectionSlot::getSocketInfo() { + pair result; + MutexSafeWrapper safeMutexSlot(mutexSocket, CODE_AT_LINE); + result.first = (socket != NULL && socket->isConnected()); + result.second = socket; + return result; } -Socket* ConnectionSlot::getSocket(bool mutexLock) { - MutexSafeWrapper safeMutexSlot(NULL,CODE_AT_LINE); - if(mutexLock == true) { - safeMutexSlot.setMutex(mutexSocket,CODE_AT_LINE); - } - return socket; +Socket *ConnectionSlot::getSocket(bool mutexLock) { + MutexSafeWrapper safeMutexSlot(NULL, CODE_AT_LINE); + if (mutexLock == true) { + safeMutexSlot.setMutex(mutexSocket, CODE_AT_LINE); + } + return socket; } void ConnectionSlot::setSocket(Socket *newSocket) { - MutexSafeWrapper safeMutexSlot(mutexSocket,CODE_AT_LINE); - socket = newSocket; + MutexSafeWrapper safeMutexSlot(mutexSocket, CODE_AT_LINE); + socket = newSocket; } void ConnectionSlot::deleteSocket() { - MutexSafeWrapper safeMutexSlot(mutexSocket,CODE_AT_LINE); - delete socket; - socket = NULL; + MutexSafeWrapper safeMutexSlot(mutexSocket, CODE_AT_LINE); + delete socket; + socket = NULL; } bool ConnectionSlot::hasDataToRead() { - bool result = false; + bool result = false; - MutexSafeWrapper safeMutexSlot(mutexSocket,CODE_AT_LINE); - if(socket != NULL && socket->hasDataToRead() == true) { - result = true; - } + MutexSafeWrapper safeMutexSlot(mutexSocket, CODE_AT_LINE); + if (socket != NULL && socket->hasDataToRead() == true) { + result = true; + } - return result; + return result; } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/network/connection_slot.h b/source/glest_game/network/connection_slot.h index e4168da6e..320a270a0 100644 --- a/source/glest_game/network/connection_slot.h +++ b/source/glest_game/network/connection_slot.h @@ -12,9 +12,9 @@ #ifndef _GLEST_GAME_CONNECTIONSLOT_H_ #define _GLEST_GAME_CONNECTIONSLOT_H_ -#include "socket.h" -#include "network_interface.h" #include "base_thread.h" +#include "network_interface.h" +#include "socket.h" #include #include @@ -24,7 +24,8 @@ using Shared::Platform::ServerSocket; using Shared::Platform::Socket; using std::vector; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { class ServerInterface; class ConnectionSlot; @@ -33,33 +34,27 @@ class ConnectionSlot; // class ConnectionSlotThread // ===================================================== -enum ConnectionSlotEventType -{ - eNone, - eReceiveSocketData, - eSendSocketData -}; +enum ConnectionSlotEventType { eNone, eReceiveSocketData, eSendSocketData }; class ConnectionSlotEvent { public: - - ConnectionSlotEvent() { - eventType = eNone; - triggerId = -1; - connectionSlot = NULL; - networkMessage = NULL; - socketTriggered = false; - eventCompleted = false; - eventId = -1; - } - - int64 triggerId; - ConnectionSlot* connectionSlot; - ConnectionSlotEventType eventType; - NetworkMessage *networkMessage; - bool socketTriggered; - bool eventCompleted; - int64 eventId; + ConnectionSlotEvent() { + eventType = eNone; + triggerId = -1; + connectionSlot = NULL; + networkMessage = NULL; + socketTriggered = false; + eventCompleted = false; + eventId = -1; + } + + int64 triggerId; + ConnectionSlot *connectionSlot; + ConnectionSlotEventType eventType; + NetworkMessage *networkMessage; + bool socketTriggered; + bool eventCompleted; + int64 eventId; }; // @@ -67,216 +62,238 @@ class ConnectionSlotEvent { // class ConnectionSlotCallbackInterface { public: - virtual bool isClientConnected(int index) = 0; - virtual bool getAllowInGameConnections() const = 0; - virtual ConnectionSlot *getSlot(int index, bool lockMutex) = 0; - virtual Mutex *getSlotMutex(int index) = 0; + virtual bool isClientConnected(int index) = 0; + virtual bool getAllowInGameConnections() const = 0; + virtual ConnectionSlot *getSlot(int index, bool lockMutex) = 0; + virtual Mutex *getSlotMutex(int index) = 0; - virtual void slotUpdateTask(ConnectionSlotEvent *event) = 0; - virtual ~ConnectionSlotCallbackInterface() {} + virtual void slotUpdateTask(ConnectionSlotEvent *event) = 0; + virtual ~ConnectionSlotCallbackInterface() {} }; -class ConnectionSlotThread : public BaseThread, public SlaveThreadControllerInterface -{ +class ConnectionSlotThread : public BaseThread, + public SlaveThreadControllerInterface { protected: + ConnectionSlotCallbackInterface *slotInterface; + Semaphore semTaskSignalled; + Mutex *triggerIdMutex; + vector eventList; + int slotIndex; + MasterSlaveThreadController *masterController; - ConnectionSlotCallbackInterface *slotInterface; - Semaphore semTaskSignalled; - Mutex *triggerIdMutex; - vector eventList; - int slotIndex; - MasterSlaveThreadController *masterController; + Mutex *triggerGameStarted; + bool gameStarted; - Mutex *triggerGameStarted; - bool gameStarted; + virtual void setQuitStatus(bool value); + virtual void setTaskCompleted(int eventId); - virtual void setQuitStatus(bool value); - virtual void setTaskCompleted(int eventId); - - void slotUpdateTask(ConnectionSlotEvent *event); + void slotUpdateTask(ConnectionSlotEvent *event); public: - explicit ConnectionSlotThread(int slotIndex); - ConnectionSlotThread(ConnectionSlotCallbackInterface *slotInterface,int slotIndex); - virtual ~ConnectionSlotThread(); + explicit ConnectionSlotThread(int slotIndex); + ConnectionSlotThread(ConnectionSlotCallbackInterface *slotInterface, + int slotIndex); + virtual ~ConnectionSlotThread(); - bool getGameStarted(); - void setGameStarted(bool value); + bool getGameStarted(); + void setGameStarted(bool value); - virtual void setMasterController(MasterSlaveThreadController *master) { masterController = master; } - virtual void signalSlave(void *userdata); + virtual void setMasterController(MasterSlaveThreadController *master) { + masterController = master; + } + virtual void signalSlave(void *userdata); - virtual void execute(); - void signalUpdate(ConnectionSlotEvent *event); - bool isSignalCompleted(ConnectionSlotEvent *event); + virtual void execute(); + void signalUpdate(ConnectionSlotEvent *event); + bool isSignalCompleted(ConnectionSlotEvent *event); - int getSlotIndex() const {return slotIndex; } - void setSlotIndex(int index) { this->slotIndex = index; } + int getSlotIndex() const { return slotIndex; } + void setSlotIndex(int index) { this->slotIndex = index; } - void purgeCompletedEvents(); - //void purgeAllEvents(); - void setAllEventsCompleted(); + void purgeCompletedEvents(); + // void purgeAllEvents(); + void setAllEventsCompleted(); - virtual bool canShutdown(bool deleteSelfIfShutdownDelayed=false); + virtual bool canShutdown(bool deleteSelfIfShutdownDelayed = false); }; // ===================================================== // class ConnectionSlot // ===================================================== -class ConnectionSlot: public NetworkInterface { +class ConnectionSlot : public NetworkInterface { private: - ServerInterface* serverInterface; - - Mutex *mutexSocket; - Socket* socket; - int playerIndex; - string name; - bool ready; - vector > vctFileList; - bool receivedNetworkGameStatus; - time_t connectedTime; - bool gotIntro; - - Mutex *mutexCloseConnection; - - Mutex *mutexPendingNetworkCommandList; - vector vctPendingNetworkCommandList; - ConnectionSlotThread* slotThreadWorker; - int currentFrameCount; - int currentLagCount; - time_t lastReceiveCommandListTime; - bool gotLagCountWarning; - string versionString; - int sessionKey; - uint32 connectedRemoteIPAddress; - int playerStatus; - string playerLanguage; - string playerUUID; - string platform; - - bool skipLagCheck; - bool joinGameInProgress; - bool canAcceptConnections; - bool startInGameConnectionLaunch; - bool pauseForInGameConnection; - bool unPauseForInGameConnection; - bool sentSavedGameInfo; - - int autoPauseGameCountForLag; + ServerInterface *serverInterface; + + Mutex *mutexSocket; + Socket *socket; + int playerIndex; + string name; + bool ready; + vector> vctFileList; + bool receivedNetworkGameStatus; + time_t connectedTime; + bool gotIntro; + + Mutex *mutexCloseConnection; + + Mutex *mutexPendingNetworkCommandList; + vector vctPendingNetworkCommandList; + ConnectionSlotThread *slotThreadWorker; + int currentFrameCount; + int currentLagCount; + time_t lastReceiveCommandListTime; + bool gotLagCountWarning; + string versionString; + int sessionKey; + uint32 connectedRemoteIPAddress; + int playerStatus; + string playerLanguage; + string playerUUID; + string platform; + + bool skipLagCheck; + bool joinGameInProgress; + bool canAcceptConnections; + bool startInGameConnectionLaunch; + bool pauseForInGameConnection; + bool unPauseForInGameConnection; + bool sentSavedGameInfo; + + int autoPauseGameCountForLag; public: - ConnectionSlot(ServerInterface* serverInterface, int playerIndex); - ~ConnectionSlot(); + ConnectionSlot(ServerInterface *serverInterface, int playerIndex); + ~ConnectionSlot(); - int getAutoPauseGameCountForLag(); - void incrementAutoPauseGameCountForLag(); + int getAutoPauseGameCountForLag(); + void incrementAutoPauseGameCountForLag(); - bool getGameStarted(); - void setGameStarted(bool value); + bool getGameStarted(); + void setGameStarted(bool value); - bool getStartInGameConnectionLaunch() const { return startInGameConnectionLaunch; } - void setStartInGameConnectionLaunch(bool value) { startInGameConnectionLaunch = value; } + bool getStartInGameConnectionLaunch() const { + return startInGameConnectionLaunch; + } + void setStartInGameConnectionLaunch(bool value) { + startInGameConnectionLaunch = value; + } - bool getPauseForInGameConnection() const { return pauseForInGameConnection; } - void setPauseForInGameConnection(bool value) { pauseForInGameConnection = value; } + bool getPauseForInGameConnection() const { return pauseForInGameConnection; } + void setPauseForInGameConnection(bool value) { + pauseForInGameConnection = value; + } - bool getUnPauseForInGameConnection() const { return unPauseForInGameConnection; } - void setUnPauseForInGameConnection(bool value) { unPauseForInGameConnection = value; } + bool getUnPauseForInGameConnection() const { + return unPauseForInGameConnection; + } + void setUnPauseForInGameConnection(bool value) { + unPauseForInGameConnection = value; + } - bool getSkipLagCheck() const { return skipLagCheck; } - bool getJoinGameInProgress() const { return joinGameInProgress; } + bool getSkipLagCheck() const { return skipLagCheck; } + bool getJoinGameInProgress() const { return joinGameInProgress; } - bool getSentSavedGameInfo() const { return sentSavedGameInfo; } - void setSentSavedGameInfo(bool value) { sentSavedGameInfo = value; } + bool getSentSavedGameInfo() const { return sentSavedGameInfo; } + void setSentSavedGameInfo(bool value) { sentSavedGameInfo = value; } - ConnectionSlotThread *getWorkerThread() { return slotThreadWorker; } + ConnectionSlotThread *getWorkerThread() { return slotThreadWorker; } - void update(bool checkForNewClients,int lockedSlotIndex); - void setPlayerIndex(int value); - int getPlayerIndex() const {return playerIndex;} + void update(bool checkForNewClients, int lockedSlotIndex); + void setPlayerIndex(int value); + int getPlayerIndex() const { return playerIndex; } - uint32 getConnectedRemoteIPAddress() const { return connectedRemoteIPAddress; } + uint32 getConnectedRemoteIPAddress() const { + return connectedRemoteIPAddress; + } - void setReady(); - const string &getName() const {return name;} - const string &getUUID() const {return playerUUID;} - const string &getPlatform() const { return platform; } - void setName(string value) {name = value;} - bool isReady() const {return ready;} + void setReady(); + const string &getName() const { return name; } + const string &getUUID() const { return playerUUID; } + const string &getPlatform() const { return platform; } + void setName(string value) { name = value; } + bool isReady() const { return ready; } - virtual std::string getIpAddress(bool mutexLock=true); + virtual std::string getIpAddress(bool mutexLock = true); - virtual Socket* getSocket(bool mutexLock=true); - pair getSocketInfo(); + virtual Socket *getSocket(bool mutexLock = true); + pair getSocketInfo(); - virtual void close(); - //virtual bool getFogOfWar(); + virtual void close(); + // virtual bool getFogOfWar(); - bool getReceivedNetworkGameStatus() const { return receivedNetworkGameStatus; } - void setReceivedNetworkGameStatus(bool value) { receivedNetworkGameStatus = value; } + bool getReceivedNetworkGameStatus() const { + return receivedNetworkGameStatus; + } + void setReceivedNetworkGameStatus(bool value) { + receivedNetworkGameStatus = value; + } - bool hasValidSocketId(); - virtual bool getConnectHasHandshaked() const { return gotIntro; } - std::vector getThreadErrorList() const { return threadErrorList; } - void clearThreadErrorList() { threadErrorList.clear(); } + bool hasValidSocketId(); + virtual bool getConnectHasHandshaked() const { return gotIntro; } + std::vector getThreadErrorList() const { + return threadErrorList; + } + void clearThreadErrorList() { threadErrorList.clear(); } - vector getPendingNetworkCommandList(bool clearList=false); - //void clearPendingNetworkCommandList(); + vector getPendingNetworkCommandList(bool clearList = false); + // void clearPendingNetworkCommandList(); - void signalUpdate(ConnectionSlotEvent *event); - bool updateCompleted(ConnectionSlotEvent *event); + void signalUpdate(ConnectionSlotEvent *event); + bool updateCompleted(ConnectionSlotEvent *event); - virtual void sendMessage(NetworkMessage* networkMessage); - int getCurrentFrameCount() const { return currentFrameCount; } + virtual void sendMessage(NetworkMessage *networkMessage); + int getCurrentFrameCount() const { return currentFrameCount; } - int getCurrentLagCount() const { return currentLagCount; } - void setCurrentLagCount(int value) { currentLagCount = value; } + int getCurrentLagCount() const { return currentLagCount; } + void setCurrentLagCount(int value) { currentLagCount = value; } - time_t getLastReceiveCommandListTime() const { return lastReceiveCommandListTime; } + time_t getLastReceiveCommandListTime() const { + return lastReceiveCommandListTime; + } - bool getLagCountWarning() const { return gotLagCountWarning; } - void setLagCountWarning(bool value) { gotLagCountWarning = value; } + bool getLagCountWarning() const { return gotLagCountWarning; } + void setLagCountWarning(bool value) { gotLagCountWarning = value; } - const string &getVersionString() const {return versionString;} + const string &getVersionString() const { return versionString; } - void validateConnection(); - virtual string getHumanPlayerName(int index=-1); - virtual int getHumanPlayerIndex() const {return playerIndex;} + void validateConnection(); + virtual string getHumanPlayerName(int index = -1); + virtual int getHumanPlayerIndex() const { return playerIndex; } - int getNetworkPlayerStatus() const { return playerStatus;} + int getNetworkPlayerStatus() const { return playerStatus; } - string getNetworkPlayerLanguage() const { return playerLanguage; } + string getNetworkPlayerLanguage() const { return playerLanguage; } - time_t getConnectedTime() const { return connectedTime; } - int getSessionKey() const { return sessionKey; } + time_t getConnectedTime() const { return connectedTime; } + int getSessionKey() const { return sessionKey; } - void updateSlot(ConnectionSlotEvent *event); - virtual bool isConnected(); + void updateSlot(ConnectionSlotEvent *event); + virtual bool isConnected(); - PLATFORM_SOCKET getSocketId(); + PLATFORM_SOCKET getSocketId(); - void setCanAcceptConnections(bool value) { canAcceptConnections = value; } - bool getCanAcceptConnections() const { return canAcceptConnections; } + void setCanAcceptConnections(bool value) { canAcceptConnections = value; } + bool getCanAcceptConnections() const { return canAcceptConnections; } - virtual void saveGame(XmlNode *rootNode) {}; + virtual void saveGame(XmlNode *rootNode){}; - //void resetJoinGameInProgressFlags(); - void setJoinGameInProgressFlags(); + // void resetJoinGameInProgressFlags(); + void setJoinGameInProgressFlags(); protected: + Mutex *getServerSynchAccessor(); + std::vector threadErrorList; + Mutex *socketSynchAccessor; - Mutex * getServerSynchAccessor(); - std::vector threadErrorList; - Mutex *socketSynchAccessor; - - void setSocket(Socket *newSocket); - void deleteSocket(); - virtual void update() {} + void setSocket(Socket *newSocket); + void deleteSocket(); + virtual void update() {} - bool hasDataToRead(); + bool hasDataToRead(); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/network/masterserver_info.h b/source/glest_game/network/masterserver_info.h index dae40d32e..edaec823e 100644 --- a/source/glest_game/network/masterserver_info.h +++ b/source/glest_game/network/masterserver_info.h @@ -3,92 +3,93 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== #ifndef _GLEST_GAME_MASTERSERVERINFO_H_ #define _GLEST_GAME_MASTERSERVERINFO_H_ -#include #include "game_constants.h" #include "leak_dumper.h" +#include using std::string; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // =========================================================== -// class ParticleSystemType +// class ParticleSystemType // /// A type of particle system // =========================================================== class MasterServerInfo { protected: - //general info: - string glestVersion; - string platform; - string binaryCompileDate; - - //game info: - string serverTitle; - string ipAddress; - - //game setup info: - string tech; - string map; - string tileset; - int activeSlots; - int networkSlots; - int connectedClients; - int externalconnectport; - string country; - int status; + // general info: + string glestVersion; + string platform; + string binaryCompileDate; + + // game info: + string serverTitle; + string ipAddress; + + // game setup info: + string tech; + string map; + string tileset; + int activeSlots; + int networkSlots; + int connectedClients; + int externalconnectport; + string country; + int status; public: - const string &getGlestVersion() const {return glestVersion;} - const string &getPlatform() const {return platform;} - const string &getBinaryCompileDate() const {return binaryCompileDate;} - - const string &getServerTitle() const {return serverTitle;} - const string &getIpAddress() const {return ipAddress;} - - const string &getTech() const {return tech;} - const string &getMap() const {return map;} - const string &getTileset() const {return tileset;} - const int getActiveSlots() const {return activeSlots;} - const int getNetworkSlots() const {return networkSlots;} - const int getConnectedClients() const {return connectedClients;} - const int getExternalConnectPort() const {return externalconnectport;} - const string &getCountry() const { return country;} - const int getStatus() const { return status;} - - - //general info: - void setGlestVersion(string value) { glestVersion = value; } - void setPlatform(string value) { platform = value; } - void setBinaryCompileDate(string value) { binaryCompileDate = value; } - - //game info: - void setServerTitle(string value) { serverTitle = value; } - void setIpAddress(string value) { ipAddress = value; } - - //game setup info: - void setTech(string value) { tech = value; } - void setMap(string value) { map = value; } - void setTileset(string value) { tileset = value; } - - void setActiveSlots(int value) { activeSlots = value; } - void setNetworkSlots(int value) { networkSlots = value; } - void setConnectedClients(int value) { connectedClients = value; } - void setExternalConnectPort(int value) { externalconnectport = value; } - void setCountry(string value) { country = value; } - void setStatus(int value) { status = value; } + const string &getGlestVersion() const { return glestVersion; } + const string &getPlatform() const { return platform; } + const string &getBinaryCompileDate() const { return binaryCompileDate; } + + const string &getServerTitle() const { return serverTitle; } + const string &getIpAddress() const { return ipAddress; } + + const string &getTech() const { return tech; } + const string &getMap() const { return map; } + const string &getTileset() const { return tileset; } + const int getActiveSlots() const { return activeSlots; } + const int getNetworkSlots() const { return networkSlots; } + const int getConnectedClients() const { return connectedClients; } + const int getExternalConnectPort() const { return externalconnectport; } + const string &getCountry() const { return country; } + const int getStatus() const { return status; } + + // general info: + void setGlestVersion(string value) { glestVersion = value; } + void setPlatform(string value) { platform = value; } + void setBinaryCompileDate(string value) { binaryCompileDate = value; } + + // game info: + void setServerTitle(string value) { serverTitle = value; } + void setIpAddress(string value) { ipAddress = value; } + + // game setup info: + void setTech(string value) { tech = value; } + void setMap(string value) { map = value; } + void setTileset(string value) { tileset = value; } + + void setActiveSlots(int value) { activeSlots = value; } + void setNetworkSlots(int value) { networkSlots = value; } + void setConnectedClients(int value) { connectedClients = value; } + void setExternalConnectPort(int value) { externalconnectport = value; } + void setCountry(string value) { country = value; } + void setStatus(int value) { status = value; } }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/network/network_interface.cpp b/source/glest_game/network/network_interface.cpp index 0eb959479..b1300d2f3 100644 --- a/source/glest_game/network/network_interface.cpp +++ b/source/glest_game/network/network_interface.cpp @@ -11,409 +11,514 @@ #include "network_interface.h" -#include #include +#include -#include "data_types.h" #include "conversion.h" +#include "data_types.h" +#include "leak_dumper.h" +#include "network_protocol.h" #include "platform_util.h" -#include #include "util.h" -#include "network_protocol.h" -#include "leak_dumper.h" +#include using namespace Shared::Platform; using namespace Shared::Util; using namespace std; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class NetworkInterface // ===================================================== -const int NetworkInterface::readyWaitTimeout= 99000; // 99 seconds to 0 looks good on the screen +const int NetworkInterface::readyWaitTimeout = + 99000; // 99 seconds to 0 looks good on the screen -bool NetworkInterface::allowGameDataSynchCheck = false; -bool NetworkInterface::allowDownloadDataSynch = false; +bool NetworkInterface::allowGameDataSynchCheck = false; +bool NetworkInterface::allowDownloadDataSynch = false; DisplayMessageFunction NetworkInterface::pCB_DisplayMessage = NULL; -Vec3f MarkedCell::static_system_marker_color(MAGENTA.x,MAGENTA.y,MAGENTA.z); +Vec3f MarkedCell::static_system_marker_color(MAGENTA.x, MAGENTA.y, MAGENTA.z); NetworkInterface::NetworkInterface() { - networkAccessMutex = new Mutex(CODE_AT_LINE); + networkAccessMutex = new Mutex(CODE_AT_LINE); - networkGameDataSynchCheckOkMap=false; - networkGameDataSynchCheckOkTile=false; - networkGameDataSynchCheckOkTech=false; - receivedDataSynchCheck=false; + networkGameDataSynchCheckOkMap = false; + networkGameDataSynchCheckOkTile = false; + networkGameDataSynchCheckOkTech = false; + receivedDataSynchCheck = false; - networkPlayerFactionCRCMutex = new Mutex(CODE_AT_LINE); - for(unsigned int index = 0; index < (unsigned int)GameConstants::maxPlayers; ++index) { - networkPlayerFactionCRC[index] = 0; - } + networkPlayerFactionCRCMutex = new Mutex(CODE_AT_LINE); + for (unsigned int index = 0; index < (unsigned int)GameConstants::maxPlayers; + ++index) { + networkPlayerFactionCRC[index] = 0; + } } void NetworkInterface::init() { - networkAccessMutex = NULL; + networkAccessMutex = NULL; - networkGameDataSynchCheckOkMap=false; - networkGameDataSynchCheckOkTile=false; - networkGameDataSynchCheckOkTech=false; - receivedDataSynchCheck=false; + networkGameDataSynchCheckOkMap = false; + networkGameDataSynchCheckOkTile = false; + networkGameDataSynchCheckOkTech = false; + receivedDataSynchCheck = false; - gameSettings = GameSettings(); + gameSettings = GameSettings(); - networkPlayerFactionCRCMutex = NULL; - for(unsigned int index = 0; index < (unsigned int)GameConstants::maxPlayers; ++index) { - networkPlayerFactionCRC[index] = 0; - } + networkPlayerFactionCRCMutex = NULL; + for (unsigned int index = 0; index < (unsigned int)GameConstants::maxPlayers; + ++index) { + networkPlayerFactionCRC[index] = 0; + } } NetworkInterface::~NetworkInterface() { - delete networkAccessMutex; - networkAccessMutex = NULL; + delete networkAccessMutex; + networkAccessMutex = NULL; - delete networkPlayerFactionCRCMutex; - networkPlayerFactionCRCMutex = NULL; + delete networkPlayerFactionCRCMutex; + networkPlayerFactionCRCMutex = NULL; } uint32 NetworkInterface::getNetworkPlayerFactionCRC(int index) { - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(networkPlayerFactionCRCMutex,mutexOwnerId); + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(networkPlayerFactionCRCMutex, mutexOwnerId); - return networkPlayerFactionCRC[index]; + return networkPlayerFactionCRC[index]; } void NetworkInterface::setNetworkPlayerFactionCRC(int index, uint32 crc) { - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(networkPlayerFactionCRCMutex,mutexOwnerId); + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(networkPlayerFactionCRCMutex, mutexOwnerId); - networkPlayerFactionCRC[index]=crc; + networkPlayerFactionCRC[index] = crc; } void NetworkInterface::addChatInfo(const ChatMsgInfo &msg) { - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(networkAccessMutex,mutexOwnerId); + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(networkAccessMutex, mutexOwnerId); - chatTextList.push_back(msg); + chatTextList.push_back(msg); } void NetworkInterface::addMarkedCell(const MarkedCell &msg) { - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(networkAccessMutex,mutexOwnerId); + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(networkAccessMutex, mutexOwnerId); - markedCellList.push_back(msg); + markedCellList.push_back(msg); } void NetworkInterface::addUnMarkedCell(const UnMarkedCell &msg) { - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(networkAccessMutex,mutexOwnerId); + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(networkAccessMutex, mutexOwnerId); - unmarkedCellList.push_back(msg); + unmarkedCellList.push_back(msg); } -void NetworkInterface::sendMessage(NetworkMessage* networkMessage){ - Socket* socket= getSocket(false); +void NetworkInterface::sendMessage(NetworkMessage *networkMessage) { + Socket *socket = getSocket(false); - networkMessage->send(socket); + networkMessage->send(socket); } NetworkMessageType NetworkInterface::getNextMessageType(int waitMilliseconds) { - Socket* socket= getSocket(false); - int8 messageType= nmtInvalid; - -/* - if(socket != NULL && - ((waitMilliseconds <= 0 && socket->hasDataToRead() == true) || - (waitMilliseconds > 0 && socket->hasDataToReadWithWait(waitMilliseconds) == true))) { - //peek message type - int dataSize = socket->getDataToRead(); - if(dataSize >= (int)sizeof(messageType)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] socket->getDataToRead() dataSize = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,dataSize); - - int iPeek = socket->peek(&messageType, sizeof(messageType)); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] socket->getDataToRead() iPeek = %d, messageType = %d [size = %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,iPeek,messageType,sizeof(messageType)); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] PEEK WARNING, socket->getDataToRead() messageType = %d [size = %d], dataSize = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,messageType,sizeof(messageType),dataSize); - } - - //sanity check new message type - if(messageType < 0 || messageType >= nmtCount) { - if(getConnectHasHandshaked() == true) { - throw megaglest_runtime_error("Invalid message type: " + intToStr(messageType)); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] Invalid message type = %d (no packet handshake yet so ignored)\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,messageType); - } - } + Socket *socket = getSocket(false); + int8 messageType = nmtInvalid; + + /* + if(socket != NULL && + ((waitMilliseconds <= 0 && socket->hasDataToRead() == true) || + (waitMilliseconds > 0 && + socket->hasDataToReadWithWait(waitMilliseconds) == true))) { + //peek message type + int dataSize = socket->getDataToRead(); + if(dataSize >= (int)sizeof(messageType)) { + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] + socket->getDataToRead() dataSize = + %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,dataSize); + + int iPeek = socket->peek(&messageType, + sizeof(messageType)); + + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] + socket->getDataToRead() iPeek = %d, messageType = %d [size = + %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,iPeek,messageType,sizeof(messageType)); + } + else { + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] + PEEK WARNING, socket->getDataToRead() messageType = %d [size = %d], + dataSize = + %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,messageType,sizeof(messageType),dataSize); + } + + //sanity check new message type + if(messageType < 0 || messageType >= nmtCount) { + if(getConnectHasHandshaked() == true) { + throw megaglest_runtime_error("Invalid message type: " + + intToStr(messageType)); + } + else { + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] + Invalid message type = %d (no packet handshake yet so + ignored)\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,messageType); + } + } + } + + return static_cast(messageType); + */ + + // According to here: https://support.microsoft.com/en-us/kb/192599 + // its a terrible sin to use MSG_PEEK so lets try an alternative + + /* + int bytesReceived = socket->receive(&messageType, sizeof(messageType), true); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] + socket->getDataToRead() iPeek = %d, messageType = %d [size = + %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,bytesReceived,messageType,sizeof(messageType)); + + return static_cast(messageType); + */ + + if (socket != NULL && + ((waitMilliseconds <= 0 && socket->hasDataToRead() == true) || + (waitMilliseconds > 0 && + socket->hasDataToReadWithWait(waitMilliseconds) == true))) { + // peek message type + int dataSize = socket->getDataToRead(); + if (dataSize >= (int)sizeof(messageType)) { + // if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: + // %d] socket->getDataToRead() dataSize = + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,dataSize); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] before recv\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // int iPeek = socket->peek(&messageType, + // sizeof(messageType)); + // if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: + // %d] socket->getDataToRead() iPeek = %d, messageType = %d [size = + //%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,iPeek,messageType,sizeof(messageType)); + // if(iPeek > 0) { + int bytesReceived = + socket->receive(&messageType, sizeof(messageType), true); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] socket->getDataToRead() " + "iPeek = %d, messageType = %d [size = %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, bytesReceived, + messageType, sizeof(messageType)); + //} } - - return static_cast(messageType); -*/ - - - // According to here: https://support.microsoft.com/en-us/kb/192599 - // its a terrible sin to use MSG_PEEK so lets try an alternative - - /* - int bytesReceived = socket->receive(&messageType, sizeof(messageType), true); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] socket->getDataToRead() iPeek = %d, messageType = %d [size = %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,bytesReceived,messageType,sizeof(messageType)); - - return static_cast(messageType); - */ - - - if(socket != NULL && - ((waitMilliseconds <= 0 && socket->hasDataToRead() == true) || - (waitMilliseconds > 0 && socket->hasDataToReadWithWait(waitMilliseconds) == true))) { - //peek message type - int dataSize = socket->getDataToRead(); - if(dataSize >= (int)sizeof(messageType)) { - //if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] socket->getDataToRead() dataSize = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,dataSize); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] before recv\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - -// int iPeek = socket->peek(&messageType, sizeof(messageType)); -// if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] socket->getDataToRead() iPeek = %d, messageType = %d [size = %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,iPeek,messageType,sizeof(messageType)); -// if(iPeek > 0) { - int bytesReceived = socket->receive(&messageType, sizeof(messageType), true); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] socket->getDataToRead() iPeek = %d, messageType = %d [size = %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,bytesReceived,messageType,sizeof(messageType)); - //} - } - //else { - // if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] PEEK WARNING, socket->getDataToRead() messageType = %d [size = %d], dataSize = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,messageType,sizeof(messageType),dataSize); - //} - - if (socket->isSocketValid() == false) { - return nmtInvalid; - } - //sanity check new message type - if(messageType < 0 || messageType >= nmtCount) { - if(getConnectHasHandshaked() == true) { - throw megaglest_runtime_error("Invalid message type: " + intToStr(messageType)); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] Invalid message type = %d (no packet handshake yet so ignored)\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,messageType); - } - } + // else { + // if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] + // PEEK WARNING, socket->getDataToRead() messageType = %d [size = %d], + // dataSize = + //%d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,messageType,sizeof(messageType),dataSize); + // } + + if (socket->isSocketValid() == false) { + return nmtInvalid; } + // sanity check new message type + if (messageType < 0 || messageType >= nmtCount) { + if (getConnectHasHandshaked() == true) { + throw megaglest_runtime_error("Invalid message type: " + + intToStr(messageType)); + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] Invalid message type = %d (no packet " + "handshake yet so ignored)\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, messageType); + } + } + } - return static_cast(messageType); - + return static_cast(messageType); } -bool NetworkInterface::receiveMessage(NetworkMessage* networkMessage){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); +bool NetworkInterface::receiveMessage(NetworkMessage *networkMessage) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, "In [%s::%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__); - Socket* socket= getSocket(false); + Socket *socket = getSocket(false); - return networkMessage->receive(socket); + return networkMessage->receive(socket); } -bool NetworkInterface::receiveMessage(NetworkMessage* networkMessage, NetworkMessageType type) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); +bool NetworkInterface::receiveMessage(NetworkMessage *networkMessage, + NetworkMessageType type) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, "In [%s::%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__); - Socket* socket = getSocket(false); + Socket *socket = getSocket(false); - return networkMessage->receive(socket, type); + return networkMessage->receive(socket, type); } -bool NetworkInterface::isConnected(){ - bool result = (getSocket()!=NULL && getSocket()->isConnected()); - return result; +bool NetworkInterface::isConnected() { + bool result = (getSocket() != NULL && getSocket()->isConnected()); + return result; } void NetworkInterface::setLastPingInfo(const NetworkMessagePing &ping) { - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(networkAccessMutex,mutexOwnerId); + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(networkAccessMutex, mutexOwnerId); - this->lastPingInfo = ping; + this->lastPingInfo = ping; } void NetworkInterface::setLastPingInfoToNow() { - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(networkAccessMutex,mutexOwnerId); + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(networkAccessMutex, mutexOwnerId); - this->lastPingInfo.setPingReceivedLocalTime(time(NULL)); + this->lastPingInfo.setPingReceivedLocalTime(time(NULL)); } NetworkMessagePing NetworkInterface::getLastPingInfo() { - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(networkAccessMutex,mutexOwnerId); + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(networkAccessMutex, mutexOwnerId); - return lastPingInfo; + return lastPingInfo; } double NetworkInterface::getLastPingLag() { - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(networkAccessMutex,mutexOwnerId); + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(networkAccessMutex, mutexOwnerId); - return difftime((long int)time(NULL),lastPingInfo.getPingReceivedLocalTime()); + return difftime((long int)time(NULL), + lastPingInfo.getPingReceivedLocalTime()); } void NetworkInterface::DisplayErrorMessage(string sErr, bool closeSocket) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] sErr [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,sErr.c_str()); - //SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] sErr [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,sErr.c_str()); - SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] sErr [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,sErr.c_str()); - - if(closeSocket == true && getSocket() != NULL) { - close(); - } - - if(pCB_DisplayMessage != NULL) { - pCB_DisplayMessage(sErr.c_str(), false); - } - else { - throw megaglest_runtime_error(sErr); - } + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] sErr [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, sErr.c_str()); + // SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] sErr + // [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,sErr.c_str()); + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] sErr [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, sErr.c_str()); + + if (closeSocket == true && getSocket() != NULL) { + close(); + } + + if (pCB_DisplayMessage != NULL) { + pCB_DisplayMessage(sErr.c_str(), false); + } else { + throw megaglest_runtime_error(sErr); + } } std::vector NetworkInterface::getChatTextList(bool clearList) { - std::vector result; + std::vector result; - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(networkAccessMutex,mutexOwnerId); + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(networkAccessMutex, mutexOwnerId); - if(chatTextList.empty() == false) { - result = chatTextList; + if (chatTextList.empty() == false) { + result = chatTextList; - if(clearList == true) { - chatTextList.clear(); - } - } - return result; + if (clearList == true) { + chatTextList.clear(); + } + } + return result; } void NetworkInterface::clearChatInfo() { - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(networkAccessMutex,mutexOwnerId); + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(networkAccessMutex, mutexOwnerId); - if(chatTextList.empty() == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] chatTextList.size() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chatTextList.size()); - chatTextList.clear(); - } + if (chatTextList.empty() == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] chatTextList.size() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, chatTextList.size()); + chatTextList.clear(); + } } std::vector NetworkInterface::getMarkedCellList(bool clearList) { - std::vector result; + std::vector result; - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(networkAccessMutex,mutexOwnerId); + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(networkAccessMutex, mutexOwnerId); - if(markedCellList.empty() == false) { - result = markedCellList; + if (markedCellList.empty() == false) { + result = markedCellList; - if(clearList == true) { - markedCellList.clear(); - } - } - return result; + if (clearList == true) { + markedCellList.clear(); + } + } + return result; } void NetworkInterface::clearMarkedCellList() { - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(networkAccessMutex,mutexOwnerId); - - if(markedCellList.empty() == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] markedCellList.size() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,markedCellList.size()); - markedCellList.clear(); - } -} - -std::vector NetworkInterface::getUnMarkedCellList(bool clearList) { - std::vector result; - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(networkAccessMutex,mutexOwnerId); - - if(unmarkedCellList.empty() == false) { - result = unmarkedCellList; - - if(clearList == true) { - unmarkedCellList.clear(); - } - } - return result; + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(networkAccessMutex, mutexOwnerId); + + if (markedCellList.empty() == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] markedCellList.size() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, markedCellList.size()); + markedCellList.clear(); + } +} + +std::vector +NetworkInterface::getUnMarkedCellList(bool clearList) { + std::vector result; + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(networkAccessMutex, mutexOwnerId); + + if (unmarkedCellList.empty() == false) { + result = unmarkedCellList; + + if (clearList == true) { + unmarkedCellList.clear(); + } + } + return result; } void NetworkInterface::clearUnMarkedCellList() { - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(networkAccessMutex,mutexOwnerId); - - if(unmarkedCellList.empty() == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] unmarkedCellList.size() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,unmarkedCellList.size()); - unmarkedCellList.clear(); - } -} - -std::vector NetworkInterface::getHighlightedCellList(bool clearList) { - std::vector result; - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(networkAccessMutex,mutexOwnerId); - - if(highlightedCellList.empty() == false) { - result = highlightedCellList; - - if(clearList == true) { - highlightedCellList.clear(); - } - } - return result; + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(networkAccessMutex, mutexOwnerId); + + if (unmarkedCellList.empty() == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] unmarkedCellList.size() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, unmarkedCellList.size()); + unmarkedCellList.clear(); + } +} + +std::vector +NetworkInterface::getHighlightedCellList(bool clearList) { + std::vector result; + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(networkAccessMutex, mutexOwnerId); + + if (highlightedCellList.empty() == false) { + result = highlightedCellList; + + if (clearList == true) { + highlightedCellList.clear(); + } + } + return result; } void NetworkInterface::clearHighlightedCellList() { - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(networkAccessMutex,mutexOwnerId); - - if(highlightedCellList.empty() == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] markedCellList.size() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,markedCellList.size()); - highlightedCellList.clear(); - } -} - -void NetworkInterface::setHighlightedCell(const MarkedCell &msg){ - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(networkAccessMutex,mutexOwnerId); - - for(int idx = 0; idx < (int)highlightedCellList.size(); idx++) { - MarkedCell mc = highlightedCellList[idx]; - if(mc.getFactionIndex()==msg.getFactionIndex()){ - highlightedCellList.erase(highlightedCellList.begin()+ idx); - break; - } - } - highlightedCellList.push_back(msg); + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(networkAccessMutex, mutexOwnerId); + + if (highlightedCellList.empty() == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] markedCellList.size() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, markedCellList.size()); + highlightedCellList.clear(); + } +} + +void NetworkInterface::setHighlightedCell(const MarkedCell &msg) { + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(networkAccessMutex, mutexOwnerId); + + for (int idx = 0; idx < (int)highlightedCellList.size(); idx++) { + MarkedCell mc = highlightedCellList[idx]; + if (mc.getFactionIndex() == msg.getFactionIndex()) { + highlightedCellList.erase(highlightedCellList.begin() + idx); + break; + } + } + highlightedCellList.push_back(msg); } float NetworkInterface::getThreadedPingMS(std::string host) { - float result = -1; + float result = -1; - if(getSocket() != NULL) { - result = getSocket()->getThreadedPingMS(host); - } - return result; + if (getSocket() != NULL) { + result = getSocket()->getThreadedPingMS(host); + } + return result; } // ===================================================== // class GameNetworkInterface // ===================================================== -GameNetworkInterface::GameNetworkInterface(){ - quit= false; -} +GameNetworkInterface::GameNetworkInterface() { quit = false; } -void GameNetworkInterface::requestCommand(const NetworkCommand *networkCommand, bool insertAtStart) { - assert(networkCommand != NULL); - Mutex *mutex = getServerSynchAccessor(); +void GameNetworkInterface::requestCommand(const NetworkCommand *networkCommand, + bool insertAtStart) { + assert(networkCommand != NULL); + Mutex *mutex = getServerSynchAccessor(); - if(insertAtStart == false) { - MutexSafeWrapper safeMutex(mutex,string(__FILE__) + "_" + intToStr(__LINE__)); - requestedCommands.push_back(*networkCommand); - } - else { - MutexSafeWrapper safeMutex(mutex,string(__FILE__) + "_" + intToStr(__LINE__)); - requestedCommands.insert(requestedCommands.begin(),*networkCommand); - } + if (insertAtStart == false) { + MutexSafeWrapper safeMutex(mutex, + string(__FILE__) + "_" + intToStr(__LINE__)); + requestedCommands.push_back(*networkCommand); + } else { + MutexSafeWrapper safeMutex(mutex, + string(__FILE__) + "_" + intToStr(__LINE__)); + requestedCommands.insert(requestedCommands.begin(), *networkCommand); + } } // ===================================================== @@ -421,176 +526,163 @@ void GameNetworkInterface::requestCommand(const NetworkCommand *networkCommand, // ===================================================== const int32 SEND_FILE = 0x20; -const int32 ACK = 0x47; +const int32 ACK = 0x47; -FileTransferSocketThread::FileTransferSocketThread(FileTransferInfo fileInfo) : info(fileInfo) { - this->info.serverPort += 100; +FileTransferSocketThread::FileTransferSocketThread(FileTransferInfo fileInfo) + : info(fileInfo) { + this->info.serverPort += 100; } -void FileTransferSocketThread::execute() -{ - if(info.hostType == eServer) - { - ServerSocket serverSocket; - serverSocket.bind(this->info.serverPort); - serverSocket.listen(1); - Socket *clientSocket = serverSocket.accept(); +void FileTransferSocketThread::execute() { + if (info.hostType == eServer) { + ServerSocket serverSocket; + serverSocket.bind(this->info.serverPort); + serverSocket.listen(1); + Socket *clientSocket = serverSocket.accept(); + + char data[513] = ""; + memset(data, 0, 256); + + clientSocket->receive(data, 256, true); + if (*data == SEND_FILE) { + FileInfo file; + + memcpy(&file, data + 1, sizeof(file)); + + *data = ACK; + clientSocket->send(data, 256); + + Checksum checksum; + checksum.addFile(file.fileName); + file.filecrc = checksum.getSum(); + + ifstream infile(file.fileName.c_str(), ios::in | ios::binary | ios::ate); + if (infile.is_open() == true) { + file.filesize = infile.tellg(); + infile.seekg(0, ios::beg); - char data[513]=""; memset(data, 0, 256); + *data = SEND_FILE; + memcpy(data + 1, &file, sizeof(file)); - clientSocket->receive(data,256, true); - if(*data == SEND_FILE) - { - FileInfo file; - - memcpy(&file, data+1, sizeof(file)); - - *data=ACK; - clientSocket->send(data,256); - - Checksum checksum; - checksum.addFile(file.fileName); - file.filecrc = checksum.getSum(); - - ifstream infile(file.fileName.c_str(), ios::in | ios::binary | ios::ate); - if(infile.is_open() == true) - { - file.filesize = infile.tellg(); - infile.seekg (0, ios::beg); - - memset(data, 0, 256); - *data=SEND_FILE; - memcpy(data+1,&file,sizeof(file)); - - clientSocket->send(data,256); - clientSocket->receive(data,256, true); - if(*data != ACK) { - //transfer error - } - - int remain=file.filesize % 512 ; - int packs=(file.filesize-remain)/512; - - while(packs--) - { - infile.read(data,512); - //if(!ReadFile(file,data,512,&read,NULL)) - // ; //read error - //if(written!=pack) - // ; //read error - clientSocket->send(data,512); - clientSocket->receive(data,256, true); - if(*data!=ACK) { - //transfer error - } - } - - infile.read(data,remain); - //if(!ReadFile(file,data,remain,&read,NULL)) - // ; //read error - //if(written!=pack) - // ; //read error - - clientSocket->send(data,remain); - clientSocket->receive(data,256, true); - if(*data!=ACK) { - //transfer error - } - - infile.close(); - } + clientSocket->send(data, 256); + clientSocket->receive(data, 256, true); + if (*data != ACK) { + // transfer error + } + + int remain = file.filesize % 512; + int packs = (file.filesize - remain) / 512; + + while (packs--) { + infile.read(data, 512); + // if(!ReadFile(file,data,512,&read,NULL)) + // ; //read error + // if(written!=pack) + // ; //read error + clientSocket->send(data, 512); + clientSocket->receive(data, 256, true); + if (*data != ACK) { + // transfer error + } + } + + infile.read(data, remain); + // if(!ReadFile(file,data,remain,&read,NULL)) + // ; //read error + // if(written!=pack) + // ; //read error + + clientSocket->send(data, remain); + clientSocket->receive(data, 256, true); + if (*data != ACK) { + // transfer error } - delete clientSocket; + infile.close(); + } } - else - { - Ip ip(this->info.serverIP); - ClientSocket clientSocket; - clientSocket.connect(this->info.serverIP, this->info.serverPort); - - if(clientSocket.isConnected() == true) - { - FileInfo file; - file.fileName = this->info.fileName; - //file.filesize = - //file.filecrc = this->info. - - string path = extractDirectoryPathFromFile(file.fileName); - createDirectoryPaths(path); - ofstream outFile(file.fileName.c_str(), ios_base::binary | ios_base::out); - if(outFile.is_open() == true) - { - char data[513]=""; - memset(data, 0, 256); - *data=SEND_FILE; - memcpy(data+1,&file,sizeof(file)); - - clientSocket.send(data,256); - clientSocket.receive(data,256, true); - if(*data!=ACK) { - //transfer error - } - - clientSocket.receive(data,256,true); - if(*data == SEND_FILE) - { - memcpy(&file, data+1, sizeof(file)); - *data=ACK; - clientSocket.send(data,256); - - int remain = file.filesize % 512 ; - int packs = (file.filesize-remain) / 512; - - while(packs--) - { - clientSocket.receive(data,512,true); - - outFile.write(data, 512); - if(outFile.bad()) - { - //int ii = 0; - } - //if(!WriteFile(file,data,512,&written,NULL)) - // ; //write error - //if(written != pack) - // ; //write error - *data=ACK; - clientSocket.send(data,256); - } - clientSocket.receive(data,remain,true); - - outFile.write(data, remain); - if(outFile.bad()) - { - //int ii = 0; - } - - //if(!WriteFile(file,data,remain,&written,NULL)) - // ; //write error - //if(written!=pack) - // ; //write error - *data=ACK; - clientSocket.send(data,256); - - Checksum checksum; - checksum.addFile(file.fileName); - uint32 crc = checksum.getSum(); - if(file.filecrc != crc) - { - //int ii = 0; - } - - //if(calc_crc(file)!=info.crc) - // ; //transfeer error - } - - outFile.close(); + + delete clientSocket; + } else { + Ip ip(this->info.serverIP); + ClientSocket clientSocket; + clientSocket.connect(this->info.serverIP, this->info.serverPort); + + if (clientSocket.isConnected() == true) { + FileInfo file; + file.fileName = this->info.fileName; + // file.filesize = + // file.filecrc = this->info. + + string path = extractDirectoryPathFromFile(file.fileName); + createDirectoryPaths(path); + ofstream outFile(file.fileName.c_str(), ios_base::binary | ios_base::out); + if (outFile.is_open() == true) { + char data[513] = ""; + memset(data, 0, 256); + *data = SEND_FILE; + memcpy(data + 1, &file, sizeof(file)); + + clientSocket.send(data, 256); + clientSocket.receive(data, 256, true); + if (*data != ACK) { + // transfer error + } + + clientSocket.receive(data, 256, true); + if (*data == SEND_FILE) { + memcpy(&file, data + 1, sizeof(file)); + *data = ACK; + clientSocket.send(data, 256); + + int remain = file.filesize % 512; + int packs = (file.filesize - remain) / 512; + + while (packs--) { + clientSocket.receive(data, 512, true); + + outFile.write(data, 512); + if (outFile.bad()) { + // int ii = 0; } + // if(!WriteFile(file,data,512,&written,NULL)) + // ; //write error + // if(written != pack) + // ; //write error + *data = ACK; + clientSocket.send(data, 256); + } + clientSocket.receive(data, remain, true); + + outFile.write(data, remain); + if (outFile.bad()) { + // int ii = 0; + } + + // if(!WriteFile(file,data,remain,&written,NULL)) + // ; //write error + // if(written!=pack) + // ; //write error + *data = ACK; + clientSocket.send(data, 256); + + Checksum checksum; + checksum.addFile(file.fileName); + uint32 crc = checksum.getSum(); + if (file.filecrc != crc) { + // int ii = 0; + } + + // if(calc_crc(file)!=info.crc) + // ; //transfeer error } + + outFile.close(); + } } + } } - -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/network/network_interface.h b/source/glest_game/network/network_interface.h index 939097179..3e7138823 100644 --- a/source/glest_game/network/network_interface.h +++ b/source/glest_game/network/network_interface.h @@ -13,28 +13,29 @@ #define _GLEST_GAME_NETWORKINTERFACE_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include -#include #include "checksum.h" +#include "data_types.h" +#include "game_settings.h" +#include "leak_dumper.h" #include "network_message.h" #include "network_types.h" -#include "game_settings.h" #include "thread.h" -#include "data_types.h" +#include #include -#include "leak_dumper.h" +#include +using Shared::Util::Checksum; using std::string; using std::vector; -using Shared::Util::Checksum; using namespace Shared::Util; using namespace Shared::Platform; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class NetworkInterface @@ -45,128 +46,125 @@ namespace Glest{ namespace Game{ // class ClientLagCallbackInterface { public: - virtual bool clientLagHandler(int slotIndex, bool networkPauseGameForLaggedClients) = 0; + virtual bool clientLagHandler(int slotIndex, + bool networkPauseGameForLaggedClients) = 0; - virtual ~ClientLagCallbackInterface() {} + virtual ~ClientLagCallbackInterface() {} }; - class ChatMsgInfo { protected: + void copyAll(const ChatMsgInfo &obj) { + this->chatText = obj.chatText.c_str(); + this->chatTeamIndex = obj.chatTeamIndex; + this->chatPlayerIndex = obj.chatPlayerIndex; + this->targetLanguage = obj.targetLanguage; + } - void copyAll(const ChatMsgInfo &obj) { - this->chatText = obj.chatText.c_str(); - this->chatTeamIndex = obj.chatTeamIndex; - this->chatPlayerIndex = obj.chatPlayerIndex; - this->targetLanguage = obj.targetLanguage; - } public: - - ChatMsgInfo() { - this->chatText = ""; - this->chatTeamIndex = -1; - this->chatPlayerIndex = -1; - this->targetLanguage = ""; - } - ChatMsgInfo(string chatText, int chatTeamIndex, int chatPlayerIndex, - string targetLanguage) { - this->chatText = chatText; - this->chatTeamIndex = chatTeamIndex; - this->chatPlayerIndex = chatPlayerIndex; - this->targetLanguage = targetLanguage; - } - ChatMsgInfo(const ChatMsgInfo& obj) { - copyAll(obj); - } - ChatMsgInfo & operator=(const ChatMsgInfo & obj) { - copyAll(obj); - return *this; - } - - string chatText; - int chatTeamIndex; - int chatPlayerIndex; - string targetLanguage; - + ChatMsgInfo() { + this->chatText = ""; + this->chatTeamIndex = -1; + this->chatPlayerIndex = -1; + this->targetLanguage = ""; + } + ChatMsgInfo(string chatText, int chatTeamIndex, int chatPlayerIndex, + string targetLanguage) { + this->chatText = chatText; + this->chatTeamIndex = chatTeamIndex; + this->chatPlayerIndex = chatPlayerIndex; + this->targetLanguage = targetLanguage; + } + ChatMsgInfo(const ChatMsgInfo &obj) { copyAll(obj); } + ChatMsgInfo &operator=(const ChatMsgInfo &obj) { + copyAll(obj); + return *this; + } + + string chatText; + int chatTeamIndex; + int chatPlayerIndex; + string targetLanguage; }; class MarkedCell { protected: - Vec2i targetPos; - const Faction *faction; - int factionIndex; - int playerIndex; - string note; - int aliveCount; + Vec2i targetPos; + const Faction *faction; + int factionIndex; + int playerIndex; + string note; + int aliveCount; public: - static Vec3f static_system_marker_color; - - MarkedCell() { - faction = NULL; - factionIndex = -1; - playerIndex = -1; - note = ""; - aliveCount=200; - } - MarkedCell(Vec2i targetPos,const Faction *faction,string note, int playerIndex) { - this->targetPos = targetPos; - this->faction = faction; - this->factionIndex = -1; - this->playerIndex = playerIndex; - this->note = note; - aliveCount=200; - } - MarkedCell(Vec2i targetPos,int factionIndex,string note, int playerIndex) { - this->targetPos = targetPos; - this->faction = NULL; - this->factionIndex = factionIndex; - this->playerIndex = playerIndex; - this->note = note; - aliveCount=200; - } - - Vec2i getTargetPos() const { return targetPos; } - const Faction * getFaction() const { return faction; } - void setFaction(const Faction *faction) { this->faction = faction; } - int getFactionIndex() const { return factionIndex; } - string getNote() const { return note; } - void decrementAliveCount() { this->aliveCount--; } - int getAliveCount() const { return aliveCount; } - void setAliveCount(int value) { this->aliveCount = value; } - int getPlayerIndex() const { return playerIndex; } - - void setNote(string value) { note = value; } - void setPlayerIndex(int value) { playerIndex = value; } + static Vec3f static_system_marker_color; + + MarkedCell() { + faction = NULL; + factionIndex = -1; + playerIndex = -1; + note = ""; + aliveCount = 200; + } + MarkedCell(Vec2i targetPos, const Faction *faction, string note, + int playerIndex) { + this->targetPos = targetPos; + this->faction = faction; + this->factionIndex = -1; + this->playerIndex = playerIndex; + this->note = note; + aliveCount = 200; + } + MarkedCell(Vec2i targetPos, int factionIndex, string note, int playerIndex) { + this->targetPos = targetPos; + this->faction = NULL; + this->factionIndex = factionIndex; + this->playerIndex = playerIndex; + this->note = note; + aliveCount = 200; + } + + Vec2i getTargetPos() const { return targetPos; } + const Faction *getFaction() const { return faction; } + void setFaction(const Faction *faction) { this->faction = faction; } + int getFactionIndex() const { return factionIndex; } + string getNote() const { return note; } + void decrementAliveCount() { this->aliveCount--; } + int getAliveCount() const { return aliveCount; } + void setAliveCount(int value) { this->aliveCount = value; } + int getPlayerIndex() const { return playerIndex; } + + void setNote(string value) { note = value; } + void setPlayerIndex(int value) { playerIndex = value; } }; class UnMarkedCell { protected: - Vec2i targetPos; - const Faction *faction; - int factionIndex; + Vec2i targetPos; + const Faction *faction; + int factionIndex; public: - UnMarkedCell() { - faction = NULL; - factionIndex = -1; - } - UnMarkedCell(Vec2i targetPos,const Faction *faction) { - this->targetPos = targetPos; - this->faction = faction; - this->factionIndex = -1; - } - UnMarkedCell(Vec2i targetPos,int factionIndex) { - this->targetPos = targetPos; - this->faction = NULL; - this->factionIndex = factionIndex; - } - - Vec2i getTargetPos() const { return targetPos; } - const Faction * getFaction() const { return faction; } - void setFaction(const Faction *faction) { this->faction = faction; } - int getFactionIndex() const { return factionIndex; } + UnMarkedCell() { + faction = NULL; + factionIndex = -1; + } + UnMarkedCell(Vec2i targetPos, const Faction *faction) { + this->targetPos = targetPos; + this->faction = faction; + this->factionIndex = -1; + } + UnMarkedCell(Vec2i targetPos, int factionIndex) { + this->targetPos = targetPos; + this->faction = NULL; + this->factionIndex = factionIndex; + } + + Vec2i getTargetPos() const { return targetPos; } + const Faction *getFaction() const { return faction; } + void setFaction(const Faction *faction) { this->faction = faction; } + int getFactionIndex() const { return factionIndex; } }; typedef int (*DisplayMessageFunction)(const char *msg, bool exit); @@ -174,125 +172,154 @@ typedef int (*DisplayMessageFunction)(const char *msg, bool exit); class NetworkInterface { protected: - static bool allowGameDataSynchCheck; - static bool allowDownloadDataSynch; - bool networkGameDataSynchCheckOkMap; - bool networkGameDataSynchCheckOkTile; - bool networkGameDataSynchCheckOkTech; - string networkGameDataSynchCheckTechMismatchReport; - bool receivedDataSynchCheck; + static bool allowGameDataSynchCheck; + static bool allowDownloadDataSynch; + bool networkGameDataSynchCheckOkMap; + bool networkGameDataSynchCheckOkTile; + bool networkGameDataSynchCheckOkTech; + string networkGameDataSynchCheckTechMismatchReport; + bool receivedDataSynchCheck; - NetworkMessagePing lastPingInfo; + NetworkMessagePing lastPingInfo; - std::vector chatTextList; - std::vector markedCellList; - std::vector unmarkedCellList; + std::vector chatTextList; + std::vector markedCellList; + std::vector unmarkedCellList; - static DisplayMessageFunction pCB_DisplayMessage; - void DisplayErrorMessage(string sErr, bool closeSocket=true); + static DisplayMessageFunction pCB_DisplayMessage; + void DisplayErrorMessage(string sErr, bool closeSocket = true); - virtual Mutex * getServerSynchAccessor() = 0; + virtual Mutex *getServerSynchAccessor() = 0; - std::vector highlightedCellList; + std::vector highlightedCellList; - Mutex *networkAccessMutex; + Mutex *networkAccessMutex; - void init(); + void init(); - Mutex *networkPlayerFactionCRCMutex; - uint32 networkPlayerFactionCRC[GameConstants::maxPlayers]; + Mutex *networkPlayerFactionCRCMutex; + uint32 networkPlayerFactionCRC[GameConstants::maxPlayers]; public: - static const int readyWaitTimeout; - GameSettings gameSettings; + static const int readyWaitTimeout; + GameSettings gameSettings; public: - NetworkInterface(); - virtual ~NetworkInterface(); - - NetworkInterface(const NetworkInterface& obj) { - init(); - throw megaglest_runtime_error("class NetworkInterface is NOT safe to copy!"); - } - NetworkInterface & operator=(const NetworkInterface& obj) { - init(); - throw megaglest_runtime_error("class NetworkInterface is NOT safe to assign!"); - } - - uint32 getNetworkPlayerFactionCRC(int index); - void setNetworkPlayerFactionCRC(int index, uint32 crc); - - virtual Socket* getSocket(bool mutexLock=true)= 0; - - virtual void close()= 0; - virtual string getHumanPlayerName(int index=-1) = 0; - virtual int getHumanPlayerIndex() const = 0; - - static void setDisplayMessageFunction(DisplayMessageFunction pDisplayMessage) { pCB_DisplayMessage = pDisplayMessage; } - static DisplayMessageFunction getDisplayMessageFunction() { return pCB_DisplayMessage; } - - virtual std::string getIpAddress(bool mutexLock=true) = 0; - string getIp() const {return Socket::getIp();} - string getHostName() const {return Socket::getHostName();} - - virtual void sendMessage(NetworkMessage* networkMessage); - NetworkMessageType getNextMessageType(int waitMilliseconds=0); - bool receiveMessage(NetworkMessage* networkMessage); - bool receiveMessage(NetworkMessage* networkMessage, NetworkMessageType type); - - virtual bool isConnected(); - - const virtual GameSettings * getGameSettings() { return &gameSettings; } - GameSettings * getGameSettingsPtr() { return &gameSettings; } - - static void setAllowDownloadDataSynch(bool value) { allowDownloadDataSynch = value; } - static bool getAllowDownloadDataSynch() { return allowDownloadDataSynch; } - - static void setAllowGameDataSynchCheck(bool value) { allowGameDataSynchCheck = value; } - static bool getAllowGameDataSynchCheck() { return allowGameDataSynchCheck; } - - virtual bool getNetworkGameDataSynchCheckOk() { return (networkGameDataSynchCheckOkMap && networkGameDataSynchCheckOkTile && networkGameDataSynchCheckOkTech); } - virtual void setNetworkGameDataSynchCheckOkMap(bool value) { networkGameDataSynchCheckOkMap = value; } - virtual void setNetworkGameDataSynchCheckOkTile(bool value) { networkGameDataSynchCheckOkTile = value; } - virtual void setNetworkGameDataSynchCheckOkTech(bool value) { networkGameDataSynchCheckOkTech = value; } - virtual bool getNetworkGameDataSynchCheckOkMap() { return networkGameDataSynchCheckOkMap; } - virtual bool getNetworkGameDataSynchCheckOkTile() { return networkGameDataSynchCheckOkTile; } - virtual bool getNetworkGameDataSynchCheckOkTech() { return networkGameDataSynchCheckOkTech; } - - std::vector getChatTextList(bool clearList); - void clearChatInfo(); - void addChatInfo(const ChatMsgInfo &msg); - - std::vector getMarkedCellList(bool clearList); - void clearMarkedCellList(); - void addMarkedCell(const MarkedCell &msg); - - std::vector getUnMarkedCellList(bool clearList); - void clearUnMarkedCellList(); - void addUnMarkedCell(const UnMarkedCell &msg); - - std::vector getHighlightedCellList(bool clearList); - void clearHighlightedCellList(); - void setHighlightedCell(const MarkedCell &msg); - - virtual bool getConnectHasHandshaked() const= 0; - - void setLastPingInfo(const NetworkMessagePing &ping); - void setLastPingInfoToNow(); - NetworkMessagePing getLastPingInfo(); - double getLastPingLag(); - - float getThreadedPingMS(std::string host); - - string getNetworkGameDataSynchCheckTechMismatchReport() const {return networkGameDataSynchCheckTechMismatchReport;} - void setNetworkGameDataSynchCheckTechMismatchReport(string value) {networkGameDataSynchCheckTechMismatchReport = value;} - - bool getReceivedDataSynchCheck() const {return receivedDataSynchCheck;} - void setReceivedDataSynchCheck(bool value) { receivedDataSynchCheck = value; } - - virtual void saveGame(XmlNode *rootNode) = 0; - //static void loadGame(string name); - + NetworkInterface(); + virtual ~NetworkInterface(); + + NetworkInterface(const NetworkInterface &obj) { + init(); + throw megaglest_runtime_error( + "class NetworkInterface is NOT safe to copy!"); + } + NetworkInterface &operator=(const NetworkInterface &obj) { + init(); + throw megaglest_runtime_error( + "class NetworkInterface is NOT safe to assign!"); + } + + uint32 getNetworkPlayerFactionCRC(int index); + void setNetworkPlayerFactionCRC(int index, uint32 crc); + + virtual Socket *getSocket(bool mutexLock = true) = 0; + + virtual void close() = 0; + virtual string getHumanPlayerName(int index = -1) = 0; + virtual int getHumanPlayerIndex() const = 0; + + static void + setDisplayMessageFunction(DisplayMessageFunction pDisplayMessage) { + pCB_DisplayMessage = pDisplayMessage; + } + static DisplayMessageFunction getDisplayMessageFunction() { + return pCB_DisplayMessage; + } + + virtual std::string getIpAddress(bool mutexLock = true) = 0; + string getIp() const { return Socket::getIp(); } + string getHostName() const { return Socket::getHostName(); } + + virtual void sendMessage(NetworkMessage *networkMessage); + NetworkMessageType getNextMessageType(int waitMilliseconds = 0); + bool receiveMessage(NetworkMessage *networkMessage); + bool receiveMessage(NetworkMessage *networkMessage, NetworkMessageType type); + + virtual bool isConnected(); + + const virtual GameSettings *getGameSettings() { return &gameSettings; } + GameSettings *getGameSettingsPtr() { return &gameSettings; } + + static void setAllowDownloadDataSynch(bool value) { + allowDownloadDataSynch = value; + } + static bool getAllowDownloadDataSynch() { return allowDownloadDataSynch; } + + static void setAllowGameDataSynchCheck(bool value) { + allowGameDataSynchCheck = value; + } + static bool getAllowGameDataSynchCheck() { return allowGameDataSynchCheck; } + + virtual bool getNetworkGameDataSynchCheckOk() { + return (networkGameDataSynchCheckOkMap && networkGameDataSynchCheckOkTile && + networkGameDataSynchCheckOkTech); + } + virtual void setNetworkGameDataSynchCheckOkMap(bool value) { + networkGameDataSynchCheckOkMap = value; + } + virtual void setNetworkGameDataSynchCheckOkTile(bool value) { + networkGameDataSynchCheckOkTile = value; + } + virtual void setNetworkGameDataSynchCheckOkTech(bool value) { + networkGameDataSynchCheckOkTech = value; + } + virtual bool getNetworkGameDataSynchCheckOkMap() { + return networkGameDataSynchCheckOkMap; + } + virtual bool getNetworkGameDataSynchCheckOkTile() { + return networkGameDataSynchCheckOkTile; + } + virtual bool getNetworkGameDataSynchCheckOkTech() { + return networkGameDataSynchCheckOkTech; + } + + std::vector getChatTextList(bool clearList); + void clearChatInfo(); + void addChatInfo(const ChatMsgInfo &msg); + + std::vector getMarkedCellList(bool clearList); + void clearMarkedCellList(); + void addMarkedCell(const MarkedCell &msg); + + std::vector getUnMarkedCellList(bool clearList); + void clearUnMarkedCellList(); + void addUnMarkedCell(const UnMarkedCell &msg); + + std::vector getHighlightedCellList(bool clearList); + void clearHighlightedCellList(); + void setHighlightedCell(const MarkedCell &msg); + + virtual bool getConnectHasHandshaked() const = 0; + + void setLastPingInfo(const NetworkMessagePing &ping); + void setLastPingInfoToNow(); + NetworkMessagePing getLastPingInfo(); + double getLastPingLag(); + + float getThreadedPingMS(std::string host); + + string getNetworkGameDataSynchCheckTechMismatchReport() const { + return networkGameDataSynchCheckTechMismatchReport; + } + void setNetworkGameDataSynchCheckTechMismatchReport(string value) { + networkGameDataSynchCheckTechMismatchReport = value; + } + + bool getReceivedDataSynchCheck() const { return receivedDataSynchCheck; } + void setReceivedDataSynchCheck(bool value) { receivedDataSynchCheck = value; } + + virtual void saveGame(XmlNode *rootNode) = 0; + // static void loadGame(string name); }; // ===================================================== @@ -302,121 +329,104 @@ class NetworkInterface { // but not connection slots // ===================================================== -class GameNetworkInterface: public NetworkInterface { +class GameNetworkInterface : public NetworkInterface { protected: - typedef vector Commands; + typedef vector Commands; - Commands requestedCommands; //commands requested by the user - Commands pendingCommands; //commands ready to be given - bool quit; + Commands requestedCommands; // commands requested by the user + Commands pendingCommands; // commands ready to be given + bool quit; public: - GameNetworkInterface(); - virtual ~GameNetworkInterface(){} - - //message processimg - virtual void update()= 0; - virtual void updateLobby()= 0; - virtual void updateKeyframe(int frameCount)= 0; - virtual void setKeyframe(int frameCount)= 0; - virtual void waitUntilReady(Checksum* checksum)= 0; - - //message sending - virtual void sendTextMessage(const string &text, int teamIndex,bool echoLocal, - string targetLanguage)= 0; - virtual void quitGame(bool userManuallyQuit)=0; - - virtual void sendMarkCellMessage(Vec2i targetPos, int factionIndex, string note,int playerIndex) = 0; - virtual void sendUnMarkCellMessage(Vec2i targetPos, int factionIndex) = 0; - virtual void sendHighlightCellMessage(Vec2i targetPos, int factionIndex) = 0; - - - //misc - virtual string getNetworkStatus() = 0; - - //access functions - void requestCommand(const NetworkCommand *networkCommand, bool insertAtStart=false); - int getPendingCommandCount() const {return (int)pendingCommands.size();} - NetworkCommand* getPendingCommand(int i) {return &pendingCommands[i];} - void clearPendingCommands() {pendingCommands.clear();} - bool getQuit() const {return quit;} + GameNetworkInterface(); + virtual ~GameNetworkInterface() {} + + // message processimg + virtual void update() = 0; + virtual void updateLobby() = 0; + virtual void updateKeyframe(int frameCount) = 0; + virtual void setKeyframe(int frameCount) = 0; + virtual void waitUntilReady(Checksum *checksum) = 0; + + // message sending + virtual void sendTextMessage(const string &text, int teamIndex, + bool echoLocal, string targetLanguage) = 0; + virtual void quitGame(bool userManuallyQuit) = 0; + + virtual void sendMarkCellMessage(Vec2i targetPos, int factionIndex, + string note, int playerIndex) = 0; + virtual void sendUnMarkCellMessage(Vec2i targetPos, int factionIndex) = 0; + virtual void sendHighlightCellMessage(Vec2i targetPos, int factionIndex) = 0; + + // misc + virtual string getNetworkStatus() = 0; + + // access functions + void requestCommand(const NetworkCommand *networkCommand, + bool insertAtStart = false); + int getPendingCommandCount() const { return (int)pendingCommands.size(); } + NetworkCommand *getPendingCommand(int i) { return &pendingCommands[i]; } + void clearPendingCommands() { pendingCommands.clear(); } + bool getQuit() const { return quit; } }; // ===================================================== // class FileTransferSocketThread // ===================================================== -enum FileTransferHostType -{ - eClient, - eServer -}; +enum FileTransferHostType { eClient, eServer }; -enum FileTransferOperationType -{ - eSend, - eReceive -}; +enum FileTransferOperationType { eSend, eReceive }; -class FileTransferInfo -{ +class FileTransferInfo { private: - - void CopyAll(const FileTransferInfo &obj) - { - hostType = obj.hostType; - serverIP = obj.serverIP; - serverPort = obj.serverPort; - opType = obj.opType; - fileName = obj.fileName; - } + void CopyAll(const FileTransferInfo &obj) { + hostType = obj.hostType; + serverIP = obj.serverIP; + serverPort = obj.serverPort; + opType = obj.opType; + fileName = obj.fileName; + } public: - FileTransferInfo() - { - hostType = eClient; - serverIP = ""; - serverPort = 0; - opType = eSend; - fileName = ""; - } - FileTransferInfo(const FileTransferInfo &obj) - { - CopyAll(obj); - } - FileTransferInfo &operator=(const FileTransferInfo &obj) - { - CopyAll(obj); - return *this; - } - - FileTransferHostType hostType; - string serverIP; - int32 serverPort; - FileTransferOperationType opType; - string fileName; + FileTransferInfo() { + hostType = eClient; + serverIP = ""; + serverPort = 0; + opType = eSend; + fileName = ""; + } + FileTransferInfo(const FileTransferInfo &obj) { CopyAll(obj); } + FileTransferInfo &operator=(const FileTransferInfo &obj) { + CopyAll(obj); + return *this; + } + + FileTransferHostType hostType; + string serverIP; + int32 serverPort; + FileTransferOperationType opType; + string fileName; }; -class FileInfo -{ +class FileInfo { public: - string fileName; - int64 filesize; - uint32 filecrc; + string fileName; + int64 filesize; + uint32 filecrc; }; -class FileTransferSocketThread : public Thread -{ +class FileTransferSocketThread : public Thread { private: - FileTransferInfo info; + FileTransferInfo info; public: - explicit FileTransferSocketThread(FileTransferInfo fileInfo); - virtual void execute(); + explicit FileTransferSocketThread(FileTransferInfo fileInfo); + virtual void execute(); }; - -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/network/network_manager.cpp b/source/glest_game/network/network_manager.cpp index 4b24ce11c..34a5a5921 100644 --- a/source/glest_game/network/network_manager.cpp +++ b/source/glest_game/network/network_manager.cpp @@ -10,131 +10,182 @@ // ============================================================== #include "network_manager.h" -#include "util.h" #include "leak_dumper.h" +#include "util.h" using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class NetworkManager // ===================================================== -NetworkManager &NetworkManager::getInstance(){ - static NetworkManager networkManager; - return networkManager; +NetworkManager &NetworkManager::getInstance() { + static NetworkManager networkManager; + return networkManager; } NetworkManager::NetworkManager() { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - gameNetworkInterface= NULL; - networkRole= nrIdle; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] this->networkRole = %d gameNetworkInterface [%p]\n",__FILE__,__FUNCTION__,__LINE__,this->networkRole,gameNetworkInterface); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + + gameNetworkInterface = NULL; + networkRole = nrIdle; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] this->networkRole = %d " + "gameNetworkInterface [%p]\n", + __FILE__, __FUNCTION__, __LINE__, + this->networkRole, gameNetworkInterface); } -NetworkManager::~NetworkManager() { - end(); -} +NetworkManager::~NetworkManager() { end(); } void NetworkManager::init(NetworkRole networkRole, bool publishEnabled) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] this->networkRole = %d, networkRole = %d, gameNetworkInterface [%p]\n",__FILE__,__FUNCTION__,__LINE__,this->networkRole,networkRole,gameNetworkInterface); - - //assert(gameNetworkInterface==NULL); - NetworkMessage::resetNetworkPacketStats(); - this->networkRole = networkRole; - - if(networkRole == nrServer) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] this->networkRole = %d, networkRole = %d, gameNetworkInterface [%p]\n",__FILE__,__FUNCTION__,__LINE__,this->networkRole,networkRole,gameNetworkInterface); - gameNetworkInterface = new ServerInterface(publishEnabled,NULL); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] this->networkRole = %d, networkRole = %d, gameNetworkInterface [%p]\n",__FILE__,__FUNCTION__,__LINE__,this->networkRole,networkRole,gameNetworkInterface); - gameNetworkInterface = new ClientInterface(); - } - - //printf("==========] CREATING gameNetworkInterface [%p]\n",gameNetworkInterface); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] this->networkRole = %d gameNetworkInterface [%p]\n",__FILE__,__FUNCTION__,__LINE__,this->networkRole,gameNetworkInterface); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] this->networkRole = %d, " + "networkRole = %d, gameNetworkInterface [%p]\n", + __FILE__, __FUNCTION__, __LINE__, + this->networkRole, networkRole, + gameNetworkInterface); + + // assert(gameNetworkInterface==NULL); + NetworkMessage::resetNetworkPacketStats(); + this->networkRole = networkRole; + + if (networkRole == nrServer) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] this->networkRole = %d, " + "networkRole = %d, gameNetworkInterface [%p]\n", + __FILE__, __FUNCTION__, __LINE__, + this->networkRole, networkRole, + gameNetworkInterface); + gameNetworkInterface = new ServerInterface(publishEnabled, NULL); + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] this->networkRole = %d, " + "networkRole = %d, gameNetworkInterface [%p]\n", + __FILE__, __FUNCTION__, __LINE__, + this->networkRole, networkRole, + gameNetworkInterface); + gameNetworkInterface = new ClientInterface(); + } + + // printf("==========] CREATING gameNetworkInterface + // [%p]\n",gameNetworkInterface); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] this->networkRole = %d " + "gameNetworkInterface [%p]\n", + __FILE__, __FUNCTION__, __LINE__, + this->networkRole, gameNetworkInterface); } void NetworkManager::initServerInterfaces(ClientLagCallbackInterface *intf) { - ServerInterface *server = getServerInterface(); - server->setClientLagCallbackInterface(intf); + ServerInterface *server = getServerInterface(); + server->setClientLagCallbackInterface(intf); } void NetworkManager::end() { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] this->networkRole = %d gameNetworkInterface [%p]\n",__FILE__,__FUNCTION__,__LINE__,this->networkRole,gameNetworkInterface); - //printf("In [%s::%s] Line: %d gameNetworkInterface = %p\n",__FILE__,__FUNCTION__,__LINE__,gameNetworkInterface); - //printf("==========] DELETING gameNetworkInterface [%p]\n",gameNetworkInterface); - - delete gameNetworkInterface; - gameNetworkInterface= NULL; - networkRole= nrIdle; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] this->networkRole = %d gameNetworkInterface [%p]\n",__FILE__,__FUNCTION__,__LINE__,this->networkRole,gameNetworkInterface); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] this->networkRole = %d " + "gameNetworkInterface [%p]\n", + __FILE__, __FUNCTION__, __LINE__, + this->networkRole, gameNetworkInterface); + // printf("In [%s::%s] Line: %d gameNetworkInterface = + // %p\n",__FILE__,__FUNCTION__,__LINE__,gameNetworkInterface); + // printf("==========] DELETING gameNetworkInterface + // [%p]\n",gameNetworkInterface); + + delete gameNetworkInterface; + gameNetworkInterface = NULL; + networkRole = nrIdle; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, __LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] this->networkRole = %d " + "gameNetworkInterface [%p]\n", + __FILE__, __FUNCTION__, __LINE__, + this->networkRole, gameNetworkInterface); } void NetworkManager::update() { - if(gameNetworkInterface!=NULL) { - gameNetworkInterface->update(); - } + if (gameNetworkInterface != NULL) { + gameNetworkInterface->update(); + } } bool NetworkManager::isNetworkGame() { - return networkRole==nrClient || (networkRole==nrServer && getServerInterface()->getSlotCount() > 0); + return networkRole == nrClient || + (networkRole == nrServer && getServerInterface()->getSlotCount() > 0); } bool NetworkManager::isNetworkGameWithConnectedClients() { - return networkRole==nrClient || (networkRole==nrServer && getServerInterface()->getConnectedSlotCount(true) > 0); + return networkRole == nrClient || + (networkRole == nrServer && + getServerInterface()->getConnectedSlotCount(true) > 0); } -GameNetworkInterface* NetworkManager::getGameNetworkInterface(bool throwErrorOnNull) { - if(throwErrorOnNull) { - //assert(gameNetworkInterface!=NULL); +GameNetworkInterface * +NetworkManager::getGameNetworkInterface(bool throwErrorOnNull) { + if (throwErrorOnNull) { + // assert(gameNetworkInterface!=NULL); - if(gameNetworkInterface==NULL) { - throw megaglest_runtime_error("gameNetworkInterface==NULL"); - } + if (gameNetworkInterface == NULL) { + throw megaglest_runtime_error("gameNetworkInterface==NULL"); } - return gameNetworkInterface; + } + return gameNetworkInterface; } -ServerInterface* NetworkManager::getServerInterface(bool throwErrorOnNull) { - if(throwErrorOnNull) { - //assert(gameNetworkInterface!=NULL); - if(gameNetworkInterface==NULL) { - throw megaglest_runtime_error("gameNetworkInterface==NULL"); - } - - assert(networkRole==nrServer); - if(networkRole!=nrServer) { - throw megaglest_runtime_error("networkRole!=nrServer"); - } +ServerInterface *NetworkManager::getServerInterface(bool throwErrorOnNull) { + if (throwErrorOnNull) { + // assert(gameNetworkInterface!=NULL); + if (gameNetworkInterface == NULL) { + throw megaglest_runtime_error("gameNetworkInterface==NULL"); } - return dynamic_cast(gameNetworkInterface); + + assert(networkRole == nrServer); + if (networkRole != nrServer) { + throw megaglest_runtime_error("networkRole!=nrServer"); + } + } + return dynamic_cast(gameNetworkInterface); } -ClientInterface* NetworkManager::getClientInterface(bool throwErrorOnNull) { - //if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] this->networkRole = %d gameNetworkInterface [%p]\n",__FILE__,__FUNCTION__,__LINE__,this->networkRole,gameNetworkInterface); +ClientInterface *NetworkManager::getClientInterface(bool throwErrorOnNull) { + // if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] + // this->networkRole = %d gameNetworkInterface + // [%p]\n",__FILE__,__FUNCTION__,__LINE__,this->networkRole,gameNetworkInterface); - if(throwErrorOnNull) { - //assert(gameNetworkInterface!=NULL); - if(gameNetworkInterface==NULL) { - throw megaglest_runtime_error("gameNetworkInterface==NULL"); - } + if (throwErrorOnNull) { + // assert(gameNetworkInterface!=NULL); + if (gameNetworkInterface == NULL) { + throw megaglest_runtime_error("gameNetworkInterface==NULL"); + } - assert(networkRole==nrClient); - if(networkRole!=nrClient) { - throw megaglest_runtime_error("networkRole!=nrClient"); - } + assert(networkRole == nrClient); + if (networkRole != nrClient) { + throw megaglest_runtime_error("networkRole!=nrClient"); } - return dynamic_cast(gameNetworkInterface); + } + return dynamic_cast(gameNetworkInterface); } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/network/network_manager.h b/source/glest_game/network/network_manager.h index 028c8e1de..64f4fa8e4 100644 --- a/source/glest_game/network/network_manager.h +++ b/source/glest_game/network/network_manager.h @@ -12,16 +12,17 @@ #ifndef _GLEST_GAME_NETWORKMANAGER_H_ #define _GLEST_GAME_NETWORKMANAGER_H_ -#include -#include "socket.h" #include "checksum.h" -#include "server_interface.h" #include "client_interface.h" #include "leak_dumper.h" +#include "server_interface.h" +#include "socket.h" +#include using Shared::Util::Checksum; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class NetworkManager @@ -29,30 +30,31 @@ namespace Glest{ namespace Game{ class NetworkManager { private: - GameNetworkInterface* gameNetworkInterface; - NetworkRole networkRole; + GameNetworkInterface *gameNetworkInterface; + NetworkRole networkRole; public: - static NetworkManager &getInstance(); + static NetworkManager &getInstance(); - NetworkManager(); - virtual ~NetworkManager(); + NetworkManager(); + virtual ~NetworkManager(); - void init(NetworkRole networkRole,bool publishEnabled=false); - void end(); - void update(); + void init(NetworkRole networkRole, bool publishEnabled = false); + void end(); + void update(); - bool isNetworkGame(); - bool isNetworkGameWithConnectedClients(); + bool isNetworkGame(); + bool isNetworkGameWithConnectedClients(); - GameNetworkInterface* getGameNetworkInterface(bool throwErrorOnNull=true); - ServerInterface* getServerInterface(bool throwErrorOnNull=true); - ClientInterface* getClientInterface(bool throwErrorOnNull=true); - NetworkRole getNetworkRole() const { return networkRole; } + GameNetworkInterface *getGameNetworkInterface(bool throwErrorOnNull = true); + ServerInterface *getServerInterface(bool throwErrorOnNull = true); + ClientInterface *getClientInterface(bool throwErrorOnNull = true); + NetworkRole getNetworkRole() const { return networkRole; } - void initServerInterfaces(ClientLagCallbackInterface *intf); + void initServerInterfaces(ClientLagCallbackInterface *intf); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/network/network_message.cpp b/source/glest_game/network/network_message.cpp index 8a73ad2da..256b019a3 100644 --- a/source/glest_game/network/network_message.cpp +++ b/source/glest_game/network/network_message.cpp @@ -11,18 +11,18 @@ #include "network_message.h" -#include "data_types.h" -#include "util.h" -#include "game_settings.h" #include "checksum.h" -#include "platform_util.h" +#include "common_scoped_ptr.h" +#include "compression_utils.h" #include "config.h" +#include "data_types.h" +#include "game_settings.h" #include "network_protocol.h" -#include "compression_utils.h" +#include "platform_util.h" +#include "util.h" #include #include #include -#include "common_scoped_ptr.h" #include "leak_dumper.h" @@ -31,7 +31,8 @@ using namespace Shared::Util; using namespace std; using std::min; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { bool NetworkMessage::useOldProtocol = true; @@ -39,578 +40,670 @@ auto_ptr NetworkMessage::mutexMessageStats(new Mutex(CODE_AT_LINE)); Chrono NetworkMessage::statsTimer; Chrono NetworkMessage::lastSend; Chrono NetworkMessage::lastRecv; -std::map NetworkMessage::mapMessageStats; +std::map NetworkMessage::mapMessageStats; // ===================================================== // class NetworkMessage // ===================================================== -bool NetworkMessage::receive(Socket* socket, void* data, int dataSize, bool tryReceiveUntilDataSizeMet) { - if(socket != NULL) { - int dataReceived = socket->receive(data, dataSize, tryReceiveUntilDataSizeMet); - if(dataReceived != dataSize) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] WARNING, dataReceived = %d dataSize = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,dataReceived,dataSize); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\nIn [%s::%s Line: %d] WARNING, dataReceived = %d dataSize = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,dataReceived,dataSize); - - if(socket != NULL && socket->isSocketValid() == true) { - throw megaglest_runtime_error("Error receiving NetworkMessage, dataReceived = " + intToStr(dataReceived) + ", dataSize = " + intToStr(dataSize)); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] socket has been disconnected\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] dataSize = %d, dataReceived = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,dataSize,dataReceived); - - dump_packet("\nINCOMING PACKET:\n",data, dataSize, false); - return true; - } - } - return false; - -} - -void NetworkMessage::send(Socket* socket, const void* data, int dataSize) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] socket = %p, data = %p, dataSize = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,socket,data,dataSize); - - if(socket != NULL) { - dump_packet("\nOUTGOING PACKET:\n",data, dataSize, true); - int sendResult = socket->send(data, dataSize); - if(sendResult != dataSize) { - if(socket != NULL && socket->isSocketValid() == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Error sending NetworkMessage, sendResult = %d, dataSize = %d",sendResult,dataSize); - throw megaglest_runtime_error(szBuf); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d socket has been disconnected\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - } - } -} - -void NetworkMessage::send(Socket* socket, const void* data, int dataSize, int8 messageType) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] socket = %p, data = %p, dataSize = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,socket,data,dataSize); - - if(socket != NULL) { - int msgTypeSize = sizeof(messageType); - int fullMsgSize = msgTypeSize + dataSize; - - char *out_buffer = new char[fullMsgSize]; - memcpy(out_buffer,&messageType,msgTypeSize); - memcpy(&out_buffer[msgTypeSize],(const char *)data,dataSize); - - dump_packet("\nOUTGOING PACKET:\n",out_buffer, fullMsgSize, true); - int sendResult = socket->send(out_buffer, fullMsgSize); - if(sendResult != fullMsgSize) { - delete [] out_buffer; - if(socket != NULL && socket->isSocketValid() == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Error sending NetworkMessage, sendResult = %d, dataSize = %d",sendResult,fullMsgSize); - throw megaglest_runtime_error(szBuf); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d socket has been disconnected\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - } - else { - delete [] out_buffer; - } - } -} - -void NetworkMessage::send(Socket* socket, const void* data, int dataSize, int8 messageType, uint32 compressedLength) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] socket = %p, data = %p, dataSize = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,socket,data,dataSize); - - if(socket != NULL) { - int msgTypeSize = sizeof(messageType); - int compressedSize = sizeof(compressedLength); - int fullMsgSize = msgTypeSize + compressedSize + dataSize; - - char *out_buffer = new char[fullMsgSize]; - memcpy(out_buffer,&messageType,msgTypeSize); - memcpy(&out_buffer[msgTypeSize],&compressedLength,compressedSize); - memcpy(&out_buffer[msgTypeSize+compressedSize],(const char *)data,dataSize); - - dump_packet("\nOUTGOING PACKET:\n",out_buffer, fullMsgSize, true); - int sendResult = socket->send(out_buffer, fullMsgSize); - if(sendResult != fullMsgSize) { - delete [] out_buffer; - if(socket != NULL && socket->isSocketValid() == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Error sending NetworkMessage, sendResult = %d, dataSize = %d",sendResult,fullMsgSize); - throw megaglest_runtime_error(szBuf); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d socket has been disconnected\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - } - else { - delete [] out_buffer; - } - } +bool NetworkMessage::receive(Socket *socket, void *data, int dataSize, + bool tryReceiveUntilDataSizeMet) { + if (socket != NULL) { + int dataReceived = + socket->receive(data, dataSize, tryReceiveUntilDataSizeMet); + if (dataReceived != dataSize) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] WARNING, dataReceived = %d dataSize = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, dataReceived, dataSize); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf( + "\nIn [%s::%s Line: %d] WARNING, dataReceived = %d dataSize = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, dataReceived, dataSize); + + if (socket != NULL && socket->isSocketValid() == true) { + throw megaglest_runtime_error( + "Error receiving NetworkMessage, dataReceived = " + + intToStr(dataReceived) + ", dataSize = " + intToStr(dataSize)); + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] socket has been disconnected\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] dataSize = %d, dataReceived = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, dataSize, dataReceived); + + dump_packet("\nINCOMING PACKET:\n", data, dataSize, false); + return true; + } + } + return false; +} + +void NetworkMessage::send(Socket *socket, const void *data, int dataSize) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] socket = %p, data = %p, dataSize = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + socket, data, dataSize); + + if (socket != NULL) { + dump_packet("\nOUTGOING PACKET:\n", data, dataSize, true); + int sendResult = socket->send(data, dataSize); + if (sendResult != dataSize) { + if (socket != NULL && socket->isSocketValid() == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "Error sending NetworkMessage, sendResult = %d, dataSize = %d", + sendResult, dataSize); + throw megaglest_runtime_error(szBuf); + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s] Line: %d socket has been disconnected\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } + } + } +} + +void NetworkMessage::send(Socket *socket, const void *data, int dataSize, + int8 messageType) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] socket = %p, data = %p, dataSize = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + socket, data, dataSize); + + if (socket != NULL) { + int msgTypeSize = sizeof(messageType); + int fullMsgSize = msgTypeSize + dataSize; + + char *out_buffer = new char[fullMsgSize]; + memcpy(out_buffer, &messageType, msgTypeSize); + memcpy(&out_buffer[msgTypeSize], (const char *)data, dataSize); + + dump_packet("\nOUTGOING PACKET:\n", out_buffer, fullMsgSize, true); + int sendResult = socket->send(out_buffer, fullMsgSize); + if (sendResult != fullMsgSize) { + delete[] out_buffer; + if (socket != NULL && socket->isSocketValid() == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "Error sending NetworkMessage, sendResult = %d, dataSize = %d", + sendResult, fullMsgSize); + throw megaglest_runtime_error(szBuf); + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s] Line: %d socket has been disconnected\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } + } else { + delete[] out_buffer; + } + } +} + +void NetworkMessage::send(Socket *socket, const void *data, int dataSize, + int8 messageType, uint32 compressedLength) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] socket = %p, data = %p, dataSize = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + socket, data, dataSize); + + if (socket != NULL) { + int msgTypeSize = sizeof(messageType); + int compressedSize = sizeof(compressedLength); + int fullMsgSize = msgTypeSize + compressedSize + dataSize; + + char *out_buffer = new char[fullMsgSize]; + memcpy(out_buffer, &messageType, msgTypeSize); + memcpy(&out_buffer[msgTypeSize], &compressedLength, compressedSize); + memcpy(&out_buffer[msgTypeSize + compressedSize], (const char *)data, + dataSize); + + dump_packet("\nOUTGOING PACKET:\n", out_buffer, fullMsgSize, true); + int sendResult = socket->send(out_buffer, fullMsgSize); + if (sendResult != fullMsgSize) { + delete[] out_buffer; + if (socket != NULL && socket->isSocketValid() == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "Error sending NetworkMessage, sendResult = %d, dataSize = %d", + sendResult, fullMsgSize); + throw megaglest_runtime_error(szBuf); + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s] Line: %d socket has been disconnected\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } + } else { + delete[] out_buffer; + } + } } void NetworkMessage::resetNetworkPacketStats() { - NetworkMessage::statsTimer.stop(); - NetworkMessage::lastSend.stop(); - NetworkMessage::lastRecv.stop(); - NetworkMessage::mapMessageStats.clear(); -} - -string NetworkMessage::getNetworkPacketStats() { - string result = "Current Timer Milliseconds: " + intToStr(NetworkMessage::statsTimer.getMillis()) + "\n"; - - for(std::map::iterator iterMap = mapMessageStats.begin(); - iterMap != mapMessageStats.end(); ++iterMap) { - switch(iterMap->first) { - case netmsgstPacketsPerMillisecondSend: - result += "send p / msec: " + intToStr(iterMap->second) + (iterMap->second > 10 ? " ****WARNING WIN32 LIMIT EXCEEDED****" : "") + "\n"; - break; - case netmsgstPacketsPerSecondSend: - result += "send p / sec: " + intToStr(iterMap->second) + "\n"; - break; - case netmsgstAverageSendSize: - result += "send avg size: " + intToStr(iterMap->second) + "\n"; - break; - - case netmsgstPacketsPerMillisecondRecv: - result += "recv p / msec: " + intToStr(iterMap->second) + "\n"; - break; - case netmsgstPacketsPerSecondRecv: - result += "recv p / sec: " + intToStr(iterMap->second) + (iterMap->second > 10 ? " ****WARNING WIN32 LIMIT EXCEEDED****" : "") + "\n"; - break; - case netmsgstAverageRecvSize: - result += "recv avg size: " + intToStr(iterMap->second) + "\n"; - break; - - } - } - return result; -} - -void NetworkMessage::dump_packet(string label, const void* data, int dataSize, bool isSend) { - Config &config = Config::getInstance(); - if( config.getBool("DebugNetworkPacketStats","false") == true) { - - MutexSafeWrapper safeMutex(NetworkMessage::mutexMessageStats.get()); - - if(NetworkMessage::statsTimer.isStarted() == false) { - NetworkMessage::statsTimer.start(); - } - - bool secondChanged = false; - if(NetworkMessage::statsTimer.getSeconds() - NetworkMessage::mapMessageStats[netmsgstLastEvent] >= 3) { - - NetworkMessage::mapMessageStats[netmsgstLastEvent] = NetworkMessage::statsTimer.getSeconds(); - secondChanged = true; - } - - if(isSend == true) { - if(NetworkMessage::lastSend.isStarted() == false) { - NetworkMessage::lastSend.start(); - } - int64 millisecondsSinceLastSend = NetworkMessage::lastSend.getMillis(); - int64 secondsSinceLastSend = NetworkMessage::lastSend.getSeconds(); - - //char szBuf[8096]=""; - //snprintf(szBuf,8095,"\nSEND check cur [%lld] last [%lld]\n", (long long)millisecondsSinceLastSend,(long long)NetworkMessage::mapMessageStats[netmsgstPacketsPerMillisecondSend_last] ); - //printf("%s",szBuf); - - if(millisecondsSinceLastSend == NetworkMessage::mapMessageStats[netmsgstPacketsPerMillisecondSend_last]) { - NetworkMessage::mapMessageStats[netmsgstPacketsPerMillisecondSend_current_count]++; - - } - else { - NetworkMessage::mapMessageStats[netmsgstPacketsPerMillisecondSend_last] = millisecondsSinceLastSend; - NetworkMessage::mapMessageStats[netmsgstPacketsPerMillisecondSend] = - (NetworkMessage::mapMessageStats[netmsgstPacketsPerMillisecondSend] + - NetworkMessage::mapMessageStats[netmsgstPacketsPerMillisecondSend_current_count]) / 2; - } - - if(secondsSinceLastSend == NetworkMessage::mapMessageStats[netmsgstPacketsPerSecondSend_last]) { - NetworkMessage::mapMessageStats[netmsgstPacketsPerSecondSend_current_count]++; - - } - else { - NetworkMessage::mapMessageStats[netmsgstPacketsPerSecondSend_last] = secondsSinceLastSend; - NetworkMessage::mapMessageStats[netmsgstPacketsPerSecondSend] = - (NetworkMessage::mapMessageStats[netmsgstPacketsPerSecondSend] + - NetworkMessage::mapMessageStats[netmsgstPacketsPerSecondSend_current_count]) / 2; - } - - NetworkMessage::mapMessageStats[netmsgstAverageSendSize] = - (NetworkMessage::mapMessageStats[netmsgstAverageSendSize] + - dataSize) / 2; - } - else { - if(NetworkMessage::lastRecv.isStarted() == false) { - NetworkMessage::lastRecv.start(); - } - int64 millisecondsSinceLastRecv = NetworkMessage::lastRecv.getMillis(); - int64 secondsSinceLastRecv = NetworkMessage::lastRecv.getSeconds(); - - //char szBuf[8096]=""; - //snprintf(szBuf,8095,"\nRECV check cur [%lld] last [%lld]\n", (long long)millisecondsSinceLastRecv,(long long)NetworkMessage::mapMessageStats[netmsgstPacketsPerMillisecondRecv_last] ); - //printf("%s",szBuf); - - if(millisecondsSinceLastRecv == NetworkMessage::mapMessageStats[netmsgstPacketsPerMillisecondRecv_last]) { - NetworkMessage::mapMessageStats[netmsgstPacketsPerMillisecondRecv_current_count]++; - - } - else { - NetworkMessage::mapMessageStats[netmsgstPacketsPerMillisecondRecv_last] = millisecondsSinceLastRecv; - NetworkMessage::mapMessageStats[netmsgstPacketsPerMillisecondRecv] = - (NetworkMessage::mapMessageStats[netmsgstPacketsPerMillisecondRecv] + - NetworkMessage::mapMessageStats[netmsgstPacketsPerMillisecondRecv_current_count]) / 2; - } - - if(secondsSinceLastRecv == NetworkMessage::mapMessageStats[netmsgstPacketsPerSecondRecv_last]) { - NetworkMessage::mapMessageStats[netmsgstPacketsPerSecondRecv_current_count]++; - - } - else { - NetworkMessage::mapMessageStats[netmsgstPacketsPerSecondRecv_last] = secondsSinceLastRecv; - NetworkMessage::mapMessageStats[netmsgstPacketsPerSecondRecv] = - (NetworkMessage::mapMessageStats[netmsgstPacketsPerSecondRecv] + - NetworkMessage::mapMessageStats[netmsgstPacketsPerSecondRecv_current_count]) / 2; - } - - NetworkMessage::mapMessageStats[netmsgstAverageRecvSize] = - (NetworkMessage::mapMessageStats[netmsgstAverageRecvSize] + - dataSize) / 2; - } - - if(secondChanged == true) { - printf("%s",NetworkMessage::getNetworkPacketStats().c_str()); - } - } - - if( config.getBool("DebugNetworkPackets","false") == true || - config.getBool("DebugNetworkPacketSizes","false") == true) { - - printf("%s DataSize = %d",label.c_str(),dataSize); - - if(config.getBool("DebugNetworkPackets","false") == true) { - - printf("\n"); - const char *buf = static_cast(data); - for(unsigned int index = 0; index < (unsigned int)dataSize; ++index) { - - printf("%u[%X][%d] ",index,buf[index],buf[index]); - if(index % 10 == 0) { - printf("\n"); - } - } - } - printf("\n======= END =======\n"); - } + NetworkMessage::statsTimer.stop(); + NetworkMessage::lastSend.stop(); + NetworkMessage::lastRecv.stop(); + NetworkMessage::mapMessageStats.clear(); +} + +string NetworkMessage::getNetworkPacketStats() { + string result = "Current Timer Milliseconds: " + + intToStr(NetworkMessage::statsTimer.getMillis()) + "\n"; + + for (std::map::iterator iterMap = + mapMessageStats.begin(); + iterMap != mapMessageStats.end(); ++iterMap) { + switch (iterMap->first) { + case netmsgstPacketsPerMillisecondSend: + result += "send p / msec: " + intToStr(iterMap->second) + + (iterMap->second > 10 ? " ****WARNING WIN32 LIMIT EXCEEDED****" + : "") + + "\n"; + break; + case netmsgstPacketsPerSecondSend: + result += "send p / sec: " + intToStr(iterMap->second) + "\n"; + break; + case netmsgstAverageSendSize: + result += "send avg size: " + intToStr(iterMap->second) + "\n"; + break; + + case netmsgstPacketsPerMillisecondRecv: + result += "recv p / msec: " + intToStr(iterMap->second) + "\n"; + break; + case netmsgstPacketsPerSecondRecv: + result += "recv p / sec: " + intToStr(iterMap->second) + + (iterMap->second > 10 ? " ****WARNING WIN32 LIMIT EXCEEDED****" + : "") + + "\n"; + break; + case netmsgstAverageRecvSize: + result += "recv avg size: " + intToStr(iterMap->second) + "\n"; + break; + } + } + return result; +} + +void NetworkMessage::dump_packet(string label, const void *data, int dataSize, + bool isSend) { + Config &config = Config::getInstance(); + if (config.getBool("DebugNetworkPacketStats", "false") == true) { + + MutexSafeWrapper safeMutex(NetworkMessage::mutexMessageStats.get()); + + if (NetworkMessage::statsTimer.isStarted() == false) { + NetworkMessage::statsTimer.start(); + } + + bool secondChanged = false; + if (NetworkMessage::statsTimer.getSeconds() - + NetworkMessage::mapMessageStats[netmsgstLastEvent] >= + 3) { + + NetworkMessage::mapMessageStats[netmsgstLastEvent] = + NetworkMessage::statsTimer.getSeconds(); + secondChanged = true; + } + + if (isSend == true) { + if (NetworkMessage::lastSend.isStarted() == false) { + NetworkMessage::lastSend.start(); + } + int64 millisecondsSinceLastSend = NetworkMessage::lastSend.getMillis(); + int64 secondsSinceLastSend = NetworkMessage::lastSend.getSeconds(); + + // char szBuf[8096]=""; + // snprintf(szBuf,8095,"\nSEND check cur [%lld] last [%lld]\n", (long + // long)millisecondsSinceLastSend,(long + // long)NetworkMessage::mapMessageStats[netmsgstPacketsPerMillisecondSend_last] + // ); printf("%s",szBuf); + + if (millisecondsSinceLastSend == + NetworkMessage::mapMessageStats + [netmsgstPacketsPerMillisecondSend_last]) { + NetworkMessage::mapMessageStats + [netmsgstPacketsPerMillisecondSend_current_count]++; + + } else { + NetworkMessage::mapMessageStats + [netmsgstPacketsPerMillisecondSend_last] = + millisecondsSinceLastSend; + NetworkMessage::mapMessageStats[netmsgstPacketsPerMillisecondSend] = + (NetworkMessage::mapMessageStats + [netmsgstPacketsPerMillisecondSend] + + NetworkMessage::mapMessageStats + [netmsgstPacketsPerMillisecondSend_current_count]) / + 2; + } + + if (secondsSinceLastSend == + NetworkMessage::mapMessageStats[netmsgstPacketsPerSecondSend_last]) { + NetworkMessage::mapMessageStats + [netmsgstPacketsPerSecondSend_current_count]++; + + } else { + NetworkMessage::mapMessageStats[netmsgstPacketsPerSecondSend_last] = + secondsSinceLastSend; + NetworkMessage::mapMessageStats[netmsgstPacketsPerSecondSend] = + (NetworkMessage::mapMessageStats[netmsgstPacketsPerSecondSend] + + NetworkMessage::mapMessageStats + [netmsgstPacketsPerSecondSend_current_count]) / + 2; + } + + NetworkMessage::mapMessageStats[netmsgstAverageSendSize] = + (NetworkMessage::mapMessageStats[netmsgstAverageSendSize] + + dataSize) / + 2; + } else { + if (NetworkMessage::lastRecv.isStarted() == false) { + NetworkMessage::lastRecv.start(); + } + int64 millisecondsSinceLastRecv = NetworkMessage::lastRecv.getMillis(); + int64 secondsSinceLastRecv = NetworkMessage::lastRecv.getSeconds(); + + // char szBuf[8096]=""; + // snprintf(szBuf,8095,"\nRECV check cur [%lld] last [%lld]\n", (long + // long)millisecondsSinceLastRecv,(long + // long)NetworkMessage::mapMessageStats[netmsgstPacketsPerMillisecondRecv_last] + // ); printf("%s",szBuf); + + if (millisecondsSinceLastRecv == + NetworkMessage::mapMessageStats + [netmsgstPacketsPerMillisecondRecv_last]) { + NetworkMessage::mapMessageStats + [netmsgstPacketsPerMillisecondRecv_current_count]++; + + } else { + NetworkMessage::mapMessageStats + [netmsgstPacketsPerMillisecondRecv_last] = + millisecondsSinceLastRecv; + NetworkMessage::mapMessageStats[netmsgstPacketsPerMillisecondRecv] = + (NetworkMessage::mapMessageStats + [netmsgstPacketsPerMillisecondRecv] + + NetworkMessage::mapMessageStats + [netmsgstPacketsPerMillisecondRecv_current_count]) / + 2; + } + + if (secondsSinceLastRecv == + NetworkMessage::mapMessageStats[netmsgstPacketsPerSecondRecv_last]) { + NetworkMessage::mapMessageStats + [netmsgstPacketsPerSecondRecv_current_count]++; + + } else { + NetworkMessage::mapMessageStats[netmsgstPacketsPerSecondRecv_last] = + secondsSinceLastRecv; + NetworkMessage::mapMessageStats[netmsgstPacketsPerSecondRecv] = + (NetworkMessage::mapMessageStats[netmsgstPacketsPerSecondRecv] + + NetworkMessage::mapMessageStats + [netmsgstPacketsPerSecondRecv_current_count]) / + 2; + } + + NetworkMessage::mapMessageStats[netmsgstAverageRecvSize] = + (NetworkMessage::mapMessageStats[netmsgstAverageRecvSize] + + dataSize) / + 2; + } + + if (secondChanged == true) { + printf("%s", NetworkMessage::getNetworkPacketStats().c_str()); + } + } + + if (config.getBool("DebugNetworkPackets", "false") == true || + config.getBool("DebugNetworkPacketSizes", "false") == true) { + + printf("%s DataSize = %d", label.c_str(), dataSize); + + if (config.getBool("DebugNetworkPackets", "false") == true) { + + printf("\n"); + const char *buf = static_cast(data); + for (unsigned int index = 0; index < (unsigned int)dataSize; ++index) { + + printf("%u[%X][%d] ", index, buf[index], buf[index]); + if (index % 10 == 0) { + printf("\n"); + } + } + } + printf("\n======= END =======\n"); + } } // ===================================================== // class NetworkMessageIntro // ===================================================== NetworkMessageIntro::NetworkMessageIntro() { - messageType= -1; - data.sessionId= -1; - data.playerIndex= -1; - data.gameState = nmgstInvalid; - data.externalIp = 0; - data.ftpPort = 0; - data.gameInProgress = 0; -} - -NetworkMessageIntro::NetworkMessageIntro(int32 sessionId,const string &versionString, - const string &name, int playerIndex, - NetworkGameStateType gameState, - uint32 externalIp, - uint32 ftpPort, - const string &playerLanguage, - int gameInProgress, const string &playerUUID, - const string &platform) { - messageType = nmtIntro; - data.sessionId = sessionId; - data.versionString = versionString; - data.name = name; - data.playerIndex = static_cast(playerIndex); - data.gameState = static_cast(gameState); - data.externalIp = externalIp; - data.ftpPort = ftpPort; - data.language = playerLanguage; - data.gameInProgress = gameInProgress; - data.playerUUID = playerUUID; - data.platform = platform; -} - -const char * NetworkMessageIntro::getPackedMessageFormat() const { - return "cl128s32shcLL60sc60s60s"; + messageType = -1; + data.sessionId = -1; + data.playerIndex = -1; + data.gameState = nmgstInvalid; + data.externalIp = 0; + data.ftpPort = 0; + data.gameInProgress = 0; +} + +NetworkMessageIntro::NetworkMessageIntro( + int32 sessionId, const string &versionString, const string &name, + int playerIndex, NetworkGameStateType gameState, uint32 externalIp, + uint32 ftpPort, const string &playerLanguage, int gameInProgress, + const string &playerUUID, const string &platform) { + messageType = nmtIntro; + data.sessionId = sessionId; + data.versionString = versionString; + data.name = name; + data.playerIndex = static_cast(playerIndex); + data.gameState = static_cast(gameState); + data.externalIp = externalIp; + data.ftpPort = ftpPort; + data.language = playerLanguage; + data.gameInProgress = gameInProgress; + data.playerUUID = playerUUID; + data.platform = platform; +} + +const char *NetworkMessageIntro::getPackedMessageFormat() const { + return "cl128s32shcLL60sc60s60s"; } unsigned int NetworkMessageIntro::getPackedSize() { - static unsigned int result = 0; - if(result == 0) { - Data packedData; - packedData.externalIp = 0; - packedData.ftpPort = 0; - packedData.gameInProgress = 0; - packedData.gameState = 0; - messageType = nmtIntro; - packedData.playerIndex = 0; - packedData.sessionId = 0; - - unsigned char *buf = new unsigned char[sizeof(packedData)*3]; - result = pack(buf, getPackedMessageFormat(), - messageType, - packedData.sessionId, - packedData.versionString.getBuffer(), - packedData.name.getBuffer(), - packedData.playerIndex, - packedData.gameState, - packedData.externalIp, - packedData.ftpPort, - packedData.language.getBuffer(), - data.gameInProgress, - packedData.playerUUID.getBuffer(), - packedData.platform.getBuffer()); - delete [] buf; - } - return result; + static unsigned int result = 0; + if (result == 0) { + Data packedData; + packedData.externalIp = 0; + packedData.ftpPort = 0; + packedData.gameInProgress = 0; + packedData.gameState = 0; + messageType = nmtIntro; + packedData.playerIndex = 0; + packedData.sessionId = 0; + + unsigned char *buf = new unsigned char[sizeof(packedData) * 3]; + result = pack(buf, getPackedMessageFormat(), messageType, + packedData.sessionId, packedData.versionString.getBuffer(), + packedData.name.getBuffer(), packedData.playerIndex, + packedData.gameState, packedData.externalIp, + packedData.ftpPort, packedData.language.getBuffer(), + data.gameInProgress, packedData.playerUUID.getBuffer(), + packedData.platform.getBuffer()); + delete[] buf; + } + return result; } void NetworkMessageIntro::unpackMessage(unsigned char *buf) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\nIn [%s] about to unpack...\n",__FUNCTION__); - unpack(buf, getPackedMessageFormat(), - &messageType, - &data.sessionId, - data.versionString.getBuffer(), - data.name.getBuffer(), - &data.playerIndex, - &data.gameState, - &data.externalIp, - &data.ftpPort, - data.language.getBuffer(), - &data.gameInProgress, - data.playerUUID.getBuffer(), - data.platform.getBuffer()); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s] unpacked data:\n%s\n",__FUNCTION__,this->toString().c_str()); -} - -unsigned char * NetworkMessageIntro::packMessage() { - unsigned char *buf = new unsigned char[getPackedSize()+1]; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\nIn [%s] about to pack...\n",__FUNCTION__); - pack(buf, getPackedMessageFormat(), - messageType, - data.sessionId, - data.versionString.getBuffer(), - data.name.getBuffer(), - data.playerIndex, - data.gameState, - data.externalIp, - data.ftpPort, - data.language.getBuffer(), - data.gameInProgress, - data.playerUUID.getBuffer(), - data.platform.getBuffer()); - return buf; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\nIn [%s] about to unpack...\n", __FUNCTION__); + unpack(buf, getPackedMessageFormat(), &messageType, &data.sessionId, + data.versionString.getBuffer(), data.name.getBuffer(), + &data.playerIndex, &data.gameState, &data.externalIp, &data.ftpPort, + data.language.getBuffer(), &data.gameInProgress, + data.playerUUID.getBuffer(), data.platform.getBuffer()); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s] unpacked data:\n%s\n", __FUNCTION__, + this->toString().c_str()); +} + +unsigned char *NetworkMessageIntro::packMessage() { + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\nIn [%s] about to pack...\n", __FUNCTION__); + pack(buf, getPackedMessageFormat(), messageType, data.sessionId, + data.versionString.getBuffer(), data.name.getBuffer(), data.playerIndex, + data.gameState, data.externalIp, data.ftpPort, data.language.getBuffer(), + data.gameInProgress, data.playerUUID.getBuffer(), + data.platform.getBuffer()); + return buf; } string NetworkMessageIntro::toString() const { - string result = "messageType = " + intToStr(messageType); - result += " sessionId = " + intToStr(data.sessionId); - result += " versionString = " + data.versionString.getString(); - result += " name = " + data.name.getString(); - result += " playerIndex = " + intToStr(data.playerIndex); - result += " gameState = " + intToStr(data.gameState); - result += " externalIp = " + uIntToStr(data.externalIp); - result += " ftpPort = " + uIntToStr(data.ftpPort); - result += " language = " + data.language.getString(); - result += " gameInProgress = " + uIntToStr(data.gameInProgress); - result += " playerUUID = " + data.playerUUID.getString(); - result += " platform = " + data.platform.getString(); - - return result; -} - -bool NetworkMessageIntro::receive(Socket* socket) { - bool result = false; - if(useOldProtocol == true) { - result = NetworkMessage::receive(socket, &data, sizeof(data), true); - if(result == true) { - messageType = this->getNetworkMessageType(); - } - } - else { - unsigned char *buf = new unsigned char[getPackedSize()+1]; - result = NetworkMessage::receive(socket, buf, getPackedSize(), true); - unpackMessage(buf); - //printf("Got packet size = %u data.messageType = %d\n%s\n",getPackedSize(),data.messageType,buf); - delete [] buf; - } - fromEndian(); - - data.name.nullTerminate(); - data.versionString.nullTerminate(); - data.language.nullTerminate(); - data.playerUUID.nullTerminate(); - data.platform.nullTerminate(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] get nmtIntro, data.playerIndex = %d, data.sessionId = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,data.playerIndex,data.sessionId); - return result; -} - -void NetworkMessageIntro::send(Socket* socket) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] sending nmtIntro, data.playerIndex = %d, data.sessionId = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,data.playerIndex,data.sessionId); - assert(messageType == nmtIntro); - toEndian(); - - if(useOldProtocol == true) { - //NetworkMessage::send(socket, &messageType, sizeof(messageType)); - NetworkMessage::send(socket, &data, sizeof(data),messageType); - } - else { - unsigned char *buf = packMessage(); - //printf("Send packet size = %u data.messageType = %d\n[%s]\n",getPackedSize(),data.messageType,buf); - //NetworkMessage::send(socket, &data, sizeof(data)); - NetworkMessage::send(socket, buf, getPackedSize()); - delete [] buf; - } + string result = "messageType = " + intToStr(messageType); + result += " sessionId = " + intToStr(data.sessionId); + result += " versionString = " + data.versionString.getString(); + result += " name = " + data.name.getString(); + result += " playerIndex = " + intToStr(data.playerIndex); + result += " gameState = " + intToStr(data.gameState); + result += " externalIp = " + uIntToStr(data.externalIp); + result += " ftpPort = " + uIntToStr(data.ftpPort); + result += " language = " + data.language.getString(); + result += " gameInProgress = " + uIntToStr(data.gameInProgress); + result += " playerUUID = " + data.playerUUID.getString(); + result += " platform = " + data.platform.getString(); + + return result; +} + +bool NetworkMessageIntro::receive(Socket *socket) { + bool result = false; + if (useOldProtocol == true) { + result = NetworkMessage::receive(socket, &data, sizeof(data), true); + if (result == true) { + messageType = this->getNetworkMessageType(); + } + } else { + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + result = NetworkMessage::receive(socket, buf, getPackedSize(), true); + unpackMessage(buf); + // printf("Got packet size = %u data.messageType = + // %d\n%s\n",getPackedSize(),data.messageType,buf); + delete[] buf; + } + fromEndian(); + + data.name.nullTerminate(); + data.versionString.nullTerminate(); + data.language.nullTerminate(); + data.playerUUID.nullTerminate(); + data.platform.nullTerminate(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] get nmtIntro, " + "data.playerIndex = %d, data.sessionId = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, data.playerIndex, + data.sessionId); + return result; +} + +void NetworkMessageIntro::send(Socket *socket) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] sending nmtIntro, " + "data.playerIndex = %d, data.sessionId = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, data.playerIndex, + data.sessionId); + assert(messageType == nmtIntro); + toEndian(); + + if (useOldProtocol == true) { + // NetworkMessage::send(socket, &messageType, sizeof(messageType)); + NetworkMessage::send(socket, &data, sizeof(data), messageType); + } else { + unsigned char *buf = packMessage(); + // printf("Send packet size = %u data.messageType = + // %d\n[%s]\n",getPackedSize(),data.messageType,buf); + // NetworkMessage::send(socket, &data, sizeof(data)); + NetworkMessage::send(socket, buf, getPackedSize()); + delete[] buf; + } } void NetworkMessageIntro::toEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); - data.sessionId = Shared::PlatformByteOrder::toCommonEndian(data.sessionId); - data.playerIndex = Shared::PlatformByteOrder::toCommonEndian(data.playerIndex); - data.gameState = Shared::PlatformByteOrder::toCommonEndian(data.gameState); - data.externalIp = Shared::PlatformByteOrder::toCommonEndian(data.externalIp); - data.ftpPort = Shared::PlatformByteOrder::toCommonEndian(data.ftpPort); - - data.gameInProgress = Shared::PlatformByteOrder::toCommonEndian(data.gameInProgress); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); + data.sessionId = Shared::PlatformByteOrder::toCommonEndian(data.sessionId); + data.playerIndex = + Shared::PlatformByteOrder::toCommonEndian(data.playerIndex); + data.gameState = Shared::PlatformByteOrder::toCommonEndian(data.gameState); + data.externalIp = + Shared::PlatformByteOrder::toCommonEndian(data.externalIp); + data.ftpPort = Shared::PlatformByteOrder::toCommonEndian(data.ftpPort); + + data.gameInProgress = + Shared::PlatformByteOrder::toCommonEndian(data.gameInProgress); + } } void NetworkMessageIntro::fromEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); - data.sessionId = Shared::PlatformByteOrder::fromCommonEndian(data.sessionId); - data.playerIndex = Shared::PlatformByteOrder::fromCommonEndian(data.playerIndex); - data.gameState = Shared::PlatformByteOrder::fromCommonEndian(data.gameState); - data.externalIp = Shared::PlatformByteOrder::fromCommonEndian(data.externalIp); - data.ftpPort = Shared::PlatformByteOrder::fromCommonEndian(data.ftpPort); - - data.gameInProgress = Shared::PlatformByteOrder::fromCommonEndian(data.gameInProgress); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); + data.sessionId = + Shared::PlatformByteOrder::fromCommonEndian(data.sessionId); + data.playerIndex = + Shared::PlatformByteOrder::fromCommonEndian(data.playerIndex); + data.gameState = + Shared::PlatformByteOrder::fromCommonEndian(data.gameState); + data.externalIp = + Shared::PlatformByteOrder::fromCommonEndian(data.externalIp); + data.ftpPort = Shared::PlatformByteOrder::fromCommonEndian(data.ftpPort); + + data.gameInProgress = + Shared::PlatformByteOrder::fromCommonEndian(data.gameInProgress); + } } // ===================================================== // class NetworkMessagePing // ===================================================== -NetworkMessagePing::NetworkMessagePing(){ - messageType = nmtPing; - data.pingFrequency = 0; - data.pingTime = 0; - pingReceivedLocalTime = 0; +NetworkMessagePing::NetworkMessagePing() { + messageType = nmtPing; + data.pingFrequency = 0; + data.pingTime = 0; + pingReceivedLocalTime = 0; } -NetworkMessagePing::NetworkMessagePing(int32 pingFrequency, int64 pingTime){ - messageType= nmtPing; - data.pingFrequency= pingFrequency; - data.pingTime= pingTime; - pingReceivedLocalTime=0; +NetworkMessagePing::NetworkMessagePing(int32 pingFrequency, int64 pingTime) { + messageType = nmtPing; + data.pingFrequency = pingFrequency; + data.pingTime = pingTime; + pingReceivedLocalTime = 0; } -const char * NetworkMessagePing::getPackedMessageFormat() const { - return "clq"; -} +const char *NetworkMessagePing::getPackedMessageFormat() const { return "clq"; } unsigned int NetworkMessagePing::getPackedSize() { - static unsigned int result = 0; - if(result == 0) { - Data packedData; - messageType = 0; - packedData.pingFrequency = 0; - packedData.pingTime = 0; - unsigned char *buf = new unsigned char[sizeof(packedData)*3]; - result = pack(buf, getPackedMessageFormat(), - messageType, - packedData.pingFrequency, - packedData.pingTime); - delete [] buf; - } - return result; + static unsigned int result = 0; + if (result == 0) { + Data packedData; + messageType = 0; + packedData.pingFrequency = 0; + packedData.pingTime = 0; + unsigned char *buf = new unsigned char[sizeof(packedData) * 3]; + result = pack(buf, getPackedMessageFormat(), messageType, + packedData.pingFrequency, packedData.pingTime); + delete[] buf; + } + return result; } void NetworkMessagePing::unpackMessage(unsigned char *buf) { - unpack(buf, getPackedMessageFormat(), - &messageType, - &data.pingFrequency, - &data.pingTime); -} - -unsigned char * NetworkMessagePing::packMessage() { - unsigned char *buf = new unsigned char[getPackedSize()+1]; - pack(buf, getPackedMessageFormat(), - messageType, - data.pingFrequency, - data.pingTime); - return buf; -} - -bool NetworkMessagePing::receive(Socket* socket){ - bool result = false; - if(useOldProtocol == true) { - result = NetworkMessage::receive(socket, &data, sizeof(data), true); - if(result == true) { - messageType = this->getNetworkMessageType(); - } - } - else { - unsigned char *buf = new unsigned char[getPackedSize()+1]; - result = NetworkMessage::receive(socket, buf, getPackedSize(), true); - unpackMessage(buf); - //printf("Got packet size = %u data.messageType = %d\n%s\n",getPackedSize(),data.messageType,buf); - delete [] buf; - } - fromEndian(); - - pingReceivedLocalTime = time(NULL); - return result; -} - -void NetworkMessagePing::send(Socket* socket) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] nmtPing\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - assert(messageType == nmtPing); - toEndian(); - - if(useOldProtocol == true) { - //NetworkMessage::send(socket, &messageType, sizeof(messageType)); - NetworkMessage::send(socket, &data, sizeof(data), messageType); - } - else { - unsigned char *buf = packMessage(); - //printf("Send packet size = %u data.messageType = %d\n[%s]\n",getPackedSize(),data.messageType,buf); - //NetworkMessage::send(socket, &data, sizeof(data)); - NetworkMessage::send(socket, buf, getPackedSize()); - delete [] buf; - } + unpack(buf, getPackedMessageFormat(), &messageType, &data.pingFrequency, + &data.pingTime); +} + +unsigned char *NetworkMessagePing::packMessage() { + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + pack(buf, getPackedMessageFormat(), messageType, data.pingFrequency, + data.pingTime); + return buf; +} + +bool NetworkMessagePing::receive(Socket *socket) { + bool result = false; + if (useOldProtocol == true) { + result = NetworkMessage::receive(socket, &data, sizeof(data), true); + if (result == true) { + messageType = this->getNetworkMessageType(); + } + } else { + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + result = NetworkMessage::receive(socket, buf, getPackedSize(), true); + unpackMessage(buf); + // printf("Got packet size = %u data.messageType = + // %d\n%s\n",getPackedSize(),data.messageType,buf); + delete[] buf; + } + fromEndian(); + + pingReceivedLocalTime = time(NULL); + return result; +} + +void NetworkMessagePing::send(Socket *socket) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d] nmtPing\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + assert(messageType == nmtPing); + toEndian(); + + if (useOldProtocol == true) { + // NetworkMessage::send(socket, &messageType, sizeof(messageType)); + NetworkMessage::send(socket, &data, sizeof(data), messageType); + } else { + unsigned char *buf = packMessage(); + // printf("Send packet size = %u data.messageType = + // %d\n[%s]\n",getPackedSize(),data.messageType,buf); + // NetworkMessage::send(socket, &data, sizeof(data)); + NetworkMessage::send(socket, buf, getPackedSize()); + delete[] buf; + } } void NetworkMessagePing::toEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); - data.pingFrequency = Shared::PlatformByteOrder::toCommonEndian(data.pingFrequency); - data.pingTime = Shared::PlatformByteOrder::toCommonEndian(data.pingTime); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); + data.pingFrequency = + Shared::PlatformByteOrder::toCommonEndian(data.pingFrequency); + data.pingTime = Shared::PlatformByteOrder::toCommonEndian(data.pingTime); + } } void NetworkMessagePing::fromEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); - data.pingFrequency = Shared::PlatformByteOrder::fromCommonEndian(data.pingFrequency); - data.pingTime = Shared::PlatformByteOrder::fromCommonEndian(data.pingTime); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); + data.pingFrequency = + Shared::PlatformByteOrder::fromCommonEndian(data.pingFrequency); + data.pingTime = Shared::PlatformByteOrder::fromCommonEndian(data.pingTime); + } } // ===================================================== @@ -618,97 +711,94 @@ void NetworkMessagePing::fromEndian() { // ===================================================== NetworkMessageReady::NetworkMessageReady() { - messageType = nmtReady; - data.checksum= 0; + messageType = nmtReady; + data.checksum = 0; } NetworkMessageReady::NetworkMessageReady(uint32 checksum) { - messageType = nmtReady; - data.checksum= checksum; + messageType = nmtReady; + data.checksum = checksum; } -const char * NetworkMessageReady::getPackedMessageFormat() const { - return "cL"; -} +const char *NetworkMessageReady::getPackedMessageFormat() const { return "cL"; } unsigned int NetworkMessageReady::getPackedSize() { - static unsigned int result = 0; - if(result == 0) { - Data packedData; - packedData.checksum = 0; - messageType = 0; - unsigned char *buf = new unsigned char[sizeof(packedData)*3]; - result = pack(buf, getPackedMessageFormat(), - messageType, - packedData.checksum); - delete [] buf; - } - return result; + static unsigned int result = 0; + if (result == 0) { + Data packedData; + packedData.checksum = 0; + messageType = 0; + unsigned char *buf = new unsigned char[sizeof(packedData) * 3]; + result = + pack(buf, getPackedMessageFormat(), messageType, packedData.checksum); + delete[] buf; + } + return result; } void NetworkMessageReady::unpackMessage(unsigned char *buf) { - unpack(buf, getPackedMessageFormat(), - &messageType, - &data.checksum); -} - -unsigned char * NetworkMessageReady::packMessage() { - unsigned char *buf = new unsigned char[getPackedSize()+1]; - pack(buf, getPackedMessageFormat(), - messageType, - data.checksum); - return buf; -} - -bool NetworkMessageReady::receive(Socket* socket){ - bool result = false; - if(useOldProtocol == true) { - result = NetworkMessage::receive(socket, &data, sizeof(data), true); - if(result == true) { - messageType = this->getNetworkMessageType(); - } - } - else { - unsigned char *buf = new unsigned char[getPackedSize()+1]; - //bool result = NetworkMessage::receive(socket, buf, getPackedSize(), true); - NetworkMessage::receive(socket, buf, getPackedSize(), true); - unpackMessage(buf); - //printf("Got packet size = %u data.messageType = %d\n%s\n",getPackedSize(),data.messageType,buf); - delete [] buf; - } - fromEndian(); - return result; -} - -void NetworkMessageReady::send(Socket* socket) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] nmtReady\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - assert(messageType == nmtReady); - toEndian(); - - if(useOldProtocol == true) { - //NetworkMessage::send(socket, &messageType, sizeof(messageType)); - NetworkMessage::send(socket, &data, sizeof(data), messageType); - } - else { - unsigned char *buf = packMessage(); - //printf("Send packet size = %u data.messageType = %d\n[%s]\n",getPackedSize(),data.messageType,buf); - NetworkMessage::send(socket, buf, getPackedSize()); - delete [] buf; - } + unpack(buf, getPackedMessageFormat(), &messageType, &data.checksum); +} + +unsigned char *NetworkMessageReady::packMessage() { + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + pack(buf, getPackedMessageFormat(), messageType, data.checksum); + return buf; +} + +bool NetworkMessageReady::receive(Socket *socket) { + bool result = false; + if (useOldProtocol == true) { + result = NetworkMessage::receive(socket, &data, sizeof(data), true); + if (result == true) { + messageType = this->getNetworkMessageType(); + } + } else { + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + // bool result = NetworkMessage::receive(socket, buf, getPackedSize(), + // true); + NetworkMessage::receive(socket, buf, getPackedSize(), true); + unpackMessage(buf); + // printf("Got packet size = %u data.messageType = + // %d\n%s\n",getPackedSize(),data.messageType,buf); + delete[] buf; + } + fromEndian(); + return result; +} + +void NetworkMessageReady::send(Socket *socket) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d] nmtReady\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + assert(messageType == nmtReady); + toEndian(); + + if (useOldProtocol == true) { + // NetworkMessage::send(socket, &messageType, sizeof(messageType)); + NetworkMessage::send(socket, &data, sizeof(data), messageType); + } else { + unsigned char *buf = packMessage(); + // printf("Send packet size = %u data.messageType = + // %d\n[%s]\n",getPackedSize(),data.messageType,buf); + NetworkMessage::send(socket, buf, getPackedSize()); + delete[] buf; + } } void NetworkMessageReady::toEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); - data.checksum = Shared::PlatformByteOrder::toCommonEndian(data.checksum); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); + data.checksum = Shared::PlatformByteOrder::toCommonEndian(data.checksum); + } } void NetworkMessageReady::fromEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); - data.checksum = Shared::PlatformByteOrder::fromCommonEndian(data.checksum); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); + data.checksum = Shared::PlatformByteOrder::fromCommonEndian(data.checksum); + } } // ===================================================== @@ -716,930 +806,971 @@ void NetworkMessageReady::fromEndian() { // ===================================================== NetworkMessageLaunch::NetworkMessageLaunch() { - messageType = -1; - compressedLength = 0; - for(unsigned int i = 0; i < (unsigned int)maxFactionCRCCount; ++i) { - data.factionNameList[i] = ""; - data.factionCRCList[i] = 0; - } - data.aiAcceptSwitchTeamPercentChance = 0; - data.cpuReplacementMultiplier = 10 ; - data.masterserver_admin = -1; - data.masterserver_admin_factionIndex = -1; -} - -NetworkMessageLaunch::NetworkMessageLaunch(const GameSettings *gameSettings,int8 messageType) { - this->messageType = messageType; - compressedLength = 0; - - data.mapFilter = gameSettings->getMapFilter(); - data.mapCRC = gameSettings->getMapCRC(); - data.tilesetCRC = gameSettings->getTilesetCRC(); - data.techCRC = gameSettings->getTechCRC(); - - for(unsigned int i = 0; i < (unsigned int)maxFactionCRCCount; ++i) { - data.factionNameList[i] = ""; - data.factionCRCList[i] = 0; - } - - vector > factionCRCList = gameSettings->getFactionCRCList(); - for(unsigned int i = 0; i < factionCRCList.size() && i < (unsigned int)maxFactionCRCCount; ++i) { - data.factionNameList[i] = factionCRCList[i].first; - data.factionCRCList[i] = factionCRCList[i].second; - } - - data.description= gameSettings->getDescription(); - data.map= gameSettings->getMap(); - data.tileset= gameSettings->getTileset(); - data.tech= gameSettings->getTech(); - data.factionCount= gameSettings->getFactionCount(); - data.thisFactionIndex= gameSettings->getThisFactionIndex(); - data.defaultResources= gameSettings->getDefaultResources(); - data.defaultUnits= gameSettings->getDefaultUnits(); - data.defaultVictoryConditions= gameSettings->getDefaultVictoryConditions(); - data.fogOfWar = gameSettings->getFogOfWar(); - data.allowObservers = gameSettings->getAllowObservers(); - data.enableObserverModeAtEndGame = gameSettings->getEnableObserverModeAtEndGame(); - data.enableServerControlledAI = gameSettings->getEnableServerControlledAI(); - data.networkFramePeriod = gameSettings->getNetworkFramePeriod(); - data.networkPauseGameForLaggedClients = gameSettings->getNetworkPauseGameForLaggedClients(); - data.pathFinderType = gameSettings->getPathFinderType(); - data.flagTypes1 = gameSettings->getFlagTypes1(); - - //for(int i= 0; i < data.factionCount; ++i) { - for(int i= 0; i < GameConstants::maxPlayers; ++i) { - data.factionTypeNames[i]= gameSettings->getFactionTypeName(i); - data.networkPlayerNames[i]= gameSettings->getNetworkPlayerName(i); - data.networkPlayerPlatform[i]= gameSettings->getNetworkPlayerPlatform(i); - data.networkPlayerStatuses[i] = gameSettings->getNetworkPlayerStatuses(i); - data.networkPlayerLanguages[i] = gameSettings->getNetworkPlayerLanguages(i); - data.factionControls[i]= gameSettings->getFactionControl(i); - data.resourceMultiplierIndex[i]= gameSettings->getResourceMultiplierIndex(i); - data.teams[i]= gameSettings->getTeam(i); - data.startLocationIndex[i]= gameSettings->getStartLocationIndex(i); - - data.networkPlayerUUID[i] = gameSettings->getNetworkPlayerUUID(i); - //printf("Build netmsg for index: %d [%s]\n",i,data.networkPlayerUUID[i].getString().c_str()); - } - data.cpuReplacementMultiplier = gameSettings->getFallbackCpuMultiplier(); - data.aiAcceptSwitchTeamPercentChance = gameSettings->getAiAcceptSwitchTeamPercentChance(); - data.masterserver_admin = gameSettings->getMasterserver_admin(); - data.masterserver_admin_factionIndex = gameSettings->getMasterserver_admin_faction_index(); - - data.scenario = gameSettings->getScenario(); - data.gameUUID = gameSettings->getGameUUID(); - - data.networkAllowNativeLanguageTechtree = gameSettings->getNetworkAllowNativeLanguageTechtree(); + messageType = -1; + compressedLength = 0; + for (unsigned int i = 0; i < (unsigned int)maxFactionCRCCount; ++i) { + data.factionNameList[i] = ""; + data.factionCRCList[i] = 0; + } + data.aiAcceptSwitchTeamPercentChance = 0; + data.cpuReplacementMultiplier = 10; + data.masterserver_admin = -1; + data.masterserver_admin_factionIndex = -1; +} + +NetworkMessageLaunch::NetworkMessageLaunch(const GameSettings *gameSettings, + int8 messageType) { + this->messageType = messageType; + compressedLength = 0; + + data.mapFilter = gameSettings->getMapFilter(); + data.mapCRC = gameSettings->getMapCRC(); + data.tilesetCRC = gameSettings->getTilesetCRC(); + data.techCRC = gameSettings->getTechCRC(); + + for (unsigned int i = 0; i < (unsigned int)maxFactionCRCCount; ++i) { + data.factionNameList[i] = ""; + data.factionCRCList[i] = 0; + } + + vector> factionCRCList = + gameSettings->getFactionCRCList(); + for (unsigned int i = 0; + i < factionCRCList.size() && i < (unsigned int)maxFactionCRCCount; ++i) { + data.factionNameList[i] = factionCRCList[i].first; + data.factionCRCList[i] = factionCRCList[i].second; + } + + data.description = gameSettings->getDescription(); + data.map = gameSettings->getMap(); + data.tileset = gameSettings->getTileset(); + data.tech = gameSettings->getTech(); + data.factionCount = gameSettings->getFactionCount(); + data.thisFactionIndex = gameSettings->getThisFactionIndex(); + data.defaultResources = gameSettings->getDefaultResources(); + data.defaultUnits = gameSettings->getDefaultUnits(); + data.defaultVictoryConditions = gameSettings->getDefaultVictoryConditions(); + data.fogOfWar = gameSettings->getFogOfWar(); + data.allowObservers = gameSettings->getAllowObservers(); + data.enableObserverModeAtEndGame = + gameSettings->getEnableObserverModeAtEndGame(); + data.enableServerControlledAI = gameSettings->getEnableServerControlledAI(); + data.networkFramePeriod = gameSettings->getNetworkFramePeriod(); + data.networkPauseGameForLaggedClients = + gameSettings->getNetworkPauseGameForLaggedClients(); + data.pathFinderType = gameSettings->getPathFinderType(); + data.flagTypes1 = gameSettings->getFlagTypes1(); + + // for(int i= 0; i < data.factionCount; ++i) { + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + data.factionTypeNames[i] = gameSettings->getFactionTypeName(i); + data.networkPlayerNames[i] = gameSettings->getNetworkPlayerName(i); + data.networkPlayerPlatform[i] = gameSettings->getNetworkPlayerPlatform(i); + data.networkPlayerStatuses[i] = gameSettings->getNetworkPlayerStatuses(i); + data.networkPlayerLanguages[i] = gameSettings->getNetworkPlayerLanguages(i); + data.factionControls[i] = gameSettings->getFactionControl(i); + data.resourceMultiplierIndex[i] = + gameSettings->getResourceMultiplierIndex(i); + data.teams[i] = gameSettings->getTeam(i); + data.startLocationIndex[i] = gameSettings->getStartLocationIndex(i); + + data.networkPlayerUUID[i] = gameSettings->getNetworkPlayerUUID(i); + // printf("Build netmsg for index: %d + // [%s]\n",i,data.networkPlayerUUID[i].getString().c_str()); + } + data.cpuReplacementMultiplier = gameSettings->getFallbackCpuMultiplier(); + data.aiAcceptSwitchTeamPercentChance = + gameSettings->getAiAcceptSwitchTeamPercentChance(); + data.masterserver_admin = gameSettings->getMasterserver_admin(); + data.masterserver_admin_factionIndex = + gameSettings->getMasterserver_admin_faction_index(); + + data.scenario = gameSettings->getScenario(); + data.gameUUID = gameSettings->getGameUUID(); + + data.networkAllowNativeLanguageTechtree = + gameSettings->getNetworkAllowNativeLanguageTechtree(); } void NetworkMessageLaunch::buildGameSettings(GameSettings *gameSettings) const { - gameSettings->setDescription(data.description.getString()); - gameSettings->setMap(data.map.getString()); - gameSettings->setTileset(data.tileset.getString()); - gameSettings->setTech(data.tech.getString()); - gameSettings->setFactionCount(data.factionCount); - gameSettings->setThisFactionIndex(data.thisFactionIndex); - gameSettings->setDefaultResources((data.defaultResources != 0)); - gameSettings->setDefaultUnits((data.defaultUnits != 0)); - gameSettings->setDefaultVictoryConditions((data.defaultVictoryConditions != 0)); - gameSettings->setFogOfWar((data.fogOfWar != 0)); - gameSettings->setAllowObservers((data.allowObservers != 0)); - - gameSettings->setEnableObserverModeAtEndGame((data.enableObserverModeAtEndGame != 0)); - gameSettings->setEnableServerControlledAI((data.enableServerControlledAI != 0)); - gameSettings->setNetworkFramePeriod(data.networkFramePeriod); - gameSettings->setNetworkPauseGameForLaggedClients((data.networkPauseGameForLaggedClients != 0)); - gameSettings->setPathFinderType(static_cast(data.pathFinderType)); - gameSettings->setFlagTypes1(data.flagTypes1); - - gameSettings->setMapCRC(data.mapCRC); - gameSettings->setMapFilter(data.mapFilter); - gameSettings->setTilesetCRC(data.tilesetCRC); - gameSettings->setTechCRC(data.techCRC); - - vector > factionCRCList; - for(unsigned int i = 0; i < (unsigned int)maxFactionCRCCount; ++i) { - if(data.factionNameList[i].getString() != "") { - factionCRCList.push_back(make_pair(data.factionNameList[i].getString(),data.factionCRCList[i])); - } - } - gameSettings->setFactionCRCList(factionCRCList); - - //for(int i= 0; i < data.factionCount; ++i) { - for(int i= 0; i < GameConstants::maxPlayers; ++i) { - gameSettings->setFactionTypeName(i, data.factionTypeNames[i].getString()); - gameSettings->setNetworkPlayerName(i,data.networkPlayerNames[i].getString()); - gameSettings->setNetworkPlayerPlatform(i,data.networkPlayerPlatform[i].getString()); - gameSettings->setNetworkPlayerStatuses(i, data.networkPlayerStatuses[i]); - gameSettings->setNetworkPlayerLanguages(i, data.networkPlayerLanguages[i].getString()); - gameSettings->setFactionControl(i, static_cast(data.factionControls[i])); - gameSettings->setResourceMultiplierIndex(i,data.resourceMultiplierIndex[i]); - gameSettings->setTeam(i, data.teams[i]); - gameSettings->setStartLocationIndex(i, data.startLocationIndex[i]); - - gameSettings->setNetworkPlayerUUID(i,data.networkPlayerUUID[i].getString()); - gameSettings->setNetworkPlayerPlatform(i,data.networkPlayerPlatform[i].getString()); - //printf("Build game settings for index: %d [%s]\n",i,data.networkPlayerUUID[i].getString().c_str()); - } - - gameSettings->setAiAcceptSwitchTeamPercentChance(data.aiAcceptSwitchTeamPercentChance); - gameSettings->setFallbackCpuMultiplier(data.cpuReplacementMultiplier); - - gameSettings->setMasterserver_admin(data.masterserver_admin); - gameSettings->setMasterserver_admin_faction_index(data.masterserver_admin_factionIndex); - - gameSettings->setScenario(data.scenario.getString()); - - gameSettings->setGameUUID(data.gameUUID.getString()); - - gameSettings->setNetworkAllowNativeLanguageTechtree((data.networkAllowNativeLanguageTechtree != 0)); -} - -vector > NetworkMessageLaunch::getFactionCRCList() const { - - vector > factionCRCList; - for(unsigned int i = 0; i < (unsigned int)maxFactionCRCCount; ++i) { - if(data.factionNameList[i].getString() != "") { - factionCRCList.push_back(make_pair(data.factionNameList[i].getString(),data.factionCRCList[i])); - } - } - return factionCRCList; -} - -const char * NetworkMessageLaunch::getPackedMessageFormat() const { - return "c256s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60sllllllll60s60s60s60s60s60s60s60sLLL60s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60sLLLLLLLLLLLLLLLLLLLLcccccccccccccccccccccccccccccccccccccccccCccLccll256s60s60s60s60s60s60s60s60sc60s"; + gameSettings->setDescription(data.description.getString()); + gameSettings->setMap(data.map.getString()); + gameSettings->setTileset(data.tileset.getString()); + gameSettings->setTech(data.tech.getString()); + gameSettings->setFactionCount(data.factionCount); + gameSettings->setThisFactionIndex(data.thisFactionIndex); + gameSettings->setDefaultResources((data.defaultResources != 0)); + gameSettings->setDefaultUnits((data.defaultUnits != 0)); + gameSettings->setDefaultVictoryConditions( + (data.defaultVictoryConditions != 0)); + gameSettings->setFogOfWar((data.fogOfWar != 0)); + gameSettings->setAllowObservers((data.allowObservers != 0)); + + gameSettings->setEnableObserverModeAtEndGame( + (data.enableObserverModeAtEndGame != 0)); + gameSettings->setEnableServerControlledAI( + (data.enableServerControlledAI != 0)); + gameSettings->setNetworkFramePeriod(data.networkFramePeriod); + gameSettings->setNetworkPauseGameForLaggedClients( + (data.networkPauseGameForLaggedClients != 0)); + gameSettings->setPathFinderType( + static_cast(data.pathFinderType)); + gameSettings->setFlagTypes1(data.flagTypes1); + + gameSettings->setMapCRC(data.mapCRC); + gameSettings->setMapFilter(data.mapFilter); + gameSettings->setTilesetCRC(data.tilesetCRC); + gameSettings->setTechCRC(data.techCRC); + + vector> factionCRCList; + for (unsigned int i = 0; i < (unsigned int)maxFactionCRCCount; ++i) { + if (data.factionNameList[i].getString() != "") { + factionCRCList.push_back(make_pair(data.factionNameList[i].getString(), + data.factionCRCList[i])); + } + } + gameSettings->setFactionCRCList(factionCRCList); + + // for(int i= 0; i < data.factionCount; ++i) { + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + gameSettings->setFactionTypeName(i, data.factionTypeNames[i].getString()); + gameSettings->setNetworkPlayerName(i, + data.networkPlayerNames[i].getString()); + gameSettings->setNetworkPlayerPlatform( + i, data.networkPlayerPlatform[i].getString()); + gameSettings->setNetworkPlayerStatuses(i, data.networkPlayerStatuses[i]); + gameSettings->setNetworkPlayerLanguages( + i, data.networkPlayerLanguages[i].getString()); + gameSettings->setFactionControl( + i, static_cast(data.factionControls[i])); + gameSettings->setResourceMultiplierIndex(i, + data.resourceMultiplierIndex[i]); + gameSettings->setTeam(i, data.teams[i]); + gameSettings->setStartLocationIndex(i, data.startLocationIndex[i]); + + gameSettings->setNetworkPlayerUUID(i, + data.networkPlayerUUID[i].getString()); + gameSettings->setNetworkPlayerPlatform( + i, data.networkPlayerPlatform[i].getString()); + // printf("Build game settings for index: %d + // [%s]\n",i,data.networkPlayerUUID[i].getString().c_str()); + } + + gameSettings->setAiAcceptSwitchTeamPercentChance( + data.aiAcceptSwitchTeamPercentChance); + gameSettings->setFallbackCpuMultiplier(data.cpuReplacementMultiplier); + + gameSettings->setMasterserver_admin(data.masterserver_admin); + gameSettings->setMasterserver_admin_faction_index( + data.masterserver_admin_factionIndex); + + gameSettings->setScenario(data.scenario.getString()); + + gameSettings->setGameUUID(data.gameUUID.getString()); + + gameSettings->setNetworkAllowNativeLanguageTechtree( + (data.networkAllowNativeLanguageTechtree != 0)); +} + +vector> NetworkMessageLaunch::getFactionCRCList() const { + + vector> factionCRCList; + for (unsigned int i = 0; i < (unsigned int)maxFactionCRCCount; ++i) { + if (data.factionNameList[i].getString() != "") { + factionCRCList.push_back(make_pair(data.factionNameList[i].getString(), + data.factionCRCList[i])); + } + } + return factionCRCList; +} + +const char *NetworkMessageLaunch::getPackedMessageFormat() const { + return "c256s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60s60s6" + "0s60s60s60s60s60sllllllll60s60s60s60s60s60s60s60sLLL60s60s60s60s60s60" + "s60s60s60s60s60s60s60s60s60s60s60s60s60s60sLLLLLLLLLLLLLLLLLLLLcccccc" + "cccccccccccccccccccccccccccccccccccCccLccll256s60s60s60s60s60s60s60s6" + "0sc60s"; } unsigned int NetworkMessageLaunch::getPackedSize() { - static unsigned int result = 0; - if(result == 0) { - Data packedData; - packedData.aiAcceptSwitchTeamPercentChance = 0; - packedData.allowObservers = 0; - packedData.cpuReplacementMultiplier = 0; - packedData.defaultResources = 0; - packedData.defaultUnits = 0; - packedData.defaultVictoryConditions = 0; - packedData.enableObserverModeAtEndGame = 0; - packedData.enableServerControlledAI = 0; - for(unsigned int index =0; index < (unsigned int)maxFactionCRCCount; ++index) { - packedData.factionCRCList[index] = 0; - } - for(unsigned int index =0; index < (unsigned int)GameConstants::maxPlayers; ++index) { - packedData.factionControls[index] = 0; - packedData.networkPlayerStatuses[index] = 0; - packedData.resourceMultiplierIndex[index] = 0; - packedData.startLocationIndex[index] = 0; - packedData.teams[index] = 0; - } - packedData.factionCount = 0; - packedData.flagTypes1 = 0; - packedData.fogOfWar = 0; - packedData.mapCRC = 0; - packedData.mapFilter = 0; - packedData.masterserver_admin = 0; - packedData.masterserver_admin_factionIndex = 0; - messageType = 0; - packedData.networkAllowNativeLanguageTechtree = 0; - packedData.networkFramePeriod = 0; - packedData.networkPauseGameForLaggedClients = 0; - packedData.pathFinderType = 0; - packedData.techCRC = 0; - packedData.thisFactionIndex = 0; - packedData.tilesetCRC = 0; - - unsigned char *buf = new unsigned char[sizeof(packedData)*3]; - result = pack(buf, getPackedMessageFormat(), - messageType, - packedData.description.getBuffer(), - packedData.map.getBuffer(), - packedData.tileset.getBuffer(), - packedData.tech.getBuffer(), - packedData.factionTypeNames[0].getBuffer(), - packedData.factionTypeNames[1].getBuffer(), - packedData.factionTypeNames[2].getBuffer(), - packedData.factionTypeNames[3].getBuffer(), - packedData.factionTypeNames[4].getBuffer(), - packedData.factionTypeNames[5].getBuffer(), - packedData.factionTypeNames[6].getBuffer(), - packedData.factionTypeNames[7].getBuffer(), - packedData.networkPlayerNames[0].getBuffer(), - packedData.networkPlayerNames[1].getBuffer(), - packedData.networkPlayerNames[2].getBuffer(), - packedData.networkPlayerNames[3].getBuffer(), - packedData.networkPlayerNames[4].getBuffer(), - packedData.networkPlayerNames[5].getBuffer(), - packedData.networkPlayerNames[6].getBuffer(), - packedData.networkPlayerNames[7].getBuffer(), - packedData.networkPlayerPlatform[0].getBuffer(), - packedData.networkPlayerPlatform[1].getBuffer(), - packedData.networkPlayerPlatform[2].getBuffer(), - packedData.networkPlayerPlatform[3].getBuffer(), - packedData.networkPlayerPlatform[4].getBuffer(), - packedData.networkPlayerPlatform[5].getBuffer(), - packedData.networkPlayerPlatform[6].getBuffer(), - packedData.networkPlayerPlatform[7].getBuffer(), - packedData.networkPlayerStatuses[0], - packedData.networkPlayerStatuses[1], - packedData.networkPlayerStatuses[2], - packedData.networkPlayerStatuses[3], - packedData.networkPlayerStatuses[4], - packedData.networkPlayerStatuses[5], - packedData.networkPlayerStatuses[6], - packedData.networkPlayerStatuses[7], - packedData.networkPlayerLanguages[0].getBuffer(), - packedData.networkPlayerLanguages[1].getBuffer(), - packedData.networkPlayerLanguages[2].getBuffer(), - packedData.networkPlayerLanguages[3].getBuffer(), - packedData.networkPlayerLanguages[4].getBuffer(), - packedData.networkPlayerLanguages[5].getBuffer(), - packedData.networkPlayerLanguages[6].getBuffer(), - packedData.networkPlayerLanguages[7].getBuffer(), - packedData.mapCRC, - packedData.mapFilter, - packedData.tilesetCRC, - packedData.techCRC, - packedData.factionNameList[0].getBuffer(), - packedData.factionNameList[1].getBuffer(), - packedData.factionNameList[2].getBuffer(), - packedData.factionNameList[3].getBuffer(), - packedData.factionNameList[4].getBuffer(), - packedData.factionNameList[5].getBuffer(), - packedData.factionNameList[6].getBuffer(), - packedData.factionNameList[7].getBuffer(), - packedData.factionNameList[8].getBuffer(), - packedData.factionNameList[9].getBuffer(), - packedData.factionNameList[10].getBuffer(), - packedData.factionNameList[11].getBuffer(), - packedData.factionNameList[12].getBuffer(), - packedData.factionNameList[13].getBuffer(), - packedData.factionNameList[14].getBuffer(), - packedData.factionNameList[15].getBuffer(), - packedData.factionNameList[16].getBuffer(), - packedData.factionNameList[17].getBuffer(), - packedData.factionNameList[18].getBuffer(), - packedData.factionNameList[19].getBuffer(), - packedData.factionCRCList[0], - packedData.factionCRCList[1], - packedData.factionCRCList[2], - packedData.factionCRCList[3], - packedData.factionCRCList[4], - packedData.factionCRCList[5], - packedData.factionCRCList[6], - packedData.factionCRCList[7], - packedData.factionCRCList[8], - packedData.factionCRCList[9], - packedData.factionCRCList[10], - packedData.factionCRCList[11], - packedData.factionCRCList[12], - packedData.factionCRCList[13], - packedData.factionCRCList[14], - packedData.factionCRCList[15], - packedData.factionCRCList[16], - packedData.factionCRCList[17], - packedData.factionCRCList[18], - packedData.factionCRCList[19], - packedData.factionControls[0], - packedData.factionControls[1], - packedData.factionControls[2], - packedData.factionControls[3], - packedData.factionControls[4], - packedData.factionControls[5], - packedData.factionControls[6], - packedData.factionControls[7], - packedData.resourceMultiplierIndex[0], - packedData.resourceMultiplierIndex[1], - packedData.resourceMultiplierIndex[2], - packedData.resourceMultiplierIndex[3], - packedData.resourceMultiplierIndex[4], - packedData.resourceMultiplierIndex[5], - packedData.resourceMultiplierIndex[6], - packedData.resourceMultiplierIndex[7], - packedData.thisFactionIndex, - packedData.factionCount, - packedData.teams[0], - packedData.teams[1], - packedData.teams[2], - packedData.teams[3], - packedData.teams[4], - packedData.teams[5], - packedData.teams[6], - packedData.teams[7], - packedData.startLocationIndex[0], - packedData.startLocationIndex[1], - packedData.startLocationIndex[2], - packedData.startLocationIndex[3], - packedData.startLocationIndex[4], - packedData.startLocationIndex[5], - packedData.startLocationIndex[6], - packedData.startLocationIndex[7], - packedData.defaultResources, - packedData.defaultUnits, - packedData.defaultVictoryConditions, - packedData.fogOfWar, - packedData.allowObservers, - packedData.enableObserverModeAtEndGame, - packedData.enableServerControlledAI, - packedData.networkFramePeriod, - packedData.networkPauseGameForLaggedClients, - packedData.pathFinderType, - packedData.flagTypes1, - packedData.aiAcceptSwitchTeamPercentChance, - packedData.cpuReplacementMultiplier, - packedData.masterserver_admin, - packedData.masterserver_admin_factionIndex, - packedData.scenario.getBuffer(), - packedData.networkPlayerUUID[0].getBuffer(), - packedData.networkPlayerUUID[1].getBuffer(), - packedData.networkPlayerUUID[2].getBuffer(), - packedData.networkPlayerUUID[3].getBuffer(), - packedData.networkPlayerUUID[4].getBuffer(), - packedData.networkPlayerUUID[5].getBuffer(), - packedData.networkPlayerUUID[6].getBuffer(), - packedData.networkPlayerUUID[7].getBuffer(), - packedData.networkAllowNativeLanguageTechtree, - packedData.gameUUID.getBuffer() - ); - delete [] buf; - } - return result; + static unsigned int result = 0; + if (result == 0) { + Data packedData; + packedData.aiAcceptSwitchTeamPercentChance = 0; + packedData.allowObservers = 0; + packedData.cpuReplacementMultiplier = 0; + packedData.defaultResources = 0; + packedData.defaultUnits = 0; + packedData.defaultVictoryConditions = 0; + packedData.enableObserverModeAtEndGame = 0; + packedData.enableServerControlledAI = 0; + for (unsigned int index = 0; index < (unsigned int)maxFactionCRCCount; + ++index) { + packedData.factionCRCList[index] = 0; + } + for (unsigned int index = 0; + index < (unsigned int)GameConstants::maxPlayers; ++index) { + packedData.factionControls[index] = 0; + packedData.networkPlayerStatuses[index] = 0; + packedData.resourceMultiplierIndex[index] = 0; + packedData.startLocationIndex[index] = 0; + packedData.teams[index] = 0; + } + packedData.factionCount = 0; + packedData.flagTypes1 = 0; + packedData.fogOfWar = 0; + packedData.mapCRC = 0; + packedData.mapFilter = 0; + packedData.masterserver_admin = 0; + packedData.masterserver_admin_factionIndex = 0; + messageType = 0; + packedData.networkAllowNativeLanguageTechtree = 0; + packedData.networkFramePeriod = 0; + packedData.networkPauseGameForLaggedClients = 0; + packedData.pathFinderType = 0; + packedData.techCRC = 0; + packedData.thisFactionIndex = 0; + packedData.tilesetCRC = 0; + + unsigned char *buf = new unsigned char[sizeof(packedData) * 3]; + result = pack( + buf, getPackedMessageFormat(), messageType, + packedData.description.getBuffer(), packedData.map.getBuffer(), + packedData.tileset.getBuffer(), packedData.tech.getBuffer(), + packedData.factionTypeNames[0].getBuffer(), + packedData.factionTypeNames[1].getBuffer(), + packedData.factionTypeNames[2].getBuffer(), + packedData.factionTypeNames[3].getBuffer(), + packedData.factionTypeNames[4].getBuffer(), + packedData.factionTypeNames[5].getBuffer(), + packedData.factionTypeNames[6].getBuffer(), + packedData.factionTypeNames[7].getBuffer(), + packedData.networkPlayerNames[0].getBuffer(), + packedData.networkPlayerNames[1].getBuffer(), + packedData.networkPlayerNames[2].getBuffer(), + packedData.networkPlayerNames[3].getBuffer(), + packedData.networkPlayerNames[4].getBuffer(), + packedData.networkPlayerNames[5].getBuffer(), + packedData.networkPlayerNames[6].getBuffer(), + packedData.networkPlayerNames[7].getBuffer(), + packedData.networkPlayerPlatform[0].getBuffer(), + packedData.networkPlayerPlatform[1].getBuffer(), + packedData.networkPlayerPlatform[2].getBuffer(), + packedData.networkPlayerPlatform[3].getBuffer(), + packedData.networkPlayerPlatform[4].getBuffer(), + packedData.networkPlayerPlatform[5].getBuffer(), + packedData.networkPlayerPlatform[6].getBuffer(), + packedData.networkPlayerPlatform[7].getBuffer(), + packedData.networkPlayerStatuses[0], + packedData.networkPlayerStatuses[1], + packedData.networkPlayerStatuses[2], + packedData.networkPlayerStatuses[3], + packedData.networkPlayerStatuses[4], + packedData.networkPlayerStatuses[5], + packedData.networkPlayerStatuses[6], + packedData.networkPlayerStatuses[7], + packedData.networkPlayerLanguages[0].getBuffer(), + packedData.networkPlayerLanguages[1].getBuffer(), + packedData.networkPlayerLanguages[2].getBuffer(), + packedData.networkPlayerLanguages[3].getBuffer(), + packedData.networkPlayerLanguages[4].getBuffer(), + packedData.networkPlayerLanguages[5].getBuffer(), + packedData.networkPlayerLanguages[6].getBuffer(), + packedData.networkPlayerLanguages[7].getBuffer(), packedData.mapCRC, + packedData.mapFilter, packedData.tilesetCRC, packedData.techCRC, + packedData.factionNameList[0].getBuffer(), + packedData.factionNameList[1].getBuffer(), + packedData.factionNameList[2].getBuffer(), + packedData.factionNameList[3].getBuffer(), + packedData.factionNameList[4].getBuffer(), + packedData.factionNameList[5].getBuffer(), + packedData.factionNameList[6].getBuffer(), + packedData.factionNameList[7].getBuffer(), + packedData.factionNameList[8].getBuffer(), + packedData.factionNameList[9].getBuffer(), + packedData.factionNameList[10].getBuffer(), + packedData.factionNameList[11].getBuffer(), + packedData.factionNameList[12].getBuffer(), + packedData.factionNameList[13].getBuffer(), + packedData.factionNameList[14].getBuffer(), + packedData.factionNameList[15].getBuffer(), + packedData.factionNameList[16].getBuffer(), + packedData.factionNameList[17].getBuffer(), + packedData.factionNameList[18].getBuffer(), + packedData.factionNameList[19].getBuffer(), + packedData.factionCRCList[0], packedData.factionCRCList[1], + packedData.factionCRCList[2], packedData.factionCRCList[3], + packedData.factionCRCList[4], packedData.factionCRCList[5], + packedData.factionCRCList[6], packedData.factionCRCList[7], + packedData.factionCRCList[8], packedData.factionCRCList[9], + packedData.factionCRCList[10], packedData.factionCRCList[11], + packedData.factionCRCList[12], packedData.factionCRCList[13], + packedData.factionCRCList[14], packedData.factionCRCList[15], + packedData.factionCRCList[16], packedData.factionCRCList[17], + packedData.factionCRCList[18], packedData.factionCRCList[19], + packedData.factionControls[0], packedData.factionControls[1], + packedData.factionControls[2], packedData.factionControls[3], + packedData.factionControls[4], packedData.factionControls[5], + packedData.factionControls[6], packedData.factionControls[7], + packedData.resourceMultiplierIndex[0], + packedData.resourceMultiplierIndex[1], + packedData.resourceMultiplierIndex[2], + packedData.resourceMultiplierIndex[3], + packedData.resourceMultiplierIndex[4], + packedData.resourceMultiplierIndex[5], + packedData.resourceMultiplierIndex[6], + packedData.resourceMultiplierIndex[7], packedData.thisFactionIndex, + packedData.factionCount, packedData.teams[0], packedData.teams[1], + packedData.teams[2], packedData.teams[3], packedData.teams[4], + packedData.teams[5], packedData.teams[6], packedData.teams[7], + packedData.startLocationIndex[0], packedData.startLocationIndex[1], + packedData.startLocationIndex[2], packedData.startLocationIndex[3], + packedData.startLocationIndex[4], packedData.startLocationIndex[5], + packedData.startLocationIndex[6], packedData.startLocationIndex[7], + packedData.defaultResources, packedData.defaultUnits, + packedData.defaultVictoryConditions, packedData.fogOfWar, + packedData.allowObservers, packedData.enableObserverModeAtEndGame, + packedData.enableServerControlledAI, packedData.networkFramePeriod, + packedData.networkPauseGameForLaggedClients, packedData.pathFinderType, + packedData.flagTypes1, packedData.aiAcceptSwitchTeamPercentChance, + packedData.cpuReplacementMultiplier, packedData.masterserver_admin, + packedData.masterserver_admin_factionIndex, + packedData.scenario.getBuffer(), + packedData.networkPlayerUUID[0].getBuffer(), + packedData.networkPlayerUUID[1].getBuffer(), + packedData.networkPlayerUUID[2].getBuffer(), + packedData.networkPlayerUUID[3].getBuffer(), + packedData.networkPlayerUUID[4].getBuffer(), + packedData.networkPlayerUUID[5].getBuffer(), + packedData.networkPlayerUUID[6].getBuffer(), + packedData.networkPlayerUUID[7].getBuffer(), + packedData.networkAllowNativeLanguageTechtree, + packedData.gameUUID.getBuffer()); + delete[] buf; + } + return result; } void NetworkMessageLaunch::unpackMessage(unsigned char *buf) { - unpack(buf, getPackedMessageFormat(), - &messageType, - data.description.getBuffer(), - data.map.getBuffer(), - data.tileset.getBuffer(), - data.tech.getBuffer(), - data.factionTypeNames[0].getBuffer(), - data.factionTypeNames[1].getBuffer(), - data.factionTypeNames[2].getBuffer(), - data.factionTypeNames[3].getBuffer(), - data.factionTypeNames[4].getBuffer(), - data.factionTypeNames[5].getBuffer(), - data.factionTypeNames[6].getBuffer(), - data.factionTypeNames[7].getBuffer(), - data.networkPlayerNames[0].getBuffer(), - data.networkPlayerNames[1].getBuffer(), - data.networkPlayerNames[2].getBuffer(), - data.networkPlayerNames[3].getBuffer(), - data.networkPlayerNames[4].getBuffer(), - data.networkPlayerNames[5].getBuffer(), - data.networkPlayerNames[6].getBuffer(), - data.networkPlayerNames[7].getBuffer(), - data.networkPlayerPlatform[0].getBuffer(), - data.networkPlayerPlatform[1].getBuffer(), - data.networkPlayerPlatform[2].getBuffer(), - data.networkPlayerPlatform[3].getBuffer(), - data.networkPlayerPlatform[4].getBuffer(), - data.networkPlayerPlatform[5].getBuffer(), - data.networkPlayerPlatform[6].getBuffer(), - data.networkPlayerPlatform[7].getBuffer(), - &data.networkPlayerStatuses[0], - &data.networkPlayerStatuses[1], - &data.networkPlayerStatuses[2], - &data.networkPlayerStatuses[3], - &data.networkPlayerStatuses[4], - &data.networkPlayerStatuses[5], - &data.networkPlayerStatuses[6], - &data.networkPlayerStatuses[7], - data.networkPlayerLanguages[0].getBuffer(), - data.networkPlayerLanguages[1].getBuffer(), - data.networkPlayerLanguages[2].getBuffer(), - data.networkPlayerLanguages[3].getBuffer(), - data.networkPlayerLanguages[4].getBuffer(), - data.networkPlayerLanguages[5].getBuffer(), - data.networkPlayerLanguages[6].getBuffer(), - data.networkPlayerLanguages[7].getBuffer(), - &data.mapFilter, - &data.mapCRC, - &data.tilesetCRC, - &data.techCRC, - data.factionNameList[0].getBuffer(), - data.factionNameList[1].getBuffer(), - data.factionNameList[2].getBuffer(), - data.factionNameList[3].getBuffer(), - data.factionNameList[4].getBuffer(), - data.factionNameList[5].getBuffer(), - data.factionNameList[6].getBuffer(), - data.factionNameList[7].getBuffer(), - data.factionNameList[8].getBuffer(), - data.factionNameList[9].getBuffer(), - data.factionNameList[10].getBuffer(), - data.factionNameList[11].getBuffer(), - data.factionNameList[12].getBuffer(), - data.factionNameList[13].getBuffer(), - data.factionNameList[14].getBuffer(), - data.factionNameList[15].getBuffer(), - data.factionNameList[16].getBuffer(), - data.factionNameList[17].getBuffer(), - data.factionNameList[18].getBuffer(), - data.factionNameList[19].getBuffer(), - &data.factionCRCList[0], - &data.factionCRCList[1], - &data.factionCRCList[2], - &data.factionCRCList[3], - &data.factionCRCList[4], - &data.factionCRCList[5], - &data.factionCRCList[6], - &data.factionCRCList[7], - &data.factionCRCList[8], - &data.factionCRCList[9], - &data.factionCRCList[10], - &data.factionCRCList[11], - &data.factionCRCList[12], - &data.factionCRCList[13], - &data.factionCRCList[14], - &data.factionCRCList[15], - &data.factionCRCList[16], - &data.factionCRCList[17], - &data.factionCRCList[18], - &data.factionCRCList[19], - &data.factionControls[0], - &data.factionControls[1], - &data.factionControls[2], - &data.factionControls[3], - &data.factionControls[4], - &data.factionControls[5], - &data.factionControls[6], - &data.factionControls[7], - &data.resourceMultiplierIndex[0], - &data.resourceMultiplierIndex[1], - &data.resourceMultiplierIndex[2], - &data.resourceMultiplierIndex[3], - &data.resourceMultiplierIndex[4], - &data.resourceMultiplierIndex[5], - &data.resourceMultiplierIndex[6], - &data.resourceMultiplierIndex[7], - &data.thisFactionIndex, - &data.factionCount, - &data.teams[0], - &data.teams[1], - &data.teams[2], - &data.teams[3], - &data.teams[4], - &data.teams[5], - &data.teams[6], - &data.teams[7], - &data.startLocationIndex[0], - &data.startLocationIndex[1], - &data.startLocationIndex[2], - &data.startLocationIndex[3], - &data.startLocationIndex[4], - &data.startLocationIndex[5], - &data.startLocationIndex[6], - &data.startLocationIndex[7], - &data.defaultResources, - &data.defaultUnits, - &data.defaultVictoryConditions, - &data.fogOfWar, - &data.allowObservers, - &data.enableObserverModeAtEndGame, - &data.enableServerControlledAI, - &data.networkFramePeriod, - &data.networkPauseGameForLaggedClients, - &data.pathFinderType, - &data.flagTypes1, - &data.aiAcceptSwitchTeamPercentChance, - &data.cpuReplacementMultiplier, - &data.masterserver_admin, - &data.masterserver_admin_factionIndex, - data.scenario.getBuffer(), - data.networkPlayerUUID[0].getBuffer(), - data.networkPlayerUUID[1].getBuffer(), - data.networkPlayerUUID[2].getBuffer(), - data.networkPlayerUUID[3].getBuffer(), - data.networkPlayerUUID[4].getBuffer(), - data.networkPlayerUUID[5].getBuffer(), - data.networkPlayerUUID[6].getBuffer(), - data.networkPlayerUUID[7].getBuffer(), - &data.networkAllowNativeLanguageTechtree, - data.gameUUID.getBuffer() - ); -} - -unsigned char * NetworkMessageLaunch::packMessage() { - unsigned char *buf = new unsigned char[getPackedSize()+1]; - pack(buf, getPackedMessageFormat(), - messageType, - data.description.getBuffer(), - data.map.getBuffer(), - data.tileset.getBuffer(), - data.tech.getBuffer(), - data.factionTypeNames[0].getBuffer(), - data.factionTypeNames[1].getBuffer(), - data.factionTypeNames[2].getBuffer(), - data.factionTypeNames[3].getBuffer(), - data.factionTypeNames[4].getBuffer(), - data.factionTypeNames[5].getBuffer(), - data.factionTypeNames[6].getBuffer(), - data.factionTypeNames[7].getBuffer(), - data.networkPlayerNames[0].getBuffer(), - data.networkPlayerNames[1].getBuffer(), - data.networkPlayerNames[2].getBuffer(), - data.networkPlayerNames[3].getBuffer(), - data.networkPlayerNames[4].getBuffer(), - data.networkPlayerNames[5].getBuffer(), - data.networkPlayerNames[6].getBuffer(), - data.networkPlayerNames[7].getBuffer(), - data.networkPlayerPlatform[0].getBuffer(), - data.networkPlayerPlatform[1].getBuffer(), - data.networkPlayerPlatform[2].getBuffer(), - data.networkPlayerPlatform[3].getBuffer(), - data.networkPlayerPlatform[4].getBuffer(), - data.networkPlayerPlatform[5].getBuffer(), - data.networkPlayerPlatform[6].getBuffer(), - data.networkPlayerPlatform[7].getBuffer(), - data.networkPlayerStatuses[0], - data.networkPlayerStatuses[1], - data.networkPlayerStatuses[2], - data.networkPlayerStatuses[3], - data.networkPlayerStatuses[4], - data.networkPlayerStatuses[5], - data.networkPlayerStatuses[6], - data.networkPlayerStatuses[7], - data.networkPlayerLanguages[0].getBuffer(), - data.networkPlayerLanguages[1].getBuffer(), - data.networkPlayerLanguages[2].getBuffer(), - data.networkPlayerLanguages[3].getBuffer(), - data.networkPlayerLanguages[4].getBuffer(), - data.networkPlayerLanguages[5].getBuffer(), - data.networkPlayerLanguages[6].getBuffer(), - data.networkPlayerLanguages[7].getBuffer(), - data.mapFilter, - data.mapCRC, - data.tilesetCRC, - data.techCRC, - data.factionNameList[0].getBuffer(), - data.factionNameList[1].getBuffer(), - data.factionNameList[2].getBuffer(), - data.factionNameList[3].getBuffer(), - data.factionNameList[4].getBuffer(), - data.factionNameList[5].getBuffer(), - data.factionNameList[6].getBuffer(), - data.factionNameList[7].getBuffer(), - data.factionNameList[8].getBuffer(), - data.factionNameList[9].getBuffer(), - data.factionNameList[10].getBuffer(), - data.factionNameList[11].getBuffer(), - data.factionNameList[12].getBuffer(), - data.factionNameList[13].getBuffer(), - data.factionNameList[14].getBuffer(), - data.factionNameList[15].getBuffer(), - data.factionNameList[16].getBuffer(), - data.factionNameList[17].getBuffer(), - data.factionNameList[18].getBuffer(), - data.factionNameList[19].getBuffer(), - data.factionCRCList[0], - data.factionCRCList[1], - data.factionCRCList[2], - data.factionCRCList[3], - data.factionCRCList[4], - data.factionCRCList[5], - data.factionCRCList[6], - data.factionCRCList[7], - data.factionCRCList[8], - data.factionCRCList[9], - data.factionCRCList[10], - data.factionCRCList[11], - data.factionCRCList[12], - data.factionCRCList[13], - data.factionCRCList[14], - data.factionCRCList[15], - data.factionCRCList[16], - data.factionCRCList[17], - data.factionCRCList[18], - data.factionCRCList[19], - data.factionControls[0], - data.factionControls[1], - data.factionControls[2], - data.factionControls[3], - data.factionControls[4], - data.factionControls[5], - data.factionControls[6], - data.factionControls[7], - data.resourceMultiplierIndex[0], - data.resourceMultiplierIndex[1], - data.resourceMultiplierIndex[2], - data.resourceMultiplierIndex[3], - data.resourceMultiplierIndex[4], - data.resourceMultiplierIndex[5], - data.resourceMultiplierIndex[6], - data.resourceMultiplierIndex[7], - data.thisFactionIndex, - data.factionCount, - data.teams[0], - data.teams[1], - data.teams[2], - data.teams[3], - data.teams[4], - data.teams[5], - data.teams[6], - data.teams[7], - data.startLocationIndex[0], - data.startLocationIndex[1], - data.startLocationIndex[2], - data.startLocationIndex[3], - data.startLocationIndex[4], - data.startLocationIndex[5], - data.startLocationIndex[6], - data.startLocationIndex[7], - data.defaultResources, - data.defaultUnits, - data.defaultVictoryConditions, - data.fogOfWar, - data.allowObservers, - data.enableObserverModeAtEndGame, - data.enableServerControlledAI, - data.networkFramePeriod, - data.networkPauseGameForLaggedClients, - data.pathFinderType, - data.flagTypes1, - data.aiAcceptSwitchTeamPercentChance, - data.cpuReplacementMultiplier, - data.masterserver_admin, - data.masterserver_admin_factionIndex, - data.scenario.getBuffer(), - data.networkPlayerUUID[0].getBuffer(), - data.networkPlayerUUID[1].getBuffer(), - data.networkPlayerUUID[2].getBuffer(), - data.networkPlayerUUID[3].getBuffer(), - data.networkPlayerUUID[4].getBuffer(), - data.networkPlayerUUID[5].getBuffer(), - data.networkPlayerUUID[6].getBuffer(), - data.networkPlayerUUID[7].getBuffer(), - data.networkAllowNativeLanguageTechtree, - data.gameUUID.getBuffer() - ); - return buf; -} - -bool NetworkMessageLaunch::receive(Socket* socket, NetworkMessageType type) { - bool result = receive(socket); - messageType = type; - return result; -} - -bool NetworkMessageLaunch::receive(Socket* socket) { - //printf("Receive NetworkMessageLaunch\n"); - bool result = false; - - Chrono chrono; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); - - if(useOldProtocol == true) { - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - //printf("UnCompressed launch packet before read compressed size\n"); - result = NetworkMessage::receive(socket, &compressedLength, sizeof(compressedLength), true); - //printf("UnCompressed launch packet after read compressed size: %d\n",compressedLength); - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - if(result == true && compressedLength > 0 && socket != NULL && socket->isSocketValid()) { - //printf("UnCompressed launch packet before: %u after: %d\n",compressedLength,(int)getDataSize()); - - unsigned char *compressedMessage = new unsigned char[compressedLength+1]; - memset(compressedMessage,0,compressedLength+1); - - result = NetworkMessage::receive(socket, compressedMessage, compressedLength, true); - //printf("UnCompressed launch packet READ returned: %d\n",result); - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - if(result == true && socket != NULL && socket->isSocketValid()) { - //printf("UnCompressed launch packet before decompress\n"); - -// printf("\n"); -// const unsigned char *buf = static_cast(compressedMessage); -// for(unsigned int index = 0; index < (unsigned int)compressedLength; ++index) { -// printf("%u[%X][%d] ",index,buf[index],buf[index]); -// if(index % 10 == 0) { -// printf("\n"); -// } -// } -// printf("\n"); - - unsigned long buffer_size = compressedLength; - std::pair decompressedBuffer = - Shared::CompressionUtil::extractMemoryToMemory(compressedMessage, buffer_size, maxNetworkMessageSize); - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - unsigned char *decompressed_buffer = decompressedBuffer.first; - memcpy(&data,decompressed_buffer,decompressedBuffer.second); - delete [] decompressed_buffer; - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - //printf("SUCCESS UnCompressed launch packet before: %u after: %lu\n",compressedLength,decompressedBuffer.second); - } - delete [] compressedMessage; - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - } - else if(result == true) { - //printf("Normal launch packet detected (uncompressed)\n"); - result = NetworkMessage::receive(socket, &data, sizeof(data), true); - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - } - } - else { - unsigned char *buf = new unsigned char[getPackedSize()+1]; - result = NetworkMessage::receive(socket, buf, getPackedSize(), true); - unpackMessage(buf); - //printf("Got packet size = %u data.messageType = %d\n%s\n",getPackedSize(),data.messageType,buf); - delete [] buf; - } - fromEndian(); - - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); - - data.description.nullTerminate(); - data.map.nullTerminate(); - data.tileset.nullTerminate(); - data.tech.nullTerminate(); - for(int i= 0; i < GameConstants::maxPlayers; ++i){ - data.factionTypeNames[i].nullTerminate(); - data.networkPlayerNames[i].nullTerminate(); - data.networkPlayerPlatform[i].nullTerminate(); - data.networkPlayerLanguages[i].nullTerminate(); - - data.networkPlayerUUID[i].nullTerminate(); - } - for(unsigned int i = 0; i < (unsigned int)maxFactionCRCCount; ++i) { - data.factionNameList[i].nullTerminate(); - } - - data.scenario.nullTerminate(); - - data.gameUUID.nullTerminate(); - - 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()); - - //for(int i= 0; i < GameConstants::maxPlayers; ++i){ - // printf("Receive index: %d resource multiplier index: %d sizeof(data): %d\n",i,data.resourceMultiplierIndex[i],sizeof(data)); - //} - - return result; -} - -unsigned char * NetworkMessageLaunch::getData() { - unsigned char *buffer = new unsigned char[getDataSize()]; - memcpy(buffer,&data,getDataSize()); - return buffer; -} - -std::pair NetworkMessageLaunch::getCompressedMessage() { - unsigned char *buffer = this->getData(); - std::pair result = - Shared::CompressionUtil::compressMemoryToMemory(buffer,getDataSize()); - delete [] buffer; - return result; -} - -void NetworkMessageLaunch::send(Socket* socket) { - //printf("Sending NetworkMessageLaunch\n"); - - //for(int i= 0; i < GameConstants::maxPlayers; ++i){ - // printf("Send index: %d resource multiplier index: %d sizeof(data): %d\n",i,data.resourceMultiplierIndex[i],sizeof(data)); - //} - - if(messageType == nmtLaunch) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] nmtLaunch\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] messageType = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,messageType); - } - toEndian(); - - if(useOldProtocol == true) { - ////NetworkMessage::send(socket, &messageType, sizeof(messageType)); - //NetworkMessage::send(socket, &data, sizeof(data), messageType); - - std::pair compressionResult = getCompressedMessage(); - compressedLength = compressionResult.second; - //printf("Compressed launch packet before: %d after: %lu\n",(int)getDataSize(),compressionResult.second); - -// printf("\n"); -// const unsigned char *buf = static_cast(compressionResult.first); -// for(unsigned int index = 0; index < (unsigned int)compressionResult.second; ++index) { -// printf("%u[%X][%d] ",index,buf[index],buf[index]); -// if(index % 10 == 0) { -// printf("\n"); -// } -// } -// printf("\n"); - -/* - NetworkMessage::send(socket, &messageType, sizeof(messageType)); - if(socket != NULL && socket->isSocketValid()) { - NetworkMessage::send(socket, &compressedLength, sizeof(compressedLength)); - if(socket != NULL && socket->isSocketValid()) { - NetworkMessage::send(socket, compressionResult.first, compressionResult.second); - } - } -*/ - NetworkMessage::send(socket, compressionResult.first, compressionResult.second, messageType, compressedLength); - delete [] compressionResult.first; - //printf("Compressed launch packet SENT\n"); - } - else { - unsigned char *buf = packMessage(); - //printf("Send packet size = %u data.messageType = %d\n[%s]\n",getPackedSize(),data.messageType,buf); - NetworkMessage::send(socket, buf, getPackedSize()); - delete [] buf; - } + unpack( + buf, getPackedMessageFormat(), &messageType, data.description.getBuffer(), + data.map.getBuffer(), data.tileset.getBuffer(), data.tech.getBuffer(), + data.factionTypeNames[0].getBuffer(), + data.factionTypeNames[1].getBuffer(), + data.factionTypeNames[2].getBuffer(), + data.factionTypeNames[3].getBuffer(), + data.factionTypeNames[4].getBuffer(), + data.factionTypeNames[5].getBuffer(), + data.factionTypeNames[6].getBuffer(), + data.factionTypeNames[7].getBuffer(), + data.networkPlayerNames[0].getBuffer(), + data.networkPlayerNames[1].getBuffer(), + data.networkPlayerNames[2].getBuffer(), + data.networkPlayerNames[3].getBuffer(), + data.networkPlayerNames[4].getBuffer(), + data.networkPlayerNames[5].getBuffer(), + data.networkPlayerNames[6].getBuffer(), + data.networkPlayerNames[7].getBuffer(), + data.networkPlayerPlatform[0].getBuffer(), + data.networkPlayerPlatform[1].getBuffer(), + data.networkPlayerPlatform[2].getBuffer(), + data.networkPlayerPlatform[3].getBuffer(), + data.networkPlayerPlatform[4].getBuffer(), + data.networkPlayerPlatform[5].getBuffer(), + data.networkPlayerPlatform[6].getBuffer(), + data.networkPlayerPlatform[7].getBuffer(), &data.networkPlayerStatuses[0], + &data.networkPlayerStatuses[1], &data.networkPlayerStatuses[2], + &data.networkPlayerStatuses[3], &data.networkPlayerStatuses[4], + &data.networkPlayerStatuses[5], &data.networkPlayerStatuses[6], + &data.networkPlayerStatuses[7], + data.networkPlayerLanguages[0].getBuffer(), + data.networkPlayerLanguages[1].getBuffer(), + data.networkPlayerLanguages[2].getBuffer(), + data.networkPlayerLanguages[3].getBuffer(), + data.networkPlayerLanguages[4].getBuffer(), + data.networkPlayerLanguages[5].getBuffer(), + data.networkPlayerLanguages[6].getBuffer(), + data.networkPlayerLanguages[7].getBuffer(), &data.mapFilter, &data.mapCRC, + &data.tilesetCRC, &data.techCRC, data.factionNameList[0].getBuffer(), + data.factionNameList[1].getBuffer(), data.factionNameList[2].getBuffer(), + data.factionNameList[3].getBuffer(), data.factionNameList[4].getBuffer(), + data.factionNameList[5].getBuffer(), data.factionNameList[6].getBuffer(), + data.factionNameList[7].getBuffer(), data.factionNameList[8].getBuffer(), + data.factionNameList[9].getBuffer(), data.factionNameList[10].getBuffer(), + data.factionNameList[11].getBuffer(), + data.factionNameList[12].getBuffer(), + data.factionNameList[13].getBuffer(), + data.factionNameList[14].getBuffer(), + data.factionNameList[15].getBuffer(), + data.factionNameList[16].getBuffer(), + data.factionNameList[17].getBuffer(), + data.factionNameList[18].getBuffer(), + data.factionNameList[19].getBuffer(), &data.factionCRCList[0], + &data.factionCRCList[1], &data.factionCRCList[2], &data.factionCRCList[3], + &data.factionCRCList[4], &data.factionCRCList[5], &data.factionCRCList[6], + &data.factionCRCList[7], &data.factionCRCList[8], &data.factionCRCList[9], + &data.factionCRCList[10], &data.factionCRCList[11], + &data.factionCRCList[12], &data.factionCRCList[13], + &data.factionCRCList[14], &data.factionCRCList[15], + &data.factionCRCList[16], &data.factionCRCList[17], + &data.factionCRCList[18], &data.factionCRCList[19], + &data.factionControls[0], &data.factionControls[1], + &data.factionControls[2], &data.factionControls[3], + &data.factionControls[4], &data.factionControls[5], + &data.factionControls[6], &data.factionControls[7], + &data.resourceMultiplierIndex[0], &data.resourceMultiplierIndex[1], + &data.resourceMultiplierIndex[2], &data.resourceMultiplierIndex[3], + &data.resourceMultiplierIndex[4], &data.resourceMultiplierIndex[5], + &data.resourceMultiplierIndex[6], &data.resourceMultiplierIndex[7], + &data.thisFactionIndex, &data.factionCount, &data.teams[0], + &data.teams[1], &data.teams[2], &data.teams[3], &data.teams[4], + &data.teams[5], &data.teams[6], &data.teams[7], + &data.startLocationIndex[0], &data.startLocationIndex[1], + &data.startLocationIndex[2], &data.startLocationIndex[3], + &data.startLocationIndex[4], &data.startLocationIndex[5], + &data.startLocationIndex[6], &data.startLocationIndex[7], + &data.defaultResources, &data.defaultUnits, + &data.defaultVictoryConditions, &data.fogOfWar, &data.allowObservers, + &data.enableObserverModeAtEndGame, &data.enableServerControlledAI, + &data.networkFramePeriod, &data.networkPauseGameForLaggedClients, + &data.pathFinderType, &data.flagTypes1, + &data.aiAcceptSwitchTeamPercentChance, &data.cpuReplacementMultiplier, + &data.masterserver_admin, &data.masterserver_admin_factionIndex, + data.scenario.getBuffer(), data.networkPlayerUUID[0].getBuffer(), + data.networkPlayerUUID[1].getBuffer(), + data.networkPlayerUUID[2].getBuffer(), + data.networkPlayerUUID[3].getBuffer(), + data.networkPlayerUUID[4].getBuffer(), + data.networkPlayerUUID[5].getBuffer(), + data.networkPlayerUUID[6].getBuffer(), + data.networkPlayerUUID[7].getBuffer(), + &data.networkAllowNativeLanguageTechtree, data.gameUUID.getBuffer()); +} + +unsigned char *NetworkMessageLaunch::packMessage() { + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + pack( + buf, getPackedMessageFormat(), messageType, data.description.getBuffer(), + data.map.getBuffer(), data.tileset.getBuffer(), data.tech.getBuffer(), + data.factionTypeNames[0].getBuffer(), + data.factionTypeNames[1].getBuffer(), + data.factionTypeNames[2].getBuffer(), + data.factionTypeNames[3].getBuffer(), + data.factionTypeNames[4].getBuffer(), + data.factionTypeNames[5].getBuffer(), + data.factionTypeNames[6].getBuffer(), + data.factionTypeNames[7].getBuffer(), + data.networkPlayerNames[0].getBuffer(), + data.networkPlayerNames[1].getBuffer(), + data.networkPlayerNames[2].getBuffer(), + data.networkPlayerNames[3].getBuffer(), + data.networkPlayerNames[4].getBuffer(), + data.networkPlayerNames[5].getBuffer(), + data.networkPlayerNames[6].getBuffer(), + data.networkPlayerNames[7].getBuffer(), + data.networkPlayerPlatform[0].getBuffer(), + data.networkPlayerPlatform[1].getBuffer(), + data.networkPlayerPlatform[2].getBuffer(), + data.networkPlayerPlatform[3].getBuffer(), + data.networkPlayerPlatform[4].getBuffer(), + data.networkPlayerPlatform[5].getBuffer(), + data.networkPlayerPlatform[6].getBuffer(), + data.networkPlayerPlatform[7].getBuffer(), data.networkPlayerStatuses[0], + data.networkPlayerStatuses[1], data.networkPlayerStatuses[2], + data.networkPlayerStatuses[3], data.networkPlayerStatuses[4], + data.networkPlayerStatuses[5], data.networkPlayerStatuses[6], + data.networkPlayerStatuses[7], data.networkPlayerLanguages[0].getBuffer(), + data.networkPlayerLanguages[1].getBuffer(), + data.networkPlayerLanguages[2].getBuffer(), + data.networkPlayerLanguages[3].getBuffer(), + data.networkPlayerLanguages[4].getBuffer(), + data.networkPlayerLanguages[5].getBuffer(), + data.networkPlayerLanguages[6].getBuffer(), + data.networkPlayerLanguages[7].getBuffer(), data.mapFilter, data.mapCRC, + data.tilesetCRC, data.techCRC, data.factionNameList[0].getBuffer(), + data.factionNameList[1].getBuffer(), data.factionNameList[2].getBuffer(), + data.factionNameList[3].getBuffer(), data.factionNameList[4].getBuffer(), + data.factionNameList[5].getBuffer(), data.factionNameList[6].getBuffer(), + data.factionNameList[7].getBuffer(), data.factionNameList[8].getBuffer(), + data.factionNameList[9].getBuffer(), data.factionNameList[10].getBuffer(), + data.factionNameList[11].getBuffer(), + data.factionNameList[12].getBuffer(), + data.factionNameList[13].getBuffer(), + data.factionNameList[14].getBuffer(), + data.factionNameList[15].getBuffer(), + data.factionNameList[16].getBuffer(), + data.factionNameList[17].getBuffer(), + data.factionNameList[18].getBuffer(), + data.factionNameList[19].getBuffer(), data.factionCRCList[0], + data.factionCRCList[1], data.factionCRCList[2], data.factionCRCList[3], + data.factionCRCList[4], data.factionCRCList[5], data.factionCRCList[6], + data.factionCRCList[7], data.factionCRCList[8], data.factionCRCList[9], + data.factionCRCList[10], data.factionCRCList[11], data.factionCRCList[12], + data.factionCRCList[13], data.factionCRCList[14], data.factionCRCList[15], + data.factionCRCList[16], data.factionCRCList[17], data.factionCRCList[18], + data.factionCRCList[19], data.factionControls[0], data.factionControls[1], + data.factionControls[2], data.factionControls[3], data.factionControls[4], + data.factionControls[5], data.factionControls[6], data.factionControls[7], + data.resourceMultiplierIndex[0], data.resourceMultiplierIndex[1], + data.resourceMultiplierIndex[2], data.resourceMultiplierIndex[3], + data.resourceMultiplierIndex[4], data.resourceMultiplierIndex[5], + data.resourceMultiplierIndex[6], data.resourceMultiplierIndex[7], + data.thisFactionIndex, data.factionCount, data.teams[0], data.teams[1], + data.teams[2], data.teams[3], data.teams[4], data.teams[5], data.teams[6], + data.teams[7], data.startLocationIndex[0], data.startLocationIndex[1], + data.startLocationIndex[2], data.startLocationIndex[3], + data.startLocationIndex[4], data.startLocationIndex[5], + data.startLocationIndex[6], data.startLocationIndex[7], + data.defaultResources, data.defaultUnits, data.defaultVictoryConditions, + data.fogOfWar, data.allowObservers, data.enableObserverModeAtEndGame, + data.enableServerControlledAI, data.networkFramePeriod, + data.networkPauseGameForLaggedClients, data.pathFinderType, + data.flagTypes1, data.aiAcceptSwitchTeamPercentChance, + data.cpuReplacementMultiplier, data.masterserver_admin, + data.masterserver_admin_factionIndex, data.scenario.getBuffer(), + data.networkPlayerUUID[0].getBuffer(), + data.networkPlayerUUID[1].getBuffer(), + data.networkPlayerUUID[2].getBuffer(), + data.networkPlayerUUID[3].getBuffer(), + data.networkPlayerUUID[4].getBuffer(), + data.networkPlayerUUID[5].getBuffer(), + data.networkPlayerUUID[6].getBuffer(), + data.networkPlayerUUID[7].getBuffer(), + data.networkAllowNativeLanguageTechtree, data.gameUUID.getBuffer()); + return buf; +} + +bool NetworkMessageLaunch::receive(Socket *socket, NetworkMessageType type) { + bool result = receive(socket); + messageType = type; + return result; +} + +bool NetworkMessageLaunch::receive(Socket *socket) { + // printf("Receive NetworkMessageLaunch\n"); + bool result = false; + + Chrono chrono; + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) + chrono.start(); + + if (useOldProtocol == true) { + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // printf("UnCompressed launch packet before read compressed size\n"); + result = NetworkMessage::receive(socket, &compressedLength, + sizeof(compressedLength), true); + // printf("UnCompressed launch packet after read compressed size: + // %d\n",compressedLength); + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (result == true && compressedLength > 0 && socket != NULL && + socket->isSocketValid()) { + // printf("UnCompressed launch packet before: %u after: + // %d\n",compressedLength,(int)getDataSize()); + + unsigned char *compressedMessage = + new unsigned char[compressedLength + 1]; + memset(compressedMessage, 0, compressedLength + 1); + + result = NetworkMessage::receive(socket, compressedMessage, + compressedLength, true); + // printf("UnCompressed launch packet READ returned: %d\n",result); + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + if (result == true && socket != NULL && socket->isSocketValid()) { + // printf("UnCompressed launch packet before decompress\n"); + + // printf("\n"); + // const unsigned char *buf = + //static_cast(compressedMessage); + // for(unsigned int index = 0; index < (unsigned int)compressedLength; + //++index) { printf("%u[%X][%d] + //",index,buf[index],buf[index]); if(index + //% 10 == 0) { printf("\n"); + // } + // } + // printf("\n"); + + unsigned long buffer_size = compressedLength; + std::pair decompressedBuffer = + Shared::CompressionUtil::extractMemoryToMemory( + compressedMessage, buffer_size, maxNetworkMessageSize); + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + unsigned char *decompressed_buffer = decompressedBuffer.first; + memcpy(&data, decompressed_buffer, decompressedBuffer.second); + delete[] decompressed_buffer; + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + // printf("SUCCESS UnCompressed launch packet before: %u after: + // %lu\n",compressedLength,decompressedBuffer.second); + } + delete[] compressedMessage; + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + } else if (result == true) { + // printf("Normal launch packet detected (uncompressed)\n"); + result = NetworkMessage::receive(socket, &data, sizeof(data), true); + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + } + } else { + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + result = NetworkMessage::receive(socket, buf, getPackedSize(), true); + unpackMessage(buf); + // printf("Got packet size = %u data.messageType = + // %d\n%s\n",getPackedSize(),data.messageType,buf); + delete[] buf; + } + fromEndian(); + + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + chrono.start(); + + data.description.nullTerminate(); + data.map.nullTerminate(); + data.tileset.nullTerminate(); + data.tech.nullTerminate(); + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + data.factionTypeNames[i].nullTerminate(); + data.networkPlayerNames[i].nullTerminate(); + data.networkPlayerPlatform[i].nullTerminate(); + data.networkPlayerLanguages[i].nullTerminate(); + + data.networkPlayerUUID[i].nullTerminate(); + } + for (unsigned int i = 0; i < (unsigned int)maxFactionCRCCount; ++i) { + data.factionNameList[i].nullTerminate(); + } + + data.scenario.nullTerminate(); + + data.gameUUID.nullTerminate(); + + 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()); + + // for(int i= 0; i < GameConstants::maxPlayers; ++i){ + // printf("Receive index: %d resource multiplier index: %d sizeof(data): + //%d\n",i,data.resourceMultiplierIndex[i],sizeof(data)); + // } + + return result; +} + +unsigned char *NetworkMessageLaunch::getData() { + unsigned char *buffer = new unsigned char[getDataSize()]; + memcpy(buffer, &data, getDataSize()); + return buffer; +} + +std::pair +NetworkMessageLaunch::getCompressedMessage() { + unsigned char *buffer = this->getData(); + std::pair result = + Shared::CompressionUtil::compressMemoryToMemory(buffer, getDataSize()); + delete[] buffer; + return result; +} + +void NetworkMessageLaunch::send(Socket *socket) { + // printf("Sending NetworkMessageLaunch\n"); + + // for(int i= 0; i < GameConstants::maxPlayers; ++i){ + // printf("Send index: %d resource multiplier index: %d sizeof(data): + //%d\n",i,data.resourceMultiplierIndex[i],sizeof(data)); + // } + + if (messageType == nmtLaunch) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] nmtLaunch\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] messageType = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, messageType); + } + toEndian(); + + if (useOldProtocol == true) { + ////NetworkMessage::send(socket, &messageType, sizeof(messageType)); + // NetworkMessage::send(socket, &data, sizeof(data), messageType); + + std::pair compressionResult = + getCompressedMessage(); + compressedLength = compressionResult.second; + // printf("Compressed launch packet before: %d after: + // %lu\n",(int)getDataSize(),compressionResult.second); + + // printf("\n"); + // const unsigned char *buf = static_cast(compressionResult.first); for(unsigned int index = 0; index < + //(unsigned int)compressionResult.second; ++index) { + // printf("%u[%X][%d] + //",index,buf[index],buf[index]); if(index % 10 == 0) { + //printf("\n"); + // } + // } + // printf("\n"); + + /* + NetworkMessage::send(socket, &messageType, + sizeof(messageType)); if(socket != NULL && socket->isSocketValid()) { + NetworkMessage::send(socket, &compressedLength, + sizeof(compressedLength)); if(socket != NULL && socket->isSocketValid()) + { NetworkMessage::send(socket, compressionResult.first, + compressionResult.second); + } + } + */ + NetworkMessage::send(socket, compressionResult.first, + compressionResult.second, messageType, + compressedLength); + delete[] compressionResult.first; + // printf("Compressed launch packet SENT\n"); + } else { + unsigned char *buf = packMessage(); + // printf("Send packet size = %u data.messageType = + // %d\n[%s]\n",getPackedSize(),data.messageType,buf); + NetworkMessage::send(socket, buf, getPackedSize()); + delete[] buf; + } } void NetworkMessageLaunch::toEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); - for(int i= 0; i < GameConstants::maxPlayers; ++i){ - data.networkPlayerStatuses[i] = Shared::PlatformByteOrder::toCommonEndian(data.networkPlayerStatuses[i]); - data.factionCRCList[i] = Shared::PlatformByteOrder::toCommonEndian(data.factionCRCList[i]); - data.factionControls[i] = Shared::PlatformByteOrder::toCommonEndian(data.factionControls[i]); - data.resourceMultiplierIndex[i] = Shared::PlatformByteOrder::toCommonEndian(data.resourceMultiplierIndex[i]); - data.teams[i] = Shared::PlatformByteOrder::toCommonEndian(data.teams[i]); - data.startLocationIndex[i] = Shared::PlatformByteOrder::toCommonEndian(data.startLocationIndex[i]); - } - data.mapFilter = Shared::PlatformByteOrder::toCommonEndian(data.mapFilter); - data.mapCRC = Shared::PlatformByteOrder::toCommonEndian(data.mapCRC); - data.tilesetCRC = Shared::PlatformByteOrder::toCommonEndian(data.tilesetCRC); - data.techCRC = Shared::PlatformByteOrder::toCommonEndian(data.techCRC); - data.thisFactionIndex = Shared::PlatformByteOrder::toCommonEndian(data.thisFactionIndex); - data.factionCount = Shared::PlatformByteOrder::toCommonEndian(data.factionCount); - data.defaultResources = Shared::PlatformByteOrder::toCommonEndian(data.defaultResources); - data.defaultUnits = Shared::PlatformByteOrder::toCommonEndian(data.defaultUnits); - - data.defaultVictoryConditions = Shared::PlatformByteOrder::toCommonEndian(data.defaultVictoryConditions); - data.fogOfWar = Shared::PlatformByteOrder::toCommonEndian(data.fogOfWar); - data.allowObservers = Shared::PlatformByteOrder::toCommonEndian(data.allowObservers); - data.enableObserverModeAtEndGame = Shared::PlatformByteOrder::toCommonEndian(data.enableObserverModeAtEndGame); - data.enableServerControlledAI = Shared::PlatformByteOrder::toCommonEndian(data.enableServerControlledAI); - data.networkFramePeriod = Shared::PlatformByteOrder::toCommonEndian(data.networkFramePeriod); - data.networkPauseGameForLaggedClients = Shared::PlatformByteOrder::toCommonEndian(data.networkPauseGameForLaggedClients); - data.pathFinderType = Shared::PlatformByteOrder::toCommonEndian(data.pathFinderType); - data.flagTypes1 = Shared::PlatformByteOrder::toCommonEndian(data.flagTypes1); - - data.aiAcceptSwitchTeamPercentChance = Shared::PlatformByteOrder::toCommonEndian(data.aiAcceptSwitchTeamPercentChance); - data.cpuReplacementMultiplier = Shared::PlatformByteOrder::toCommonEndian(data.cpuReplacementMultiplier); - data.masterserver_admin = Shared::PlatformByteOrder::toCommonEndian(data.masterserver_admin); - data.masterserver_admin_factionIndex = Shared::PlatformByteOrder::toCommonEndian(data.masterserver_admin_factionIndex); - - data.networkAllowNativeLanguageTechtree = Shared::PlatformByteOrder::toCommonEndian(data.networkAllowNativeLanguageTechtree); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + data.networkPlayerStatuses[i] = Shared::PlatformByteOrder::toCommonEndian( + data.networkPlayerStatuses[i]); + data.factionCRCList[i] = + Shared::PlatformByteOrder::toCommonEndian(data.factionCRCList[i]); + data.factionControls[i] = + Shared::PlatformByteOrder::toCommonEndian(data.factionControls[i]); + data.resourceMultiplierIndex[i] = + Shared::PlatformByteOrder::toCommonEndian( + data.resourceMultiplierIndex[i]); + data.teams[i] = Shared::PlatformByteOrder::toCommonEndian(data.teams[i]); + data.startLocationIndex[i] = + Shared::PlatformByteOrder::toCommonEndian(data.startLocationIndex[i]); + } + data.mapFilter = Shared::PlatformByteOrder::toCommonEndian(data.mapFilter); + data.mapCRC = Shared::PlatformByteOrder::toCommonEndian(data.mapCRC); + data.tilesetCRC = + Shared::PlatformByteOrder::toCommonEndian(data.tilesetCRC); + data.techCRC = Shared::PlatformByteOrder::toCommonEndian(data.techCRC); + data.thisFactionIndex = + Shared::PlatformByteOrder::toCommonEndian(data.thisFactionIndex); + data.factionCount = + Shared::PlatformByteOrder::toCommonEndian(data.factionCount); + data.defaultResources = + Shared::PlatformByteOrder::toCommonEndian(data.defaultResources); + data.defaultUnits = + Shared::PlatformByteOrder::toCommonEndian(data.defaultUnits); + + data.defaultVictoryConditions = Shared::PlatformByteOrder::toCommonEndian( + data.defaultVictoryConditions); + data.fogOfWar = Shared::PlatformByteOrder::toCommonEndian(data.fogOfWar); + data.allowObservers = + Shared::PlatformByteOrder::toCommonEndian(data.allowObservers); + data.enableObserverModeAtEndGame = + Shared::PlatformByteOrder::toCommonEndian( + data.enableObserverModeAtEndGame); + data.enableServerControlledAI = Shared::PlatformByteOrder::toCommonEndian( + data.enableServerControlledAI); + data.networkFramePeriod = + Shared::PlatformByteOrder::toCommonEndian(data.networkFramePeriod); + data.networkPauseGameForLaggedClients = + Shared::PlatformByteOrder::toCommonEndian( + data.networkPauseGameForLaggedClients); + data.pathFinderType = + Shared::PlatformByteOrder::toCommonEndian(data.pathFinderType); + data.flagTypes1 = + Shared::PlatformByteOrder::toCommonEndian(data.flagTypes1); + + data.aiAcceptSwitchTeamPercentChance = + Shared::PlatformByteOrder::toCommonEndian( + data.aiAcceptSwitchTeamPercentChance); + data.cpuReplacementMultiplier = Shared::PlatformByteOrder::toCommonEndian( + data.cpuReplacementMultiplier); + data.masterserver_admin = + Shared::PlatformByteOrder::toCommonEndian(data.masterserver_admin); + data.masterserver_admin_factionIndex = + Shared::PlatformByteOrder::toCommonEndian( + data.masterserver_admin_factionIndex); + + data.networkAllowNativeLanguageTechtree = + Shared::PlatformByteOrder::toCommonEndian( + data.networkAllowNativeLanguageTechtree); + } } void NetworkMessageLaunch::fromEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); - for(int i= 0; i < GameConstants::maxPlayers; ++i){ - data.networkPlayerStatuses[i] = Shared::PlatformByteOrder::fromCommonEndian(data.networkPlayerStatuses[i]); - data.factionCRCList[i] = Shared::PlatformByteOrder::fromCommonEndian(data.factionCRCList[i]); - data.factionControls[i] = Shared::PlatformByteOrder::fromCommonEndian(data.factionControls[i]); - data.resourceMultiplierIndex[i] = Shared::PlatformByteOrder::fromCommonEndian(data.resourceMultiplierIndex[i]); - data.teams[i] = Shared::PlatformByteOrder::fromCommonEndian(data.teams[i]); - data.startLocationIndex[i] = Shared::PlatformByteOrder::fromCommonEndian(data.startLocationIndex[i]); - } - data.mapFilter = Shared::PlatformByteOrder::fromCommonEndian(data.mapFilter); - data.mapCRC = Shared::PlatformByteOrder::fromCommonEndian(data.mapCRC); - data.tilesetCRC = Shared::PlatformByteOrder::fromCommonEndian(data.tilesetCRC); - data.techCRC = Shared::PlatformByteOrder::fromCommonEndian(data.techCRC); - data.thisFactionIndex = Shared::PlatformByteOrder::fromCommonEndian(data.thisFactionIndex); - data.factionCount = Shared::PlatformByteOrder::fromCommonEndian(data.factionCount); - data.defaultResources = Shared::PlatformByteOrder::fromCommonEndian(data.defaultResources); - data.defaultUnits = Shared::PlatformByteOrder::fromCommonEndian(data.defaultUnits); - - data.defaultVictoryConditions = Shared::PlatformByteOrder::fromCommonEndian(data.defaultVictoryConditions); - data.fogOfWar = Shared::PlatformByteOrder::fromCommonEndian(data.fogOfWar); - data.allowObservers = Shared::PlatformByteOrder::fromCommonEndian(data.allowObservers); - data.enableObserverModeAtEndGame = Shared::PlatformByteOrder::fromCommonEndian(data.enableObserverModeAtEndGame); - data.enableServerControlledAI = Shared::PlatformByteOrder::fromCommonEndian(data.enableServerControlledAI); - data.networkFramePeriod = Shared::PlatformByteOrder::fromCommonEndian(data.networkFramePeriod); - data.networkPauseGameForLaggedClients = Shared::PlatformByteOrder::fromCommonEndian(data.networkPauseGameForLaggedClients); - data.pathFinderType = Shared::PlatformByteOrder::fromCommonEndian(data.pathFinderType); - data.flagTypes1 = Shared::PlatformByteOrder::fromCommonEndian(data.flagTypes1); - - data.aiAcceptSwitchTeamPercentChance = Shared::PlatformByteOrder::fromCommonEndian(data.aiAcceptSwitchTeamPercentChance); - data.cpuReplacementMultiplier = Shared::PlatformByteOrder::fromCommonEndian(data.cpuReplacementMultiplier); - data.masterserver_admin = Shared::PlatformByteOrder::fromCommonEndian(data.masterserver_admin); - data.masterserver_admin_factionIndex = Shared::PlatformByteOrder::fromCommonEndian(data.masterserver_admin_factionIndex); - - data.networkAllowNativeLanguageTechtree = Shared::PlatformByteOrder::fromCommonEndian(data.networkAllowNativeLanguageTechtree); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + data.networkPlayerStatuses[i] = + Shared::PlatformByteOrder::fromCommonEndian( + data.networkPlayerStatuses[i]); + data.factionCRCList[i] = + Shared::PlatformByteOrder::fromCommonEndian(data.factionCRCList[i]); + data.factionControls[i] = + Shared::PlatformByteOrder::fromCommonEndian(data.factionControls[i]); + data.resourceMultiplierIndex[i] = + Shared::PlatformByteOrder::fromCommonEndian( + data.resourceMultiplierIndex[i]); + data.teams[i] = + Shared::PlatformByteOrder::fromCommonEndian(data.teams[i]); + data.startLocationIndex[i] = Shared::PlatformByteOrder::fromCommonEndian( + data.startLocationIndex[i]); + } + data.mapFilter = + Shared::PlatformByteOrder::fromCommonEndian(data.mapFilter); + data.mapCRC = Shared::PlatformByteOrder::fromCommonEndian(data.mapCRC); + data.tilesetCRC = + Shared::PlatformByteOrder::fromCommonEndian(data.tilesetCRC); + data.techCRC = Shared::PlatformByteOrder::fromCommonEndian(data.techCRC); + data.thisFactionIndex = + Shared::PlatformByteOrder::fromCommonEndian(data.thisFactionIndex); + data.factionCount = + Shared::PlatformByteOrder::fromCommonEndian(data.factionCount); + data.defaultResources = + Shared::PlatformByteOrder::fromCommonEndian(data.defaultResources); + data.defaultUnits = + Shared::PlatformByteOrder::fromCommonEndian(data.defaultUnits); + + data.defaultVictoryConditions = Shared::PlatformByteOrder::fromCommonEndian( + data.defaultVictoryConditions); + data.fogOfWar = Shared::PlatformByteOrder::fromCommonEndian(data.fogOfWar); + data.allowObservers = + Shared::PlatformByteOrder::fromCommonEndian(data.allowObservers); + data.enableObserverModeAtEndGame = + Shared::PlatformByteOrder::fromCommonEndian( + data.enableObserverModeAtEndGame); + data.enableServerControlledAI = Shared::PlatformByteOrder::fromCommonEndian( + data.enableServerControlledAI); + data.networkFramePeriod = + Shared::PlatformByteOrder::fromCommonEndian(data.networkFramePeriod); + data.networkPauseGameForLaggedClients = + Shared::PlatformByteOrder::fromCommonEndian( + data.networkPauseGameForLaggedClients); + data.pathFinderType = + Shared::PlatformByteOrder::fromCommonEndian(data.pathFinderType); + data.flagTypes1 = + Shared::PlatformByteOrder::fromCommonEndian(data.flagTypes1); + + data.aiAcceptSwitchTeamPercentChance = + Shared::PlatformByteOrder::fromCommonEndian( + data.aiAcceptSwitchTeamPercentChance); + data.cpuReplacementMultiplier = Shared::PlatformByteOrder::fromCommonEndian( + data.cpuReplacementMultiplier); + data.masterserver_admin = + Shared::PlatformByteOrder::fromCommonEndian(data.masterserver_admin); + data.masterserver_admin_factionIndex = + Shared::PlatformByteOrder::fromCommonEndian( + data.masterserver_admin_factionIndex); + + data.networkAllowNativeLanguageTechtree = + Shared::PlatformByteOrder::fromCommonEndian( + data.networkAllowNativeLanguageTechtree); + } } // ===================================================== @@ -1647,1815 +1778,2039 @@ void NetworkMessageLaunch::fromEndian() { // ===================================================== NetworkMessageCommandList::NetworkMessageCommandList(int32 frameCount) { - data.messageType = nmtCommandList; - data.header.frameCount= frameCount; - data.header.commandCount= 0; - for(int index = 0; index < GameConstants::maxPlayers; ++index) { - data.header.networkPlayerFactionCRC[index]=0; - } + data.messageType = nmtCommandList; + data.header.frameCount = frameCount; + data.header.commandCount = 0; + for (int index = 0; index < GameConstants::maxPlayers; ++index) { + data.header.networkPlayerFactionCRC[index] = 0; + } } -bool NetworkMessageCommandList::addCommand(const NetworkCommand* networkCommand){ - data.commands.push_back(*networkCommand); - data.header.commandCount++; - return true; +bool NetworkMessageCommandList::addCommand( + const NetworkCommand *networkCommand) { + data.commands.push_back(*networkCommand); + data.header.commandCount++; + return true; } -const char * NetworkMessageCommandList::getPackedMessageFormatHeader() const { - return "cHlLLLLLLLL"; +const char *NetworkMessageCommandList::getPackedMessageFormatHeader() const { + return "cHlLLLLLLLL"; } unsigned int NetworkMessageCommandList::getPackedSizeHeader() { - static unsigned int result = 0; - if(result == 0) { - Data packedData; - init(packedData); - unsigned char *buf = new unsigned char[sizeof(packedData)*3]; - result = pack(buf, getPackedMessageFormatHeader(), - packedData.messageType, - packedData.header.commandCount, - packedData.header.frameCount, - packedData.header.networkPlayerFactionCRC[0], - packedData.header.networkPlayerFactionCRC[1], - packedData.header.networkPlayerFactionCRC[2], - packedData.header.networkPlayerFactionCRC[3], - packedData.header.networkPlayerFactionCRC[4], - packedData.header.networkPlayerFactionCRC[5], - packedData.header.networkPlayerFactionCRC[6], - packedData.header.networkPlayerFactionCRC[7]); - delete [] buf; - } - return result; + static unsigned int result = 0; + if (result == 0) { + Data packedData; + init(packedData); + unsigned char *buf = new unsigned char[sizeof(packedData) * 3]; + result = pack(buf, getPackedMessageFormatHeader(), packedData.messageType, + packedData.header.commandCount, packedData.header.frameCount, + packedData.header.networkPlayerFactionCRC[0], + packedData.header.networkPlayerFactionCRC[1], + packedData.header.networkPlayerFactionCRC[2], + packedData.header.networkPlayerFactionCRC[3], + packedData.header.networkPlayerFactionCRC[4], + packedData.header.networkPlayerFactionCRC[5], + packedData.header.networkPlayerFactionCRC[6], + packedData.header.networkPlayerFactionCRC[7]); + delete[] buf; + } + return result; } void NetworkMessageCommandList::unpackMessageHeader(unsigned char *buf) { - unpack(buf, getPackedMessageFormatHeader(), - &data.messageType, - &data.header.commandCount, - &data.header.frameCount, - &data.header.networkPlayerFactionCRC[0], - &data.header.networkPlayerFactionCRC[1], - &data.header.networkPlayerFactionCRC[2], - &data.header.networkPlayerFactionCRC[3], - &data.header.networkPlayerFactionCRC[4], - &data.header.networkPlayerFactionCRC[5], - &data.header.networkPlayerFactionCRC[6], - &data.header.networkPlayerFactionCRC[7]); -} - -unsigned char * NetworkMessageCommandList::packMessageHeader() { - unsigned char *buf = new unsigned char[getPackedSizeHeader()+1]; - pack(buf, getPackedMessageFormatHeader(), - data.messageType, - data.header.commandCount, - data.header.frameCount, - data.header.networkPlayerFactionCRC[0], - data.header.networkPlayerFactionCRC[1], - data.header.networkPlayerFactionCRC[2], - data.header.networkPlayerFactionCRC[3], - data.header.networkPlayerFactionCRC[4], - data.header.networkPlayerFactionCRC[5], - data.header.networkPlayerFactionCRC[6], - data.header.networkPlayerFactionCRC[7]); - return buf; -} - -const char * NetworkMessageCommandList::getPackedMessageFormatDetail() const { - return "hlhhhhlccHccll"; + unpack(buf, getPackedMessageFormatHeader(), &data.messageType, + &data.header.commandCount, &data.header.frameCount, + &data.header.networkPlayerFactionCRC[0], + &data.header.networkPlayerFactionCRC[1], + &data.header.networkPlayerFactionCRC[2], + &data.header.networkPlayerFactionCRC[3], + &data.header.networkPlayerFactionCRC[4], + &data.header.networkPlayerFactionCRC[5], + &data.header.networkPlayerFactionCRC[6], + &data.header.networkPlayerFactionCRC[7]); +} + +unsigned char *NetworkMessageCommandList::packMessageHeader() { + unsigned char *buf = new unsigned char[getPackedSizeHeader() + 1]; + pack(buf, getPackedMessageFormatHeader(), data.messageType, + data.header.commandCount, data.header.frameCount, + data.header.networkPlayerFactionCRC[0], + data.header.networkPlayerFactionCRC[1], + data.header.networkPlayerFactionCRC[2], + data.header.networkPlayerFactionCRC[3], + data.header.networkPlayerFactionCRC[4], + data.header.networkPlayerFactionCRC[5], + data.header.networkPlayerFactionCRC[6], + data.header.networkPlayerFactionCRC[7]); + return buf; +} + +const char *NetworkMessageCommandList::getPackedMessageFormatDetail() const { + return "hlhhhhlccHccll"; } unsigned int NetworkMessageCommandList::getPackedSizeDetail(int count) { - unsigned int result = 0; - //if(result == 0) { - for(unsigned int i = 0; i < (unsigned int)count; ++i) { - NetworkCommand packedData; - unsigned char *buf = new unsigned char[sizeof(NetworkCommand)*3]; - result += pack(buf, getPackedMessageFormatDetail(), - packedData.networkCommandType, - packedData.unitId, - packedData.unitTypeId, - packedData.commandTypeId, - packedData.positionX, - packedData.positionY, - packedData.targetId, - packedData.wantQueue, - packedData.fromFactionIndex, - packedData.unitFactionUnitCount, - packedData.unitFactionIndex, - packedData.commandStateType, - packedData.commandStateValue, - packedData.unitCommandGroupId); - delete [] buf; - } - //} - return result; -} -void NetworkMessageCommandList::unpackMessageDetail(unsigned char *buf,int count) { - data.commands.clear(); - data.commands.resize(count); - //unsigned int bytes_processed_total = 0; - unsigned char *bufMove = buf; - for(unsigned int i = 0; i < (unsigned int)count; ++i) { - unsigned int bytes_processed = unpack(bufMove, getPackedMessageFormatDetail(), - &data.commands[i].networkCommandType, - &data.commands[i].unitId, - &data.commands[i].unitTypeId, - &data.commands[i].commandTypeId, - &data.commands[i].positionX, - &data.commands[i].positionY, - &data.commands[i].targetId, - &data.commands[i].wantQueue, - &data.commands[i].fromFactionIndex, - &data.commands[i].unitFactionUnitCount, - &data.commands[i].unitFactionIndex, - &data.commands[i].commandStateType, - &data.commands[i].commandStateValue, - &data.commands[i].unitCommandGroupId); - bufMove += bytes_processed; - //bytes_processed_total += bytes_processed; - } - //printf("\nUnPacked detail size = %u\n",bytes_processed_total); -} - -unsigned char * NetworkMessageCommandList::packMessageDetail(uint16 totalCommand) { - int packetSize = getPackedSizeDetail(totalCommand) +1; - unsigned char *buf = new unsigned char[packetSize]; - unsigned char *bufMove = buf; - //unsigned int bytes_processed_total = 0; - for(unsigned int i = 0; i < totalCommand; ++i) { - unsigned int bytes_processed = pack(bufMove, getPackedMessageFormatDetail(), - data.commands[i].networkCommandType, - data.commands[i].unitId, - data.commands[i].unitTypeId, - data.commands[i].commandTypeId, - data.commands[i].positionX, - data.commands[i].positionY, - data.commands[i].targetId, - data.commands[i].wantQueue, - data.commands[i].fromFactionIndex, - data.commands[i].unitFactionUnitCount, - data.commands[i].unitFactionIndex, - data.commands[i].commandStateType, - data.commands[i].commandStateValue, - data.commands[i].unitCommandGroupId); - bufMove += bytes_processed; - //bytes_processed_total += bytes_processed; - } - //printf("\nPacked detail size = %u, allocated = %d\n",bytes_processed_total,packetSize); - return buf; -} - -bool NetworkMessageCommandList::receive(Socket* socket) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - unsigned char *buf = NULL; - bool result = false; - if(useOldProtocol == true) { - result = NetworkMessage::receive(socket, &data.header, commandListHeaderSize, true); - if(result == true) { - data.messageType = this->getNetworkMessageType(); - } - - //printf("!!! =====> IN Network hdr cmd get frame: %d data.header.commandCount: %u\n",data.header.frameCount,data.header.commandCount); - } - else { - buf = new unsigned char[getPackedSizeHeader()+1]; - result = NetworkMessage::receive(socket, buf, getPackedSizeHeader(), true); - unpackMessageHeader(buf); - //if(data.header.commandCount) printf("\n\nGot packet size = %u data.messageType = %d\n%s\ncommandcount [%u] framecount [%d]\n",getPackedSizeHeader(),data.header.messageType,buf,data.header.commandCount,data.header.frameCount); - delete [] buf; - } - fromEndianHeader(); - - if(result == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] got header, messageType = %d, commandCount = %u, frameCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,data.messageType,data.header.commandCount,data.header.frameCount); - - //printf("!!! =====> IN Network cmd get frame: %d data.header.commandCount: %u\n",data.header.frameCount,data.header.commandCount); - - if(data.header.commandCount > 0) { - data.commands.resize(data.header.commandCount); - - if(useOldProtocol == true) { - int totalMsgSize = (sizeof(NetworkCommand) * data.header.commandCount); - result = NetworkMessage::receive(socket, &data.commands[0], totalMsgSize, true); - -// if(data.commands[0].getNetworkCommandType() == nctPauseResume) { -// printf("=====> IN Network cmd type: %d [%d] frame: %d\n",data.commands[0].getNetworkCommandType(),nctPauseResume,data.header.frameCount); -// } - } - else { - //int totalMsgSize = (sizeof(NetworkCommand) * data.header.commandCount); - //result = NetworkMessage::receive(socket, &data.commands[0], totalMsgSize, true); - buf = new unsigned char[getPackedSizeDetail(data.header.commandCount)+1]; - result = NetworkMessage::receive(socket, buf, getPackedSizeDetail(data.header.commandCount), true); - unpackMessageDetail(buf,data.header.commandCount); - //printf("Got packet size = %u data.messageType = %d\n%s\n",getPackedSize(),data.messageType,buf); - delete [] buf; - } - fromEndianDetail(); - -// for(int idx = 0 ; idx < data.header.commandCount; ++idx) { -// const NetworkCommand &cmd = data.commands[idx]; -// printf("========> Got index = %d / %u, got networkCommand [%s]\n",idx, data.header.commandCount,cmd.toString().c_str()); -// } - - if(result == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled == true) { - for(int idx = 0 ; idx < data.header.commandCount; ++idx) { - const NetworkCommand &cmd = data.commands[idx]; - - SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] index = %d, received networkCommand [%s]\n", - extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,idx, cmd.toString().c_str()); - } - } - } - else { - //if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] ERROR Failed to get command data, totalMsgSize = %d.\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,totalMsgSize); - } - } - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] ERROR header not received as expected\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] ERROR header not received as expected\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - return result; - -} - -unsigned char * NetworkMessageCommandList::getData() { - int headerSize = sizeof(data.header); - uint16 totalCommand = data.header.commandCount; - int detailSize = (sizeof(NetworkCommand) * totalCommand); - int fullBufferSize = headerSize + detailSize; - - unsigned char *buffer = new unsigned char[fullBufferSize]; - memcpy(buffer,&data.header,headerSize); - memcpy(&buffer[headerSize],&data.commands[0],detailSize); - return buffer; -} - -void NetworkMessageCommandList::send(Socket* socket) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] nmtCommandList, frameCount = %d, data.header.commandCount = %d, data.header.messageType = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,data.header.frameCount,data.header.commandCount,data.messageType); - - assert(data.messageType == nmtCommandList); - uint16 totalCommand = data.header.commandCount; - toEndianHeader(); - toEndianDetail(totalCommand); - - unsigned char *buf = NULL; - //bool result = false; - if(useOldProtocol == true) { - //printf("<===== OUT Network hdr cmd type: frame: %d totalCommand: %u [%u]\n",data.header.frameCount,totalCommand,data.header.commandCount); - //NetworkMessage::send(socket, &data.messageType, sizeof(data.messageType)); - - //NetworkMessage::send(socket, &data.header, commandListHeaderSize, data.messageType); - unsigned char *send_buffer = getData(); - int headerSize = sizeof(data.header); - uint16 totalCommand = data.header.commandCount; - int detailSize = (sizeof(NetworkCommand) * totalCommand); - int fullBufferSize = headerSize + detailSize; - NetworkMessage::send(socket, send_buffer, fullBufferSize, data.messageType); - delete [] send_buffer; - } - else { - //NetworkMessage::send(socket, &data.header, commandListHeaderSize); - buf = packMessageHeader(); - //if(totalCommand) printf("\n\nSend packet size = %u data.messageType = %d\n%s\ncommandcount [%u] framecount [%d]\n",getPackedSizeHeader(),data.header.messageType,buf,totalCommand,data.header.frameCount); - NetworkMessage::send(socket, buf, getPackedSizeHeader()); - delete [] buf; - } - - if(totalCommand > 0) { - //printf("\n#2 Send packet commandcount [%u] framecount [%d]\n",totalCommand,data.header.frameCount); - //toEndianDetail(totalCommand); - //printf("\n#3 Send packet commandcount [%u] framecount [%d]\n",totalCommand,data.header.frameCount); - - //bool result = false; - if(useOldProtocol == true) { -// if(data.commands[0].getNetworkCommandType() == nctPauseResume) { -// printf("<===== OUT Network cmd type: %d [%d] frame: %d totalCommand: %u [%u]\n",data.commands[0].getNetworkCommandType(),nctPauseResume,data.header.frameCount,totalCommand,data.header.commandCount); -// } - //NetworkMessage::send(socket, &data.commands[0], (sizeof(NetworkCommand) * totalCommand)); - } - else { - buf = packMessageDetail(totalCommand); - //printf("\n#4 Send packet commandcount [%u] framecount [%d]\n",totalCommand,data.header.frameCount); - //printf("Send packet size = %u data.messageType = %d\n[%s]\n",getPackedSize(),data.messageType,buf); - NetworkMessage::send(socket, buf, getPackedSizeDetail(totalCommand)); - //printf("\n#5 Send packet commandcount [%u] framecount [%d]\n",totalCommand,data.header.frameCount); - delete [] buf; - //printf("\n#6 Send packet commandcount [%u] framecount [%d]\n",totalCommand,data.header.frameCount); - - // for(int idx = 0 ; idx < totalCommand; ++idx) { - // const NetworkCommand &cmd = data.commands[idx]; - // printf("========> Send index = %d / %u, sent networkCommand [%s]\n",idx, totalCommand,cmd.toString().c_str()); - // } - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled == true) { - SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] messageType = %d, frameCount = %d, data.commandCount = %d\n", - extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,data.messageType,data.header.frameCount,data.header.commandCount); - - if (totalCommand > 0) { - for(int idx = 0 ; idx < totalCommand; ++idx) { - const NetworkCommand &cmd = data.commands[idx]; - - SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] index = %d, sent networkCommand [%s]\n", - extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,idx, cmd.toString().c_str()); - } - - SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] END of loop, nmtCommandList, frameCount = %d, data.header.commandCount = %d, data.header.messageType = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,data.header.frameCount,totalCommand,data.messageType); + unsigned int result = 0; + // if(result == 0) { + for (unsigned int i = 0; i < (unsigned int)count; ++i) { + NetworkCommand packedData; + unsigned char *buf = new unsigned char[sizeof(NetworkCommand) * 3]; + result += + pack(buf, getPackedMessageFormatDetail(), packedData.networkCommandType, + packedData.unitId, packedData.unitTypeId, packedData.commandTypeId, + packedData.positionX, packedData.positionY, packedData.targetId, + packedData.wantQueue, packedData.fromFactionIndex, + packedData.unitFactionUnitCount, packedData.unitFactionIndex, + packedData.commandStateType, packedData.commandStateValue, + packedData.unitCommandGroupId); + delete[] buf; + } + //} + return result; +} +void NetworkMessageCommandList::unpackMessageDetail(unsigned char *buf, + int count) { + data.commands.clear(); + data.commands.resize(count); + // unsigned int bytes_processed_total = 0; + unsigned char *bufMove = buf; + for (unsigned int i = 0; i < (unsigned int)count; ++i) { + unsigned int bytes_processed = unpack( + bufMove, getPackedMessageFormatDetail(), + &data.commands[i].networkCommandType, &data.commands[i].unitId, + &data.commands[i].unitTypeId, &data.commands[i].commandTypeId, + &data.commands[i].positionX, &data.commands[i].positionY, + &data.commands[i].targetId, &data.commands[i].wantQueue, + &data.commands[i].fromFactionIndex, + &data.commands[i].unitFactionUnitCount, + &data.commands[i].unitFactionIndex, &data.commands[i].commandStateType, + &data.commands[i].commandStateValue, + &data.commands[i].unitCommandGroupId); + bufMove += bytes_processed; + // bytes_processed_total += bytes_processed; + } + // printf("\nUnPacked detail size = %u\n",bytes_processed_total); +} + +unsigned char * +NetworkMessageCommandList::packMessageDetail(uint16 totalCommand) { + int packetSize = getPackedSizeDetail(totalCommand) + 1; + unsigned char *buf = new unsigned char[packetSize]; + unsigned char *bufMove = buf; + // unsigned int bytes_processed_total = 0; + for (unsigned int i = 0; i < totalCommand; ++i) { + unsigned int bytes_processed = pack( + bufMove, getPackedMessageFormatDetail(), + data.commands[i].networkCommandType, data.commands[i].unitId, + data.commands[i].unitTypeId, data.commands[i].commandTypeId, + data.commands[i].positionX, data.commands[i].positionY, + data.commands[i].targetId, data.commands[i].wantQueue, + data.commands[i].fromFactionIndex, + data.commands[i].unitFactionUnitCount, + data.commands[i].unitFactionIndex, data.commands[i].commandStateType, + data.commands[i].commandStateValue, + data.commands[i].unitCommandGroupId); + bufMove += bytes_processed; + // bytes_processed_total += bytes_processed; + } + // printf("\nPacked detail size = %u, allocated = + // %d\n",bytes_processed_total,packetSize); + return buf; +} + +bool NetworkMessageCommandList::receive(Socket *socket) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + unsigned char *buf = NULL; + bool result = false; + if (useOldProtocol == true) { + result = NetworkMessage::receive(socket, &data.header, + commandListHeaderSize, true); + if (result == true) { + data.messageType = this->getNetworkMessageType(); + } + + // printf("!!! =====> IN Network hdr cmd get frame: %d + // data.header.commandCount: + // %u\n",data.header.frameCount,data.header.commandCount); + } else { + buf = new unsigned char[getPackedSizeHeader() + 1]; + result = NetworkMessage::receive(socket, buf, getPackedSizeHeader(), true); + unpackMessageHeader(buf); + // if(data.header.commandCount) printf("\n\nGot packet size = %u + // data.messageType = %d\n%s\ncommandcount [%u] framecount + // [%d]\n",getPackedSizeHeader(),data.header.messageType,buf,data.header.commandCount,data.header.frameCount); + delete[] buf; + } + fromEndianHeader(); + + if (result == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] got header, messageType = " + "%d, commandCount = %u, frameCount = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, data.messageType, + data.header.commandCount, + data.header.frameCount); + + // printf("!!! =====> IN Network cmd get frame: %d data.header.commandCount: + // %u\n",data.header.frameCount,data.header.commandCount); + + if (data.header.commandCount > 0) { + data.commands.resize(data.header.commandCount); + + if (useOldProtocol == true) { + int totalMsgSize = (sizeof(NetworkCommand) * data.header.commandCount); + result = NetworkMessage::receive(socket, &data.commands[0], + totalMsgSize, true); + + // if(data.commands[0].getNetworkCommandType() + //== + // nctPauseResume) { printf("=====> IN Network + // cmd type: %d [%d] frame: + //%d\n",data.commands[0].getNetworkCommandType(),nctPauseResume,data.header.frameCount); + // } + } else { + // int totalMsgSize = (sizeof(NetworkCommand) * + // data.header.commandCount); result = NetworkMessage::receive(socket, + // &data.commands[0], totalMsgSize, true); + buf = new unsigned char[getPackedSizeDetail(data.header.commandCount) + + 1]; + result = NetworkMessage::receive( + socket, buf, getPackedSizeDetail(data.header.commandCount), true); + unpackMessageDetail(buf, data.header.commandCount); + // printf("Got packet size = %u data.messageType = + // %d\n%s\n",getPackedSize(),data.messageType,buf); + delete[] buf; + } + fromEndianDetail(); + + // for(int idx = 0 ; idx < data.header.commandCount; ++idx) + //{ const NetworkCommand &cmd = data.commands[idx]; + //printf("========> Got index = %d / %u, got networkCommand [%s]\n",idx, + // data.header.commandCount,cmd.toString().c_str()); + // } + + if (result == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled == true) { + for (int idx = 0; idx < data.header.commandCount; ++idx) { + const NetworkCommand &cmd = data.commands[idx]; + + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] index = %d, received networkCommand " + "[%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, idx, cmd.toString().c_str()); + } } - } + } else { + // if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: + // %d] ERROR Failed to get command data, totalMsgSize = + // %d.\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,totalMsgSize); + } + } + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] ERROR header not received as expected\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d] ERROR header not received as expected\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + } + return result; +} + +unsigned char *NetworkMessageCommandList::getData() { + int headerSize = sizeof(data.header); + uint16 totalCommand = data.header.commandCount; + int detailSize = (sizeof(NetworkCommand) * totalCommand); + int fullBufferSize = headerSize + detailSize; + + unsigned char *buffer = new unsigned char[fullBufferSize]; + memcpy(buffer, &data.header, headerSize); + memcpy(&buffer[headerSize], &data.commands[0], detailSize); + return buffer; +} + +void NetworkMessageCommandList::send(Socket *socket) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] nmtCommandList, frameCount = %d, " + "data.header.commandCount = %d, data.header.messageType = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + data.header.frameCount, data.header.commandCount, data.messageType); + + assert(data.messageType == nmtCommandList); + uint16 totalCommand = data.header.commandCount; + toEndianHeader(); + toEndianDetail(totalCommand); + + unsigned char *buf = NULL; + // bool result = false; + if (useOldProtocol == true) { + // printf("<===== OUT Network hdr cmd type: frame: %d totalCommand: %u + // [%u]\n",data.header.frameCount,totalCommand,data.header.commandCount); + // NetworkMessage::send(socket, &data.messageType, + // sizeof(data.messageType)); + + // NetworkMessage::send(socket, &data.header, commandListHeaderSize, + // data.messageType); + unsigned char *send_buffer = getData(); + int headerSize = sizeof(data.header); + uint16 totalCommand = data.header.commandCount; + int detailSize = (sizeof(NetworkCommand) * totalCommand); + int fullBufferSize = headerSize + detailSize; + NetworkMessage::send(socket, send_buffer, fullBufferSize, data.messageType); + delete[] send_buffer; + } else { + // NetworkMessage::send(socket, &data.header, commandListHeaderSize); + buf = packMessageHeader(); + // if(totalCommand) printf("\n\nSend packet size = %u data.messageType = + // %d\n%s\ncommandcount [%u] framecount + // [%d]\n",getPackedSizeHeader(),data.header.messageType,buf,totalCommand,data.header.frameCount); + NetworkMessage::send(socket, buf, getPackedSizeHeader()); + delete[] buf; + } + + if (totalCommand > 0) { + // printf("\n#2 Send packet commandcount [%u] framecount + // [%d]\n",totalCommand,data.header.frameCount); + // toEndianDetail(totalCommand); + // printf("\n#3 Send packet commandcount [%u] framecount + // [%d]\n",totalCommand,data.header.frameCount); + + // bool result = false; + if (useOldProtocol == true) { + // if(data.commands[0].getNetworkCommandType() == + // nctPauseResume) { printf("<===== OUT + // Network cmd type: %d [%d] frame: %d totalCommand: %u + //[%u]\n",data.commands[0].getNetworkCommandType(),nctPauseResume,data.header.frameCount,totalCommand,data.header.commandCount); + // } + // NetworkMessage::send(socket, &data.commands[0], (sizeof(NetworkCommand) + // * totalCommand)); + } else { + buf = packMessageDetail(totalCommand); + // printf("\n#4 Send packet commandcount [%u] framecount + // [%d]\n",totalCommand,data.header.frameCount); printf("Send packet size + // = %u data.messageType = + // %d\n[%s]\n",getPackedSize(),data.messageType,buf); + NetworkMessage::send(socket, buf, getPackedSizeDetail(totalCommand)); + // printf("\n#5 Send packet commandcount [%u] framecount + // [%d]\n",totalCommand,data.header.frameCount); + delete[] buf; + // printf("\n#6 Send packet commandcount [%u] framecount + // [%d]\n",totalCommand,data.header.frameCount); + + // for(int idx = 0 ; idx < totalCommand; ++idx) { + // const NetworkCommand &cmd = data.commands[idx]; + // printf("========> Send index = %d / %u, sent networkCommand + // [%s]\n",idx, totalCommand,cmd.toString().c_str()); + // } + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled == + true) { + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] messageType = %d, " + "frameCount = %d, data.commandCount = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, data.messageType, + data.header.frameCount, data.header.commandCount); + + if (totalCommand > 0) { + for (int idx = 0; idx < totalCommand; ++idx) { + const NetworkCommand &cmd = data.commands[idx]; + + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] index = %d, sent networkCommand [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, idx, cmd.toString().c_str()); + } + + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] END of loop, nmtCommandList, frameCount = %d, " + "data.header.commandCount = %d, data.header.messageType = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, data.header.frameCount, totalCommand, data.messageType); + } + } } void NetworkMessageCommandList::toEndianHeader() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - data.messageType = Shared::PlatformByteOrder::toCommonEndian(data.messageType); - data.header.commandCount = Shared::PlatformByteOrder::toCommonEndian(data.header.commandCount); - data.header.frameCount = Shared::PlatformByteOrder::toCommonEndian(data.header.frameCount); - for(int index = 0; index < GameConstants::maxPlayers; ++index) { - data.header.networkPlayerFactionCRC[index] = Shared::PlatformByteOrder::toCommonEndian(data.header.networkPlayerFactionCRC[index]); - } - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + data.messageType = + Shared::PlatformByteOrder::toCommonEndian(data.messageType); + data.header.commandCount = + Shared::PlatformByteOrder::toCommonEndian(data.header.commandCount); + data.header.frameCount = + Shared::PlatformByteOrder::toCommonEndian(data.header.frameCount); + for (int index = 0; index < GameConstants::maxPlayers; ++index) { + data.header.networkPlayerFactionCRC[index] = + Shared::PlatformByteOrder::toCommonEndian( + data.header.networkPlayerFactionCRC[index]); + } + } } void NetworkMessageCommandList::fromEndianHeader() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - data.messageType = Shared::PlatformByteOrder::fromCommonEndian(data.messageType); - data.header.commandCount = Shared::PlatformByteOrder::fromCommonEndian(data.header.commandCount); - data.header.frameCount = Shared::PlatformByteOrder::fromCommonEndian(data.header.frameCount); - for(int index = 0; index < GameConstants::maxPlayers; ++index) { - data.header.networkPlayerFactionCRC[index] = Shared::PlatformByteOrder::fromCommonEndian(data.header.networkPlayerFactionCRC[index]); - } - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + data.messageType = + Shared::PlatformByteOrder::fromCommonEndian(data.messageType); + data.header.commandCount = + Shared::PlatformByteOrder::fromCommonEndian(data.header.commandCount); + data.header.frameCount = + Shared::PlatformByteOrder::fromCommonEndian(data.header.frameCount); + for (int index = 0; index < GameConstants::maxPlayers; ++index) { + data.header.networkPlayerFactionCRC[index] = + Shared::PlatformByteOrder::fromCommonEndian( + data.header.networkPlayerFactionCRC[index]); + } + } } void NetworkMessageCommandList::toEndianDetail(uint16 totalCommand) { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - if(totalCommand > 0) { - for(int idx = 0 ; idx < totalCommand; ++idx) { - NetworkCommand &cmd = data.commands[idx]; - cmd.toEndian(); - } - } - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + if (totalCommand > 0) { + for (int idx = 0; idx < totalCommand; ++idx) { + NetworkCommand &cmd = data.commands[idx]; + cmd.toEndian(); + } + } + } } void NetworkMessageCommandList::fromEndianDetail() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - if(data.header.commandCount > 0) { - for(int idx = 0 ; idx < data.header.commandCount; ++idx) { - NetworkCommand &cmd = data.commands[idx]; - cmd.fromEndian(); - } - } - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + if (data.header.commandCount > 0) { + for (int idx = 0; idx < data.header.commandCount; ++idx) { + NetworkCommand &cmd = data.commands[idx]; + cmd.fromEndian(); + } + } + } } // ===================================================== // class NetworkMessageText // ===================================================== -NetworkMessageText::NetworkMessageText() { - messageType = nmtText; -} -NetworkMessageText::NetworkMessageText(const string &text, int teamIndex, int playerIndex, - const string targetLanguage) { - if((int)text.length() >= maxTextStringSize) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] WARNING / ERROR - text [%s] length = %d, max = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,text.c_str(),text.length(),maxTextStringSize); - } +NetworkMessageText::NetworkMessageText() { messageType = nmtText; } +NetworkMessageText::NetworkMessageText(const string &text, int teamIndex, + int playerIndex, + const string targetLanguage) { + if ((int)text.length() >= maxTextStringSize) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] WARNING / ERROR - text " + "[%s] length = %d, max = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, text.c_str(), + text.length(), maxTextStringSize); + } - messageType = nmtText; - data.text = text.substr(0,maxTextStringSize); - data.teamIndex = teamIndex; - data.playerIndex = playerIndex; - data.targetLanguage = targetLanguage; + messageType = nmtText; + data.text = text.substr(0, maxTextStringSize); + data.teamIndex = teamIndex; + data.playerIndex = playerIndex; + data.targetLanguage = targetLanguage; } -NetworkMessageText * NetworkMessageText::getCopy() const { - NetworkMessageText *copy = new NetworkMessageText(); - copy->data = this->data; - return copy; +NetworkMessageText *NetworkMessageText::getCopy() const { + NetworkMessageText *copy = new NetworkMessageText(); + copy->data = this->data; + return copy; } -const char * NetworkMessageText::getPackedMessageFormat() const { - return "c500scc60s"; +const char *NetworkMessageText::getPackedMessageFormat() const { + return "c500scc60s"; } unsigned int NetworkMessageText::getPackedSize() { - static unsigned int result = 0; - if(result == 0) { - Data packedData; - messageType = nmtText; - packedData.playerIndex = 0; - packedData.teamIndex = 0; - unsigned char *buf = new unsigned char[sizeof(packedData)*3]; - result = pack(buf, getPackedMessageFormat(), - messageType, - packedData.text.getBuffer(), - packedData.teamIndex, - packedData.playerIndex, - packedData.targetLanguage.getBuffer()); - delete [] buf; - } - return result; + static unsigned int result = 0; + if (result == 0) { + Data packedData; + messageType = nmtText; + packedData.playerIndex = 0; + packedData.teamIndex = 0; + unsigned char *buf = new unsigned char[sizeof(packedData) * 3]; + result = + pack(buf, getPackedMessageFormat(), messageType, + packedData.text.getBuffer(), packedData.teamIndex, + packedData.playerIndex, packedData.targetLanguage.getBuffer()); + delete[] buf; + } + return result; } void NetworkMessageText::unpackMessage(unsigned char *buf) { - unpack(buf, getPackedMessageFormat(), - &messageType, - data.text.getBuffer(), - &data.teamIndex, - &data.playerIndex, - data.targetLanguage.getBuffer()); -} - -unsigned char * NetworkMessageText::packMessage() { - unsigned char *buf = new unsigned char[getPackedSize()+1]; - pack(buf, getPackedMessageFormat(), - messageType, - data.text.getBuffer(), - data.teamIndex, - data.playerIndex, - data.targetLanguage.getBuffer()); - return buf; -} - -bool NetworkMessageText::receive(Socket* socket) { - bool result = false; - if(useOldProtocol == true) { - result = NetworkMessage::receive(socket, &data, sizeof(data), true); - if(result == true) { - messageType = this->getNetworkMessageType(); - } - } - else { - unsigned char *buf = new unsigned char[getPackedSize()+1]; - result = NetworkMessage::receive(socket, buf, getPackedSize(), true); - unpackMessage(buf); - //printf("Got packet size = %u data.messageType = %d\n%s\n",getPackedSize(),data.messageType,buf); - delete [] buf; - } - fromEndian(); - - data.text.nullTerminate(); - data.targetLanguage.nullTerminate(); - - return result; -} - -void NetworkMessageText::send(Socket* socket) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] nmtText\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - assert(messageType == nmtText); - toEndian(); - - if(useOldProtocol == true) { - //NetworkMessage::send(socket, &messageType, sizeof(messageType)); - NetworkMessage::send(socket, &data, sizeof(data), messageType); - } - else { - unsigned char *buf = packMessage(); - //printf("Send packet size = %u data.messageType = %d\n[%s]\n",getPackedSize(),data.messageType,buf); - NetworkMessage::send(socket, buf, getPackedSize()); - delete [] buf; - } + unpack(buf, getPackedMessageFormat(), &messageType, data.text.getBuffer(), + &data.teamIndex, &data.playerIndex, data.targetLanguage.getBuffer()); +} + +unsigned char *NetworkMessageText::packMessage() { + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + pack(buf, getPackedMessageFormat(), messageType, data.text.getBuffer(), + data.teamIndex, data.playerIndex, data.targetLanguage.getBuffer()); + return buf; +} + +bool NetworkMessageText::receive(Socket *socket) { + bool result = false; + if (useOldProtocol == true) { + result = NetworkMessage::receive(socket, &data, sizeof(data), true); + if (result == true) { + messageType = this->getNetworkMessageType(); + } + } else { + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + result = NetworkMessage::receive(socket, buf, getPackedSize(), true); + unpackMessage(buf); + // printf("Got packet size = %u data.messageType = + // %d\n%s\n",getPackedSize(),data.messageType,buf); + delete[] buf; + } + fromEndian(); + + data.text.nullTerminate(); + data.targetLanguage.nullTerminate(); + + return result; +} + +void NetworkMessageText::send(Socket *socket) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d] nmtText\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + assert(messageType == nmtText); + toEndian(); + + if (useOldProtocol == true) { + // NetworkMessage::send(socket, &messageType, sizeof(messageType)); + NetworkMessage::send(socket, &data, sizeof(data), messageType); + } else { + unsigned char *buf = packMessage(); + // printf("Send packet size = %u data.messageType = + // %d\n[%s]\n",getPackedSize(),data.messageType,buf); + NetworkMessage::send(socket, buf, getPackedSize()); + delete[] buf; + } } void NetworkMessageText::toEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); - data.teamIndex = Shared::PlatformByteOrder::toCommonEndian(data.teamIndex); - data.playerIndex = Shared::PlatformByteOrder::toCommonEndian(data.playerIndex); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); + data.teamIndex = Shared::PlatformByteOrder::toCommonEndian(data.teamIndex); + data.playerIndex = + Shared::PlatformByteOrder::toCommonEndian(data.playerIndex); + } } void NetworkMessageText::fromEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); - data.teamIndex = Shared::PlatformByteOrder::fromCommonEndian(data.teamIndex); - data.playerIndex = Shared::PlatformByteOrder::fromCommonEndian(data.playerIndex); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); + data.teamIndex = + Shared::PlatformByteOrder::fromCommonEndian(data.teamIndex); + data.playerIndex = + Shared::PlatformByteOrder::fromCommonEndian(data.playerIndex); + } } // ===================================================== // class NetworkMessageQuit // ===================================================== -NetworkMessageQuit::NetworkMessageQuit(){ - messageType = nmtQuit; -} +NetworkMessageQuit::NetworkMessageQuit() { messageType = nmtQuit; } -const char * NetworkMessageQuit::getPackedMessageFormat() const { - return "c"; -} +const char *NetworkMessageQuit::getPackedMessageFormat() const { return "c"; } unsigned int NetworkMessageQuit::getPackedSize() { - static unsigned int result = 0; - if(result == 0) { - //Data packedData; - messageType = 0; - unsigned char *buf = new unsigned char[sizeof(messageType)*3]; - result = pack(buf, getPackedMessageFormat(), - messageType); - delete [] buf; - } - return result; + static unsigned int result = 0; + if (result == 0) { + // Data packedData; + messageType = 0; + unsigned char *buf = new unsigned char[sizeof(messageType) * 3]; + result = pack(buf, getPackedMessageFormat(), messageType); + delete[] buf; + } + return result; } void NetworkMessageQuit::unpackMessage(unsigned char *buf) { - unpack(buf, getPackedMessageFormat(), - &messageType); -} - -unsigned char * NetworkMessageQuit::packMessage() { - unsigned char *buf = new unsigned char[getPackedSize()+1]; - pack(buf, getPackedMessageFormat(), - messageType); - return buf; -} - -bool NetworkMessageQuit::receive(Socket* socket) { - bool result = false; - if(useOldProtocol == true) { - result = NetworkMessage::receive(socket, &messageType, sizeof(messageType),true); - } - else { - //fromEndian(); - unsigned char *buf = new unsigned char[getPackedSize()+1]; - result = NetworkMessage::receive(socket, buf, getPackedSize(), true); - unpackMessage(buf); - //printf("Got packet size = %u data.messageType = %d\n%s\n",getPackedSize(),data.messageType,buf); - delete [] buf; - } - fromEndian(); - - return result; -} - -void NetworkMessageQuit::send(Socket* socket) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] nmtQuit\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - assert(messageType == nmtQuit); - toEndian(); - - if(useOldProtocol == true) { - NetworkMessage::send(socket, &messageType, sizeof(messageType)); - } - else { - unsigned char *buf = packMessage(); - //printf("Send packet size = %u data.messageType = %d\n[%s]\n",getPackedSize(),data.messageType,buf); - NetworkMessage::send(socket, buf, getPackedSize()); - delete [] buf; - } + unpack(buf, getPackedMessageFormat(), &messageType); +} + +unsigned char *NetworkMessageQuit::packMessage() { + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + pack(buf, getPackedMessageFormat(), messageType); + return buf; +} + +bool NetworkMessageQuit::receive(Socket *socket) { + bool result = false; + if (useOldProtocol == true) { + result = NetworkMessage::receive(socket, &messageType, sizeof(messageType), + true); + } else { + // fromEndian(); + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + result = NetworkMessage::receive(socket, buf, getPackedSize(), true); + unpackMessage(buf); + // printf("Got packet size = %u data.messageType = + // %d\n%s\n",getPackedSize(),data.messageType,buf); + delete[] buf; + } + fromEndian(); + + return result; +} + +void NetworkMessageQuit::send(Socket *socket) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d] nmtQuit\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + assert(messageType == nmtQuit); + toEndian(); + + if (useOldProtocol == true) { + NetworkMessage::send(socket, &messageType, sizeof(messageType)); + } else { + unsigned char *buf = packMessage(); + // printf("Send packet size = %u data.messageType = + // %d\n[%s]\n",getPackedSize(),data.messageType,buf); + NetworkMessage::send(socket, buf, getPackedSize()); + delete[] buf; + } } void NetworkMessageQuit::toEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); + } } void NetworkMessageQuit::fromEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); + } } // ===================================================== // class NetworkMessageSynchNetworkGameData // ===================================================== -NetworkMessageSynchNetworkGameData::NetworkMessageSynchNetworkGameData(const GameSettings *gameSettings) -{ - data.messageType= nmtSynchNetworkGameData; - - if(gameSettings == NULL) { - throw std::runtime_error("gameSettings == NULL"); - } - data.header.map = gameSettings->getMap(); - data.header.tileset = gameSettings->getTileset(); - data.header.tech = gameSettings->getTech(); - - Config &config = Config::getInstance(); - string scenarioDir = ""; - if(gameSettings->getScenarioDir() != "") { - scenarioDir = gameSettings->getScenarioDir(); - if(EndsWith(scenarioDir, ".xml") == true) { - scenarioDir = scenarioDir.erase(scenarioDir.size() - 4, 4); - scenarioDir = scenarioDir.erase(scenarioDir.size() - gameSettings->getScenario().size(), gameSettings->getScenario().size() + 1); +NetworkMessageSynchNetworkGameData::NetworkMessageSynchNetworkGameData( + const GameSettings *gameSettings) { + data.messageType = nmtSynchNetworkGameData; + + if (gameSettings == NULL) { + throw std::runtime_error("gameSettings == NULL"); + } + data.header.map = gameSettings->getMap(); + data.header.tileset = gameSettings->getTileset(); + data.header.tech = gameSettings->getTech(); + + Config &config = Config::getInstance(); + string scenarioDir = ""; + if (gameSettings->getScenarioDir() != "") { + scenarioDir = gameSettings->getScenarioDir(); + if (EndsWith(scenarioDir, ".xml") == true) { + scenarioDir = scenarioDir.erase(scenarioDir.size() - 4, 4); + scenarioDir = scenarioDir.erase(scenarioDir.size() - + gameSettings->getScenario().size(), + gameSettings->getScenario().size() + 1); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] gameSettings.getScenarioDir() = [%s] " + "gameSettings.getScenario() = [%s] scenarioDir = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, gameSettings->getScenarioDir().c_str(), + gameSettings->getScenario().c_str(), scenarioDir.c_str()); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + data.header.tilesetCRC = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTilesets, scenarioDir), + string("/") + gameSettings->getTileset() + string("/*"), ".xml", NULL); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] data.tilesetCRC = %d, [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + data.header.tilesetCRC, gameSettings->getTileset().c_str()); + + // tech, load before map because of resources + data.header.techCRC = getFolderTreeContentsCheckSumRecursively( + config.getPathListForType(ptTechs, scenarioDir), + string("/") + gameSettings->getTech() + string("/*"), ".xml", NULL); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] data.techCRC = %d, [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, data.header.techCRC, + gameSettings->getTech().c_str()); + + vector> vctFileList; + vctFileList = getFolderTreeContentsCheckSumListRecursively( + config.getPathListForType(ptTechs, scenarioDir), + string("/") + gameSettings->getTech() + string("/*"), ".xml", + &vctFileList); + data.header.techCRCFileCount = + min((int)vctFileList.size(), (int)maxFileCRCCount); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] vctFileList.size() = %d, maxFileCRCCount = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + vctFileList.size(), maxFileCRCCount); + + for (int idx = 0; idx < (int)data.header.techCRCFileCount; ++idx) { + const std::pair &fileInfo = vctFileList[idx]; + data.detail.techCRCFileList[idx] = fileInfo.first; + data.detail.techCRCFileCRCList[idx] = fileInfo.second; + } + + // map + Checksum checksum; + string file = Config::getMapPath(gameSettings->getMap(), scenarioDir, false); + checksum.addFile(file); + data.header.mapCRC = checksum.getSum(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] data.mapCRC = %d, [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, data.header.mapCRC, + gameSettings->getMap().c_str()); +} + +string NetworkMessageSynchNetworkGameData::getTechCRCFileMismatchReport( + vector> &vctFileList) { + string result = "Techtree: [" + data.header.tech.getString() + + "] Filecount local: " + intToStr(vctFileList.size()) + + " remote: " + intToStr(data.header.techCRCFileCount) + "\n"; + if (vctFileList.size() <= 0) { + result = result + "Local player has no files.\n"; + } else if (data.header.techCRCFileCount <= 0) { + result = result + "Remote player has no files.\n"; + } else { + for (int idx = 0; idx < (int)vctFileList.size(); ++idx) { + std::pair &fileInfo = vctFileList[idx]; + bool fileFound = false; + uint32 remoteCRC = 0; + for (int j = 0; j < (int)data.header.techCRCFileCount; ++j) { + string networkFile = data.detail.techCRCFileList[j].getString(); + uint32 &networkFileCRC = data.detail.techCRCFileCRCList[j]; + if (fileInfo.first == networkFile) { + fileFound = true; + remoteCRC = networkFileCRC; + break; } + } + + if (fileFound == false) { + result = + result + "local file [" + fileInfo.first + "] missing remotely.\n"; + } else if (fileInfo.second != remoteCRC) { + result = result + "local file [" + fileInfo.first + "] CRC mismatch.\n"; + } + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] gameSettings.getScenarioDir() = [%s] gameSettings.getScenario() = [%s] scenarioDir = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,gameSettings->getScenarioDir().c_str(),gameSettings->getScenario().c_str(),scenarioDir.c_str()); + for (int i = 0; i < (int)data.header.techCRCFileCount; ++i) { + string networkFile = data.detail.techCRCFileList[i].getString(); + uint32 &networkFileCRC = data.detail.techCRCFileCRCList[i]; + bool fileFound = false; + uint32 localCRC = 0; + for (int idx = 0; idx < (int)vctFileList.size(); ++idx) { + std::pair &fileInfo = vctFileList[idx]; + if (networkFile == fileInfo.first) { + fileFound = true; + localCRC = fileInfo.second; + break; + } + } + + if (fileFound == false) { + result = + result + "remote file [" + networkFile + "] missing locally.\n"; + } else if (networkFileCRC != localCRC) { + result = result + "remote file [" + networkFile + "] CRC mismatch.\n"; + } } + } + return result; +} - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - data.header.tilesetCRC = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTilesets,scenarioDir), string("/") + gameSettings->getTileset() + string("/*"), ".xml", NULL); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] data.tilesetCRC = %d, [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__, data.header.tilesetCRC,gameSettings->getTileset().c_str()); - - //tech, load before map because of resources - data.header.techCRC = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,scenarioDir), string("/") + gameSettings->getTech() + string("/*"), ".xml", NULL); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] data.techCRC = %d, [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__, data.header.techCRC,gameSettings->getTech().c_str()); - - vector > vctFileList; - vctFileList = getFolderTreeContentsCheckSumListRecursively(config.getPathListForType(ptTechs,scenarioDir),string("/") + gameSettings->getTech() + string("/*"), ".xml",&vctFileList); - data.header.techCRCFileCount = min((int)vctFileList.size(),(int)maxFileCRCCount); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] vctFileList.size() = %d, maxFileCRCCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__, vctFileList.size(),maxFileCRCCount); - - for(int idx =0; idx < (int)data.header.techCRCFileCount; ++idx) { - const std::pair &fileInfo = vctFileList[idx]; - data.detail.techCRCFileList[idx] = fileInfo.first; - data.detail.techCRCFileCRCList[idx] = fileInfo.second; - } - - //map - Checksum checksum; - string file = Config::getMapPath(gameSettings->getMap(),scenarioDir,false); - checksum.addFile(file); - data.header.mapCRC = checksum.getSum(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] data.mapCRC = %d, [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__, data.header.mapCRC,gameSettings->getMap().c_str()); -} - -string NetworkMessageSynchNetworkGameData::getTechCRCFileMismatchReport(vector > &vctFileList) { - string result = "Techtree: [" + data.header.tech.getString() + "] Filecount local: " + intToStr(vctFileList.size()) + " remote: " + intToStr(data.header.techCRCFileCount) + "\n"; - if(vctFileList.size() <= 0) { - result = result + "Local player has no files.\n"; - } - else if(data.header.techCRCFileCount <= 0) { - result = result + "Remote player has no files.\n"; - } - else { - for(int idx = 0; idx < (int)vctFileList.size(); ++idx) { - std::pair &fileInfo = vctFileList[idx]; - bool fileFound = false; - uint32 remoteCRC = 0; - for(int j = 0; j < (int)data.header.techCRCFileCount; ++j) { - string networkFile = data.detail.techCRCFileList[j].getString(); - uint32 &networkFileCRC = data.detail.techCRCFileCRCList[j]; - if(fileInfo.first == networkFile) { - fileFound = true; - remoteCRC = networkFileCRC; - break; - } - } - - if(fileFound == false) { - result = result + "local file [" + fileInfo.first + "] missing remotely.\n"; - } - else if(fileInfo.second != remoteCRC) { - result = result + "local file [" + fileInfo.first + "] CRC mismatch.\n"; - } - } - - for(int i = 0; i < (int)data.header.techCRCFileCount; ++i) { - string networkFile = data.detail.techCRCFileList[i].getString(); - uint32 &networkFileCRC = data.detail.techCRCFileCRCList[i]; - bool fileFound = false; - uint32 localCRC = 0; - for(int idx = 0; idx < (int)vctFileList.size(); ++idx) { - std::pair &fileInfo = vctFileList[idx]; - if(networkFile == fileInfo.first) { - fileFound = true; - localCRC = fileInfo.second; - break; - } - } - - if(fileFound == false) { - result = result + "remote file [" + networkFile + "] missing locally.\n"; - } - else if(networkFileCRC != localCRC) { - result = result + "remote file [" + networkFile + "] CRC mismatch.\n"; - } - } - } - return result; -} - -const char * NetworkMessageSynchNetworkGameData::getPackedMessageFormatHeader() const { - return "c255s255s255sLLLL"; +const char * +NetworkMessageSynchNetworkGameData::getPackedMessageFormatHeader() const { + return "c255s255s255sLLLL"; } unsigned int NetworkMessageSynchNetworkGameData::getPackedSizeHeader() { - static unsigned int result = 0; - if(result == 0) { - Data packedData; - packedData.messageType=0; - unsigned char *buf = new unsigned char[sizeof(packedData)*3]; - result = pack(buf, getPackedMessageFormatHeader(), - packedData.messageType, - packedData.header.map.getBuffer(), - packedData.header.tileset.getBuffer(), - packedData.header.tech.getBuffer(), - packedData.header.mapCRC, - packedData.header.tilesetCRC, - packedData.header.techCRC, - packedData.header.techCRCFileCount); - delete [] buf; - } - return result; -} -void NetworkMessageSynchNetworkGameData::unpackMessageHeader(unsigned char *buf) { - unpack(buf, getPackedMessageFormatHeader(), - &data.messageType, - data.header.map.getBuffer(), - data.header.tileset.getBuffer(), - data.header.tech.getBuffer(), - &data.header.mapCRC, - &data.header.tilesetCRC, - &data.header.techCRC, - &data.header.techCRCFileCount); -} - -unsigned char * NetworkMessageSynchNetworkGameData::packMessageHeader() { - unsigned char *buf = new unsigned char[getPackedSizeHeader()+1]; - pack(buf, getPackedMessageFormatHeader(), - data.messageType, - data.header.map.getBuffer(), - data.header.tileset.getBuffer(), - data.header.tech.getBuffer(), - data.header.mapCRC, - data.header.tilesetCRC, - data.header.techCRC, - data.header.techCRCFileCount); - - return buf; + static unsigned int result = 0; + if (result == 0) { + Data packedData; + packedData.messageType = 0; + unsigned char *buf = new unsigned char[sizeof(packedData) * 3]; + result = pack(buf, getPackedMessageFormatHeader(), packedData.messageType, + packedData.header.map.getBuffer(), + packedData.header.tileset.getBuffer(), + packedData.header.tech.getBuffer(), packedData.header.mapCRC, + packedData.header.tilesetCRC, packedData.header.techCRC, + packedData.header.techCRCFileCount); + delete[] buf; + } + return result; +} +void NetworkMessageSynchNetworkGameData::unpackMessageHeader( + unsigned char *buf) { + unpack(buf, getPackedMessageFormatHeader(), &data.messageType, + data.header.map.getBuffer(), data.header.tileset.getBuffer(), + data.header.tech.getBuffer(), &data.header.mapCRC, + &data.header.tilesetCRC, &data.header.techCRC, + &data.header.techCRCFileCount); +} + +unsigned char *NetworkMessageSynchNetworkGameData::packMessageHeader() { + unsigned char *buf = new unsigned char[getPackedSizeHeader() + 1]; + pack(buf, getPackedMessageFormatHeader(), data.messageType, + data.header.map.getBuffer(), data.header.tileset.getBuffer(), + data.header.tech.getBuffer(), data.header.mapCRC, data.header.tilesetCRC, + data.header.techCRC, data.header.techCRCFileCount); + + return buf; } unsigned int NetworkMessageSynchNetworkGameData::getPackedSizeDetail() { - static unsigned int result = 0; - if(result == 0) { - DataDetail packedData; - for(unsigned int index = 0; index < (unsigned int)maxFileCRCCount; ++index) { - packedData.techCRCFileCRCList[index] = 0; - } - unsigned char *buf = new unsigned char[sizeof(DataDetail)*3]; - - for(unsigned int i = 0; i < (unsigned int)maxFileCRCCount; ++i) { - result += pack(buf, "255s", - packedData.techCRCFileList[i].getBuffer()); - buf += result; - } - for(unsigned int i = 0; i < (unsigned int)maxFileCRCCount; ++i) { - result += pack(buf, "L", - packedData.techCRCFileCRCList[i]); - buf += result; - } - - delete [] buf; - } - return result; -} -void NetworkMessageSynchNetworkGameData::unpackMessageDetail(unsigned char *buf) { - for(unsigned int i = 0; i < (unsigned int)maxFileCRCCount; ++i) { - unsigned int bytes_processed = unpack(buf, "255s", - data.detail.techCRCFileList[i].getBuffer()); - buf += bytes_processed; - } - for(unsigned int i = 0; i < (unsigned int)maxFileCRCCount; ++i) { - unsigned int bytes_processed = unpack(buf, "L", - &data.detail.techCRCFileCRCList[i]); - buf += bytes_processed; - } -} - -unsigned char * NetworkMessageSynchNetworkGameData::packMessageDetail() { - unsigned char *buf = new unsigned char[sizeof(DataDetail)*3 +1]; - unsigned char *bufMove = buf; - for(unsigned int i = 0; i < (unsigned int)maxFileCRCCount; ++i) { - unsigned int bytes_processed = pack(bufMove, "255s", - data.detail.techCRCFileList[i].getBuffer()); - bufMove += bytes_processed; - } - for(unsigned int i = 0; i < (unsigned int)maxFileCRCCount; ++i) { - unsigned int bytes_processed = pack(bufMove, "L", - data.detail.techCRCFileCRCList[i]); - bufMove += bytes_processed; - } - - return buf; -} - - -bool NetworkMessageSynchNetworkGameData::receive(Socket* socket) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] about to get nmtSynchNetworkGameData\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - data.header.techCRCFileCount = 0; - bool result = NetworkMessage::receive(socket, &data.header, HeaderSize, true); - fromEndianHeader(); - if(result == true) { - data.messageType = nmtSynchNetworkGameData; - } - - if(result == true && data.header.techCRCFileCount > 0) { - data.header.map.nullTerminate(); - data.header.tileset.nullTerminate(); - data.header.tech.nullTerminate(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] messageType = %d, data.techCRCFileCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,data.messageType,data.header.techCRCFileCount); - - - - // Here we loop possibly multiple times - int packetLoopCount = 1; - if(data.header.techCRCFileCount > (uint32)NetworkMessageSynchNetworkGameData::maxFileCRCPacketCount) { - packetLoopCount = (data.header.techCRCFileCount / NetworkMessageSynchNetworkGameData::maxFileCRCPacketCount); - if(data.header.techCRCFileCount % NetworkMessageSynchNetworkGameData::maxFileCRCPacketCount > 0) { - packetLoopCount++; - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] packetLoopCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,packetLoopCount); - - for(int iPacketLoop = 0; result == true && iPacketLoop < packetLoopCount; ++iPacketLoop) { - - int packetIndex = iPacketLoop * NetworkMessageSynchNetworkGameData::maxFileCRCPacketCount; - int maxFileCountPerPacket = maxFileCRCPacketCount; - int packetFileCount = min((uint32)maxFileCountPerPacket,data.header.techCRCFileCount - packetIndex); - int packetDetail1DataSize = (DetailSize1 * packetFileCount); - int packetDetail2DataSize = (DetailSize2 * packetFileCount); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] iPacketLoop = %d, packetIndex = %d, maxFileCountPerPacket = %d, packetFileCount = %d, packetDetail1DataSize = %d, packetDetail2DataSize = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,iPacketLoop,packetIndex,maxFileCountPerPacket,packetFileCount,packetDetail1DataSize,packetDetail2DataSize); - - // Wait a max of x seconds for this message - result = NetworkMessage::receive(socket, &data.detail.techCRCFileList[packetIndex], packetDetail1DataSize, true); - if(result == true) { - for(unsigned int i = 0; i < data.header.techCRCFileCount; ++i) { - data.detail.techCRCFileList[i].nullTerminate(); - } - - result = NetworkMessage::receive(socket, &data.detail.techCRCFileCRCList[packetIndex], packetDetail2DataSize, true); - } - } - fromEndianDetail(); - } - - return result; -} - -void NetworkMessageSynchNetworkGameData::send(Socket* socket) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] about to send nmtSynchNetworkGameData\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - assert(data.messageType == nmtSynchNetworkGameData); - uint32 totalFileCount = data.header.techCRCFileCount; - toEndianHeader(); - NetworkMessage::send(socket, &data, HeaderSize); - if(totalFileCount > 0) { - // Here we loop possibly multiple times - int packetLoopCount = 1; - if(totalFileCount > (uint32)NetworkMessageSynchNetworkGameData::maxFileCRCPacketCount) { - packetLoopCount = (totalFileCount / NetworkMessageSynchNetworkGameData::maxFileCRCPacketCount); - if(totalFileCount % NetworkMessageSynchNetworkGameData::maxFileCRCPacketCount > 0) { - packetLoopCount++; - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] packetLoopCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,packetLoopCount); + static unsigned int result = 0; + if (result == 0) { + DataDetail packedData; + for (unsigned int index = 0; index < (unsigned int)maxFileCRCCount; + ++index) { + packedData.techCRCFileCRCList[index] = 0; + } + unsigned char *buf = new unsigned char[sizeof(DataDetail) * 3]; + + for (unsigned int i = 0; i < (unsigned int)maxFileCRCCount; ++i) { + result += pack(buf, "255s", packedData.techCRCFileList[i].getBuffer()); + buf += result; + } + for (unsigned int i = 0; i < (unsigned int)maxFileCRCCount; ++i) { + result += pack(buf, "L", packedData.techCRCFileCRCList[i]); + buf += result; + } - for(int iPacketLoop = 0; iPacketLoop < packetLoopCount; ++iPacketLoop) { + delete[] buf; + } + return result; +} +void NetworkMessageSynchNetworkGameData::unpackMessageDetail( + unsigned char *buf) { + for (unsigned int i = 0; i < (unsigned int)maxFileCRCCount; ++i) { + unsigned int bytes_processed = + unpack(buf, "255s", data.detail.techCRCFileList[i].getBuffer()); + buf += bytes_processed; + } + for (unsigned int i = 0; i < (unsigned int)maxFileCRCCount; ++i) { + unsigned int bytes_processed = + unpack(buf, "L", &data.detail.techCRCFileCRCList[i]); + buf += bytes_processed; + } +} + +unsigned char *NetworkMessageSynchNetworkGameData::packMessageDetail() { + unsigned char *buf = new unsigned char[sizeof(DataDetail) * 3 + 1]; + unsigned char *bufMove = buf; + for (unsigned int i = 0; i < (unsigned int)maxFileCRCCount; ++i) { + unsigned int bytes_processed = + pack(bufMove, "255s", data.detail.techCRCFileList[i].getBuffer()); + bufMove += bytes_processed; + } + for (unsigned int i = 0; i < (unsigned int)maxFileCRCCount; ++i) { + unsigned int bytes_processed = + pack(bufMove, "L", data.detail.techCRCFileCRCList[i]); + bufMove += bytes_processed; + } + + return buf; +} + +bool NetworkMessageSynchNetworkGameData::receive(Socket *socket) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] about to get nmtSynchNetworkGameData\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + data.header.techCRCFileCount = 0; + bool result = NetworkMessage::receive(socket, &data.header, HeaderSize, true); + fromEndianHeader(); + if (result == true) { + data.messageType = nmtSynchNetworkGameData; + } + + if (result == true && data.header.techCRCFileCount > 0) { + data.header.map.nullTerminate(); + data.header.tileset.nullTerminate(); + data.header.tech.nullTerminate(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] messageType = %d, data.techCRCFileCount = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, data.messageType, data.header.techCRCFileCount); + + // Here we loop possibly multiple times + int packetLoopCount = 1; + if (data.header.techCRCFileCount > + (uint32)NetworkMessageSynchNetworkGameData::maxFileCRCPacketCount) { + packetLoopCount = + (data.header.techCRCFileCount / + NetworkMessageSynchNetworkGameData::maxFileCRCPacketCount); + if (data.header.techCRCFileCount % + NetworkMessageSynchNetworkGameData::maxFileCRCPacketCount > + 0) { + packetLoopCount++; + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] packetLoopCount = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, packetLoopCount); + + for (int iPacketLoop = 0; result == true && iPacketLoop < packetLoopCount; + ++iPacketLoop) { + + int packetIndex = + iPacketLoop * + NetworkMessageSynchNetworkGameData::maxFileCRCPacketCount; + int maxFileCountPerPacket = maxFileCRCPacketCount; + int packetFileCount = min((uint32)maxFileCountPerPacket, + data.header.techCRCFileCount - packetIndex); + int packetDetail1DataSize = (DetailSize1 * packetFileCount); + int packetDetail2DataSize = (DetailSize2 * packetFileCount); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] iPacketLoop = %d, packetIndex = %d, " + "maxFileCountPerPacket = %d, packetFileCount = %d, " + "packetDetail1DataSize = %d, packetDetail2DataSize = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, iPacketLoop, packetIndex, maxFileCountPerPacket, + packetFileCount, packetDetail1DataSize, packetDetail2DataSize); + + // Wait a max of x seconds for this message + result = NetworkMessage::receive( + socket, &data.detail.techCRCFileList[packetIndex], + packetDetail1DataSize, true); + if (result == true) { + for (unsigned int i = 0; i < data.header.techCRCFileCount; ++i) { + data.detail.techCRCFileList[i].nullTerminate(); + } - int packetIndex = iPacketLoop * NetworkMessageSynchNetworkGameData::maxFileCRCPacketCount; - int maxFileCountPerPacket = maxFileCRCPacketCount; - int packetFileCount = min((uint32)maxFileCountPerPacket,totalFileCount - packetIndex); + result = NetworkMessage::receive( + socket, &data.detail.techCRCFileCRCList[packetIndex], + packetDetail2DataSize, true); + } + } + fromEndianDetail(); + } + + return result; +} + +void NetworkMessageSynchNetworkGameData::send(Socket *socket) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] about to send nmtSynchNetworkGameData\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + assert(data.messageType == nmtSynchNetworkGameData); + uint32 totalFileCount = data.header.techCRCFileCount; + toEndianHeader(); + NetworkMessage::send(socket, &data, HeaderSize); + if (totalFileCount > 0) { + // Here we loop possibly multiple times + int packetLoopCount = 1; + if (totalFileCount > + (uint32)NetworkMessageSynchNetworkGameData::maxFileCRCPacketCount) { + packetLoopCount = + (totalFileCount / + NetworkMessageSynchNetworkGameData::maxFileCRCPacketCount); + if (totalFileCount % + NetworkMessageSynchNetworkGameData::maxFileCRCPacketCount > + 0) { + packetLoopCount++; + } + } - NetworkMessage::send(socket, &data.detail.techCRCFileList[packetIndex], (DetailSize1 * packetFileCount)); - NetworkMessage::send(socket, &data.detail.techCRCFileCRCList[packetIndex], (DetailSize2 * packetFileCount)); - } - toEndianDetail(totalFileCount); - } + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] packetLoopCount = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, packetLoopCount); + + for (int iPacketLoop = 0; iPacketLoop < packetLoopCount; ++iPacketLoop) { + + int packetIndex = + iPacketLoop * + NetworkMessageSynchNetworkGameData::maxFileCRCPacketCount; + int maxFileCountPerPacket = maxFileCRCPacketCount; + int packetFileCount = + min((uint32)maxFileCountPerPacket, totalFileCount - packetIndex); + + NetworkMessage::send(socket, &data.detail.techCRCFileList[packetIndex], + (DetailSize1 * packetFileCount)); + NetworkMessage::send(socket, &data.detail.techCRCFileCRCList[packetIndex], + (DetailSize2 * packetFileCount)); + } + toEndianDetail(totalFileCount); + } } void NetworkMessageSynchNetworkGameData::toEndianHeader() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - data.messageType = Shared::PlatformByteOrder::toCommonEndian(data.messageType); - data.header.mapCRC = Shared::PlatformByteOrder::toCommonEndian(data.header.mapCRC); - data.header.tilesetCRC = Shared::PlatformByteOrder::toCommonEndian(data.header.tilesetCRC); - data.header.techCRC = Shared::PlatformByteOrder::toCommonEndian(data.header.techCRC); - data.header.techCRCFileCount = Shared::PlatformByteOrder::toCommonEndian(data.header.techCRCFileCount); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + data.messageType = + Shared::PlatformByteOrder::toCommonEndian(data.messageType); + data.header.mapCRC = + Shared::PlatformByteOrder::toCommonEndian(data.header.mapCRC); + data.header.tilesetCRC = + Shared::PlatformByteOrder::toCommonEndian(data.header.tilesetCRC); + data.header.techCRC = + Shared::PlatformByteOrder::toCommonEndian(data.header.techCRC); + data.header.techCRCFileCount = + Shared::PlatformByteOrder::toCommonEndian(data.header.techCRCFileCount); + } } void NetworkMessageSynchNetworkGameData::fromEndianHeader() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - data.messageType = Shared::PlatformByteOrder::fromCommonEndian(data.messageType); - data.header.mapCRC = Shared::PlatformByteOrder::fromCommonEndian(data.header.mapCRC); - data.header.tilesetCRC = Shared::PlatformByteOrder::fromCommonEndian(data.header.tilesetCRC); - data.header.techCRC = Shared::PlatformByteOrder::fromCommonEndian(data.header.techCRC); - data.header.techCRCFileCount = Shared::PlatformByteOrder::fromCommonEndian(data.header.techCRCFileCount); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + data.messageType = + Shared::PlatformByteOrder::fromCommonEndian(data.messageType); + data.header.mapCRC = + Shared::PlatformByteOrder::fromCommonEndian(data.header.mapCRC); + data.header.tilesetCRC = + Shared::PlatformByteOrder::fromCommonEndian(data.header.tilesetCRC); + data.header.techCRC = + Shared::PlatformByteOrder::fromCommonEndian(data.header.techCRC); + data.header.techCRCFileCount = Shared::PlatformByteOrder::fromCommonEndian( + data.header.techCRCFileCount); + } } void NetworkMessageSynchNetworkGameData::toEndianDetail(uint32 totalFileCount) { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - for(unsigned int i = 0; i < totalFileCount; ++i) { - data.detail.techCRCFileCRCList[i] = Shared::PlatformByteOrder::toCommonEndian(data.detail.techCRCFileCRCList[i]); - } - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + for (unsigned int i = 0; i < totalFileCount; ++i) { + data.detail.techCRCFileCRCList[i] = + Shared::PlatformByteOrder::toCommonEndian( + data.detail.techCRCFileCRCList[i]); + } + } } void NetworkMessageSynchNetworkGameData::fromEndianDetail() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - for(unsigned int i = 0; i < data.header.techCRCFileCount; ++i) { - data.detail.techCRCFileCRCList[i] = Shared::PlatformByteOrder::fromCommonEndian(data.detail.techCRCFileCRCList[i]); - } - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + for (unsigned int i = 0; i < data.header.techCRCFileCount; ++i) { + data.detail.techCRCFileCRCList[i] = + Shared::PlatformByteOrder::fromCommonEndian( + data.detail.techCRCFileCRCList[i]); + } + } } // ===================================================== // class NetworkMessageSynchNetworkGameDataStatus // ===================================================== -NetworkMessageSynchNetworkGameDataStatus::NetworkMessageSynchNetworkGameDataStatus(uint32 mapCRC, uint32 tilesetCRC, uint32 techCRC, vector > &vctFileList) -{ - data.messageType= nmtSynchNetworkGameDataStatus; - - data.header.tilesetCRC = tilesetCRC; - data.header.techCRC = techCRC; - data.header.mapCRC = mapCRC; - - data.header.techCRCFileCount = min((int)vctFileList.size(),(int)maxFileCRCCount); - for(unsigned int idx =0; idx < data.header.techCRCFileCount; ++idx) { - const std::pair &fileInfo = vctFileList[idx]; - data.detail.techCRCFileList[idx] = fileInfo.first; - data.detail.techCRCFileCRCList[idx] = fileInfo.second; - } -} - -string NetworkMessageSynchNetworkGameDataStatus::getTechCRCFileMismatchReport(string techtree, vector > &vctFileList) { - string result = "Techtree: [" + techtree + "] Filecount local: " + intToStr(vctFileList.size()) + " remote: " + intToStr(data.header.techCRCFileCount) + "\n"; - if(vctFileList.size() <= 0) { - result = result + "Local player has no files.\n"; - } - else if(data.header.techCRCFileCount <= 0) { - result = result + "Remote player has no files.\n"; - } - else { - for(int idx = 0; idx < (int)vctFileList.size(); ++idx) { - std::pair &fileInfo = vctFileList[idx]; - bool fileFound = false; - uint32 remoteCRC = 0; - for(int j = 0; j < (int)data.header.techCRCFileCount; ++j) { - string networkFile = data.detail.techCRCFileList[j].getString(); - uint32 &networkFileCRC = data.detail.techCRCFileCRCList[j]; - if(fileInfo.first == networkFile) { - fileFound = true; - remoteCRC = networkFileCRC; - break; - } - } - - if(fileFound == false) { - result = result + "local file [" + fileInfo.first + "] missing remotely.\n"; - } - else if(fileInfo.second != remoteCRC) { - result = result + "local file [" + fileInfo.first + "] CRC mismatch.\n"; - } - } - - for(int i = 0; i < (int)data.header.techCRCFileCount; ++i) { - string networkFile = data.detail.techCRCFileList[i].getString(); - uint32 &networkFileCRC = data.detail.techCRCFileCRCList[i]; - bool fileFound = false; - uint32 localCRC = 0; - for(int idx = 0; idx < (int)vctFileList.size(); ++idx) { - std::pair &fileInfo = vctFileList[idx]; - - if(networkFile == fileInfo.first) { - fileFound = true; - localCRC = fileInfo.second; - break; - } - } - - if(fileFound == false) { - result = result + "remote file [" + networkFile + "] missing locally.\n"; - } - else if(networkFileCRC != localCRC) { - result = result + "remote file [" + networkFile + "] CRC mismatch.\n"; - } - } - } - return result; -} - -bool NetworkMessageSynchNetworkGameDataStatus::receive(Socket* socket) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] about to get nmtSynchNetworkGameDataStatus\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - data.header.techCRCFileCount = 0; - - bool result = NetworkMessage::receive(socket, &data.header, HeaderSize, true); - if(result == true && data.header.techCRCFileCount > 0) { - fromEndianHeader(); - // Here we loop possibly multiple times - uint32 packetLoopCount = 1; - if(data.header.techCRCFileCount > NetworkMessageSynchNetworkGameDataStatus::maxFileCRCPacketCount) { - packetLoopCount = (data.header.techCRCFileCount / NetworkMessageSynchNetworkGameDataStatus::maxFileCRCPacketCount); - if(data.header.techCRCFileCount % NetworkMessageSynchNetworkGameDataStatus::maxFileCRCPacketCount > 0) { - packetLoopCount++; - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] packetLoopCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,packetLoopCount); - - for(uint32 iPacketLoop = 0; iPacketLoop < packetLoopCount; ++iPacketLoop) { - - uint32 packetIndex = iPacketLoop * NetworkMessageSynchNetworkGameDataStatus::maxFileCRCPacketCount; - uint32 maxFileCountPerPacket = maxFileCRCPacketCount; - uint32 packetFileCount = min((uint32)maxFileCountPerPacket,data.header.techCRCFileCount - packetIndex); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] iPacketLoop = %u, packetIndex = %u, packetFileCount = %u\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,iPacketLoop,packetIndex,packetFileCount); - - result = NetworkMessage::receive(socket, &data.detail.techCRCFileList[packetIndex], ((uint32)DetailSize1 * packetFileCount),true); - if(result == true) { - for(int i = 0; i < (int)data.header.techCRCFileCount; ++i) { - data.detail.techCRCFileList[i].nullTerminate(); - } - - // Wait a max of x seconds for this message - result = NetworkMessage::receive(socket, &data.detail.techCRCFileCRCList[packetIndex], ((uint32)DetailSize2 * packetFileCount),true); - } - } - fromEndianDetail(); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] result = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,result); - - return result; -} - -void NetworkMessageSynchNetworkGameDataStatus::send(Socket* socket) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] about to send nmtSynchNetworkGameDataStatus, data.header.techCRCFileCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,data.header.techCRCFileCount); - - assert(data.messageType == nmtSynchNetworkGameDataStatus); - uint32 totalFileCount = data.header.techCRCFileCount; - toEndianHeader(); - NetworkMessage::send(socket, &data, HeaderSize); - if(totalFileCount > 0) { - // Here we loop possibly multiple times - int packetLoopCount = 1; - if(totalFileCount > NetworkMessageSynchNetworkGameDataStatus::maxFileCRCPacketCount) { - packetLoopCount = (totalFileCount / NetworkMessageSynchNetworkGameDataStatus::maxFileCRCPacketCount); - if(totalFileCount % NetworkMessageSynchNetworkGameDataStatus::maxFileCRCPacketCount > 0) { - packetLoopCount++; - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] packetLoopCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,packetLoopCount); - - toEndianDetail(totalFileCount); - for(int iPacketLoop = 0; iPacketLoop < packetLoopCount; ++iPacketLoop) { - - int packetIndex = iPacketLoop * NetworkMessageSynchNetworkGameDataStatus::maxFileCRCPacketCount; - int maxFileCountPerPacket = maxFileCRCPacketCount; - int packetFileCount = min((uint32)maxFileCountPerPacket,totalFileCount - packetIndex); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] packetLoop = %d, packetIndex = %d, packetFileCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,iPacketLoop,packetIndex,packetFileCount); - - NetworkMessage::send(socket, &data.detail.techCRCFileList[packetIndex], (DetailSize1 * packetFileCount)); - NetworkMessage::send(socket, &data.detail.techCRCFileCRCList[packetIndex], (DetailSize2 * packetFileCount)); - } - } +NetworkMessageSynchNetworkGameDataStatus:: + NetworkMessageSynchNetworkGameDataStatus( + uint32 mapCRC, uint32 tilesetCRC, uint32 techCRC, + vector> &vctFileList) { + data.messageType = nmtSynchNetworkGameDataStatus; + + data.header.tilesetCRC = tilesetCRC; + data.header.techCRC = techCRC; + data.header.mapCRC = mapCRC; + + data.header.techCRCFileCount = + min((int)vctFileList.size(), (int)maxFileCRCCount); + for (unsigned int idx = 0; idx < data.header.techCRCFileCount; ++idx) { + const std::pair &fileInfo = vctFileList[idx]; + data.detail.techCRCFileList[idx] = fileInfo.first; + data.detail.techCRCFileCRCList[idx] = fileInfo.second; + } +} + +string NetworkMessageSynchNetworkGameDataStatus::getTechCRCFileMismatchReport( + string techtree, vector> &vctFileList) { + string result = "Techtree: [" + techtree + + "] Filecount local: " + intToStr(vctFileList.size()) + + " remote: " + intToStr(data.header.techCRCFileCount) + "\n"; + if (vctFileList.size() <= 0) { + result = result + "Local player has no files.\n"; + } else if (data.header.techCRCFileCount <= 0) { + result = result + "Remote player has no files.\n"; + } else { + for (int idx = 0; idx < (int)vctFileList.size(); ++idx) { + std::pair &fileInfo = vctFileList[idx]; + bool fileFound = false; + uint32 remoteCRC = 0; + for (int j = 0; j < (int)data.header.techCRCFileCount; ++j) { + string networkFile = data.detail.techCRCFileList[j].getString(); + uint32 &networkFileCRC = data.detail.techCRCFileCRCList[j]; + if (fileInfo.first == networkFile) { + fileFound = true; + remoteCRC = networkFileCRC; + break; + } + } + + if (fileFound == false) { + result = + result + "local file [" + fileInfo.first + "] missing remotely.\n"; + } else if (fileInfo.second != remoteCRC) { + result = result + "local file [" + fileInfo.first + "] CRC mismatch.\n"; + } + } + + for (int i = 0; i < (int)data.header.techCRCFileCount; ++i) { + string networkFile = data.detail.techCRCFileList[i].getString(); + uint32 &networkFileCRC = data.detail.techCRCFileCRCList[i]; + bool fileFound = false; + uint32 localCRC = 0; + for (int idx = 0; idx < (int)vctFileList.size(); ++idx) { + std::pair &fileInfo = vctFileList[idx]; + + if (networkFile == fileInfo.first) { + fileFound = true; + localCRC = fileInfo.second; + break; + } + } + + if (fileFound == false) { + result = + result + "remote file [" + networkFile + "] missing locally.\n"; + } else if (networkFileCRC != localCRC) { + result = result + "remote file [" + networkFile + "] CRC mismatch.\n"; + } + } + } + return result; +} + +bool NetworkMessageSynchNetworkGameDataStatus::receive(Socket *socket) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] about to get nmtSynchNetworkGameDataStatus\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + data.header.techCRCFileCount = 0; + + bool result = NetworkMessage::receive(socket, &data.header, HeaderSize, true); + if (result == true && data.header.techCRCFileCount > 0) { + fromEndianHeader(); + // Here we loop possibly multiple times + uint32 packetLoopCount = 1; + if (data.header.techCRCFileCount > + NetworkMessageSynchNetworkGameDataStatus::maxFileCRCPacketCount) { + packetLoopCount = + (data.header.techCRCFileCount / + NetworkMessageSynchNetworkGameDataStatus::maxFileCRCPacketCount); + if (data.header.techCRCFileCount % + NetworkMessageSynchNetworkGameDataStatus::maxFileCRCPacketCount > + 0) { + packetLoopCount++; + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] packetLoopCount = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, packetLoopCount); + + for (uint32 iPacketLoop = 0; iPacketLoop < packetLoopCount; ++iPacketLoop) { + + uint32 packetIndex = + iPacketLoop * + NetworkMessageSynchNetworkGameDataStatus::maxFileCRCPacketCount; + uint32 maxFileCountPerPacket = maxFileCRCPacketCount; + uint32 packetFileCount = min((uint32)maxFileCountPerPacket, + data.header.techCRCFileCount - packetIndex); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] iPacketLoop = %u, " + "packetIndex = %u, packetFileCount = %u\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, iPacketLoop, + packetIndex, packetFileCount); + + result = NetworkMessage::receive( + socket, &data.detail.techCRCFileList[packetIndex], + ((uint32)DetailSize1 * packetFileCount), true); + if (result == true) { + for (int i = 0; i < (int)data.header.techCRCFileCount; ++i) { + data.detail.techCRCFileList[i].nullTerminate(); + } + + // Wait a max of x seconds for this message + result = NetworkMessage::receive( + socket, &data.detail.techCRCFileCRCList[packetIndex], + ((uint32)DetailSize2 * packetFileCount), true); + } + } + fromEndianDetail(); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] result = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, result); + + return result; +} + +void NetworkMessageSynchNetworkGameDataStatus::send(Socket *socket) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] about to send nmtSynchNetworkGameDataStatus, " + "data.header.techCRCFileCount = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + data.header.techCRCFileCount); + + assert(data.messageType == nmtSynchNetworkGameDataStatus); + uint32 totalFileCount = data.header.techCRCFileCount; + toEndianHeader(); + NetworkMessage::send(socket, &data, HeaderSize); + if (totalFileCount > 0) { + // Here we loop possibly multiple times + int packetLoopCount = 1; + if (totalFileCount > + NetworkMessageSynchNetworkGameDataStatus::maxFileCRCPacketCount) { + packetLoopCount = + (totalFileCount / + NetworkMessageSynchNetworkGameDataStatus::maxFileCRCPacketCount); + if (totalFileCount % + NetworkMessageSynchNetworkGameDataStatus::maxFileCRCPacketCount > + 0) { + packetLoopCount++; + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] packetLoopCount = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, packetLoopCount); + + toEndianDetail(totalFileCount); + for (int iPacketLoop = 0; iPacketLoop < packetLoopCount; ++iPacketLoop) { + + int packetIndex = + iPacketLoop * + NetworkMessageSynchNetworkGameDataStatus::maxFileCRCPacketCount; + int maxFileCountPerPacket = maxFileCRCPacketCount; + int packetFileCount = + min((uint32)maxFileCountPerPacket, totalFileCount - packetIndex); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] packetLoop = %d, " + "packetIndex = %d, packetFileCount = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, iPacketLoop, + packetIndex, packetFileCount); + + NetworkMessage::send(socket, &data.detail.techCRCFileList[packetIndex], + (DetailSize1 * packetFileCount)); + NetworkMessage::send(socket, &data.detail.techCRCFileCRCList[packetIndex], + (DetailSize2 * packetFileCount)); + } + } } void NetworkMessageSynchNetworkGameDataStatus::toEndianHeader() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - data.messageType = Shared::PlatformByteOrder::toCommonEndian(data.messageType); - data.header.mapCRC = Shared::PlatformByteOrder::toCommonEndian(data.header.mapCRC); - data.header.tilesetCRC = Shared::PlatformByteOrder::toCommonEndian(data.header.tilesetCRC); - data.header.techCRC = Shared::PlatformByteOrder::toCommonEndian(data.header.techCRC); - data.header.techCRCFileCount = Shared::PlatformByteOrder::toCommonEndian(data.header.techCRCFileCount); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + data.messageType = + Shared::PlatformByteOrder::toCommonEndian(data.messageType); + data.header.mapCRC = + Shared::PlatformByteOrder::toCommonEndian(data.header.mapCRC); + data.header.tilesetCRC = + Shared::PlatformByteOrder::toCommonEndian(data.header.tilesetCRC); + data.header.techCRC = + Shared::PlatformByteOrder::toCommonEndian(data.header.techCRC); + data.header.techCRCFileCount = + Shared::PlatformByteOrder::toCommonEndian(data.header.techCRCFileCount); + } } void NetworkMessageSynchNetworkGameDataStatus::fromEndianHeader() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - data.messageType = Shared::PlatformByteOrder::fromCommonEndian(data.messageType); - data.header.mapCRC = Shared::PlatformByteOrder::fromCommonEndian(data.header.mapCRC); - data.header.tilesetCRC = Shared::PlatformByteOrder::fromCommonEndian(data.header.tilesetCRC); - data.header.techCRC = Shared::PlatformByteOrder::fromCommonEndian(data.header.techCRC); - data.header.techCRCFileCount = Shared::PlatformByteOrder::fromCommonEndian(data.header.techCRCFileCount); - } -} - -void NetworkMessageSynchNetworkGameDataStatus::toEndianDetail(uint32 totalFileCount) { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - for(unsigned int i = 0; i < totalFileCount; ++i) { - data.detail.techCRCFileCRCList[i] = Shared::PlatformByteOrder::toCommonEndian(data.detail.techCRCFileCRCList[i]); - } - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + data.messageType = + Shared::PlatformByteOrder::fromCommonEndian(data.messageType); + data.header.mapCRC = + Shared::PlatformByteOrder::fromCommonEndian(data.header.mapCRC); + data.header.tilesetCRC = + Shared::PlatformByteOrder::fromCommonEndian(data.header.tilesetCRC); + data.header.techCRC = + Shared::PlatformByteOrder::fromCommonEndian(data.header.techCRC); + data.header.techCRCFileCount = Shared::PlatformByteOrder::fromCommonEndian( + data.header.techCRCFileCount); + } +} + +void NetworkMessageSynchNetworkGameDataStatus::toEndianDetail( + uint32 totalFileCount) { + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + for (unsigned int i = 0; i < totalFileCount; ++i) { + data.detail.techCRCFileCRCList[i] = + Shared::PlatformByteOrder::toCommonEndian( + data.detail.techCRCFileCRCList[i]); + } + } } void NetworkMessageSynchNetworkGameDataStatus::fromEndianDetail() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - for(unsigned int i = 0; i < data.header.techCRCFileCount; ++i) { - data.detail.techCRCFileCRCList[i] = Shared::PlatformByteOrder::fromCommonEndian(data.detail.techCRCFileCRCList[i]); - } - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + for (unsigned int i = 0; i < data.header.techCRCFileCount; ++i) { + data.detail.techCRCFileCRCList[i] = + Shared::PlatformByteOrder::fromCommonEndian( + data.detail.techCRCFileCRCList[i]); + } + } } // ===================================================== // class NetworkMessageSynchNetworkGameDataFileCRCCheck // ===================================================== -NetworkMessageSynchNetworkGameDataFileCRCCheck::NetworkMessageSynchNetworkGameDataFileCRCCheck() { - messageType= nmtSynchNetworkGameDataFileCRCCheck; +NetworkMessageSynchNetworkGameDataFileCRCCheck:: + NetworkMessageSynchNetworkGameDataFileCRCCheck() { + messageType = nmtSynchNetworkGameDataFileCRCCheck; } -NetworkMessageSynchNetworkGameDataFileCRCCheck::NetworkMessageSynchNetworkGameDataFileCRCCheck( - uint32 totalFileCount, uint32 fileIndex, uint32 fileCRC, const string fileName) -{ - messageType= nmtSynchNetworkGameDataFileCRCCheck; +NetworkMessageSynchNetworkGameDataFileCRCCheck:: + NetworkMessageSynchNetworkGameDataFileCRCCheck(uint32 totalFileCount, + uint32 fileIndex, + uint32 fileCRC, + const string fileName) { + messageType = nmtSynchNetworkGameDataFileCRCCheck; - data.totalFileCount = totalFileCount; - data.fileIndex = fileIndex; - data.fileCRC = fileCRC; - data.fileName = fileName; + data.totalFileCount = totalFileCount; + data.fileIndex = fileIndex; + data.fileCRC = fileCRC; + data.fileName = fileName; } -const char * NetworkMessageSynchNetworkGameDataFileCRCCheck::getPackedMessageFormat() const { - return "cLLL256s"; +const char * +NetworkMessageSynchNetworkGameDataFileCRCCheck::getPackedMessageFormat() const { + return "cLLL256s"; } unsigned int NetworkMessageSynchNetworkGameDataFileCRCCheck::getPackedSize() { - static unsigned int result = 0; - if(result == 0) { - Data packedData; - packedData.fileCRC = 0; - packedData.fileIndex = 0; - messageType = nmtSynchNetworkGameDataFileCRCCheck; - packedData.totalFileCount = 0; - - unsigned char *buf = new unsigned char[sizeof(packedData)*3]; - result = pack(buf, getPackedMessageFormat(), - messageType, - packedData.totalFileCount, - packedData.fileIndex, - packedData.fileCRC, - packedData.fileName.getBuffer()); - delete [] buf; - } - return result; -} -void NetworkMessageSynchNetworkGameDataFileCRCCheck::unpackMessage(unsigned char *buf) { - unpack(buf, getPackedMessageFormat(), - &messageType, - &data.totalFileCount, - &data.fileIndex, - &data.fileCRC, - data.fileName.getBuffer()); -} - -unsigned char * NetworkMessageSynchNetworkGameDataFileCRCCheck::packMessage() { - unsigned char *buf = new unsigned char[getPackedSize()+1]; - pack(buf, getPackedMessageFormat(), - messageType, - data.totalFileCount, - data.fileIndex, - data.fileCRC, - data.fileName.getBuffer()); - return buf; -} - -bool NetworkMessageSynchNetworkGameDataFileCRCCheck::receive(Socket* socket) { - bool result = false; - if(useOldProtocol == true) { - result = NetworkMessage::receive(socket, &data, sizeof(data),true); - } - else { - unsigned char *buf = new unsigned char[getPackedSize()+1]; - result = NetworkMessage::receive(socket, buf, getPackedSize(), true); - unpackMessage(buf); - //printf("Got packet size = %u data.messageType = %d\n%s\n",getPackedSize(),data.messageType,buf); - delete [] buf; - } - fromEndian(); - data.fileName.nullTerminate(); - - return result; -} - -void NetworkMessageSynchNetworkGameDataFileCRCCheck::send(Socket* socket) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] nmtSynchNetworkGameDataFileCRCCheck\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - assert(messageType == nmtSynchNetworkGameDataFileCRCCheck); - toEndian(); - - if(useOldProtocol == true) { - //NetworkMessage::send(socket, &messageType, sizeof(messageType)); - NetworkMessage::send(socket, &data, sizeof(data), messageType); - } - else { - unsigned char *buf = packMessage(); - //printf("Send packet size = %u data.messageType = %d\n[%s]\n",getPackedSize(),data.messageType,buf); - NetworkMessage::send(socket, buf, getPackedSize()); - delete [] buf; - } + static unsigned int result = 0; + if (result == 0) { + Data packedData; + packedData.fileCRC = 0; + packedData.fileIndex = 0; + messageType = nmtSynchNetworkGameDataFileCRCCheck; + packedData.totalFileCount = 0; + + unsigned char *buf = new unsigned char[sizeof(packedData) * 3]; + result = pack(buf, getPackedMessageFormat(), messageType, + packedData.totalFileCount, packedData.fileIndex, + packedData.fileCRC, packedData.fileName.getBuffer()); + delete[] buf; + } + return result; +} +void NetworkMessageSynchNetworkGameDataFileCRCCheck::unpackMessage( + unsigned char *buf) { + unpack(buf, getPackedMessageFormat(), &messageType, &data.totalFileCount, + &data.fileIndex, &data.fileCRC, data.fileName.getBuffer()); +} + +unsigned char *NetworkMessageSynchNetworkGameDataFileCRCCheck::packMessage() { + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + pack(buf, getPackedMessageFormat(), messageType, data.totalFileCount, + data.fileIndex, data.fileCRC, data.fileName.getBuffer()); + return buf; +} + +bool NetworkMessageSynchNetworkGameDataFileCRCCheck::receive(Socket *socket) { + bool result = false; + if (useOldProtocol == true) { + result = NetworkMessage::receive(socket, &data, sizeof(data), true); + } else { + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + result = NetworkMessage::receive(socket, buf, getPackedSize(), true); + unpackMessage(buf); + // printf("Got packet size = %u data.messageType = + // %d\n%s\n",getPackedSize(),data.messageType,buf); + delete[] buf; + } + fromEndian(); + data.fileName.nullTerminate(); + + return result; +} + +void NetworkMessageSynchNetworkGameDataFileCRCCheck::send(Socket *socket) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] nmtSynchNetworkGameDataFileCRCCheck\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + assert(messageType == nmtSynchNetworkGameDataFileCRCCheck); + toEndian(); + + if (useOldProtocol == true) { + // NetworkMessage::send(socket, &messageType, sizeof(messageType)); + NetworkMessage::send(socket, &data, sizeof(data), messageType); + } else { + unsigned char *buf = packMessage(); + // printf("Send packet size = %u data.messageType = + // %d\n[%s]\n",getPackedSize(),data.messageType,buf); + NetworkMessage::send(socket, buf, getPackedSize()); + delete[] buf; + } } void NetworkMessageSynchNetworkGameDataFileCRCCheck::toEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); - data.totalFileCount = Shared::PlatformByteOrder::toCommonEndian(data.totalFileCount); - data.fileIndex = Shared::PlatformByteOrder::toCommonEndian(data.fileIndex); - data.fileCRC = Shared::PlatformByteOrder::toCommonEndian(data.fileCRC); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); + data.totalFileCount = + Shared::PlatformByteOrder::toCommonEndian(data.totalFileCount); + data.fileIndex = Shared::PlatformByteOrder::toCommonEndian(data.fileIndex); + data.fileCRC = Shared::PlatformByteOrder::toCommonEndian(data.fileCRC); + } } void NetworkMessageSynchNetworkGameDataFileCRCCheck::fromEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); - data.totalFileCount = Shared::PlatformByteOrder::fromCommonEndian(data.totalFileCount); - data.fileIndex = Shared::PlatformByteOrder::fromCommonEndian(data.fileIndex); - data.fileCRC = Shared::PlatformByteOrder::fromCommonEndian(data.fileCRC); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); + data.totalFileCount = + Shared::PlatformByteOrder::fromCommonEndian(data.totalFileCount); + data.fileIndex = + Shared::PlatformByteOrder::fromCommonEndian(data.fileIndex); + data.fileCRC = Shared::PlatformByteOrder::fromCommonEndian(data.fileCRC); + } } // ===================================================== // class NetworkMessageSynchNetworkGameDataFileGet // ===================================================== -NetworkMessageSynchNetworkGameDataFileGet::NetworkMessageSynchNetworkGameDataFileGet() { - messageType= nmtSynchNetworkGameDataFileGet; +NetworkMessageSynchNetworkGameDataFileGet:: + NetworkMessageSynchNetworkGameDataFileGet() { + messageType = nmtSynchNetworkGameDataFileGet; } -NetworkMessageSynchNetworkGameDataFileGet::NetworkMessageSynchNetworkGameDataFileGet(const string fileName) { - messageType= nmtSynchNetworkGameDataFileGet; - data.fileName = fileName; +NetworkMessageSynchNetworkGameDataFileGet:: + NetworkMessageSynchNetworkGameDataFileGet(const string fileName) { + messageType = nmtSynchNetworkGameDataFileGet; + data.fileName = fileName; } -const char * NetworkMessageSynchNetworkGameDataFileGet::getPackedMessageFormat() const { - return "c256s"; +const char * +NetworkMessageSynchNetworkGameDataFileGet::getPackedMessageFormat() const { + return "c256s"; } unsigned int NetworkMessageSynchNetworkGameDataFileGet::getPackedSize() { - static unsigned int result = 0; - if(result == 0) { - Data packedData; - messageType = nmtSynchNetworkGameDataFileGet; - unsigned char *buf = new unsigned char[sizeof(packedData)*3]; - result = pack(buf, getPackedMessageFormat(), - messageType, - packedData.fileName.getBuffer()); - delete [] buf; - } - return result; -} -void NetworkMessageSynchNetworkGameDataFileGet::unpackMessage(unsigned char *buf) { - unpack(buf, getPackedMessageFormat(), - &messageType, - data.fileName.getBuffer()); -} - -unsigned char * NetworkMessageSynchNetworkGameDataFileGet::packMessage() { - unsigned char *buf = new unsigned char[getPackedSize()+1]; - pack(buf, getPackedMessageFormat(), - messageType, - data.fileName.getBuffer()); - return buf; -} - -bool NetworkMessageSynchNetworkGameDataFileGet::receive(Socket* socket) { - bool result = false; - if(useOldProtocol == true) { - result = NetworkMessage::receive(socket, &data, sizeof(data),true); - } - else { - unsigned char *buf = new unsigned char[getPackedSize()+1]; - result = NetworkMessage::receive(socket, buf, getPackedSize(), true); - unpackMessage(buf); - //printf("Got packet size = %u data.messageType = %d\n%s\n",getPackedSize(),data.messageType,buf); - delete [] buf; - } - fromEndian(); - data.fileName.nullTerminate(); - - return result; -} - -void NetworkMessageSynchNetworkGameDataFileGet::send(Socket* socket) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] nmtSynchNetworkGameDataFileGet\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - assert(messageType == nmtSynchNetworkGameDataFileGet); - toEndian(); - if(useOldProtocol == true) { - //NetworkMessage::send(socket, &messageType, sizeof(messageType)); - NetworkMessage::send(socket, &data, sizeof(data), messageType); - } - else { - unsigned char *buf = packMessage(); - //printf("Send packet size = %u data.messageType = %d\n[%s]\n",getPackedSize(),data.messageType,buf); - NetworkMessage::send(socket, buf, getPackedSize()); - delete [] buf; - } + static unsigned int result = 0; + if (result == 0) { + Data packedData; + messageType = nmtSynchNetworkGameDataFileGet; + unsigned char *buf = new unsigned char[sizeof(packedData) * 3]; + result = pack(buf, getPackedMessageFormat(), messageType, + packedData.fileName.getBuffer()); + delete[] buf; + } + return result; +} +void NetworkMessageSynchNetworkGameDataFileGet::unpackMessage( + unsigned char *buf) { + unpack(buf, getPackedMessageFormat(), &messageType, + data.fileName.getBuffer()); +} + +unsigned char *NetworkMessageSynchNetworkGameDataFileGet::packMessage() { + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + pack(buf, getPackedMessageFormat(), messageType, data.fileName.getBuffer()); + return buf; +} + +bool NetworkMessageSynchNetworkGameDataFileGet::receive(Socket *socket) { + bool result = false; + if (useOldProtocol == true) { + result = NetworkMessage::receive(socket, &data, sizeof(data), true); + } else { + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + result = NetworkMessage::receive(socket, buf, getPackedSize(), true); + unpackMessage(buf); + // printf("Got packet size = %u data.messageType = + // %d\n%s\n",getPackedSize(),data.messageType,buf); + delete[] buf; + } + fromEndian(); + data.fileName.nullTerminate(); + + return result; +} + +void NetworkMessageSynchNetworkGameDataFileGet::send(Socket *socket) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] nmtSynchNetworkGameDataFileGet\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + assert(messageType == nmtSynchNetworkGameDataFileGet); + toEndian(); + if (useOldProtocol == true) { + // NetworkMessage::send(socket, &messageType, sizeof(messageType)); + NetworkMessage::send(socket, &data, sizeof(data), messageType); + } else { + unsigned char *buf = packMessage(); + // printf("Send packet size = %u data.messageType = + // %d\n[%s]\n",getPackedSize(),data.messageType,buf); + NetworkMessage::send(socket, buf, getPackedSize()); + delete[] buf; + } } void NetworkMessageSynchNetworkGameDataFileGet::toEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); + } } void NetworkMessageSynchNetworkGameDataFileGet::fromEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); + } } - // ===================================================== // class SwitchSetupRequest // ===================================================== SwitchSetupRequest::SwitchSetupRequest() { - messageType= nmtSwitchSetupRequest; - data.selectedFactionName=""; - data.currentSlotIndex=-1; - data.toSlotIndex=-1; - data.toTeam = -1; - data.networkPlayerName=""; - data.networkPlayerStatus = npst_None; - data.switchFlags = ssrft_None; - data.language = ""; -} - -SwitchSetupRequest::SwitchSetupRequest(string selectedFactionName, int8 currentFactionIndex, - int8 toFactionIndex,int8 toTeam,string networkPlayerName, - int8 networkPlayerStatus, int8 flags, - string language) { - messageType= nmtSwitchSetupRequest; - data.selectedFactionName=selectedFactionName; - data.currentSlotIndex=currentFactionIndex; - data.toSlotIndex=toFactionIndex; - data.toTeam = toTeam; - data.networkPlayerName=networkPlayerName; - data.networkPlayerStatus=networkPlayerStatus; - data.switchFlags = flags; - data.language = language; -} - -const char * SwitchSetupRequest::getPackedMessageFormat() const { - return "c256sccc80scc60s"; + messageType = nmtSwitchSetupRequest; + data.selectedFactionName = ""; + data.currentSlotIndex = -1; + data.toSlotIndex = -1; + data.toTeam = -1; + data.networkPlayerName = ""; + data.networkPlayerStatus = npst_None; + data.switchFlags = ssrft_None; + data.language = ""; +} + +SwitchSetupRequest::SwitchSetupRequest(string selectedFactionName, + int8 currentFactionIndex, + int8 toFactionIndex, int8 toTeam, + string networkPlayerName, + int8 networkPlayerStatus, int8 flags, + string language) { + messageType = nmtSwitchSetupRequest; + data.selectedFactionName = selectedFactionName; + data.currentSlotIndex = currentFactionIndex; + data.toSlotIndex = toFactionIndex; + data.toTeam = toTeam; + data.networkPlayerName = networkPlayerName; + data.networkPlayerStatus = networkPlayerStatus; + data.switchFlags = flags; + data.language = language; +} + +const char *SwitchSetupRequest::getPackedMessageFormat() const { + return "c256sccc80scc60s"; } unsigned int SwitchSetupRequest::getPackedSize() { - static unsigned int result = 0; - if(result == 0) { - Data packedData; - packedData.currentSlotIndex = 0; - messageType = nmtSwitchSetupRequest; - packedData.networkPlayerStatus = 0; - packedData.switchFlags = 0; - packedData.toSlotIndex = 0; - packedData.toTeam = 0; - - unsigned char *buf = new unsigned char[sizeof(Data)*3]; - result = pack(buf, getPackedMessageFormat(), - messageType, - packedData.selectedFactionName.getBuffer(), - packedData.currentSlotIndex, - packedData.toSlotIndex, - packedData.toTeam, - packedData.networkPlayerName.getBuffer(), - packedData.networkPlayerStatus, - packedData.switchFlags, - packedData.language.getBuffer()); - delete [] buf; - } - return result; + static unsigned int result = 0; + if (result == 0) { + Data packedData; + packedData.currentSlotIndex = 0; + messageType = nmtSwitchSetupRequest; + packedData.networkPlayerStatus = 0; + packedData.switchFlags = 0; + packedData.toSlotIndex = 0; + packedData.toTeam = 0; + + unsigned char *buf = new unsigned char[sizeof(Data) * 3]; + result = pack(buf, getPackedMessageFormat(), messageType, + packedData.selectedFactionName.getBuffer(), + packedData.currentSlotIndex, packedData.toSlotIndex, + packedData.toTeam, packedData.networkPlayerName.getBuffer(), + packedData.networkPlayerStatus, packedData.switchFlags, + packedData.language.getBuffer()); + delete[] buf; + } + return result; } void SwitchSetupRequest::unpackMessage(unsigned char *buf) { - unpack(buf, getPackedMessageFormat(), - &messageType, - data.selectedFactionName.getBuffer(), - &data.currentSlotIndex, - &data.toSlotIndex, - &data.toTeam, - data.networkPlayerName.getBuffer(), - &data.networkPlayerStatus, - &data.switchFlags, - data.language.getBuffer()); -} - -unsigned char * SwitchSetupRequest::packMessage() { - unsigned char *buf = new unsigned char[getPackedSize()+1]; - pack(buf, getPackedMessageFormat(), - messageType, - data.selectedFactionName.getBuffer(), - data.currentSlotIndex, - data.toSlotIndex, - data.toTeam, - data.networkPlayerName.getBuffer(), - data.networkPlayerStatus, - data.switchFlags, - data.language.getBuffer()); - return buf; -} - -bool SwitchSetupRequest::receive(Socket* socket) { - bool result = false; - if(useOldProtocol == true) { - - result = NetworkMessage::receive(socket, &data, sizeof(data), true); - if(result == true) { - messageType = nmtSwitchSetupRequest; - } - - } - else { - //fromEndian(); - unsigned char *buf = new unsigned char[getPackedSize()+1]; - result = NetworkMessage::receive(socket, buf, getPackedSize(), true); - unpackMessage(buf); - //printf("Got packet size = %u data.messageType = %d\n%s\nTeam = %d faction [%s] currentFactionIndex = %d toFactionIndex = %d\n",getPackedSize(),data.messageType,buf,data.toTeam,data.selectedFactionName.getBuffer(),data.currentFactionIndex,data.toFactionIndex); - delete [] buf; - } - fromEndian(); - - data.selectedFactionName.nullTerminate(); - data.networkPlayerName.nullTerminate(); - data.language.nullTerminate(); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d] data.networkPlayerName [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,data.networkPlayerName.getString().c_str()); - - return result; -} - -void SwitchSetupRequest::send(Socket* socket) { - assert(messageType == nmtSwitchSetupRequest); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d] data.networkPlayerName [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,data.networkPlayerName.getString().c_str()); - toEndian(); - - if(useOldProtocol == true) { - //NetworkMessage::send(socket, &messageType, sizeof(messageType)); - NetworkMessage::send(socket, &data, sizeof(data), messageType); - } - else { - unsigned char *buf = packMessage(); - //printf("Send packet size = %u data.messageType = %d\n%s\nTeam = %d faction [%s] currentFactionIndex = %d toFactionIndex = %d\n",getPackedSize(),data.messageType,buf,data.toTeam,data.selectedFactionName.getBuffer(),data.currentFactionIndex,data.toFactionIndex); - NetworkMessage::send(socket, buf, getPackedSize()); - delete [] buf; - } + unpack(buf, getPackedMessageFormat(), &messageType, + data.selectedFactionName.getBuffer(), &data.currentSlotIndex, + &data.toSlotIndex, &data.toTeam, data.networkPlayerName.getBuffer(), + &data.networkPlayerStatus, &data.switchFlags, + data.language.getBuffer()); +} + +unsigned char *SwitchSetupRequest::packMessage() { + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + pack(buf, getPackedMessageFormat(), messageType, + data.selectedFactionName.getBuffer(), data.currentSlotIndex, + data.toSlotIndex, data.toTeam, data.networkPlayerName.getBuffer(), + data.networkPlayerStatus, data.switchFlags, data.language.getBuffer()); + return buf; +} + +bool SwitchSetupRequest::receive(Socket *socket) { + bool result = false; + if (useOldProtocol == true) { + + result = NetworkMessage::receive(socket, &data, sizeof(data), true); + if (result == true) { + messageType = nmtSwitchSetupRequest; + } + + } else { + // fromEndian(); + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + result = NetworkMessage::receive(socket, buf, getPackedSize(), true); + unpackMessage(buf); + // printf("Got packet size = %u data.messageType = %d\n%s\nTeam = %d faction + // [%s] currentFactionIndex = %d toFactionIndex = + // %d\n",getPackedSize(),data.messageType,buf,data.toTeam,data.selectedFactionName.getBuffer(),data.currentFactionIndex,data.toFactionIndex); + delete[] buf; + } + fromEndian(); + + data.selectedFactionName.nullTerminate(); + data.networkPlayerName.nullTerminate(); + data.language.nullTerminate(); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d] data.networkPlayerName [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, data.networkPlayerName.getString().c_str()); + + return result; +} + +void SwitchSetupRequest::send(Socket *socket) { + assert(messageType == nmtSwitchSetupRequest); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line %d] data.networkPlayerName [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, data.networkPlayerName.getString().c_str()); + toEndian(); + + if (useOldProtocol == true) { + // NetworkMessage::send(socket, &messageType, sizeof(messageType)); + NetworkMessage::send(socket, &data, sizeof(data), messageType); + } else { + unsigned char *buf = packMessage(); + // printf("Send packet size = %u data.messageType = %d\n%s\nTeam = %d + // faction [%s] currentFactionIndex = %d toFactionIndex = + // %d\n",getPackedSize(),data.messageType,buf,data.toTeam,data.selectedFactionName.getBuffer(),data.currentFactionIndex,data.toFactionIndex); + NetworkMessage::send(socket, buf, getPackedSize()); + delete[] buf; + } } void SwitchSetupRequest::toEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); - data.currentSlotIndex = Shared::PlatformByteOrder::toCommonEndian(data.currentSlotIndex); - data.toSlotIndex = Shared::PlatformByteOrder::toCommonEndian(data.toSlotIndex); - data.toTeam = Shared::PlatformByteOrder::toCommonEndian(data.toTeam); - data.networkPlayerStatus = Shared::PlatformByteOrder::toCommonEndian(data.networkPlayerStatus); - data.switchFlags = Shared::PlatformByteOrder::toCommonEndian(data.switchFlags); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); + data.currentSlotIndex = + Shared::PlatformByteOrder::toCommonEndian(data.currentSlotIndex); + data.toSlotIndex = + Shared::PlatformByteOrder::toCommonEndian(data.toSlotIndex); + data.toTeam = Shared::PlatformByteOrder::toCommonEndian(data.toTeam); + data.networkPlayerStatus = + Shared::PlatformByteOrder::toCommonEndian(data.networkPlayerStatus); + data.switchFlags = + Shared::PlatformByteOrder::toCommonEndian(data.switchFlags); + } } void SwitchSetupRequest::fromEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); - data.currentSlotIndex = Shared::PlatformByteOrder::fromCommonEndian(data.currentSlotIndex); - data.toSlotIndex = Shared::PlatformByteOrder::fromCommonEndian(data.toSlotIndex); - data.toTeam = Shared::PlatformByteOrder::fromCommonEndian(data.toTeam); - data.networkPlayerStatus = Shared::PlatformByteOrder::fromCommonEndian(data.networkPlayerStatus); - data.switchFlags = Shared::PlatformByteOrder::fromCommonEndian(data.switchFlags); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); + data.currentSlotIndex = + Shared::PlatformByteOrder::fromCommonEndian(data.currentSlotIndex); + data.toSlotIndex = + Shared::PlatformByteOrder::fromCommonEndian(data.toSlotIndex); + data.toTeam = Shared::PlatformByteOrder::fromCommonEndian(data.toTeam); + data.networkPlayerStatus = + Shared::PlatformByteOrder::fromCommonEndian(data.networkPlayerStatus); + data.switchFlags = + Shared::PlatformByteOrder::fromCommonEndian(data.switchFlags); + } } // ===================================================== // class PlayerIndexMessage // ===================================================== PlayerIndexMessage::PlayerIndexMessage(int16 playerIndex) { - messageType = nmtPlayerIndexMessage; - data.playerIndex=playerIndex; + messageType = nmtPlayerIndexMessage; + data.playerIndex = playerIndex; } -const char * PlayerIndexMessage::getPackedMessageFormat() const { - return "ch"; -} +const char *PlayerIndexMessage::getPackedMessageFormat() const { return "ch"; } unsigned int PlayerIndexMessage::getPackedSize() { - static unsigned int result = 0; - if(result == 0) { - Data packedData; - messageType = 0; - packedData.playerIndex = 0; - unsigned char *buf = new unsigned char[sizeof(packedData)*3]; - result = pack(buf, getPackedMessageFormat(), - messageType, - packedData.playerIndex); - delete [] buf; - } - return result; + static unsigned int result = 0; + if (result == 0) { + Data packedData; + messageType = 0; + packedData.playerIndex = 0; + unsigned char *buf = new unsigned char[sizeof(packedData) * 3]; + result = pack(buf, getPackedMessageFormat(), messageType, + packedData.playerIndex); + delete[] buf; + } + return result; } void PlayerIndexMessage::unpackMessage(unsigned char *buf) { - unpack(buf, getPackedMessageFormat(), - &messageType, - &data.playerIndex); -} - -unsigned char * PlayerIndexMessage::packMessage() { - unsigned char *buf = new unsigned char[getPackedSize()+1]; - pack(buf, getPackedMessageFormat(), - messageType, - data.playerIndex); - return buf; -} - -bool PlayerIndexMessage::receive(Socket* socket) { - bool result = false; - if(useOldProtocol == true) { - result = NetworkMessage::receive(socket, &data, sizeof(data), true); - if(result == true) { - messageType = nmtPlayerIndexMessage; - } - - } - else { - //fromEndian(); - unsigned char *buf = new unsigned char[getPackedSize()+1]; - result = NetworkMessage::receive(socket, buf, getPackedSize(), true); - unpackMessage(buf); - //printf("Got packet size = %u data.messageType = %d\n%s\n",getPackedSize(),data.messageType,buf); - delete [] buf; - } - fromEndian(); - - return result; -} - -void PlayerIndexMessage::send(Socket* socket) { - assert(messageType == nmtPlayerIndexMessage); - toEndian(); - - if(useOldProtocol == true) { - //NetworkMessage::send(socket, &messageType, sizeof(messageType)); - NetworkMessage::send(socket, &data, sizeof(data), messageType); - } - else { - unsigned char *buf = packMessage(); - //printf("Send packet size = %u data.messageType = %d\n[%s]\n",getPackedSize(),data.messageType,buf); - //NetworkMessage::send(socket, &data, sizeof(data)); - NetworkMessage::send(socket, buf, getPackedSize()); - delete [] buf; - } + unpack(buf, getPackedMessageFormat(), &messageType, &data.playerIndex); +} + +unsigned char *PlayerIndexMessage::packMessage() { + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + pack(buf, getPackedMessageFormat(), messageType, data.playerIndex); + return buf; +} + +bool PlayerIndexMessage::receive(Socket *socket) { + bool result = false; + if (useOldProtocol == true) { + result = NetworkMessage::receive(socket, &data, sizeof(data), true); + if (result == true) { + messageType = nmtPlayerIndexMessage; + } + + } else { + // fromEndian(); + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + result = NetworkMessage::receive(socket, buf, getPackedSize(), true); + unpackMessage(buf); + // printf("Got packet size = %u data.messageType = + // %d\n%s\n",getPackedSize(),data.messageType,buf); + delete[] buf; + } + fromEndian(); + + return result; +} + +void PlayerIndexMessage::send(Socket *socket) { + assert(messageType == nmtPlayerIndexMessage); + toEndian(); + + if (useOldProtocol == true) { + // NetworkMessage::send(socket, &messageType, sizeof(messageType)); + NetworkMessage::send(socket, &data, sizeof(data), messageType); + } else { + unsigned char *buf = packMessage(); + // printf("Send packet size = %u data.messageType = + // %d\n[%s]\n",getPackedSize(),data.messageType,buf); + // NetworkMessage::send(socket, &data, sizeof(data)); + NetworkMessage::send(socket, buf, getPackedSize()); + delete[] buf; + } } void PlayerIndexMessage::toEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); - data.playerIndex = Shared::PlatformByteOrder::toCommonEndian(data.playerIndex); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); + data.playerIndex = + Shared::PlatformByteOrder::toCommonEndian(data.playerIndex); + } } void PlayerIndexMessage::fromEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); - data.playerIndex = Shared::PlatformByteOrder::fromCommonEndian(data.playerIndex); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); + data.playerIndex = + Shared::PlatformByteOrder::fromCommonEndian(data.playerIndex); + } } // ===================================================== // class NetworkMessageLoadingStatus // ===================================================== -NetworkMessageLoadingStatus::NetworkMessageLoadingStatus(uint32 status) -{ - messageType = nmtLoadingStatusMessage; - data.status=status; +NetworkMessageLoadingStatus::NetworkMessageLoadingStatus(uint32 status) { + messageType = nmtLoadingStatusMessage; + data.status = status; } -const char * NetworkMessageLoadingStatus::getPackedMessageFormat() const { - return "cL"; +const char *NetworkMessageLoadingStatus::getPackedMessageFormat() const { + return "cL"; } unsigned int NetworkMessageLoadingStatus::getPackedSize() { - static unsigned int result = 0; - if(result == 0) { - Data packedData; - messageType = 0; - packedData.status = 0; - unsigned char *buf = new unsigned char[sizeof(packedData)*3]; - result = pack(buf, getPackedMessageFormat(), - messageType, - packedData.status); - delete [] buf; - } - return result; + static unsigned int result = 0; + if (result == 0) { + Data packedData; + messageType = 0; + packedData.status = 0; + unsigned char *buf = new unsigned char[sizeof(packedData) * 3]; + result = + pack(buf, getPackedMessageFormat(), messageType, packedData.status); + delete[] buf; + } + return result; } void NetworkMessageLoadingStatus::unpackMessage(unsigned char *buf) { - unpack(buf, getPackedMessageFormat(), - &messageType, - &data.status); -} - -unsigned char * NetworkMessageLoadingStatus::packMessage() { - unsigned char *buf = new unsigned char[getPackedSize()+1]; - pack(buf, getPackedMessageFormat(), - messageType, - data.status); - return buf; -} - -bool NetworkMessageLoadingStatus::receive(Socket* socket) { - bool result = false; - if(useOldProtocol == true) { - result = NetworkMessage::receive(socket, &data, sizeof(data), true); - if(result == true) { - messageType = nmtLoadingStatusMessage; - } - } - else { - //fromEndian(); - unsigned char *buf = new unsigned char[getPackedSize()+1]; - result = NetworkMessage::receive(socket, buf, getPackedSize(), true); - unpackMessage(buf); - //printf("Got packet size = %u data.messageType = %d\n%s\n",getPackedSize(),data.messageType,buf); - delete [] buf; - } - fromEndian(); - - return result; -} - -void NetworkMessageLoadingStatus::send(Socket* socket) { - assert(messageType == nmtLoadingStatusMessage); - toEndian(); - - if(useOldProtocol == true) { - //NetworkMessage::send(socket, &messageType, sizeof(messageType)); - NetworkMessage::send(socket, &data, sizeof(data), messageType); - } - else { - unsigned char *buf = packMessage(); - //printf("Send packet size = %u data.messageType = %d\n[%s]\n",getPackedSize(),data.messageType,buf); - NetworkMessage::send(socket, buf, getPackedSize()); - delete [] buf; - } + unpack(buf, getPackedMessageFormat(), &messageType, &data.status); +} + +unsigned char *NetworkMessageLoadingStatus::packMessage() { + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + pack(buf, getPackedMessageFormat(), messageType, data.status); + return buf; +} + +bool NetworkMessageLoadingStatus::receive(Socket *socket) { + bool result = false; + if (useOldProtocol == true) { + result = NetworkMessage::receive(socket, &data, sizeof(data), true); + if (result == true) { + messageType = nmtLoadingStatusMessage; + } + } else { + // fromEndian(); + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + result = NetworkMessage::receive(socket, buf, getPackedSize(), true); + unpackMessage(buf); + // printf("Got packet size = %u data.messageType = + // %d\n%s\n",getPackedSize(),data.messageType,buf); + delete[] buf; + } + fromEndian(); + + return result; +} + +void NetworkMessageLoadingStatus::send(Socket *socket) { + assert(messageType == nmtLoadingStatusMessage); + toEndian(); + + if (useOldProtocol == true) { + // NetworkMessage::send(socket, &messageType, sizeof(messageType)); + NetworkMessage::send(socket, &data, sizeof(data), messageType); + } else { + unsigned char *buf = packMessage(); + // printf("Send packet size = %u data.messageType = + // %d\n[%s]\n",getPackedSize(),data.messageType,buf); + NetworkMessage::send(socket, buf, getPackedSize()); + delete[] buf; + } } void NetworkMessageLoadingStatus::toEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); - data.status = Shared::PlatformByteOrder::toCommonEndian(data.status); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); + data.status = Shared::PlatformByteOrder::toCommonEndian(data.status); + } } void NetworkMessageLoadingStatus::fromEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); - data.status = Shared::PlatformByteOrder::fromCommonEndian(data.status); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); + data.status = Shared::PlatformByteOrder::fromCommonEndian(data.status); + } } // ===================================================== // class NetworkMessageMarkCell // ===================================================== -NetworkMessageMarkCell::NetworkMessageMarkCell() { - messageType = nmtMarkCell; -} +NetworkMessageMarkCell::NetworkMessageMarkCell() { messageType = nmtMarkCell; } -NetworkMessageMarkCell::NetworkMessageMarkCell(Vec2i target, int factionIndex, const string &text, int playerIndex) { - if((int)text.length() >= maxTextStringSize) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] WARNING / ERROR - text [%s] length = %d, max = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,text.c_str(),text.length(),maxTextStringSize); - } +NetworkMessageMarkCell::NetworkMessageMarkCell(Vec2i target, int factionIndex, + const string &text, + int playerIndex) { + if ((int)text.length() >= maxTextStringSize) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] WARNING / ERROR - text " + "[%s] length = %d, max = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, text.c_str(), + text.length(), maxTextStringSize); + } - messageType = nmtMarkCell; - data.text = text; - data.targetX = target.x; - data.targetY = target.y; - data.factionIndex = factionIndex; - data.playerIndex = playerIndex; + messageType = nmtMarkCell; + data.text = text; + data.targetX = target.x; + data.targetY = target.y; + data.factionIndex = factionIndex; + data.playerIndex = playerIndex; } -NetworkMessageMarkCell * NetworkMessageMarkCell::getCopy() const { - NetworkMessageMarkCell *copy = new NetworkMessageMarkCell(); - copy->data = this->data; - return copy; +NetworkMessageMarkCell *NetworkMessageMarkCell::getCopy() const { + NetworkMessageMarkCell *copy = new NetworkMessageMarkCell(); + copy->data = this->data; + return copy; } -const char * NetworkMessageMarkCell::getPackedMessageFormat() const { - return "chhcc500s"; +const char *NetworkMessageMarkCell::getPackedMessageFormat() const { + return "chhcc500s"; } unsigned int NetworkMessageMarkCell::getPackedSize() { - static unsigned int result = 0; - if(result == 0) { - Data packedData; - packedData.factionIndex = 0; - messageType = nmtMarkCell; - packedData.playerIndex = 0; - packedData.targetX = 0; - packedData.targetY = 0; - - unsigned char *buf = new unsigned char[sizeof(packedData)*3]; - result = pack(buf, getPackedMessageFormat(), - messageType, - packedData.targetX, - packedData.targetY, - packedData.factionIndex, - packedData.playerIndex, - packedData.text.getBuffer()); - delete [] buf; - } - return result; + static unsigned int result = 0; + if (result == 0) { + Data packedData; + packedData.factionIndex = 0; + messageType = nmtMarkCell; + packedData.playerIndex = 0; + packedData.targetX = 0; + packedData.targetY = 0; + + unsigned char *buf = new unsigned char[sizeof(packedData) * 3]; + result = + pack(buf, getPackedMessageFormat(), messageType, packedData.targetX, + packedData.targetY, packedData.factionIndex, + packedData.playerIndex, packedData.text.getBuffer()); + delete[] buf; + } + return result; } void NetworkMessageMarkCell::unpackMessage(unsigned char *buf) { - unpack(buf, getPackedMessageFormat(), - &messageType, - &data.targetX, - &data.targetY, - &data.factionIndex, - &data.playerIndex, - data.text.getBuffer()); - -} - -unsigned char * NetworkMessageMarkCell::packMessage() { - unsigned char *buf = new unsigned char[getPackedSize()+1]; - pack(buf, getPackedMessageFormat(), - messageType, - data.targetX, - data.targetY, - data.factionIndex, - data.playerIndex, - data.text.getBuffer()); - - return buf; -} - -bool NetworkMessageMarkCell::receive(Socket* socket){ - bool result = false; - if(useOldProtocol == true) { - result = NetworkMessage::receive(socket, &data, sizeof(data), true); - if(result == true) { - messageType = nmtMarkCell; - } - } - else { - unsigned char *buf = new unsigned char[getPackedSize()+1]; - result = NetworkMessage::receive(socket, buf, getPackedSize(), true); - unpackMessage(buf); - //printf("Got packet size = %u data.messageType = %d\n%s\n",getPackedSize(),data.messageType,buf); - delete [] buf; - } - fromEndian(); - - data.text.nullTerminate(); - return result; -} - -void NetworkMessageMarkCell::send(Socket* socket) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] nmtMarkCell\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - assert(messageType == nmtMarkCell); - toEndian(); - - if(useOldProtocol == true) { - //NetworkMessage::send(socket, &messageType, sizeof(messageType)); - NetworkMessage::send(socket, &data, sizeof(data), messageType); - } - else { - unsigned char *buf = packMessage(); - //printf("Send packet size = %u data.messageType = %d\n[%s]\n",getPackedSize(),data.messageType,buf); - NetworkMessage::send(socket, buf, getPackedSize()); - delete [] buf; - } + unpack(buf, getPackedMessageFormat(), &messageType, &data.targetX, + &data.targetY, &data.factionIndex, &data.playerIndex, + data.text.getBuffer()); +} + +unsigned char *NetworkMessageMarkCell::packMessage() { + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + pack(buf, getPackedMessageFormat(), messageType, data.targetX, data.targetY, + data.factionIndex, data.playerIndex, data.text.getBuffer()); + + return buf; +} + +bool NetworkMessageMarkCell::receive(Socket *socket) { + bool result = false; + if (useOldProtocol == true) { + result = NetworkMessage::receive(socket, &data, sizeof(data), true); + if (result == true) { + messageType = nmtMarkCell; + } + } else { + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + result = NetworkMessage::receive(socket, buf, getPackedSize(), true); + unpackMessage(buf); + // printf("Got packet size = %u data.messageType = + // %d\n%s\n",getPackedSize(),data.messageType,buf); + delete[] buf; + } + fromEndian(); + + data.text.nullTerminate(); + return result; +} + +void NetworkMessageMarkCell::send(Socket *socket) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d] nmtMarkCell\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + assert(messageType == nmtMarkCell); + toEndian(); + + if (useOldProtocol == true) { + // NetworkMessage::send(socket, &messageType, sizeof(messageType)); + NetworkMessage::send(socket, &data, sizeof(data), messageType); + } else { + unsigned char *buf = packMessage(); + // printf("Send packet size = %u data.messageType = + // %d\n[%s]\n",getPackedSize(),data.messageType,buf); + NetworkMessage::send(socket, buf, getPackedSize()); + delete[] buf; + } } void NetworkMessageMarkCell::toEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); - data.targetX = Shared::PlatformByteOrder::toCommonEndian(data.targetX); - data.targetY = Shared::PlatformByteOrder::toCommonEndian(data.targetY); - data.factionIndex = Shared::PlatformByteOrder::toCommonEndian(data.factionIndex); - data.playerIndex = Shared::PlatformByteOrder::toCommonEndian(data.playerIndex); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); + data.targetX = Shared::PlatformByteOrder::toCommonEndian(data.targetX); + data.targetY = Shared::PlatformByteOrder::toCommonEndian(data.targetY); + data.factionIndex = + Shared::PlatformByteOrder::toCommonEndian(data.factionIndex); + data.playerIndex = + Shared::PlatformByteOrder::toCommonEndian(data.playerIndex); + } } void NetworkMessageMarkCell::fromEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); - data.targetX = Shared::PlatformByteOrder::fromCommonEndian(data.targetX); - data.targetY = Shared::PlatformByteOrder::fromCommonEndian(data.targetY); - data.factionIndex = Shared::PlatformByteOrder::fromCommonEndian(data.factionIndex); - data.playerIndex = Shared::PlatformByteOrder::fromCommonEndian(data.playerIndex); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); + data.targetX = Shared::PlatformByteOrder::fromCommonEndian(data.targetX); + data.targetY = Shared::PlatformByteOrder::fromCommonEndian(data.targetY); + data.factionIndex = + Shared::PlatformByteOrder::fromCommonEndian(data.factionIndex); + data.playerIndex = + Shared::PlatformByteOrder::fromCommonEndian(data.playerIndex); + } } // ===================================================== @@ -3463,122 +3818,119 @@ void NetworkMessageMarkCell::fromEndian() { // ===================================================== NetworkMessageUnMarkCell::NetworkMessageUnMarkCell() { - messageType = nmtUnMarkCell; - data.targetX = 0; - data.targetY = 0; - data.factionIndex = 0; + messageType = nmtUnMarkCell; + data.targetX = 0; + data.targetY = 0; + data.factionIndex = 0; } -NetworkMessageUnMarkCell::NetworkMessageUnMarkCell(Vec2i target, int factionIndex) { - messageType = nmtUnMarkCell; - data.targetX = target.x; - data.targetY = target.y; - data.factionIndex = factionIndex; +NetworkMessageUnMarkCell::NetworkMessageUnMarkCell(Vec2i target, + int factionIndex) { + messageType = nmtUnMarkCell; + data.targetX = target.x; + data.targetY = target.y; + data.factionIndex = factionIndex; } -NetworkMessageUnMarkCell * NetworkMessageUnMarkCell::getCopy() const { - NetworkMessageUnMarkCell *copy = new NetworkMessageUnMarkCell(); - copy->data = this->data; - return copy; +NetworkMessageUnMarkCell *NetworkMessageUnMarkCell::getCopy() const { + NetworkMessageUnMarkCell *copy = new NetworkMessageUnMarkCell(); + copy->data = this->data; + return copy; } -const char * NetworkMessageUnMarkCell::getPackedMessageFormat() const { - return "chhc"; +const char *NetworkMessageUnMarkCell::getPackedMessageFormat() const { + return "chhc"; } unsigned int NetworkMessageUnMarkCell::getPackedSize() { - static unsigned int result = 0; - if(result == 0) { - Data packedData; - packedData.factionIndex = 0; - messageType = 0; - packedData.targetX = 0; - packedData.targetY = 0; - unsigned char *buf = new unsigned char[sizeof(packedData)*3]; - result = pack(buf, getPackedMessageFormat(), - messageType, - packedData.targetX, - packedData.targetY, - packedData.factionIndex); - delete [] buf; - } - return result; + static unsigned int result = 0; + if (result == 0) { + Data packedData; + packedData.factionIndex = 0; + messageType = 0; + packedData.targetX = 0; + packedData.targetY = 0; + unsigned char *buf = new unsigned char[sizeof(packedData) * 3]; + result = + pack(buf, getPackedMessageFormat(), messageType, packedData.targetX, + packedData.targetY, packedData.factionIndex); + delete[] buf; + } + return result; } void NetworkMessageUnMarkCell::unpackMessage(unsigned char *buf) { - unpack(buf, getPackedMessageFormat(), - &messageType, - &data.targetX, - &data.targetY, - &data.factionIndex); - -} - -unsigned char * NetworkMessageUnMarkCell::packMessage() { - unsigned char *buf = new unsigned char[getPackedSize()+1]; - pack(buf, getPackedMessageFormat(), - messageType, - data.targetX, - data.targetY, - data.factionIndex); - - return buf; -} - -bool NetworkMessageUnMarkCell::receive(Socket* socket){ - bool result = false; - if(useOldProtocol == true) { - result = NetworkMessage::receive(socket, &data, sizeof(data), true); - if(result == true) { - messageType = nmtUnMarkCell; - } - } - else { - unsigned char *buf = new unsigned char[getPackedSize()+1]; - result = NetworkMessage::receive(socket, buf, getPackedSize(), true); - unpackMessage(buf); - //printf("Got packet size = %u data.messageType = %d\n%s\n",getPackedSize(),data.messageType,buf); - delete [] buf; - } - fromEndian(); - - return result; -} - -void NetworkMessageUnMarkCell::send(Socket* socket) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] nmtUnMarkCell\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - assert(messageType == nmtUnMarkCell); - toEndian(); - - if(useOldProtocol == true) { - //NetworkMessage::send(socket, &messageType, sizeof(messageType)); - NetworkMessage::send(socket, &data, sizeof(data), messageType); - } - else { - unsigned char *buf = packMessage(); - //printf("Send packet size = %u data.messageType = %d\n[%s]\n",getPackedSize(),data.messageType,buf); - NetworkMessage::send(socket, buf, getPackedSize()); - delete [] buf; - } + unpack(buf, getPackedMessageFormat(), &messageType, &data.targetX, + &data.targetY, &data.factionIndex); +} + +unsigned char *NetworkMessageUnMarkCell::packMessage() { + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + pack(buf, getPackedMessageFormat(), messageType, data.targetX, data.targetY, + data.factionIndex); + + return buf; +} + +bool NetworkMessageUnMarkCell::receive(Socket *socket) { + bool result = false; + if (useOldProtocol == true) { + result = NetworkMessage::receive(socket, &data, sizeof(data), true); + if (result == true) { + messageType = nmtUnMarkCell; + } + } else { + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + result = NetworkMessage::receive(socket, buf, getPackedSize(), true); + unpackMessage(buf); + // printf("Got packet size = %u data.messageType = + // %d\n%s\n",getPackedSize(),data.messageType,buf); + delete[] buf; + } + fromEndian(); + + return result; +} + +void NetworkMessageUnMarkCell::send(Socket *socket) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d] nmtUnMarkCell\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + assert(messageType == nmtUnMarkCell); + toEndian(); + + if (useOldProtocol == true) { + // NetworkMessage::send(socket, &messageType, sizeof(messageType)); + NetworkMessage::send(socket, &data, sizeof(data), messageType); + } else { + unsigned char *buf = packMessage(); + // printf("Send packet size = %u data.messageType = + // %d\n[%s]\n",getPackedSize(),data.messageType,buf); + NetworkMessage::send(socket, buf, getPackedSize()); + delete[] buf; + } } void NetworkMessageUnMarkCell::toEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); - data.targetX = Shared::PlatformByteOrder::toCommonEndian(data.targetX); - data.targetY = Shared::PlatformByteOrder::toCommonEndian(data.targetY); - data.factionIndex = Shared::PlatformByteOrder::toCommonEndian(data.factionIndex); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); + data.targetX = Shared::PlatformByteOrder::toCommonEndian(data.targetX); + data.targetY = Shared::PlatformByteOrder::toCommonEndian(data.targetY); + data.factionIndex = + Shared::PlatformByteOrder::toCommonEndian(data.factionIndex); + } } void NetworkMessageUnMarkCell::fromEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); - data.targetX = Shared::PlatformByteOrder::fromCommonEndian(data.targetX); - data.targetY = Shared::PlatformByteOrder::fromCommonEndian(data.targetY); - data.factionIndex = Shared::PlatformByteOrder::fromCommonEndian(data.factionIndex); - } + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); + data.targetX = Shared::PlatformByteOrder::fromCommonEndian(data.targetX); + data.targetY = Shared::PlatformByteOrder::fromCommonEndian(data.targetY); + data.factionIndex = + Shared::PlatformByteOrder::fromCommonEndian(data.factionIndex); + } } // ===================================================== @@ -3586,115 +3938,113 @@ void NetworkMessageUnMarkCell::fromEndian() { // ===================================================== NetworkMessageHighlightCell::NetworkMessageHighlightCell() { - messageType = nmtHighlightCell; - data.targetX = 0; - data.targetY = 0; - data.factionIndex = 0; + messageType = nmtHighlightCell; + data.targetX = 0; + data.targetY = 0; + data.factionIndex = 0; } -NetworkMessageHighlightCell::NetworkMessageHighlightCell(Vec2i target, int factionIndex) { - messageType = nmtHighlightCell; - data.targetX = target.x; - data.targetY = target.y; - data.factionIndex = factionIndex; +NetworkMessageHighlightCell::NetworkMessageHighlightCell(Vec2i target, + int factionIndex) { + messageType = nmtHighlightCell; + data.targetX = target.x; + data.targetY = target.y; + data.factionIndex = factionIndex; } -const char * NetworkMessageHighlightCell::getPackedMessageFormat() const { - return "chhc"; +const char *NetworkMessageHighlightCell::getPackedMessageFormat() const { + return "chhc"; } unsigned int NetworkMessageHighlightCell::getPackedSize() { - static unsigned int result = 0; - if(result == 0) { - Data packedData; - packedData.factionIndex = 0; - messageType = 0; - packedData.targetX = 0; - packedData.targetY = 0; - unsigned char *buf = new unsigned char[sizeof(packedData)*3]; - result = pack(buf, getPackedMessageFormat(), - messageType, - packedData.targetX, - packedData.targetY, - packedData.factionIndex); - delete [] buf; - } - return result; + static unsigned int result = 0; + if (result == 0) { + Data packedData; + packedData.factionIndex = 0; + messageType = 0; + packedData.targetX = 0; + packedData.targetY = 0; + unsigned char *buf = new unsigned char[sizeof(packedData) * 3]; + result = + pack(buf, getPackedMessageFormat(), messageType, packedData.targetX, + packedData.targetY, packedData.factionIndex); + delete[] buf; + } + return result; } void NetworkMessageHighlightCell::unpackMessage(unsigned char *buf) { - unpack(buf, getPackedMessageFormat(), - &messageType, - &data.targetX, - &data.targetY, - &data.factionIndex); - -} - -unsigned char * NetworkMessageHighlightCell::packMessage() { - unsigned char *buf = new unsigned char[getPackedSize()+1]; - pack(buf, getPackedMessageFormat(), - messageType, - data.targetX, - data.targetY, - data.factionIndex); - - return buf; -} - -bool NetworkMessageHighlightCell::receive(Socket* socket) { - bool result = false; - if(useOldProtocol == true) { - result = NetworkMessage::receive(socket, &data, sizeof(data), true); - if(result == true) { - messageType = nmtHighlightCell; - } - } - else { - unsigned char *buf = new unsigned char[getPackedSize()+1]; - result = NetworkMessage::receive(socket, buf, getPackedSize(), true); - unpackMessage(buf); - //printf("Got packet size = %u data.messageType = %d\n%s\n",getPackedSize(),data.messageType,buf); - delete [] buf; - } - fromEndian(); - return result; -} - -void NetworkMessageHighlightCell::send(Socket* socket) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] nmtMarkCell\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - assert(messageType == nmtHighlightCell); - toEndian(); - - if(useOldProtocol == true) { - //NetworkMessage::send(socket, &messageType, sizeof(messageType)); - NetworkMessage::send(socket, &data, sizeof(data), messageType); - } - else { - unsigned char *buf = packMessage(); - //printf("Send packet size = %u data.messageType = %d\n[%s]\n",getPackedSize(),data.messageType,buf); - NetworkMessage::send(socket, buf, getPackedSize()); - delete [] buf; - } + unpack(buf, getPackedMessageFormat(), &messageType, &data.targetX, + &data.targetY, &data.factionIndex); } -void NetworkMessageHighlightCell::toEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); - data.targetX = Shared::PlatformByteOrder::toCommonEndian(data.targetX); - data.targetY = Shared::PlatformByteOrder::toCommonEndian(data.targetY); - data.factionIndex = Shared::PlatformByteOrder::toCommonEndian(data.factionIndex); - } +unsigned char *NetworkMessageHighlightCell::packMessage() { + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + pack(buf, getPackedMessageFormat(), messageType, data.targetX, data.targetY, + data.factionIndex); + + return buf; } -void NetworkMessageHighlightCell::fromEndian() { - static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); - if(bigEndianSystem == true) { - messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); - data.targetX = Shared::PlatformByteOrder::fromCommonEndian(data.targetX); - data.targetY = Shared::PlatformByteOrder::fromCommonEndian(data.targetY); - data.factionIndex = Shared::PlatformByteOrder::fromCommonEndian(data.factionIndex); - } + +bool NetworkMessageHighlightCell::receive(Socket *socket) { + bool result = false; + if (useOldProtocol == true) { + result = NetworkMessage::receive(socket, &data, sizeof(data), true); + if (result == true) { + messageType = nmtHighlightCell; + } + } else { + unsigned char *buf = new unsigned char[getPackedSize() + 1]; + result = NetworkMessage::receive(socket, buf, getPackedSize(), true); + unpackMessage(buf); + // printf("Got packet size = %u data.messageType = + // %d\n%s\n",getPackedSize(),data.messageType,buf); + delete[] buf; + } + fromEndian(); + return result; +} + +void NetworkMessageHighlightCell::send(Socket *socket) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d] nmtMarkCell\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + assert(messageType == nmtHighlightCell); + toEndian(); + + if (useOldProtocol == true) { + // NetworkMessage::send(socket, &messageType, sizeof(messageType)); + NetworkMessage::send(socket, &data, sizeof(data), messageType); + } else { + unsigned char *buf = packMessage(); + // printf("Send packet size = %u data.messageType = + // %d\n[%s]\n",getPackedSize(),data.messageType,buf); + NetworkMessage::send(socket, buf, getPackedSize()); + delete[] buf; + } } -}}//end namespace +void NetworkMessageHighlightCell::toEndian() { + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::toCommonEndian(messageType); + data.targetX = Shared::PlatformByteOrder::toCommonEndian(data.targetX); + data.targetY = Shared::PlatformByteOrder::toCommonEndian(data.targetY); + data.factionIndex = + Shared::PlatformByteOrder::toCommonEndian(data.factionIndex); + } +} +void NetworkMessageHighlightCell::fromEndian() { + static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian(); + if (bigEndianSystem == true) { + messageType = Shared::PlatformByteOrder::fromCommonEndian(messageType); + data.targetX = Shared::PlatformByteOrder::fromCommonEndian(data.targetX); + data.targetY = Shared::PlatformByteOrder::fromCommonEndian(data.targetY); + data.factionIndex = + Shared::PlatformByteOrder::fromCommonEndian(data.factionIndex); + } +} + +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/network/network_message.h b/source/glest_game/network/network_message.h index 15c10438f..946e1f2cf 100644 --- a/source/glest_game/network/network_message.h +++ b/source/glest_game/network/network_message.h @@ -12,126 +12,130 @@ #ifndef _GLEST_GAME_NETWORKMESSAGE_H_ #define _GLEST_GAME_NETWORKMESSAGE_H_ -#include "socket.h" -#include "game_constants.h" -#include "network_types.h" #include "byte_order.h" -#include #include "common_scoped_ptr.h" +#include "game_constants.h" #include "leak_dumper.h" +#include "network_types.h" +#include "socket.h" +#include -using Shared::Platform::Socket; +using Shared::Platform::int16; using Shared::Platform::int8; +using Shared::Platform::Socket; using Shared::Platform::uint8; -using Shared::Platform::int16; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { class GameSettings; enum NetworkMessageType { - nmtInvalid, - nmtIntro, - nmtPing, - nmtReady, - nmtLaunch, - nmtCommandList, - nmtText, - nmtQuit, - nmtSynchNetworkGameData, - nmtSynchNetworkGameDataStatus, - nmtSynchNetworkGameDataFileCRCCheck, - nmtSynchNetworkGameDataFileGet, - nmtBroadCastSetup, - nmtSwitchSetupRequest, - nmtPlayerIndexMessage, - nmtLoadingStatusMessage, - nmtMarkCell, - nmtUnMarkCell, - nmtHighlightCell, -// nmtCompressedPacket, - - nmtCount + nmtInvalid, + nmtIntro, + nmtPing, + nmtReady, + nmtLaunch, + nmtCommandList, + nmtText, + nmtQuit, + nmtSynchNetworkGameData, + nmtSynchNetworkGameDataStatus, + nmtSynchNetworkGameDataFileCRCCheck, + nmtSynchNetworkGameDataFileGet, + nmtBroadCastSetup, + nmtSwitchSetupRequest, + nmtPlayerIndexMessage, + nmtLoadingStatusMessage, + nmtMarkCell, + nmtUnMarkCell, + nmtHighlightCell, + // nmtCompressedPacket, + + nmtCount }; enum NetworkGameStateType { - nmgstInvalid, - nmgstOk, - nmgstNoSlots, + nmgstInvalid, + nmgstOk, + nmgstNoSlots, - nmgstCount + nmgstCount }; -static const int maxLanguageStringSize= 60; -static const int maxNetworkMessageSize= 20000; +static const int maxLanguageStringSize = 60; +static const int maxNetworkMessageSize = 20000; // ===================================================== // class NetworkMessage // ===================================================== enum NetworkMessageStatisticType { - netmsgstPacketsPerMillisecondSend, - netmsgstPacketsPerMillisecondSend_current_count, - netmsgstPacketsPerMillisecondSend_last, + netmsgstPacketsPerMillisecondSend, + netmsgstPacketsPerMillisecondSend_current_count, + netmsgstPacketsPerMillisecondSend_last, - netmsgstPacketsPerSecondSend, - netmsgstPacketsPerSecondSend_current_count, - netmsgstPacketsPerSecondSend_last, + netmsgstPacketsPerSecondSend, + netmsgstPacketsPerSecondSend_current_count, + netmsgstPacketsPerSecondSend_last, - netmsgstAverageSendSize, + netmsgstAverageSendSize, - // --------------------------------------------- - netmsgstPacketsPerMillisecondRecv, - netmsgstPacketsPerMillisecondRecv_current_count, - netmsgstPacketsPerMillisecondRecv_last, + // --------------------------------------------- + netmsgstPacketsPerMillisecondRecv, + netmsgstPacketsPerMillisecondRecv_current_count, + netmsgstPacketsPerMillisecondRecv_last, - netmsgstPacketsPerSecondRecv, - netmsgstPacketsPerSecondRecv_current_count, - netmsgstPacketsPerSecondRecv_last, + netmsgstPacketsPerSecondRecv, + netmsgstPacketsPerSecondRecv_current_count, + netmsgstPacketsPerSecondRecv_last, - netmsgstAverageRecvSize, + netmsgstAverageRecvSize, - netmsgstLastEvent + netmsgstLastEvent }; class NetworkMessage { private: - - static auto_ptr mutexMessageStats; - static Chrono statsTimer; - static Chrono lastSend; - static Chrono lastRecv; - static std::map mapMessageStats; + static auto_ptr mutexMessageStats; + static Chrono statsTimer; + static Chrono lastSend; + static Chrono lastRecv; + static std::map mapMessageStats; public: - static void resetNetworkPacketStats(); - static string getNetworkPacketStats(); + static void resetNetworkPacketStats(); + static string getNetworkPacketStats(); - static bool useOldProtocol; - virtual ~NetworkMessage(){} - virtual bool receive(Socket* socket)= 0; - virtual bool receive(Socket* socket, NetworkMessageType type) { return receive(socket); }; + static bool useOldProtocol; + virtual ~NetworkMessage() {} + virtual bool receive(Socket *socket) = 0; + virtual bool receive(Socket *socket, NetworkMessageType type) { + return receive(socket); + }; - virtual void send(Socket* socket) = 0; - virtual size_t getDataSize() const = 0; - virtual unsigned char * getData() { return NULL; } + virtual void send(Socket *socket) = 0; + virtual size_t getDataSize() const = 0; + virtual unsigned char *getData() { return NULL; } - virtual NetworkMessageType getNetworkMessageType() const = 0; + virtual NetworkMessageType getNetworkMessageType() const = 0; - void dump_packet(string label, const void* data, int dataSize, bool isSend); + void dump_packet(string label, const void *data, int dataSize, bool isSend); protected: - //bool peek(Socket* socket, void* data, int dataSize); - bool receive(Socket* socket, void* data, int dataSize,bool tryReceiveUntilDataSizeMet); - void send(Socket* socket, const void* data, int dataSize); - void send(Socket* socket, const void* data, int dataSize, int8 messageType); - void send(Socket* socket, const void* data, int dataSize, int8 messageType, uint32 compressedLength); - - virtual const char * getPackedMessageFormat() const = 0; - virtual unsigned int getPackedSize() = 0; - virtual void unpackMessage(unsigned char *buf) = 0; - virtual unsigned char * packMessage() = 0; + // bool peek(Socket* socket, void* data, int dataSize); + bool receive(Socket *socket, void *data, int dataSize, + bool tryReceiveUntilDataSizeMet); + void send(Socket *socket, const void *data, int dataSize); + void send(Socket *socket, const void *data, int dataSize, int8 messageType); + void send(Socket *socket, const void *data, int dataSize, int8 messageType, + uint32 compressedLength); + + virtual const char *getPackedMessageFormat() const = 0; + virtual unsigned int getPackedSize() = 0; + virtual void unpackMessage(unsigned char *buf) = 0; + virtual unsigned char *packMessage() = 0; }; // ===================================================== @@ -142,72 +146,72 @@ class NetworkMessage { // ===================================================== #pragma pack(push, 1) -class NetworkMessageIntro: public NetworkMessage{ +class NetworkMessageIntro : public NetworkMessage { private: - static const int maxVersionStringSize= 128; - static const int maxNameSize= 32; - static const int maxSmallStringSize= 60; + static const int maxVersionStringSize = 128; + static const int maxNameSize = 32; + static const int maxSmallStringSize = 60; private: - int8 messageType; - struct Data { - int32 sessionId; - NetworkString versionString; - NetworkString name; - int16 playerIndex; - int8 gameState; - uint32 externalIp; - uint32 ftpPort; - NetworkString language; - int8 gameInProgress; - NetworkString playerUUID; - NetworkString platform; - }; - - void toEndian(); - void fromEndian(); + int8 messageType; + struct Data { + int32 sessionId; + NetworkString versionString; + NetworkString name; + int16 playerIndex; + int8 gameState; + uint32 externalIp; + uint32 ftpPort; + NetworkString language; + int8 gameInProgress; + NetworkString playerUUID; + NetworkString platform; + }; + + void toEndian(); + void fromEndian(); private: - Data data; + Data data; protected: - public: - NetworkMessageIntro(); - NetworkMessageIntro(int32 sessionId, const string &versionString, - const string &name, int playerIndex, NetworkGameStateType gameState, - uint32 externalIp, uint32 ftpPort, const string &playerLanguage, - int gameInProgress, const string &playerUUID, const string &platform); - - - virtual const char * getPackedMessageFormat() const; - virtual unsigned int getPackedSize(); - virtual void unpackMessage(unsigned char *buf); - virtual unsigned char * packMessage(); - - virtual size_t getDataSize() const { return sizeof(Data); } - - virtual NetworkMessageType getNetworkMessageType() const { - return nmtIntro; - } - - int32 getSessionId() const { return data.sessionId;} - string getVersionString() const { return data.versionString.getString(); } - string getName() const { return data.name.getString(); } - int getPlayerIndex() const { return data.playerIndex; } - NetworkGameStateType getGameState() const { return static_cast(data.gameState); } - uint32 getExternalIp() const { return data.externalIp;} - uint32 getFtpPort() const { return data.ftpPort; } - string getPlayerLanguage() const { return data.language.getString(); } - uint8 getGameInProgress() const { return data.gameInProgress; } - - string getPlayerUUID() const { return data.playerUUID.getString();} - string getPlayerPlatform() const { return data.platform.getString();} - - virtual bool receive(Socket* socket); - virtual void send(Socket* socket); - - string toString() const; + NetworkMessageIntro(); + NetworkMessageIntro(int32 sessionId, const string &versionString, + const string &name, int playerIndex, + NetworkGameStateType gameState, uint32 externalIp, + uint32 ftpPort, const string &playerLanguage, + int gameInProgress, const string &playerUUID, + const string &platform); + + virtual const char *getPackedMessageFormat() const; + virtual unsigned int getPackedSize(); + virtual void unpackMessage(unsigned char *buf); + virtual unsigned char *packMessage(); + + virtual size_t getDataSize() const { return sizeof(Data); } + + virtual NetworkMessageType getNetworkMessageType() const { return nmtIntro; } + + int32 getSessionId() const { return data.sessionId; } + string getVersionString() const { return data.versionString.getString(); } + string getName() const { return data.name.getString(); } + int getPlayerIndex() const { return data.playerIndex; } + NetworkGameStateType getGameState() const { + return static_cast(data.gameState); + } + uint32 getExternalIp() const { return data.externalIp; } + uint32 getFtpPort() const { return data.ftpPort; } + string getPlayerLanguage() const { return data.language.getString(); } + uint8 getGameInProgress() const { return data.gameInProgress; } + + string getPlayerUUID() const { return data.playerUUID.getString(); } + string getPlayerPlatform() const { return data.platform.getString(); } + + virtual bool receive(Socket *socket); + virtual void send(Socket *socket); + + string toString() const; }; #pragma pack(pop) @@ -218,43 +222,43 @@ class NetworkMessageIntro: public NetworkMessage{ // ===================================================== #pragma pack(push, 1) -class NetworkMessagePing: public NetworkMessage{ +class NetworkMessagePing : public NetworkMessage { private: - int8 messageType; - struct Data{ - int32 pingFrequency; - int64 pingTime; - }; - void toEndian(); - void fromEndian(); + int8 messageType; + struct Data { + int32 pingFrequency; + int64 pingTime; + }; + void toEndian(); + void fromEndian(); private: - Data data; - int64 pingReceivedLocalTime; + Data data; + int64 pingReceivedLocalTime; protected: - virtual const char * getPackedMessageFormat() const; - virtual unsigned int getPackedSize(); - virtual void unpackMessage(unsigned char *buf); - virtual unsigned char * packMessage(); + virtual const char *getPackedMessageFormat() const; + virtual unsigned int getPackedSize(); + virtual void unpackMessage(unsigned char *buf); + virtual unsigned char *packMessage(); public: - NetworkMessagePing(); - NetworkMessagePing(int32 pingFrequency, int64 pingTime); + NetworkMessagePing(); + NetworkMessagePing(int32 pingFrequency, int64 pingTime); - virtual size_t getDataSize() const { return sizeof(Data); } + virtual size_t getDataSize() const { return sizeof(Data); } - virtual NetworkMessageType getNetworkMessageType() const { - return nmtPing; - } + virtual NetworkMessageType getNetworkMessageType() const { return nmtPing; } - int32 getPingFrequency() const {return data.pingFrequency;} - int64 getPingTime() const {return data.pingTime;} - int64 getPingReceivedLocalTime() const { return pingReceivedLocalTime; } - void setPingReceivedLocalTime(int64 pingTime) { pingReceivedLocalTime = pingTime; } + int32 getPingFrequency() const { return data.pingFrequency; } + int64 getPingTime() const { return data.pingTime; } + int64 getPingReceivedLocalTime() const { return pingReceivedLocalTime; } + void setPingReceivedLocalTime(int64 pingTime) { + pingReceivedLocalTime = pingTime; + } - virtual bool receive(Socket* socket); - virtual void send(Socket* socket); + virtual bool receive(Socket *socket); + virtual void send(Socket *socket); }; #pragma pack(pop) @@ -265,38 +269,36 @@ class NetworkMessagePing: public NetworkMessage{ // ===================================================== #pragma pack(push, 1) -class NetworkMessageReady: public NetworkMessage{ +class NetworkMessageReady : public NetworkMessage { private: - int8 messageType; - struct Data{ - uint32 checksum; - }; - void toEndian(); - void fromEndian(); + int8 messageType; + struct Data { + uint32 checksum; + }; + void toEndian(); + void fromEndian(); private: - Data data; + Data data; protected: - virtual const char * getPackedMessageFormat() const; - virtual unsigned int getPackedSize(); - virtual void unpackMessage(unsigned char *buf); - virtual unsigned char * packMessage(); + virtual const char *getPackedMessageFormat() const; + virtual unsigned int getPackedSize(); + virtual void unpackMessage(unsigned char *buf); + virtual unsigned char *packMessage(); public: - NetworkMessageReady(); - explicit NetworkMessageReady(uint32 checksum); + NetworkMessageReady(); + explicit NetworkMessageReady(uint32 checksum); - virtual size_t getDataSize() const { return sizeof(Data); } + virtual size_t getDataSize() const { return sizeof(Data); } - virtual NetworkMessageType getNetworkMessageType() const { - return nmtReady; - } + virtual NetworkMessageType getNetworkMessageType() const { return nmtReady; } - uint32 getChecksum() const {return data.checksum;} + uint32 getChecksum() const { return data.checksum; } - virtual bool receive(Socket* socket); - virtual void send(Socket* socket); + virtual bool receive(Socket *socket); + virtual void send(Socket *socket); }; #pragma pack(pop) @@ -308,101 +310,105 @@ class NetworkMessageReady: public NetworkMessage{ // ===================================================== #pragma pack(push, 1) -class NetworkMessageLaunch: public NetworkMessage { +class NetworkMessageLaunch : public NetworkMessage { private: - static const int maxStringSize= 256; - static const int maxSmallStringSize= 60; - static const int maxFactionCRCCount= 20; + static const int maxStringSize = 256; + static const int maxSmallStringSize = 60; + static const int maxFactionCRCCount = 20; private: + int8 messageType; + uint32 compressedLength; + struct Data { + NetworkString description; + NetworkString map; + NetworkString tileset; + NetworkString tech; + NetworkString + factionTypeNames[GameConstants::maxPlayers]; // faction names + NetworkString + networkPlayerNames[GameConstants::maxPlayers]; // networkPlayerNames + NetworkString + networkPlayerPlatform[GameConstants::maxPlayers]; + int32 networkPlayerStatuses + [GameConstants::maxPlayers]; // networkPlayerStatuses + NetworkString + networkPlayerLanguages[GameConstants::maxPlayers]; + + uint32 mapCRC; + int8 mapFilter; + uint32 tilesetCRC; + uint32 techCRC; + NetworkString factionNameList[maxFactionCRCCount]; + uint32 factionCRCList[maxFactionCRCCount]; + + int8 factionControls[GameConstants::maxPlayers]; + int8 resourceMultiplierIndex[GameConstants::maxPlayers]; + + int8 thisFactionIndex; + int8 factionCount; + int8 teams[GameConstants::maxPlayers]; + int8 startLocationIndex[GameConstants::maxPlayers]; + + int8 defaultResources; + int8 defaultUnits; + int8 defaultVictoryConditions; + int8 fogOfWar; + int8 allowObservers; + int8 enableObserverModeAtEndGame; + int8 enableServerControlledAI; + uint8 networkFramePeriod; // allowed values 0 - 255 + int8 networkPauseGameForLaggedClients; + int8 pathFinderType; + uint32 flagTypes1; + + int8 aiAcceptSwitchTeamPercentChance; + int8 cpuReplacementMultiplier; + int32 masterserver_admin; + int32 masterserver_admin_factionIndex; + + NetworkString scenario; + + NetworkString + networkPlayerUUID[GameConstants::maxPlayers]; + + int8 networkAllowNativeLanguageTechtree; + NetworkString gameUUID; + }; + void toEndian(); + void fromEndian(); + std::pair getCompressedMessage(); - int8 messageType; - uint32 compressedLength; - struct Data { - NetworkString description; - NetworkString map; - NetworkString tileset; - NetworkString tech; - NetworkString factionTypeNames[GameConstants::maxPlayers]; //faction names - NetworkString networkPlayerNames[GameConstants::maxPlayers]; //networkPlayerNames - NetworkString networkPlayerPlatform[GameConstants::maxPlayers]; - int32 networkPlayerStatuses[GameConstants::maxPlayers]; //networkPlayerStatuses - NetworkString networkPlayerLanguages[GameConstants::maxPlayers]; - - uint32 mapCRC; - int8 mapFilter; - uint32 tilesetCRC; - uint32 techCRC; - NetworkString factionNameList[maxFactionCRCCount]; - uint32 factionCRCList[maxFactionCRCCount]; - - int8 factionControls[GameConstants::maxPlayers]; - int8 resourceMultiplierIndex[GameConstants::maxPlayers]; - - int8 thisFactionIndex; - int8 factionCount; - int8 teams[GameConstants::maxPlayers]; - int8 startLocationIndex[GameConstants::maxPlayers]; - - int8 defaultResources; - int8 defaultUnits; - int8 defaultVictoryConditions; - int8 fogOfWar; - int8 allowObservers; - int8 enableObserverModeAtEndGame; - int8 enableServerControlledAI; - uint8 networkFramePeriod; // allowed values 0 - 255 - int8 networkPauseGameForLaggedClients; - int8 pathFinderType; - uint32 flagTypes1; - - int8 aiAcceptSwitchTeamPercentChance; - int8 cpuReplacementMultiplier; - int32 masterserver_admin; - int32 masterserver_admin_factionIndex; - - NetworkString scenario; - - NetworkString networkPlayerUUID[GameConstants::maxPlayers]; - - int8 networkAllowNativeLanguageTechtree; - NetworkString gameUUID; - }; - void toEndian(); - void fromEndian(); - std::pair getCompressedMessage(); private: - Data data; + Data data; protected: - virtual const char * getPackedMessageFormat() const; - virtual unsigned int getPackedSize(); - virtual void unpackMessage(unsigned char *buf); - virtual unsigned char * packMessage(); + virtual const char *getPackedMessageFormat() const; + virtual unsigned int getPackedSize(); + virtual void unpackMessage(unsigned char *buf); + virtual unsigned char *packMessage(); public: - NetworkMessageLaunch(); - NetworkMessageLaunch(const GameSettings *gameSettings,int8 messageType); + NetworkMessageLaunch(); + NetworkMessageLaunch(const GameSettings *gameSettings, int8 messageType); - virtual size_t getDataSize() const { return sizeof(Data); } - virtual unsigned char * getData(); + virtual size_t getDataSize() const { return sizeof(Data); } + virtual unsigned char *getData(); - virtual NetworkMessageType getNetworkMessageType() const { - return nmtLaunch; - } + virtual NetworkMessageType getNetworkMessageType() const { return nmtLaunch; } - void buildGameSettings(GameSettings *gameSettings) const; - int getMessageType() const { return messageType; } + void buildGameSettings(GameSettings *gameSettings) const; + int getMessageType() const { return messageType; } - int getMapCRC() const { return data.mapCRC; } - int getTilesetCRC() const { return data.tilesetCRC; } - int getTechCRC() const { return data.techCRC; } - vector > getFactionCRCList() const; + int getMapCRC() const { return data.mapCRC; } + int getTilesetCRC() const { return data.tilesetCRC; } + int getTechCRC() const { return data.techCRC; } + vector> getFactionCRCList() const; - virtual bool receive(Socket* socket); - virtual bool receive(Socket* socket, NetworkMessageType type); + virtual bool receive(Socket *socket); + virtual bool receive(Socket *socket, NetworkMessageType type); - virtual void send(Socket* socket); + virtual void send(Socket *socket); }; #pragma pack(pop) @@ -413,78 +419,81 @@ class NetworkMessageLaunch: public NetworkMessage { // ===================================================== #pragma pack(push, 1) -class NetworkMessageCommandList: public NetworkMessage { +class NetworkMessageCommandList : public NetworkMessage { private: - - struct DataHeader { - - uint16 commandCount; - int32 frameCount; - uint32 networkPlayerFactionCRC[GameConstants::maxPlayers]; - }; - - static const int32 commandListHeaderSize = sizeof(DataHeader); - - struct Data { - int8 messageType; - DataHeader header; - std::vector commands; - }; - void init(Data &data_ref) { - data_ref.messageType = 0; - data_ref.header.commandCount = 0; - data_ref.header.frameCount = 0; - for(int index = 0; index < GameConstants::maxPlayers; ++index) { - data_ref.header.networkPlayerFactionCRC[index] = 0; - } - } - void toEndianHeader(); - void fromEndianHeader(); - void toEndianDetail(uint16 totalCommand); - void fromEndianDetail(); + struct DataHeader { + + uint16 commandCount; + int32 frameCount; + uint32 networkPlayerFactionCRC[GameConstants::maxPlayers]; + }; + + static const int32 commandListHeaderSize = sizeof(DataHeader); + + struct Data { + int8 messageType; + DataHeader header; + std::vector commands; + }; + void init(Data &data_ref) { + data_ref.messageType = 0; + data_ref.header.commandCount = 0; + data_ref.header.frameCount = 0; + for (int index = 0; index < GameConstants::maxPlayers; ++index) { + data_ref.header.networkPlayerFactionCRC[index] = 0; + } + } + void toEndianHeader(); + void fromEndianHeader(); + void toEndianDetail(uint16 totalCommand); + void fromEndianDetail(); private: - Data data; + Data data; protected: - virtual const char * getPackedMessageFormat() const { return NULL; } - virtual unsigned int getPackedSize() { return 0; } - virtual void unpackMessage(unsigned char *buf) { }; - virtual unsigned char * packMessage() { return NULL; } + virtual const char *getPackedMessageFormat() const { return NULL; } + virtual unsigned int getPackedSize() { return 0; } + virtual void unpackMessage(unsigned char *buf){}; + virtual unsigned char *packMessage() { return NULL; } - const char * getPackedMessageFormatHeader() const; - unsigned int getPackedSizeHeader(); - void unpackMessageHeader(unsigned char *buf); - unsigned char * packMessageHeader(); + const char *getPackedMessageFormatHeader() const; + unsigned int getPackedSizeHeader(); + void unpackMessageHeader(unsigned char *buf); + unsigned char *packMessageHeader(); - const char * getPackedMessageFormatDetail() const; - unsigned int getPackedSizeDetail(int count); - void unpackMessageDetail(unsigned char *buf,int count); - unsigned char * packMessageDetail(uint16 totalCommand); + const char *getPackedMessageFormatDetail() const; + unsigned int getPackedSizeDetail(int count); + void unpackMessageDetail(unsigned char *buf, int count); + unsigned char *packMessageDetail(uint16 totalCommand); public: - explicit NetworkMessageCommandList(int32 frameCount= -1); + explicit NetworkMessageCommandList(int32 frameCount = -1); - virtual size_t getDataSize() const { return sizeof(Data); } - virtual unsigned char * getData(); + virtual size_t getDataSize() const { return sizeof(Data); } + virtual unsigned char *getData(); - virtual NetworkMessageType getNetworkMessageType() const { - return nmtCommandList; - } + virtual NetworkMessageType getNetworkMessageType() const { + return nmtCommandList; + } - bool addCommand(const NetworkCommand* networkCommand); + bool addCommand(const NetworkCommand *networkCommand); - void clear() {data.header.commandCount= 0;} - int getCommandCount() const {return data.header.commandCount;} - int getFrameCount() const {return data.header.frameCount;} - uint32 getNetworkPlayerFactionCRC(int index) const {return data.header.networkPlayerFactionCRC[index];} - void setNetworkPlayerFactionCRC(int index, uint32 crc) { data.header.networkPlayerFactionCRC[index]=crc;} + void clear() { data.header.commandCount = 0; } + int getCommandCount() const { return data.header.commandCount; } + int getFrameCount() const { return data.header.frameCount; } + uint32 getNetworkPlayerFactionCRC(int index) const { + return data.header.networkPlayerFactionCRC[index]; + } + void setNetworkPlayerFactionCRC(int index, uint32 crc) { + data.header.networkPlayerFactionCRC[index] = crc; + } - const NetworkCommand* getCommand(int i) const {return &data.commands[i];} + const NetworkCommand *getCommand(int i) const { return &data.commands[i]; } - virtual bool receive(Socket* socket); - virtual void send(Socket* socket); + virtual bool receive(Socket *socket); + virtual void send(Socket *socket); }; #pragma pack(pop) @@ -495,50 +504,48 @@ class NetworkMessageCommandList: public NetworkMessage { // ===================================================== #pragma pack(push, 1) -class NetworkMessageText: public NetworkMessage { +class NetworkMessageText : public NetworkMessage { private: - static const int maxTextStringSize= 500; + static const int maxTextStringSize = 500; private: - int8 messageType; - struct Data{ + int8 messageType; + struct Data { - NetworkString text; - int8 teamIndex; - int8 playerIndex; - NetworkString targetLanguage; - }; - void toEndian(); - void fromEndian(); + NetworkString text; + int8 teamIndex; + int8 playerIndex; + NetworkString targetLanguage; + }; + void toEndian(); + void fromEndian(); private: - Data data; + Data data; protected: - virtual const char * getPackedMessageFormat() const; - virtual unsigned int getPackedSize(); - virtual void unpackMessage(unsigned char *buf); - virtual unsigned char * packMessage(); + virtual const char *getPackedMessageFormat() const; + virtual unsigned int getPackedSize(); + virtual void unpackMessage(unsigned char *buf); + virtual unsigned char *packMessage(); public: - NetworkMessageText(); - NetworkMessageText(const string &text, int teamIndex, int playerIndex, - const string targetLanguage); + NetworkMessageText(); + NetworkMessageText(const string &text, int teamIndex, int playerIndex, + const string targetLanguage); - virtual size_t getDataSize() const { return sizeof(Data); } + virtual size_t getDataSize() const { return sizeof(Data); } - virtual NetworkMessageType getNetworkMessageType() const { - return nmtText; - } + virtual NetworkMessageType getNetworkMessageType() const { return nmtText; } - string getText() const {return data.text.getString();} - int getTeamIndex() const {return data.teamIndex;} - int getPlayerIndex() const {return data.playerIndex;} - string getTargetLanguage() const {return data.targetLanguage.getString();} + string getText() const { return data.text.getString(); } + int getTeamIndex() const { return data.teamIndex; } + int getPlayerIndex() const { return data.playerIndex; } + string getTargetLanguage() const { return data.targetLanguage.getString(); } - virtual bool receive(Socket* socket); - virtual void send(Socket* socket); - NetworkMessageText * getCopy() const; + virtual bool receive(Socket *socket); + virtual void send(Socket *socket); + NetworkMessageText *getCopy() const; }; #pragma pack(pop) @@ -549,37 +556,34 @@ class NetworkMessageText: public NetworkMessage { // ===================================================== #pragma pack(push, 1) -class NetworkMessageQuit: public NetworkMessage{ +class NetworkMessageQuit : public NetworkMessage { private: - - int8 messageType; - //struct Data{ - // int8 messageType; - //}; - void toEndian(); - void fromEndian(); + int8 messageType; + // struct Data{ + // int8 messageType; + // }; + void toEndian(); + void fromEndian(); private: - //Data data; + // Data data; protected: - virtual const char * getPackedMessageFormat() const; - virtual unsigned int getPackedSize(); - virtual void unpackMessage(unsigned char *buf); - virtual unsigned char * packMessage(); + virtual const char *getPackedMessageFormat() const; + virtual unsigned int getPackedSize(); + virtual void unpackMessage(unsigned char *buf); + virtual unsigned char *packMessage(); public: - NetworkMessageQuit(); + NetworkMessageQuit(); - //virtual size_t getDataSize() const { return sizeof(Data); } - virtual size_t getDataSize() const { return 0; } + // virtual size_t getDataSize() const { return sizeof(Data); } + virtual size_t getDataSize() const { return 0; } - virtual NetworkMessageType getNetworkMessageType() const { - return nmtQuit; - } + virtual NetworkMessageType getNetworkMessageType() const { return nmtQuit; } - virtual bool receive(Socket* socket); - virtual void send(Socket* socket); + virtual bool receive(Socket *socket); + virtual void send(Socket *socket); }; #pragma pack(pop) @@ -590,92 +594,95 @@ class NetworkMessageQuit: public NetworkMessage{ // ===================================================== #pragma pack(push, 1) -class NetworkMessageSynchNetworkGameData: public NetworkMessage{ +class NetworkMessageSynchNetworkGameData : public NetworkMessage { private: - -static const int maxStringSize= 255; -static const int maxFileCRCCount= 1500; -static const int maxFileCRCPacketCount= 25; + static const int maxStringSize = 255; + static const int maxFileCRCCount = 1500; + static const int maxFileCRCPacketCount = 25; private: - - struct DataHeader { - NetworkString map; - NetworkString tileset; - NetworkString tech; - - uint32 mapCRC; - uint32 tilesetCRC; - uint32 techCRC; - - uint32 techCRCFileCount; - }; - - static const int32 HeaderSize = sizeof(DataHeader); - - struct DataDetail { - NetworkString techCRCFileList[maxFileCRCCount]; - uint32 techCRCFileCRCList[maxFileCRCCount]; - }; - - static const int32 DetailSize1 = sizeof(NetworkString); - static const int32 DetailSize2 = sizeof(uint32); - - struct Data { - int8 messageType; - DataHeader header; - DataDetail detail; - }; - void toEndianHeader(); - void fromEndianHeader(); - void toEndianDetail(uint32 totalFileCount); - void fromEndianDetail(); + struct DataHeader { + NetworkString map; + NetworkString tileset; + NetworkString tech; + + uint32 mapCRC; + uint32 tilesetCRC; + uint32 techCRC; + + uint32 techCRCFileCount; + }; + + static const int32 HeaderSize = sizeof(DataHeader); + + struct DataDetail { + NetworkString techCRCFileList[maxFileCRCCount]; + uint32 techCRCFileCRCList[maxFileCRCCount]; + }; + + static const int32 DetailSize1 = sizeof(NetworkString); + static const int32 DetailSize2 = sizeof(uint32); + + struct Data { + int8 messageType; + DataHeader header; + DataDetail detail; + }; + void toEndianHeader(); + void fromEndianHeader(); + void toEndianDetail(uint32 totalFileCount); + void fromEndianDetail(); private: - Data data; + Data data; protected: - virtual const char * getPackedMessageFormat() const { return NULL; } - virtual unsigned int getPackedSize() { return 0; } - virtual void unpackMessage(unsigned char *buf) { }; - virtual unsigned char * packMessage() { return NULL; } + virtual const char *getPackedMessageFormat() const { return NULL; } + virtual unsigned int getPackedSize() { return 0; } + virtual void unpackMessage(unsigned char *buf){}; + virtual unsigned char *packMessage() { return NULL; } - const char * getPackedMessageFormatHeader() const; - unsigned int getPackedSizeHeader(); - void unpackMessageHeader(unsigned char *buf); - unsigned char * packMessageHeader(); + const char *getPackedMessageFormatHeader() const; + unsigned int getPackedSizeHeader(); + void unpackMessageHeader(unsigned char *buf); + unsigned char *packMessageHeader(); - unsigned int getPackedSizeDetail(); - void unpackMessageDetail(unsigned char *buf); - unsigned char * packMessageDetail(); + unsigned int getPackedSizeDetail(); + void unpackMessageDetail(unsigned char *buf); + unsigned char *packMessageDetail(); public: - NetworkMessageSynchNetworkGameData() {}; - explicit NetworkMessageSynchNetworkGameData(const GameSettings *gameSettings); + NetworkMessageSynchNetworkGameData(){}; + explicit NetworkMessageSynchNetworkGameData(const GameSettings *gameSettings); - virtual size_t getDataSize() const { return sizeof(Data); } + virtual size_t getDataSize() const { return sizeof(Data); } - virtual NetworkMessageType getNetworkMessageType() const { - return nmtSynchNetworkGameData; - } + virtual NetworkMessageType getNetworkMessageType() const { + return nmtSynchNetworkGameData; + } - virtual bool receive(Socket* socket); - virtual void send(Socket* socket); + virtual bool receive(Socket *socket); + virtual void send(Socket *socket); - string getMap() const {return data.header.map.getString();} - string getTileset() const {return data.header.tileset.getString();} - string getTech() const {return data.header.tech.getString();} + string getMap() const { return data.header.map.getString(); } + string getTileset() const { return data.header.tileset.getString(); } + string getTech() const { return data.header.tech.getString(); } - uint32 getMapCRC() const {return data.header.mapCRC;} - uint32 getTilesetCRC() const {return data.header.tilesetCRC;} - uint32 getTechCRC() const {return data.header.techCRC;} + uint32 getMapCRC() const { return data.header.mapCRC; } + uint32 getTilesetCRC() const { return data.header.tilesetCRC; } + uint32 getTechCRC() const { return data.header.techCRC; } - uint32 getTechCRCFileCount() const {return data.header.techCRCFileCount;} - const NetworkString * getTechCRCFileList() const {return &data.detail.techCRCFileList[0];} - const uint32 * getTechCRCFileCRCList() const {return data.detail.techCRCFileCRCList;} + uint32 getTechCRCFileCount() const { return data.header.techCRCFileCount; } + const NetworkString *getTechCRCFileList() const { + return &data.detail.techCRCFileList[0]; + } + const uint32 *getTechCRCFileCRCList() const { + return data.detail.techCRCFileCRCList; + } - string getTechCRCFileMismatchReport(vector > &vctFileList); + string + getTechCRCFileMismatchReport(vector> &vctFileList); }; #pragma pack(pop) @@ -686,75 +693,80 @@ static const int maxFileCRCPacketCount= 25; // ===================================================== #pragma pack(push, 1) -class NetworkMessageSynchNetworkGameDataStatus: public NetworkMessage{ +class NetworkMessageSynchNetworkGameDataStatus : public NetworkMessage { private: - -static const int maxStringSize= 255; -static const int maxFileCRCCount= 1500; -static const uint32 maxFileCRCPacketCount= 25; + static const int maxStringSize = 255; + static const int maxFileCRCCount = 1500; + static const uint32 maxFileCRCPacketCount = 25; private: - - struct DataHeader { - uint32 mapCRC; - uint32 tilesetCRC; - uint32 techCRC; - - uint32 techCRCFileCount; - }; - static const int32 HeaderSize = sizeof(DataHeader); - - struct DataDetail { - NetworkString techCRCFileList[maxFileCRCCount]; - uint32 techCRCFileCRCList[maxFileCRCCount]; - }; - - static const int32 DetailSize1 = sizeof(NetworkString); - static const int32 DetailSize2 = sizeof(uint32); - - struct Data { - int8 messageType; - DataHeader header; - DataDetail detail; - }; - void toEndianHeader(); - void fromEndianHeader(); - void toEndianDetail(uint32 totalFileCount); - void fromEndianDetail(); + struct DataHeader { + uint32 mapCRC; + uint32 tilesetCRC; + uint32 techCRC; + + uint32 techCRCFileCount; + }; + static const int32 HeaderSize = sizeof(DataHeader); + + struct DataDetail { + NetworkString techCRCFileList[maxFileCRCCount]; + uint32 techCRCFileCRCList[maxFileCRCCount]; + }; + + static const int32 DetailSize1 = sizeof(NetworkString); + static const int32 DetailSize2 = sizeof(uint32); + + struct Data { + int8 messageType; + DataHeader header; + DataDetail detail; + }; + void toEndianHeader(); + void fromEndianHeader(); + void toEndianDetail(uint32 totalFileCount); + void fromEndianDetail(); private: - Data data; + Data data; protected: - virtual const char * getPackedMessageFormat() const { return NULL; } - virtual unsigned int getPackedSize() { return 0; } - virtual void unpackMessage(unsigned char *buf) { }; - virtual unsigned char * packMessage() { return NULL; } + virtual const char *getPackedMessageFormat() const { return NULL; } + virtual unsigned int getPackedSize() { return 0; } + virtual void unpackMessage(unsigned char *buf){}; + virtual unsigned char *packMessage() { return NULL; } public: - NetworkMessageSynchNetworkGameDataStatus() {}; - NetworkMessageSynchNetworkGameDataStatus(uint32 mapCRC, uint32 tilesetCRC, uint32 techCRC, vector > &vctFileList); - - virtual size_t getDataSize() const { return sizeof(Data); } - - virtual NetworkMessageType getNetworkMessageType() const { - return nmtSynchNetworkGameDataStatus; - } - - virtual bool receive(Socket* socket); - virtual void send(Socket* socket); - - uint32 getMapCRC() const {return data.header.mapCRC;} - uint32 getTilesetCRC() const {return data.header.tilesetCRC;} - uint32 getTechCRC() const {return data.header.techCRC;} - - uint32 getTechCRCFileCount() const {return data.header.techCRCFileCount;} - const NetworkString * getTechCRCFileList() const {return &data.detail.techCRCFileList[0];} - const uint32 * getTechCRCFileCRCList() const {return data.detail.techCRCFileCRCList;} - - string getTechCRCFileMismatchReport(string techtree, vector > &vctFileList); - + NetworkMessageSynchNetworkGameDataStatus(){}; + NetworkMessageSynchNetworkGameDataStatus( + uint32 mapCRC, uint32 tilesetCRC, uint32 techCRC, + vector> &vctFileList); + + virtual size_t getDataSize() const { return sizeof(Data); } + + virtual NetworkMessageType getNetworkMessageType() const { + return nmtSynchNetworkGameDataStatus; + } + + virtual bool receive(Socket *socket); + virtual void send(Socket *socket); + + uint32 getMapCRC() const { return data.header.mapCRC; } + uint32 getTilesetCRC() const { return data.header.tilesetCRC; } + uint32 getTechCRC() const { return data.header.techCRC; } + + uint32 getTechCRCFileCount() const { return data.header.techCRCFileCount; } + const NetworkString *getTechCRCFileList() const { + return &data.detail.techCRCFileList[0]; + } + const uint32 *getTechCRCFileCRCList() const { + return data.detail.techCRCFileCRCList; + } + + string + getTechCRCFileMismatchReport(string techtree, + vector> &vctFileList); }; #pragma pack(pop) @@ -765,51 +777,52 @@ static const uint32 maxFileCRCPacketCount= 25; // ===================================================== #pragma pack(push, 1) -class NetworkMessageSynchNetworkGameDataFileCRCCheck: public NetworkMessage{ +class NetworkMessageSynchNetworkGameDataFileCRCCheck : public NetworkMessage { private: - -static const int maxStringSize= 256; + static const int maxStringSize = 256; private: - int8 messageType; - struct Data{ + int8 messageType; + struct Data { - - uint32 totalFileCount; - uint32 fileIndex; - uint32 fileCRC; - NetworkString fileName; - }; - void toEndian(); - void fromEndian(); + uint32 totalFileCount; + uint32 fileIndex; + uint32 fileCRC; + NetworkString fileName; + }; + void toEndian(); + void fromEndian(); private: - Data data; + Data data; protected: - virtual const char * getPackedMessageFormat() const; - virtual unsigned int getPackedSize(); - virtual void unpackMessage(unsigned char *buf); - virtual unsigned char * packMessage(); + virtual const char *getPackedMessageFormat() const; + virtual unsigned int getPackedSize(); + virtual void unpackMessage(unsigned char *buf); + virtual unsigned char *packMessage(); public: - NetworkMessageSynchNetworkGameDataFileCRCCheck(); - NetworkMessageSynchNetworkGameDataFileCRCCheck(uint32 totalFileCount, uint32 fileIndex, uint32 fileCRC, const string fileName); + NetworkMessageSynchNetworkGameDataFileCRCCheck(); + NetworkMessageSynchNetworkGameDataFileCRCCheck(uint32 totalFileCount, + uint32 fileIndex, + uint32 fileCRC, + const string fileName); - virtual size_t getDataSize() const { return sizeof(Data); } + virtual size_t getDataSize() const { return sizeof(Data); } - virtual NetworkMessageType getNetworkMessageType() const { - return nmtSynchNetworkGameDataFileCRCCheck; - } + virtual NetworkMessageType getNetworkMessageType() const { + return nmtSynchNetworkGameDataFileCRCCheck; + } - virtual bool receive(Socket* socket); - virtual void send(Socket* socket); + virtual bool receive(Socket *socket); + virtual void send(Socket *socket); - uint32 getTotalFileCount() const {return data.totalFileCount;} - uint32 getFileIndex() const {return data.fileIndex;} - uint32 getFileCRC() const {return data.fileCRC;} - string getFileName() const {return data.fileName.getString();} + uint32 getTotalFileCount() const { return data.totalFileCount; } + uint32 getFileIndex() const { return data.fileIndex; } + uint32 getFileCRC() const { return data.fileCRC; } + string getFileName() const { return data.fileName.getString(); } }; #pragma pack(pop) @@ -820,45 +833,43 @@ static const int maxStringSize= 256; // ===================================================== #pragma pack(push, 1) -class NetworkMessageSynchNetworkGameDataFileGet: public NetworkMessage{ +class NetworkMessageSynchNetworkGameDataFileGet : public NetworkMessage { private: - -static const int maxStringSize= 256; + static const int maxStringSize = 256; private: + int8 messageType; + struct Data { - int8 messageType; - struct Data{ - - NetworkString fileName; - }; - void toEndian(); - void fromEndian(); + NetworkString fileName; + }; + void toEndian(); + void fromEndian(); private: - Data data; + Data data; protected: - virtual const char * getPackedMessageFormat() const; - virtual unsigned int getPackedSize(); - virtual void unpackMessage(unsigned char *buf); - virtual unsigned char * packMessage(); + virtual const char *getPackedMessageFormat() const; + virtual unsigned int getPackedSize(); + virtual void unpackMessage(unsigned char *buf); + virtual unsigned char *packMessage(); public: - NetworkMessageSynchNetworkGameDataFileGet(); - explicit NetworkMessageSynchNetworkGameDataFileGet(const string fileName); + NetworkMessageSynchNetworkGameDataFileGet(); + explicit NetworkMessageSynchNetworkGameDataFileGet(const string fileName); - virtual size_t getDataSize() const { return sizeof(Data); } + virtual size_t getDataSize() const { return sizeof(Data); } - virtual NetworkMessageType getNetworkMessageType() const { - return nmtSynchNetworkGameDataFileGet; - } + virtual NetworkMessageType getNetworkMessageType() const { + return nmtSynchNetworkGameDataFileGet; + } - virtual bool receive(Socket* socket); - virtual void send(Socket* socket); + virtual bool receive(Socket *socket); + virtual void send(Socket *socket); - string getFileName() const {return data.fileName.getString();} + string getFileName() const { return data.fileName.getString(); } }; #pragma pack(pop) @@ -871,74 +882,80 @@ static const int maxStringSize= 256; // Each bit represents which item in the packet has a changed value enum SwitchSetupRequestFlagType { - ssrft_None = 0x00, - ssrft_SelectedFactionName = 0x01, - ssrft_CurrentFactionIndex = 0x02, - ssrft_ToFactionIndex = 0x04, - ssrft_ToTeam = 0x08, - ssrft_NetworkPlayerName = 0x10, - ssrft_PlayerStatus = 0x20 + ssrft_None = 0x00, + ssrft_SelectedFactionName = 0x01, + ssrft_CurrentFactionIndex = 0x02, + ssrft_ToFactionIndex = 0x04, + ssrft_ToTeam = 0x08, + ssrft_NetworkPlayerName = 0x10, + ssrft_PlayerStatus = 0x20 }; #pragma pack(push, 1) -class SwitchSetupRequest: public NetworkMessage{ +class SwitchSetupRequest : public NetworkMessage { private: - static const int maxStringSize= 256; - static const int maxPlayernameStringSize= 80; + static const int maxStringSize = 256; + static const int maxPlayernameStringSize = 80; private: - - int8 messageType; - struct Data { - - NetworkString selectedFactionName; //wanted faction name - int8 currentSlotIndex; - int8 toSlotIndex; - int8 toTeam; - NetworkString networkPlayerName; - int8 networkPlayerStatus; - int8 switchFlags; - NetworkString language; - }; - void toEndian(); - void fromEndian(); + int8 messageType; + struct Data { + + NetworkString selectedFactionName; // wanted faction name + int8 currentSlotIndex; + int8 toSlotIndex; + int8 toTeam; + NetworkString networkPlayerName; + int8 networkPlayerStatus; + int8 switchFlags; + NetworkString language; + }; + void toEndian(); + void fromEndian(); private: - Data data; + Data data; public: - virtual const char * getPackedMessageFormat() const; - virtual unsigned int getPackedSize(); - virtual void unpackMessage(unsigned char *buf); - virtual unsigned char * packMessage(); + virtual const char *getPackedMessageFormat() const; + virtual unsigned int getPackedSize(); + virtual void unpackMessage(unsigned char *buf); + virtual unsigned char *packMessage(); public: - SwitchSetupRequest(); - SwitchSetupRequest( string selectedFactionName, int8 currentFactionIndex, - int8 toFactionIndex,int8 toTeam,string networkPlayerName, - int8 networkPlayerStatus, int8 flags, - string language); - - virtual size_t getDataSize() const { return sizeof(Data); } - - virtual NetworkMessageType getNetworkMessageType() const { - return nmtSwitchSetupRequest; - } - - string getSelectedFactionName() const {return data.selectedFactionName.getString();} - int getCurrentSlotIndex() const {return data.currentSlotIndex;} - int getToSlotIndex() const {return data.toSlotIndex;} - int getToTeam() const {return data.toTeam;} - string getNetworkPlayerName() const {return data.networkPlayerName.getString(); } - int getSwitchFlags() const {return data.switchFlags;} - void addSwitchFlag(SwitchSetupRequestFlagType flag) { data.switchFlags |= flag;} - void clearSwitchFlag(SwitchSetupRequestFlagType flag) { data.switchFlags &= ~flag;} - - int getNetworkPlayerStatus() const { return data.networkPlayerStatus; } - string getNetworkPlayerLanguage() const { return data.language.getString(); } - - virtual bool receive(Socket* socket); - virtual void send(Socket* socket); + SwitchSetupRequest(); + SwitchSetupRequest(string selectedFactionName, int8 currentFactionIndex, + int8 toFactionIndex, int8 toTeam, string networkPlayerName, + int8 networkPlayerStatus, int8 flags, string language); + + virtual size_t getDataSize() const { return sizeof(Data); } + + virtual NetworkMessageType getNetworkMessageType() const { + return nmtSwitchSetupRequest; + } + + string getSelectedFactionName() const { + return data.selectedFactionName.getString(); + } + int getCurrentSlotIndex() const { return data.currentSlotIndex; } + int getToSlotIndex() const { return data.toSlotIndex; } + int getToTeam() const { return data.toTeam; } + string getNetworkPlayerName() const { + return data.networkPlayerName.getString(); + } + int getSwitchFlags() const { return data.switchFlags; } + void addSwitchFlag(SwitchSetupRequestFlagType flag) { + data.switchFlags |= flag; + } + void clearSwitchFlag(SwitchSetupRequestFlagType flag) { + data.switchFlags &= ~flag; + } + + int getNetworkPlayerStatus() const { return data.networkPlayerStatus; } + string getNetworkPlayerLanguage() const { return data.language.getString(); } + + virtual bool receive(Socket *socket); + virtual void send(Socket *socket); }; #pragma pack(pop) @@ -950,40 +967,39 @@ class SwitchSetupRequest: public NetworkMessage{ // ===================================================== #pragma pack(push, 1) -class PlayerIndexMessage: public NetworkMessage{ +class PlayerIndexMessage : public NetworkMessage { private: + int8 messageType; + struct Data { - int8 messageType; - struct Data { - - int16 playerIndex; - }; - void toEndian(); - void fromEndian(); + int16 playerIndex; + }; + void toEndian(); + void fromEndian(); private: - Data data; + Data data; protected: - virtual const char * getPackedMessageFormat() const; - virtual unsigned int getPackedSize(); - virtual void unpackMessage(unsigned char *buf); - virtual unsigned char * packMessage(); + virtual const char *getPackedMessageFormat() const; + virtual unsigned int getPackedSize(); + virtual void unpackMessage(unsigned char *buf); + virtual unsigned char *packMessage(); public: - explicit PlayerIndexMessage( int16 playerIndex); + explicit PlayerIndexMessage(int16 playerIndex); - virtual size_t getDataSize() const { return sizeof(Data); } + virtual size_t getDataSize() const { return sizeof(Data); } - virtual NetworkMessageType getNetworkMessageType() const { - return nmtPlayerIndexMessage; - } + virtual NetworkMessageType getNetworkMessageType() const { + return nmtPlayerIndexMessage; + } - int16 getPlayerIndex() const {return data.playerIndex;} + int16 getPlayerIndex() const { return data.playerIndex; } - virtual bool receive(Socket* socket); - virtual void send(Socket* socket); + virtual bool receive(Socket *socket); + virtual void send(Socket *socket); }; #pragma pack(pop) @@ -994,66 +1010,64 @@ class PlayerIndexMessage: public NetworkMessage{ // ===================================================== enum NetworkMessageLoadingStatusType { - nmls_NONE = 0x00, - - nmls_PLAYER1_CONNECTED = 0x01, - nmls_PLAYER2_CONNECTED = 0x02, - nmls_PLAYER3_CONNECTED = 0x04, - nmls_PLAYER4_CONNECTED = 0x08, - nmls_PLAYER5_CONNECTED = 0x10, - nmls_PLAYER6_CONNECTED = 0x20, - nmls_PLAYER7_CONNECTED = 0x40, - nmls_PLAYER8_CONNECTED = 0x80, - - nmls_PLAYER1_READY = 0x100, - nmls_PLAYER2_READY = 0x200, - nmls_PLAYER3_READY = 0x400, - nmls_PLAYER4_READY = 0x1000, - nmls_PLAYER5_READY = 0x2000, - nmls_PLAYER6_READY = 0x4000, - nmls_PLAYER7_READY = 0x8000, - nmls_PLAYER8_READY = 0x10000 + nmls_NONE = 0x00, + + nmls_PLAYER1_CONNECTED = 0x01, + nmls_PLAYER2_CONNECTED = 0x02, + nmls_PLAYER3_CONNECTED = 0x04, + nmls_PLAYER4_CONNECTED = 0x08, + nmls_PLAYER5_CONNECTED = 0x10, + nmls_PLAYER6_CONNECTED = 0x20, + nmls_PLAYER7_CONNECTED = 0x40, + nmls_PLAYER8_CONNECTED = 0x80, + + nmls_PLAYER1_READY = 0x100, + nmls_PLAYER2_READY = 0x200, + nmls_PLAYER3_READY = 0x400, + nmls_PLAYER4_READY = 0x1000, + nmls_PLAYER5_READY = 0x2000, + nmls_PLAYER6_READY = 0x4000, + nmls_PLAYER7_READY = 0x8000, + nmls_PLAYER8_READY = 0x10000 }; #pragma pack(push, 1) class NetworkMessageLoadingStatus : public NetworkMessage { private: + int8 messageType; + struct Data { - int8 messageType; - struct Data { - - uint32 status; - }; - void toEndian(); - void fromEndian(); + uint32 status; + }; + void toEndian(); + void fromEndian(); private: - Data data; + Data data; protected: - virtual const char * getPackedMessageFormat() const; - virtual unsigned int getPackedSize(); - virtual void unpackMessage(unsigned char *buf); - virtual unsigned char * packMessage(); + virtual const char *getPackedMessageFormat() const; + virtual unsigned int getPackedSize(); + virtual void unpackMessage(unsigned char *buf); + virtual unsigned char *packMessage(); public: - NetworkMessageLoadingStatus(); - explicit NetworkMessageLoadingStatus(uint32 status); + NetworkMessageLoadingStatus(); + explicit NetworkMessageLoadingStatus(uint32 status); - virtual size_t getDataSize() const { return sizeof(Data); } + virtual size_t getDataSize() const { return sizeof(Data); } - virtual NetworkMessageType getNetworkMessageType() const { - return nmtLoadingStatusMessage; - } + virtual NetworkMessageType getNetworkMessageType() const { + return nmtLoadingStatusMessage; + } - uint32 getStatus() const {return data.status;} + uint32 getStatus() const { return data.status; } - virtual bool receive(Socket* socket); - virtual void send(Socket* socket); + virtual bool receive(Socket *socket); + virtual void send(Socket *socket); }; #pragma pack(pop) - // ===================================================== // class NetworkMessageMarkCell // @@ -1061,52 +1075,51 @@ class NetworkMessageLoadingStatus : public NetworkMessage { // ===================================================== #pragma pack(push, 1) -class NetworkMessageMarkCell: public NetworkMessage { +class NetworkMessageMarkCell : public NetworkMessage { private: - static const int maxTextStringSize= 500; + static const int maxTextStringSize = 500; private: - - int8 messageType; - struct Data{ - - - int16 targetX; - int16 targetY; - int8 factionIndex; - int8 playerIndex; - NetworkString text; - }; - void toEndian(); - void fromEndian(); + int8 messageType; + struct Data { + + int16 targetX; + int16 targetY; + int8 factionIndex; + int8 playerIndex; + NetworkString text; + }; + void toEndian(); + void fromEndian(); private: - Data data; + Data data; protected: - virtual const char * getPackedMessageFormat() const; - virtual unsigned int getPackedSize(); - virtual void unpackMessage(unsigned char *buf); - virtual unsigned char * packMessage(); + virtual const char *getPackedMessageFormat() const; + virtual unsigned int getPackedSize(); + virtual void unpackMessage(unsigned char *buf); + virtual unsigned char *packMessage(); public: - NetworkMessageMarkCell(); - NetworkMessageMarkCell(Vec2i target, int factionIndex, const string &text, int playerIndex); + NetworkMessageMarkCell(); + NetworkMessageMarkCell(Vec2i target, int factionIndex, const string &text, + int playerIndex); - virtual size_t getDataSize() const { return sizeof(Data); } + virtual size_t getDataSize() const { return sizeof(Data); } - virtual NetworkMessageType getNetworkMessageType() const { - return nmtMarkCell; - } + virtual NetworkMessageType getNetworkMessageType() const { + return nmtMarkCell; + } - string getText() const { return data.text.getString(); } - Vec2i getTarget() const { return Vec2i(data.targetX,data.targetY); } - int getFactionIndex() const { return data.factionIndex; } - int getPlayerIndex() const { return data.playerIndex; } + string getText() const { return data.text.getString(); } + Vec2i getTarget() const { return Vec2i(data.targetX, data.targetY); } + int getFactionIndex() const { return data.factionIndex; } + int getPlayerIndex() const { return data.playerIndex; } - virtual bool receive(Socket* socket); - virtual void send(Socket* socket); - NetworkMessageMarkCell * getCopy() const; + virtual bool receive(Socket *socket); + virtual void send(Socket *socket); + NetworkMessageMarkCell *getCopy() const; }; #pragma pack(pop) @@ -1117,46 +1130,44 @@ class NetworkMessageMarkCell: public NetworkMessage { // ===================================================== #pragma pack(push, 1) -class NetworkMessageUnMarkCell: public NetworkMessage { +class NetworkMessageUnMarkCell : public NetworkMessage { private: + int8 messageType; + struct Data { - int8 messageType; - struct Data { - - - int16 targetX; - int16 targetY; - int8 factionIndex; - }; - void toEndian(); - void fromEndian(); + int16 targetX; + int16 targetY; + int8 factionIndex; + }; + void toEndian(); + void fromEndian(); private: - Data data; + Data data; protected: - virtual const char * getPackedMessageFormat() const; - virtual unsigned int getPackedSize(); - virtual void unpackMessage(unsigned char *buf); - virtual unsigned char * packMessage(); + virtual const char *getPackedMessageFormat() const; + virtual unsigned int getPackedSize(); + virtual void unpackMessage(unsigned char *buf); + virtual unsigned char *packMessage(); public: - NetworkMessageUnMarkCell(); - NetworkMessageUnMarkCell(Vec2i target, int factionIndex); + NetworkMessageUnMarkCell(); + NetworkMessageUnMarkCell(Vec2i target, int factionIndex); - virtual size_t getDataSize() const { return sizeof(Data); } + virtual size_t getDataSize() const { return sizeof(Data); } - virtual NetworkMessageType getNetworkMessageType() const { - return nmtUnMarkCell; - } + virtual NetworkMessageType getNetworkMessageType() const { + return nmtUnMarkCell; + } - Vec2i getTarget() const { return Vec2i(data.targetX,data.targetY); } - int getFactionIndex() const { return data.factionIndex; } + Vec2i getTarget() const { return Vec2i(data.targetX, data.targetY); } + int getFactionIndex() const { return data.factionIndex; } - virtual bool receive(Socket* socket); - virtual void send(Socket* socket); - NetworkMessageUnMarkCell * getCopy() const; + virtual bool receive(Socket *socket); + virtual void send(Socket *socket); + NetworkMessageUnMarkCell *getCopy() const; }; #pragma pack(pop) @@ -1166,51 +1177,50 @@ class NetworkMessageUnMarkCell: public NetworkMessage { // Highlight a Cell message // ===================================================== - #pragma pack(push, 1) -class NetworkMessageHighlightCell: public NetworkMessage { +class NetworkMessageHighlightCell : public NetworkMessage { private: - static const int maxTextStringSize= 500; + static const int maxTextStringSize = 500; private: + int8 messageType; + struct Data { - int8 messageType; - struct Data{ - - int16 targetX; - int16 targetY; - int8 factionIndex; - }; - void toEndian(); - void fromEndian(); + int16 targetX; + int16 targetY; + int8 factionIndex; + }; + void toEndian(); + void fromEndian(); private: - Data data; + Data data; protected: - virtual const char * getPackedMessageFormat() const; - virtual unsigned int getPackedSize(); - virtual void unpackMessage(unsigned char *buf); - virtual unsigned char * packMessage(); + virtual const char *getPackedMessageFormat() const; + virtual unsigned int getPackedSize(); + virtual void unpackMessage(unsigned char *buf); + virtual unsigned char *packMessage(); public: - NetworkMessageHighlightCell(); - NetworkMessageHighlightCell(Vec2i target, int factionIndex); + NetworkMessageHighlightCell(); + NetworkMessageHighlightCell(Vec2i target, int factionIndex); - virtual size_t getDataSize() const { return sizeof(Data); } + virtual size_t getDataSize() const { return sizeof(Data); } - virtual NetworkMessageType getNetworkMessageType() const { - return nmtHighlightCell; - } + virtual NetworkMessageType getNetworkMessageType() const { + return nmtHighlightCell; + } - Vec2i getTarget() const { return Vec2i(data.targetX,data.targetY); } - int getFactionIndex() const { return data.factionIndex; } + Vec2i getTarget() const { return Vec2i(data.targetX, data.targetY); } + int getFactionIndex() const { return data.factionIndex; } - virtual bool receive(Socket* socket); - virtual void send(Socket* socket); + virtual bool receive(Socket *socket); + virtual void send(Socket *socket); }; #pragma pack(pop) -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/network/network_protocol.cpp b/source/glest_game/network/network_protocol.cpp index fdb3adfa6..2a523052a 100644 --- a/source/glest_game/network/network_protocol.cpp +++ b/source/glest_game/network/network_protocol.cpp @@ -9,18 +9,19 @@ // License, or (at your option) any later version // ============================================================== #include "network_protocol.h" -#include +#include "data_types.h" +#include "leak_dumper.h" +#include "util.h" #include #include +#include #include -#include "data_types.h" -#include "util.h" -#include "leak_dumper.h" using namespace Shared::Platform; using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { #pragma pack(push, 1) @@ -35,194 +36,202 @@ namespace Glest{ namespace Game{ /* ** pack754() -- pack a floating point number into IEEE-754 format */ -unsigned long long int pack754(long double f, unsigned bits, unsigned expbits) -{ - long double fnorm; - int shift; - long long sign, exp, significand; - unsigned significandbits = bits - expbits - 1; // -1 for sign bit - - if (f == 0.0) return 0; // get this special case out of the way - - // check sign and begin normalization - if (f < 0) { sign = 1; fnorm = -f; } - else { sign = 0; fnorm = f; } - - // get the normalized form of f and track the exponent - shift = 0; - while(fnorm >= 2.0) { fnorm /= 2.0; shift++; } - while(fnorm < 1.0) { fnorm *= 2.0; shift--; } - fnorm = fnorm - 1.0; - - // calculate the binary form (non-float) of the significand data - significand = fnorm * ((1LL<= 2.0) { + fnorm /= 2.0; + shift++; + } + while (fnorm < 1.0) { + fnorm *= 2.0; + shift--; + } + fnorm = fnorm - 1.0; + + // calculate the binary form (non-float) of the significand data + significand = fnorm * ((1LL << significandbits) + 0.5f); + + // get the biased exponent + exp = (long long)shift + ((1 << (expbits - 1)) - 1); // shift + bias + + // return the final answer + return (sign << (bits - 1)) | (exp << (bits - expbits - 1)) | significand; } /* ** unpack754() -- unpack a floating point number from IEEE-754 format */ -long double unpack754(unsigned long long int i, unsigned bits, unsigned expbits) -{ - long double result; - long long shift; - unsigned bias; - unsigned significandbits = bits - expbits - 1; // -1 for sign bit - - if (i == 0) return 0.0; - - // pull the significand - result = (i&((1LL<>significandbits)&((1LL< 0) { result *= 2.0; shift--; } - while(shift < 0) { result /= 2.0; shift++; } - - // sign it - result *= ((i>>(bits-1))&1) ? -1.0: 1.0; - - return result; +long double unpack754(unsigned long long int i, unsigned bits, + unsigned expbits) { + long double result; + long long shift; + unsigned bias; + unsigned significandbits = bits - expbits - 1; // -1 for sign bit + + if (i == 0) + return 0.0; + + // pull the significand + result = (i & ((1LL << significandbits) - 1)); // mask + result /= (1LL << significandbits); // convert back to float + result += 1.0f; // add the one back on + + // deal with the exponent + bias = (1 << (expbits - 1)) - 1; + shift = ((i >> significandbits) & ((1LL << expbits) - 1)) - bias; + while (shift > 0) { + result *= 2.0; + shift--; + } + while (shift < 0) { + result /= 2.0; + shift++; + } + + // sign it + result *= ((i >> (bits - 1)) & 1) ? -1.0 : 1.0; + + return result; } /* ** packi16() -- store a 16-bit int into a char buffer (like htons()) */ -void packi16(unsigned char *buf, uint16 i) -{ - *buf++ = i>>8; *buf++ = i; +void packi16(unsigned char *buf, uint16 i) { + *buf++ = i >> 8; + *buf++ = i; } /* ** packi32() -- store a 32-bit int into a char buffer (like htonl()) */ -void packi32(unsigned char *buf, uint32 i) -{ - *buf++ = i>>24; *buf++ = i>>16; - *buf++ = i>>8; *buf++ = i; +void packi32(unsigned char *buf, uint32 i) { + *buf++ = i >> 24; + *buf++ = i >> 16; + *buf++ = i >> 8; + *buf++ = i; } /* ** packi64() -- store a 64-bit int into a char buffer (like htonl()) */ -void packi64(unsigned char *buf, uint64 i) -{ - *buf++ = i>>56; *buf++ = i>>48; - *buf++ = i>>40; *buf++ = i>>32; - *buf++ = i>>24; *buf++ = i>>16; - *buf++ = i>>8; *buf++ = i; +void packi64(unsigned char *buf, uint64 i) { + *buf++ = i >> 56; + *buf++ = i >> 48; + *buf++ = i >> 40; + *buf++ = i >> 32; + *buf++ = i >> 24; + *buf++ = i >> 16; + *buf++ = i >> 8; + *buf++ = i; } /* ** unpacki16() -- unpack a 16-bit int from a char buffer (like ntohs()) */ -int16 unpacki16(unsigned char *buf) -{ - uint16 i2 = ((uint16)buf[0]<<8) | buf[1]; - int16 i; - - // change unsigned numbers to signed - if (i2 <= 0x7fffu) { - i = i2; - } - else { - i = -1 - (uint16)(0xffffu - i2); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("IN [%s] [%d] [%d] [%d] [%u]\n",__FUNCTION__,buf[0],buf[1],i,i2); - } - - return i; +int16 unpacki16(unsigned char *buf) { + uint16 i2 = ((uint16)buf[0] << 8) | buf[1]; + int16 i; + + // change unsigned numbers to signed + if (i2 <= 0x7fffu) { + i = i2; + } else { + i = -1 - (uint16)(0xffffu - i2); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("IN [%s] [%d] [%d] [%d] [%u]\n", __FUNCTION__, buf[0], buf[1], i, + i2); + } + + return i; } /* ** unpacku16() -- unpack a 16-bit unsigned from a char buffer (like ntohs()) */ -uint16 unpacku16(unsigned char *buf) -{ - return ((uint16)buf[0]<<8) | buf[1]; -} +uint16 unpacku16(unsigned char *buf) { return ((uint16)buf[0] << 8) | buf[1]; } /* ** unpacki32() -- unpack a 32-bit int from a char buffer (like ntohl()) */ -int32 unpacki32(unsigned char *buf) -{ - uint32 i2 = ((uint32)buf[0]<<24) | - ((uint32)buf[1]<<16) | - ((uint32)buf[2]<<8) | - buf[3]; - int32 i; - - // change unsigned numbers to signed - if (i2 <= 0x7fffffffu) { - i = i2; - } - else { - i = -1 - (int32)(0xffffffffu - i2); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("IN [%s] [%d] [%d] [%d] [%d] [%d] [%u]\n",__FUNCTION__,buf[0],buf[1],buf[2],buf[3],i,i2); - } - - return i; +int32 unpacki32(unsigned char *buf) { + uint32 i2 = ((uint32)buf[0] << 24) | ((uint32)buf[1] << 16) | + ((uint32)buf[2] << 8) | buf[3]; + int32 i; + + // change unsigned numbers to signed + if (i2 <= 0x7fffffffu) { + i = i2; + } else { + i = -1 - (int32)(0xffffffffu - i2); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("IN [%s] [%d] [%d] [%d] [%d] [%d] [%u]\n", __FUNCTION__, buf[0], + buf[1], buf[2], buf[3], i, i2); + } + + return i; } /* ** unpacku32() -- unpack a 32-bit unsigned from a char buffer (like ntohl()) */ -uint32 unpacku32(unsigned char *buf) -{ - return ((uint32)buf[0]<<24) | - ((uint32)buf[1]<<16) | - ((uint32)buf[2]<<8) | - buf[3]; +uint32 unpacku32(unsigned char *buf) { + return ((uint32)buf[0] << 24) | ((uint32)buf[1] << 16) | + ((uint32)buf[2] << 8) | buf[3]; } /* ** unpacki64() -- unpack a 64-bit int from a char buffer (like ntohl()) */ -int64 unpacki64(unsigned char *buf) -{ - uint64 i2 = ((uint64)buf[0]<<56) | - ((uint64)buf[1]<<48) | - ((uint64)buf[2]<<40) | - ((uint64)buf[3]<<32) | - ((uint64)buf[4]<<24) | - ((uint64)buf[5]<<16) | - ((uint64)buf[6]<<8) | - buf[7]; - int64 i; - - // change unsigned numbers to signed - if (i2 <= 0x7fffffffffffffffull) { - i = i2; - } - else { - i = -1 -(int64)(0xffffffffffffffffull - i2); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("IN [%s] [%d] [%d] [%d] [%d] [%d] [%d] [%d] [%d] [" MG_I64_SPECIFIER "] [" MG_I64U_SPECIFIER "]\n",__FUNCTION__,buf[0],buf[1],buf[2],buf[3],buf[4],buf[5],buf[6],buf[7],i,i2); - } - - return i; +int64 unpacki64(unsigned char *buf) { + uint64 i2 = ((uint64)buf[0] << 56) | ((uint64)buf[1] << 48) | + ((uint64)buf[2] << 40) | ((uint64)buf[3] << 32) | + ((uint64)buf[4] << 24) | ((uint64)buf[5] << 16) | + ((uint64)buf[6] << 8) | buf[7]; + int64 i; + + // change unsigned numbers to signed + if (i2 <= 0x7fffffffffffffffull) { + i = i2; + } else { + i = -1 - (int64)(0xffffffffffffffffull - i2); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf( + "IN [%s] [%d] [%d] [%d] [%d] [%d] [%d] [%d] [%d] [" MG_I64_SPECIFIER + "] [" MG_I64U_SPECIFIER "]\n", + __FUNCTION__, buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], + buf[7], i, i2); + } + + return i; } /* ** unpacku64() -- unpack a 64-bit unsigned from a char buffer (like ntohl()) */ -uint64 unpacku64(unsigned char *buf) -{ - return ((uint64)buf[0]<<56) | - ((uint64)buf[1]<<48) | - ((uint64)buf[2]<<40) | - ((uint64)buf[3]<<32) | - ((uint64)buf[4]<<24) | - ((uint64)buf[5]<<16) | - ((uint64)buf[6]<<8) | - buf[7]; +uint64 unpacku64(unsigned char *buf) { + return ((uint64)buf[0] << 56) | ((uint64)buf[1] << 48) | + ((uint64)buf[2] << 40) | ((uint64)buf[3] << 32) | + ((uint64)buf[4] << 24) | ((uint64)buf[5] << 16) | + ((uint64)buf[6] << 8) | buf[7]; } /* @@ -240,163 +249,187 @@ uint64 unpacku64(unsigned char *buf) */ unsigned int pack(unsigned char *buf, const char *format, ...) { - va_list ap; - - int8 c; // 8-bit - uint8 C; - - int16 h; // 16-bit - uint16 H; - - int32 l; // 32-bit - uint32 L; - - int64 q; // 64-bit - uint64 Q; - - float f; // floats - double d; - long double g; - unsigned long long int fhold; - - char *s; // strings - uint16 len; - - unsigned int size = 0; - - uint16 maxstrlen=0; - - unsigned char *bufStart = buf; - - va_start(ap, format); - - for(; *format != '\0'; format++) { - switch(*format) { - case 'c': // 8-bit - size += 1; - c = (int8)va_arg(ap, int); // promoted - *buf++ = (unsigned char)c; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("pack int8 = %d [%X] c = %d [%X] buf pos = %lu\n",*(buf-1),*(buf-1),c,c,(unsigned long)(buf - bufStart)); - break; - - case 'C': // 8-bit unsigned - size += 1; - C = (uint8)va_arg(ap, unsigned int); // promoted - *buf++ = (unsigned char)C; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("pack uint8 = %u [%X] C = %u [%X] buf pos = %lu\n",*(buf-1),*(buf-1),C,C,(unsigned long)(buf - bufStart)); - break; - - case 'h': // 16-bit - size += 2; - h = (int16)va_arg(ap, int); - packi16(buf, h); - buf += 2; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("pack int16 = %d [%X] h = %d [%X] buf pos = %lu\n",*(buf-2),*(buf-2),h,h,(unsigned long)(buf - bufStart)); - break; - - case 'H': // 16-bit unsigned - size += 2; - H = (uint16)va_arg(ap, unsigned int); - packi16(buf, H); - buf += 2; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("pack uint16 = %u [%X] H = %u [%X] buf pos = %lu\n",*(buf-2),*(buf-2),H,H,(unsigned long)(buf - bufStart)); - break; - - case 'l': // 32-bit - size += 4; - l = va_arg(ap, int32); - packi32(buf, l); - buf += 4; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("pack int32 = %d [%X] l = %d [%X] buf pos = %lu\n",*(buf-4),*(buf-4),l,l,(unsigned long)(buf - bufStart)); - break; - - case 'L': // 32-bit unsigned - size += 4; - L = va_arg(ap, uint32); - packi32(buf, L); - buf += 4; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("pack uint32 = %u [%X] L = %u [%X] buf pos = %lu\n",*(buf-4),*(buf-4),L,L,(unsigned long)(buf - bufStart)); - break; - - case 'q': // 64-bit - size += 8; - q = va_arg(ap, int64); - packi64(buf, q); - buf += 8; - - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("pack int64 = " MG_I64_SPECIFIER " [%X] q = " MG_I64_SPECIFIER " [%lX] buf pos = %lu\n",(int64)*(buf-8),*(buf-8),q,q,(unsigned long)(buf - bufStart)); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("pack int64 = " MG_I64_SPECIFIER " [%X] q = " MG_I64_SPECIFIER " buf pos = %lu\n",(int64)*(buf-8),*(buf-8),q,(unsigned long)(buf - bufStart)); - break; - - case 'Q': // 64-bit unsigned - size += 8; - Q = va_arg(ap, uint64); - packi64(buf, Q); - buf += 8; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("pack uint64 = " MG_I64U_SPECIFIER " [%X] Q = " MG_I64U_SPECIFIER " buf pos = %lu\n",(uint64)*(buf-8),*(buf-8),Q,(unsigned long)(buf - bufStart)); - break; - - case 'f': // float-16 - size += 2; - f = (float)va_arg(ap, double); // promoted - fhold = pack754_16(f); // convert to IEEE 754 - packi16(buf, fhold); - buf += 2; - break; - - case 'd': // float-32 - size += 4; - d = va_arg(ap, double); - fhold = pack754_32(d); // convert to IEEE 754 - packi32(buf, fhold); - buf += 4; - break; - - case 'g': // float-64 - size += 8; - g = va_arg(ap, long double); - fhold = pack754_64(g); // convert to IEEE 754 - packi64(buf, fhold); - buf += 8; - break; - - case 's': // string - s = va_arg(ap, char*); - len = (uint16)strlen(s); - if (maxstrlen > 0 && len < maxstrlen) - len = maxstrlen - 1; - - size += len + 2; - packi16(buf, len); - buf += 2; - - memcpy(buf, s, len); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("pack string size = %d [%X] len = %d str [%s] buf pos = %lu\n",*(buf-2),*(buf-2),len,s,(unsigned long)(buf - bufStart)); - - buf += len; - break; - - default: - if (isdigit(*format)) { // track max str len - maxstrlen = maxstrlen * 10 + (*format-'0'); - } - break; - } - - if (!isdigit(*format)) maxstrlen = 0; - - } - - va_end(ap); - - return size; + va_list ap; + + int8 c; // 8-bit + uint8 C; + + int16 h; // 16-bit + uint16 H; + + int32 l; // 32-bit + uint32 L; + + int64 q; // 64-bit + uint64 Q; + + float f; // floats + double d; + long double g; + unsigned long long int fhold; + + char *s; // strings + uint16 len; + + unsigned int size = 0; + + uint16 maxstrlen = 0; + + unsigned char *bufStart = buf; + + va_start(ap, format); + + for (; *format != '\0'; format++) { + switch (*format) { + case 'c': // 8-bit + size += 1; + c = (int8)va_arg(ap, int); // promoted + *buf++ = (unsigned char)c; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("pack int8 = %d [%X] c = %d [%X] buf pos = %lu\n", *(buf - 1), + *(buf - 1), c, c, (unsigned long)(buf - bufStart)); + break; + + case 'C': // 8-bit unsigned + size += 1; + C = (uint8)va_arg(ap, unsigned int); // promoted + *buf++ = (unsigned char)C; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("pack uint8 = %u [%X] C = %u [%X] buf pos = %lu\n", *(buf - 1), + *(buf - 1), C, C, (unsigned long)(buf - bufStart)); + break; + + case 'h': // 16-bit + size += 2; + h = (int16)va_arg(ap, int); + packi16(buf, h); + buf += 2; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("pack int16 = %d [%X] h = %d [%X] buf pos = %lu\n", *(buf - 2), + *(buf - 2), h, h, (unsigned long)(buf - bufStart)); + break; + + case 'H': // 16-bit unsigned + size += 2; + H = (uint16)va_arg(ap, unsigned int); + packi16(buf, H); + buf += 2; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("pack uint16 = %u [%X] H = %u [%X] buf pos = %lu\n", *(buf - 2), + *(buf - 2), H, H, (unsigned long)(buf - bufStart)); + break; + + case 'l': // 32-bit + size += 4; + l = va_arg(ap, int32); + packi32(buf, l); + buf += 4; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("pack int32 = %d [%X] l = %d [%X] buf pos = %lu\n", *(buf - 4), + *(buf - 4), l, l, (unsigned long)(buf - bufStart)); + break; + + case 'L': // 32-bit unsigned + size += 4; + L = va_arg(ap, uint32); + packi32(buf, L); + buf += 4; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("pack uint32 = %u [%X] L = %u [%X] buf pos = %lu\n", *(buf - 4), + *(buf - 4), L, L, (unsigned long)(buf - bufStart)); + break; + + case 'q': // 64-bit + size += 8; + q = va_arg(ap, int64); + packi64(buf, q); + buf += 8; + + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("pack int64 = " + // MG_I64_SPECIFIER " [%X] q = " MG_I64_SPECIFIER " [%lX] buf pos = + // %lu\n",(int64)*(buf-8),*(buf-8),q,q,(unsigned long)(buf - bufStart)); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("pack int64 = " MG_I64_SPECIFIER " [%X] q = " MG_I64_SPECIFIER + " buf pos = %lu\n", + (int64) * (buf - 8), *(buf - 8), q, + (unsigned long)(buf - bufStart)); + break; + + case 'Q': // 64-bit unsigned + size += 8; + Q = va_arg(ap, uint64); + packi64(buf, Q); + buf += 8; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("pack uint64 = " MG_I64U_SPECIFIER " [%X] Q = " MG_I64U_SPECIFIER + " buf pos = %lu\n", + (uint64) * (buf - 8), *(buf - 8), Q, + (unsigned long)(buf - bufStart)); + break; + + case 'f': // float-16 + size += 2; + f = (float)va_arg(ap, double); // promoted + fhold = pack754_16(f); // convert to IEEE 754 + packi16(buf, fhold); + buf += 2; + break; + + case 'd': // float-32 + size += 4; + d = va_arg(ap, double); + fhold = pack754_32(d); // convert to IEEE 754 + packi32(buf, fhold); + buf += 4; + break; + + case 'g': // float-64 + size += 8; + g = va_arg(ap, long double); + fhold = pack754_64(g); // convert to IEEE 754 + packi64(buf, fhold); + buf += 8; + break; + + case 's': // string + s = va_arg(ap, char *); + len = (uint16)strlen(s); + if (maxstrlen > 0 && len < maxstrlen) + len = maxstrlen - 1; + + size += len + 2; + packi16(buf, len); + buf += 2; + + memcpy(buf, s, len); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("pack string size = %d [%X] len = %d str [%s] buf pos = %lu\n", + *(buf - 2), *(buf - 2), len, s, (unsigned long)(buf - bufStart)); + + buf += len; + break; + + default: + if (isdigit(*format)) { // track max str len + maxstrlen = maxstrlen * 10 + (*format - '0'); + } + break; + } + + if (!isdigit(*format)) + maxstrlen = 0; + } + + va_end(ap); + + return size; } /* @@ -414,172 +447,195 @@ unsigned int pack(unsigned char *buf, const char *format, ...) { ** prepended with a max length) */ unsigned int unpack(unsigned char *buf, const char *format, ...) { - va_list ap; - - int8 *c; // 8-bit - uint8 *C; - - int16 *h; // 16-bit - uint16 *H; - - int32 *l; // 32-bit - uint32 *L; - - int64 *q; // 64-bit - uint64 *Q; - - unsigned long long int fhold; - - char *s; - uint16 len, maxstrlen=0, count; - - unsigned int size = 0; - - unsigned char *bufStart = buf; - - va_start(ap, format); - - for(; *format != '\0'; format++) { - switch(*format) { - case 'c': // 8-bit - c = va_arg(ap, int8*); -// if (*buf <= 0x7f) { -// *c = *buf++; -// size += 1; -// } // re-sign -// else { -// *c = -1 - (unsigned char)(0xffu - *buf); -// } - *c = (int8)*buf++; - size += 1; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("unpack int8 = %d [%X] c = %d [%X] buf pos = %lu\n",*(buf-1),*(buf-1),*c,*c,(unsigned long)(buf - bufStart)); - break; - - case 'C': // 8-bit unsigned - C = va_arg(ap, uint8*); - *C = (uint8)*buf++; - size += 1; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("unpack uint8 = %u [%X] C = %u [%X] buf pos = %lu\n",*(buf-1),*(buf-1),*C,*C,(unsigned long)(buf - bufStart)); - break; - - case 'h': // 16-bit - h = va_arg(ap, int16*); - *h = unpacki16(buf); - buf += 2; - size += 2; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("unpack int16 = %d [%X] h = %d [%X] buf pos = %lu\n",*(buf-2),*(buf-2),*h,*h,(unsigned long)(buf - bufStart)); - break; - - case 'H': // 16-bit unsigned - H = va_arg(ap, uint16*); - *H = unpacku16(buf); - buf += 2; - size += 2; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("unpack uint16 = %u [%X] H = %u [%X] buf pos = %lu\n",*(buf-2),*(buf-2),*H,*H,(unsigned long)(buf - bufStart)); - break; - - case 'l': // 32-bit - l = va_arg(ap, int32*); - *l = unpacki32(buf); - buf += 4; - size += 4; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("unpack int32 = %d [%X] l = %d [%X] buf pos = %lu\n",*(buf-4),*(buf-4),*l,*l,(unsigned long)(buf - bufStart)); - break; - - case 'L': // 32-bit unsigned - L = va_arg(ap, uint32*); - *L = unpacku32(buf); - buf += 4; - size += 4; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("unpack uint32 = %u [%X] L = %u [%X] buf pos = %lu\n",*(buf-4),*(buf-4),*L,*L,(unsigned long)(buf - bufStart)); - break; - - case 'q': // 64-bit - q = va_arg(ap, int64*); - *q = unpacki64(buf); - buf += 8; - size += 8; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("unpack int64 = " MG_I64_SPECIFIER " [%X] q = " MG_I64_SPECIFIER " buf pos = %lu\n",(int64)*(buf-8),*(buf-8),*q,(unsigned long)(buf - bufStart)); - break; - - case 'Q': // 64-bit unsigned - Q = va_arg(ap, uint64*); - *Q = unpacku64(buf); - buf += 8; - size += 8; - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("unpack uint64 = " MG_I64U_SPECIFIER " [%X] Q = " MG_I64U_SPECIFIER " buf pos = %lu\n",(uint64)*(buf-8),*(buf-8),*Q,(unsigned long)(buf - bufStart)); - break; - - case 'f': // float - { - float *f = va_arg(ap, float*); - fhold = unpacku16(buf); - *f = unpack754_16(fhold); - buf += 2; - size += 2; - } - break; - - case 'd': // float-32 - { - double *d = va_arg(ap, double*); - fhold = unpacku32(buf); - *d = unpack754_32(fhold); - buf += 4; - size += 4; - } - break; - - case 'g': // float-64 - { - long double *g = va_arg(ap, long double*); - fhold = unpacku64(buf); - *g = unpack754_64(fhold); - buf += 8; - size += 8; - } - break; - - case 's': // string - s = va_arg(ap, char*); - len = unpacku16(buf); - buf += 2; - if (maxstrlen > 0 && len > maxstrlen) - count = maxstrlen - 1; - else - count = len; - - memcpy(s, buf, count); - s[count] = '\0'; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("unpack string size = %d [%X] count = %d len = %d str [%s] buf pos = %lu\n",*(buf-2),*(buf-2),count,len,s,(unsigned long)(buf - bufStart)); - - buf += len; - size += len; - break; - - default: - if (isdigit(*format)) { // track max str len - maxstrlen = maxstrlen * 10 + (*format-'0'); - } - break; - } - - if (!isdigit(*format)) maxstrlen = 0; - } - - va_end(ap); - - return size; + va_list ap; + + int8 *c; // 8-bit + uint8 *C; + + int16 *h; // 16-bit + uint16 *H; + + int32 *l; // 32-bit + uint32 *L; + + int64 *q; // 64-bit + uint64 *Q; + + unsigned long long int fhold; + + char *s; + uint16 len, maxstrlen = 0, count; + + unsigned int size = 0; + + unsigned char *bufStart = buf; + + va_start(ap, format); + + for (; *format != '\0'; format++) { + switch (*format) { + case 'c': // 8-bit + c = va_arg(ap, int8 *); + // if (*buf <= 0x7f) { + // *c = *buf++; + // size += 1; + // } // re-sign + // else { + // *c = -1 - (unsigned char)(0xffu - *buf); + // } + *c = (int8)*buf++; + size += 1; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("unpack int8 = %d [%X] c = %d [%X] buf pos = %lu\n", *(buf - 1), + *(buf - 1), *c, *c, (unsigned long)(buf - bufStart)); + break; + + case 'C': // 8-bit unsigned + C = va_arg(ap, uint8 *); + *C = (uint8)*buf++; + size += 1; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("unpack uint8 = %u [%X] C = %u [%X] buf pos = %lu\n", *(buf - 1), + *(buf - 1), *C, *C, (unsigned long)(buf - bufStart)); + break; + + case 'h': // 16-bit + h = va_arg(ap, int16 *); + *h = unpacki16(buf); + buf += 2; + size += 2; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("unpack int16 = %d [%X] h = %d [%X] buf pos = %lu\n", *(buf - 2), + *(buf - 2), *h, *h, (unsigned long)(buf - bufStart)); + break; + + case 'H': // 16-bit unsigned + H = va_arg(ap, uint16 *); + *H = unpacku16(buf); + buf += 2; + size += 2; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("unpack uint16 = %u [%X] H = %u [%X] buf pos = %lu\n", + *(buf - 2), *(buf - 2), *H, *H, (unsigned long)(buf - bufStart)); + break; + + case 'l': // 32-bit + l = va_arg(ap, int32 *); + *l = unpacki32(buf); + buf += 4; + size += 4; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("unpack int32 = %d [%X] l = %d [%X] buf pos = %lu\n", *(buf - 4), + *(buf - 4), *l, *l, (unsigned long)(buf - bufStart)); + break; + + case 'L': // 32-bit unsigned + L = va_arg(ap, uint32 *); + *L = unpacku32(buf); + buf += 4; + size += 4; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("unpack uint32 = %u [%X] L = %u [%X] buf pos = %lu\n", + *(buf - 4), *(buf - 4), *L, *L, (unsigned long)(buf - bufStart)); + break; + + case 'q': // 64-bit + q = va_arg(ap, int64 *); + *q = unpacki64(buf); + buf += 8; + size += 8; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("unpack int64 = " MG_I64_SPECIFIER " [%X] q = " MG_I64_SPECIFIER + " buf pos = %lu\n", + (int64) * (buf - 8), *(buf - 8), *q, + (unsigned long)(buf - bufStart)); + break; + + case 'Q': // 64-bit unsigned + Q = va_arg(ap, uint64 *); + *Q = unpacku64(buf); + buf += 8; + size += 8; + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("unpack uint64 = " MG_I64U_SPECIFIER + " [%X] Q = " MG_I64U_SPECIFIER " buf pos = %lu\n", + (uint64) * (buf - 8), *(buf - 8), *Q, + (unsigned long)(buf - bufStart)); + break; + + case 'f': // float + { + float *f = va_arg(ap, float *); + fhold = unpacku16(buf); + *f = unpack754_16(fhold); + buf += 2; + size += 2; + } break; + + case 'd': // float-32 + { + double *d = va_arg(ap, double *); + fhold = unpacku32(buf); + *d = unpack754_32(fhold); + buf += 4; + size += 4; + } break; + + case 'g': // float-64 + { + long double *g = va_arg(ap, long double *); + fhold = unpacku64(buf); + *g = unpack754_64(fhold); + buf += 8; + size += 8; + } break; + + case 's': // string + s = va_arg(ap, char *); + len = unpacku16(buf); + buf += 2; + if (maxstrlen > 0 && len > maxstrlen) + count = maxstrlen - 1; + else + count = len; + + memcpy(s, buf, count); + s[count] = '\0'; + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("unpack string size = %d [%X] count = %d len = %d str [%s] buf " + "pos = %lu\n", + *(buf - 2), *(buf - 2), count, len, s, + (unsigned long)(buf - bufStart)); + + buf += len; + size += len; + break; + + default: + if (isdigit(*format)) { // track max str len + maxstrlen = maxstrlen * 10 + (*format - '0'); + } + break; + } + + if (!isdigit(*format)) + maxstrlen = 0; + } + + va_end(ap); + + return size; } #pragma pack(pop) -}} +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/network/network_protocol.h b/source/glest_game/network/network_protocol.h index eb23fb1bd..f0438cd81 100644 --- a/source/glest_game/network/network_protocol.h +++ b/source/glest_game/network/network_protocol.h @@ -12,11 +12,13 @@ #ifndef NETWORK_PROTOCOL_H_ #define NETWORK_PROTOCOL_H_ -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { unsigned int pack(unsigned char *buf, const char *format, ...); unsigned int unpack(unsigned char *buf, const char *format, ...); -}}; +} // namespace Game +}; // namespace Glest #endif /* NETWORK_PROTOCOL_H_ */ diff --git a/source/glest_game/network/network_types.cpp b/source/glest_game/network/network_types.cpp index 62b73425a..bbeb7bad6 100644 --- a/source/glest_game/network/network_types.cpp +++ b/source/glest_game/network/network_types.cpp @@ -10,196 +10,250 @@ // ============================================================== #include "network_types.h" -#include "util.h" -#include "unit.h" -#include "world.h" -#include "unit_type.h" #include "game.h" #include "gui.h" #include "leak_dumper.h" +#include "unit.h" +#include "unit_type.h" +#include "util.h" +#include "world.h" using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class NetworkCommand // ===================================================== NetworkCommand::NetworkCommand(World *world, int networkCommandType, int unitId, - int commandTypeId, const Vec2i &pos, int unitTypeId, - int targetId, int facing, bool wantQueue, - CommandStateType commandStateType, - int commandStateValue, int unitCommandGroupId) - : networkCommandType(networkCommandType) - , unitId(unitId) - , unitTypeId(unitTypeId) - , commandTypeId(commandTypeId) - , positionX(pos.x) - , positionY(pos.y) - , wantQueue(wantQueue) - , commandStateType(commandStateType) - , commandStateValue(commandStateValue) - , unitCommandGroupId(unitCommandGroupId) - , unitFactionUnitCount(0) - , unitFactionIndex(0) { - - assert(targetId == -1 || facing == -1); - this->targetId = targetId >= 0 ? targetId : facing; - this->fromFactionIndex = world->getThisFactionIndex(); - - if(this->networkCommandType == nctGiveCommand) { - const Unit *unit= world->findUnitById(this->unitId); - - //validate unit - if(unit != NULL) { - this->unitFactionIndex = unit->getFaction()->getIndex(); - this->unitFactionUnitCount = unit->getFaction()->getUnitCount(); - - //const UnitType *unitType= world->findUnitTypeById(unit->getFaction()->getType(), this->unitTypeId); - const CommandType *ct = unit->getType()->findCommandTypeById(this->commandTypeId); - if(ct != NULL && ct->getClass() == ccBuild) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] %s\n",__FILE__,__FUNCTION__,__LINE__,toString().c_str()); - CardinalDir::assertDirValid(facing); - assert(targetId == -1); - } - } + int commandTypeId, const Vec2i &pos, + int unitTypeId, int targetId, int facing, + bool wantQueue, + CommandStateType commandStateType, + int commandStateValue, int unitCommandGroupId) + : networkCommandType(networkCommandType), unitId(unitId), + unitTypeId(unitTypeId), commandTypeId(commandTypeId), positionX(pos.x), + positionY(pos.y), wantQueue(wantQueue), + commandStateType(commandStateType), commandStateValue(commandStateValue), + unitCommandGroupId(unitCommandGroupId), unitFactionUnitCount(0), + unitFactionIndex(0) { + + assert(targetId == -1 || facing == -1); + this->targetId = targetId >= 0 ? targetId : facing; + this->fromFactionIndex = world->getThisFactionIndex(); + + if (this->networkCommandType == nctGiveCommand) { + const Unit *unit = world->findUnitById(this->unitId); + + // validate unit + if (unit != NULL) { + this->unitFactionIndex = unit->getFaction()->getIndex(); + this->unitFactionUnitCount = unit->getFaction()->getUnitCount(); + + // const UnitType *unitType= + // world->findUnitTypeById(unit->getFaction()->getType(), + // this->unitTypeId); + const CommandType *ct = + unit->getType()->findCommandTypeById(this->commandTypeId); + if (ct != NULL && ct->getClass() == ccBuild) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] %s\n", __FILE__, + __FUNCTION__, __LINE__, toString().c_str()); + CardinalDir::assertDirValid(facing); + assert(targetId == -1); + } } + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] Created NetworkCommand as follows:\n%s\n",__FILE__,__FUNCTION__,__LINE__,toString().c_str()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] Created NetworkCommand as follows:\n%s\n", + __FILE__, __FUNCTION__, __LINE__, toString().c_str()); } void NetworkCommand::preprocessNetworkCommand(World *world) { - if(networkCommandType == nctGiveCommand) { - const Unit *unit= world->findUnitById(unitId); - - //validate unit - if(unit != NULL) { - //const UnitType *unitType= world->findUnitTypeById(unit->getFaction()->getType(), unitTypeId); - const CommandType *ct = unit->getType()->findCommandTypeById(commandTypeId); - if(ct != NULL && ct->getClass() == ccBuild && targetId >= 0) { - CardinalDir::assertDirValid(targetId); - } - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] (unit == NULL) %s\n",__FILE__,__FUNCTION__,__LINE__,toString().c_str()); - } + if (networkCommandType == nctGiveCommand) { + const Unit *unit = world->findUnitById(unitId); + + // validate unit + if (unit != NULL) { + // const UnitType *unitType= + // world->findUnitTypeById(unit->getFaction()->getType(), unitTypeId); + const CommandType *ct = + unit->getType()->findCommandTypeById(commandTypeId); + if (ct != NULL && ct->getClass() == ccBuild && targetId >= 0) { + CardinalDir::assertDirValid(targetId); + } + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] (unit == NULL) %s\n", + __FILE__, __FUNCTION__, __LINE__, + toString().c_str()); } + } } - string NetworkCommand::toString() const { - char szBuf[8096]=""; - snprintf(szBuf,8096,"networkCommandType = %d\nunitId = %d\ncommandTypeId = %d\npositionX = %d\npositionY = %d\nunitTypeId = %d\ntargetId = %d\nwantQueue= %d\nfromFactionIndex = %d\nunitFactionUnitCount = %d\nunitFactionIndex = %d, commandStateType = %d, commandStateValue = %d, unitCommandGroupId = %d", - networkCommandType,unitId,commandTypeId,positionX,positionY,unitTypeId,targetId,wantQueue, - fromFactionIndex,unitFactionUnitCount,unitFactionIndex,commandStateType,commandStateValue, - unitCommandGroupId); - - string result = szBuf; - return result; + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "networkCommandType = %d\nunitId = %d\ncommandTypeId = " + "%d\npositionX = %d\npositionY = %d\nunitTypeId = %d\ntargetId = " + "%d\nwantQueue= %d\nfromFactionIndex = %d\nunitFactionUnitCount = " + "%d\nunitFactionIndex = %d, commandStateType = %d, " + "commandStateValue = %d, unitCommandGroupId = %d", + networkCommandType, unitId, commandTypeId, positionX, positionY, + unitTypeId, targetId, wantQueue, fromFactionIndex, + unitFactionUnitCount, unitFactionIndex, commandStateType, + commandStateValue, unitCommandGroupId); + + string result = szBuf; + return result; } void NetworkCommand::toEndian() { - networkCommandType = ::Shared::PlatformByteOrder::toCommonEndian(networkCommandType); - unitId = ::Shared::PlatformByteOrder::toCommonEndian(unitId); - unitTypeId = ::Shared::PlatformByteOrder::toCommonEndian(unitTypeId); - commandTypeId = ::Shared::PlatformByteOrder::toCommonEndian(commandTypeId); - positionX = ::Shared::PlatformByteOrder::toCommonEndian(positionX); - positionY = ::Shared::PlatformByteOrder::toCommonEndian(positionY); - targetId = ::Shared::PlatformByteOrder::toCommonEndian(targetId); - wantQueue = ::Shared::PlatformByteOrder::toCommonEndian(wantQueue); - fromFactionIndex = ::Shared::PlatformByteOrder::toCommonEndian(fromFactionIndex); - unitFactionUnitCount = ::Shared::PlatformByteOrder::toCommonEndian(unitFactionUnitCount); - unitFactionIndex = ::Shared::PlatformByteOrder::toCommonEndian(unitFactionIndex); - commandStateType = ::Shared::PlatformByteOrder::toCommonEndian(commandStateType); - commandStateValue = ::Shared::PlatformByteOrder::toCommonEndian(commandStateValue); - unitCommandGroupId = ::Shared::PlatformByteOrder::toCommonEndian(unitCommandGroupId); - + networkCommandType = + ::Shared::PlatformByteOrder::toCommonEndian(networkCommandType); + unitId = ::Shared::PlatformByteOrder::toCommonEndian(unitId); + unitTypeId = ::Shared::PlatformByteOrder::toCommonEndian(unitTypeId); + commandTypeId = ::Shared::PlatformByteOrder::toCommonEndian(commandTypeId); + positionX = ::Shared::PlatformByteOrder::toCommonEndian(positionX); + positionY = ::Shared::PlatformByteOrder::toCommonEndian(positionY); + targetId = ::Shared::PlatformByteOrder::toCommonEndian(targetId); + wantQueue = ::Shared::PlatformByteOrder::toCommonEndian(wantQueue); + fromFactionIndex = + ::Shared::PlatformByteOrder::toCommonEndian(fromFactionIndex); + unitFactionUnitCount = + ::Shared::PlatformByteOrder::toCommonEndian(unitFactionUnitCount); + unitFactionIndex = + ::Shared::PlatformByteOrder::toCommonEndian(unitFactionIndex); + commandStateType = + ::Shared::PlatformByteOrder::toCommonEndian(commandStateType); + commandStateValue = + ::Shared::PlatformByteOrder::toCommonEndian(commandStateValue); + unitCommandGroupId = + ::Shared::PlatformByteOrder::toCommonEndian(unitCommandGroupId); } void NetworkCommand::fromEndian() { - networkCommandType = ::Shared::PlatformByteOrder::fromCommonEndian(networkCommandType); - unitId = ::Shared::PlatformByteOrder::fromCommonEndian(unitId); - unitTypeId = ::Shared::PlatformByteOrder::fromCommonEndian(unitTypeId); - commandTypeId = ::Shared::PlatformByteOrder::fromCommonEndian(commandTypeId); - positionX = ::Shared::PlatformByteOrder::fromCommonEndian(positionX); - positionY = ::Shared::PlatformByteOrder::fromCommonEndian(positionY); - targetId = ::Shared::PlatformByteOrder::fromCommonEndian(targetId); - wantQueue = ::Shared::PlatformByteOrder::fromCommonEndian(wantQueue); - fromFactionIndex = ::Shared::PlatformByteOrder::fromCommonEndian(fromFactionIndex); - unitFactionUnitCount = ::Shared::PlatformByteOrder::fromCommonEndian(unitFactionUnitCount); - unitFactionIndex = ::Shared::PlatformByteOrder::fromCommonEndian(unitFactionIndex); - commandStateType = ::Shared::PlatformByteOrder::fromCommonEndian(commandStateType); - commandStateValue = ::Shared::PlatformByteOrder::fromCommonEndian(commandStateValue); - unitCommandGroupId = ::Shared::PlatformByteOrder::fromCommonEndian(unitCommandGroupId); + networkCommandType = + ::Shared::PlatformByteOrder::fromCommonEndian(networkCommandType); + unitId = ::Shared::PlatformByteOrder::fromCommonEndian(unitId); + unitTypeId = ::Shared::PlatformByteOrder::fromCommonEndian(unitTypeId); + commandTypeId = ::Shared::PlatformByteOrder::fromCommonEndian(commandTypeId); + positionX = ::Shared::PlatformByteOrder::fromCommonEndian(positionX); + positionY = ::Shared::PlatformByteOrder::fromCommonEndian(positionY); + targetId = ::Shared::PlatformByteOrder::fromCommonEndian(targetId); + wantQueue = ::Shared::PlatformByteOrder::fromCommonEndian(wantQueue); + fromFactionIndex = + ::Shared::PlatformByteOrder::fromCommonEndian(fromFactionIndex); + unitFactionUnitCount = + ::Shared::PlatformByteOrder::fromCommonEndian(unitFactionUnitCount); + unitFactionIndex = + ::Shared::PlatformByteOrder::fromCommonEndian(unitFactionIndex); + commandStateType = + ::Shared::PlatformByteOrder::fromCommonEndian(commandStateType); + commandStateValue = + ::Shared::PlatformByteOrder::fromCommonEndian(commandStateValue); + unitCommandGroupId = + ::Shared::PlatformByteOrder::fromCommonEndian(unitCommandGroupId); } -XmlNode * NetworkCommand::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *networkCommandNode = rootNode->addChild("NetworkCommand"); - -// int16 networkCommandType; - networkCommandNode->addAttribute("networkCommandType",intToStr(networkCommandType), mapTagReplacements); -// int32 unitId; - networkCommandNode->addAttribute("unitId",intToStr(unitId), mapTagReplacements); -// int16 unitTypeId; - networkCommandNode->addAttribute("unitTypeId",intToStr(unitTypeId), mapTagReplacements); -// int16 commandTypeId; - networkCommandNode->addAttribute("commandTypeId",intToStr(commandTypeId), mapTagReplacements); -// int16 positionX; - networkCommandNode->addAttribute("positionX",intToStr(positionX), mapTagReplacements); -// int16 positionY; - networkCommandNode->addAttribute("positionY",intToStr(positionY), mapTagReplacements); -// int32 targetId; - networkCommandNode->addAttribute("targetId",intToStr(targetId), mapTagReplacements); -// int8 wantQueue; - networkCommandNode->addAttribute("wantQueue",intToStr(wantQueue), mapTagReplacements); -// int8 fromFactionIndex; - networkCommandNode->addAttribute("fromFactionIndex",intToStr(fromFactionIndex), mapTagReplacements); -// uint16 unitFactionUnitCount; - networkCommandNode->addAttribute("unitFactionUnitCount",intToStr(unitFactionUnitCount), mapTagReplacements); -// int8 unitFactionIndex; - networkCommandNode->addAttribute("unitFactionIndex",intToStr(unitFactionIndex), mapTagReplacements); -// int8 commandStateType; - networkCommandNode->addAttribute("commandStateType",intToStr(commandStateType), mapTagReplacements); -// int32 commandStateValue; - networkCommandNode->addAttribute("commandStateValue",intToStr(commandStateValue), mapTagReplacements); -// int32 unitCommandGroupId; - networkCommandNode->addAttribute("unitCommandGroupId",intToStr(unitCommandGroupId), mapTagReplacements); - - return networkCommandNode; +XmlNode *NetworkCommand::saveGame(XmlNode *rootNode) { + std::map mapTagReplacements; + XmlNode *networkCommandNode = rootNode->addChild("NetworkCommand"); + + // int16 networkCommandType; + networkCommandNode->addAttribute( + "networkCommandType", intToStr(networkCommandType), mapTagReplacements); + // int32 unitId; + networkCommandNode->addAttribute("unitId", intToStr(unitId), + mapTagReplacements); + // int16 unitTypeId; + networkCommandNode->addAttribute("unitTypeId", intToStr(unitTypeId), + mapTagReplacements); + // int16 commandTypeId; + networkCommandNode->addAttribute("commandTypeId", intToStr(commandTypeId), + mapTagReplacements); + // int16 positionX; + networkCommandNode->addAttribute("positionX", intToStr(positionX), + mapTagReplacements); + // int16 positionY; + networkCommandNode->addAttribute("positionY", intToStr(positionY), + mapTagReplacements); + // int32 targetId; + networkCommandNode->addAttribute("targetId", intToStr(targetId), + mapTagReplacements); + // int8 wantQueue; + networkCommandNode->addAttribute("wantQueue", intToStr(wantQueue), + mapTagReplacements); + // int8 fromFactionIndex; + networkCommandNode->addAttribute( + "fromFactionIndex", intToStr(fromFactionIndex), mapTagReplacements); + // uint16 unitFactionUnitCount; + networkCommandNode->addAttribute("unitFactionUnitCount", + intToStr(unitFactionUnitCount), + mapTagReplacements); + // int8 unitFactionIndex; + networkCommandNode->addAttribute( + "unitFactionIndex", intToStr(unitFactionIndex), mapTagReplacements); + // int8 commandStateType; + networkCommandNode->addAttribute( + "commandStateType", intToStr(commandStateType), mapTagReplacements); + // int32 commandStateValue; + networkCommandNode->addAttribute( + "commandStateValue", intToStr(commandStateValue), mapTagReplacements); + // int32 unitCommandGroupId; + networkCommandNode->addAttribute( + "unitCommandGroupId", intToStr(unitCommandGroupId), mapTagReplacements); + + return networkCommandNode; } void NetworkCommand::loadGame(const XmlNode *rootNode) { - const XmlNode *networkCommandNode = rootNode; - -// int16 networkCommandType; - networkCommandType = networkCommandNode->getAttribute("networkCommandType")->getIntValue(); -// int32 unitId; - unitId = networkCommandNode->getAttribute("unitId")->getIntValue(); -// int16 unitTypeId; - unitTypeId = networkCommandNode->getAttribute("unitTypeId")->getIntValue(); -// int16 commandTypeId; - commandTypeId = networkCommandNode->getAttribute("commandTypeId")->getIntValue(); -// int16 positionX; - positionX = networkCommandNode->getAttribute("positionX")->getIntValue(); -// int16 positionY; - positionY = networkCommandNode->getAttribute("positionY")->getIntValue(); -// int32 targetId; - targetId = networkCommandNode->getAttribute("targetId")->getIntValue(); -// int8 wantQueue; - wantQueue = networkCommandNode->getAttribute("wantQueue")->getIntValue(); -// int8 fromFactionIndex; - fromFactionIndex = networkCommandNode->getAttribute("fromFactionIndex")->getIntValue(); -// uint16 unitFactionUnitCount; - unitFactionUnitCount = networkCommandNode->getAttribute("unitFactionUnitCount")->getIntValue(); -// int8 unitFactionIndex; - unitFactionIndex = networkCommandNode->getAttribute("unitFactionIndex")->getIntValue(); -// int8 commandStateType; - commandStateType = networkCommandNode->getAttribute("commandStateType")->getIntValue(); -// int32 commandStateValue; - commandStateValue = networkCommandNode->getAttribute("commandStateValue")->getIntValue(); -// int32 unitCommandGroupId; - unitCommandGroupId = networkCommandNode->getAttribute("unitCommandGroupId")->getIntValue(); + const XmlNode *networkCommandNode = rootNode; + + // int16 networkCommandType; + networkCommandType = + networkCommandNode->getAttribute("networkCommandType")->getIntValue(); + // int32 unitId; + unitId = networkCommandNode->getAttribute("unitId")->getIntValue(); + // int16 unitTypeId; + unitTypeId = networkCommandNode->getAttribute("unitTypeId")->getIntValue(); + // int16 commandTypeId; + commandTypeId = + networkCommandNode->getAttribute("commandTypeId")->getIntValue(); + // int16 positionX; + positionX = networkCommandNode->getAttribute("positionX")->getIntValue(); + // int16 positionY; + positionY = networkCommandNode->getAttribute("positionY")->getIntValue(); + // int32 targetId; + targetId = networkCommandNode->getAttribute("targetId")->getIntValue(); + // int8 wantQueue; + wantQueue = networkCommandNode->getAttribute("wantQueue")->getIntValue(); + // int8 fromFactionIndex; + fromFactionIndex = + networkCommandNode->getAttribute("fromFactionIndex")->getIntValue(); + // uint16 unitFactionUnitCount; + unitFactionUnitCount = + networkCommandNode->getAttribute("unitFactionUnitCount")->getIntValue(); + // int8 unitFactionIndex; + unitFactionIndex = + networkCommandNode->getAttribute("unitFactionIndex")->getIntValue(); + // int8 commandStateType; + commandStateType = + networkCommandNode->getAttribute("commandStateType")->getIntValue(); + // int32 commandStateValue; + commandStateValue = + networkCommandNode->getAttribute("commandStateValue")->getIntValue(); + // int32 unitCommandGroupId; + unitCommandGroupId = + networkCommandNode->getAttribute("unitCommandGroupId")->getIntValue(); } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/network/network_types.h b/source/glest_game/network/network_types.h index 224935821..95bcdc434 100644 --- a/source/glest_game/network/network_types.h +++ b/source/glest_game/network/network_types.h @@ -13,26 +13,27 @@ #define _GLEST_GAME_NETWORKTYPES_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include -#include "data_types.h" -#include "vec.h" #include "command.h" +#include "data_types.h" #include "leak_dumper.h" +#include "vec.h" +#include -using std::string; -using std::min; -using Shared::Platform::int8; -using Shared::Platform::uint8; +using Shared::Graphics::Vec2i; using Shared::Platform::int16; -using Shared::Platform::uint16; using Shared::Platform::int32; -using Shared::Graphics::Vec2i; +using Shared::Platform::int8; +using Shared::Platform::uint16; +using Shared::Platform::uint8; +using std::min; +using std::string; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { class World; // ===================================================== @@ -40,29 +41,26 @@ class World; // ===================================================== #pragma pack(push, 1) -template -class NetworkString{ +template class NetworkString { private: - char buffer[S]; + char buffer[S]; public: - NetworkString() { - memset(buffer, 0, S); - } - NetworkString & operator=(const string& str) { - // ensure we don't have a buffer overflow - int maxBufferSize = sizeof(buffer) / sizeof(buffer[0]); - strncpy(buffer, str.c_str(), min(S-1,maxBufferSize-1)); - - return *this; - } - void nullTerminate() { - int maxBufferSize = sizeof(buffer) / sizeof(buffer[0]); - buffer[maxBufferSize-1] = '\0'; - } - - char *getBuffer() { return &buffer[0]; } - string getString() const { return (buffer[0] != '\0' ? buffer : ""); } + NetworkString() { memset(buffer, 0, S); } + NetworkString &operator=(const string &str) { + // ensure we don't have a buffer overflow + int maxBufferSize = sizeof(buffer) / sizeof(buffer[0]); + strncpy(buffer, str.c_str(), min(S - 1, maxBufferSize - 1)); + + return *this; + } + void nullTerminate() { + int maxBufferSize = sizeof(buffer) / sizeof(buffer[0]); + buffer[maxBufferSize - 1] = '\0'; + } + + char *getBuffer() { return &buffer[0]; } + string getString() const { return (buffer[0] != '\0' ? buffer : ""); } }; #pragma pack(pop) @@ -71,98 +69,96 @@ class NetworkString{ // ===================================================== enum NetworkCommandType { - nctGiveCommand, - nctCancelCommand, - nctSetMeetingPoint, - nctSwitchTeam, - nctSwitchTeamVote, - nctPauseResume, - nctPlayerStatusChange, - nctDisconnectNetworkPlayer - //nctNetworkCommand + nctGiveCommand, + nctCancelCommand, + nctSetMeetingPoint, + nctSwitchTeam, + nctSwitchTeamVote, + nctPauseResume, + nctPlayerStatusChange, + nctDisconnectNetworkPlayer + // nctNetworkCommand }; -//enum NetworkCommandSubType { +// enum NetworkCommandSubType { // ncstRotateUnit -//}; +// }; #pragma pack(push, 1) class NetworkCommand { public: - NetworkCommand() { - networkCommandType=0; - unitId=0; - unitTypeId=0; - commandTypeId=0; - positionX=0; - positionY=0; - targetId=0; - wantQueue=0; - fromFactionIndex=0; - unitFactionUnitCount=0; - unitFactionIndex=0; - commandStateType=0; - commandStateValue=0; - unitCommandGroupId=0; - } - - NetworkCommand( - World *world, - int networkCommandType, - int unitId, - int commandTypeId= -1, - const Vec2i &pos= Vec2i(0), - int unitTypeId= -1, - int targetId= -1, - int facing= -1, - bool wantQueue = false, - CommandStateType commandStateType = cst_None, - int commandTypeStateValue = -1, - int unitCommandGroupId = -1); - - int16 networkCommandType; - int32 unitId; - int16 unitTypeId; - int16 commandTypeId; - int16 positionX; - int16 positionY; - int32 targetId; - int8 wantQueue; - int8 fromFactionIndex; - uint16 unitFactionUnitCount; - int8 unitFactionIndex; - int8 commandStateType; - int32 commandStateValue; - int32 unitCommandGroupId; - - NetworkCommandType getNetworkCommandType() const {return static_cast(networkCommandType);} - int getUnitId() const {return unitId;} - int getCommandTypeId() const {return commandTypeId;} - Vec2i getPosition() const {return Vec2i(positionX, positionY);} - int getUnitTypeId() const {return unitTypeId;} - int getTargetId() const {return targetId;} - int getWantQueue() const {return wantQueue;} - int getFromFactionIndex() const {return fromFactionIndex;} - int getUnitFactionUnitCount() const {return unitFactionUnitCount;} - int getUnitFactionIndex() const {return unitFactionIndex;} - - CommandStateType getCommandStateType() const {return static_cast(commandStateType);} - int getCommandStateValue() const {return commandStateValue;} - - int getUnitCommandGroupId() const { return unitCommandGroupId; } - - void preprocessNetworkCommand(World *world); - string toString() const; - - void toEndian(); - void fromEndian(); - - XmlNode * saveGame(XmlNode *rootNode); - void loadGame(const XmlNode *rootNode); + NetworkCommand() { + networkCommandType = 0; + unitId = 0; + unitTypeId = 0; + commandTypeId = 0; + positionX = 0; + positionY = 0; + targetId = 0; + wantQueue = 0; + fromFactionIndex = 0; + unitFactionUnitCount = 0; + unitFactionIndex = 0; + commandStateType = 0; + commandStateValue = 0; + unitCommandGroupId = 0; + } + + NetworkCommand(World *world, int networkCommandType, int unitId, + int commandTypeId = -1, const Vec2i &pos = Vec2i(0), + int unitTypeId = -1, int targetId = -1, int facing = -1, + bool wantQueue = false, + CommandStateType commandStateType = cst_None, + int commandTypeStateValue = -1, int unitCommandGroupId = -1); + + int16 networkCommandType; + int32 unitId; + int16 unitTypeId; + int16 commandTypeId; + int16 positionX; + int16 positionY; + int32 targetId; + int8 wantQueue; + int8 fromFactionIndex; + uint16 unitFactionUnitCount; + int8 unitFactionIndex; + int8 commandStateType; + int32 commandStateValue; + int32 unitCommandGroupId; + + NetworkCommandType getNetworkCommandType() const { + return static_cast(networkCommandType); + } + int getUnitId() const { return unitId; } + int getCommandTypeId() const { return commandTypeId; } + Vec2i getPosition() const { return Vec2i(positionX, positionY); } + int getUnitTypeId() const { return unitTypeId; } + int getTargetId() const { return targetId; } + int getWantQueue() const { return wantQueue; } + int getFromFactionIndex() const { return fromFactionIndex; } + int getUnitFactionUnitCount() const { return unitFactionUnitCount; } + int getUnitFactionIndex() const { return unitFactionIndex; } + + CommandStateType getCommandStateType() const { + return static_cast(commandStateType); + } + int getCommandStateValue() const { return commandStateValue; } + + int getUnitCommandGroupId() const { return unitCommandGroupId; } + + void preprocessNetworkCommand(World *world); + string toString() const; + + void toEndian(); + void fromEndian(); + + XmlNode *saveGame(XmlNode *rootNode); + void loadGame(const XmlNode *rootNode); }; #pragma pack(pop) -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/network/server_interface.cpp b/source/glest_game/network/server_interface.cpp index d6952a401..1f3feaeac 100644 --- a/source/glest_game/network/server_interface.cpp +++ b/source/glest_game/network/server_interface.cpp @@ -13,22 +13,22 @@ #include -#include "window.h" #include "logger.h" +#include "window.h" -#include "platform_util.h" -#include "conversion.h" #include "config.h" -#include "lang.h" -#include "util.h" +#include "conversion.h" #include "game_util.h" -#include "miniftpserver.h" +#include "lang.h" #include "map_preview.h" +#include "miniftpserver.h" +#include "platform_util.h" #include "stats.h" -#include -#include +#include "util.h" #include #include +#include +#include #include "leak_dumper.h" @@ -37,3239 +37,4332 @@ using namespace Shared::Platform; using namespace Shared::Util; using namespace Shared::Map; -namespace Glest { namespace Game { +namespace Glest { +namespace Game { -double maxFrameCountLagAllowed = 30; -double maxClientLagTimeAllowed = 25; -double maxFrameCountLagAllowedEver = 30; -double maxClientLagTimeAllowedEver = 25; +double maxFrameCountLagAllowed = 30; +double maxClientLagTimeAllowed = 25; +double maxFrameCountLagAllowedEver = 30; +double maxClientLagTimeAllowedEver = 25; -double warnFrameCountLagPercent = 0.50; -double LAG_CHECK_GRACE_PERIOD = 15; -double LAG_CHECK_INTERVAL_PERIOD = 4; +double warnFrameCountLagPercent = 0.50; +double LAG_CHECK_GRACE_PERIOD = 15; +double LAG_CHECK_INTERVAL_PERIOD = 4; -const int MAX_CLIENT_WAIT_SECONDS_FOR_PAUSE_MILLISECONDS = 15000; -const int MAX_CLIENT_PAUSE_FOR_LAG_COUNT = 3; -const int MAX_SLOT_THREAD_WAIT_TIME_MILLISECONDS = 1500; -const int MASTERSERVER_HEARTBEAT_GAME_STATUS_SECONDS = 30; +const int MAX_CLIENT_WAIT_SECONDS_FOR_PAUSE_MILLISECONDS = 15000; +const int MAX_CLIENT_PAUSE_FOR_LAG_COUNT = 3; +const int MAX_SLOT_THREAD_WAIT_TIME_MILLISECONDS = 1500; +const int MASTERSERVER_HEARTBEAT_GAME_STATUS_SECONDS = 30; const int MAX_EMPTY_NETWORK_COMMAND_LIST_BROADCAST_INTERVAL_MILLISECONDS = 4000; -ServerInterface::ServerInterface(bool publishEnabled, ClientLagCallbackInterface *clientLagCallbackInterface) : GameNetworkInterface() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - this->clientLagCallbackInterface = clientLagCallbackInterface; - this->clientsAutoPausedDueToLag = false; - - allowInGameConnections = false; - gameLaunched = false; - - serverSynchAccessor = new Mutex(CODE_AT_LINE); - switchSetupRequestsSynchAccessor = new Mutex(CODE_AT_LINE); - - for(int index = 0; index < GameConstants::maxPlayers; ++index) { - slotAccessorMutexes[index] = new Mutex(CODE_AT_LINE); - } - masterServerThreadAccessor = new Mutex(CODE_AT_LINE); - textMessageQueueThreadAccessor = new Mutex(CODE_AT_LINE); - broadcastMessageQueueThreadAccessor = new Mutex(CODE_AT_LINE); - inBroadcastMessageThreadAccessor = new Mutex(CODE_AT_LINE); - - serverSocketAdmin = NULL; - nextEventId = 1; - gameHasBeenInitiated = false; - exitServer = false; - gameSettingsUpdateCount = 0; - currentFrameCount = 0; - gameStartTime = 0; - resumeGameStartTime = 0; - publishToMasterserverThread = NULL; - lastMasterserverHeartbeatTime = 0; - needToRepublishToMasterserver = false; - ftpServer = NULL; - inBroadcastMessage = false; - lastGlobalLagCheckTime = 0; - masterserverAdminRequestLaunch = false; - lastListenerSlotCheckTime = 0; - - // This is an admin port listening only on the localhost intended to - // give current connection status info +ServerInterface::ServerInterface( + bool publishEnabled, ClientLagCallbackInterface *clientLagCallbackInterface) + : GameNetworkInterface() { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + this->clientLagCallbackInterface = clientLagCallbackInterface; + this->clientsAutoPausedDueToLag = false; + + allowInGameConnections = false; + gameLaunched = false; + + serverSynchAccessor = new Mutex(CODE_AT_LINE); + switchSetupRequestsSynchAccessor = new Mutex(CODE_AT_LINE); + + for (int index = 0; index < GameConstants::maxPlayers; ++index) { + slotAccessorMutexes[index] = new Mutex(CODE_AT_LINE); + } + masterServerThreadAccessor = new Mutex(CODE_AT_LINE); + textMessageQueueThreadAccessor = new Mutex(CODE_AT_LINE); + broadcastMessageQueueThreadAccessor = new Mutex(CODE_AT_LINE); + inBroadcastMessageThreadAccessor = new Mutex(CODE_AT_LINE); + + serverSocketAdmin = NULL; + nextEventId = 1; + gameHasBeenInitiated = false; + exitServer = false; + gameSettingsUpdateCount = 0; + currentFrameCount = 0; + gameStartTime = 0; + resumeGameStartTime = 0; + publishToMasterserverThread = NULL; + lastMasterserverHeartbeatTime = 0; + needToRepublishToMasterserver = false; + ftpServer = NULL; + inBroadcastMessage = false; + lastGlobalLagCheckTime = 0; + masterserverAdminRequestLaunch = false; + lastListenerSlotCheckTime = 0; + + // This is an admin port listening only on the localhost intended to + // give current connection status info #ifndef __APPLE__ - try { - serverSocketAdmin = new ServerSocket(true); - serverSocketAdmin->setBlock(false); - serverSocketAdmin->setBindPort(Config::getInstance().getInt("ServerAdminPort", intToStr(GameConstants::serverAdminPort).c_str())); - serverSocketAdmin->setBindSpecificAddress(Config::getInstance().getString("ServerAdminBindAddress", "127.0.0.1")); - serverSocketAdmin->listen(5); - } - catch(const std::exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] Warning Server admin port bind/listen error:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); - } + try { + serverSocketAdmin = new ServerSocket(true); + serverSocketAdmin->setBlock(false); + serverSocketAdmin->setBindPort(Config::getInstance().getInt( + "ServerAdminPort", intToStr(GameConstants::serverAdminPort).c_str())); + serverSocketAdmin->setBindSpecificAddress( + Config::getInstance().getString("ServerAdminBindAddress", "127.0.0.1")); + serverSocketAdmin->listen(5); + } catch (const std::exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] Warning Server admin port bind/listen " + "error:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + } #endif - maxFrameCountLagAllowed = Config::getInstance().getInt("MaxFrameCountLagAllowed", intToStr(maxFrameCountLagAllowed).c_str()); - maxFrameCountLagAllowedEver = Config::getInstance().getInt("MaxFrameCountLagAllowedEver", intToStr(maxFrameCountLagAllowedEver).c_str()); - maxClientLagTimeAllowedEver = Config::getInstance().getInt("MaxClientLagTimeAllowedEver", intToStr(maxClientLagTimeAllowedEver).c_str()); - maxClientLagTimeAllowed = Config::getInstance().getInt("MaxClientLagTimeAllowed", intToStr(maxClientLagTimeAllowed).c_str()); - warnFrameCountLagPercent = Config::getInstance().getFloat("WarnFrameCountLagPercent", doubleToStr(warnFrameCountLagPercent).c_str()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] maxFrameCountLagAllowed = %f, maxFrameCountLagAllowedEver = %f, maxClientLagTimeAllowed = %f, maxClientLagTimeAllowedEver = %f\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,maxFrameCountLagAllowed,maxFrameCountLagAllowedEver,maxClientLagTimeAllowed,maxClientLagTimeAllowedEver); - - for(int index = 0; index < GameConstants::maxPlayers; ++index) { - slots[index] = NULL; - switchSetupRequests[index] = NULL; - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - serverSocket.setBlock(false); - serverSocket.setBindPort(Config::getInstance().getInt("PortServer", intToStr(GameConstants::serverPort).c_str())); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - gameStatsThreadAccessor = new Mutex(CODE_AT_LINE); - gameStats = NULL; - - Config &config = Config::getInstance(); - string scenarioDir = ""; - vector pathList = config.getPathListForType(ptMaps,scenarioDir); - vector invalidMapList; - vector allMaps = MapPreview::findAllValidMaps(pathList,scenarioDir,false,true,&invalidMapList); - if (allMaps.empty()) { - //throw megaglest_runtime_error("No maps were found!"); - printf("No maps were found (srv)!\n"); - } - std::sort(allMaps.begin(),allMaps.end(),compareNonCaseSensitive); - vector results; - copy(allMaps.begin(), allMaps.end(), std::back_inserter(results)); - mapFiles = results; - - //player Sorted maps - //////////////////// - for(unsigned int i = 0; i < GameConstants::maxPlayers+1; ++i) { - playerSortedMaps[i].clear(); - } - - // at index=0 fill in the whole list - copy(mapFiles.begin(), mapFiles.end(), std::back_inserter(playerSortedMaps[0])); - - MapInfo mapInfo; - // fill playerSortedMaps according to map player count - for(int i= 0; i < (int)mapFiles.size(); i++){// fetch info and put map in right list - //printf("mapFiles.at(i) %s allMaps.at[i] %s\n",mapFiles[i].c_str(),allMaps.at(i).c_str()); - MapPreview::loadMapInfo(Config::getMapPath(mapFiles.at(i)), &mapInfo, "MaxPlayers","Size",true) ; - playerSortedMaps[mapInfo.players].push_back(mapFiles.at(i)); - } - /////////////////// - - results.clear(); - findDirs(config.getPathListForType(ptTilesets), results); - if (results.empty()) { - //throw megaglest_runtime_error("No tile-sets were found!"); - printf("No tile-sets were found (srv)!"); - } - tilesetFiles = results; - - results.clear(); - findDirs(config.getPathListForType(ptTechs), results); - if(results.empty()) { - //throw megaglest_runtime_error("No tech-trees were found!"); - printf("No tech-trees were found (srv)!\n"); - } - techTreeFiles = results; - - if(Config::getInstance().getBool("EnableFTPServer","true") == true) { - std::pair mapsPath; - vector pathList = Config::getInstance().getPathListForType(ptMaps); - if(pathList.empty() == false) { - mapsPath.first = pathList[0]; - if(pathList.size() > 1) { - mapsPath.second = pathList[1]; - } - } - - std::pair tilesetsPath; - vector tilesetsList = Config::getInstance().getPathListForType(ptTilesets); - if(tilesetsList.empty() == false) { - tilesetsPath.first = tilesetsList[0]; - if(tilesetsList.size() > 1) { - tilesetsPath.second = tilesetsList[1]; - } - } - - std::pair techtreesPath; - vector techtreesList = Config::getInstance().getPathListForType(ptTechs); - if(techtreesList.empty() == false) { - techtreesPath.first = techtreesList[0]; - if(techtreesList.size() > 1) { - techtreesPath.second = techtreesList[1]; - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - int portNumber = Config::getInstance().getInt("FTPServerPort",intToStr(ServerSocket::getFTPServerPort()).c_str()); - ServerSocket::setFTPServerPort(portNumber); - //printf("In [%s::%s] portNumber = %d ServerSocket::getFTPServerPort() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,portNumber,ServerSocket::getFTPServerPort()); - - bool allowInternetTilesetFileTransfers = Config::getInstance().getBool("EnableFTPServerInternetTilesetXfer","true"); - bool allowInternetTechtreeFileTransfers = Config::getInstance().getBool("EnableFTPServerInternetTechtreeXfer","true"); - - // Get path to temp files - string tempFilePath = "temp/"; - if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - tempFilePath = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + tempFilePath; - } - else { - string userData = config.getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); - } - tempFilePath = userData + tempFilePath; - } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Temp files path [%s]\n",tempFilePath.c_str()); - - ftpServer = new FTPServerThread(mapsPath,tilesetsPath,techtreesPath, - publishEnabled,allowInternetTilesetFileTransfers, - allowInternetTechtreeFileTransfers,portNumber,GameConstants::maxPlayers, - this,tempFilePath); - ftpServer->start(); - } - - if(publishToMasterserverThread == NULL) { - if(needToRepublishToMasterserver == true || GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); - publishToMasterserverThread = new SimpleTaskThread(this,0,125); - publishToMasterserverThread->setUniqueID(mutexOwnerId); - publishToMasterserverThread->start(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] needToRepublishToMasterserver = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,needToRepublishToMasterserver); - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + maxFrameCountLagAllowed = Config::getInstance().getInt( + "MaxFrameCountLagAllowed", intToStr(maxFrameCountLagAllowed).c_str()); + maxFrameCountLagAllowedEver = Config::getInstance().getInt( + "MaxFrameCountLagAllowedEver", + intToStr(maxFrameCountLagAllowedEver).c_str()); + maxClientLagTimeAllowedEver = Config::getInstance().getInt( + "MaxClientLagTimeAllowedEver", + intToStr(maxClientLagTimeAllowedEver).c_str()); + maxClientLagTimeAllowed = Config::getInstance().getInt( + "MaxClientLagTimeAllowed", intToStr(maxClientLagTimeAllowed).c_str()); + warnFrameCountLagPercent = Config::getInstance().getFloat( + "WarnFrameCountLagPercent", + doubleToStr(warnFrameCountLagPercent).c_str()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] maxFrameCountLagAllowed = %f, " + "maxFrameCountLagAllowedEver = %f, maxClientLagTimeAllowed = %f, " + "maxClientLagTimeAllowedEver = %f\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + maxFrameCountLagAllowed, maxFrameCountLagAllowedEver, + maxClientLagTimeAllowed, maxClientLagTimeAllowedEver); + + for (int index = 0; index < GameConstants::maxPlayers; ++index) { + slots[index] = NULL; + switchSetupRequests[index] = NULL; + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + serverSocket.setBlock(false); + serverSocket.setBindPort(Config::getInstance().getInt( + "PortServer", intToStr(GameConstants::serverPort).c_str())); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + gameStatsThreadAccessor = new Mutex(CODE_AT_LINE); + gameStats = NULL; + + Config &config = Config::getInstance(); + string scenarioDir = ""; + vector pathList = config.getPathListForType(ptMaps, scenarioDir); + vector invalidMapList; + vector allMaps = MapPreview::findAllValidMaps( + pathList, scenarioDir, false, true, &invalidMapList); + if (allMaps.empty()) { + // throw megaglest_runtime_error("No maps were found!"); + printf("No maps were found (srv)!\n"); + } + std::sort(allMaps.begin(), allMaps.end(), compareNonCaseSensitive); + vector results; + copy(allMaps.begin(), allMaps.end(), std::back_inserter(results)); + mapFiles = results; + + // player Sorted maps + //////////////////// + for (unsigned int i = 0; i < GameConstants::maxPlayers + 1; ++i) { + playerSortedMaps[i].clear(); + } + + // at index=0 fill in the whole list + copy(mapFiles.begin(), mapFiles.end(), + std::back_inserter(playerSortedMaps[0])); + + MapInfo mapInfo; + // fill playerSortedMaps according to map player count + for (int i = 0; i < (int)mapFiles.size(); + i++) { // fetch info and put map in right list + // printf("mapFiles.at(i) %s allMaps.at[i] + // %s\n",mapFiles[i].c_str(),allMaps.at(i).c_str()); + MapPreview::loadMapInfo(Config::getMapPath(mapFiles.at(i)), &mapInfo, + "MaxPlayers", "Size", true); + playerSortedMaps[mapInfo.players].push_back(mapFiles.at(i)); + } + /////////////////// + + results.clear(); + findDirs(config.getPathListForType(ptTilesets), results); + if (results.empty()) { + // throw megaglest_runtime_error("No tile-sets were found!"); + printf("No tile-sets were found (srv)!"); + } + tilesetFiles = results; + + results.clear(); + findDirs(config.getPathListForType(ptTechs), results); + if (results.empty()) { + // throw megaglest_runtime_error("No tech-trees were found!"); + printf("No tech-trees were found (srv)!\n"); + } + techTreeFiles = results; + + if (Config::getInstance().getBool("EnableFTPServer", "true") == true) { + std::pair mapsPath; + vector pathList = Config::getInstance().getPathListForType(ptMaps); + if (pathList.empty() == false) { + mapsPath.first = pathList[0]; + if (pathList.size() > 1) { + mapsPath.second = pathList[1]; + } + } + + std::pair tilesetsPath; + vector tilesetsList = + Config::getInstance().getPathListForType(ptTilesets); + if (tilesetsList.empty() == false) { + tilesetsPath.first = tilesetsList[0]; + if (tilesetsList.size() > 1) { + tilesetsPath.second = tilesetsList[1]; + } + } + + std::pair techtreesPath; + vector techtreesList = + Config::getInstance().getPathListForType(ptTechs); + if (techtreesList.empty() == false) { + techtreesPath.first = techtreesList[0]; + if (techtreesList.size() > 1) { + techtreesPath.second = techtreesList[1]; + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + int portNumber = Config::getInstance().getInt( + "FTPServerPort", intToStr(ServerSocket::getFTPServerPort()).c_str()); + ServerSocket::setFTPServerPort(portNumber); + // printf("In [%s::%s] portNumber = %d ServerSocket::getFTPServerPort() = + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,portNumber,ServerSocket::getFTPServerPort()); + + bool allowInternetTilesetFileTransfers = Config::getInstance().getBool( + "EnableFTPServerInternetTilesetXfer", "true"); + bool allowInternetTechtreeFileTransfers = Config::getInstance().getBool( + "EnableFTPServerInternetTechtreeXfer", "true"); + + // Get path to temp files + string tempFilePath = "temp/"; + if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { + tempFilePath = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + + tempFilePath; + } else { + string userData = config.getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + tempFilePath = userData + tempFilePath; + } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Temp files path [%s]\n", tempFilePath.c_str()); + + ftpServer = new FTPServerThread( + mapsPath, tilesetsPath, techtreesPath, publishEnabled, + allowInternetTilesetFileTransfers, allowInternetTechtreeFileTransfers, + portNumber, GameConstants::maxPlayers, this, tempFilePath); + ftpServer->start(); + } + + if (publishToMasterserverThread == NULL) { + if (needToRepublishToMasterserver == true || + GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + static string mutexOwnerId = + string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + + intToStr(__LINE__); + publishToMasterserverThread = new SimpleTaskThread(this, 0, 125); + publishToMasterserverThread->setUniqueID(mutexOwnerId); + publishToMasterserverThread->start(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] needToRepublishToMasterserver = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, needToRepublishToMasterserver); + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); } void ServerInterface::setPublishEnabled(bool value) { - if(ftpServer != NULL) { - ftpServer->setInternetEnabled(value); - } + if (ftpServer != NULL) { + ftpServer->setInternetEnabled(value); + } } void ServerInterface::shutdownMasterserverPublishThread() { - MutexSafeWrapper safeMutex(masterServerThreadAccessor,CODE_AT_LINE); - - if(publishToMasterserverThread != NULL) { - time_t elapsed = time(NULL); - publishToMasterserverThread->signalQuit(); - for(;publishToMasterserverThread->canShutdown(false) == false && - difftime((long int)time(NULL),elapsed) <= 15;) { - //sleep(150); - } - if(publishToMasterserverThread->canShutdown(true)) { - delete publishToMasterserverThread; - publishToMasterserverThread = NULL; - } - } + MutexSafeWrapper safeMutex(masterServerThreadAccessor, CODE_AT_LINE); + + if (publishToMasterserverThread != NULL) { + time_t elapsed = time(NULL); + publishToMasterserverThread->signalQuit(); + for (; publishToMasterserverThread->canShutdown(false) == false && + difftime((long int)time(NULL), elapsed) <= 15;) { + // sleep(150); + } + if (publishToMasterserverThread->canShutdown(true)) { + delete publishToMasterserverThread; + publishToMasterserverThread = NULL; + } + } } ServerInterface::~ServerInterface() { - //printf("===> Destructor for ServerInterface\n"); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - masterController.clearSlaves(true); - exitServer = true; - for(int index = 0; index < GameConstants::maxPlayers; ++index) { - if(slots[index] != NULL) { - MutexSafeWrapper safeMutex(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); - delete slots[index]; - slots[index] = NULL; - } - - if(switchSetupRequests[index] != NULL) { - delete switchSetupRequests[index]; - switchSetupRequests[index] = NULL; - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - close(); - shutdownFTPServer(); - shutdownMasterserverPublishThread(); - - lastMasterserverHeartbeatTime = 0; - if(needToRepublishToMasterserver == true) { - simpleTask(NULL,NULL); - } - - for(int index = 0; index < GameConstants::maxPlayers; ++index) { - delete slotAccessorMutexes[index]; - slotAccessorMutexes[index] = NULL; - } - - delete textMessageQueueThreadAccessor; - textMessageQueueThreadAccessor = NULL; - - delete broadcastMessageQueueThreadAccessor; - broadcastMessageQueueThreadAccessor = NULL; - - delete inBroadcastMessageThreadAccessor; - inBroadcastMessageThreadAccessor = NULL; - - delete serverSynchAccessor; - serverSynchAccessor = NULL; - - delete masterServerThreadAccessor; - masterServerThreadAccessor = NULL; - - delete serverSocketAdmin; - serverSocketAdmin = NULL; - - for(int index = 0; index < (int)broadcastMessageQueue.size(); ++index) { - pair &item = broadcastMessageQueue[index]; - if(item.first != NULL) { - delete item.first; - } - item.first = NULL; - } - broadcastMessageQueue.clear(); - - delete switchSetupRequestsSynchAccessor; - switchSetupRequestsSynchAccessor = NULL; - - delete gameStatsThreadAccessor; - gameStatsThreadAccessor = NULL; - - delete gameStats; - gameStats = NULL; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // printf("===> Destructor for ServerInterface\n"); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + masterController.clearSlaves(true); + exitServer = true; + for (int index = 0; index < GameConstants::maxPlayers; ++index) { + if (slots[index] != NULL) { + MutexSafeWrapper safeMutex(slotAccessorMutexes[index], + CODE_AT_LINE_X(index)); + delete slots[index]; + slots[index] = NULL; + } + + if (switchSetupRequests[index] != NULL) { + delete switchSetupRequests[index]; + switchSetupRequests[index] = NULL; + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + close(); + shutdownFTPServer(); + shutdownMasterserverPublishThread(); + + lastMasterserverHeartbeatTime = 0; + if (needToRepublishToMasterserver == true) { + simpleTask(NULL, NULL); + } + + for (int index = 0; index < GameConstants::maxPlayers; ++index) { + delete slotAccessorMutexes[index]; + slotAccessorMutexes[index] = NULL; + } + + delete textMessageQueueThreadAccessor; + textMessageQueueThreadAccessor = NULL; + + delete broadcastMessageQueueThreadAccessor; + broadcastMessageQueueThreadAccessor = NULL; + + delete inBroadcastMessageThreadAccessor; + inBroadcastMessageThreadAccessor = NULL; + + delete serverSynchAccessor; + serverSynchAccessor = NULL; + + delete masterServerThreadAccessor; + masterServerThreadAccessor = NULL; + + delete serverSocketAdmin; + serverSocketAdmin = NULL; + + for (int index = 0; index < (int)broadcastMessageQueue.size(); ++index) { + pair &item = broadcastMessageQueue[index]; + if (item.first != NULL) { + delete item.first; + } + item.first = NULL; + } + broadcastMessageQueue.clear(); + + delete switchSetupRequestsSynchAccessor; + switchSetupRequestsSynchAccessor = NULL; + + delete gameStatsThreadAccessor; + gameStatsThreadAccessor = NULL; + + delete gameStats; + gameStats = NULL; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); } -SwitchSetupRequest ** ServerInterface::getSwitchSetupRequests() { - MutexSafeWrapper safeMutex(switchSetupRequestsSynchAccessor,CODE_AT_LINE); - return &switchSetupRequests[0]; +SwitchSetupRequest **ServerInterface::getSwitchSetupRequests() { + MutexSafeWrapper safeMutex(switchSetupRequestsSynchAccessor, CODE_AT_LINE); + return &switchSetupRequests[0]; } -SwitchSetupRequest * ServerInterface::getSwitchSetupRequests(int index) { - MutexSafeWrapper safeMutex(switchSetupRequestsSynchAccessor,CODE_AT_LINE); - return switchSetupRequests[index]; +SwitchSetupRequest *ServerInterface::getSwitchSetupRequests(int index) { + MutexSafeWrapper safeMutex(switchSetupRequestsSynchAccessor, CODE_AT_LINE); + return switchSetupRequests[index]; } -void ServerInterface::setSwitchSetupRequests(int index,SwitchSetupRequest *ptr) { - MutexSafeWrapper safeMutex(switchSetupRequestsSynchAccessor,CODE_AT_LINE); - switchSetupRequests[index] = ptr; +void ServerInterface::setSwitchSetupRequests(int index, + SwitchSetupRequest *ptr) { + MutexSafeWrapper safeMutex(switchSetupRequestsSynchAccessor, CODE_AT_LINE); + switchSetupRequests[index] = ptr; } int ServerInterface::isValidClientType(uint32 clientIp) { - int result = 0; - for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { - MutexSafeWrapper safeMutex(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); - if(slots[index] != NULL) { - Socket *socket = slots[index]->getSocket(); - if(socket != NULL) { - uint32 slotIp = socket->getConnectedIPAddress(socket->getIpAddress()); - if(slotIp == clientIp) { - result = 1; - break; - } - } - } - } - return result; -} - -int ServerInterface::isClientAllowedToGetFile(uint32 clientIp, const char *username, const char *filename) { - int result = 1; - - if( username != NULL && - strlen(username) > 0 && - filename != NULL && - strlen(filename) > 0) { - string user = username; - string file = filename; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d username [%s] file [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,username,filename); - - if(StartsWith(user,"tilesets") == true && EndsWith(file,"7z") == false) { - if(Config::getInstance().getBool("DisableFTPServerXferUncompressedTilesets","false") == true) { - result = 0; - } - else { - char szIP[100] = ""; - Ip::Inet_NtoA(clientIp,szIP); - string clientIP = szIP; - std::vector serverList = Socket::getLocalIPAddressList(); - - result = 0; - for(unsigned int index = 0; index < serverList.size(); ++index) { - string serverIP = serverList[index]; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d clientIP [%s] serverIP [%s] %d / %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,clientIP.c_str(),serverIP.c_str(),index,serverList.size()); - - vector clientTokens; - Tokenize(clientIP,clientTokens,"."); - - vector serverTokens; - Tokenize(serverIP,serverTokens,"."); - - if(clientTokens.size() == 4 && serverTokens.size() == 4) { - if( clientTokens[0] == serverTokens[0] || - clientTokens[1] == serverTokens[1] || - clientTokens[2] == serverTokens[2]) { - result = 1; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d clientIP [%s] IS NOT BLOCKED\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,clientIP.c_str()); - - break; - } - } - } - } - } - } - return result; -} - -void ServerInterface::addClientToServerIPAddress(uint32 clientIp, uint32 ServerIp) { - FTPServerThread::addClientToServerIPAddress(clientIp, ServerIp); + int result = 0; + for (int index = 0; exitServer == false && index < GameConstants::maxPlayers; + ++index) { + MutexSafeWrapper safeMutex(slotAccessorMutexes[index], + CODE_AT_LINE_X(index)); + if (slots[index] != NULL) { + Socket *socket = slots[index]->getSocket(); + if (socket != NULL) { + uint32 slotIp = socket->getConnectedIPAddress(socket->getIpAddress()); + if (slotIp == clientIp) { + result = 1; + break; + } + } + } + } + return result; } -void ServerInterface::addSlot(int playerIndex) { - //printf("Adding slot for playerIndex = %d, serverSocket.isPortBound() = %d\n",playerIndex,serverSocket.isPortBound()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(playerIndex < 0 || playerIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] playerIndex is invalid = %d",extractFileFromDirectoryPath(extractFileFromDirectoryPath(__FILE__).c_str()).c_str(),__FUNCTION__,__LINE__,playerIndex); - throw megaglest_runtime_error(szBuf); - } - MutexSafeWrapper safeMutex(serverSynchAccessor,CODE_AT_LINE); - if(serverSocketAdmin != NULL && serverSocketAdmin->isSocketValid() == false) { - serverSocketAdmin->listen(5); - } - if(serverSocket.isPortBound() == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - serverSocket.bind(serverSocket.getBindPort()); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[playerIndex],CODE_AT_LINE_X(playerIndex)); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - ConnectionSlot *slot = slots[playerIndex]; - if(slot != NULL) { - slots[playerIndex] = NULL; - } - slots[playerIndex] = new ConnectionSlot(this, playerIndex); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - safeMutexSlot.ReleaseLock(); - delete slot; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - safeMutex.ReleaseLock(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +int ServerInterface::isClientAllowedToGetFile(uint32 clientIp, + const char *username, + const char *filename) { + int result = 1; + + if (username != NULL && strlen(username) > 0 && filename != NULL && + strlen(filename) > 0) { + string user = username; + string file = filename; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s] Line: %d username [%s] file [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, username, filename); + + if (StartsWith(user, "tilesets") == true && EndsWith(file, "7z") == false) { + if (Config::getInstance().getBool( + "DisableFTPServerXferUncompressedTilesets", "false") == true) { + result = 0; + } else { + char szIP[100] = ""; + Ip::Inet_NtoA(clientIp, szIP); + string clientIP = szIP; + std::vector serverList = Socket::getLocalIPAddressList(); + + result = 0; + for (unsigned int index = 0; index < serverList.size(); ++index) { + string serverIP = serverList[index]; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s] Line: %d clientIP [%s] serverIP [%s] %d / %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, clientIP.c_str(), serverIP.c_str(), index, + serverList.size()); + + vector clientTokens; + Tokenize(clientIP, clientTokens, "."); + + vector serverTokens; + Tokenize(serverIP, serverTokens, "."); + + if (clientTokens.size() == 4 && serverTokens.size() == 4) { + if (clientTokens[0] == serverTokens[0] || + clientTokens[1] == serverTokens[1] || + clientTokens[2] == serverTokens[2]) { + result = 1; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s] Line: %d clientIP [%s] IS NOT BLOCKED\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, clientIP.c_str()); + + break; + } + } + } + } + } + } + return result; +} - updateListen(); +void ServerInterface::addClientToServerIPAddress(uint32 clientIp, + uint32 ServerIp) { + FTPServerThread::addClientToServerIPAddress(clientIp, ServerIp); +} - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void ServerInterface::addSlot(int playerIndex) { + // printf("Adding slot for playerIndex = %d, serverSocket.isPortBound() = + // %d\n",playerIndex,serverSocket.isPortBound()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + if (playerIndex < 0 || playerIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] playerIndex is invalid = %d", + extractFileFromDirectoryPath( + extractFileFromDirectoryPath(__FILE__).c_str()) + .c_str(), + __FUNCTION__, __LINE__, playerIndex); + throw megaglest_runtime_error(szBuf); + } + MutexSafeWrapper safeMutex(serverSynchAccessor, CODE_AT_LINE); + if (serverSocketAdmin != NULL && + serverSocketAdmin->isSocketValid() == false) { + serverSocketAdmin->listen(5); + } + if (serverSocket.isPortBound() == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + serverSocket.bind(serverSocket.getBindPort()); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[playerIndex], + CODE_AT_LINE_X(playerIndex)); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + ConnectionSlot *slot = slots[playerIndex]; + if (slot != NULL) { + slots[playerIndex] = NULL; + } + slots[playerIndex] = new ConnectionSlot(this, playerIndex); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + safeMutexSlot.ReleaseLock(); + delete slot; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + safeMutex.ReleaseLock(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + updateListen(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); } void ServerInterface::removeSlot(int playerIndex, int lockedSlotIndex) { - //printf("Removing slot for playerIndex = %d, serverSocket.isPortBound() = %d\n",playerIndex,serverSocket.isPortBound()); - - if(playerIndex < 0 || playerIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] playerIndex is invalid = %d",extractFileFromDirectoryPath(extractFileFromDirectoryPath(__FILE__).c_str()).c_str(),__FUNCTION__,__LINE__,playerIndex); - throw megaglest_runtime_error(szBuf); - } - - Lang &lang= Lang::getInstance(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playerIndex,lockedSlotIndex); - - MutexSafeWrapper safeMutex(serverSynchAccessor,CODE_AT_LINE); - MutexSafeWrapper safeMutexSlot(NULL,CODE_AT_LINE_X(playerIndex)); - if(playerIndex != lockedSlotIndex) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playerIndex,lockedSlotIndex); - safeMutexSlot.setMutex(slotAccessorMutexes[playerIndex],CODE_AT_LINE_X(playerIndex)); - } - - vector msgList; - ConnectionSlot *slot = slots[playerIndex]; - bool notifyDisconnect = false; - const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); - if(slot != NULL) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playerIndex,lockedSlotIndex); - - if(slot->getLastReceiveCommandListTime() > 0) { - char szBuf[4096] = ""; - - for(unsigned int index = 0; index < languageList.size(); ++index) { - string msgTemplate = "Player %s, disconnected from the game."; - if(lang.hasString("PlayerDisconnected",languageList[index]) == true) { - msgTemplate = lang.getString("PlayerDisconnected",languageList[index]); - } + // printf("Removing slot for playerIndex = %d, serverSocket.isPortBound() = + // %d\n",playerIndex,serverSocket.isPortBound()); + + if (playerIndex < 0 || playerIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] playerIndex is invalid = %d", + extractFileFromDirectoryPath( + extractFileFromDirectoryPath(__FILE__).c_str()) + .c_str(), + __FUNCTION__, __LINE__, playerIndex); + throw megaglest_runtime_error(szBuf); + } + + Lang &lang = Lang::getInstance(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + playerIndex, lockedSlotIndex); + + MutexSafeWrapper safeMutex(serverSynchAccessor, CODE_AT_LINE); + MutexSafeWrapper safeMutexSlot(NULL, CODE_AT_LINE_X(playerIndex)); + if (playerIndex != lockedSlotIndex) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, playerIndex, lockedSlotIndex); + safeMutexSlot.setMutex(slotAccessorMutexes[playerIndex], + CODE_AT_LINE_X(playerIndex)); + } + + vector msgList; + ConnectionSlot *slot = slots[playerIndex]; + bool notifyDisconnect = false; + const vector languageList = + this->gameSettings.getUniqueNetworkPlayerLanguages(); + if (slot != NULL) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, playerIndex, lockedSlotIndex); + + if (slot->getLastReceiveCommandListTime() > 0) { + char szBuf[4096] = ""; + + for (unsigned int index = 0; index < languageList.size(); ++index) { + string msgTemplate = "Player %s, disconnected from the game."; + if (lang.hasString("PlayerDisconnected", languageList[index]) == true) { + msgTemplate = + lang.getString("PlayerDisconnected", languageList[index]); + } #ifdef WIN32 - _snprintf(szBuf,4095,msgTemplate.c_str(),slot->getName().c_str()); + _snprintf(szBuf, 4095, msgTemplate.c_str(), slot->getName().c_str()); #else - snprintf(szBuf,4095,msgTemplate.c_str(),slot->getName().c_str()); + snprintf(szBuf, 4095, msgTemplate.c_str(), slot->getName().c_str()); #endif - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] %s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,szBuf); - - msgList.push_back(szBuf); - } - - notifyDisconnect = true; - } - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playerIndex,lockedSlotIndex); - - slots[playerIndex]= NULL; - safeMutexSlot.ReleaseLock(); - safeMutex.ReleaseLock(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playerIndex,lockedSlotIndex); - - if(slot != NULL) slot->close(); - delete slot; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playerIndex,lockedSlotIndex); - - updateListen(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playerIndex,lockedSlotIndex); - - if(notifyDisconnect == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playerIndex,lockedSlotIndex); - - for(unsigned int index = 0; index < languageList.size(); ++index) { - bool localEcho = lang.isLanguageLocal(languageList[index]); - queueTextMessage(msgList[index],-1, localEcho, languageList[index]); - } - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playerIndex,lockedSlotIndex); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d] %s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, szBuf); + + msgList.push_back(szBuf); + } + + notifyDisconnect = true; + } + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + playerIndex, lockedSlotIndex); + + slots[playerIndex] = NULL; + safeMutexSlot.ReleaseLock(); + safeMutex.ReleaseLock(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + playerIndex, lockedSlotIndex); + + if (slot != NULL) + slot->close(); + delete slot; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + playerIndex, lockedSlotIndex); + + updateListen(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + playerIndex, lockedSlotIndex); + + if (notifyDisconnect == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, playerIndex, lockedSlotIndex); + + for (unsigned int index = 0; index < languageList.size(); ++index) { + bool localEcho = lang.isLanguageLocal(languageList[index]); + queueTextMessage(msgList[index], -1, localEcho, languageList[index]); + } + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + playerIndex, lockedSlotIndex); } bool ServerInterface::switchSlot(int fromPlayerIndex, int toPlayerIndex) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - bool result = false; - - //printf("#1 Server is switching slots\n"); - - if(fromPlayerIndex < 0 || fromPlayerIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] fromPlayerIndex is invalid = %d",extractFileFromDirectoryPath(extractFileFromDirectoryPath(__FILE__).c_str()).c_str(),__FUNCTION__,__LINE__,fromPlayerIndex); - throw megaglest_runtime_error(szBuf); - } - - if(toPlayerIndex < 0 || toPlayerIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] toPlayerIndex is invalid = %d",extractFileFromDirectoryPath(extractFileFromDirectoryPath(__FILE__).c_str()).c_str(),__FUNCTION__,__LINE__,toPlayerIndex); - throw megaglest_runtime_error(szBuf); - } - - if(fromPlayerIndex == toPlayerIndex) { - return false; - } - - MutexSafeWrapper safeMutex(serverSynchAccessor,CODE_AT_LINE); - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[fromPlayerIndex],CODE_AT_LINE_X(fromPlayerIndex)); - MutexSafeWrapper safeMutexSlot2(slotAccessorMutexes[toPlayerIndex],CODE_AT_LINE_X(toPlayerIndex)); - - //printf("#1a Server is switching slots\n"); - - if(slots[toPlayerIndex] != NULL && - slots[toPlayerIndex]->hasValidSocketId() == false) { - - //printf("#2 Server is switching slots\n"); - - slots[fromPlayerIndex]->setPlayerIndex(toPlayerIndex); - slots[toPlayerIndex]->setPlayerIndex(fromPlayerIndex); - ConnectionSlot *tmp = slots[toPlayerIndex]; - slots[toPlayerIndex] = slots[fromPlayerIndex]; - slots[fromPlayerIndex] = tmp; - - safeMutex.ReleaseLock(); - - PlayerIndexMessage playerIndexMessage(toPlayerIndex); - slots[toPlayerIndex]->sendMessage(&playerIndexMessage); - - //slots[fromPlayerIndex]->resetJoinGameInProgressFlags(); - //slots[toPlayerIndex]->setJoinGameInProgressFlags(); - - safeMutexSlot.ReleaseLock(); - safeMutexSlot2.ReleaseLock(); - result = true; - updateListen(); - } - else { - //printf("#3 Server is switching slots aborted, is slot already connected?\n"); - - safeMutexSlot.ReleaseLock(); - safeMutexSlot2.ReleaseLock(); - safeMutex.ReleaseLock(); - } - //printf("#4 Server is switching slots\n"); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - return result; + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + bool result = false; + + // printf("#1 Server is switching slots\n"); + + if (fromPlayerIndex < 0 || fromPlayerIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] fromPlayerIndex is invalid = %d", + extractFileFromDirectoryPath( + extractFileFromDirectoryPath(__FILE__).c_str()) + .c_str(), + __FUNCTION__, __LINE__, fromPlayerIndex); + throw megaglest_runtime_error(szBuf); + } + + if (toPlayerIndex < 0 || toPlayerIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] toPlayerIndex is invalid = %d", + extractFileFromDirectoryPath( + extractFileFromDirectoryPath(__FILE__).c_str()) + .c_str(), + __FUNCTION__, __LINE__, toPlayerIndex); + throw megaglest_runtime_error(szBuf); + } + + if (fromPlayerIndex == toPlayerIndex) { + return false; + } + + MutexSafeWrapper safeMutex(serverSynchAccessor, CODE_AT_LINE); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[fromPlayerIndex], + CODE_AT_LINE_X(fromPlayerIndex)); + MutexSafeWrapper safeMutexSlot2(slotAccessorMutexes[toPlayerIndex], + CODE_AT_LINE_X(toPlayerIndex)); + + // printf("#1a Server is switching slots\n"); + + if (slots[toPlayerIndex] != NULL && + slots[toPlayerIndex]->hasValidSocketId() == false) { + + // printf("#2 Server is switching slots\n"); + + slots[fromPlayerIndex]->setPlayerIndex(toPlayerIndex); + slots[toPlayerIndex]->setPlayerIndex(fromPlayerIndex); + ConnectionSlot *tmp = slots[toPlayerIndex]; + slots[toPlayerIndex] = slots[fromPlayerIndex]; + slots[fromPlayerIndex] = tmp; + + safeMutex.ReleaseLock(); + + PlayerIndexMessage playerIndexMessage(toPlayerIndex); + slots[toPlayerIndex]->sendMessage(&playerIndexMessage); + + // slots[fromPlayerIndex]->resetJoinGameInProgressFlags(); + // slots[toPlayerIndex]->setJoinGameInProgressFlags(); + + safeMutexSlot.ReleaseLock(); + safeMutexSlot2.ReleaseLock(); + result = true; + updateListen(); + } else { + // printf("#3 Server is switching slots aborted, is slot already + // connected?\n"); + + safeMutexSlot.ReleaseLock(); + safeMutexSlot2.ReleaseLock(); + safeMutex.ReleaseLock(); + } + // printf("#4 Server is switching slots\n"); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + return result; } Mutex *ServerInterface::getSlotMutex(int playerIndex) { - return slotAccessorMutexes[playerIndex]; + return slotAccessorMutexes[playerIndex]; } ConnectionSlot *ServerInterface::getSlot(int playerIndex, bool lockMutex) { - if(playerIndex < 0 || playerIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] playerIndex is invalid = %d",extractFileFromDirectoryPath(extractFileFromDirectoryPath(__FILE__).c_str()).c_str(),__FUNCTION__,__LINE__,playerIndex); - throw megaglest_runtime_error(szBuf); - } - - MutexSafeWrapper safeMutexSlot((lockMutex == true ? slotAccessorMutexes[playerIndex] : NULL),CODE_AT_LINE_X(playerIndex)); - ConnectionSlot *result = slots[playerIndex]; - return result; + if (playerIndex < 0 || playerIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] playerIndex is invalid = %d", + extractFileFromDirectoryPath( + extractFileFromDirectoryPath(__FILE__).c_str()) + .c_str(), + __FUNCTION__, __LINE__, playerIndex); + throw megaglest_runtime_error(szBuf); + } + + MutexSafeWrapper safeMutexSlot( + (lockMutex == true ? slotAccessorMutexes[playerIndex] : NULL), + CODE_AT_LINE_X(playerIndex)); + ConnectionSlot *result = slots[playerIndex]; + return result; } bool ServerInterface::isClientConnected(int playerIndex) { - if(playerIndex < 0 || playerIndex >= GameConstants::maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] playerIndex is invalid = %d",extractFileFromDirectoryPath(extractFileFromDirectoryPath(__FILE__).c_str()).c_str(),__FUNCTION__,__LINE__,playerIndex); - throw megaglest_runtime_error(szBuf); - } - - bool result = false; - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[playerIndex],CODE_AT_LINE_X(playerIndex)); - if(slots[playerIndex] != NULL && slots[playerIndex]->isConnected() == true) { - result = true; - } - return result; + if (playerIndex < 0 || playerIndex >= GameConstants::maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] playerIndex is invalid = %d", + extractFileFromDirectoryPath( + extractFileFromDirectoryPath(__FILE__).c_str()) + .c_str(), + __FUNCTION__, __LINE__, playerIndex); + throw megaglest_runtime_error(szBuf); + } + + bool result = false; + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[playerIndex], + CODE_AT_LINE_X(playerIndex)); + if (slots[playerIndex] != NULL && slots[playerIndex]->isConnected() == true) { + result = true; + } + return result; } bool ServerInterface::hasClientConnection() { - bool result = false; - for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { - if(isClientConnected(index) == true) { - result = true; - break; - } - } - return result; + bool result = false; + for (int index = 0; exitServer == false && index < GameConstants::maxPlayers; + ++index) { + if (isClientConnected(index) == true) { + result = true; + break; + } + } + return result; } int ServerInterface::getSlotCount() { - int slotCount = 0; - for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); - if(slots[index] != NULL) { - ++slotCount; - } - } - return slotCount; + int slotCount = 0; + for (int index = 0; exitServer == false && index < GameConstants::maxPlayers; + ++index) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index], + CODE_AT_LINE_X(index)); + if (slots[index] != NULL) { + ++slotCount; + } + } + return slotCount; } int ServerInterface::getConnectedSlotCount(bool authenticated) { - int connectedSlotCount = 0; - for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); - if(slots[index] != NULL && slots[index]->isConnected() == true) { - if(authenticated == false || - (authenticated == true && slots[index]->getConnectHasHandshaked() == true)) { - ++connectedSlotCount; - } - } - } - return connectedSlotCount; + int connectedSlotCount = 0; + for (int index = 0; exitServer == false && index < GameConstants::maxPlayers; + ++index) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index], + CODE_AT_LINE_X(index)); + if (slots[index] != NULL && slots[index]->isConnected() == true) { + if (authenticated == false || + (authenticated == true && + slots[index]->getConnectHasHandshaked() == true)) { + ++connectedSlotCount; + } + } + } + return connectedSlotCount; } int64 ServerInterface::getNextEventId() { - nextEventId++; - if(nextEventId > INT_MAX) { - nextEventId = 1; - } - return nextEventId; -} - -std::pair ServerInterface::clientLagCheck(ConnectionSlot *connectionSlot, bool skipNetworkBroadCast) { - std::pair clientLagExceededOrWarned = std::make_pair(false, false); - static bool alreadyInLagCheck = false; - - if(alreadyInLagCheck == true || - (connectionSlot != NULL && (connectionSlot->getSkipLagCheck() == true || - connectionSlot->getConnectHasHandshaked() == false))) { - return clientLagExceededOrWarned; - } - - try { - alreadyInLagCheck = true; - - if((gameStartTime > 0 && - difftime((long int)time(NULL),gameStartTime) >= LAG_CHECK_GRACE_PERIOD) && - (resumeGameStartTime == 0 || - (resumeGameStartTime > 0 && - difftime((long int)time(NULL),resumeGameStartTime) >= LAG_CHECK_GRACE_PERIOD))) { - if(connectionSlot != NULL && connectionSlot->isConnected() == true) { - - double clientLag = this->getCurrentFrameCount() - connectionSlot->getCurrentFrameCount(); - double clientLagCount = (gameSettings.getNetworkFramePeriod() > 0 ? (clientLag / gameSettings.getNetworkFramePeriod()) : 0); - connectionSlot->setCurrentLagCount(clientLagCount); - - double clientLagTime = difftime((long int)time(NULL),connectionSlot->getLastReceiveCommandListTime()); - - if(this->getCurrentFrameCount() > 0) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] playerIndex = %d, clientLag = %f, clientLagCount = %f, this->getCurrentFrameCount() = %d, connectionSlot->getCurrentFrameCount() = %d, clientLagTime = %f\n", - extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__, - connectionSlot->getPlayerIndex(), - clientLag,clientLagCount, - this->getCurrentFrameCount(), - connectionSlot->getCurrentFrameCount(), - clientLagTime); - } - - // TEST LAG Error and warnings!!! - //clientLagCount = maxFrameCountLagAllowed + 1; - //clientLagTime = maxClientLagTimeAllowed + 1; - /* - if(difftime(time(NULL),gameStartTime) >= LAG_CHECK_GRACE_PERIOD + 5) { - clientLagTime = maxClientLagTimeAllowed + 1; - } - else if(difftime(time(NULL),gameStartTime) >= LAG_CHECK_GRACE_PERIOD) { - clientLagTime = (maxClientLagTimeAllowed * warnFrameCountLagPercent) + 1; - } - */ - // END test - - - //printf("skipNetworkBroadCast [%d] clientLagCount [%f][%f][%f] clientLagTime [%f][%f][%f]\n",skipNetworkBroadCast,clientLagCount,(maxFrameCountLagAllowed * warnFrameCountLagPercent),maxFrameCountLagAllowed,clientLagTime,(maxClientLagTimeAllowed * warnFrameCountLagPercent),maxClientLagTimeAllowed); - - // New lag check - if((maxFrameCountLagAllowed > 0 && clientLagCount > maxFrameCountLagAllowed) || - (maxClientLagTimeAllowed > 0 && clientLagTime > maxClientLagTimeAllowed) || - (maxFrameCountLagAllowedEver > 0 && clientLagCount > maxFrameCountLagAllowedEver) || - ( maxClientLagTimeAllowedEver > 0 && clientLagTime > maxClientLagTimeAllowedEver)) { - - clientLagExceededOrWarned.first = true; - //printf("#1 Client Warned\n"); - - Lang &lang= Lang::getInstance(); - const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); - for(unsigned int index = 0; index < languageList.size(); ++index) { - char szBuf[4096]=""; - - string msgTemplate = "DROPPING %s, exceeded max allowed LAG count of %f [time = %f], clientLag = %f [%f], disconnecting client."; - if(lang.hasString("ClientLagDropping") == true) { - msgTemplate = lang.getString("ClientLagDropping",languageList[index]); - } - if(gameSettings.getNetworkPauseGameForLaggedClients() == true && - ((maxFrameCountLagAllowedEver <= 0 || clientLagCount <= maxFrameCountLagAllowedEver) && - (maxClientLagTimeAllowedEver <= 0 || clientLagTime <= maxClientLagTimeAllowedEver))) { - msgTemplate = "PAUSING GAME TEMPORARILY for %s, exceeded max allowed LAG count of %f [time = %f], clientLag = %f [%f], waiting for client to catch up..."; - if(lang.hasString("ClientLagPausing") == true) { - msgTemplate = lang.getString("ClientLagPausing",languageList[index]); - } - } -#ifdef WIN32 - _snprintf(szBuf,4095,msgTemplate.c_str(),connectionSlot->getName().c_str() ,maxFrameCountLagAllowed,maxClientLagTimeAllowed,clientLagCount,clientLagTime); -#else - snprintf(szBuf,4095,msgTemplate.c_str(),connectionSlot->getName().c_str(),maxFrameCountLagAllowed,maxClientLagTimeAllowed,clientLagCount,clientLagTime); -#endif - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] %s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,szBuf); - - if(skipNetworkBroadCast == false) { - string sMsg = szBuf; - bool echoLocal = lang.isLanguageLocal(languageList[index]); - sendTextMessage(sMsg,-1, echoLocal, languageList[index], connectionSlot->getPlayerIndex()); - } - } - - if(gameSettings.getNetworkPauseGameForLaggedClients() == false || - (maxFrameCountLagAllowedEver > 0 && clientLagCount > maxFrameCountLagAllowedEver) || - (maxClientLagTimeAllowedEver > 0 && clientLagTime > maxClientLagTimeAllowedEver)) { - - //printf("Closing connection slot lagged out!\n"); - connectionSlot->close(); - } - - } - // New lag check warning - else if((maxFrameCountLagAllowed > 0 && warnFrameCountLagPercent > 0 && - clientLagCount > (maxFrameCountLagAllowed * warnFrameCountLagPercent)) || - (maxClientLagTimeAllowed > 0 && warnFrameCountLagPercent > 0 && - clientLagTime > (maxClientLagTimeAllowed * warnFrameCountLagPercent)) ) { - - clientLagExceededOrWarned.second = true; - //printf("#2 Client Warned\n"); - - if(connectionSlot->getLagCountWarning() == false) { - connectionSlot->setLagCountWarning(true); - - Lang &lang= Lang::getInstance(); - const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); - for(unsigned int index = 0; index < languageList.size(); ++index) { - char szBuf[4096]=""; - - string msgTemplate = "LAG WARNING for %s, may exceed max allowed LAG count of %f [time = %f], clientLag = %f [%f], WARNING..."; - if(lang.hasString("ClientLagWarning") == true) { - msgTemplate = lang.getString("ClientLagWarning",languageList[index]); - } - - #ifdef WIN32 - _snprintf(szBuf,4095,msgTemplate.c_str(),connectionSlot->getName().c_str(),maxFrameCountLagAllowed,maxClientLagTimeAllowed,clientLagCount,clientLagTime); - #else - snprintf(szBuf,4095,msgTemplate.c_str(),connectionSlot->getName().c_str(),maxFrameCountLagAllowed,maxClientLagTimeAllowed,clientLagCount,clientLagTime); - #endif - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] %s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,szBuf); - - if(skipNetworkBroadCast == false) { - string sMsg = szBuf; - bool echoLocal = lang.isLanguageLocal(languageList[index]); - sendTextMessage(sMsg,-1, echoLocal, languageList[index], connectionSlot->getPlayerIndex()); - } - } - } - } - else if(connectionSlot->getLagCountWarning() == true) { - connectionSlot->setLagCountWarning(false); - } - } - } - } - catch(const exception &ex) { - alreadyInLagCheck = false; - - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] ERROR [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - throw megaglest_runtime_error(ex.what()); - } - - alreadyInLagCheck = false; - return clientLagExceededOrWarned; -} - -void ServerInterface::updateSocketTriggeredList(std::map & socketTriggeredList) { - for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); - ConnectionSlot *connectionSlot = slots[index]; - if(connectionSlot != NULL) { - PLATFORM_SOCKET clientSocket = connectionSlot->getSocketId(); - if(Socket::isSocketValid(&clientSocket) == true) { - socketTriggeredList[clientSocket] = false; - } - } - } -} - -void ServerInterface::validateConnectedClients() { - for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); - ConnectionSlot* connectionSlot = slots[index]; - if(connectionSlot != NULL) { - connectionSlot->validateConnection(); - } - } -} - -bool ServerInterface::signalClientReceiveCommands(ConnectionSlot *connectionSlot, - int slotIndex, bool socketTriggered, ConnectionSlotEvent & event) { - bool slotSignalled = false; - - event.eventType = eReceiveSocketData; - event.networkMessage = NULL; - event.connectionSlot = connectionSlot; - event.socketTriggered = socketTriggered; - event.triggerId = slotIndex; - event.eventId = getNextEventId(); - - if(connectionSlot != NULL) { - if(socketTriggered == true || connectionSlot->isConnected() == false) { - connectionSlot->signalUpdate(&event); - slotSignalled = true; - } - } - return slotSignalled; -} - -void ServerInterface::signalClientsToRecieveData(std::map &socketTriggeredList, - std::map &eventList, - std::map & mapSlotSignalledList) { - //printf("====================================In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //printf("Signal clients get new data\n"); - const bool newThreadManager = Config::getInstance().getBool("EnableNewThreadManager","false"); - if(newThreadManager == true) { - masterController.clearSlaves(true); - std::vector slaveThreadList; - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot* connectionSlot = slots[i]; - - bool socketTriggered = false; - - if(connectionSlot != NULL) { - PLATFORM_SOCKET clientSocket = connectionSlot->getSocketId(); - if(Socket::isSocketValid(&clientSocket)) { - socketTriggered = socketTriggeredList[clientSocket]; - } - else if(this->getGameHasBeenInitiated() == true && - this->getAllowInGameConnections() == true) { - socketTriggeredList[clientSocket] = true; - socketTriggered = socketTriggeredList[clientSocket]; - } - } - ConnectionSlotEvent &event = eventList[i]; - event.eventType = eReceiveSocketData; - event.networkMessage = NULL; - event.connectionSlot = connectionSlot; - event.socketTriggered = socketTriggered; - event.triggerId = i; - event.eventId = getNextEventId(); - - if(connectionSlot != NULL) { - if(socketTriggered == true || connectionSlot->isConnected() == false) { - if(connectionSlot->getWorkerThread() != NULL) { - slaveThreadList.push_back(connectionSlot->getWorkerThread()); - mapSlotSignalledList[i] = true; - } - } - } - } - masterController.setSlaves(slaveThreadList); - masterController.signalSlaves(&eventList); - } - else { - for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); - ConnectionSlot *connectionSlot = slots[index]; - - if(connectionSlot != NULL) { - bool socketTriggered = false; - PLATFORM_SOCKET clientSocket = connectionSlot->getSocketId(); - if(Socket::isSocketValid(&clientSocket)) { - socketTriggered = socketTriggeredList[clientSocket]; - } - - ConnectionSlotEvent &event = eventList[index]; - bool socketSignalled = signalClientReceiveCommands(connectionSlot,index,socketTriggered,event); - if(connectionSlot != NULL && socketTriggered == true) { - mapSlotSignalledList[index] = socketSignalled; - } - } - } - } + nextEventId++; + if (nextEventId > INT_MAX) { + nextEventId = 1; + } + return nextEventId; } -void ServerInterface::checkForCompletedClientsUsingThreadManager( - std::map &mapSlotSignalledList, std::vector& errorMsgList) { - - masterController.waitTillSlavesTrigger(MAX_SLOT_THREAD_WAIT_TIME_MILLISECONDS); - masterController.clearSlaves(true); - - for (int i = 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - - ConnectionSlot* connectionSlot = slots[i]; - if (connectionSlot != NULL && mapSlotSignalledList[i] == true) { - - try { - std::vector errorList = - connectionSlot->getThreadErrorList(); - // Collect any collected errors from threads - if (errorList.empty() == false) { - for (int iErrIdx = 0; iErrIdx < (int) errorList.size();++iErrIdx) { - string &sErr = errorList[iErrIdx]; - - if (sErr != "") { - errorMsgList.push_back(sErr); - } - } - connectionSlot->clearThreadErrorList(); - } - } catch (const exception &ex) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] error detected [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); +std::pair +ServerInterface::clientLagCheck(ConnectionSlot *connectionSlot, + bool skipNetworkBroadCast) { + std::pair clientLagExceededOrWarned = + std::make_pair(false, false); + static bool alreadyInLagCheck = false; + + if (alreadyInLagCheck == true || + (connectionSlot != NULL && + (connectionSlot->getSkipLagCheck() == true || + connectionSlot->getConnectHasHandshaked() == false))) { + return clientLagExceededOrWarned; + } + + try { + alreadyInLagCheck = true; + + if ((gameStartTime > 0 && difftime((long int)time(NULL), gameStartTime) >= + LAG_CHECK_GRACE_PERIOD) && + (resumeGameStartTime == 0 || + (resumeGameStartTime > 0 && + difftime((long int)time(NULL), resumeGameStartTime) >= + LAG_CHECK_GRACE_PERIOD))) { + if (connectionSlot != NULL && connectionSlot->isConnected() == true) { + + double clientLag = this->getCurrentFrameCount() - + connectionSlot->getCurrentFrameCount(); + double clientLagCount = + (gameSettings.getNetworkFramePeriod() > 0 + ? (clientLag / gameSettings.getNetworkFramePeriod()) + : 0); + connectionSlot->setCurrentLagCount(clientLagCount); + + double clientLagTime = + difftime((long int)time(NULL), + connectionSlot->getLastReceiveCommandListTime()); + + if (this->getCurrentFrameCount() > 0) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] playerIndex = %d, clientLag = %f, " + "clientLagCount = %f, this->getCurrentFrameCount() = %d, " + "connectionSlot->getCurrentFrameCount() = %d, clientLagTime = " + "%f\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, connectionSlot->getPlayerIndex(), clientLag, + clientLagCount, this->getCurrentFrameCount(), + connectionSlot->getCurrentFrameCount(), clientLagTime); + } - errorMsgList.push_back(ex.what()); - } - } - } -} + // TEST LAG Error and warnings!!! + // clientLagCount = maxFrameCountLagAllowed + 1; + // clientLagTime = maxClientLagTimeAllowed + 1; + /* + if(difftime(time(NULL),gameStartTime) >= LAG_CHECK_GRACE_PERIOD + 5) { + clientLagTime = maxClientLagTimeAllowed + 1; + } + else if(difftime(time(NULL),gameStartTime) >= LAG_CHECK_GRACE_PERIOD) { + clientLagTime = (maxClientLagTimeAllowed * + warnFrameCountLagPercent) + 1; + } + */ + // END test + + // printf("skipNetworkBroadCast [%d] clientLagCount [%f][%f][%f] + // clientLagTime + // [%f][%f][%f]\n",skipNetworkBroadCast,clientLagCount,(maxFrameCountLagAllowed + // * warnFrameCountLagPercent),maxFrameCountLagAllowed,clientLagTime,(maxClientLagTimeAllowed * warnFrameCountLagPercent),maxClientLagTimeAllowed); + + // New lag check + if ((maxFrameCountLagAllowed > 0 && + clientLagCount > maxFrameCountLagAllowed) || + (maxClientLagTimeAllowed > 0 && + clientLagTime > maxClientLagTimeAllowed) || + (maxFrameCountLagAllowedEver > 0 && + clientLagCount > maxFrameCountLagAllowedEver) || + (maxClientLagTimeAllowedEver > 0 && + clientLagTime > maxClientLagTimeAllowedEver)) { + + clientLagExceededOrWarned.first = true; + // printf("#1 Client Warned\n"); + + Lang &lang = Lang::getInstance(); + const vector languageList = + this->gameSettings.getUniqueNetworkPlayerLanguages(); + for (unsigned int index = 0; index < languageList.size(); ++index) { + char szBuf[4096] = ""; + + string msgTemplate = + "DROPPING %s, exceeded max allowed LAG count of %f [time = " + "%f], clientLag = %f [%f], disconnecting client."; + if (lang.hasString("ClientLagDropping") == true) { + msgTemplate = + lang.getString("ClientLagDropping", languageList[index]); + } + if (gameSettings.getNetworkPauseGameForLaggedClients() == true && + ((maxFrameCountLagAllowedEver <= 0 || + clientLagCount <= maxFrameCountLagAllowedEver) && + (maxClientLagTimeAllowedEver <= 0 || + clientLagTime <= maxClientLagTimeAllowedEver))) { + msgTemplate = "PAUSING GAME TEMPORARILY for %s, exceeded max " + "allowed LAG count of %f [time = %f], clientLag = " + "%f [%f], waiting for client to catch up..."; + if (lang.hasString("ClientLagPausing") == true) { + msgTemplate = + lang.getString("ClientLagPausing", languageList[index]); + } + } +#ifdef WIN32 + _snprintf(szBuf, 4095, msgTemplate.c_str(), + connectionSlot->getName().c_str(), + maxFrameCountLagAllowed, maxClientLagTimeAllowed, + clientLagCount, clientLagTime); +#else + snprintf(szBuf, 4095, msgTemplate.c_str(), + connectionSlot->getName().c_str(), maxFrameCountLagAllowed, + maxClientLagTimeAllowed, clientLagCount, clientLagTime); +#endif + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d] %s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, szBuf); + + if (skipNetworkBroadCast == false) { + string sMsg = szBuf; + bool echoLocal = lang.isLanguageLocal(languageList[index]); + sendTextMessage(sMsg, -1, echoLocal, languageList[index], + connectionSlot->getPlayerIndex()); + } + } + + if (gameSettings.getNetworkPauseGameForLaggedClients() == false || + (maxFrameCountLagAllowedEver > 0 && + clientLagCount > maxFrameCountLagAllowedEver) || + (maxClientLagTimeAllowedEver > 0 && + clientLagTime > maxClientLagTimeAllowedEver)) { + + // printf("Closing connection slot lagged out!\n"); + connectionSlot->close(); + } -void ServerInterface::checkForCompletedClientsUsingLoop( - std::map& mapSlotSignalledList, std::vector &errorMsgList, - std::map &eventList) { - - //time_t waitForThreadElapsed = time(NULL); - Chrono waitForThreadElapsed(true); - - std::map slotsCompleted; - for (bool threadsDone = false; exitServer == false && threadsDone == false && - waitForThreadElapsed.getMillis() <= MAX_SLOT_THREAD_WAIT_TIME_MILLISECONDS;) { - - threadsDone = true; - // Examine all threads for completion of delegation - for (int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); - - ConnectionSlot *connectionSlot = slots[index]; - if (connectionSlot != NULL && connectionSlot->isConnected() == true && - mapSlotSignalledList[index] == true && - connectionSlot->getJoinGameInProgress() == false && - slotsCompleted.find(index) == slotsCompleted.end()) { - - try { - std::vector errorList = connectionSlot->getThreadErrorList(); - // Collect any collected errors from threads - if (errorList.empty() == false) { - - for (int iErrIdx = 0; iErrIdx < (int) errorList.size();++iErrIdx) { - - string &sErr = errorList[iErrIdx]; - if (sErr != "") { - errorMsgList.push_back(sErr); - } - } - connectionSlot->clearThreadErrorList(); - } - - // Not done waiting for data yet - bool updateFinished = (connectionSlot != NULL ? connectionSlot->updateCompleted(&eventList[index]) : true); - if (updateFinished == false) { - threadsDone = false; - break; - } - else { - slotsCompleted[index] = true; - } - } - catch (const exception &ex) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] error detected [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - - errorMsgList.push_back(ex.what()); - } - } - } - } -} + } + // New lag check warning + else if ((maxFrameCountLagAllowed > 0 && warnFrameCountLagPercent > 0 && + clientLagCount > + (maxFrameCountLagAllowed * warnFrameCountLagPercent)) || + (maxClientLagTimeAllowed > 0 && warnFrameCountLagPercent > 0 && + clientLagTime > + (maxClientLagTimeAllowed * warnFrameCountLagPercent))) { + + clientLagExceededOrWarned.second = true; + // printf("#2 Client Warned\n"); + + if (connectionSlot->getLagCountWarning() == false) { + connectionSlot->setLagCountWarning(true); + + Lang &lang = Lang::getInstance(); + const vector languageList = + this->gameSettings.getUniqueNetworkPlayerLanguages(); + for (unsigned int index = 0; index < languageList.size(); ++index) { + char szBuf[4096] = ""; + + string msgTemplate = + "LAG WARNING for %s, may exceed max allowed LAG count of %f " + "[time = %f], clientLag = %f [%f], WARNING..."; + if (lang.hasString("ClientLagWarning") == true) { + msgTemplate = + lang.getString("ClientLagWarning", languageList[index]); + } -std::string ServerInterface::getIpAddress(bool mutexLock) { - string result = serverSocket.getIpAddress(); - return result; +#ifdef WIN32 + _snprintf(szBuf, 4095, msgTemplate.c_str(), + connectionSlot->getName().c_str(), + maxFrameCountLagAllowed, maxClientLagTimeAllowed, + clientLagCount, clientLagTime); +#else + snprintf(szBuf, 4095, msgTemplate.c_str(), + connectionSlot->getName().c_str(), + maxFrameCountLagAllowed, maxClientLagTimeAllowed, + clientLagCount, clientLagTime); +#endif + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d] %s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, szBuf); + + if (skipNetworkBroadCast == false) { + string sMsg = szBuf; + bool echoLocal = lang.isLanguageLocal(languageList[index]); + sendTextMessage(sMsg, -1, echoLocal, languageList[index], + connectionSlot->getPlayerIndex()); + } + } + } + } else if (connectionSlot->getLagCountWarning() == true) { + connectionSlot->setLagCountWarning(false); + } + } + } + } catch (const exception &ex) { + alreadyInLagCheck = false; + + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] ERROR [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + throw megaglest_runtime_error(ex.what()); + } + + alreadyInLagCheck = false; + return clientLagExceededOrWarned; } -void ServerInterface::setClientLagCallbackInterface(ClientLagCallbackInterface *intf) { - this->clientLagCallbackInterface = intf; +void ServerInterface::updateSocketTriggeredList( + std::map &socketTriggeredList) { + for (int index = 0; exitServer == false && index < GameConstants::maxPlayers; + ++index) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index], + CODE_AT_LINE_X(index)); + ConnectionSlot *connectionSlot = slots[index]; + if (connectionSlot != NULL) { + PLATFORM_SOCKET clientSocket = connectionSlot->getSocketId(); + if (Socket::isSocketValid(&clientSocket) == true) { + socketTriggeredList[clientSocket] = false; + } + } + } } -bool ServerInterface::getClientsAutoPausedDueToLag() { - return this->clientsAutoPausedDueToLag; -} - -void ServerInterface::checkForCompletedClients(std::map & mapSlotSignalledList, - std::vector &errorMsgList, - std::map &eventList) { - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - const bool newThreadManager = Config::getInstance().getBool("EnableNewThreadManager","false"); - if(newThreadManager == true) { - checkForCompletedClientsUsingThreadManager(mapSlotSignalledList, errorMsgList); - } - else { - checkForCompletedClientsUsingLoop(mapSlotSignalledList, errorMsgList, eventList); - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); -} - -void ServerInterface::checkForAutoPauseForLaggingClient(int index,ConnectionSlot* connectionSlot) { - - if (gameSettings.getNetworkPauseGameForLaggedClients() == true && - this->clientsAutoPausedDueToLag == false) { - if (connectionSlot != NULL && connectionSlot->isConnected() == true) { - if (connectionSlot->getAutoPauseGameCountForLag() < MAX_CLIENT_PAUSE_FOR_LAG_COUNT) { - if (this->clientLagCallbackInterface != NULL) { - - if (this->clientsAutoPausedDueToLagTimer.isStarted() == false || - this->clientsAutoPausedDueToLagTimer.getMillis() >= MAX_CLIENT_WAIT_SECONDS_FOR_PAUSE_MILLISECONDS) { - - connectionSlot->incrementAutoPauseGameCountForLag(); - - this->clientsAutoPausedDueToLag = true; - if (this->clientLagCallbackInterface->clientLagHandler(index, true) == false) { - connectionSlot->close(); - } - else { - if (this->clientsAutoPausedDueToLagTimer.isStarted()== true) { - - this->clientsAutoPausedDueToLagTimer.reset(); - this->clientsAutoPausedDueToLagTimer.stop(); - } - this->clientsAutoPausedDueToLagTimer.start(); - } - } - } - } - } - } -} - -void ServerInterface::checkForLaggingClients(std::map &mapSlotSignalledList, - std::map &eventList, - std::map &socketTriggeredList, - std::vector &errorMsgList) { - bool lastGlobalLagCheckTimeUpdate = false; - if(gameHasBeenInitiated == true) { - - //time_t waitForClientsElapsed = time(NULL); - Chrono waitForClientsElapsed(true); - //time_t waitForThreadElapsed = time(NULL); - Chrono waitForThreadElapsed(true); - std::map slotsCompleted; - std::map slotsWarnedList; - - for(bool threadsDone = false; - exitServer == false && threadsDone == false && - waitForThreadElapsed.getMillis() <= MAX_SLOT_THREAD_WAIT_TIME_MILLISECONDS;) { - - threadsDone = true; - // Examine all threads for completion of delegation - for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { - //printf("#1 Check lag for i: %d\n",i); - - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); - ConnectionSlot* connectionSlot = slots[index]; - - if(connectionSlot != NULL && connectionSlot->isConnected() == true && - connectionSlot->getSkipLagCheck() == false && - mapSlotSignalledList[index] == true && - slotsCompleted.find(index) == slotsCompleted.end()) { - - //printf("#2 Check lag for i: %d playerindex: %d name [%s] socket: %d\n",i,connectionSlot->getPlayerIndex(),connectionSlot->getName().c_str(),connectionSlot->getSocketId()); - try { - std::vector errorList = connectionSlot->getThreadErrorList(); - // Show any collected errors from threads - if(errorList.empty() == false) { - for(int iErrIdx = 0; iErrIdx < (int)errorList.size(); ++iErrIdx) { - string &sErr = errorList[iErrIdx]; - if(sErr != "") { - errorMsgList.push_back(sErr); - } - } - connectionSlot->clearThreadErrorList(); - } - - // Not done waiting for data yet - bool updateFinished = (connectionSlot != NULL ? connectionSlot->updateCompleted(&eventList[index]) : true); - if(updateFinished == false) { - //printf("#2a Check lag for i: %d\n",i); - threadsDone = false; - break; - } - else { - // New lag check - std::pair clientLagExceededOrWarned = std::make_pair(false,false); - if( gameHasBeenInitiated == true && connectionSlot != NULL && - connectionSlot->isConnected() == true) { - clientLagExceededOrWarned = clientLagCheck(connectionSlot,slotsWarnedList[index]); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] clientLagExceededOrWarned.first = %d, clientLagExceededOrWarned.second = %d, gameSettings.getNetworkPauseGameForLaggedClients() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,clientLagExceededOrWarned.first,clientLagExceededOrWarned.second,gameSettings.getNetworkPauseGameForLaggedClients()); - - if(clientLagExceededOrWarned.first == true) { - slotsWarnedList[index] = true; - } - } - // If the client has exceeded lag and the server wants - // to pause while they catch up, re-trigger the - // client reader thread - if((clientLagExceededOrWarned.second == true && - gameSettings.getNetworkPauseGameForLaggedClients() == true)) { - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d, clientLagExceededOrWarned.first = %d, clientLagExceededOrWarned.second = %d, waitForClientsElapsed.getMillis() = %d, MAX_CLIENT_WAIT_SECONDS_FOR_PAUSE_MILLISECONDS = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,clientLagExceededOrWarned.first,clientLagExceededOrWarned.second,(int)waitForClientsElapsed.getMillis(),MAX_CLIENT_WAIT_SECONDS_FOR_PAUSE_MILLISECONDS); - - checkForAutoPauseForLaggingClient(index, connectionSlot); - - slotsCompleted[index] = true; - } - else { - slotsCompleted[index] = true; - } - } - } - catch(const exception &ex) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] error detected [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - errorMsgList.push_back(ex.what()); - } - } - - //printf("#3 Check lag for i: %d\n",i); - if(connectionSlot != NULL && - connectionSlot->isConnected() == true && - connectionSlot->getSkipLagCheck() == false) { - //printf("#4 Check lag for i: %d\n",i); - - try { - if(gameHasBeenInitiated == true && - difftime((long int)time(NULL),gameStartTime) >= LAG_CHECK_GRACE_PERIOD && - difftime((long int)time(NULL),lastGlobalLagCheckTime) >= LAG_CHECK_INTERVAL_PERIOD) { - - //printf("\n\n\n^^^^^^^^^^^^^^ PART A\n\n\n"); - - // New lag check - std::pair clientLagExceededOrWarned = std::make_pair(false,false); - if( connectionSlot != NULL && connectionSlot->isConnected() == true) { - //printf("\n\n\n^^^^^^^^^^^^^^ PART B\n\n\n"); - - lastGlobalLagCheckTimeUpdate = true; - clientLagExceededOrWarned = clientLagCheck(connectionSlot,slotsWarnedList[index]); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] clientLagExceededOrWarned.first = %d, clientLagExceededOrWarned.second = %d, gameSettings.getNetworkPauseGameForLaggedClients() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,clientLagExceededOrWarned.first,clientLagExceededOrWarned.second,gameSettings.getNetworkPauseGameForLaggedClients()); - - if(clientLagExceededOrWarned.first == true) { - slotsWarnedList[index] = true; - } - - // If the client has exceeded lag and the server wants - // to pause while they catch up, re-trigger the - // client reader thread - if((clientLagExceededOrWarned.second == true && - gameSettings.getNetworkPauseGameForLaggedClients() == true)) { - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d, clientLagExceededOrWarned.first = %d, clientLagExceededOrWarned.second = %d, waitForClientsElapsed.getMillis() = %d, MAX_CLIENT_WAIT_SECONDS_FOR_PAUSE_MILLISECONDS = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,clientLagExceededOrWarned.first,clientLagExceededOrWarned.second,(int)waitForClientsElapsed.getMillis(),MAX_CLIENT_WAIT_SECONDS_FOR_PAUSE_MILLISECONDS); - - checkForAutoPauseForLaggingClient(index, connectionSlot); - } - } - } - } - catch(const exception &ex) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] error detected [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - errorMsgList.push_back(ex.what()); - } - } - - //printf("#5 Check lag for i: %d\n",i); - } - } - } - if(lastGlobalLagCheckTimeUpdate == true) { - lastGlobalLagCheckTime = time(NULL); - } +void ServerInterface::validateConnectedClients() { + for (int index = 0; exitServer == false && index < GameConstants::maxPlayers; + ++index) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index], + CODE_AT_LINE_X(index)); + ConnectionSlot *connectionSlot = slots[index]; + if (connectionSlot != NULL) { + connectionSlot->validateConnection(); + } + } } -void ServerInterface::executeNetworkCommandsFromClients() { - if(gameHasBeenInitiated == true) { - for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); - ConnectionSlot* connectionSlot= slots[index]; - if(connectionSlot != NULL && connectionSlot->isConnected() == true) { - vector pendingList = connectionSlot->getPendingNetworkCommandList(true); - if(pendingList.empty() == false) { - for(int idx = 0; exitServer == false && idx < (int)pendingList.size(); ++idx) { - NetworkCommand &cmd = pendingList[idx]; - this->requestCommand(&cmd); - } - //printf("Executed: %d commands from slot: %d\n",pendingList.size(),index); - } - } - } - } -} - -void ServerInterface::dispatchPendingChatMessages(std::vector &errorMsgList) { - for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { - - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); - ConnectionSlot *connectionSlot = slots[index]; - - if(connectionSlot != NULL && - connectionSlot->getChatTextList(false).empty() == false) { - try { - std::vector chatText = connectionSlot->getChatTextList(true); - for(int chatIdx = 0; - exitServer == false && slots[index] != NULL && - chatIdx < (int)chatText.size(); chatIdx++) { - - connectionSlot = slots[index]; - if(connectionSlot != NULL) { - ChatMsgInfo msg(chatText[chatIdx]); - this->addChatInfo(msg); - - string newChatText = msg.chatText.c_str(); - int newChatTeamIndex = msg.chatTeamIndex; - int newChatPlayerIndex = msg.chatPlayerIndex; - string newChatLanguage = msg.targetLanguage; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] #1 about to broadcast nmtText chatText [%s] chatTeamIndex = %d, newChatPlayerIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,newChatText.c_str(),newChatTeamIndex,newChatPlayerIndex); - - if(newChatLanguage == "" || - newChatLanguage == connectionSlot->getNetworkPlayerLanguage()) { - - NetworkMessageText networkMessageText(newChatText.c_str(),newChatTeamIndex,newChatPlayerIndex,newChatLanguage); - broadcastMessage(&networkMessageText, connectionSlot->getPlayerIndex(),index); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] after broadcast nmtText chatText [%s] chatTeamIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,newChatText.c_str(),newChatTeamIndex); - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] index = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,index); - // Its possible that the slot is disconnected here - // so check the original pointer again - if(slots[index] != NULL) { - slots[index]->clearChatInfo(); - } - } - catch(const exception &ex) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] error detected [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - errorMsgList.push_back(ex.what()); - } - } - } -} - -void ServerInterface::dispatchPendingMarkCellMessages(std::vector &errorMsgList) { - for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { - - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); - ConnectionSlot* connectionSlot= slots[index]; - - if(connectionSlot != NULL && - connectionSlot->getMarkedCellList(false).empty() == false) { - - try { - std::vector chatText = connectionSlot->getMarkedCellList(true); - for(int chatIdx = 0; - exitServer == false && slots[index] != NULL && - chatIdx < (int)chatText.size(); chatIdx++) { - - connectionSlot= slots[index]; - if(connectionSlot != NULL) { - MarkedCell msg(chatText[chatIdx]); - this->addMarkedCell(msg); - - NetworkMessageMarkCell networkMessageMarkCell(msg.getTargetPos(),msg.getFactionIndex(),msg.getNote(),msg.getPlayerIndex()); - broadcastMessage(&networkMessageMarkCell, connectionSlot->getPlayerIndex(),index); - //if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] after broadcast nmtText chatText [%s] chatTeamIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,newChatText.c_str(),newChatTeamIndex); - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] i = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,index); - // Its possible that the slot is disconnected here - // so check the original pointer again - if(slots[index] != NULL) { - slots[index]->clearMarkedCellList(); - } - } - catch(const exception &ex) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] error detected [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - errorMsgList.push_back(ex.what()); - } - } - } -} -void ServerInterface::dispatchPendingHighlightCellMessages(std::vector &errorMsgList) { - for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { - - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); - ConnectionSlot* connectionSlot= slots[index]; - if(connectionSlot != NULL && - connectionSlot->getHighlightedCellList(false).empty() == false) { - - try { - std::vector highlightedCells = connectionSlot->getHighlightedCellList(true); - for(int chatIdx = 0; - exitServer == false && slots[index] != NULL && - chatIdx < (int)highlightedCells.size(); chatIdx++) { - - connectionSlot= slots[index]; - if(connectionSlot != NULL) { - MarkedCell msg(highlightedCells[chatIdx]); - this->setHighlightedCell(msg); - - NetworkMessageHighlightCell networkMessageHighlightCell(msg.getTargetPos(),msg.getFactionIndex()); - broadcastMessage(&networkMessageHighlightCell, connectionSlot->getPlayerIndex(),index); - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] index = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,index); - // Its possible that the slot is disconnected here - // so check the original pointer again - if(slots[index] != NULL) { - slots[index]->clearHighlightedCellList(); - } - } - catch(const exception &ex) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] error detected [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - errorMsgList.push_back(ex.what()); - } - } - } -} - -void ServerInterface::dispatchPendingUnMarkCellMessages(std::vector &errorMsgList) { - for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { - - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); - ConnectionSlot* connectionSlot= slots[index]; - if(connectionSlot != NULL && - connectionSlot->getUnMarkedCellList(false).empty() == false) { - - try { - std::vector chatText = connectionSlot->getUnMarkedCellList(true); - for(int chatIdx = 0; - exitServer == false && slots[index] != NULL && - chatIdx < (int)chatText.size(); chatIdx++) { - - connectionSlot = slots[index]; - if(connectionSlot != NULL) { - UnMarkedCell msg(chatText[chatIdx]); - this->addUnMarkedCell(msg); - - NetworkMessageUnMarkCell networkMessageMarkCell(msg.getTargetPos(),msg.getFactionIndex()); - broadcastMessage(&networkMessageMarkCell, connectionSlot->getPlayerIndex(),index); - //if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] after broadcast nmtText chatText [%s] chatTeamIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,newChatText.c_str(),newChatTeamIndex); - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] i = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,index); - // Its possible that the slot is disconnected here - // so check the original pointer again - if(slots[index] != NULL) { - slots[index]->clearUnMarkedCellList(); - } - } - catch(const exception &ex) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] error detected [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - errorMsgList.push_back(ex.what()); - } - } - } +bool ServerInterface::signalClientReceiveCommands( + ConnectionSlot *connectionSlot, int slotIndex, bool socketTriggered, + ConnectionSlotEvent &event) { + bool slotSignalled = false; + + event.eventType = eReceiveSocketData; + event.networkMessage = NULL; + event.connectionSlot = connectionSlot; + event.socketTriggered = socketTriggered; + event.triggerId = slotIndex; + event.eventId = getNextEventId(); + + if (connectionSlot != NULL) { + if (socketTriggered == true || connectionSlot->isConnected() == false) { + connectionSlot->signalUpdate(&event); + slotSignalled = true; + } + } + return slotSignalled; } -void ServerInterface::checkForAutoResumeForLaggingClients() { - if (gameSettings.getNetworkPauseGameForLaggedClients() == true && - this->clientsAutoPausedDueToLag == true && - this->clientsAutoPausedDueToLagTimer.getMillis() >= MAX_CLIENT_WAIT_SECONDS_FOR_PAUSE_MILLISECONDS) { - - //printf("this->clientsAutoPausedDueToLag: %d [%lld]\n",this->clientsAutoPausedDueToLag,(long long)this->clientsAutoPausedDueToLagTimer.getMillis()); - if (this->clientLagCallbackInterface != NULL) { - - this->clientsAutoPausedDueToLag = false; - this->clientLagCallbackInterface->clientLagHandler(-1, false); +void ServerInterface::signalClientsToRecieveData( + std::map &socketTriggeredList, + std::map &eventList, + std::map &mapSlotSignalledList) { + // printf("====================================In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + // printf("Signal clients get new data\n"); + const bool newThreadManager = + Config::getInstance().getBool("EnableNewThreadManager", "false"); + if (newThreadManager == true) { + masterController.clearSlaves(true); + std::vector slaveThreadList; + for (int i = 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i], CODE_AT_LINE_X(i)); + ConnectionSlot *connectionSlot = slots[i]; + + bool socketTriggered = false; + + if (connectionSlot != NULL) { + PLATFORM_SOCKET clientSocket = connectionSlot->getSocketId(); + if (Socket::isSocketValid(&clientSocket)) { + socketTriggered = socketTriggeredList[clientSocket]; + } else if (this->getGameHasBeenInitiated() == true && + this->getAllowInGameConnections() == true) { + socketTriggeredList[clientSocket] = true; + socketTriggered = socketTriggeredList[clientSocket]; + } + } + ConnectionSlotEvent &event = eventList[i]; + event.eventType = eReceiveSocketData; + event.networkMessage = NULL; + event.connectionSlot = connectionSlot; + event.socketTriggered = socketTriggered; + event.triggerId = i; + event.eventId = getNextEventId(); + + if (connectionSlot != NULL) { + if (socketTriggered == true || connectionSlot->isConnected() == false) { + if (connectionSlot->getWorkerThread() != NULL) { + slaveThreadList.push_back(connectionSlot->getWorkerThread()); + mapSlotSignalledList[i] = true; + } + } + } + } + masterController.setSlaves(slaveThreadList); + masterController.signalSlaves(&eventList); + } else { + for (int index = 0; + exitServer == false && index < GameConstants::maxPlayers; ++index) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index], + CODE_AT_LINE_X(index)); + ConnectionSlot *connectionSlot = slots[index]; + + if (connectionSlot != NULL) { + bool socketTriggered = false; + PLATFORM_SOCKET clientSocket = connectionSlot->getSocketId(); + if (Socket::isSocketValid(&clientSocket)) { + socketTriggered = socketTriggeredList[clientSocket]; + } - this->clientsAutoPausedDueToLagTimer.reset(); - this->clientsAutoPausedDueToLagTimer.stop(); - this->clientsAutoPausedDueToLagTimer.start(); - } - } + ConnectionSlotEvent &event = eventList[index]; + bool socketSignalled = signalClientReceiveCommands( + connectionSlot, index, socketTriggered, event); + if (connectionSlot != NULL && socketTriggered == true) { + mapSlotSignalledList[index] = socketSignalled; + } + } + } + } } -void ServerInterface::update() { - //printf("\nServerInterface::update -- A\n"); - - std::vector errorMsgList; - try { - // The first thing we will do is check all clients to ensure they have - // properly identified themselves within the alloted time period - validateConnectedClients(); - - //printf("\nServerInterface::update -- B\n"); - - processTextMessageQueue(); - processBroadCastMessageQueue(); - - checkForAutoResumeForLaggingClients(); - - //printf("\nServerInterface::update -- C\n"); - - std::map socketTriggeredList; - //update all slots - updateSocketTriggeredList(socketTriggeredList); - - //printf("\nServerInterface::update -- D\n"); - - if(gameHasBeenInitiated == false || - socketTriggeredList.empty() == false) { - //printf("\nServerInterface::update -- E\n"); - - std::map eventList; - - bool hasData = false; - if(gameHasBeenInitiated == false) { - hasData = Socket::hasDataToRead(socketTriggeredList); - } - else { - hasData = true; - } - - if(hasData && SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] hasData == true\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); - - if(gameHasBeenInitiated == false || hasData == true) { - //printf("START Server update #2\n"); - std::map mapSlotSignalledList; - - // Step #1 tell all connection slot worker threads to receive socket data - if(gameHasBeenInitiated == false) { - signalClientsToRecieveData(socketTriggeredList, eventList, mapSlotSignalledList); - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] ============ Step #2\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //printf("START Server update #2\n"); - if(gameHasBeenInitiated == false || hasData == true) { - //printf("START Server update #3\n"); - - // Step #2 check all connection slot worker threads for completed status - if(gameHasBeenInitiated == false) { - checkForCompletedClients(mapSlotSignalledList,errorMsgList, eventList); - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] ============ Step #3\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //printf("START Server update #4\n"); - //printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - // Step #3 check clients for any lagging scenarios and try to deal with them - if(gameHasBeenInitiated == false) { - checkForLaggingClients(mapSlotSignalledList, eventList, socketTriggeredList,errorMsgList); - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] ============ Step #4\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //printf("START Server update #5\n"); - //printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - // Step #4 dispatch network commands to the pending list so that they are done in proper order - executeNetworkCommandsFromClients(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] ============ Step #5\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //printf("START Server update #6\n"); - //printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - // Step #5 dispatch pending chat messages - dispatchPendingChatMessages(errorMsgList); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - dispatchPendingMarkCellMessages(errorMsgList); - dispatchPendingUnMarkCellMessages(errorMsgList); - - dispatchPendingHighlightCellMessages(errorMsgList); - - if(gameHasBeenInitiated == true && - difftime((long int)time(NULL),gameStartTime) >= LAG_CHECK_GRACE_PERIOD && - difftime((long int)time(NULL),lastGlobalLagCheckTime) >= LAG_CHECK_INTERVAL_PERIOD) { - - std::map mapSlotSignalledList; - checkForLaggingClients(mapSlotSignalledList, eventList, socketTriggeredList,errorMsgList); - } - //printf("START Server update #7\n"); - } - else if(gameHasBeenInitiated == true && - difftime((long int)time(NULL),gameStartTime) >= LAG_CHECK_GRACE_PERIOD && - difftime((long int)time(NULL),lastGlobalLagCheckTime) >= LAG_CHECK_INTERVAL_PERIOD) { - - //printf("Skip network data process because hasData == false\n"); - //printf("START Server update #8\n"); - - std::map mapSlotSignalledList; - checkForLaggingClients(mapSlotSignalledList, eventList, socketTriggeredList,errorMsgList); - } - //printf("START Server update #9\n"); - } - else if(gameHasBeenInitiated == true && - difftime((long int)time(NULL),gameStartTime) >= LAG_CHECK_GRACE_PERIOD && - difftime((long int)time(NULL),lastGlobalLagCheckTime) >= LAG_CHECK_INTERVAL_PERIOD) { - - //printf("\nServerInterface::update -- E1\n"); - //printf("START Server update #10\n"); - - std::map mapSlotSignalledList; - checkForLaggingClients(mapSlotSignalledList, eventList, socketTriggeredList,errorMsgList); - } - //printf("START Server update #11\n"); - } - else if(gameHasBeenInitiated == true && - difftime((long int)time(NULL),gameStartTime) >= LAG_CHECK_GRACE_PERIOD && - difftime((long int)time(NULL),lastGlobalLagCheckTime) >= LAG_CHECK_INTERVAL_PERIOD) { - - //printf("\nServerInterface::update -- F\n"); - //printf("START Server update #12\n"); - - std::map eventList; - std::map mapSlotSignalledList; - - checkForLaggingClients(mapSlotSignalledList, eventList, socketTriggeredList,errorMsgList); - } - //printf("START Server update #13\n"); - - // Check if we need to switch masterserver admin to a new player because original admin disconnected - if(gameHasBeenInitiated == true && - this->gameSettings.getMasterserver_admin() > 0) { - - bool foundAdminSlot = false; - int iFirstConnectedSlot = -1; - for(int index = 0; index < GameConstants::maxPlayers; ++index) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); - if(slots[index] != NULL && slots[index]->isConnected() == true) { - if(iFirstConnectedSlot < 0) { - iFirstConnectedSlot = index; - } - if(this->gameSettings.getMasterserver_admin() == slots[index]->getSessionKey()) { - foundAdminSlot = true; - break; - } - } - } - - if(foundAdminSlot == false && iFirstConnectedSlot >= 0) { - printf("Switching masterserver admin to slot#%d...\n",iFirstConnectedSlot); - - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[iFirstConnectedSlot],CODE_AT_LINE_X(iFirstConnectedSlot)); - if(slots[iFirstConnectedSlot] != NULL) { - string sMsg = "Switching player to admin mode: " + slots[iFirstConnectedSlot]->getName(); - sendTextMessage(sMsg,-1, true,""); - - this->gameSettings.setMasterserver_admin(slots[iFirstConnectedSlot]->getSessionKey()); - this->gameSettings.setMasterserver_admin_faction_index(slots[iFirstConnectedSlot]->getPlayerIndex()); - - safeMutexSlot.ReleaseLock(); - this->broadcastGameSetup(&this->gameSettings); - } - } - } - //printf("\nServerInterface::update -- G\n"); - //printf("START Server update #14\n"); - - checkListenerSlots(); - - //printf("START Server update #15\n"); - } - catch(const exception &ex) { - //printf("\nServerInterface::update -- H\n"); - - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] error detected [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - errorMsgList.push_back(ex.what()); - } - - if(errorMsgList.empty() == false){ - for(int iErrIdx = 0; iErrIdx < (int)errorMsgList.size(); ++iErrIdx) { - string &sErr = errorMsgList[iErrIdx]; - if(sErr != "") { - DisplayErrorMessage(sErr); - } - } - } +void ServerInterface::checkForCompletedClientsUsingThreadManager( + std::map &mapSlotSignalledList, + std::vector &errorMsgList) { + + masterController.waitTillSlavesTrigger( + MAX_SLOT_THREAD_WAIT_TIME_MILLISECONDS); + masterController.clearSlaves(true); + + for (int i = 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i], CODE_AT_LINE_X(i)); + + ConnectionSlot *connectionSlot = slots[i]; + if (connectionSlot != NULL && mapSlotSignalledList[i] == true) { + + try { + std::vector errorList = + connectionSlot->getThreadErrorList(); + // Collect any collected errors from threads + if (errorList.empty() == false) { + for (int iErrIdx = 0; iErrIdx < (int)errorList.size(); ++iErrIdx) { + string &sErr = errorList[iErrIdx]; + + if (sErr != "") { + errorMsgList.push_back(sErr); + } + } + connectionSlot->clearThreadErrorList(); + } + } catch (const exception &ex) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] error detected [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + + errorMsgList.push_back(ex.what()); + } + } + } } -void ServerInterface::updateKeyframe(int frameCount) { - currentFrameCount = frameCount; - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] currentFrameCount = %d, requestedCommands.size() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,currentFrameCount,requestedCommands.size()); - - NetworkMessageCommandList networkMessageCommandList(frameCount); - for(int index = 0; index < GameConstants::maxPlayers; ++index) { - networkMessageCommandList.setNetworkPlayerFactionCRC(index,this->getNetworkPlayerFactionCRC(index)); - } - - while(requestedCommands.empty() == false) { - // First add the command to the broadcast list (for all clients) - if(networkMessageCommandList.addCommand(&requestedCommands.back())) { - // Add the command to the local server command list - pendingCommands.push_back(requestedCommands.back()); - requestedCommands.pop_back(); - } - else { - break; - } - } - - try { - // Possible cause of out of synch since we have more commands that need - // to be sent in this frame - if(requestedCommands.empty() == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] WARNING / ERROR, requestedCommands.size() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,requestedCommands.size()); - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] WARNING / ERROR, requestedCommands.size() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,requestedCommands.size()); - - string sMsg = "may go out of synch: server requestedCommands.size() = " + intToStr(requestedCommands.size()); - sendTextMessage(sMsg,-1, true,""); - } - - // broadcast commands - // If we have more than 0 commands to send, automatically broadcast them - bool sendBroadcastMessage = (networkMessageCommandList.getCommandCount() > 0); - if(sendBroadcastMessage == false) { - - // Is auto pause due to lag NOT enabled - if(this->getClientsAutoPausedDueToLag() == false) { - - // ****NOTE: - // We always need to broadcast when not pause as clients - // look for broadcasts every network frame. - sendBroadcastMessage = true; - } - // Auto pause is enabled due to client lagging, only send empty command - // broadcasts every MAX_EMPTY_NETWORK_COMMAND_LIST_BROADCAST_INTERVAL_MILLISECONDS - else if(this->getClientsAutoPausedDueToLag() == true && - (lastBroadcastCommandsTimer.isStarted() == false || - lastBroadcastCommandsTimer.getMillis() >= MAX_EMPTY_NETWORK_COMMAND_LIST_BROADCAST_INTERVAL_MILLISECONDS)) { - - sendBroadcastMessage = true; - } - } - - if(sendBroadcastMessage == true) { - - if(lastBroadcastCommandsTimer.isStarted() == false) { - lastBroadcastCommandsTimer.start(); - } - else { - lastBroadcastCommandsTimer.stop(); - lastBroadcastCommandsTimer.reset(); - lastBroadcastCommandsTimer.start(); - } - broadcastMessage(&networkMessageCommandList); - } - } - catch(const exception &ex) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] error detected [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - DisplayErrorMessage(ex.what()); - } -} - -bool ServerInterface::shouldDiscardNetworkMessage(NetworkMessageType networkMessageType, - ConnectionSlot *connectionSlot) { - bool discard = false; - if(connectionSlot != NULL) { - switch(networkMessageType) { - case nmtIntro: - { - discard = true; - NetworkMessageIntro msg = NetworkMessageIntro(); - connectionSlot->receiveMessage(&msg); - } - break; - case nmtPing: - { - discard = true; - NetworkMessagePing msg = NetworkMessagePing(); - connectionSlot->receiveMessage(&msg); - lastPingInfo = msg; - } - break; - - case nmtLaunch: - { - discard = true; - NetworkMessageLaunch msg = NetworkMessageLaunch(); - connectionSlot->receiveMessage(&msg); - } - break; - case nmtText: - { - discard = true; - NetworkMessageText netMsg = NetworkMessageText(); - connectionSlot->receiveMessage(&netMsg); - - ChatMsgInfo msg(netMsg.getText().c_str(),netMsg.getTeamIndex(),netMsg.getPlayerIndex(),netMsg.getTargetLanguage()); - this->addChatInfo(msg); - - string newChatText = msg.chatText.c_str(); - //string newChatSender = msg.chatSender.c_str(); - int newChatTeamIndex = msg.chatTeamIndex; - int newChatPlayerIndex = msg.chatPlayerIndex; - string newChatLanguage = msg.targetLanguage.c_str(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] #1 about to broadcast nmtText chatText [%s] chatTeamIndex = %d, newChatPlayerIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,newChatText.c_str(),newChatTeamIndex,newChatPlayerIndex); - - NetworkMessageText networkMessageText(newChatText.c_str(),newChatTeamIndex,newChatPlayerIndex,newChatLanguage); - broadcastMessage(&networkMessageText, connectionSlot->getPlayerIndex()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] after broadcast nmtText chatText [%s] chatTeamIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,newChatText.c_str(),newChatTeamIndex); - - } - break; - - case nmtMarkCell: - { - discard = true; - NetworkMessageMarkCell networkMessageMarkCell; - connectionSlot->receiveMessage(&networkMessageMarkCell); - - MarkedCell msg(networkMessageMarkCell.getTarget(), - networkMessageMarkCell.getFactionIndex(), - networkMessageMarkCell.getText().c_str(), - networkMessageMarkCell.getPlayerIndex()); - - this->addMarkedCell(msg); - - NetworkMessageMarkCell networkMessageMarkCellBroadcast( - networkMessageMarkCell.getTarget(), - networkMessageMarkCell.getFactionIndex(), - networkMessageMarkCell.getText().c_str(), - networkMessageMarkCell.getPlayerIndex()); - broadcastMessage(&networkMessageMarkCellBroadcast, connectionSlot->getPlayerIndex()); - - //if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] after broadcast nmtMarkCell chatText [%s] chatTeamIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,newChatText.c_str(),newChatTeamIndex); - - } - break; - - case nmtUnMarkCell: - { - discard = true; - NetworkMessageUnMarkCell networkMessageMarkCell; - connectionSlot->receiveMessage(&networkMessageMarkCell); - - UnMarkedCell msg(networkMessageMarkCell.getTarget(), - networkMessageMarkCell.getFactionIndex()); - - this->addUnMarkedCell(msg); - - NetworkMessageUnMarkCell networkMessageMarkCellBroadcast( - networkMessageMarkCell.getTarget(), - networkMessageMarkCell.getFactionIndex()); - broadcastMessage(&networkMessageMarkCellBroadcast, connectionSlot->getPlayerIndex()); - - //if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] after broadcast nmtMarkCell chatText [%s] chatTeamIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,newChatText.c_str(),newChatTeamIndex); - - } - break; - case nmtHighlightCell: - { - discard = true; - NetworkMessageHighlightCell networkMessageHighlightCell; - connectionSlot->receiveMessage(&networkMessageHighlightCell); - - MarkedCell msg(networkMessageHighlightCell.getTarget(), - networkMessageHighlightCell.getFactionIndex(), - "none",-1); - - this->setHighlightedCell(msg); - - NetworkMessageHighlightCell networkMessageHighlightCellBroadcast( - networkMessageHighlightCell.getTarget(), - networkMessageHighlightCell.getFactionIndex()); - broadcastMessage(&networkMessageHighlightCellBroadcast, connectionSlot->getPlayerIndex()); - - //if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] after broadcast nmtMarkCell chatTeamIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,newChatTeamIndex); - - } - break; - - case nmtSynchNetworkGameData: - { - discard = true; - NetworkMessageSynchNetworkGameData msg = NetworkMessageSynchNetworkGameData(); - connectionSlot->receiveMessage(&msg); - } - break; - case nmtSynchNetworkGameDataStatus: - { - discard = true; - NetworkMessageSynchNetworkGameDataStatus msg = NetworkMessageSynchNetworkGameDataStatus(); - connectionSlot->receiveMessage(&msg); - } - break; - case nmtSynchNetworkGameDataFileCRCCheck: - { - discard = true; - NetworkMessageSynchNetworkGameDataFileCRCCheck msg = NetworkMessageSynchNetworkGameDataFileCRCCheck(); - connectionSlot->receiveMessage(&msg); - } - break; - case nmtSynchNetworkGameDataFileGet: - { - discard = true; - NetworkMessageSynchNetworkGameDataFileGet msg = NetworkMessageSynchNetworkGameDataFileGet(); - connectionSlot->receiveMessage(&msg); - } - break; - case nmtSwitchSetupRequest: - { - discard = true; - SwitchSetupRequest msg = SwitchSetupRequest(); - connectionSlot->receiveMessage(&msg); - } - break; - case nmtPlayerIndexMessage: - { - discard = true; - PlayerIndexMessage msg = PlayerIndexMessage(0); - connectionSlot->receiveMessage(&msg); - } - break; - } - } - return discard; +void ServerInterface::checkForCompletedClientsUsingLoop( + std::map &mapSlotSignalledList, + std::vector &errorMsgList, + std::map &eventList) { + + // time_t waitForThreadElapsed = time(NULL); + Chrono waitForThreadElapsed(true); + + std::map slotsCompleted; + for (bool threadsDone = false; exitServer == false && threadsDone == false && + waitForThreadElapsed.getMillis() <= + MAX_SLOT_THREAD_WAIT_TIME_MILLISECONDS;) { + + threadsDone = true; + // Examine all threads for completion of delegation + for (int index = 0; + exitServer == false && index < GameConstants::maxPlayers; ++index) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index], + CODE_AT_LINE_X(index)); + + ConnectionSlot *connectionSlot = slots[index]; + if (connectionSlot != NULL && connectionSlot->isConnected() == true && + mapSlotSignalledList[index] == true && + connectionSlot->getJoinGameInProgress() == false && + slotsCompleted.find(index) == slotsCompleted.end()) { + + try { + std::vector errorList = + connectionSlot->getThreadErrorList(); + // Collect any collected errors from threads + if (errorList.empty() == false) { + + for (int iErrIdx = 0; iErrIdx < (int)errorList.size(); ++iErrIdx) { + + string &sErr = errorList[iErrIdx]; + if (sErr != "") { + errorMsgList.push_back(sErr); + } + } + connectionSlot->clearThreadErrorList(); + } + + // Not done waiting for data yet + bool updateFinished = + (connectionSlot != NULL + ? connectionSlot->updateCompleted(&eventList[index]) + : true); + if (updateFinished == false) { + threadsDone = false; + break; + } else { + slotsCompleted[index] = true; + } + } catch (const exception &ex) { + SystemFlags::OutputDebug( + SystemFlags::debugError, "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] error detected [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + + errorMsgList.push_back(ex.what()); + } + } + } + } } -void ServerInterface::waitUntilReady(Checksum *checksum) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s] START\n",__FUNCTION__); - Logger & logger = Logger::getInstance(); - gameHasBeenInitiated = true; - Chrono chrono; - chrono.start(); - - bool allReady = false; - - if(Config::getInstance().getBool("EnableGameServerLoadCancel","false") == true) { - logger.setCancelLoadingEnabled(true); - } - - Lang &lang = Lang::getInstance(); - uint64 waitLoopIterationCount = 0; - uint64 MAX_LOOP_COUNT_BEFORE_SLEEP = 10; - MAX_LOOP_COUNT_BEFORE_SLEEP = Config::getInstance().getInt("NetworkServerLoopGameLoadingCap",intToStr(MAX_LOOP_COUNT_BEFORE_SLEEP).c_str()); - if(MAX_LOOP_COUNT_BEFORE_SLEEP == 0) { - MAX_LOOP_COUNT_BEFORE_SLEEP = 1; - } - int sleepMillis = Config::getInstance().getInt("NetworkServerLoopGameLoadingCapSleepMillis","10"); - int64 lastStatusUpdate = 0; - - while(exitServer == false && - allReady == false && - logger.getCancelLoading() == false) { - - waitLoopIterationCount++; - if(waitLoopIterationCount > 0 && - waitLoopIterationCount % MAX_LOOP_COUNT_BEFORE_SLEEP == 0) { - - sleep(sleepMillis); - waitLoopIterationCount = 0; - } - vector waitingForHosts; - allReady= true; - for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { - - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); - ConnectionSlot* connectionSlot= slots[index]; - if(connectionSlot != NULL && connectionSlot->isConnected() == true) { - if(connectionSlot->isReady() == false) { - - NetworkMessageType networkMessageType= connectionSlot->getNextMessageType(); - - // consume old messages from the lobby - bool discarded = shouldDiscardNetworkMessage(networkMessageType,connectionSlot); - if(discarded == false) { - - NetworkMessageReady networkMessageReady; - if(networkMessageType == nmtReady && - connectionSlot->receiveMessage(&networkMessageReady)) { - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s] networkMessageType==nmtReady\n",__FUNCTION__); - - connectionSlot->setReady(); - connectionSlot->setGameStarted(true); - } - else if(networkMessageType != nmtInvalid) { - string sErr = "Unexpected network message: " + intToStr(networkMessageType); - sendTextMessage(sErr,-1, true,"",index); - DisplayErrorMessage(sErr); - logger.setCancelLoading(false); - return; - } - } - waitingForHosts.push_back(connectionSlot->getName()); - allReady= false; - } - } - } - - //check for timeout - if(allReady == false) { - if(chrono.getMillis() > readyWaitTimeout) { - Lang &lang= Lang::getInstance(); - const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); - for(unsigned int langIndex = 0; langIndex < languageList.size(); ++langIndex) { - string sErr = "Timeout waiting for clients."; - if(lang.hasString("TimeoutWaitingForClients") == true) { - sErr = lang.getString("TimeoutWaitingForClients",languageList[langIndex]); - } - bool localEcho = lang.isLanguageLocal(languageList[langIndex]); - sendTextMessage(sErr,-1, localEcho, languageList[langIndex]); - if(localEcho == true) { - DisplayErrorMessage(sErr); - } - } - logger.setCancelLoading(false); - return; - } - else { - if(chrono.getMillis() - lastStatusUpdate > 200) { - lastStatusUpdate = chrono.getMillis(); - - string waitForHosts = ""; - for(int hostIndex = 0; hostIndex < (int)waitingForHosts.size(); hostIndex++) { - if(waitForHosts != "") { - waitForHosts += ", "; - } - waitForHosts += waitingForHosts[hostIndex]; - } - - char szBuf[8096]=""; - string updateTextFormat = lang.getString("NetworkGameServerLoadStatus"); - if(updateTextFormat == "" || - updateTextFormat[0] == '?') { - - updateTextFormat = "Waiting for network: %lld seconds elapsed (maximum wait time: %d seconds)"; - } - snprintf(szBuf,8096,updateTextFormat.c_str(),(long long int)(chrono.getMillis() / 1000),int(readyWaitTimeout / 1000)); - - char szBuf1[8096]=""; - string statusTextFormat = lang.getString("NetworkGameStatusWaiting"); - if(statusTextFormat == "" || - statusTextFormat[0] == '?') { - - statusTextFormat = "Waiting for players: %s"; - } - snprintf(szBuf1,8096,statusTextFormat.c_str(),waitForHosts.c_str()); - - logger.add(szBuf, true, szBuf1); - - uint32 loadingStatus = nmls_NONE; - //send ready message after, so clients start delayed - for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); - ConnectionSlot *connectionSlot= slots[slotIndex]; - if(connectionSlot != NULL && connectionSlot->isConnected() == true) { - switch(slotIndex) { - case 0: - loadingStatus |= nmls_PLAYER1_CONNECTED; - if(connectionSlot->isReady()) { - loadingStatus |= nmls_PLAYER1_READY; - } - break; - case 1: - loadingStatus |= nmls_PLAYER2_CONNECTED; - if(connectionSlot->isReady()) { - loadingStatus |= nmls_PLAYER2_READY; - } - break; - case 2: - loadingStatus |= nmls_PLAYER3_CONNECTED; - if(connectionSlot->isReady()) { - loadingStatus |= nmls_PLAYER3_READY; - } - break; - case 3: - loadingStatus |= nmls_PLAYER4_CONNECTED; - if(connectionSlot->isReady()) { - loadingStatus |= nmls_PLAYER4_READY; - } - break; - case 4: - loadingStatus |= nmls_PLAYER5_CONNECTED; - if(connectionSlot->isReady()) { - loadingStatus |= nmls_PLAYER5_READY; - } - break; - case 5: - loadingStatus |= nmls_PLAYER6_CONNECTED; - if(connectionSlot->isReady()) { - loadingStatus |= nmls_PLAYER6_READY; - } - break; - case 6: - loadingStatus |= nmls_PLAYER7_CONNECTED; - if(connectionSlot->isReady()) { - loadingStatus |= nmls_PLAYER7_READY; - } - break; - case 7: - loadingStatus |= nmls_PLAYER8_CONNECTED; - if(connectionSlot->isReady()) { - loadingStatus |= nmls_PLAYER8_READY; - } - break; - } - } - } - - // send loading status message - for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); - ConnectionSlot* connectionSlot= slots[slotIndex]; - if(connectionSlot != NULL && connectionSlot->isConnected() == true) { - NetworkMessageLoadingStatus networkMessageLoadingStatus(loadingStatus); - connectionSlot->sendMessage(&networkMessageLoadingStatus); - } - } - - sleep(0); - } - } - } - - Shared::Platform::Window::handleEvent(); - } - - if(logger.getCancelLoading() == true) { - Lang &lang= Lang::getInstance(); - const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); - for(unsigned int langIndex = 0; langIndex < languageList.size(); ++langIndex) { - - string sErr = lang.getString("GameCancelledByUser",languageList[langIndex]); - bool localEcho = lang.isLanguageLocal(languageList[langIndex]); - sendTextMessage(sErr,-1, localEcho,languageList[langIndex]); - - if(localEcho == true) { - DisplayErrorMessage(sErr); - } - } - quitGame(true); - logger.setCancelLoading(false); - return; - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s] PART B (telling client we are ready!\n",__FUNCTION__); - try { - //send ready message after, so clients start delayed - for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { - - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); - ConnectionSlot* connectionSlot= slots[slotIndex]; - if(connectionSlot != NULL && connectionSlot->isConnected() == true) { - NetworkMessageReady networkMessageReady(checksum->getSum()); - connectionSlot->sendMessage(&networkMessageReady); - connectionSlot->setGameStarted(true); - } - } - - gameStartTime = time(NULL); - } - catch(const exception &ex) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] error detected [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - DisplayErrorMessage(ex.what()); - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s] END\n",__FUNCTION__); +std::string ServerInterface::getIpAddress(bool mutexLock) { + string result = serverSocket.getIpAddress(); + return result; } -void ServerInterface::processBroadCastMessageQueue() { - MutexSafeWrapper safeMutexSlot(broadcastMessageQueueThreadAccessor,CODE_AT_LINE); - if(broadcastMessageQueue.empty() == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] broadcastMessageQueue.size() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,broadcastMessageQueue.size()); - for(int index = 0; index < (int)broadcastMessageQueue.size(); ++index) { - pair &item = broadcastMessageQueue[index]; - if(item.first != NULL) { - this->broadcastMessage(item.first,item.second); - delete item.first; - } - item.first = NULL; - } - broadcastMessageQueue.clear(); - } -} - -void ServerInterface::queueBroadcastMessage(NetworkMessage *networkMessage, int excludeSlot) { - MutexSafeWrapper safeMutexSlot(broadcastMessageQueueThreadAccessor,CODE_AT_LINE); - pair item; - item.first = networkMessage; - item.second = excludeSlot; - broadcastMessageQueue.push_back(item); +void ServerInterface::setClientLagCallbackInterface( + ClientLagCallbackInterface *intf) { + this->clientLagCallbackInterface = intf; } -void ServerInterface::processTextMessageQueue() { - MutexSafeWrapper safeMutexSlot(textMessageQueueThreadAccessor,CODE_AT_LINE); - if(textMessageQueue.empty() == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] textMessageQueue.size() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,textMessageQueue.size()); - for(int index = 0; index < (int)textMessageQueue.size(); ++index) { - TextMessageQueue &item = textMessageQueue[index]; - sendTextMessage(item.text, item.teamIndex, item.echoLocal, item.targetLanguage); - } - textMessageQueue.clear(); - } +bool ServerInterface::getClientsAutoPausedDueToLag() { + return this->clientsAutoPausedDueToLag; } -void ServerInterface::queueTextMessage(const string & text, int teamIndex, - bool echoLocal, string targetLanguage) { - //printf("Line: %d text [%s]\n",__LINE__,text.c_str()); - - MutexSafeWrapper safeMutexSlot(textMessageQueueThreadAccessor,CODE_AT_LINE); - TextMessageQueue item; - item.text = text; - item.teamIndex = teamIndex; - item.echoLocal = echoLocal; - item.targetLanguage = targetLanguage; - textMessageQueue.push_back(item); +void ServerInterface::checkForCompletedClients( + std::map &mapSlotSignalledList, + std::vector &errorMsgList, + std::map &eventList) { + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + const bool newThreadManager = + Config::getInstance().getBool("EnableNewThreadManager", "false"); + if (newThreadManager == true) { + checkForCompletedClientsUsingThreadManager(mapSlotSignalledList, + errorMsgList); + } else { + checkForCompletedClientsUsingLoop(mapSlotSignalledList, errorMsgList, + eventList); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); } -void ServerInterface::sendTextMessage(const string & text, int teamIndex, - bool echoLocal,string targetLanguage) { - sendTextMessage(text, teamIndex, echoLocal, targetLanguage, -1); +void ServerInterface::checkForAutoPauseForLaggingClient( + int index, ConnectionSlot *connectionSlot) { + + if (gameSettings.getNetworkPauseGameForLaggedClients() == true && + this->clientsAutoPausedDueToLag == false) { + if (connectionSlot != NULL && connectionSlot->isConnected() == true) { + if (connectionSlot->getAutoPauseGameCountForLag() < + MAX_CLIENT_PAUSE_FOR_LAG_COUNT) { + if (this->clientLagCallbackInterface != NULL) { + + if (this->clientsAutoPausedDueToLagTimer.isStarted() == false || + this->clientsAutoPausedDueToLagTimer.getMillis() >= + MAX_CLIENT_WAIT_SECONDS_FOR_PAUSE_MILLISECONDS) { + + connectionSlot->incrementAutoPauseGameCountForLag(); + + this->clientsAutoPausedDueToLag = true; + if (this->clientLagCallbackInterface->clientLagHandler( + index, true) == false) { + connectionSlot->close(); + } else { + if (this->clientsAutoPausedDueToLagTimer.isStarted() == true) { + + this->clientsAutoPausedDueToLagTimer.reset(); + this->clientsAutoPausedDueToLagTimer.stop(); + } + this->clientsAutoPausedDueToLagTimer.start(); + } + } + } + } + } + } } -void ServerInterface::sendTextMessage(const string& text, int teamIndex, bool echoLocal, - string targetLanguage, int lockedSlotIndex) { - //printf("Line: %d text [%s] echoLocal = %d\n",__LINE__,text.c_str(),echoLocal); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] text [%s] teamIndex = %d, echoLocal = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,text.c_str(),teamIndex,echoLocal,lockedSlotIndex); - - NetworkMessageText networkMessageText(text, teamIndex, getHumanPlayerIndex(), targetLanguage); - broadcastMessage(&networkMessageText, -1, lockedSlotIndex); +void ServerInterface::checkForLaggingClients( + std::map &mapSlotSignalledList, + std::map &eventList, + std::map &socketTriggeredList, + std::vector &errorMsgList) { + bool lastGlobalLagCheckTimeUpdate = false; + if (gameHasBeenInitiated == true) { + + // time_t waitForClientsElapsed = time(NULL); + Chrono waitForClientsElapsed(true); + // time_t waitForThreadElapsed = time(NULL); + Chrono waitForThreadElapsed(true); + std::map slotsCompleted; + std::map slotsWarnedList; + + for (bool threadsDone = false; + exitServer == false && threadsDone == false && + waitForThreadElapsed.getMillis() <= + MAX_SLOT_THREAD_WAIT_TIME_MILLISECONDS;) { + + threadsDone = true; + // Examine all threads for completion of delegation + for (int index = 0; + exitServer == false && index < GameConstants::maxPlayers; ++index) { + // printf("#1 Check lag for i: %d\n",i); + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index], + CODE_AT_LINE_X(index)); + ConnectionSlot *connectionSlot = slots[index]; + + if (connectionSlot != NULL && connectionSlot->isConnected() == true && + connectionSlot->getSkipLagCheck() == false && + mapSlotSignalledList[index] == true && + slotsCompleted.find(index) == slotsCompleted.end()) { + + // printf("#2 Check lag for i: %d playerindex: %d name [%s] socket: + // %d\n",i,connectionSlot->getPlayerIndex(),connectionSlot->getName().c_str(),connectionSlot->getSocketId()); + try { + std::vector errorList = + connectionSlot->getThreadErrorList(); + // Show any collected errors from threads + if (errorList.empty() == false) { + for (int iErrIdx = 0; iErrIdx < (int)errorList.size(); + ++iErrIdx) { + string &sErr = errorList[iErrIdx]; + if (sErr != "") { + errorMsgList.push_back(sErr); + } + } + connectionSlot->clearThreadErrorList(); + } + + // Not done waiting for data yet + bool updateFinished = + (connectionSlot != NULL + ? connectionSlot->updateCompleted(&eventList[index]) + : true); + if (updateFinished == false) { + // printf("#2a Check lag for i: %d\n",i); + threadsDone = false; + break; + } else { + // New lag check + std::pair clientLagExceededOrWarned = + std::make_pair(false, false); + if (gameHasBeenInitiated == true && connectionSlot != NULL && + connectionSlot->isConnected() == true) { + clientLagExceededOrWarned = + clientLagCheck(connectionSlot, slotsWarnedList[index]); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] clientLagExceededOrWarned.first = " + "%d, clientLagExceededOrWarned.second = %d, " + "gameSettings.getNetworkPauseGameForLaggedClients() = " + "%d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, clientLagExceededOrWarned.first, + clientLagExceededOrWarned.second, + gameSettings.getNetworkPauseGameForLaggedClients()); + + if (clientLagExceededOrWarned.first == true) { + slotsWarnedList[index] = true; + } + } + // If the client has exceeded lag and the server wants + // to pause while they catch up, re-trigger the + // client reader thread + if ((clientLagExceededOrWarned.second == true && + gameSettings.getNetworkPauseGameForLaggedClients() == + true)) { + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s] Line: %d, clientLagExceededOrWarned.first = " + "%d, clientLagExceededOrWarned.second = %d, " + "waitForClientsElapsed.getMillis() = %d, " + "MAX_CLIENT_WAIT_SECONDS_FOR_PAUSE_MILLISECONDS = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, clientLagExceededOrWarned.first, + clientLagExceededOrWarned.second, + (int)waitForClientsElapsed.getMillis(), + MAX_CLIENT_WAIT_SECONDS_FOR_PAUSE_MILLISECONDS); + + checkForAutoPauseForLaggingClient(index, connectionSlot); + + slotsCompleted[index] = true; + } else { + slotsCompleted[index] = true; + } + } + } catch (const exception &ex) { + SystemFlags::OutputDebug( + SystemFlags::debugError, "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] error detected [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + errorMsgList.push_back(ex.what()); + } + } - if(echoLocal == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // printf("#3 Check lag for i: %d\n",i); + if (connectionSlot != NULL && connectionSlot->isConnected() == true && + connectionSlot->getSkipLagCheck() == false) { + // printf("#4 Check lag for i: %d\n",i); + + try { + if (gameHasBeenInitiated == true && + difftime((long int)time(NULL), gameStartTime) >= + LAG_CHECK_GRACE_PERIOD && + difftime((long int)time(NULL), lastGlobalLagCheckTime) >= + LAG_CHECK_INTERVAL_PERIOD) { + + // printf("\n\n\n^^^^^^^^^^^^^^ PART A\n\n\n"); + + // New lag check + std::pair clientLagExceededOrWarned = + std::make_pair(false, false); + if (connectionSlot != NULL && + connectionSlot->isConnected() == true) { + // printf("\n\n\n^^^^^^^^^^^^^^ PART B\n\n\n"); + + lastGlobalLagCheckTimeUpdate = true; + clientLagExceededOrWarned = + clientLagCheck(connectionSlot, slotsWarnedList[index]); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] clientLagExceededOrWarned.first = " + "%d, clientLagExceededOrWarned.second = %d, " + "gameSettings.getNetworkPauseGameForLaggedClients() = " + "%d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, clientLagExceededOrWarned.first, + clientLagExceededOrWarned.second, + gameSettings.getNetworkPauseGameForLaggedClients()); + + if (clientLagExceededOrWarned.first == true) { + slotsWarnedList[index] = true; + } + + // If the client has exceeded lag and the server wants + // to pause while they catch up, re-trigger the + // client reader thread + if ((clientLagExceededOrWarned.second == true && + gameSettings.getNetworkPauseGameForLaggedClients() == + true)) { + + if (SystemFlags::getSystemSettingType( + SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s] Line: %d, clientLagExceededOrWarned.first " + "= %d, clientLagExceededOrWarned.second = %d, " + "waitForClientsElapsed.getMillis() = %d, " + "MAX_CLIENT_WAIT_SECONDS_FOR_PAUSE_MILLISECONDS = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, clientLagExceededOrWarned.first, + clientLagExceededOrWarned.second, + (int)waitForClientsElapsed.getMillis(), + MAX_CLIENT_WAIT_SECONDS_FOR_PAUSE_MILLISECONDS); + + checkForAutoPauseForLaggingClient(index, connectionSlot); + } + } + } + } catch (const exception &ex) { + SystemFlags::OutputDebug( + SystemFlags::debugError, "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] error detected [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + errorMsgList.push_back(ex.what()); + } + } - ChatMsgInfo msg(text.c_str(),teamIndex,networkMessageText.getPlayerIndex(), targetLanguage); - this->addChatInfo(msg); - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // printf("#5 Check lag for i: %d\n",i); + } + } + } + if (lastGlobalLagCheckTimeUpdate == true) { + lastGlobalLagCheckTime = time(NULL); + } } -void ServerInterface::sendMarkCellMessage(Vec2i targetPos, int factionIndex, string note,int playerIndex) { - sendMarkCellMessage(targetPos, factionIndex, note, playerIndex, -1); +void ServerInterface::executeNetworkCommandsFromClients() { + if (gameHasBeenInitiated == true) { + for (int index = 0; + exitServer == false && index < GameConstants::maxPlayers; ++index) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index], + CODE_AT_LINE_X(index)); + ConnectionSlot *connectionSlot = slots[index]; + if (connectionSlot != NULL && connectionSlot->isConnected() == true) { + vector pendingList = + connectionSlot->getPendingNetworkCommandList(true); + if (pendingList.empty() == false) { + for (int idx = 0; + exitServer == false && idx < (int)pendingList.size(); ++idx) { + NetworkCommand &cmd = pendingList[idx]; + this->requestCommand(&cmd); + } + // printf("Executed: %d commands from slot: + // %d\n",pendingList.size(),index); + } + } + } + } } -void ServerInterface::sendMarkCellMessage(Vec2i targetPos, int factionIndex, string note, int playerIndex, int lockedSlotIndex) { - NetworkMessageMarkCell networkMessageMarkCell(targetPos,factionIndex, note, playerIndex); - broadcastMessage(&networkMessageMarkCell, -1, lockedSlotIndex); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); -} +void ServerInterface::dispatchPendingChatMessages( + std::vector &errorMsgList) { + for (int index = 0; exitServer == false && index < GameConstants::maxPlayers; + ++index) { + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index], + CODE_AT_LINE_X(index)); + ConnectionSlot *connectionSlot = slots[index]; + + if (connectionSlot != NULL && + connectionSlot->getChatTextList(false).empty() == false) { + try { + std::vector chatText = + connectionSlot->getChatTextList(true); + for (int chatIdx = 0; exitServer == false && slots[index] != NULL && + chatIdx < (int)chatText.size(); + chatIdx++) { + + connectionSlot = slots[index]; + if (connectionSlot != NULL) { + ChatMsgInfo msg(chatText[chatIdx]); + this->addChatInfo(msg); + + string newChatText = msg.chatText.c_str(); + int newChatTeamIndex = msg.chatTeamIndex; + int newChatPlayerIndex = msg.chatPlayerIndex; + string newChatLanguage = msg.targetLanguage; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] #1 about to broadcast nmtText chatText " + "[%s] chatTeamIndex = %d, newChatPlayerIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, newChatText.c_str(), newChatTeamIndex, + newChatPlayerIndex); + + if (newChatLanguage == "" || + newChatLanguage == connectionSlot->getNetworkPlayerLanguage()) { + + NetworkMessageText networkMessageText( + newChatText.c_str(), newChatTeamIndex, newChatPlayerIndex, + newChatLanguage); + broadcastMessage(&networkMessageText, + connectionSlot->getPlayerIndex(), index); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] after broadcast nmtText chatText [%s] " + "chatTeamIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, newChatText.c_str(), newChatTeamIndex); + } + } -void ServerInterface::sendHighlightCellMessage(Vec2i targetPos, int factionIndex) { - sendHighlightCellMessage(targetPos, factionIndex, -1); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d] index = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, index); + // Its possible that the slot is disconnected here + // so check the original pointer again + if (slots[index] != NULL) { + slots[index]->clearChatInfo(); + } + } catch (const exception &ex) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] error detected [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + errorMsgList.push_back(ex.what()); + } + } + } } -void ServerInterface::sendHighlightCellMessage(Vec2i targetPos, int factionIndex, int lockedSlotIndex) { - NetworkMessageHighlightCell networkMessageHighlightCell(targetPos,factionIndex); - broadcastMessage(&networkMessageHighlightCell, -1, lockedSlotIndex); +void ServerInterface::dispatchPendingMarkCellMessages( + std::vector &errorMsgList) { + for (int index = 0; exitServer == false && index < GameConstants::maxPlayers; + ++index) { + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index], + CODE_AT_LINE_X(index)); + ConnectionSlot *connectionSlot = slots[index]; + + if (connectionSlot != NULL && + connectionSlot->getMarkedCellList(false).empty() == false) { + + try { + std::vector chatText = + connectionSlot->getMarkedCellList(true); + for (int chatIdx = 0; exitServer == false && slots[index] != NULL && + chatIdx < (int)chatText.size(); + chatIdx++) { + + connectionSlot = slots[index]; + if (connectionSlot != NULL) { + MarkedCell msg(chatText[chatIdx]); + this->addMarkedCell(msg); + + NetworkMessageMarkCell networkMessageMarkCell( + msg.getTargetPos(), msg.getFactionIndex(), msg.getNote(), + msg.getPlayerIndex()); + broadcastMessage(&networkMessageMarkCell, + connectionSlot->getPlayerIndex(), index); + // if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s + // Line: %d] after broadcast nmtText chatText [%s] chatTeamIndex = + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,newChatText.c_str(),newChatTeamIndex); + } + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d] i = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, index); + // Its possible that the slot is disconnected here + // so check the original pointer again + if (slots[index] != NULL) { + slots[index]->clearMarkedCellList(); + } + } catch (const exception &ex) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] error detected [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + errorMsgList.push_back(ex.what()); + } + } + } } +void ServerInterface::dispatchPendingHighlightCellMessages( + std::vector &errorMsgList) { + for (int index = 0; exitServer == false && index < GameConstants::maxPlayers; + ++index) { + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index], + CODE_AT_LINE_X(index)); + ConnectionSlot *connectionSlot = slots[index]; + if (connectionSlot != NULL && + connectionSlot->getHighlightedCellList(false).empty() == false) { + + try { + std::vector highlightedCells = + connectionSlot->getHighlightedCellList(true); + for (int chatIdx = 0; exitServer == false && slots[index] != NULL && + chatIdx < (int)highlightedCells.size(); + chatIdx++) { + + connectionSlot = slots[index]; + if (connectionSlot != NULL) { + MarkedCell msg(highlightedCells[chatIdx]); + this->setHighlightedCell(msg); + + NetworkMessageHighlightCell networkMessageHighlightCell( + msg.getTargetPos(), msg.getFactionIndex()); + broadcastMessage(&networkMessageHighlightCell, + connectionSlot->getPlayerIndex(), index); + } + } -void ServerInterface::sendUnMarkCellMessage(Vec2i targetPos, int factionIndex) { - sendUnMarkCellMessage(targetPos, factionIndex, -1); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d] index = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, index); + // Its possible that the slot is disconnected here + // so check the original pointer again + if (slots[index] != NULL) { + slots[index]->clearHighlightedCellList(); + } + } catch (const exception &ex) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] error detected [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + errorMsgList.push_back(ex.what()); + } + } + } } -void ServerInterface::sendUnMarkCellMessage(Vec2i targetPos, int factionIndex, int lockedSlotIndex) { - NetworkMessageUnMarkCell networkMessageMarkCell(targetPos,factionIndex); - broadcastMessage(&networkMessageMarkCell, -1, lockedSlotIndex); +void ServerInterface::dispatchPendingUnMarkCellMessages( + std::vector &errorMsgList) { + for (int index = 0; exitServer == false && index < GameConstants::maxPlayers; + ++index) { + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index], + CODE_AT_LINE_X(index)); + ConnectionSlot *connectionSlot = slots[index]; + if (connectionSlot != NULL && + connectionSlot->getUnMarkedCellList(false).empty() == false) { + + try { + std::vector chatText = + connectionSlot->getUnMarkedCellList(true); + for (int chatIdx = 0; exitServer == false && slots[index] != NULL && + chatIdx < (int)chatText.size(); + chatIdx++) { + + connectionSlot = slots[index]; + if (connectionSlot != NULL) { + UnMarkedCell msg(chatText[chatIdx]); + this->addUnMarkedCell(msg); + + NetworkMessageUnMarkCell networkMessageMarkCell( + msg.getTargetPos(), msg.getFactionIndex()); + broadcastMessage(&networkMessageMarkCell, + connectionSlot->getPlayerIndex(), index); + // if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s + // Line: %d] after broadcast nmtText chatText [%s] chatTeamIndex = + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,newChatText.c_str(),newChatTeamIndex); + } + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d] i = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, index); + // Its possible that the slot is disconnected here + // so check the original pointer again + if (slots[index] != NULL) { + slots[index]->clearUnMarkedCellList(); + } + } catch (const exception &ex) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] error detected [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + errorMsgList.push_back(ex.what()); + } + } + } } -void ServerInterface::quitGame(bool userManuallyQuit) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - NetworkMessageQuit networkMessageQuit; - broadcastMessage(&networkMessageQuit); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +void ServerInterface::checkForAutoResumeForLaggingClients() { + if (gameSettings.getNetworkPauseGameForLaggedClients() == true && + this->clientsAutoPausedDueToLag == true && + this->clientsAutoPausedDueToLagTimer.getMillis() >= + MAX_CLIENT_WAIT_SECONDS_FOR_PAUSE_MILLISECONDS) { + + // printf("this->clientsAutoPausedDueToLag: %d + // [%lld]\n",this->clientsAutoPausedDueToLag,(long + // long)this->clientsAutoPausedDueToLagTimer.getMillis()); + if (this->clientLagCallbackInterface != NULL) { + + this->clientsAutoPausedDueToLag = false; + this->clientLagCallbackInterface->clientLagHandler(-1, false); + + this->clientsAutoPausedDueToLagTimer.reset(); + this->clientsAutoPausedDueToLagTimer.stop(); + this->clientsAutoPausedDueToLagTimer.start(); + } + } } -string ServerInterface::getNetworkStatus() { - Lang &lang = Lang::getInstance(); - string str = ""; - for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); - ConnectionSlot *connectionSlot= slots[index]; - - str += intToStr(index)+ ": "; - - if(connectionSlot!= NULL) { - if(connectionSlot->isConnected()) { - int clientLagCount = connectionSlot->getCurrentLagCount(); - double lastClientCommandListTimeLag = difftime((long int)time(NULL),connectionSlot->getLastReceiveCommandListTime()); - //float pingTime = connectionSlot->getThreadedPingMS(connectionSlot->getIpAddress().c_str()); - char szBuf[8096]=""; - snprintf(szBuf,8096,", lag = %d [%.2f]",clientLagCount,lastClientCommandListTimeLag); - str += connectionSlot->getName() + " [" + connectionSlot->getUUID() + "] " + string(szBuf); - } - } - else { - str += lang.getString("NotConnected"); - } - - str += '\n'; - } - return str; -} +void ServerInterface::update() { + // printf("\nServerInterface::update -- A\n"); -bool ServerInterface::launchGame(const GameSettings *gameSettings) { - bool bOkToStart = true; + std::vector errorMsgList; + try { + // The first thing we will do is check all clients to ensure they have + // properly identified themselves within the alloted time period + validateConnectedClients(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // printf("\nServerInterface::update -- B\n"); - for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { + processTextMessageQueue(); + processBroadCastMessageQueue(); - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); - ConnectionSlot *connectionSlot= slots[index]; - if(connectionSlot != NULL && - (connectionSlot->getAllowDownloadDataSynch() == true || connectionSlot->getAllowGameDataSynchCheck() == true) && - connectionSlot->isConnected()) { + checkForAutoResumeForLaggingClients(); - if(connectionSlot->getNetworkGameDataSynchCheckOk() == false) { + // printf("\nServerInterface::update -- C\n"); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] map [%d] tile [%d] techtree [%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,connectionSlot->getNetworkGameDataSynchCheckOkMap(),connectionSlot->getNetworkGameDataSynchCheckOkTile(),connectionSlot->getNetworkGameDataSynchCheckOkTech()); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] map [%d] tile [%d] techtree [%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,connectionSlot->getNetworkGameDataSynchCheckOkMap(),connectionSlot->getNetworkGameDataSynchCheckOkTile(),connectionSlot->getNetworkGameDataSynchCheckOkTech()); + std::map socketTriggeredList; + // update all slots + updateSocketTriggeredList(socketTriggeredList); - bOkToStart = false; - break; - } - } - } - if(bOkToStart == true) { + // printf("\nServerInterface::update -- D\n"); - bool useInGameBlockingClientSockets = Config::getInstance().getBool("EnableInGameBlockingSockets","true"); - if(useInGameBlockingClientSockets == true) { + if (gameHasBeenInitiated == false || socketTriggeredList.empty() == false) { + // printf("\nServerInterface::update -- E\n"); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + std::map eventList; - for(int index = 0; index < GameConstants::maxPlayers; ++index) { + bool hasData = false; + if (gameHasBeenInitiated == false) { + hasData = Socket::hasDataToRead(socketTriggeredList); + } else { + hasData = true; + } - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); - ConnectionSlot *connectionSlot= slots[index]; - if(connectionSlot != NULL && connectionSlot->isConnected()) { - connectionSlot->getSocket()->setBlock(true); - } - } - } + if (hasData && + SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] hasData == true\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (gameHasBeenInitiated == false || hasData == true) { + // printf("START Server update #2\n"); + std::map mapSlotSignalledList; - bool requiresUPNPTrigger = false; - for(int startIndex = 0; startIndex < GameConstants::maxPlayers; ++startIndex) { + // Step #1 tell all connection slot worker threads to receive socket + // data + if (gameHasBeenInitiated == false) { + signalClientsToRecieveData(socketTriggeredList, eventList, + mapSlotSignalledList); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] ============ Step #2\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + // printf("START Server update #2\n"); + if (gameHasBeenInitiated == false || hasData == true) { + // printf("START Server update #3\n"); + + // Step #2 check all connection slot worker threads for completed + // status + if (gameHasBeenInitiated == false) { + checkForCompletedClients(mapSlotSignalledList, errorMsgList, + eventList); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] ============ Step #3\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + // printf("START Server update #4\n"); + // printf("In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + // Step #3 check clients for any lagging scenarios and try to deal + // with them + if (gameHasBeenInitiated == false) { + checkForLaggingClients(mapSlotSignalledList, eventList, + socketTriggeredList, errorMsgList); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] ============ Step #4\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + // printf("START Server update #5\n"); + // printf("In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // Step #4 dispatch network commands to the pending list so that they + // are done in proper order + executeNetworkCommandsFromClients(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] ============ Step #5\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + // printf("START Server update #6\n"); + // printf("In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // Step #5 dispatch pending chat messages + dispatchPendingChatMessages(errorMsgList); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + dispatchPendingMarkCellMessages(errorMsgList); + dispatchPendingUnMarkCellMessages(errorMsgList); + + dispatchPendingHighlightCellMessages(errorMsgList); + + if (gameHasBeenInitiated == true && + difftime((long int)time(NULL), gameStartTime) >= + LAG_CHECK_GRACE_PERIOD && + difftime((long int)time(NULL), lastGlobalLagCheckTime) >= + LAG_CHECK_INTERVAL_PERIOD) { + + std::map mapSlotSignalledList; + checkForLaggingClients(mapSlotSignalledList, eventList, + socketTriggeredList, errorMsgList); + } + // printf("START Server update #7\n"); + } else if (gameHasBeenInitiated == true && + difftime((long int)time(NULL), gameStartTime) >= + LAG_CHECK_GRACE_PERIOD && + difftime((long int)time(NULL), lastGlobalLagCheckTime) >= + LAG_CHECK_INTERVAL_PERIOD) { + + // printf("Skip network data process because hasData == false\n"); + // printf("START Server update #8\n"); + + std::map mapSlotSignalledList; + checkForLaggingClients(mapSlotSignalledList, eventList, + socketTriggeredList, errorMsgList); + } + // printf("START Server update #9\n"); + } else if (gameHasBeenInitiated == true && + difftime((long int)time(NULL), gameStartTime) >= + LAG_CHECK_GRACE_PERIOD && + difftime((long int)time(NULL), lastGlobalLagCheckTime) >= + LAG_CHECK_INTERVAL_PERIOD) { + + // printf("\nServerInterface::update -- E1\n"); + // printf("START Server update #10\n"); + + std::map mapSlotSignalledList; + checkForLaggingClients(mapSlotSignalledList, eventList, + socketTriggeredList, errorMsgList); + } + // printf("START Server update #11\n"); + } else if (gameHasBeenInitiated == true && + difftime((long int)time(NULL), gameStartTime) >= + LAG_CHECK_GRACE_PERIOD && + difftime((long int)time(NULL), lastGlobalLagCheckTime) >= + LAG_CHECK_INTERVAL_PERIOD) { + + // printf("\nServerInterface::update -- F\n"); + // printf("START Server update #12\n"); + + std::map eventList; + std::map mapSlotSignalledList; + + checkForLaggingClients(mapSlotSignalledList, eventList, + socketTriggeredList, errorMsgList); + } + // printf("START Server update #13\n"); + + // Check if we need to switch masterserver admin to a new player because + // original admin disconnected + if (gameHasBeenInitiated == true && + this->gameSettings.getMasterserver_admin() > 0) { + + bool foundAdminSlot = false; + int iFirstConnectedSlot = -1; + for (int index = 0; index < GameConstants::maxPlayers; ++index) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index], + CODE_AT_LINE_X(index)); + if (slots[index] != NULL && slots[index]->isConnected() == true) { + if (iFirstConnectedSlot < 0) { + iFirstConnectedSlot = index; + } + if (this->gameSettings.getMasterserver_admin() == + slots[index]->getSessionKey()) { + foundAdminSlot = true; + break; + } + } + } + + if (foundAdminSlot == false && iFirstConnectedSlot >= 0) { + printf("Switching masterserver admin to slot#%d...\n", + iFirstConnectedSlot); + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[iFirstConnectedSlot], + CODE_AT_LINE_X(iFirstConnectedSlot)); + if (slots[iFirstConnectedSlot] != NULL) { + string sMsg = "Switching player to admin mode: " + + slots[iFirstConnectedSlot]->getName(); + sendTextMessage(sMsg, -1, true, ""); + + this->gameSettings.setMasterserver_admin( + slots[iFirstConnectedSlot]->getSessionKey()); + this->gameSettings.setMasterserver_admin_faction_index( + slots[iFirstConnectedSlot]->getPlayerIndex()); + + safeMutexSlot.ReleaseLock(); + this->broadcastGameSetup(&this->gameSettings); + } + } + } + // printf("\nServerInterface::update -- G\n"); + // printf("START Server update #14\n"); + + checkListenerSlots(); + + // printf("START Server update #15\n"); + } catch (const exception &ex) { + // printf("\nServerInterface::update -- H\n"); + + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] error detected [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + errorMsgList.push_back(ex.what()); + } + + if (errorMsgList.empty() == false) { + for (int iErrIdx = 0; iErrIdx < (int)errorMsgList.size(); ++iErrIdx) { + string &sErr = errorMsgList[iErrIdx]; + if (sErr != "") { + DisplayErrorMessage(sErr); + } + } + } +} - int factionIndex = gameSettings->getFactionIndexForStartLocation(startIndex); - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[startIndex],CODE_AT_LINE_X(startIndex)); - ConnectionSlot *connectionSlot= slots[startIndex]; - if((connectionSlot == NULL || connectionSlot->isConnected() == false) && - this->getAllowInGameConnections() == true) { +void ServerInterface::updateKeyframe(int frameCount) { + currentFrameCount = frameCount; + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] currentFrameCount = %d, " + "requestedCommands.size() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, currentFrameCount, + requestedCommands.size()); + + NetworkMessageCommandList networkMessageCommandList(frameCount); + for (int index = 0; index < GameConstants::maxPlayers; ++index) { + networkMessageCommandList.setNetworkPlayerFactionCRC( + index, this->getNetworkPlayerFactionCRC(index)); + } + + while (requestedCommands.empty() == false) { + // First add the command to the broadcast list (for all clients) + if (networkMessageCommandList.addCommand(&requestedCommands.back())) { + // Add the command to the local server command list + pendingCommands.push_back(requestedCommands.back()); + requestedCommands.pop_back(); + } else { + break; + } + } + + try { + // Possible cause of out of synch since we have more commands that need + // to be sent in this frame + if (requestedCommands.empty() == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] WARNING / ERROR, " + "requestedCommands.size() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, + requestedCommands.size()); + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] WARNING / ERROR, " + "requestedCommands.size() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, + requestedCommands.size()); + + string sMsg = "may go out of synch: server requestedCommands.size() = " + + intToStr(requestedCommands.size()); + sendTextMessage(sMsg, -1, true, ""); + } + + // broadcast commands + // If we have more than 0 commands to send, automatically broadcast them + bool sendBroadcastMessage = + (networkMessageCommandList.getCommandCount() > 0); + if (sendBroadcastMessage == false) { + + // Is auto pause due to lag NOT enabled + if (this->getClientsAutoPausedDueToLag() == false) { + + // ****NOTE: + // We always need to broadcast when not pause as clients + // look for broadcasts every network frame. + sendBroadcastMessage = true; + } + // Auto pause is enabled due to client lagging, only send empty command + // broadcasts every + // MAX_EMPTY_NETWORK_COMMAND_LIST_BROADCAST_INTERVAL_MILLISECONDS + else if ( + this->getClientsAutoPausedDueToLag() == true && + (lastBroadcastCommandsTimer.isStarted() == false || + lastBroadcastCommandsTimer.getMillis() >= + MAX_EMPTY_NETWORK_COMMAND_LIST_BROADCAST_INTERVAL_MILLISECONDS)) { + + sendBroadcastMessage = true; + } + } + + if (sendBroadcastMessage == true) { + + if (lastBroadcastCommandsTimer.isStarted() == false) { + lastBroadcastCommandsTimer.start(); + } else { + lastBroadcastCommandsTimer.stop(); + lastBroadcastCommandsTimer.reset(); + lastBroadcastCommandsTimer.start(); + } + broadcastMessage(&networkMessageCommandList); + } + } catch (const exception &ex) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] error detected [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + DisplayErrorMessage(ex.what()); + } +} - // Open slots for joining in progress game - if(gameSettings->getFactionControl(factionIndex) != ctClosed && - gameSettings->getFactionControl(factionIndex) != ctHuman) { +bool ServerInterface::shouldDiscardNetworkMessage( + NetworkMessageType networkMessageType, ConnectionSlot *connectionSlot) { + bool discard = false; + if (connectionSlot != NULL) { + switch (networkMessageType) { + case nmtIntro: { + discard = true; + NetworkMessageIntro msg = NetworkMessageIntro(); + connectionSlot->receiveMessage(&msg); + } break; + case nmtPing: { + discard = true; + NetworkMessagePing msg = NetworkMessagePing(); + connectionSlot->receiveMessage(&msg); + lastPingInfo = msg; + } break; + + case nmtLaunch: { + discard = true; + NetworkMessageLaunch msg = NetworkMessageLaunch(); + connectionSlot->receiveMessage(&msg); + } break; + case nmtText: { + discard = true; + NetworkMessageText netMsg = NetworkMessageText(); + connectionSlot->receiveMessage(&netMsg); + + ChatMsgInfo msg(netMsg.getText().c_str(), netMsg.getTeamIndex(), + netMsg.getPlayerIndex(), netMsg.getTargetLanguage()); + this->addChatInfo(msg); + + string newChatText = msg.chatText.c_str(); + // string newChatSender = msg.chatSender.c_str(); + int newChatTeamIndex = msg.chatTeamIndex; + int newChatPlayerIndex = msg.chatPlayerIndex; + string newChatLanguage = msg.targetLanguage.c_str(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] #1 about to broadcast nmtText chatText [%s] " + "chatTeamIndex = %d, newChatPlayerIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, newChatText.c_str(), newChatTeamIndex, + newChatPlayerIndex); + + NetworkMessageText networkMessageText( + newChatText.c_str(), newChatTeamIndex, newChatPlayerIndex, + newChatLanguage); + broadcastMessage(&networkMessageText, connectionSlot->getPlayerIndex()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] after broadcast nmtText " + "chatText [%s] chatTeamIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, newChatText.c_str(), + newChatTeamIndex); + + } break; + + case nmtMarkCell: { + discard = true; + NetworkMessageMarkCell networkMessageMarkCell; + connectionSlot->receiveMessage(&networkMessageMarkCell); + + MarkedCell msg(networkMessageMarkCell.getTarget(), + networkMessageMarkCell.getFactionIndex(), + networkMessageMarkCell.getText().c_str(), + networkMessageMarkCell.getPlayerIndex()); + + this->addMarkedCell(msg); + + NetworkMessageMarkCell networkMessageMarkCellBroadcast( + networkMessageMarkCell.getTarget(), + networkMessageMarkCell.getFactionIndex(), + networkMessageMarkCell.getText().c_str(), + networkMessageMarkCell.getPlayerIndex()); + broadcastMessage(&networkMessageMarkCellBroadcast, + connectionSlot->getPlayerIndex()); + + // if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: + // %d] after broadcast nmtMarkCell chatText [%s] chatTeamIndex = + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,newChatText.c_str(),newChatTeamIndex); + + } break; + + case nmtUnMarkCell: { + discard = true; + NetworkMessageUnMarkCell networkMessageMarkCell; + connectionSlot->receiveMessage(&networkMessageMarkCell); + + UnMarkedCell msg(networkMessageMarkCell.getTarget(), + networkMessageMarkCell.getFactionIndex()); + + this->addUnMarkedCell(msg); + + NetworkMessageUnMarkCell networkMessageMarkCellBroadcast( + networkMessageMarkCell.getTarget(), + networkMessageMarkCell.getFactionIndex()); + broadcastMessage(&networkMessageMarkCellBroadcast, + connectionSlot->getPlayerIndex()); + + // if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: + // %d] after broadcast nmtMarkCell chatText [%s] chatTeamIndex = + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,newChatText.c_str(),newChatTeamIndex); + + } break; + case nmtHighlightCell: { + discard = true; + NetworkMessageHighlightCell networkMessageHighlightCell; + connectionSlot->receiveMessage(&networkMessageHighlightCell); + + MarkedCell msg(networkMessageHighlightCell.getTarget(), + networkMessageHighlightCell.getFactionIndex(), "none", -1); + + this->setHighlightedCell(msg); + + NetworkMessageHighlightCell networkMessageHighlightCellBroadcast( + networkMessageHighlightCell.getTarget(), + networkMessageHighlightCell.getFactionIndex()); + broadcastMessage(&networkMessageHighlightCellBroadcast, + connectionSlot->getPlayerIndex()); + + // if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: + // %d] after broadcast nmtMarkCell chatTeamIndex = + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,newChatTeamIndex); + + } break; + + case nmtSynchNetworkGameData: { + discard = true; + NetworkMessageSynchNetworkGameData msg = + NetworkMessageSynchNetworkGameData(); + connectionSlot->receiveMessage(&msg); + } break; + case nmtSynchNetworkGameDataStatus: { + discard = true; + NetworkMessageSynchNetworkGameDataStatus msg = + NetworkMessageSynchNetworkGameDataStatus(); + connectionSlot->receiveMessage(&msg); + } break; + case nmtSynchNetworkGameDataFileCRCCheck: { + discard = true; + NetworkMessageSynchNetworkGameDataFileCRCCheck msg = + NetworkMessageSynchNetworkGameDataFileCRCCheck(); + connectionSlot->receiveMessage(&msg); + } break; + case nmtSynchNetworkGameDataFileGet: { + discard = true; + NetworkMessageSynchNetworkGameDataFileGet msg = + NetworkMessageSynchNetworkGameDataFileGet(); + connectionSlot->receiveMessage(&msg); + } break; + case nmtSwitchSetupRequest: { + discard = true; + SwitchSetupRequest msg = SwitchSetupRequest(); + connectionSlot->receiveMessage(&msg); + } break; + case nmtPlayerIndexMessage: { + discard = true; + PlayerIndexMessage msg = PlayerIndexMessage(0); + connectionSlot->receiveMessage(&msg); + } break; + } + } + return discard; +} - //printf("Opening slot for in game connections for slot: %d, faction: %d\n",i,factionIndex); - if(connectionSlot == NULL) { - addSlot(startIndex); - connectionSlot = slots[startIndex]; - requiresUPNPTrigger = true; - } - connectionSlot->setCanAcceptConnections(true); - } - } - } +void ServerInterface::waitUntilReady(Checksum *checksum) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, "In [%s] START\n", + __FUNCTION__); + Logger &logger = Logger::getInstance(); + gameHasBeenInitiated = true; + Chrono chrono; + chrono.start(); + + bool allReady = false; + + if (Config::getInstance().getBool("EnableGameServerLoadCancel", "false") == + true) { + logger.setCancelLoadingEnabled(true); + } + + Lang &lang = Lang::getInstance(); + uint64 waitLoopIterationCount = 0; + uint64 MAX_LOOP_COUNT_BEFORE_SLEEP = 10; + MAX_LOOP_COUNT_BEFORE_SLEEP = Config::getInstance().getInt( + "NetworkServerLoopGameLoadingCap", + intToStr(MAX_LOOP_COUNT_BEFORE_SLEEP).c_str()); + if (MAX_LOOP_COUNT_BEFORE_SLEEP == 0) { + MAX_LOOP_COUNT_BEFORE_SLEEP = 1; + } + int sleepMillis = Config::getInstance().getInt( + "NetworkServerLoopGameLoadingCapSleepMillis", "10"); + int64 lastStatusUpdate = 0; + + while (exitServer == false && allReady == false && + logger.getCancelLoading() == false) { + + waitLoopIterationCount++; + if (waitLoopIterationCount > 0 && + waitLoopIterationCount % MAX_LOOP_COUNT_BEFORE_SLEEP == 0) { + + sleep(sleepMillis); + waitLoopIterationCount = 0; + } + vector waitingForHosts; + allReady = true; + for (int index = 0; + exitServer == false && index < GameConstants::maxPlayers; ++index) { + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index], + CODE_AT_LINE_X(index)); + ConnectionSlot *connectionSlot = slots[index]; + if (connectionSlot != NULL && connectionSlot->isConnected() == true) { + if (connectionSlot->isReady() == false) { + + NetworkMessageType networkMessageType = + connectionSlot->getNextMessageType(); + + // consume old messages from the lobby + bool discarded = + shouldDiscardNetworkMessage(networkMessageType, connectionSlot); + if (discarded == false) { + + NetworkMessageReady networkMessageReady; + if (networkMessageType == nmtReady && + connectionSlot->receiveMessage(&networkMessageReady)) { + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s] networkMessageType==nmtReady\n", __FUNCTION__); + + connectionSlot->setReady(); + connectionSlot->setGameStarted(true); + } else if (networkMessageType != nmtInvalid) { + string sErr = + "Unexpected network message: " + intToStr(networkMessageType); + sendTextMessage(sErr, -1, true, "", index); + DisplayErrorMessage(sErr); + logger.setCancelLoading(false); + return; + } + } + waitingForHosts.push_back(connectionSlot->getName()); + allReady = false; + } + } + } + + // check for timeout + if (allReady == false) { + if (chrono.getMillis() > readyWaitTimeout) { + Lang &lang = Lang::getInstance(); + const vector languageList = + this->gameSettings.getUniqueNetworkPlayerLanguages(); + for (unsigned int langIndex = 0; langIndex < languageList.size(); + ++langIndex) { + string sErr = "Timeout waiting for clients."; + if (lang.hasString("TimeoutWaitingForClients") == true) { + sErr = lang.getString("TimeoutWaitingForClients", + languageList[langIndex]); + } + bool localEcho = lang.isLanguageLocal(languageList[langIndex]); + sendTextMessage(sErr, -1, localEcho, languageList[langIndex]); + if (localEcho == true) { + DisplayErrorMessage(sErr); + } + } + logger.setCancelLoading(false); + return; + } else { + if (chrono.getMillis() - lastStatusUpdate > 200) { + lastStatusUpdate = chrono.getMillis(); + + string waitForHosts = ""; + for (int hostIndex = 0; hostIndex < (int)waitingForHosts.size(); + hostIndex++) { + if (waitForHosts != "") { + waitForHosts += ", "; + } + waitForHosts += waitingForHosts[hostIndex]; + } + + char szBuf[8096] = ""; + string updateTextFormat = + lang.getString("NetworkGameServerLoadStatus"); + if (updateTextFormat == "" || updateTextFormat[0] == '?') { + + updateTextFormat = "Waiting for network: %lld seconds elapsed " + "(maximum wait time: %d seconds)"; + } + snprintf(szBuf, 8096, updateTextFormat.c_str(), + (long long int)(chrono.getMillis() / 1000), + int(readyWaitTimeout / 1000)); + + char szBuf1[8096] = ""; + string statusTextFormat = lang.getString("NetworkGameStatusWaiting"); + if (statusTextFormat == "" || statusTextFormat[0] == '?') { + + statusTextFormat = "Waiting for players: %s"; + } + snprintf(szBuf1, 8096, statusTextFormat.c_str(), + waitForHosts.c_str()); + + logger.add(szBuf, true, szBuf1); + + uint32 loadingStatus = nmls_NONE; + // send ready message after, so clients start delayed + for (int slotIndex = 0; + exitServer == false && slotIndex < GameConstants::maxPlayers; + ++slotIndex) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex], + CODE_AT_LINE_X(slotIndex)); + ConnectionSlot *connectionSlot = slots[slotIndex]; + if (connectionSlot != NULL && + connectionSlot->isConnected() == true) { + switch (slotIndex) { + case 0: + loadingStatus |= nmls_PLAYER1_CONNECTED; + if (connectionSlot->isReady()) { + loadingStatus |= nmls_PLAYER1_READY; + } + break; + case 1: + loadingStatus |= nmls_PLAYER2_CONNECTED; + if (connectionSlot->isReady()) { + loadingStatus |= nmls_PLAYER2_READY; + } + break; + case 2: + loadingStatus |= nmls_PLAYER3_CONNECTED; + if (connectionSlot->isReady()) { + loadingStatus |= nmls_PLAYER3_READY; + } + break; + case 3: + loadingStatus |= nmls_PLAYER4_CONNECTED; + if (connectionSlot->isReady()) { + loadingStatus |= nmls_PLAYER4_READY; + } + break; + case 4: + loadingStatus |= nmls_PLAYER5_CONNECTED; + if (connectionSlot->isReady()) { + loadingStatus |= nmls_PLAYER5_READY; + } + break; + case 5: + loadingStatus |= nmls_PLAYER6_CONNECTED; + if (connectionSlot->isReady()) { + loadingStatus |= nmls_PLAYER6_READY; + } + break; + case 6: + loadingStatus |= nmls_PLAYER7_CONNECTED; + if (connectionSlot->isReady()) { + loadingStatus |= nmls_PLAYER7_READY; + } + break; + case 7: + loadingStatus |= nmls_PLAYER8_CONNECTED; + if (connectionSlot->isReady()) { + loadingStatus |= nmls_PLAYER8_READY; + } + break; + } + } + } + + // send loading status message + for (int slotIndex = 0; + exitServer == false && slotIndex < GameConstants::maxPlayers; + ++slotIndex) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex], + CODE_AT_LINE_X(slotIndex)); + ConnectionSlot *connectionSlot = slots[slotIndex]; + if (connectionSlot != NULL && + connectionSlot->isConnected() == true) { + NetworkMessageLoadingStatus networkMessageLoadingStatus( + loadingStatus); + connectionSlot->sendMessage(&networkMessageLoadingStatus); + } + } + + sleep(0); + } + } + } + + Shared::Platform::Window::handleEvent(); + } + + if (logger.getCancelLoading() == true) { + Lang &lang = Lang::getInstance(); + const vector languageList = + this->gameSettings.getUniqueNetworkPlayerLanguages(); + for (unsigned int langIndex = 0; langIndex < languageList.size(); + ++langIndex) { + + string sErr = + lang.getString("GameCancelledByUser", languageList[langIndex]); + bool localEcho = lang.isLanguageLocal(languageList[langIndex]); + sendTextMessage(sErr, -1, localEcho, languageList[langIndex]); + + if (localEcho == true) { + DisplayErrorMessage(sErr); + } + } + quitGame(true); + logger.setCancelLoading(false); + return; + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s] PART B (telling client we are ready!\n", + __FUNCTION__); + try { + // send ready message after, so clients start delayed + for (int slotIndex = 0; + exitServer == false && slotIndex < GameConstants::maxPlayers; + ++slotIndex) { + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex], + CODE_AT_LINE_X(slotIndex)); + ConnectionSlot *connectionSlot = slots[slotIndex]; + if (connectionSlot != NULL && connectionSlot->isConnected() == true) { + NetworkMessageReady networkMessageReady(checksum->getSum()); + connectionSlot->sendMessage(&networkMessageReady); + connectionSlot->setGameStarted(true); + } + } + + gameStartTime = time(NULL); + } catch (const exception &ex) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] error detected [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + DisplayErrorMessage(ex.what()); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, "In [%s] END\n", + __FUNCTION__); +} - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] needToRepublishToMasterserver = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,needToRepublishToMasterserver); +void ServerInterface::processBroadCastMessageQueue() { + MutexSafeWrapper safeMutexSlot(broadcastMessageQueueThreadAccessor, + CODE_AT_LINE); + if (broadcastMessageQueue.empty() == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] broadcastMessageQueue.size() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, broadcastMessageQueue.size()); + for (int index = 0; index < (int)broadcastMessageQueue.size(); ++index) { + pair &item = broadcastMessageQueue[index]; + if (item.first != NULL) { + this->broadcastMessage(item.first, item.second); + delete item.first; + } + item.first = NULL; + } + broadcastMessageQueue.clear(); + } +} - if(this->getAllowInGameConnections() == false) { - serverSocket.stopBroadCastThread(); - } +void ServerInterface::queueBroadcastMessage(NetworkMessage *networkMessage, + int excludeSlot) { + MutexSafeWrapper safeMutexSlot(broadcastMessageQueueThreadAccessor, + CODE_AT_LINE); + pair item; + item.first = networkMessage; + item.second = excludeSlot; + broadcastMessageQueue.push_back(item); +} - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] needToRepublishToMasterserver = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,needToRepublishToMasterserver); +void ServerInterface::processTextMessageQueue() { + MutexSafeWrapper safeMutexSlot(textMessageQueueThreadAccessor, CODE_AT_LINE); + if (textMessageQueue.empty() == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] textMessageQueue.size() = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, textMessageQueue.size()); + for (int index = 0; index < (int)textMessageQueue.size(); ++index) { + TextMessageQueue &item = textMessageQueue[index]; + sendTextMessage(item.text, item.teamIndex, item.echoLocal, + item.targetLanguage); + } + textMessageQueue.clear(); + } +} - this->gameSettings = *gameSettings; - //printf("#1 Data synch: lmap %u ltile: %d ltech: %u\n",gameSettings->getMapCRC(),gameSettings->getTilesetCRC(),gameSettings->getTechCRC()); +void ServerInterface::queueTextMessage(const string &text, int teamIndex, + bool echoLocal, string targetLanguage) { + // printf("Line: %d text [%s]\n",__LINE__,text.c_str()); + + MutexSafeWrapper safeMutexSlot(textMessageQueueThreadAccessor, CODE_AT_LINE); + TextMessageQueue item; + item.text = text; + item.teamIndex = teamIndex; + item.echoLocal = echoLocal; + item.targetLanguage = targetLanguage; + textMessageQueue.push_back(item); +} - NetworkMessageLaunch networkMessageLaunch(gameSettings,nmtLaunch); - broadcastMessage(&networkMessageLaunch); +void ServerInterface::sendTextMessage(const string &text, int teamIndex, + bool echoLocal, string targetLanguage) { + sendTextMessage(text, teamIndex, echoLocal, targetLanguage, -1); +} - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] needToRepublishToMasterserver = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,needToRepublishToMasterserver); +void ServerInterface::sendTextMessage(const string &text, int teamIndex, + bool echoLocal, string targetLanguage, + int lockedSlotIndex) { + // printf("Line: %d text [%s] echoLocal = + // %d\n",__LINE__,text.c_str(),echoLocal); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] text [%s] teamIndex = %d, " + "echoLocal = %d, lockedSlotIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, text.c_str(), teamIndex, + echoLocal, lockedSlotIndex); + + NetworkMessageText networkMessageText(text, teamIndex, getHumanPlayerIndex(), + targetLanguage); + broadcastMessage(&networkMessageText, -1, lockedSlotIndex); + + if (echoLocal == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + ChatMsgInfo msg(text.c_str(), teamIndex, + networkMessageText.getPlayerIndex(), targetLanguage); + this->addChatInfo(msg); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); +} - shutdownMasterserverPublishThread(); - MutexSafeWrapper safeMutex(masterServerThreadAccessor,CODE_AT_LINE); - lastMasterserverHeartbeatTime = 0; +void ServerInterface::sendMarkCellMessage(Vec2i targetPos, int factionIndex, + string note, int playerIndex) { + sendMarkCellMessage(targetPos, factionIndex, note, playerIndex, -1); +} - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] ftpServer = %p\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ftpServer); +void ServerInterface::sendMarkCellMessage(Vec2i targetPos, int factionIndex, + string note, int playerIndex, + int lockedSlotIndex) { + NetworkMessageMarkCell networkMessageMarkCell(targetPos, factionIndex, note, + playerIndex); + broadcastMessage(&networkMessageMarkCell, -1, lockedSlotIndex); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); +} - if(this->getAllowInGameConnections() == false) { - shutdownFTPServer(); - } +void ServerInterface::sendHighlightCellMessage(Vec2i targetPos, + int factionIndex) { + sendHighlightCellMessage(targetPos, factionIndex, -1); +} - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] needToRepublishToMasterserver = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,needToRepublishToMasterserver); +void ServerInterface::sendHighlightCellMessage(Vec2i targetPos, + int factionIndex, + int lockedSlotIndex) { + NetworkMessageHighlightCell networkMessageHighlightCell(targetPos, + factionIndex); + broadcastMessage(&networkMessageHighlightCell, -1, lockedSlotIndex); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); +} - if(publishToMasterserverThread == NULL) { - if(needToRepublishToMasterserver == true || - GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { +void ServerInterface::sendUnMarkCellMessage(Vec2i targetPos, int factionIndex) { + sendUnMarkCellMessage(targetPos, factionIndex, -1); +} - static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); - publishToMasterserverThread = new SimpleTaskThread(this,0,125); - publishToMasterserverThread->setUniqueID(mutexOwnerId); - publishToMasterserverThread->start(); +void ServerInterface::sendUnMarkCellMessage(Vec2i targetPos, int factionIndex, + int lockedSlotIndex) { + NetworkMessageUnMarkCell networkMessageMarkCell(targetPos, factionIndex); + broadcastMessage(&networkMessageMarkCell, -1, lockedSlotIndex); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] needToRepublishToMasterserver = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,needToRepublishToMasterserver); - } - } + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); +} - if(this->getAllowInGameConnections() == false) { - shutdownFTPServer(); - } +void ServerInterface::quitGame(bool userManuallyQuit) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + NetworkMessageQuit networkMessageQuit; + broadcastMessage(&networkMessageQuit); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); +} - if((needToRepublishToMasterserver == true || - GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) && - requiresUPNPTrigger == true) { +string ServerInterface::getNetworkStatus() { + Lang &lang = Lang::getInstance(); + string str = ""; + for (int index = 0; exitServer == false && index < GameConstants::maxPlayers; + ++index) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index], + CODE_AT_LINE_X(index)); + ConnectionSlot *connectionSlot = slots[index]; + + str += intToStr(index) + ": "; + + if (connectionSlot != NULL) { + if (connectionSlot->isConnected()) { + int clientLagCount = connectionSlot->getCurrentLagCount(); + double lastClientCommandListTimeLag = + difftime((long int)time(NULL), + connectionSlot->getLastReceiveCommandListTime()); + // float pingTime = + // connectionSlot->getThreadedPingMS(connectionSlot->getIpAddress().c_str()); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, ", lag = %d [%.2f]", clientLagCount, + lastClientCommandListTimeLag); + str += connectionSlot->getName() + " [" + connectionSlot->getUUID() + + "] " + string(szBuf); + } + } else { + str += lang.getString("NotConnected"); + } + + str += '\n'; + } + return str; +} - this->getServerSocket()->NETdiscoverUPnPDevices(); +bool ServerInterface::launchGame(const GameSettings *gameSettings) { + bool bOkToStart = true; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + for (int index = 0; exitServer == false && index < GameConstants::maxPlayers; + ++index) { + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index], + CODE_AT_LINE_X(index)); + ConnectionSlot *connectionSlot = slots[index]; + if (connectionSlot != NULL && + (connectionSlot->getAllowDownloadDataSynch() == true || + connectionSlot->getAllowGameDataSynchCheck() == true) && + connectionSlot->isConnected()) { + + if (connectionSlot->getNetworkGameDataSynchCheckOk() == false) { + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] map [%d] tile [%d] techtree [%d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, connectionSlot->getNetworkGameDataSynchCheckOkMap(), + connectionSlot->getNetworkGameDataSynchCheckOkTile(), + connectionSlot->getNetworkGameDataSynchCheckOkTech()); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] map [%d] tile [%d] techtree [%d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, connectionSlot->getNetworkGameDataSynchCheckOkMap(), + connectionSlot->getNetworkGameDataSynchCheckOkTile(), + connectionSlot->getNetworkGameDataSynchCheckOkTech()); + + bOkToStart = false; + break; + } + } + } + if (bOkToStart == true) { + + bool useInGameBlockingClientSockets = + Config::getInstance().getBool("EnableInGameBlockingSockets", "true"); + if (useInGameBlockingClientSockets == true) { + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + for (int index = 0; index < GameConstants::maxPlayers; ++index) { + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index], + CODE_AT_LINE_X(index)); + ConnectionSlot *connectionSlot = slots[index]; + if (connectionSlot != NULL && connectionSlot->isConnected()) { + connectionSlot->getSocket()->setBlock(true); } - - gameLaunched = true; - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - return bOkToStart; + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + bool requiresUPNPTrigger = false; + for (int startIndex = 0; startIndex < GameConstants::maxPlayers; + ++startIndex) { + + int factionIndex = + gameSettings->getFactionIndexForStartLocation(startIndex); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[startIndex], + CODE_AT_LINE_X(startIndex)); + ConnectionSlot *connectionSlot = slots[startIndex]; + if ((connectionSlot == NULL || connectionSlot->isConnected() == false) && + this->getAllowInGameConnections() == true) { + + // Open slots for joining in progress game + if (gameSettings->getFactionControl(factionIndex) != ctClosed && + gameSettings->getFactionControl(factionIndex) != ctHuman) { + + // printf("Opening slot for in game connections for slot: %d, faction: + // %d\n",i,factionIndex); + if (connectionSlot == NULL) { + addSlot(startIndex); + connectionSlot = slots[startIndex]; + requiresUPNPTrigger = true; + } + connectionSlot->setCanAcceptConnections(true); + } + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] needToRepublishToMasterserver = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, needToRepublishToMasterserver); + + if (this->getAllowInGameConnections() == false) { + serverSocket.stopBroadCastThread(); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] needToRepublishToMasterserver = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, needToRepublishToMasterserver); + + this->gameSettings = *gameSettings; + // printf("#1 Data synch: lmap %u ltile: %d ltech: + // %u\n",gameSettings->getMapCRC(),gameSettings->getTilesetCRC(),gameSettings->getTechCRC()); + + NetworkMessageLaunch networkMessageLaunch(gameSettings, nmtLaunch); + broadcastMessage(&networkMessageLaunch); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] needToRepublishToMasterserver = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, needToRepublishToMasterserver); + + shutdownMasterserverPublishThread(); + MutexSafeWrapper safeMutex(masterServerThreadAccessor, CODE_AT_LINE); + lastMasterserverHeartbeatTime = 0; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] ftpServer = %p\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ftpServer); + + if (this->getAllowInGameConnections() == false) { + shutdownFTPServer(); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] needToRepublishToMasterserver = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, needToRepublishToMasterserver); + + if (publishToMasterserverThread == NULL) { + if (needToRepublishToMasterserver == true || + GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + + static string mutexOwnerId = + string(extractFileFromDirectoryPath(__FILE__).c_str()) + + string("_") + intToStr(__LINE__); + publishToMasterserverThread = new SimpleTaskThread(this, 0, 125); + publishToMasterserverThread->setUniqueID(mutexOwnerId); + publishToMasterserverThread->start(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] needToRepublishToMasterserver = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, needToRepublishToMasterserver); + } + } + + if (this->getAllowInGameConnections() == false) { + shutdownFTPServer(); + } + + if ((needToRepublishToMasterserver == true || + GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) && + requiresUPNPTrigger == true) { + + this->getServerSocket()->NETdiscoverUPnPDevices(); + } + + gameLaunched = true; + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + return bOkToStart; } void ServerInterface::shutdownFTPServer() { - if(ftpServer != NULL) { - ftpServer->shutdownAndWait(); - delete ftpServer; - ftpServer = NULL; - } + if (ftpServer != NULL) { + ftpServer->shutdownAndWait(); + delete ftpServer; + ftpServer = NULL; + } } void ServerInterface::checkListenerSlots() { - if(gameLaunched == true && - this->getAllowInGameConnections() == true) { - - if(difftime((long int)time(NULL),lastListenerSlotCheckTime) >= 7) { - - lastListenerSlotCheckTime = time(NULL); - bool useInGameBlockingClientSockets = Config::getInstance().getBool("EnableInGameBlockingSockets","true"); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - for(int startIndex = 0; startIndex < GameConstants::maxPlayers; ++startIndex) { - - int factionIndex = gameSettings.getFactionIndexForStartLocation(startIndex); - if(gameSettings.getFactionControl(factionIndex) != ctClosed && - gameSettings.getFactionControl(factionIndex) != ctHuman) { - - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[startIndex],CODE_AT_LINE_X(startIndex)); - ConnectionSlot *connectionSlot= slots[startIndex]; - // Open slots for joining in progress game - if(connectionSlot == NULL) { - printf("Opening slot for in game connections, slot: %d, factionindex: %d name: %s\n",startIndex,factionIndex,gameSettings.getFactionTypeName(factionIndex).c_str()); - - addSlot(startIndex); - connectionSlot = slots[startIndex]; - if(useInGameBlockingClientSockets == true) { - connectionSlot->getSocket()->setBlock(true); - } - connectionSlot->setCanAcceptConnections(true); - } - else if(connectionSlot != NULL && - connectionSlot->getCanAcceptConnections() == false && - connectionSlot->isConnected() == false) { - printf("Removing slot for in game connections, slot: %d, factionindex: %d name: %s\n",startIndex,factionIndex,gameSettings.getFactionTypeName(factionIndex).c_str()); - - this->removeSlot(startIndex); - } - } - } - } - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] needToRepublishToMasterserver = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,needToRepublishToMasterserver); -} - -void ServerInterface::broadcastGameSetup(GameSettings *gameSettingsBuffer, bool setGameSettingsBuffer) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(gameSettingsBuffer == NULL) { - throw megaglest_runtime_error("gameSettingsBuffer == NULL"); - } - for(unsigned int factionIndex = 0; factionIndex < (unsigned int)gameSettingsBuffer->getFactionCount(); ++factionIndex) { - - int slotIndex = gameSettingsBuffer->getStartLocationIndex(factionIndex); - if(gameSettingsBuffer->getFactionControl(factionIndex) == ctNetwork && - isClientConnected(slotIndex) == false) { - - gameSettingsBuffer->setNetworkPlayerName(factionIndex,GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME); - } - } - if(setGameSettingsBuffer == true) { - validateGameSettings(gameSettingsBuffer); - } - - MutexSafeWrapper safeMutex(serverSynchAccessor,CODE_AT_LINE); - if(setGameSettingsBuffer == true) { - gameSettings = *gameSettingsBuffer; - gameSettingsUpdateCount++; - } - - NetworkMessageLaunch networkMessageLaunch(gameSettingsBuffer, nmtBroadCastSetup); - broadcastMessage(&networkMessageLaunch); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); -} - -void ServerInterface::broadcastMessage(NetworkMessage *networkMessage, int excludeSlot, int lockedSlotIndex) { - try { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - MutexSafeWrapper safeMutexSlotBroadCastAccessor(inBroadcastMessageThreadAccessor,CODE_AT_LINE); - if(inBroadcastMessage == true && - dynamic_cast(networkMessage) != NULL) { - - safeMutexSlotBroadCastAccessor.ReleaseLock(); - NetworkMessageText *txtMsg = dynamic_cast(networkMessage); - if(txtMsg != NULL) { - NetworkMessageText *msgCopy = txtMsg->getCopy(); - queueBroadcastMessage(msgCopy, excludeSlot); - } - return; - } - else { - inBroadcastMessage = true; - safeMutexSlotBroadCastAccessor.ReleaseLock(true); - } - - for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { - MutexSafeWrapper safeMutexSlot(NULL,CODE_AT_LINE_X(slotIndex)); - if(slotIndex != lockedSlotIndex) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] i = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,slotIndex,lockedSlotIndex); - safeMutexSlot.setMutex(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); - } - - ConnectionSlot* connectionSlot= slots[slotIndex]; - - if(slotIndex != excludeSlot && connectionSlot != NULL) { - if(connectionSlot->isConnected()) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] before sendMessage\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - connectionSlot->sendMessage(networkMessage); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] after sendMessage\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - if(gameHasBeenInitiated == true && connectionSlot->isConnected() == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] #1 before removeSlot for slot# %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,slotIndex); - - if(this->getAllowInGameConnections() == false) { - removeSlot(slotIndex,slotIndex); - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] #1 after removeSlot for slot# %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,slotIndex); - } - } - else if(slotIndex == excludeSlot && gameHasBeenInitiated == true && - connectionSlot != NULL && connectionSlot->isConnected() == false) { - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] #2 before removeSlot for slot# %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,slotIndex); - - if(this->getAllowInGameConnections() == false) { - removeSlot(slotIndex,slotIndex); - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] #2 after removeSlot for slot# %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,slotIndex); - } - } - - safeMutexSlotBroadCastAccessor.Lock(); - - inBroadcastMessage = false; - - safeMutexSlotBroadCastAccessor.ReleaseLock(); - } - catch(const exception &ex) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] ERROR [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - - MutexSafeWrapper safeMutexSlotBroadCastAccessor(inBroadcastMessageThreadAccessor,CODE_AT_LINE); - inBroadcastMessage = false; - safeMutexSlotBroadCastAccessor.ReleaseLock(); - - string sMsg = ex.what(); - sendTextMessage(sMsg,-1, true, "", lockedSlotIndex); - } -} - -void ServerInterface::broadcastMessageToConnectedClients(NetworkMessage *networkMessage, int excludeSlot) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - try { - for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); - ConnectionSlot *connectionSlot= slots[slotIndex]; - - if(slotIndex != excludeSlot && connectionSlot != NULL) { - if(connectionSlot->isConnected()) { - connectionSlot->sendMessage(networkMessage); - } - } - } - } - catch(const exception &ex) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] ERROR [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - DisplayErrorMessage(ex.what()); - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (gameLaunched == true && this->getAllowInGameConnections() == true) { + + if (difftime((long int)time(NULL), lastListenerSlotCheckTime) >= 7) { + + lastListenerSlotCheckTime = time(NULL); + bool useInGameBlockingClientSockets = + Config::getInstance().getBool("EnableInGameBlockingSockets", "true"); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + for (int startIndex = 0; startIndex < GameConstants::maxPlayers; + ++startIndex) { + + int factionIndex = + gameSettings.getFactionIndexForStartLocation(startIndex); + if (gameSettings.getFactionControl(factionIndex) != ctClosed && + gameSettings.getFactionControl(factionIndex) != ctHuman) { + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[startIndex], + CODE_AT_LINE_X(startIndex)); + ConnectionSlot *connectionSlot = slots[startIndex]; + // Open slots for joining in progress game + if (connectionSlot == NULL) { + printf("Opening slot for in game connections, slot: %d, " + "factionindex: %d name: %s\n", + startIndex, factionIndex, + gameSettings.getFactionTypeName(factionIndex).c_str()); + + addSlot(startIndex); + connectionSlot = slots[startIndex]; + if (useInGameBlockingClientSockets == true) { + connectionSlot->getSocket()->setBlock(true); + } + connectionSlot->setCanAcceptConnections(true); + } else if (connectionSlot != NULL && + connectionSlot->getCanAcceptConnections() == false && + connectionSlot->isConnected() == false) { + printf("Removing slot for in game connections, slot: %d, " + "factionindex: %d name: %s\n", + startIndex, factionIndex, + gameSettings.getFactionTypeName(factionIndex).c_str()); + + this->removeSlot(startIndex); + } + } + } + } + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] needToRepublishToMasterserver = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + needToRepublishToMasterserver); } -void ServerInterface::updateListen() { - if(gameHasBeenInitiated == true && - this->getAllowInGameConnections() == false) { - return; - } +void ServerInterface::broadcastGameSetup(GameSettings *gameSettingsBuffer, + bool setGameSettingsBuffer) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + + if (gameSettingsBuffer == NULL) { + throw megaglest_runtime_error("gameSettingsBuffer == NULL"); + } + for (unsigned int factionIndex = 0; + factionIndex < (unsigned int)gameSettingsBuffer->getFactionCount(); + ++factionIndex) { + + int slotIndex = gameSettingsBuffer->getStartLocationIndex(factionIndex); + if (gameSettingsBuffer->getFactionControl(factionIndex) == ctNetwork && + isClientConnected(slotIndex) == false) { + + gameSettingsBuffer->setNetworkPlayerName( + factionIndex, GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME); + } + } + if (setGameSettingsBuffer == true) { + validateGameSettings(gameSettingsBuffer); + } + + MutexSafeWrapper safeMutex(serverSynchAccessor, CODE_AT_LINE); + if (setGameSettingsBuffer == true) { + gameSettings = *gameSettingsBuffer; + gameSettingsUpdateCount++; + } + + NetworkMessageLaunch networkMessageLaunch(gameSettingsBuffer, + nmtBroadCastSetup); + broadcastMessage(&networkMessageLaunch); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); +} - int openSlotCount = 0; - for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { +void ServerInterface::broadcastMessage(NetworkMessage *networkMessage, + int excludeSlot, int lockedSlotIndex) { + try { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + MutexSafeWrapper safeMutexSlotBroadCastAccessor( + inBroadcastMessageThreadAccessor, CODE_AT_LINE); + if (inBroadcastMessage == true && + dynamic_cast(networkMessage) != NULL) { + + safeMutexSlotBroadCastAccessor.ReleaseLock(); + NetworkMessageText *txtMsg = + dynamic_cast(networkMessage); + if (txtMsg != NULL) { + NetworkMessageText *msgCopy = txtMsg->getCopy(); + queueBroadcastMessage(msgCopy, excludeSlot); + } + return; + } else { + inBroadcastMessage = true; + safeMutexSlotBroadCastAccessor.ReleaseLock(true); + } + + for (int slotIndex = 0; + exitServer == false && slotIndex < GameConstants::maxPlayers; + ++slotIndex) { + MutexSafeWrapper safeMutexSlot(NULL, CODE_AT_LINE_X(slotIndex)); + if (slotIndex != lockedSlotIndex) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] i = %d, lockedSlotIndex = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, slotIndex, lockedSlotIndex); + safeMutexSlot.setMutex(slotAccessorMutexes[slotIndex], + CODE_AT_LINE_X(slotIndex)); + } + + ConnectionSlot *connectionSlot = slots[slotIndex]; + + if (slotIndex != excludeSlot && connectionSlot != NULL) { + if (connectionSlot->isConnected()) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] before sendMessage\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + + connectionSlot->sendMessage(networkMessage); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] after sendMessage\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + } + if (gameHasBeenInitiated == true && + connectionSlot->isConnected() == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] #1 before removeSlot for slot# %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, slotIndex); + + if (this->getAllowInGameConnections() == false) { + removeSlot(slotIndex, slotIndex); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] #1 after removeSlot for slot# %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, slotIndex); + } + } else if (slotIndex == excludeSlot && gameHasBeenInitiated == true && + connectionSlot != NULL && + connectionSlot->isConnected() == false) { + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] #2 before removeSlot for slot# %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, slotIndex); + + if (this->getAllowInGameConnections() == false) { + removeSlot(slotIndex, slotIndex); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line: %d] #2 after removeSlot for slot# %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, slotIndex); + } + } + + safeMutexSlotBroadCastAccessor.Lock(); + + inBroadcastMessage = false; + + safeMutexSlotBroadCastAccessor.ReleaseLock(); + } catch (const exception &ex) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] ERROR [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + + MutexSafeWrapper safeMutexSlotBroadCastAccessor( + inBroadcastMessageThreadAccessor, CODE_AT_LINE); + inBroadcastMessage = false; + safeMutexSlotBroadCastAccessor.ReleaseLock(); + + string sMsg = ex.what(); + sendTextMessage(sMsg, -1, true, "", lockedSlotIndex); + } +} - bool isSlotOpen = (slots[slotIndex] != NULL && slots[slotIndex]->isConnected() == false); - if(isSlotOpen == true) { - ++openSlotCount; - } - } +void ServerInterface::broadcastMessageToConnectedClients( + NetworkMessage *networkMessage, int excludeSlot) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); + try { + for (int slotIndex = 0; + exitServer == false && slotIndex < GameConstants::maxPlayers; + ++slotIndex) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex], + CODE_AT_LINE_X(slotIndex)); + ConnectionSlot *connectionSlot = slots[slotIndex]; + + if (slotIndex != excludeSlot && connectionSlot != NULL) { + if (connectionSlot->isConnected()) { + connectionSlot->sendMessage(networkMessage); + } + } + } + } catch (const exception &ex) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line: %d] ERROR [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + DisplayErrorMessage(ex.what()); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, "In [%s::%s] Line: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__); +} - serverSocket.listen(openSlotCount); +void ServerInterface::updateListen() { + if (gameHasBeenInitiated == true && + this->getAllowInGameConnections() == false) { + return; + } + + int openSlotCount = 0; + for (int slotIndex = 0; + exitServer == false && slotIndex < GameConstants::maxPlayers; + ++slotIndex) { + + bool isSlotOpen = + (slots[slotIndex] != NULL && slots[slotIndex]->isConnected() == false); + if (isSlotOpen == true) { + ++openSlotCount; + } + } + + serverSocket.listen(openSlotCount); } int ServerInterface::getOpenSlotCount() { - int openSlotCount = 0; - for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { - - bool isSlotOpen = (slots[slotIndex] != NULL && slots[slotIndex]->isConnected() == false); - if(isSlotOpen == true) { - ++openSlotCount; - } - } - return openSlotCount; + int openSlotCount = 0; + for (int slotIndex = 0; + exitServer == false && slotIndex < GameConstants::maxPlayers; + ++slotIndex) { + + bool isSlotOpen = + (slots[slotIndex] != NULL && slots[slotIndex]->isConnected() == false); + if (isSlotOpen == true) { + ++openSlotCount; + } + } + return openSlotCount; } int ServerInterface::getGameSettingsUpdateCount() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] START gameSettingsUpdateCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,gameSettingsUpdateCount); - - MutexSafeWrapper safeMutex(serverSynchAccessor,CODE_AT_LINE); - int result = gameSettingsUpdateCount; - safeMutex.ReleaseLock(); - return result; + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s] START gameSettingsUpdateCount = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, gameSettingsUpdateCount); + + MutexSafeWrapper safeMutex(serverSynchAccessor, CODE_AT_LINE); + int result = gameSettingsUpdateCount; + safeMutex.ReleaseLock(); + return result; } void ServerInterface::validateGameSettings(GameSettings *serverGameSettings) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); - - MutexSafeWrapper safeMutex(serverSynchAccessor,CODE_AT_LINE); - string mapFile = serverGameSettings->getMap(); - //printf("Trying to set map to [%s]. Current map is [%s]\n",serverGameSettings->getMap().c_str(),gameSettings.getMap().c_str()); - if(gameSettings.getMapFilter()!=serverGameSettings->getMapFilter()){ - if( playerSortedMaps[serverGameSettings->getMapFilter()].size()==0){ - serverGameSettings->setMapFilter(0); - } - } - int playerIndex=serverGameSettings->getMapFilter(); - if(find(playerSortedMaps[playerIndex].begin(),playerSortedMaps[playerIndex].end(),mapFile) == playerSortedMaps[playerIndex].end()) { - // switch to closest map - string foundMap = ""; - for (int i = 0 ;i < (int)playerSortedMaps[playerIndex].size(); ++i) { - foundMap=playerSortedMaps[playerIndex][i]; - if(toLower(foundMap)>toLower(serverGameSettings->getMap())){ - break; - } - } - printf("map %s not found on this server. Switching to map %s\n",serverGameSettings->getMap().c_str(),foundMap.c_str()); - serverGameSettings->setMap(foundMap); - } - Checksum checksum; - string file = Config::getMapPath(serverGameSettings->getMap(),"",false); - checksum.addFile(file); - serverGameSettings->setMapCRC(checksum.getSum()); - - string tilesetFile = serverGameSettings->getTileset(); - if(find(tilesetFiles.begin(),tilesetFiles.end(),tilesetFile) == tilesetFiles.end()) { - printf("Reverting tileset from [%s] to [%s]\n",serverGameSettings->getTileset().c_str(),gameSettings.getTileset().c_str()); - - serverGameSettings->setTileset(gameSettings.getTileset()); - serverGameSettings->setTilesetCRC(gameSettings.getTilesetCRC()); - } - - string techtreeFile = serverGameSettings->getTech(); - if(find(techTreeFiles.begin(),techTreeFiles.end(),techtreeFile) == techTreeFiles.end()) { - printf("Reverting tech from [%s] to [%s]\n",serverGameSettings->getTech().c_str(),gameSettings.getTech().c_str()); - - serverGameSettings->setTech(gameSettings.getTech()); - serverGameSettings->setTechCRC(gameSettings.getTechCRC()); - } -} - -void ServerInterface::setGameSettings(GameSettings *serverGameSettings, bool waitForClientAck) { - MutexSafeWrapper safeMutex(serverSynchAccessor,CODE_AT_LINE); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] START gameSettingsUpdateCount = %d, waitForClientAck = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,gameSettingsUpdateCount,waitForClientAck); - - if(serverGameSettings->getScenario() == "") { - string mapFile = serverGameSettings->getMap(); - if(find(mapFiles.begin(),mapFiles.end(),mapFile) == mapFiles.end()) { - printf("Reverting map from [%s] to [%s]\n",serverGameSettings->getMap().c_str(),gameSettings.getMap().c_str()); - - serverGameSettings->setMapFilter(gameSettings.getMapFilter()); - serverGameSettings->setMap(gameSettings.getMap()); - serverGameSettings->setMapCRC(gameSettings.getMapCRC()); - } - - string tilesetFile = serverGameSettings->getTileset(); - if(find(tilesetFiles.begin(),tilesetFiles.end(),tilesetFile) == tilesetFiles.end()) { - printf("Reverting tileset from [%s] to [%s]\n",serverGameSettings->getTileset().c_str(),gameSettings.getTileset().c_str()); - - serverGameSettings->setTileset(gameSettings.getTileset()); - serverGameSettings->setTilesetCRC(gameSettings.getTilesetCRC()); - } - - string techtreeFile = serverGameSettings->getTech(); - if(find(techTreeFiles.begin(),techTreeFiles.end(),techtreeFile) == techTreeFiles.end()) { - printf("Reverting tech from [%s] to [%s]\n",serverGameSettings->getTech().c_str(),gameSettings.getTech().c_str()); - - serverGameSettings->setTech(gameSettings.getTech()); - serverGameSettings->setTechCRC(gameSettings.getTechCRC()); - } - } - - gameSettings = *serverGameSettings; - - if(getAllowGameDataSynchCheck() == true) { - if(waitForClientAck == true && gameSettingsUpdateCount > 0) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Waiting for client acks #1\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); - - time_t tStart = time(NULL); - bool gotAckFromAllClients = false; - while(gotAckFromAllClients == false && difftime((long int)time(NULL),tStart) <= 5) { - gotAckFromAllClients = true; - for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { - //printf("===> START slot %d - About to setGameSettings #1\n",i); - - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); - ConnectionSlot *connectionSlot = slots[slotIndex]; - if(connectionSlot != NULL && connectionSlot->isConnected()) { - if(connectionSlot->getReceivedNetworkGameStatus() == false) { - gotAckFromAllClients = false; - } - - connectionSlot->update(true,slotIndex); - } - //printf("===> END slot %d - About to setGameSettings #1\n",i); - } - } - } - - for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); - ConnectionSlot *connectionSlot = slots[slotIndex]; - if(connectionSlot != NULL && connectionSlot->isConnected()) { - connectionSlot->setReceivedNetworkGameStatus(false); - } - } - - NetworkMessageSynchNetworkGameData networkMessageSynchNetworkGameData(getGameSettings()); - broadcastMessageToConnectedClients(&networkMessageSynchNetworkGameData); - - if(waitForClientAck == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Waiting for client acks #2\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); - - time_t tStart = time(NULL); - bool gotAckFromAllClients = false; - while(gotAckFromAllClients == false && difftime((long int)time(NULL),tStart) <= 5) { - gotAckFromAllClients = true; - for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { - //printf("===> START slot %d - About to setGameSettings 2\n",slotIndex); - - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); - ConnectionSlot *connectionSlot = slots[slotIndex]; - if(connectionSlot != NULL && connectionSlot->isConnected()) { - if(connectionSlot->getReceivedNetworkGameStatus() == false) { - gotAckFromAllClients = false; - } - - connectionSlot->update(true,slotIndex); - } - //printf("===> END slot %d - About to setGameSettings 2\n",slotIndex); - } - } - } - - } - gameSettingsUpdateCount++; - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] END\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, "In [%s::%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__); + + MutexSafeWrapper safeMutex(serverSynchAccessor, CODE_AT_LINE); + string mapFile = serverGameSettings->getMap(); + // printf("Trying to set map to [%s]. Current map is + // [%s]\n",serverGameSettings->getMap().c_str(),gameSettings.getMap().c_str()); + if (gameSettings.getMapFilter() != serverGameSettings->getMapFilter()) { + if (playerSortedMaps[serverGameSettings->getMapFilter()].size() == 0) { + serverGameSettings->setMapFilter(0); + } + } + int playerIndex = serverGameSettings->getMapFilter(); + if (find(playerSortedMaps[playerIndex].begin(), + playerSortedMaps[playerIndex].end(), + mapFile) == playerSortedMaps[playerIndex].end()) { + // switch to closest map + string foundMap = ""; + for (int i = 0; i < (int)playerSortedMaps[playerIndex].size(); ++i) { + foundMap = playerSortedMaps[playerIndex][i]; + if (toLower(foundMap) > toLower(serverGameSettings->getMap())) { + break; + } + } + printf("map %s not found on this server. Switching to map %s\n", + serverGameSettings->getMap().c_str(), foundMap.c_str()); + serverGameSettings->setMap(foundMap); + } + Checksum checksum; + string file = Config::getMapPath(serverGameSettings->getMap(), "", false); + checksum.addFile(file); + serverGameSettings->setMapCRC(checksum.getSum()); + + string tilesetFile = serverGameSettings->getTileset(); + if (find(tilesetFiles.begin(), tilesetFiles.end(), tilesetFile) == + tilesetFiles.end()) { + printf("Reverting tileset from [%s] to [%s]\n", + serverGameSettings->getTileset().c_str(), + gameSettings.getTileset().c_str()); + + serverGameSettings->setTileset(gameSettings.getTileset()); + serverGameSettings->setTilesetCRC(gameSettings.getTilesetCRC()); + } + + string techtreeFile = serverGameSettings->getTech(); + if (find(techTreeFiles.begin(), techTreeFiles.end(), techtreeFile) == + techTreeFiles.end()) { + printf("Reverting tech from [%s] to [%s]\n", + serverGameSettings->getTech().c_str(), + gameSettings.getTech().c_str()); + + serverGameSettings->setTech(gameSettings.getTech()); + serverGameSettings->setTechCRC(gameSettings.getTechCRC()); + } +} + +void ServerInterface::setGameSettings(GameSettings *serverGameSettings, + bool waitForClientAck) { + MutexSafeWrapper safeMutex(serverSynchAccessor, CODE_AT_LINE); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s] START gameSettingsUpdateCount = %d, " + "waitForClientAck = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, gameSettingsUpdateCount, + waitForClientAck); + + if (serverGameSettings->getScenario() == "") { + string mapFile = serverGameSettings->getMap(); + if (find(mapFiles.begin(), mapFiles.end(), mapFile) == mapFiles.end()) { + printf("Reverting map from [%s] to [%s]\n", + serverGameSettings->getMap().c_str(), + gameSettings.getMap().c_str()); + + serverGameSettings->setMapFilter(gameSettings.getMapFilter()); + serverGameSettings->setMap(gameSettings.getMap()); + serverGameSettings->setMapCRC(gameSettings.getMapCRC()); + } + + string tilesetFile = serverGameSettings->getTileset(); + if (find(tilesetFiles.begin(), tilesetFiles.end(), tilesetFile) == + tilesetFiles.end()) { + printf("Reverting tileset from [%s] to [%s]\n", + serverGameSettings->getTileset().c_str(), + gameSettings.getTileset().c_str()); + + serverGameSettings->setTileset(gameSettings.getTileset()); + serverGameSettings->setTilesetCRC(gameSettings.getTilesetCRC()); + } + + string techtreeFile = serverGameSettings->getTech(); + if (find(techTreeFiles.begin(), techTreeFiles.end(), techtreeFile) == + techTreeFiles.end()) { + printf("Reverting tech from [%s] to [%s]\n", + serverGameSettings->getTech().c_str(), + gameSettings.getTech().c_str()); + + serverGameSettings->setTech(gameSettings.getTech()); + serverGameSettings->setTechCRC(gameSettings.getTechCRC()); + } + } + + gameSettings = *serverGameSettings; + + if (getAllowGameDataSynchCheck() == true) { + if (waitForClientAck == true && gameSettingsUpdateCount > 0) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s] Waiting for client acks #1\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__); + + time_t tStart = time(NULL); + bool gotAckFromAllClients = false; + while (gotAckFromAllClients == false && + difftime((long int)time(NULL), tStart) <= 5) { + gotAckFromAllClients = true; + for (int slotIndex = 0; + exitServer == false && slotIndex < GameConstants::maxPlayers; + ++slotIndex) { + // printf("===> START slot %d - About to setGameSettings #1\n",i); + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex], + CODE_AT_LINE_X(slotIndex)); + ConnectionSlot *connectionSlot = slots[slotIndex]; + if (connectionSlot != NULL && connectionSlot->isConnected()) { + if (connectionSlot->getReceivedNetworkGameStatus() == false) { + gotAckFromAllClients = false; + } + + connectionSlot->update(true, slotIndex); + } + // printf("===> END slot %d - About to setGameSettings #1\n",i); + } + } + } + + for (int slotIndex = 0; + exitServer == false && slotIndex < GameConstants::maxPlayers; + ++slotIndex) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex], + CODE_AT_LINE_X(slotIndex)); + ConnectionSlot *connectionSlot = slots[slotIndex]; + if (connectionSlot != NULL && connectionSlot->isConnected()) { + connectionSlot->setReceivedNetworkGameStatus(false); + } + } + + NetworkMessageSynchNetworkGameData networkMessageSynchNetworkGameData( + getGameSettings()); + broadcastMessageToConnectedClients(&networkMessageSynchNetworkGameData); + + if (waitForClientAck == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s] Waiting for client acks #2\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__); + + time_t tStart = time(NULL); + bool gotAckFromAllClients = false; + while (gotAckFromAllClients == false && + difftime((long int)time(NULL), tStart) <= 5) { + gotAckFromAllClients = true; + for (int slotIndex = 0; + exitServer == false && slotIndex < GameConstants::maxPlayers; + ++slotIndex) { + // printf("===> START slot %d - About to setGameSettings + // 2\n",slotIndex); + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex], + CODE_AT_LINE_X(slotIndex)); + ConnectionSlot *connectionSlot = slots[slotIndex]; + if (connectionSlot != NULL && connectionSlot->isConnected()) { + if (connectionSlot->getReceivedNetworkGameStatus() == false) { + gotAckFromAllClients = false; + } + + connectionSlot->update(true, slotIndex); + } + // printf("===> END slot %d - About to setGameSettings + // 2\n",slotIndex); + } + } + } + } + gameSettingsUpdateCount++; + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, "In [%s::%s] END\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__); } void ServerInterface::close() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] START\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, "In [%s::%s] START\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__); } string ServerInterface::getHumanPlayerName(int index) { - string result = Config::getInstance().getString("NetPlayerName", Socket::getHostName().c_str()); - if(index >= 0 || gameSettings.getThisFactionIndex() >= 0) { - if(index < 0) { - index = gameSettings.getThisFactionIndex(); - } - if(gameSettings.getNetworkPlayerName(index) != "") { - result = gameSettings.getNetworkPlayerName(index); - } - } - - return result; + string result = Config::getInstance().getString( + "NetPlayerName", Socket::getHostName().c_str()); + if (index >= 0 || gameSettings.getThisFactionIndex() >= 0) { + if (index < 0) { + index = gameSettings.getThisFactionIndex(); + } + if (gameSettings.getNetworkPlayerName(index) != "") { + result = gameSettings.getNetworkPlayerName(index); + } + } + + return result; } int ServerInterface::getHumanPlayerIndex() const { - return gameSettings.getStartLocationIndex(gameSettings.getThisFactionIndex()); -} - -std::map ServerInterface::publishToMasterserver() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - int slotCountUsed = 1; - int slotCountHumans = 1; - int slotCountConnectedPlayers = 1; - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - slotCountUsed = 0; - slotCountHumans = 0; - slotCountConnectedPlayers = 0; - } - - Config & config = Config::getInstance(); - std::map < string, string > publishToServerInfo; - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); - if(slots[slotIndex] != NULL) { - slotCountUsed++; - slotCountHumans++; - ConnectionSlot* connectionSlot= slots[slotIndex]; - if((connectionSlot!=NULL) && (connectionSlot->isConnected())) { - slotCountConnectedPlayers++; - } - } - } - publishToServerInfo["uuid"] = Config::getInstance().getString("PlayerId",""); - publishToServerInfo["glestVersion"] = glestVersionString; - publishToServerInfo["platform"] = getPlatformNameString() + "-" + getGITRevisionString(); - publishToServerInfo["binaryCompileDate"] = getCompileDateTime(); - publishToServerInfo["serverTitle"] = this->getGameSettings()->getGameName(); - publishToServerInfo["tech"] = this->getGameSettings()->getTech(); - publishToServerInfo["map"] = this->getGameSettings()->getMap(); - publishToServerInfo["tileset"] = this->getGameSettings()->getTileset(); - - bool updateSlots = true; - MutexSafeWrapper safeMutex2(gameStatsThreadAccessor,CODE_AT_LINE); - if(gameStats != NULL) { - for(int factionIndex = 0; factionIndex < gameStats->getFactionCount(); ++factionIndex) { - if(gameStats->getVictory(factionIndex) == true) { - updateSlots = false; - break; - } - } - } - safeMutex2.ReleaseLock(); - - if(updateSlots == true) { - publishToServerInfo["activeSlots"] = intToStr(slotCountUsed); - publishToServerInfo["networkSlots"] = intToStr(slotCountHumans); - publishToServerInfo["connectedClients"] = intToStr(slotCountConnectedPlayers); - } - - string serverPort = config.getString("PortServer", intToStr(GameConstants::serverPort).c_str()); - string externalPort = config.getString("PortExternal", serverPort.c_str()); - publishToServerInfo["externalconnectport"] = externalPort; - publishToServerInfo["privacyPlease"] = intToStr(config.getBool("PrivacyPlease","false")); - publishToServerInfo["gameStatus"] = intToStr(game_status_in_progress); - - if(publishToMasterserverThread == NULL) { - publishToServerInfo["gameCmd"] = "gameOver"; - publishToServerInfo["gameStatus"] = intToStr(game_status_finished); - } - - //printf("Host game id = %s\n",this->getGameSettings()->getGameUUID().c_str()); - publishToServerInfo["gameUUID"] = this->getGameSettings()->getGameUUID(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - return publishToServerInfo; -} - -std::map ServerInterface::publishToMasterserverStats() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - MutexSafeWrapper safeMutex(gameStatsThreadAccessor,CODE_AT_LINE); - std::map < string, string > publishToServerInfo; - if(gameStats != NULL) { - publishToServerInfo["gameUUID"] = this->getGameSettings()->getGameUUID(); - publishToServerInfo["tech"] = this->getGameSettings()->getTech(); - publishToServerInfo["factionCount"] = intToStr(gameStats->getFactionCount()); - publishToServerInfo["framesPlayed"] = intToStr(gameStats->getFramesPlayed()); - publishToServerInfo["framesToCalculatePlaytime"] = intToStr(gameStats->getFramesToCalculatePlaytime()); - publishToServerInfo["maxConcurrentUnitCount"] = intToStr(gameStats->getMaxConcurrentUnitCount()); - publishToServerInfo["totalEndGameConcurrentUnitCount"] = intToStr(gameStats->getTotalEndGameConcurrentUnitCount()); - publishToServerInfo["isHeadlessServer"] = intToStr(gameStats->getIsMasterserverMode()); - - for(int factionIndex = 0; factionIndex < gameStats->getFactionCount(); ++factionIndex) { - publishToServerInfo["factionIndex_" + intToStr(factionIndex)] = intToStr(factionIndex); - publishToServerInfo["controlType_" + intToStr(factionIndex)] = intToStr(gameStats->getControl(factionIndex)); - publishToServerInfo["resourceMultiplier_" + intToStr(factionIndex)] = floatToStr(gameStats->getResourceMultiplier(factionIndex)); - publishToServerInfo["factionTypeName_" + intToStr(factionIndex)] = gameStats->getFactionTypeName(factionIndex); - publishToServerInfo["personalityType_" + intToStr(factionIndex)] = intToStr(gameStats->getPersonalityType(factionIndex)); - publishToServerInfo["teamIndex_" + intToStr(factionIndex)] = intToStr(gameStats->getTeam(factionIndex)); - publishToServerInfo["wonGame_" + intToStr(factionIndex)] = intToStr(gameStats->getVictory(factionIndex)); - publishToServerInfo["killCount_" + intToStr(factionIndex)] = intToStr(gameStats->getKills(factionIndex)); - publishToServerInfo["enemyKillCount_" + intToStr(factionIndex)] = intToStr(gameStats->getEnemyKills(factionIndex)); - publishToServerInfo["deathCount_" + intToStr(factionIndex)] = intToStr(gameStats->getDeaths(factionIndex)); - publishToServerInfo["unitsProducedCount_" + intToStr(factionIndex)] = intToStr(gameStats->getUnitsProduced(factionIndex)); - publishToServerInfo["resourceHarvestedCount_" + intToStr(factionIndex)] = intToStr(gameStats->getResourcesHarvested(factionIndex)); - publishToServerInfo["playerName_" + intToStr(factionIndex)] = gameStats->getPlayerName(factionIndex); - publishToServerInfo["quitBeforeGameEnd_" + intToStr(factionIndex)] = intToStr(gameStats->getPlayerLeftBeforeEnd(factionIndex)); - publishToServerInfo["quitTime_" + intToStr(factionIndex)] = intToStr(gameStats->getTimePlayerLeft(factionIndex)); - publishToServerInfo["playerUUID_" + intToStr(factionIndex)] = this->getGameSettings()->getNetworkPlayerUUID(factionIndex); - publishToServerInfo["platform_" + intToStr(factionIndex)] = this->getGameSettings()->getNetworkPlayerPlatform(factionIndex); - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - return publishToServerInfo; + return gameSettings.getStartLocationIndex(gameSettings.getThisFactionIndex()); +} + +std::map ServerInterface::publishToMasterserver() { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + int slotCountUsed = 1; + int slotCountHumans = 1; + int slotCountConnectedPlayers = 1; + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + slotCountUsed = 0; + slotCountHumans = 0; + slotCountConnectedPlayers = 0; + } + + Config &config = Config::getInstance(); + std::map publishToServerInfo; + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + for (int slotIndex = 0; + exitServer == false && slotIndex < GameConstants::maxPlayers; + ++slotIndex) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex], + CODE_AT_LINE_X(slotIndex)); + if (slots[slotIndex] != NULL) { + slotCountUsed++; + slotCountHumans++; + ConnectionSlot *connectionSlot = slots[slotIndex]; + if ((connectionSlot != NULL) && (connectionSlot->isConnected())) { + slotCountConnectedPlayers++; + } + } + } + publishToServerInfo["uuid"] = Config::getInstance().getString("PlayerId", ""); + publishToServerInfo["glestVersion"] = glestVersionString; + publishToServerInfo["platform"] = + getPlatformNameString() + "-" + getGITRevisionString(); + publishToServerInfo["binaryCompileDate"] = getCompileDateTime(); + publishToServerInfo["serverTitle"] = this->getGameSettings()->getGameName(); + publishToServerInfo["tech"] = this->getGameSettings()->getTech(); + publishToServerInfo["map"] = this->getGameSettings()->getMap(); + publishToServerInfo["tileset"] = this->getGameSettings()->getTileset(); + + bool updateSlots = true; + MutexSafeWrapper safeMutex2(gameStatsThreadAccessor, CODE_AT_LINE); + if (gameStats != NULL) { + for (int factionIndex = 0; factionIndex < gameStats->getFactionCount(); + ++factionIndex) { + if (gameStats->getVictory(factionIndex) == true) { + updateSlots = false; + break; + } + } + } + safeMutex2.ReleaseLock(); + + if (updateSlots == true) { + publishToServerInfo["activeSlots"] = intToStr(slotCountUsed); + publishToServerInfo["networkSlots"] = intToStr(slotCountHumans); + publishToServerInfo["connectedClients"] = + intToStr(slotCountConnectedPlayers); + } + + string serverPort = config.getString( + "PortServer", intToStr(GameConstants::serverPort).c_str()); + string externalPort = config.getString("PortExternal", serverPort.c_str()); + publishToServerInfo["externalconnectport"] = externalPort; + publishToServerInfo["privacyPlease"] = + intToStr(config.getBool("PrivacyPlease", "false")); + publishToServerInfo["gameStatus"] = intToStr(game_status_in_progress); + + if (publishToMasterserverThread == NULL) { + publishToServerInfo["gameCmd"] = "gameOver"; + publishToServerInfo["gameStatus"] = intToStr(game_status_finished); + } + + // printf("Host game id = + // %s\n",this->getGameSettings()->getGameUUID().c_str()); + publishToServerInfo["gameUUID"] = this->getGameSettings()->getGameUUID(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + return publishToServerInfo; +} + +std::map ServerInterface::publishToMasterserverStats() { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + MutexSafeWrapper safeMutex(gameStatsThreadAccessor, CODE_AT_LINE); + std::map publishToServerInfo; + if (gameStats != NULL) { + publishToServerInfo["gameUUID"] = this->getGameSettings()->getGameUUID(); + publishToServerInfo["tech"] = this->getGameSettings()->getTech(); + publishToServerInfo["factionCount"] = + intToStr(gameStats->getFactionCount()); + publishToServerInfo["framesPlayed"] = + intToStr(gameStats->getFramesPlayed()); + publishToServerInfo["framesToCalculatePlaytime"] = + intToStr(gameStats->getFramesToCalculatePlaytime()); + publishToServerInfo["maxConcurrentUnitCount"] = + intToStr(gameStats->getMaxConcurrentUnitCount()); + publishToServerInfo["totalEndGameConcurrentUnitCount"] = + intToStr(gameStats->getTotalEndGameConcurrentUnitCount()); + publishToServerInfo["isHeadlessServer"] = + intToStr(gameStats->getIsMasterserverMode()); + + for (int factionIndex = 0; factionIndex < gameStats->getFactionCount(); + ++factionIndex) { + publishToServerInfo["factionIndex_" + intToStr(factionIndex)] = + intToStr(factionIndex); + publishToServerInfo["controlType_" + intToStr(factionIndex)] = + intToStr(gameStats->getControl(factionIndex)); + publishToServerInfo["resourceMultiplier_" + intToStr(factionIndex)] = + floatToStr(gameStats->getResourceMultiplier(factionIndex)); + publishToServerInfo["factionTypeName_" + intToStr(factionIndex)] = + gameStats->getFactionTypeName(factionIndex); + publishToServerInfo["personalityType_" + intToStr(factionIndex)] = + intToStr(gameStats->getPersonalityType(factionIndex)); + publishToServerInfo["teamIndex_" + intToStr(factionIndex)] = + intToStr(gameStats->getTeam(factionIndex)); + publishToServerInfo["wonGame_" + intToStr(factionIndex)] = + intToStr(gameStats->getVictory(factionIndex)); + publishToServerInfo["killCount_" + intToStr(factionIndex)] = + intToStr(gameStats->getKills(factionIndex)); + publishToServerInfo["enemyKillCount_" + intToStr(factionIndex)] = + intToStr(gameStats->getEnemyKills(factionIndex)); + publishToServerInfo["deathCount_" + intToStr(factionIndex)] = + intToStr(gameStats->getDeaths(factionIndex)); + publishToServerInfo["unitsProducedCount_" + intToStr(factionIndex)] = + intToStr(gameStats->getUnitsProduced(factionIndex)); + publishToServerInfo["resourceHarvestedCount_" + intToStr(factionIndex)] = + intToStr(gameStats->getResourcesHarvested(factionIndex)); + publishToServerInfo["playerName_" + intToStr(factionIndex)] = + gameStats->getPlayerName(factionIndex); + publishToServerInfo["quitBeforeGameEnd_" + intToStr(factionIndex)] = + intToStr(gameStats->getPlayerLeftBeforeEnd(factionIndex)); + publishToServerInfo["quitTime_" + intToStr(factionIndex)] = + intToStr(gameStats->getTimePlayerLeft(factionIndex)); + publishToServerInfo["playerUUID_" + intToStr(factionIndex)] = + this->getGameSettings()->getNetworkPlayerUUID(factionIndex); + publishToServerInfo["platform_" + intToStr(factionIndex)] = + this->getGameSettings()->getNetworkPlayerPlatform(factionIndex); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + } + return publishToServerInfo; } void ServerInterface::setGameStats(Stats *stats) { - if(stats == NULL) { - return; - } - MutexSafeWrapper safeMutex(gameStatsThreadAccessor,CODE_AT_LINE); - if(gameStats == NULL) { - gameStats = new Stats(); - } - *gameStats = *stats; -} - -void ServerInterface::simpleTask(BaseThread *callingThread,void *userdata) { - MutexSafeWrapper safeMutex(masterServerThreadAccessor,CODE_AT_LINE); - - if(difftime((long int)time(NULL),lastMasterserverHeartbeatTime) >= MASTERSERVER_HEARTBEAT_GAME_STATUS_SECONDS) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Checking to see masterserver needs an update of the game status [%d] callingThread [%p] publishToMasterserverThread [%p]\n",needToRepublishToMasterserver,callingThread,publishToMasterserverThread); - - lastMasterserverHeartbeatTime = time(NULL); - if(needToRepublishToMasterserver == true) { - try { - if(Config::getInstance().getString("Masterserver","") != "") { - string request = Config::getInstance().getString("Masterserver"); - if(request != "") { - endPathWithSlash(request,false); - } - request += "addServerInfo.php?"; - - std::map newPublishToServerInfo = publishToMasterserver(); - - CURL *handle = SystemFlags::initHTTP(); - for(std::map::const_iterator iterMap = newPublishToServerInfo.begin(); - iterMap != newPublishToServerInfo.end(); ++iterMap) { - - request += iterMap->first; - request += "="; - request += SystemFlags::escapeURL(iterMap->second,handle); - request += "&"; - } - - //printf("The Host request is:\n%s\n",request.c_str()); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("The Host request is:\n%s\n",request.c_str()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line %d] the request is:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,request.c_str()); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Calling masterserver [%s]...\n",request.c_str()); - - std::string serverInfo = SystemFlags::getHTTP(request,handle); - //printf("Result:\n%s\n",serverInfo .c_str()); - - string requestStats = Config::getInstance().getString("Masterserver"); - if(requestStats != "") { - endPathWithSlash(requestStats,false); - } - requestStats += "addGameStats.php?"; - - std::map newPublishToServerInfoStats = publishToMasterserverStats(); - if(newPublishToServerInfoStats.empty() == false) { - for(std::map::const_iterator iterMap = newPublishToServerInfoStats.begin(); - iterMap != newPublishToServerInfoStats.end(); ++iterMap) { - - requestStats += iterMap->first; - requestStats += "="; - requestStats += SystemFlags::escapeURL(iterMap->second,handle); - requestStats += "&"; - } - - //printf("The Host stats request is:\n%s\n",requestStats.c_str()); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("The Host request is:\n%s\n",requestStats.c_str()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line %d] the request is:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,requestStats.c_str()); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Calling masterserver [%s]...\n",requestStats.c_str()); - - std::string serverInfoStats = SystemFlags::getHTTP(requestStats,handle); - //printf("Result:\n%s\n",serverInfoStats .c_str()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line %d] the result is:\n'%s'\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,serverInfoStats.c_str()); - } - - SystemFlags::cleanupHTTP(&handle); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Done Calling masterserver\n"); - - //printf("the result is:\n'%s'\n",serverInfo.c_str()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line %d] the result is:\n'%s'\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,serverInfo.c_str()); - } - else { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line %d] error, no masterserver defined!\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - } - catch(const exception &ex) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line %d] error during game status update: [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - } - } - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - DumpStatsToLog(false); - } - } - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - //printf("Attempt Accept\n"); - if(serverSocketAdmin != NULL) { - Socket *cli = serverSocketAdmin->accept(false); - if(cli != NULL) { - printf("Got status request connection, dumping info...\n"); - - string data = DumpStatsToLog(true); - cli->send(data.c_str(),(int)data.length()); - cli->disconnectSocket(); - } - } - } + if (stats == NULL) { + return; + } + MutexSafeWrapper safeMutex(gameStatsThreadAccessor, CODE_AT_LINE); + if (gameStats == NULL) { + gameStats = new Stats(); + } + *gameStats = *stats; } -std::string ServerInterface::DumpStatsToLog(bool dumpToStringOnly) const { - string headlessLogFile = Config::getInstance().getString("HeadlessLogFile","headless.log"); - if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { - headlessLogFile = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + headlessLogFile ; - } - else { - string userData = Config::getInstance().getString("UserData_Root",""); - if(userData != "") { - endPathWithSlash(userData); +void ServerInterface::simpleTask(BaseThread *callingThread, void *userdata) { + MutexSafeWrapper safeMutex(masterServerThreadAccessor, CODE_AT_LINE); + + if (difftime((long int)time(NULL), lastMasterserverHeartbeatTime) >= + MASTERSERVER_HEARTBEAT_GAME_STATUS_SECONDS) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) + SystemFlags::OutputDebug(SystemFlags::debugNetwork, + "In [%s::%s Line %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Checking to see masterserver needs an update of the game status " + "[%d] callingThread [%p] publishToMasterserverThread [%p]\n", + needToRepublishToMasterserver, callingThread, + publishToMasterserverThread); + + lastMasterserverHeartbeatTime = time(NULL); + if (needToRepublishToMasterserver == true) { + try { + if (Config::getInstance().getString("Masterserver", "") != "") { + string request = Config::getInstance().getString("Masterserver"); + if (request != "") { + endPathWithSlash(request, false); + } + request += "addServerInfo.php?"; + + std::map newPublishToServerInfo = + publishToMasterserver(); + + CURL *handle = SystemFlags::initHTTP(); + for (std::map::const_iterator iterMap = + newPublishToServerInfo.begin(); + iterMap != newPublishToServerInfo.end(); ++iterMap) { + + request += iterMap->first; + request += "="; + request += SystemFlags::escapeURL(iterMap->second, handle); + request += "&"; + } + + // printf("The Host request is:\n%s\n",request.c_str()); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("The Host request is:\n%s\n", request.c_str()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line %d] the request is:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, request.c_str()); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Calling masterserver [%s]...\n", request.c_str()); + + std::string serverInfo = SystemFlags::getHTTP(request, handle); + // printf("Result:\n%s\n",serverInfo .c_str()); + + string requestStats = Config::getInstance().getString("Masterserver"); + if (requestStats != "") { + endPathWithSlash(requestStats, false); + } + requestStats += "addGameStats.php?"; + + std::map newPublishToServerInfoStats = + publishToMasterserverStats(); + if (newPublishToServerInfoStats.empty() == false) { + for (std::map::const_iterator iterMap = + newPublishToServerInfoStats.begin(); + iterMap != newPublishToServerInfoStats.end(); ++iterMap) { + + requestStats += iterMap->first; + requestStats += "="; + requestStats += SystemFlags::escapeURL(iterMap->second, handle); + requestStats += "&"; + } + + // printf("The Host stats request is:\n%s\n",requestStats.c_str()); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("The Host request is:\n%s\n", requestStats.c_str()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line %d] the request is:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, requestStats.c_str()); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Calling masterserver [%s]...\n", requestStats.c_str()); + + std::string serverInfoStats = + SystemFlags::getHTTP(requestStats, handle); + // printf("Result:\n%s\n",serverInfoStats .c_str()); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line %d] the result is:\n'%s'\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, serverInfoStats.c_str()); + } + + SystemFlags::cleanupHTTP(&handle); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("Done Calling masterserver\n"); + + // printf("the result is:\n'%s'\n",serverInfo.c_str()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugNetwork) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugNetwork, + "In [%s::%s Line %d] the result is:\n'%s'\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, serverInfo.c_str()); + } else { + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line %d] error, no masterserver defined!\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); } - headlessLogFile = userData + headlessLogFile ; - } - - ostringstream out; - out << "=========================================" << std::endl; - out << "Headless Server Current Game information:" << std::endl; - out << "=========================================" << std::endl; - - int connectedSlotCount = 0; - for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { - - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); - ConnectionSlot *slot = slots[slotIndex]; - if(slot != NULL) { - - connectedSlotCount++; - out << "Network connection for index: " << slotIndex << std::endl; - out << "------------------------------" << std::endl; - out << "Connected: " << boolToStr(slot->isConnected()) << std::endl; - out << "Handshake received: " << boolToStr(slot->getConnectHasHandshaked()) << std::endl; - if(slot->isConnected() == true) { - - time_t connectTime = slot->getConnectedTime(); - //struct tm *loctime = localtime (&connectTime); - struct tm loctime = threadsafe_localtime(connectTime); - char szBuf[8096] = ""; - strftime(szBuf,100,"%Y-%m-%d %H:%M:%S",&loctime); - - const int HOURS_IN_DAY = 24; - const int MINUTES_IN_HOUR = 60; - const int SECONDS_IN_MINUTE = 60; - int InSeconds = difftime((long int)time(NULL),slot->getConnectedTime()); - // compute seconds - int seconds = InSeconds % SECONDS_IN_MINUTE ; - // throw away seconds used in previous statement and convert to minutes - int InMinutes = InSeconds / SECONDS_IN_MINUTE ; - // compute minutes - int minutes = InMinutes % MINUTES_IN_HOUR ; - - // throw away minutes used in previous statement and convert to hours - int InHours = InMinutes / MINUTES_IN_HOUR ; - // compute hours - int hours = InHours % HOURS_IN_DAY ; - - out << "Connected at: " << szBuf << std::endl; - out << "Connection duration: " << hours << " hours " << minutes << " minutes " << seconds << " seconds." << std::endl; - out << "Player Index: " << slot->getPlayerIndex() << std::endl; - out << "IP Address: " << slot->getIpAddress() << std::endl; - out << "Player name: " << slot->getName() << std::endl; - out << "Player uuid: " << slot->getUUID() << std::endl; - out << "Language: " << slot->getNetworkPlayerLanguage() << std::endl; - out << "Game Version: " << slot->getVersionString() << std::endl; - out << "Session id: " << slot->getSessionKey() << std::endl; - out << "Socket id: " << slot->getSocketId() << std::endl; - } - } - } - out << "Total Slot Count: " << connectedSlotCount << std::endl; - out << "=========================================" << std::endl; - - std::string result = out.str(); - - if(dumpToStringOnly == false) { + } catch (const exception &ex) { + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line %d] error during game status update: [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + } + } + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + DumpStatsToLog(false); + } + } + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + // printf("Attempt Accept\n"); + if (serverSocketAdmin != NULL) { + Socket *cli = serverSocketAdmin->accept(false); + if (cli != NULL) { + printf("Got status request connection, dumping info...\n"); + + string data = DumpStatsToLog(true); + cli->send(data.c_str(), (int)data.length()); + cli->disconnectSocket(); + } + } + } +} + +std::string ServerInterface::DumpStatsToLog(bool dumpToStringOnly) const { + string headlessLogFile = + Config::getInstance().getString("HeadlessLogFile", "headless.log"); + if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") { + headlessLogFile = + getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + + headlessLogFile; + } else { + string userData = Config::getInstance().getString("UserData_Root", ""); + if (userData != "") { + endPathWithSlash(userData); + } + headlessLogFile = userData + headlessLogFile; + } + + ostringstream out; + out << "=========================================" << std::endl; + out << "Headless Server Current Game information:" << std::endl; + out << "=========================================" << std::endl; + + int connectedSlotCount = 0; + for (int slotIndex = 0; + exitServer == false && slotIndex < GameConstants::maxPlayers; + ++slotIndex) { + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex], + CODE_AT_LINE_X(slotIndex)); + ConnectionSlot *slot = slots[slotIndex]; + if (slot != NULL) { + + connectedSlotCount++; + out << "Network connection for index: " << slotIndex << std::endl; + out << "------------------------------" << std::endl; + out << "Connected: " << boolToStr(slot->isConnected()) << std::endl; + out << "Handshake received: " + << boolToStr(slot->getConnectHasHandshaked()) << std::endl; + if (slot->isConnected() == true) { + + time_t connectTime = slot->getConnectedTime(); + // struct tm *loctime = localtime (&connectTime); + struct tm loctime = threadsafe_localtime(connectTime); + char szBuf[8096] = ""; + strftime(szBuf, 100, "%Y-%m-%d %H:%M:%S", &loctime); + + const int HOURS_IN_DAY = 24; + const int MINUTES_IN_HOUR = 60; + const int SECONDS_IN_MINUTE = 60; + int InSeconds = + difftime((long int)time(NULL), slot->getConnectedTime()); + // compute seconds + int seconds = InSeconds % SECONDS_IN_MINUTE; + // throw away seconds used in previous statement and convert to minutes + int InMinutes = InSeconds / SECONDS_IN_MINUTE; + // compute minutes + int minutes = InMinutes % MINUTES_IN_HOUR; + + // throw away minutes used in previous statement and convert to hours + int InHours = InMinutes / MINUTES_IN_HOUR; + // compute hours + int hours = InHours % HOURS_IN_DAY; + + out << "Connected at: " << szBuf << std::endl; + out << "Connection duration: " << hours << " hours " << minutes + << " minutes " << seconds << " seconds." << std::endl; + out << "Player Index: " << slot->getPlayerIndex() << std::endl; + out << "IP Address: " << slot->getIpAddress() << std::endl; + out << "Player name: " << slot->getName() << std::endl; + out << "Player uuid: " << slot->getUUID() << std::endl; + out << "Language: " << slot->getNetworkPlayerLanguage() << std::endl; + out << "Game Version: " << slot->getVersionString() << std::endl; + out << "Session id: " << slot->getSessionKey() << std::endl; + out << "Socket id: " << slot->getSocketId() << std::endl; + } + } + } + out << "Total Slot Count: " << connectedSlotCount << std::endl; + out << "=========================================" << std::endl; + + std::string result = out.str(); + + if (dumpToStringOnly == false) { #if defined(WIN32) && !defined(__MINGW32__) - FILE *fp = _wfopen(utf8_decode(headlessLogFile ).c_str(), L"w"); - std::ofstream logFile(fp); + FILE *fp = _wfopen(utf8_decode(headlessLogFile).c_str(), L"w"); + std::ofstream logFile(fp); #else - std::ofstream logFile; - logFile.open(headlessLogFile .c_str(), ios_base::out | ios_base::trunc); + std::ofstream logFile; + logFile.open(headlessLogFile.c_str(), ios_base::out | ios_base::trunc); #endif - logFile << result; - logFile.close(); + logFile << result; + logFile.close(); #if defined(WIN32) && !defined(__MINGW32__) - if(fp) { - fclose(fp); - } + if (fp) { + fclose(fp); + } #endif - } + } - return result; + return result; } void ServerInterface::notifyBadClientConnectAttempt(string ipAddress) { - //printf("In [%s::%s Line: %d] ipAddress [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ipAddress.c_str()); - - if(badClientConnectIPList.find(ipAddress) == badClientConnectIPList.end()) { - badClientConnectIPList[ipAddress] = make_pair(0,(long int)time(NULL)); - } - - pair &lastBadConnectionAttempt = badClientConnectIPList[ipAddress]; - - const uint64 BLOCK_BAD_CLIENT_CONNECT_MAX_SECONDS = Config::getInstance().getInt("BlockBadClientConnectMaxSeconds", "60"); - const uint64 BLOCK_BAD_CLIENT_CONNECT_MAX_ATTEMPTS = Config::getInstance().getInt("BlockBadClientConnectMaxAttempts", "6"); - bool addToBlockedClientsList = false; - - if(difftime((long int)time(NULL),lastBadConnectionAttempt.second) <= BLOCK_BAD_CLIENT_CONNECT_MAX_SECONDS) { - - if(lastBadConnectionAttempt.first+1 > BLOCK_BAD_CLIENT_CONNECT_MAX_ATTEMPTS) { - addToBlockedClientsList = true; - } - } - else { - // Reset after x seconds - lastBadConnectionAttempt.first = 0; - } - - if(this->getAllowInGameConnections() == true) { - printf("notifyBadClientConnectAttempt() #1: %s!\n",ipAddress.c_str()); - } - - if(addToBlockedClientsList == true) { - serverSocket.addIPAddressToBlockedList(ipAddress); - } - - lastBadConnectionAttempt.first++; - lastBadConnectionAttempt.second = time(NULL); + // printf("In [%s::%s Line: %d] ipAddress + // [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ipAddress.c_str()); + + if (badClientConnectIPList.find(ipAddress) == badClientConnectIPList.end()) { + badClientConnectIPList[ipAddress] = make_pair(0, (long int)time(NULL)); + } + + pair &lastBadConnectionAttempt = + badClientConnectIPList[ipAddress]; + + const uint64 BLOCK_BAD_CLIENT_CONNECT_MAX_SECONDS = + Config::getInstance().getInt("BlockBadClientConnectMaxSeconds", "60"); + const uint64 BLOCK_BAD_CLIENT_CONNECT_MAX_ATTEMPTS = + Config::getInstance().getInt("BlockBadClientConnectMaxAttempts", "6"); + bool addToBlockedClientsList = false; + + if (difftime((long int)time(NULL), lastBadConnectionAttempt.second) <= + BLOCK_BAD_CLIENT_CONNECT_MAX_SECONDS) { + + if (lastBadConnectionAttempt.first + 1 > + BLOCK_BAD_CLIENT_CONNECT_MAX_ATTEMPTS) { + addToBlockedClientsList = true; + } + } else { + // Reset after x seconds + lastBadConnectionAttempt.first = 0; + } + + if (this->getAllowInGameConnections() == true) { + printf("notifyBadClientConnectAttempt() #1: %s!\n", ipAddress.c_str()); + } + + if (addToBlockedClientsList == true) { + serverSocket.addIPAddressToBlockedList(ipAddress); + } + + lastBadConnectionAttempt.first++; + lastBadConnectionAttempt.second = time(NULL); } bool ServerInterface::getStartInGameConnectionLaunch() { - bool result = false; - for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { - MutexSafeWrapper safeMutex(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); - if(slots[slotIndex] != NULL) { - - ConnectionSlot *slot = slots[slotIndex]; - if(slot->getStartInGameConnectionLaunch() == true) { - result = true; - break; - } - } - } - return result; + bool result = false; + for (int slotIndex = 0; + exitServer == false && slotIndex < GameConstants::maxPlayers; + ++slotIndex) { + MutexSafeWrapper safeMutex(slotAccessorMutexes[slotIndex], + CODE_AT_LINE_X(slotIndex)); + if (slots[slotIndex] != NULL) { + + ConnectionSlot *slot = slots[slotIndex]; + if (slot->getStartInGameConnectionLaunch() == true) { + result = true; + break; + } + } + } + return result; } bool ServerInterface::getPauseForInGameConnection() { - bool result = false; - for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { - MutexSafeWrapper safeMutex(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); - if(slots[slotIndex] != NULL) { - - ConnectionSlot *slot = slots[slotIndex]; - if(slot->getPauseForInGameConnection() == true) { - result = true; - break; - } - } - } - return result; + bool result = false; + for (int slotIndex = 0; + exitServer == false && slotIndex < GameConstants::maxPlayers; + ++slotIndex) { + MutexSafeWrapper safeMutex(slotAccessorMutexes[slotIndex], + CODE_AT_LINE_X(slotIndex)); + if (slots[slotIndex] != NULL) { + + ConnectionSlot *slot = slots[slotIndex]; + if (slot->getPauseForInGameConnection() == true) { + result = true; + break; + } + } + } + return result; } bool ServerInterface::getUnPauseForInGameConnection() { - bool result = false; - for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { - MutexSafeWrapper safeMutex(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); - if(slots[slotIndex] != NULL) { - - ConnectionSlot *slot = slots[slotIndex]; - if(slot->isConnected() == true) { - if(slot->isReady() == true) { - result = true; - if(slot->getUnPauseForInGameConnection() == false) { - result = false; - break; - } - } - else { - result = false; - break; - } - } - } - } - if(result == true) { - resumeGameStartTime = time(NULL); - } - return result; -} - -ConnectionSlot * ServerInterface::findSlotForUUID(string uuid, bool unConnectedOnly) { - ConnectionSlot *result = NULL; - if(uuid != "") { - for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { - - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); - ConnectionSlot *connectionSlot= slots[slotIndex]; - - if(connectionSlot != NULL) { - if(connectionSlot->getUUID() == uuid) { - if(unConnectedOnly == false || - (unConnectedOnly == true && connectionSlot->isConnected() == false)) { - - if(result == NULL || - (result->getConnectedTime() > connectionSlot->getConnectedTime())) - - result = connectionSlot; - } - } - } - } - } - return result; + bool result = false; + for (int slotIndex = 0; + exitServer == false && slotIndex < GameConstants::maxPlayers; + ++slotIndex) { + MutexSafeWrapper safeMutex(slotAccessorMutexes[slotIndex], + CODE_AT_LINE_X(slotIndex)); + if (slots[slotIndex] != NULL) { + + ConnectionSlot *slot = slots[slotIndex]; + if (slot->isConnected() == true) { + if (slot->isReady() == true) { + result = true; + if (slot->getUnPauseForInGameConnection() == false) { + result = false; + break; + } + } else { + result = false; + break; + } + } + } + } + if (result == true) { + resumeGameStartTime = time(NULL); + } + return result; +} + +ConnectionSlot *ServerInterface::findSlotForUUID(string uuid, + bool unConnectedOnly) { + ConnectionSlot *result = NULL; + if (uuid != "") { + for (int slotIndex = 0; + exitServer == false && slotIndex < GameConstants::maxPlayers; + ++slotIndex) { + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex], + CODE_AT_LINE_X(slotIndex)); + ConnectionSlot *connectionSlot = slots[slotIndex]; + + if (connectionSlot != NULL) { + if (connectionSlot->getUUID() == uuid) { + if (unConnectedOnly == false || + (unConnectedOnly == true && + connectionSlot->isConnected() == false)) { + + if (result == NULL || (result->getConnectedTime() > + connectionSlot->getConnectedTime())) + + result = connectionSlot; + } + } + } + } + } + return result; } void ServerInterface::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *serverInterfaceNode = rootNode->addChild("ServerInterface"); - - for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { - MutexSafeWrapper safeMutex(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); - if(slots[slotIndex] != NULL) { - - XmlNode *slotNode = serverInterfaceNode->addChild("Slot"); - - ConnectionSlot *slot = slots[slotIndex]; - if(slot != NULL) { - slotNode->addAttribute("isconnected",intToStr(slot->isConnected()), mapTagReplacements); - slotNode->addAttribute("sessionkey",intToStr(slot->getSessionKey()), mapTagReplacements); - slotNode->addAttribute("ipaddress",slot->getSocket(false)->getIpAddress(), mapTagReplacements); - slotNode->addAttribute("name",slot->getName(), mapTagReplacements); - slotNode->addAttribute("uuid",slot->getUUID(), mapTagReplacements); - } - else { - slotNode->addAttribute("isconnected",intToStr(false), mapTagReplacements); - } - } - } -} - -}}//end namespace + std::map mapTagReplacements; + XmlNode *serverInterfaceNode = rootNode->addChild("ServerInterface"); + + for (int slotIndex = 0; + exitServer == false && slotIndex < GameConstants::maxPlayers; + ++slotIndex) { + MutexSafeWrapper safeMutex(slotAccessorMutexes[slotIndex], + CODE_AT_LINE_X(slotIndex)); + if (slots[slotIndex] != NULL) { + + XmlNode *slotNode = serverInterfaceNode->addChild("Slot"); + + ConnectionSlot *slot = slots[slotIndex]; + if (slot != NULL) { + slotNode->addAttribute("isconnected", intToStr(slot->isConnected()), + mapTagReplacements); + slotNode->addAttribute("sessionkey", intToStr(slot->getSessionKey()), + mapTagReplacements); + slotNode->addAttribute("ipaddress", + slot->getSocket(false)->getIpAddress(), + mapTagReplacements); + slotNode->addAttribute("name", slot->getName(), mapTagReplacements); + slotNode->addAttribute("uuid", slot->getUUID(), mapTagReplacements); + } else { + slotNode->addAttribute("isconnected", intToStr(false), + mapTagReplacements); + } + } + } +} + +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/network/server_interface.h b/source/glest_game/network/server_interface.h index 06884a495..c2acc356d 100644 --- a/source/glest_game/network/server_interface.h +++ b/source/glest_game/network/server_interface.h @@ -13,283 +13,308 @@ #define _GLEST_GAME_SERVERINTERFACE_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include +#include "connection_slot.h" #include "game_constants.h" +#include "leak_dumper.h" #include "network_interface.h" -#include "connection_slot.h" #include "socket.h" -#include "leak_dumper.h" +#include -using std::vector; using Shared::Platform::ServerSocket; +using std::vector; -namespace Shared { namespace PlatformCommon { class FTPServerThread; }} +namespace Shared { +namespace PlatformCommon { +class FTPServerThread; +} +} // namespace Shared -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { class Stats; // ===================================================== // class ServerInterface // ===================================================== -class ServerInterface: public GameNetworkInterface, - public ConnectionSlotCallbackInterface, - // This is for publishing game status to the masterserver - public SimpleTaskCallbackInterface, - public FTPClientValidationInterface { +class ServerInterface + : public GameNetworkInterface, + public ConnectionSlotCallbackInterface, + // This is for publishing game status to the masterserver + public SimpleTaskCallbackInterface, + public FTPClientValidationInterface { -class TextMessageQueue { -public: + class TextMessageQueue { + public: string text; int teamIndex; bool echoLocal; string targetLanguage; -}; + }; private: - ConnectionSlot* slots[GameConstants::maxPlayers]; - Mutex *slotAccessorMutexes[GameConstants::maxPlayers]; + ConnectionSlot *slots[GameConstants::maxPlayers]; + Mutex *slotAccessorMutexes[GameConstants::maxPlayers]; - ServerSocket serverSocket; + ServerSocket serverSocket; - Mutex *switchSetupRequestsSynchAccessor; - SwitchSetupRequest* switchSetupRequests[GameConstants::maxPlayers]; + Mutex *switchSetupRequestsSynchAccessor; + SwitchSetupRequest *switchSetupRequests[GameConstants::maxPlayers]; - Mutex *serverSynchAccessor; - int currentFrameCount; + Mutex *serverSynchAccessor; + int currentFrameCount; - time_t gameStartTime; + time_t gameStartTime; - time_t lastGlobalLagCheckTime; + time_t lastGlobalLagCheckTime; - SimpleTaskThread *publishToMasterserverThread; - Mutex *masterServerThreadAccessor; - time_t lastMasterserverHeartbeatTime; - bool needToRepublishToMasterserver; + SimpleTaskThread *publishToMasterserverThread; + Mutex *masterServerThreadAccessor; + time_t lastMasterserverHeartbeatTime; + bool needToRepublishToMasterserver; - ::Shared::PlatformCommon::FTPServerThread *ftpServer; - bool exitServer; - int64 nextEventId; + ::Shared::PlatformCommon::FTPServerThread *ftpServer; + bool exitServer; + int64 nextEventId; - Mutex *textMessageQueueThreadAccessor; - vector textMessageQueue; + Mutex *textMessageQueueThreadAccessor; + vector textMessageQueue; - Mutex *broadcastMessageQueueThreadAccessor; - vector > broadcastMessageQueue; + Mutex *broadcastMessageQueueThreadAccessor; + vector> broadcastMessageQueue; - Mutex *inBroadcastMessageThreadAccessor; - bool inBroadcastMessage; + Mutex *inBroadcastMessageThreadAccessor; + bool inBroadcastMessage; - bool masterserverAdminRequestLaunch; + bool masterserverAdminRequestLaunch; - vector mapFiles; - vector playerSortedMaps[GameConstants::maxPlayers+1]; - vector techTreeFiles; - vector tilesetFiles; + vector mapFiles; + vector playerSortedMaps[GameConstants::maxPlayers + 1]; + vector techTreeFiles; + vector tilesetFiles; - map > badClientConnectIPList; + map> badClientConnectIPList; - ServerSocket *serverSocketAdmin; - MasterSlaveThreadController masterController; + ServerSocket *serverSocketAdmin; + MasterSlaveThreadController masterController; - bool gameHasBeenInitiated; - int gameSettingsUpdateCount; + bool gameHasBeenInitiated; + int gameSettingsUpdateCount; - bool allowInGameConnections; - bool gameLaunched; - time_t lastListenerSlotCheckTime; + bool allowInGameConnections; + bool gameLaunched; + time_t lastListenerSlotCheckTime; - time_t resumeGameStartTime; + time_t resumeGameStartTime; - Mutex *gameStatsThreadAccessor; - Stats *gameStats; + Mutex *gameStatsThreadAccessor; + Stats *gameStats; - bool clientsAutoPausedDueToLag; - Chrono clientsAutoPausedDueToLagTimer; - Chrono lastBroadcastCommandsTimer; - ClientLagCallbackInterface *clientLagCallbackInterface; + bool clientsAutoPausedDueToLag; + Chrono clientsAutoPausedDueToLagTimer; + Chrono lastBroadcastCommandsTimer; + ClientLagCallbackInterface *clientLagCallbackInterface; public: - ServerInterface(bool publishEnabled, ClientLagCallbackInterface *clientLagCallbackInterface); - virtual ~ServerInterface(); - - bool getClientsAutoPausedDueToLag(); - void setClientLagCallbackInterface(ClientLagCallbackInterface *intf); - void setGameStats(Stats *gameStats); - - virtual Socket* getSocket(bool mutexLock=true) {return &serverSocket;} - virtual std::string getIpAddress(bool mutexLock=true); - - time_t getGameStartTime() const { return gameStartTime; } - - virtual bool getAllowInGameConnections() const { return allowInGameConnections; } - void setAllowInGameConnections(bool value) { allowInGameConnections = value; } - - bool getStartInGameConnectionLaunch(); - bool getPauseForInGameConnection(); - bool getUnPauseForInGameConnection(); - - void shutdownFTPServer(); - - virtual void close(); - virtual void update(); - virtual void updateLobby() { }; - virtual void updateKeyframe(int frameCount); - virtual void setKeyframe(int frameCount) { currentFrameCount = frameCount; } - - virtual void waitUntilReady(Checksum *checksum); - virtual void sendTextMessage(const string & text, int teamIndex, bool echoLocal, string targetLanguage); - void sendTextMessage(const string & text, int teamIndex, bool echoLocal, string targetLanguage, int lockedSlotIndex); - - void queueTextMessage(const string & text, int teamIndex, bool echoLocal, string targetLanguage); - - virtual void sendMarkCellMessage(Vec2i targetPos, int factionIndex, string note,int playerIndex); - void sendMarkCellMessage(Vec2i targetPos, int factionIndex, string note, int playerIndex, int lockedSlotIndex); - - virtual void sendHighlightCellMessage(Vec2i targetPos, int factionIndex); - void sendHighlightCellMessage(Vec2i targetPos, int factionIndex, int lockedSlotIndex); - - virtual void sendUnMarkCellMessage(Vec2i targetPos, int factionIndex); - void sendUnMarkCellMessage(Vec2i targetPos, int factionIndex, int lockedSlotIndex); - - virtual void quitGame(bool userManuallyQuit); - virtual string getNetworkStatus(); - ServerSocket *getServerSocket() { - return &serverSocket; - } - - SwitchSetupRequest **getSwitchSetupRequests(); - SwitchSetupRequest *getSwitchSetupRequests(int index); - void setSwitchSetupRequests(int index,SwitchSetupRequest *ptr); - Mutex * getSwitchSetupRequestsMutex() { return switchSetupRequestsSynchAccessor; } - - void addSlot(int playerIndex); - bool switchSlot(int fromPlayerIndex, int toPlayerIndex); - void removeSlot(int playerIndex, int lockedSlotIndex = -1); - virtual ConnectionSlot *getSlot(int playerIndex, bool lockMutex); - virtual Mutex *getSlotMutex(int playerIndex); - int getSlotCount(); - int getConnectedSlotCount(bool authenticated); - - int getOpenSlotCount(); - bool launchGame(const GameSettings *gameSettings); - void validateGameSettings(GameSettings *serverGameSettings); - void setGameSettings(GameSettings *serverGameSettings, bool waitForClientAck); - void broadcastGameSetup(GameSettings *gameSettingsBuffer, bool setGameSettingsBuffer=false); - - int getGameSettingsUpdateCount(); - - bool getMasterserverAdminRequestLaunch() const { return masterserverAdminRequestLaunch; } - void setMasterserverAdminRequestLaunch(bool value) { masterserverAdminRequestLaunch = value; } - - void updateListen(); - virtual bool getConnectHasHandshaked() const { - return false; - } - - virtual void slotUpdateTask(ConnectionSlotEvent *event) { }; - bool hasClientConnection(); - virtual bool isClientConnected(int index); - - int getCurrentFrameCount() const { - return currentFrameCount; - } - - std::pair clientLagCheck(ConnectionSlot *connectionSlot, bool skipNetworkBroadCast = false); - bool signalClientReceiveCommands(ConnectionSlot *connectionSlot, int slotIndex, bool socketTriggered, ConnectionSlotEvent & event); - void updateSocketTriggeredList(std::map & socketTriggeredList); - bool isPortBound() const { - return serverSocket.isPortBound(); - } - - int getBindPort() const { - return serverSocket.getBindPort(); - } - - void broadcastPing(NetworkMessagePing *networkMessage, int excludeSlot = -1) { - this->broadcastMessage(networkMessage, excludeSlot); - } - - void queueBroadcastMessage(NetworkMessage *networkMessage, int excludeSlot = -1); - virtual string getHumanPlayerName(int index = -1); - virtual int getHumanPlayerIndex() const; - bool getNeedToRepublishToMasterserver() const { - return needToRepublishToMasterserver; - } - - void setNeedToRepublishToMasterserver(bool value) { - needToRepublishToMasterserver = value; - } - - void setPublishEnabled(bool value); - - bool getGameHasBeenInitiated() const { - return gameHasBeenInitiated; - } + ServerInterface(bool publishEnabled, + ClientLagCallbackInterface *clientLagCallbackInterface); + virtual ~ServerInterface(); + + bool getClientsAutoPausedDueToLag(); + void setClientLagCallbackInterface(ClientLagCallbackInterface *intf); + void setGameStats(Stats *gameStats); + + virtual Socket *getSocket(bool mutexLock = true) { return &serverSocket; } + virtual std::string getIpAddress(bool mutexLock = true); + + time_t getGameStartTime() const { return gameStartTime; } + + virtual bool getAllowInGameConnections() const { + return allowInGameConnections; + } + void setAllowInGameConnections(bool value) { allowInGameConnections = value; } + + bool getStartInGameConnectionLaunch(); + bool getPauseForInGameConnection(); + bool getUnPauseForInGameConnection(); + + void shutdownFTPServer(); + + virtual void close(); + virtual void update(); + virtual void updateLobby(){}; + virtual void updateKeyframe(int frameCount); + virtual void setKeyframe(int frameCount) { currentFrameCount = frameCount; } + + virtual void waitUntilReady(Checksum *checksum); + virtual void sendTextMessage(const string &text, int teamIndex, + bool echoLocal, string targetLanguage); + void sendTextMessage(const string &text, int teamIndex, bool echoLocal, + string targetLanguage, int lockedSlotIndex); + + void queueTextMessage(const string &text, int teamIndex, bool echoLocal, + string targetLanguage); + + virtual void sendMarkCellMessage(Vec2i targetPos, int factionIndex, + string note, int playerIndex); + void sendMarkCellMessage(Vec2i targetPos, int factionIndex, string note, + int playerIndex, int lockedSlotIndex); + + virtual void sendHighlightCellMessage(Vec2i targetPos, int factionIndex); + void sendHighlightCellMessage(Vec2i targetPos, int factionIndex, + int lockedSlotIndex); + + virtual void sendUnMarkCellMessage(Vec2i targetPos, int factionIndex); + void sendUnMarkCellMessage(Vec2i targetPos, int factionIndex, + int lockedSlotIndex); + + virtual void quitGame(bool userManuallyQuit); + virtual string getNetworkStatus(); + ServerSocket *getServerSocket() { return &serverSocket; } + + SwitchSetupRequest **getSwitchSetupRequests(); + SwitchSetupRequest *getSwitchSetupRequests(int index); + void setSwitchSetupRequests(int index, SwitchSetupRequest *ptr); + Mutex *getSwitchSetupRequestsMutex() { + return switchSetupRequestsSynchAccessor; + } + + void addSlot(int playerIndex); + bool switchSlot(int fromPlayerIndex, int toPlayerIndex); + void removeSlot(int playerIndex, int lockedSlotIndex = -1); + virtual ConnectionSlot *getSlot(int playerIndex, bool lockMutex); + virtual Mutex *getSlotMutex(int playerIndex); + int getSlotCount(); + int getConnectedSlotCount(bool authenticated); + + int getOpenSlotCount(); + bool launchGame(const GameSettings *gameSettings); + void validateGameSettings(GameSettings *serverGameSettings); + void setGameSettings(GameSettings *serverGameSettings, bool waitForClientAck); + void broadcastGameSetup(GameSettings *gameSettingsBuffer, + bool setGameSettingsBuffer = false); + + int getGameSettingsUpdateCount(); + + bool getMasterserverAdminRequestLaunch() const { + return masterserverAdminRequestLaunch; + } + void setMasterserverAdminRequestLaunch(bool value) { + masterserverAdminRequestLaunch = value; + } + + void updateListen(); + virtual bool getConnectHasHandshaked() const { return false; } + + virtual void slotUpdateTask(ConnectionSlotEvent *event){}; + bool hasClientConnection(); + virtual bool isClientConnected(int index); + + int getCurrentFrameCount() const { return currentFrameCount; } + + std::pair clientLagCheck(ConnectionSlot *connectionSlot, + bool skipNetworkBroadCast = false); + bool signalClientReceiveCommands(ConnectionSlot *connectionSlot, + int slotIndex, bool socketTriggered, + ConnectionSlotEvent &event); + void updateSocketTriggeredList( + std::map &socketTriggeredList); + bool isPortBound() const { return serverSocket.isPortBound(); } + + int getBindPort() const { return serverSocket.getBindPort(); } + + void broadcastPing(NetworkMessagePing *networkMessage, int excludeSlot = -1) { + this->broadcastMessage(networkMessage, excludeSlot); + } + + void queueBroadcastMessage(NetworkMessage *networkMessage, + int excludeSlot = -1); + virtual string getHumanPlayerName(int index = -1); + virtual int getHumanPlayerIndex() const; + bool getNeedToRepublishToMasterserver() const { + return needToRepublishToMasterserver; + } + + void setNeedToRepublishToMasterserver(bool value) { + needToRepublishToMasterserver = value; + } + + void setPublishEnabled(bool value); + + bool getGameHasBeenInitiated() const { return gameHasBeenInitiated; } public: - Mutex *getServerSynchAccessor() { - return serverSynchAccessor; - } + Mutex *getServerSynchAccessor() { return serverSynchAccessor; } - virtual void simpleTask(BaseThread *callingThread,void *userdata); - void addClientToServerIPAddress(uint32 clientIp, uint32 ServerIp); - virtual int isValidClientType(uint32 clientIp); - virtual int isClientAllowedToGetFile(uint32 clientIp, const char *username, const char *filename); + virtual void simpleTask(BaseThread *callingThread, void *userdata); + void addClientToServerIPAddress(uint32 clientIp, uint32 ServerIp); + virtual int isValidClientType(uint32 clientIp); + virtual int isClientAllowedToGetFile(uint32 clientIp, const char *username, + const char *filename); - void notifyBadClientConnectAttempt(string ipAddress); - std::string DumpStatsToLog(bool dumpToStringOnly) const; + void notifyBadClientConnectAttempt(string ipAddress); + std::string DumpStatsToLog(bool dumpToStringOnly) const; - virtual void saveGame(XmlNode *rootNode); + virtual void saveGame(XmlNode *rootNode); - void broadcastMessage(NetworkMessage *networkMessage, int excludeSlot = -1, int lockedSlotIndex = -1); + void broadcastMessage(NetworkMessage *networkMessage, int excludeSlot = -1, + int lockedSlotIndex = -1); - ConnectionSlot * findSlotForUUID(string uuid, bool unConnectedOnly=true); + ConnectionSlot *findSlotForUUID(string uuid, bool unConnectedOnly = true); private: - - void broadcastMessageToConnectedClients(NetworkMessage *networkMessage, int excludeSlot = -1); - bool shouldDiscardNetworkMessage(NetworkMessageType networkMessageType, ConnectionSlot *connectionSlot); - void updateSlot(ConnectionSlotEvent *event); - void validateConnectedClients(); - - std::map publishToMasterserver(); - std::map publishToMasterserverStats(); - - int64 getNextEventId(); - void processTextMessageQueue(); - void processBroadCastMessageQueue(); - void checkListenerSlots(); - void checkForCompletedClientsUsingThreadManager( - std::map& mapSlotSignalledList, - std::vector& errorMsgList); - void checkForCompletedClientsUsingLoop( - std::map& mapSlotSignalledList, - std::vector& errorMsgList, - std::map& eventList); - void checkForAutoPauseForLaggingClient(int index, - ConnectionSlot* connectionSlot); - void checkForAutoResumeForLaggingClients(); + void broadcastMessageToConnectedClients(NetworkMessage *networkMessage, + int excludeSlot = -1); + bool shouldDiscardNetworkMessage(NetworkMessageType networkMessageType, + ConnectionSlot *connectionSlot); + void updateSlot(ConnectionSlotEvent *event); + void validateConnectedClients(); + + std::map publishToMasterserver(); + std::map publishToMasterserverStats(); + + int64 getNextEventId(); + void processTextMessageQueue(); + void processBroadCastMessageQueue(); + void checkListenerSlots(); + void checkForCompletedClientsUsingThreadManager( + std::map &mapSlotSignalledList, + std::vector &errorMsgList); + void checkForCompletedClientsUsingLoop( + std::map &mapSlotSignalledList, + std::vector &errorMsgList, + std::map &eventList); + void checkForAutoPauseForLaggingClient(int index, + ConnectionSlot *connectionSlot); + void checkForAutoResumeForLaggingClients(); protected: - void signalClientsToRecieveData(std::map & socketTriggeredList, std::map & eventList, std::map & mapSlotSignalledList); - void checkForCompletedClients(std::map & mapSlotSignalledList,std::vector &errorMsgList,std::map &eventList); - void checkForLaggingClients(std::map &mapSlotSignalledList, std::map &eventList, std::map &socketTriggeredList,std::vector &errorMsgList); - void executeNetworkCommandsFromClients(); - void dispatchPendingChatMessages(std::vector &errorMsgList); - void dispatchPendingMarkCellMessages(std::vector &errorMsgList); - void dispatchPendingUnMarkCellMessages(std::vector &errorMsgList); - void dispatchPendingHighlightCellMessages(std::vector &errorMsgList); - - void shutdownMasterserverPublishThread(); - - + void signalClientsToRecieveData( + std::map &socketTriggeredList, + std::map &eventList, + std::map &mapSlotSignalledList); + void checkForCompletedClients(std::map &mapSlotSignalledList, + std::vector &errorMsgList, + std::map &eventList); + void + checkForLaggingClients(std::map &mapSlotSignalledList, + std::map &eventList, + std::map &socketTriggeredList, + std::vector &errorMsgList); + void executeNetworkCommandsFromClients(); + void dispatchPendingChatMessages(std::vector &errorMsgList); + void dispatchPendingMarkCellMessages(std::vector &errorMsgList); + void dispatchPendingUnMarkCellMessages(std::vector &errorMsgList); + void dispatchPendingHighlightCellMessages(std::vector &errorMsgList); + + void shutdownMasterserverPublishThread(); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/sound/sound_container.cpp b/source/glest_game/sound/sound_container.cpp index 2b1f2f40f..d99b84c2a 100644 --- a/source/glest_game/sound/sound_container.cpp +++ b/source/glest_game/sound/sound_container.cpp @@ -3,43 +3,43 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== #include "sound_container.h" -#include "util.h" #include "leak_dumper.h" +#include "util.h" using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class SoundContainer // ===================================================== -SoundContainer::SoundContainer(){ - lastSound= -1; -} - -StaticSound *SoundContainer::getRandSound() const{ - switch(sounds.size()){ - case 0: - return NULL; - case 1: - return sounds[0]; - default: - int soundIndex= random.randRange(0, (int)sounds.size()-1); - if(soundIndex==lastSound){ - soundIndex= (lastSound+1) % sounds.size(); - } - lastSound= soundIndex; - return sounds[soundIndex]; - } +SoundContainer::SoundContainer() { lastSound = -1; } + +StaticSound *SoundContainer::getRandSound() const { + switch (sounds.size()) { + case 0: + return NULL; + case 1: + return sounds[0]; + default: + int soundIndex = random.randRange(0, (int)sounds.size() - 1); + if (soundIndex == lastSound) { + soundIndex = (lastSound + 1) % sounds.size(); + } + lastSound = soundIndex; + return sounds[soundIndex]; + } } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/sound/sound_container.h b/source/glest_game/sound/sound_container.h index ee4c058e2..cbcc2b839 100644 --- a/source/glest_game/sound/sound_container.h +++ b/source/glest_game/sound/sound_container.h @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,20 +13,21 @@ #define _GLEST_GAME_SOUNDCONTAINER_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include -#include "sound.h" -#include "randomgen.h" #include "leak_dumper.h" +#include "randomgen.h" +#include "sound.h" +#include -using std::vector; -using Shared::Util::RandomGen; using Shared::Sound::StaticSound; +using Shared::Util::RandomGen; +using std::vector; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class SoundContainer @@ -34,27 +35,28 @@ namespace Glest{ namespace Game{ /// Holds a list of sounds that are usually played at random // ===================================================== -class SoundContainer{ +class SoundContainer { public: - typedef vector Sounds; + typedef vector Sounds; private: - Sounds sounds; - mutable RandomGen random; - mutable int lastSound; + Sounds sounds; + mutable RandomGen random; + mutable int lastSound; public: - SoundContainer(); + SoundContainer(); - void resize(int size) {sounds.resize(size);} - StaticSound *&operator[](int i) {return sounds[i];} + void resize(int size) { sounds.resize(size); } + StaticSound *&operator[](int i) { return sounds[i]; } - const Sounds &getSounds() const {return sounds;} - void clearSounds() {sounds.clear();} - Sounds *getSoundsPtr() {return &sounds;} - StaticSound *getRandSound() const; + const Sounds &getSounds() const { return sounds; } + void clearSounds() { sounds.clear(); } + Sounds *getSoundsPtr() { return &sounds; } + StaticSound *getRandSound() const; }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/sound/sound_renderer.cpp b/source/glest_game/sound/sound_renderer.cpp index 7d0948095..9dc55c09a 100644 --- a/source/glest_game/sound/sound_renderer.cpp +++ b/source/glest_game/sound/sound_renderer.cpp @@ -10,271 +10,302 @@ #include "sound_renderer.h" -#include "core_data.h" #include "config.h" -#include "sound_interface.h" +#include "core_data.h" #include "factory_repository.h" -#include "util.h" #include "leak_dumper.h" +#include "sound_interface.h" +#include "util.h" using namespace Shared::Util; using namespace Shared::Graphics; using namespace Shared::Sound; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { -const int SoundRenderer::ambientFade= 6000; -const float SoundRenderer::audibleDist= 50.f; +const int SoundRenderer::ambientFade = 6000; +const float SoundRenderer::audibleDist = 50.f; // ===================================================== // class SoundRenderer // ===================================================== SoundRenderer::SoundRenderer() : mutex(new Mutex(CODE_AT_LINE)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); - soundPlayer = NULL; - loadConfig(); + soundPlayer = NULL; + loadConfig(); - Config &config= Config::getInstance(); - runThreadSafe = config.getBool("ThreadedSoundStream","true"); + Config &config = Config::getInstance(); + runThreadSafe = config.getBool("ThreadedSoundStream", "true"); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] runThreadSafe = %d\n",__FILE__,__FUNCTION__,__LINE__,runThreadSafe); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] runThreadSafe = %d\n", + __FILE__, __FUNCTION__, __LINE__, runThreadSafe); } bool SoundRenderer::init(Window *window) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); - - SoundInterface &si= SoundInterface::getInstance(); - FactoryRepository &fr= FactoryRepository::getInstance(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); - Config &config= Config::getInstance(); - si.setFactory(fr.getSoundFactory(config.getString("FactorySound"))); - - cleanup(); - stopAllSounds(); - - MutexSafeWrapper safeMutex(NULL,string(__FILE__) + "_" + intToStr(__LINE__)); - if(runThreadSafe == true) { - safeMutex.setMutex(mutex); - } - - soundPlayer= si.newSoundPlayer(); - if(soundPlayer != NULL) { - SoundPlayerParams soundPlayerParams; - soundPlayerParams.staticBufferCount= config.getInt("SoundStaticBuffers"); - soundPlayerParams.strBufferCount= config.getInt("SoundStreamingBuffers"); - soundPlayer->init(&soundPlayerParams); - } - safeMutex.ReleaseLock(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); - - return wasInitOk(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + SoundInterface &si = SoundInterface::getInstance(); + FactoryRepository &fr = FactoryRepository::getInstance(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); + Config &config = Config::getInstance(); + si.setFactory(fr.getSoundFactory(config.getString("FactorySound"))); + + cleanup(); + stopAllSounds(); + + MutexSafeWrapper safeMutex(NULL, string(__FILE__) + "_" + intToStr(__LINE__)); + if (runThreadSafe == true) { + safeMutex.setMutex(mutex); + } + + soundPlayer = si.newSoundPlayer(); + if (soundPlayer != NULL) { + SoundPlayerParams soundPlayerParams; + soundPlayerParams.staticBufferCount = config.getInt("SoundStaticBuffers"); + soundPlayerParams.strBufferCount = config.getInt("SoundStreamingBuffers"); + soundPlayer->init(&soundPlayerParams); + } + safeMutex.ReleaseLock(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + return wasInitOk(); } void SoundRenderer::cleanup() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); - - stopAllSounds(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); - - MutexSafeWrapper safeMutex(NULL,string(__FILE__) + "_" + intToStr(__LINE__)); - if(runThreadSafe == true) { - safeMutex.setMutex(mutex); - } - delete soundPlayer; - soundPlayer = NULL; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + stopAllSounds(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + MutexSafeWrapper safeMutex(NULL, string(__FILE__) + "_" + intToStr(__LINE__)); + if (runThreadSafe == true) { + safeMutex.setMutex(mutex); + } + delete soundPlayer; + soundPlayer = NULL; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); } bool SoundRenderer::wasInitOk() const { - bool result = false; - if(soundPlayer != NULL) { - result = soundPlayer->wasInitOk(); - } - else { - Config &config= Config::getInstance(); - if(config.getString("FactorySound") == "" || - config.getString("FactorySound") == "None") { - result = true; - } - } - return result; + bool result = false; + if (soundPlayer != NULL) { + result = soundPlayer->wasInitOk(); + } else { + Config &config = Config::getInstance(); + if (config.getString("FactorySound") == "" || + config.getString("FactorySound") == "None") { + result = true; + } + } + return result; } SoundRenderer::~SoundRenderer() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); - cleanup(); + cleanup(); - delete mutex; - mutex = NULL; + delete mutex; + mutex = NULL; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s %d]\n", + __FILE__, __FUNCTION__, __LINE__); } SoundRenderer &SoundRenderer::getInstance() { - static SoundRenderer soundRenderer; - return soundRenderer; + static SoundRenderer soundRenderer; + return soundRenderer; } void SoundRenderer::update() { - if(wasInitOk() == true && soundPlayer != NULL) { - MutexSafeWrapper safeMutex(NULL,string(__FILE__) + "_" + intToStr(__LINE__)); - if(runThreadSafe == true) { - safeMutex.setMutex(mutex); - } - if(soundPlayer) { - soundPlayer->updateStreams(); - } + if (wasInitOk() == true && soundPlayer != NULL) { + MutexSafeWrapper safeMutex(NULL, + string(__FILE__) + "_" + intToStr(__LINE__)); + if (runThreadSafe == true) { + safeMutex.setMutex(mutex); + } + if (soundPlayer) { + soundPlayer->updateStreams(); } + } } // ======================= Music ============================ void SoundRenderer::playMusic(StrSound *strSound) { - if(strSound != NULL) { - strSound->setVolume(musicVolume); - strSound->restart(); - if(soundPlayer != NULL) { - MutexSafeWrapper safeMutex(NULL,string(__FILE__) + "_" + intToStr(__LINE__)); - if(runThreadSafe == true) { - safeMutex.setMutex(mutex); - } - - if(soundPlayer) { - soundPlayer->play(strSound); - } - } - } + if (strSound != NULL) { + strSound->setVolume(musicVolume); + strSound->restart(); + if (soundPlayer != NULL) { + MutexSafeWrapper safeMutex(NULL, + string(__FILE__) + "_" + intToStr(__LINE__)); + if (runThreadSafe == true) { + safeMutex.setMutex(mutex); + } + + if (soundPlayer) { + soundPlayer->play(strSound); + } + } + } } void SoundRenderer::setMusicVolume(StrSound *strSound) { - if(strSound != NULL) { - strSound->setVolume(musicVolume); - } + if (strSound != NULL) { + strSound->setVolume(musicVolume); + } } void SoundRenderer::stopMusic(StrSound *strSound) { - if(soundPlayer != NULL) { - MutexSafeWrapper safeMutex(NULL,string(__FILE__) + "_" + intToStr(__LINE__)); - if(runThreadSafe == true) { - safeMutex.setMutex(mutex); - } - - if(soundPlayer) { - soundPlayer->stop(strSound); - if(strSound != NULL) { - if(strSound->getNext() != NULL) { - soundPlayer->stop(strSound->getNext()); - } - } - } + if (soundPlayer != NULL) { + MutexSafeWrapper safeMutex(NULL, + string(__FILE__) + "_" + intToStr(__LINE__)); + if (runThreadSafe == true) { + safeMutex.setMutex(mutex); + } + + if (soundPlayer) { + soundPlayer->stop(strSound); + if (strSound != NULL) { + if (strSound->getNext() != NULL) { + soundPlayer->stop(strSound->getNext()); + } + } } + } } // ======================= Fx ============================ -void SoundRenderer::playFx(StaticSound *staticSound, Vec3f soundPos, Vec3f camPos) { - if(staticSound!=NULL){ - float d= soundPos.dist(camPos); +void SoundRenderer::playFx(StaticSound *staticSound, Vec3f soundPos, + Vec3f camPos) { + if (staticSound != NULL) { + float d = soundPos.dist(camPos); - if(d < audibleDist){ - float vol= (1.f-d/audibleDist)*fxVolume; - float correctedVol= std::log10(std::log10(vol*9+1)*9+1); + if (d < audibleDist) { + float vol = (1.f - d / audibleDist) * fxVolume; + float correctedVol = std::log10(std::log10(vol * 9 + 1) * 9 + 1); - staticSound->setVolume(correctedVol); + staticSound->setVolume(correctedVol); - if(soundPlayer != NULL) { - MutexSafeWrapper safeMutex(NULL,string(__FILE__) + "_" + intToStr(__LINE__)); - if(runThreadSafe == true) { - safeMutex.setMutex(mutex); - } + if (soundPlayer != NULL) { + MutexSafeWrapper safeMutex(NULL, + string(__FILE__) + "_" + intToStr(__LINE__)); + if (runThreadSafe == true) { + safeMutex.setMutex(mutex); + } - if(soundPlayer) { - soundPlayer->play(staticSound); - } - } - } - } + if (soundPlayer) { + soundPlayer->play(staticSound); + } + } + } + } } void SoundRenderer::playFx(StaticSound *staticSound, bool force) { - if(staticSound!=NULL){ - staticSound->setVolume(fxVolume); - if(soundPlayer != NULL) { - MutexSafeWrapper safeMutex(NULL,string(__FILE__) + "_" + intToStr(__LINE__)); - if(runThreadSafe == true) { - safeMutex.setMutex(mutex); - } - - if(soundPlayer) { - soundPlayer->play(staticSound, force); - } - } - } + if (staticSound != NULL) { + staticSound->setVolume(fxVolume); + if (soundPlayer != NULL) { + MutexSafeWrapper safeMutex(NULL, + string(__FILE__) + "_" + intToStr(__LINE__)); + if (runThreadSafe == true) { + safeMutex.setMutex(mutex); + } + + if (soundPlayer) { + soundPlayer->play(staticSound, force); + } + } + } } // ======================= Ambient ============================ void SoundRenderer::playAmbient(StrSound *strSound) { - if(strSound != NULL) { - strSound->setVolume(ambientVolume); - if(soundPlayer != NULL) { - MutexSafeWrapper safeMutex(NULL,string(__FILE__) + "_" + intToStr(__LINE__)); - if(runThreadSafe == true) { - safeMutex.setMutex(mutex); - } - - if(soundPlayer) { - soundPlayer->play(strSound, ambientFade); - } - } - } + if (strSound != NULL) { + strSound->setVolume(ambientVolume); + if (soundPlayer != NULL) { + MutexSafeWrapper safeMutex(NULL, + string(__FILE__) + "_" + intToStr(__LINE__)); + if (runThreadSafe == true) { + safeMutex.setMutex(mutex); + } + + if (soundPlayer) { + soundPlayer->play(strSound, ambientFade); + } + } + } } void SoundRenderer::stopAmbient(StrSound *strSound) { - if(soundPlayer != NULL) { - MutexSafeWrapper safeMutex(NULL,string(__FILE__) + "_" + intToStr(__LINE__)); - if(runThreadSafe == true) { - safeMutex.setMutex(mutex); - } - - if(soundPlayer) { - soundPlayer->stop(strSound, ambientFade); - } + if (soundPlayer != NULL) { + MutexSafeWrapper safeMutex(NULL, + string(__FILE__) + "_" + intToStr(__LINE__)); + if (runThreadSafe == true) { + safeMutex.setMutex(mutex); } + + if (soundPlayer) { + soundPlayer->stop(strSound, ambientFade); + } + } } // ======================= Misc ============================ void SoundRenderer::stopAllSounds(int64 fadeOff) { - if(soundPlayer != NULL) { - MutexSafeWrapper safeMutex(NULL,string(__FILE__) + "_" + intToStr(__LINE__)); - if(runThreadSafe == true) { - safeMutex.setMutex(mutex); - } - - if(soundPlayer) { - soundPlayer->stopAllSounds(fadeOff); - } + if (soundPlayer != NULL) { + MutexSafeWrapper safeMutex(NULL, + string(__FILE__) + "_" + intToStr(__LINE__)); + if (runThreadSafe == true) { + safeMutex.setMutex(mutex); + } + + if (soundPlayer) { + soundPlayer->stopAllSounds(fadeOff); } + } } bool SoundRenderer::isVolumeTurnedOff() const { - return (fxVolume <= 0 && musicVolume <= 0 && ambientVolume <= 0); + return (fxVolume <= 0 && musicVolume <= 0 && ambientVolume <= 0); } void SoundRenderer::loadConfig() { - Config &config= Config::getInstance(); + Config &config = Config::getInstance(); - fxVolume= config.getInt("SoundVolumeFx")/100.f; - musicVolume= config.getInt("SoundVolumeMusic")/100.f; - ambientVolume= config.getInt("SoundVolumeAmbient")/100.f; + fxVolume = config.getInt("SoundVolumeFx") / 100.f; + musicVolume = config.getInt("SoundVolumeMusic") / 100.f; + ambientVolume = config.getInt("SoundVolumeAmbient") / 100.f; } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/sound/sound_renderer.h b/source/glest_game/sound/sound_renderer.h index 0f17196b4..6fcb66e1c 100644 --- a/source/glest_game/sound/sound_renderer.h +++ b/source/glest_game/sound/sound_renderer.h @@ -13,24 +13,25 @@ #define _GLEST_GAME_SOUNDRENDERER_H_ #ifdef WIN32 - #include - #include +#include +#include #endif +#include "leak_dumper.h" +#include "platform_common.h" +#include "simple_threads.h" #include "sound.h" #include "sound_player.h" -#include "window.h" #include "vec.h" -#include "simple_threads.h" -#include "platform_common.h" -#include "leak_dumper.h" +#include "window.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { -using ::Shared::Sound::StrSound; -using ::Shared::Sound::StaticSound; -using ::Shared::Sound::SoundPlayer; using ::Shared::Graphics::Vec3f; +using ::Shared::Sound::SoundPlayer; +using ::Shared::Sound::StaticSound; +using ::Shared::Sound::StrSound; using namespace ::Shared::PlatformCommon; // ===================================================== @@ -41,57 +42,61 @@ using namespace ::Shared::PlatformCommon; class SoundRenderer : public SimpleTaskCallbackInterface { public: - static const int ambientFade; - static const float audibleDist; + static const int ambientFade; + static const float audibleDist; + private: - SoundPlayer *soundPlayer; + SoundPlayer *soundPlayer; - //volume - float fxVolume; - float musicVolume; - float ambientVolume; + // volume + float fxVolume; + float musicVolume; + float ambientVolume; - Mutex *mutex; - bool runThreadSafe; + Mutex *mutex; + bool runThreadSafe; private: - SoundRenderer(); + SoundRenderer(); - void cleanup(); + void cleanup(); public: - //misc - virtual ~SoundRenderer(); - static SoundRenderer &getInstance(); - bool init(Window *window); - void update(); - virtual void simpleTask(BaseThread *callingThread,void *userdata) { update(); } - SoundPlayer *getSoundPlayer() const {return soundPlayer;} - - //music - void playMusic(StrSound *strSound); - void setMusicVolume(StrSound *strSound); - void stopMusic(StrSound *strSound); - - //fx - void playFx(StaticSound *staticSound, Vec3f soundPos, Vec3f camPos); - void playFx(StaticSound *staticSound, bool force=false); - - //ambient - void playAmbient(StrSound *strSound); - void stopAmbient(StrSound *strSound); - - //misc - void stopAllSounds(int64 fadeOff=0); - void loadConfig(); - - bool wasInitOk() const; - - bool runningThreaded() const { return runThreadSafe; } - - bool isVolumeTurnedOff() const; + // misc + virtual ~SoundRenderer(); + static SoundRenderer &getInstance(); + bool init(Window *window); + void update(); + virtual void simpleTask(BaseThread *callingThread, void *userdata) { + update(); + } + SoundPlayer *getSoundPlayer() const { return soundPlayer; } + + // music + void playMusic(StrSound *strSound); + void setMusicVolume(StrSound *strSound); + void stopMusic(StrSound *strSound); + + // fx + void playFx(StaticSound *staticSound, Vec3f soundPos, Vec3f camPos); + void playFx(StaticSound *staticSound, bool force = false); + + // ambient + void playAmbient(StrSound *strSound); + void stopAmbient(StrSound *strSound); + + // misc + void stopAllSounds(int64 fadeOff = 0); + void loadConfig(); + + bool wasInitOk() const; + + bool runningThreaded() const { return runThreadSafe; } + + bool isVolumeTurnedOff() const; }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/steam/steam.cpp b/source/glest_game/steam/steam.cpp index bff8c0a58..d30546064 100644 --- a/source/glest_game/steam/steam.cpp +++ b/source/glest_game/steam/steam.cpp @@ -1,357 +1,367 @@ #include "steam.h" -#include -#include -#include "steamshim_child.h" #include "platform_common.h" #include "properties.h" +#include "steamshim_child.h" +#include +#include using Shared::PlatformCommon::fileExists; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { -std::map Steam::SteamStatNameTypes = Steam::create_map(); +std::map Steam::SteamStatNameTypes = + Steam::create_map(); // Language map -static inline std::map gen_langToCode() -{ - std::map map; - map["brazilian"] = "pt_BR"; - map["bulgarian"] = "bg"; - map["czech"] = "cz"; - map["danish"] = "da"; - map["dutch"] = "nl"; - map["english"] = "en"; - map["finnish"] = "fi"; - map["french"] = "fr"; - map["german"] = "de"; - map["greek"] = "el"; - map["hungarian"] = "hu"; - map["italian"] = "it"; - map["japanese"] = "ja"; - map["koreana"] = "ko"; - map["korean"] = "ko"; - map["norwegian"] = "no"; - map["polish"] = "pl"; - map["portuguese"] = "pt"; - map["romanian"] = "ro"; - map["russian"] = "ru"; - map["schinese"] = "zh_CN"; - map["spanish"] = "es"; - map["swedish"] = "sv"; - map["tchinese"] = "zh_TW"; - map["thai"] = "th"; - map["turkish"] = "tr"; - map["ukrainian"] = "uk"; - return map; +static inline std::map gen_langToCode() { + std::map map; + map["brazilian"] = "pt_BR"; + map["bulgarian"] = "bg"; + map["czech"] = "cz"; + map["danish"] = "da"; + map["dutch"] = "nl"; + map["english"] = "en"; + map["finnish"] = "fi"; + map["french"] = "fr"; + map["german"] = "de"; + map["greek"] = "el"; + map["hungarian"] = "hu"; + map["italian"] = "it"; + map["japanese"] = "ja"; + map["koreana"] = "ko"; + map["korean"] = "ko"; + map["norwegian"] = "no"; + map["polish"] = "pl"; + map["portuguese"] = "pt"; + map["romanian"] = "ro"; + map["russian"] = "ru"; + map["schinese"] = "zh_CN"; + map["spanish"] = "es"; + map["swedish"] = "sv"; + map["tchinese"] = "zh_TW"; + map["thai"] = "th"; + map["turkish"] = "tr"; + map["ukrainian"] = "uk"; + return map; } static const std::map langToCode = gen_langToCode(); static std::string steamToIsoLang(const char *steamLang) { - //printf("Steam language [%s]\n",steamLang); - std::map::const_iterator it = langToCode.find(steamLang); - if (it != langToCode.end()) { - return it->second; - } - return "en"; + // printf("Steam language [%s]\n",steamLang); + std::map::const_iterator it = + langToCode.find(steamLang); + if (it != langToCode.end()) { + return it->second; + } + return "en"; } // SteamPrivate struct SteamPrivate { - static bool debugEnabled; - std::map achievements; - std::map stats; - - std::string userName; - std::string lang; - - SteamPrivate() { - if(debugEnabled) printf("\nCreating private steam state container\n"); - STEAMSHIM_getPersonaName(); - STEAMSHIM_getCurrentGameLanguage(); - STEAMSHIM_requestStats(); - STEAMSHIM_EventType statsReceived = SHIMEVENT_STATSRECEIVED; - - Shared::PlatformCommon::Chrono timerStats; - timerStats.start(); - while(update(&statsReceived) == NULL && timerStats.getMillis() < 2500) { - SDL_Delay(100); - } - - refreshAllStats(); - } - - static void setDebugEnabled(bool value) { - debugEnabled = value; - } - - void refreshAllStats() { - achievements.clear(); - stats.clear(); - - for(int index = 0; index < EnumParser::getCount(); ++index) { - SteamStatName statName = static_cast(index); - string statNameStr = EnumParser::getString(statName); - SteamStatType statType = Steam::getSteamStatNameType(statNameStr); - switch(statType) { - case stat_int: - STEAMSHIM_getStatI(statNameStr.c_str()); - break; - case stat_float: - STEAMSHIM_getStatF(statNameStr.c_str()); - break; - default: - break; - } - } - for(int index = 0; index < EnumParser::getCount(); ++index) { - SteamAchievementName achName = static_cast(index); - string achNameStr = EnumParser::getString(achName); - STEAMSHIM_getAchievement(achNameStr.c_str()); - } - - Shared::PlatformCommon::Chrono timer; - timer.start(); - while(!initialized() && timer.getMillis() < 2500) { - SDL_Delay(100); - update(); - } - } - - void setAchievement(const char *name, bool set) { - achievements[name] = set; - STEAMSHIM_setAchievement(name, set); - } - - void updateAchievement(const char *name, bool isSet) { - achievements[name] = isSet; - } - - bool isAchievementSet(const char *name) { - return achievements[name]; - } - - void updateStat(const char *name, double value) { - stats[name] = value; - } - - int getStatAsInt(const char *name) const { - std::map::const_iterator iterFind = stats.find(name); - if(iterFind != stats.end()) { - return iterFind->second; - } - return 0; - } - double getStatAsDouble(const char *name) const { - std::map::const_iterator iterFind = stats.find(name); - if(iterFind != stats.end()) { - return iterFind->second; - } - return 0; - } - - void setStatAsInt(const char *name, int value) { - STEAMSHIM_setStatI(name, value); - update(); - } - void setStatAsFloat(const char *name, float value) { - STEAMSHIM_setStatF(name, value); - update(); - } -// void clearLocalStats() { -// stats.clear(); -// } - - const STEAMSHIM_Event * update(STEAMSHIM_EventType *waitForEvent=NULL) { - const STEAMSHIM_Event *e; - while ((e = STEAMSHIM_pump()) != 0) { - // Handle events - switch (e->type) - { - case SHIMEVENT_GETACHIEVEMENT: - if(debugEnabled) printf("\nGot Shim event SHIMEVENT_GETACHIEVEMENT name [%s] value [%d] isOk = %d\n",e->name,e->ivalue,e->okay); - if(e->okay) { - updateAchievement(e->name, e->ivalue); - } - break; - case SHIMEVENT_SETACHIEVEMENT: - if(debugEnabled) printf("\nGot Shim event SHIMEVENT_SETACHIEVEMENT for name [%s] value [%d] isOk = %d\n",e->name,e->ivalue,e->okay); - break; - case SHIMEVENT_GETPERSONANAME: - if(debugEnabled) printf("\nGot Shim event SHIMEVENT_GETPERSONANAME isOk = %d value [%s]\n",e->okay,e->name); - userName = e->name; - break; - case SHIMEVENT_GETCURRENTGAMELANGUAGE: - if(debugEnabled) printf("\nGot Shim event SHIMEVENT_GETCURRENTGAMELANGUAGE isOk = %d value [%s]\n",e->okay,e->name); - lang = steamToIsoLang(e->name); - break; - case SHIMEVENT_STATSRECEIVED: - if(debugEnabled) printf("\nGot Shim event SHIMEVENT_STATSRECEIVED isOk = %d\n",e->okay); - break; - case SHIMEVENT_STATSSTORED: - if(debugEnabled) printf("\nGot Shim event SHIMEVENT_STATSSTORED isOk = %d\n",e->okay); - break; - case SHIMEVENT_GETSTATI: - if(debugEnabled) printf("\nGot Shim event SHIMEVENT_GETSTATI for stat [%s] value [%d] isOk = %d\n",e->name,e->ivalue,e->okay); - if(e->okay) { - updateStat(e->name, e->ivalue); - } - break; - case SHIMEVENT_GETSTATF: - if(debugEnabled) printf("\nGot Shim event SHIMEVENT_GETSTATF for stat [%s] value [%f] isOk = %d\n",e->name,e->fvalue,e->okay); - if(e->okay) { - updateStat(e->name, e->fvalue); - } - break; - case SHIMEVENT_SETSTATI: - if(debugEnabled) printf("\nGot Shim event SHIMEVENT_SETSTATI for stat [%s] value [%d] isOk = %d\n",e->name,e->ivalue,e->okay); - break; - case SHIMEVENT_SETSTATF: - if(debugEnabled) printf("\nGot Shim event SHIMEVENT_SETSTATF for stat [%s] value [%f] isOk = %d\n",e->name,e->fvalue,e->okay); - break; - default: - if(debugEnabled) printf("\nGot Shim event [%d] isOk = %d\n",e->type,e->okay); - break; - } - if(waitForEvent != NULL && *waitForEvent == e->type) { - return e; - } + static bool debugEnabled; + std::map achievements; + std::map stats; + + std::string userName; + std::string lang; + + SteamPrivate() { + if (debugEnabled) + printf("\nCreating private steam state container\n"); + STEAMSHIM_getPersonaName(); + STEAMSHIM_getCurrentGameLanguage(); + STEAMSHIM_requestStats(); + STEAMSHIM_EventType statsReceived = SHIMEVENT_STATSRECEIVED; + + Shared::PlatformCommon::Chrono timerStats; + timerStats.start(); + while (update(&statsReceived) == NULL && timerStats.getMillis() < 2500) { + SDL_Delay(100); + } + + refreshAllStats(); + } + + static void setDebugEnabled(bool value) { debugEnabled = value; } + + void refreshAllStats() { + achievements.clear(); + stats.clear(); + + for (int index = 0; index < EnumParser::getCount(); + ++index) { + SteamStatName statName = static_cast(index); + string statNameStr = EnumParser::getString(statName); + SteamStatType statType = Steam::getSteamStatNameType(statNameStr); + switch (statType) { + case stat_int: + STEAMSHIM_getStatI(statNameStr.c_str()); + break; + case stat_float: + STEAMSHIM_getStatF(statNameStr.c_str()); + break; + default: + break; + } + } + for (int index = 0; index < EnumParser::getCount(); + ++index) { + SteamAchievementName achName = static_cast(index); + string achNameStr = EnumParser::getString(achName); + STEAMSHIM_getAchievement(achNameStr.c_str()); + } + + Shared::PlatformCommon::Chrono timer; + timer.start(); + while (!initialized() && timer.getMillis() < 2500) { + SDL_Delay(100); + update(); + } + } + + void setAchievement(const char *name, bool set) { + achievements[name] = set; + STEAMSHIM_setAchievement(name, set); + } + + void updateAchievement(const char *name, bool isSet) { + achievements[name] = isSet; + } + + bool isAchievementSet(const char *name) { return achievements[name]; } + + void updateStat(const char *name, double value) { stats[name] = value; } + + int getStatAsInt(const char *name) const { + std::map::const_iterator iterFind = stats.find(name); + if (iterFind != stats.end()) { + return iterFind->second; + } + return 0; + } + double getStatAsDouble(const char *name) const { + std::map::const_iterator iterFind = stats.find(name); + if (iterFind != stats.end()) { + return iterFind->second; + } + return 0; + } + + void setStatAsInt(const char *name, int value) { + STEAMSHIM_setStatI(name, value); + update(); + } + void setStatAsFloat(const char *name, float value) { + STEAMSHIM_setStatF(name, value); + update(); + } + // void clearLocalStats() { + // stats.clear(); + // } + + const STEAMSHIM_Event *update(STEAMSHIM_EventType *waitForEvent = NULL) { + const STEAMSHIM_Event *e; + while ((e = STEAMSHIM_pump()) != 0) { + // Handle events + switch (e->type) { + case SHIMEVENT_GETACHIEVEMENT: + if (debugEnabled) + printf("\nGot Shim event SHIMEVENT_GETACHIEVEMENT name [%s] value " + "[%d] isOk = %d\n", + e->name, e->ivalue, e->okay); + if (e->okay) { + updateAchievement(e->name, e->ivalue); + } + break; + case SHIMEVENT_SETACHIEVEMENT: + if (debugEnabled) + printf("\nGot Shim event SHIMEVENT_SETACHIEVEMENT for name [%s] " + "value [%d] isOk = %d\n", + e->name, e->ivalue, e->okay); + break; + case SHIMEVENT_GETPERSONANAME: + if (debugEnabled) + printf("\nGot Shim event SHIMEVENT_GETPERSONANAME isOk = %d value " + "[%s]\n", + e->okay, e->name); + userName = e->name; + break; + case SHIMEVENT_GETCURRENTGAMELANGUAGE: + if (debugEnabled) + printf("\nGot Shim event SHIMEVENT_GETCURRENTGAMELANGUAGE isOk = %d " + "value [%s]\n", + e->okay, e->name); + lang = steamToIsoLang(e->name); + break; + case SHIMEVENT_STATSRECEIVED: + if (debugEnabled) + printf("\nGot Shim event SHIMEVENT_STATSRECEIVED isOk = %d\n", + e->okay); + break; + case SHIMEVENT_STATSSTORED: + if (debugEnabled) + printf("\nGot Shim event SHIMEVENT_STATSSTORED isOk = %d\n", e->okay); + break; + case SHIMEVENT_GETSTATI: + if (debugEnabled) + printf("\nGot Shim event SHIMEVENT_GETSTATI for stat [%s] value [%d] " + "isOk = %d\n", + e->name, e->ivalue, e->okay); + if (e->okay) { + updateStat(e->name, e->ivalue); } - return NULL; - } - - bool initialized() { - return !userName.empty() - && !lang.empty() - && (int)stats.size() >= EnumParser::getCount() - && (int)achievements.size() >= EnumParser::getCount(); - } + break; + case SHIMEVENT_GETSTATF: + if (debugEnabled) + printf("\nGot Shim event SHIMEVENT_GETSTATF for stat [%s] value [%f] " + "isOk = %d\n", + e->name, e->fvalue, e->okay); + if (e->okay) { + updateStat(e->name, e->fvalue); + } + break; + case SHIMEVENT_SETSTATI: + if (debugEnabled) + printf("\nGot Shim event SHIMEVENT_SETSTATI for stat [%s] value [%d] " + "isOk = %d\n", + e->name, e->ivalue, e->okay); + break; + case SHIMEVENT_SETSTATF: + if (debugEnabled) + printf("\nGot Shim event SHIMEVENT_SETSTATF for stat [%s] value [%f] " + "isOk = %d\n", + e->name, e->fvalue, e->okay); + break; + default: + if (debugEnabled) + printf("\nGot Shim event [%d] isOk = %d\n", e->type, e->okay); + break; + } + if (waitForEvent != NULL && *waitForEvent == e->type) { + return e; + } + } + return NULL; + } + + bool initialized() { + return !userName.empty() && !lang.empty() && + (int)stats.size() >= EnumParser::getCount() && + (int)achievements.size() >= + EnumParser::getCount(); + } }; bool SteamPrivate::debugEnabled = false; /* Steam */ -Steam::Steam() : p(new SteamPrivate()) { -} +Steam::Steam() : p(new SteamPrivate()) {} -Steam::~Steam() { - delete p; -} +Steam::~Steam() { delete p; } -const std::string &Steam::userName() const { - return p->userName; -} +const std::string &Steam::userName() const { return p->userName; } -const std::string &Steam::lang() const { - return p->lang; -} +const std::string &Steam::lang() const { return p->lang; } void Steam::resetStats(const int bAlsoAchievements) const { - STEAMSHIM_resetStats(false); - p->update(); + STEAMSHIM_resetStats(false); + p->update(); } void Steam::storeStats() const { - STEAMSHIM_storeStats(); - STEAMSHIM_EventType statsStored = SHIMEVENT_STATSSTORED; - - Shared::PlatformCommon::Chrono timer; - timer.start(); - while(timer.getMillis() < 2500) { - SDL_Delay(100); - const STEAMSHIM_Event *evt = p->update(&statsStored); - if(evt != NULL && evt->type == statsStored) { - break; - } - } + STEAMSHIM_storeStats(); + STEAMSHIM_EventType statsStored = SHIMEVENT_STATSSTORED; + + Shared::PlatformCommon::Chrono timer; + timer.start(); + while (timer.getMillis() < 2500) { + SDL_Delay(100); + const STEAMSHIM_Event *evt = p->update(&statsStored); + if (evt != NULL && evt->type == statsStored) { + break; + } + } } int Steam::getStatAsInt(const char *name) const { - return p->getStatAsInt(name); + return p->getStatAsInt(name); } double Steam::getStatAsDouble(const char *name) const { - return p->getStatAsDouble(name); + return p->getStatAsDouble(name); } void Steam::setStatAsInt(const char *name, int value) { - p->setStatAsInt(name, value); + p->setStatAsInt(name, value); } void Steam::setStatAsDouble(const char *name, double value) { - p->setStatAsFloat(name, value); + p->setStatAsFloat(name, value); } void Steam::requestRefreshStats() { - STEAMSHIM_requestStats(); - STEAMSHIM_EventType statsReceived = SHIMEVENT_STATSRECEIVED; - Shared::PlatformCommon::Chrono timerStats; - timerStats.start(); - while(p->update(&statsReceived) == NULL && timerStats.getMillis() < 2500) { - SDL_Delay(100); - } - p->refreshAllStats(); + STEAMSHIM_requestStats(); + STEAMSHIM_EventType statsReceived = SHIMEVENT_STATSRECEIVED; + Shared::PlatformCommon::Chrono timerStats; + timerStats.start(); + while (p->update(&statsReceived) == NULL && timerStats.getMillis() < 2500) { + SDL_Delay(100); + } + p->refreshAllStats(); } SteamStatType Steam::getSteamStatNameType(string value) { - return SteamStatNameTypes[value]; + return SteamStatNameTypes[value]; } -void Steam::unlock(const char *name) { - p->setAchievement(name, true); -} +void Steam::unlock(const char *name) { p->setAchievement(name, true); } -void Steam::lock(const char *name) { - p->setAchievement(name, false); -} +void Steam::lock(const char *name) { p->setAchievement(name, false); } -bool Steam::isUnlocked(const char *name) { - return p->isAchievementSet(name); -} +bool Steam::isUnlocked(const char *name) { return p->isAchievementSet(name); } void Steam::setDebugEnabled(bool value) { - SteamPrivate::setDebugEnabled(value); + SteamPrivate::setDebugEnabled(value); } /* SteamLocal */ SteamLocal::SteamLocal(string file) : p(new Properties()) { - saveFilePlayerLocalStats = file; - if(fileExists(saveFilePlayerLocalStats)) { - p->load(saveFilePlayerLocalStats); - } + saveFilePlayerLocalStats = file; + if (fileExists(saveFilePlayerLocalStats)) { + p->load(saveFilePlayerLocalStats); + } } -SteamLocal::~SteamLocal() { - delete p; -} +SteamLocal::~SteamLocal() { delete p; } void SteamLocal::unlock(const char *name) { - //p->setAchievement(name, true); - p->setBool(name,true); + // p->setAchievement(name, true); + p->setBool(name, true); } void SteamLocal::lock(const char *name) { - //p->setAchievement(name, false); + // p->setAchievement(name, false); } bool SteamLocal::isUnlocked(const char *name) { - //return p->isAchievementSet(name); - return p->getBool(name,"false"); + // return p->isAchievementSet(name); + return p->getBool(name, "false"); } int SteamLocal::getStatAsInt(const char *name) const { - return p->getInt(name,"0"); + return p->getInt(name, "0"); } void SteamLocal::setStatAsInt(const char *name, int value) { - p->setInt(name,value); + p->setInt(name, value); } -//void SteamLocal::save(const string &path) { +// void SteamLocal::save(const string &path) { // p->save(path); -//} +// } -void SteamLocal::storeStats() const { - p->save(saveFilePlayerLocalStats); -} +void SteamLocal::storeStats() const { p->save(saveFilePlayerLocalStats); } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/steam/steam.h b/source/glest_game/steam/steam.h index 5b1c6905c..83e2fc833 100644 --- a/source/glest_game/steam/steam.h +++ b/source/glest_game/steam/steam.h @@ -1,85 +1,87 @@ #ifndef STEAM_H #define STEAM_H -#include -#include #include "game_constants.h" +#include +#include -namespace Shared{ namespace Util{ - class Properties; -}} +namespace Shared { +namespace Util { +class Properties; +} +} // namespace Shared -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { struct SteamPrivate; enum SteamStatName { - stat_online_wins, - stat_online_loses, - stat_online_kills, - stat_online_kills_enemy, - stat_online_deaths, - stat_online_units, - stat_online_resources_harvested, - stat_online_quit_before_end, - stat_online_minutes_played, - games_played, - network_games_played -}; - -enum SteamStatType { - stat_int, - stat_float, - stat_avg + stat_online_wins, + stat_online_loses, + stat_online_kills, + stat_online_kills_enemy, + stat_online_deaths, + stat_online_units, + stat_online_resources_harvested, + stat_online_quit_before_end, + stat_online_minutes_played, + games_played, + network_games_played }; -template <> -inline EnumParser::EnumParser() { - enumMap["stat_online_wins"] = stat_online_wins; - enumMap["stat_online_loses"] = stat_online_loses; - enumMap["stat_online_kills"] = stat_online_kills; - enumMap["stat_online_kills_enemy"] = stat_online_kills_enemy; - enumMap["stat_online_deaths"] = stat_online_deaths; - enumMap["stat_online_units"] = stat_online_units; - enumMap["stat_online_resources_harvested"] = stat_online_resources_harvested; - enumMap["stat_online_quit_before_end"] = stat_online_quit_before_end; - enumMap["stat_online_minutes_played"] = stat_online_minutes_played; - enumMap["games_played"] = games_played; - enumMap["network_games_played"] = network_games_played; +enum SteamStatType { stat_int, stat_float, stat_avg }; + +template <> inline EnumParser::EnumParser() { + enumMap["stat_online_wins"] = stat_online_wins; + enumMap["stat_online_loses"] = stat_online_loses; + enumMap["stat_online_kills"] = stat_online_kills; + enumMap["stat_online_kills_enemy"] = stat_online_kills_enemy; + enumMap["stat_online_deaths"] = stat_online_deaths; + enumMap["stat_online_units"] = stat_online_units; + enumMap["stat_online_resources_harvested"] = stat_online_resources_harvested; + enumMap["stat_online_quit_before_end"] = stat_online_quit_before_end; + enumMap["stat_online_minutes_played"] = stat_online_minutes_played; + enumMap["games_played"] = games_played; + enumMap["network_games_played"] = network_games_played; } enum SteamAchievementName { - ACH_WIN_ONE_GAME, - ACH_PLAY_FIFTY_GAMES, - ACH_PLAY_ONE_HUNDRED_GAMES, - ACH_PLAY_TWO_HUNDRED_FIFTY_GAMES, - ACH_PLAY_FIVE_HUNDRED_GAMES, - ACH_PLAY_OVER_THOUSAND_GAMES, - - ACH_WIN_ONE_GAME_ONLINE, - ACH_PLAY_FIFTY_GAMES_ONLINE, - ACH_PLAY_ONE_HUNDRED_GAMES_ONLINE, - ACH_PLAY_TWO_HUNDRED_FIFTY_GAMES_ONLINE, - ACH_PLAY_FIVE_HUNDRED_GAMES_ONLINE, - ACH_PLAY_OVER_THOUSAND_GAMES_ONLINE + ACH_WIN_ONE_GAME, + ACH_PLAY_FIFTY_GAMES, + ACH_PLAY_ONE_HUNDRED_GAMES, + ACH_PLAY_TWO_HUNDRED_FIFTY_GAMES, + ACH_PLAY_FIVE_HUNDRED_GAMES, + ACH_PLAY_OVER_THOUSAND_GAMES, + + ACH_WIN_ONE_GAME_ONLINE, + ACH_PLAY_FIFTY_GAMES_ONLINE, + ACH_PLAY_ONE_HUNDRED_GAMES_ONLINE, + ACH_PLAY_TWO_HUNDRED_FIFTY_GAMES_ONLINE, + ACH_PLAY_FIVE_HUNDRED_GAMES_ONLINE, + ACH_PLAY_OVER_THOUSAND_GAMES_ONLINE }; -template <> -inline EnumParser::EnumParser() { - enumMap["ACH_WIN_ONE_GAME"] = ACH_WIN_ONE_GAME; - enumMap["ACH_PLAY_FIFTY_GAMES"] = ACH_PLAY_FIFTY_GAMES; - enumMap["ACH_PLAY_ONE_HUNDRED_GAMES"] = ACH_PLAY_ONE_HUNDRED_GAMES; - enumMap["ACH_PLAY_TWO_HUNDRED_FIFTY_GAMES"] = ACH_PLAY_TWO_HUNDRED_FIFTY_GAMES; - enumMap["ACH_PLAY_FIVE_HUNDRED_GAMES"] = ACH_PLAY_FIVE_HUNDRED_GAMES; - enumMap["ACH_PLAY_OVER_THOUSAND_GAMES"] = ACH_PLAY_OVER_THOUSAND_GAMES; - - enumMap["ACH_WIN_ONE_GAME_ONLINE"] = ACH_WIN_ONE_GAME_ONLINE; - enumMap["ACH_PLAY_FIFTY_GAMES_ONLINE"] = ACH_PLAY_FIFTY_GAMES_ONLINE; - enumMap["ACH_PLAY_ONE_HUNDRED_GAMES_ONLINE"] = ACH_PLAY_ONE_HUNDRED_GAMES_ONLINE; - enumMap["ACH_PLAY_TWO_HUNDRED_FIFTY_GAMES_ONLINE"] = ACH_PLAY_TWO_HUNDRED_FIFTY_GAMES_ONLINE; - enumMap["ACH_PLAY_FIVE_HUNDRED_GAMES_ONLINE"] = ACH_PLAY_FIVE_HUNDRED_GAMES_ONLINE; - enumMap["ACH_PLAY_OVER_THOUSAND_GAMES_ONLINE"] = ACH_PLAY_OVER_THOUSAND_GAMES_ONLINE; +template <> inline EnumParser::EnumParser() { + enumMap["ACH_WIN_ONE_GAME"] = ACH_WIN_ONE_GAME; + enumMap["ACH_PLAY_FIFTY_GAMES"] = ACH_PLAY_FIFTY_GAMES; + enumMap["ACH_PLAY_ONE_HUNDRED_GAMES"] = ACH_PLAY_ONE_HUNDRED_GAMES; + enumMap["ACH_PLAY_TWO_HUNDRED_FIFTY_GAMES"] = + ACH_PLAY_TWO_HUNDRED_FIFTY_GAMES; + enumMap["ACH_PLAY_FIVE_HUNDRED_GAMES"] = ACH_PLAY_FIVE_HUNDRED_GAMES; + enumMap["ACH_PLAY_OVER_THOUSAND_GAMES"] = ACH_PLAY_OVER_THOUSAND_GAMES; + + enumMap["ACH_WIN_ONE_GAME_ONLINE"] = ACH_WIN_ONE_GAME_ONLINE; + enumMap["ACH_PLAY_FIFTY_GAMES_ONLINE"] = ACH_PLAY_FIFTY_GAMES_ONLINE; + enumMap["ACH_PLAY_ONE_HUNDRED_GAMES_ONLINE"] = + ACH_PLAY_ONE_HUNDRED_GAMES_ONLINE; + enumMap["ACH_PLAY_TWO_HUNDRED_FIFTY_GAMES_ONLINE"] = + ACH_PLAY_TWO_HUNDRED_FIFTY_GAMES_ONLINE; + enumMap["ACH_PLAY_FIVE_HUNDRED_GAMES_ONLINE"] = + ACH_PLAY_FIVE_HUNDRED_GAMES_ONLINE; + enumMap["ACH_PLAY_OVER_THOUSAND_GAMES_ONLINE"] = + ACH_PLAY_OVER_THOUSAND_GAMES_ONLINE; } // @@ -87,83 +89,82 @@ inline EnumParser::EnumParser() { // class PlayerAchievementsInterface { public: - virtual void unlock(const char *name) = 0; - virtual void lock(const char *name) = 0; - virtual bool isUnlocked(const char *name) = 0; - virtual int getStatAsInt(const char *name) const = 0; - virtual void setStatAsInt(const char *name, int value) = 0; - virtual void storeStats() const = 0; - - virtual ~PlayerAchievementsInterface() {} + virtual void unlock(const char *name) = 0; + virtual void lock(const char *name) = 0; + virtual bool isUnlocked(const char *name) = 0; + virtual int getStatAsInt(const char *name) const = 0; + virtual void setStatAsInt(const char *name, int value) = 0; + virtual void storeStats() const = 0; + + virtual ~PlayerAchievementsInterface() {} }; -class Steam: public PlayerAchievementsInterface -{ +class Steam : public PlayerAchievementsInterface { public: - void unlock(const char *name); - void lock(const char *name); - bool isUnlocked(const char *name); + void unlock(const char *name); + void lock(const char *name); + bool isUnlocked(const char *name); - static SteamStatType getSteamStatNameType(string value); + static SteamStatType getSteamStatNameType(string value); - const std::string &userName() const; - const std::string &lang() const; + const std::string &userName() const; + const std::string &lang() const; - void resetStats(const int bAlsoAchievements) const; - void storeStats() const; - int getStatAsInt(const char *name) const; - double getStatAsDouble(const char *name) const; - void setStatAsInt(const char *name, int value); - void setStatAsDouble(const char *name, double value); + void resetStats(const int bAlsoAchievements) const; + void storeStats() const; + int getStatAsInt(const char *name) const; + double getStatAsDouble(const char *name) const; + void setStatAsInt(const char *name, int value); + void setStatAsDouble(const char *name, double value); - void requestRefreshStats(); - static void setDebugEnabled(bool value); + void requestRefreshStats(); + static void setDebugEnabled(bool value); - Steam(); - ~Steam(); + Steam(); + ~Steam(); private: - //friend struct SharedStatePrivate; - - SteamPrivate *p; - static std::map SteamStatNameTypes; - - static std::map create_map() { - std::map steamStatNameTypes; - steamStatNameTypes["stat_online_wins"] = stat_int; - steamStatNameTypes["stat_online_loses"] = stat_int; - steamStatNameTypes["stat_online_kills"] = stat_int; - steamStatNameTypes["stat_online_kills_enemy"] = stat_int; - steamStatNameTypes["stat_online_deaths"] = stat_int; - steamStatNameTypes["stat_online_units"] = stat_int; - steamStatNameTypes["stat_online_resources_harvested"] = stat_int; - steamStatNameTypes["stat_online_quit_before_end"] = stat_int; - steamStatNameTypes["stat_online_minutes_played"] = stat_float; - return steamStatNameTypes; - } + // friend struct SharedStatePrivate; + + SteamPrivate *p; + static std::map SteamStatNameTypes; + + static std::map create_map() { + std::map steamStatNameTypes; + steamStatNameTypes["stat_online_wins"] = stat_int; + steamStatNameTypes["stat_online_loses"] = stat_int; + steamStatNameTypes["stat_online_kills"] = stat_int; + steamStatNameTypes["stat_online_kills_enemy"] = stat_int; + steamStatNameTypes["stat_online_deaths"] = stat_int; + steamStatNameTypes["stat_online_units"] = stat_int; + steamStatNameTypes["stat_online_resources_harvested"] = stat_int; + steamStatNameTypes["stat_online_quit_before_end"] = stat_int; + steamStatNameTypes["stat_online_minutes_played"] = stat_float; + return steamStatNameTypes; + } }; -class SteamLocal: public PlayerAchievementsInterface -{ +class SteamLocal : public PlayerAchievementsInterface { public: - SteamLocal(string file); - ~SteamLocal(); + SteamLocal(string file); + ~SteamLocal(); - void unlock(const char *name); - void lock(const char *name); - bool isUnlocked(const char *name); - int getStatAsInt(const char *name) const; + void unlock(const char *name); + void lock(const char *name); + bool isUnlocked(const char *name); + int getStatAsInt(const char *name) const; - void setStatAsInt(const char *name, int value); + void setStatAsInt(const char *name, int value); - //void save(const string &path); - void storeStats() const; + // void save(const string &path); + void storeStats() const; private: - Properties *p; - string saveFilePlayerLocalStats; + Properties *p; + string saveFilePlayerLocalStats; }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif // STEAM_H diff --git a/source/glest_game/steamshim/steamshim_child.c b/source/glest_game/steamshim/steamshim_child.c index be456a6ec..28e9d5811 100644 --- a/source/glest_game/steamshim/steamshim_child.c +++ b/source/glest_game/steamshim/steamshim_child.c @@ -8,13 +8,13 @@ typedef unsigned __int8 uint8; typedef __int32 int32; typedef unsigned __int64 uint64; #else -#include -#include -#include -#include #include #include #include +#include +#include +#include +#include typedef uint8_t uint8; typedef int32_t int32; typedef uint64_t uint64; @@ -37,427 +37,394 @@ static void closePipe(PipeType fd); static char *getEnvVar(const char *key, char *buf, const size_t buflen); static int pipeReady(PipeType fd); - #ifdef _WIN32 -static int pipeReady(PipeType fd) -{ - DWORD avail = 0; - return (PeekNamedPipe(fd, NULL, 0, NULL, &avail, NULL) && (avail > 0)); +static int pipeReady(PipeType fd) { + DWORD avail = 0; + return (PeekNamedPipe(fd, NULL, 0, NULL, &avail, NULL) && (avail > 0)); } /* pipeReady */ -static int writePipe(PipeType fd, const void *buf, const unsigned int _len) -{ - const DWORD len = (DWORD) _len; - DWORD bw = 0; - return ((WriteFile(fd, buf, len, &bw, NULL) != 0) && (bw == len)); +static int writePipe(PipeType fd, const void *buf, const unsigned int _len) { + const DWORD len = (DWORD)_len; + DWORD bw = 0; + return ((WriteFile(fd, buf, len, &bw, NULL) != 0) && (bw == len)); } /* writePipe */ -static int readPipe(PipeType fd, void *buf, const unsigned int _len) -{ - const DWORD len = (DWORD) _len; - DWORD br = 0; - return ReadFile(fd, buf, len, &br, NULL) ? (int) br : -1; +static int readPipe(PipeType fd, void *buf, const unsigned int _len) { + const DWORD len = (DWORD)_len; + DWORD br = 0; + return ReadFile(fd, buf, len, &br, NULL) ? (int)br : -1; } /* readPipe */ -static void closePipe(PipeType fd) -{ - CloseHandle(fd); -} /* closePipe */ +static void closePipe(PipeType fd) { CloseHandle(fd); } /* closePipe */ -static char *getEnvVar(const char *key, char *buf, const size_t buflen) -{ - const DWORD rc = GetEnvironmentVariableA(key, buf, buflen); - /* rc doesn't count null char, hence "<". */ - return ((rc > 0) && (rc < buflen)) ? buf : NULL; +static char *getEnvVar(const char *key, char *buf, const size_t buflen) { + const DWORD rc = GetEnvironmentVariableA(key, buf, buflen); + /* rc doesn't count null char, hence "<". */ + return ((rc > 0) && (rc < buflen)) ? buf : NULL; } /* getEnvVar */ #else -static int pipeReady(PipeType fd) -{ - int rc; - struct pollfd pfd = { fd, POLLIN | POLLERR | POLLHUP, 0 }; - while (((rc = poll(&pfd, 1, 0)) == -1) && (errno == EINTR)) { /*spin*/ } - return (rc == 1); +static int pipeReady(PipeType fd) { + int rc; + struct pollfd pfd = {fd, POLLIN | POLLERR | POLLHUP, 0}; + while (((rc = poll(&pfd, 1, 0)) == -1) && (errno == EINTR)) { /*spin*/ + } + return (rc == 1); } /* pipeReady */ -static int writePipe(PipeType fd, const void *buf, const unsigned int _len) -{ - const ssize_t len = (ssize_t) _len; - ssize_t bw; - while (((bw = write(fd, buf, len)) == -1) && (errno == EINTR)) { /*spin*/ } - return (bw == len); +static int writePipe(PipeType fd, const void *buf, const unsigned int _len) { + const ssize_t len = (ssize_t)_len; + ssize_t bw; + while (((bw = write(fd, buf, len)) == -1) && (errno == EINTR)) { /*spin*/ + } + return (bw == len); } /* writePipe */ -static int readPipe(PipeType fd, void *buf, const unsigned int _len) -{ - const ssize_t len = (ssize_t) _len; - ssize_t br; - while (((br = read(fd, buf, len)) == -1) && (errno == EINTR)) { /*spin*/ } - return (int) br; +static int readPipe(PipeType fd, void *buf, const unsigned int _len) { + const ssize_t len = (ssize_t)_len; + ssize_t br; + while (((br = read(fd, buf, len)) == -1) && (errno == EINTR)) { /*spin*/ + } + return (int)br; } /* readPipe */ -static void closePipe(PipeType fd) -{ - close(fd); -} /* closePipe */ - -static char *getEnvVar(const char *key, char *buf, const size_t buflen) -{ - const char *envr = getenv(key); - if (!envr || (strlen(envr) >= buflen)) - return NULL; - strcpy(buf, envr); - return buf; +static void closePipe(PipeType fd) { close(fd); } /* closePipe */ + +static char *getEnvVar(const char *key, char *buf, const size_t buflen) { + const char *envr = getenv(key); + if (!envr || (strlen(envr) >= buflen)) + return NULL; + strcpy(buf, envr); + return buf; } /* getEnvVar */ #endif - static PipeType GPipeRead = NULLPIPE; static PipeType GPipeWrite = NULLPIPE; -typedef enum ShimCmd -{ - SHIMCMD_BYE, - SHIMCMD_PUMP, - SHIMCMD_REQUESTSTATS, - SHIMCMD_STORESTATS, - SHIMCMD_SETACHIEVEMENT, - SHIMCMD_GETACHIEVEMENT, - SHIMCMD_RESETSTATS, - SHIMCMD_SETSTATI, - SHIMCMD_GETSTATI, - SHIMCMD_SETSTATF, - SHIMCMD_GETSTATF, - SHIMCMD_GETPERSONANAME, - SHIMCMD_GETCURRENTGAMELANGUAGE, +typedef enum ShimCmd { + SHIMCMD_BYE, + SHIMCMD_PUMP, + SHIMCMD_REQUESTSTATS, + SHIMCMD_STORESTATS, + SHIMCMD_SETACHIEVEMENT, + SHIMCMD_GETACHIEVEMENT, + SHIMCMD_RESETSTATS, + SHIMCMD_SETSTATI, + SHIMCMD_GETSTATI, + SHIMCMD_SETSTATF, + SHIMCMD_GETSTATF, + SHIMCMD_GETPERSONANAME, + SHIMCMD_GETCURRENTGAMELANGUAGE, } ShimCmd; -static int write1ByteCmd(const uint8 b1) -{ - const uint8 buf[] = { 1, b1 }; - return writePipe(GPipeWrite, buf, sizeof (buf)); +static int write1ByteCmd(const uint8 b1) { + const uint8 buf[] = {1, b1}; + return writePipe(GPipeWrite, buf, sizeof(buf)); } /* write1ByteCmd */ -static int write2ByteCmd(const uint8 b1, const uint8 b2) -{ - const uint8 buf[] = { 2, b1, b2 }; - return writePipe(GPipeWrite, buf, sizeof (buf)); +static int write2ByteCmd(const uint8 b1, const uint8 b2) { + const uint8 buf[] = {2, b1, b2}; + return writePipe(GPipeWrite, buf, sizeof(buf)); } /* write2ByteCmd */ -static inline int writeBye(void) -{ - dbgpipe("Child sending SHIMCMD_BYE().\n"); - return write1ByteCmd(SHIMCMD_BYE); +static inline int writeBye(void) { + dbgpipe("Child sending SHIMCMD_BYE().\n"); + return write1ByteCmd(SHIMCMD_BYE); } // writeBye -static int initPipes(void) -{ - char buf[64]; +static int initPipes(void) { + char buf[64]; - if (!getEnvVar("STEAMSHIM_READHANDLE", buf, sizeof (buf))) - return 0; - GPipeRead = (PipeType) strtoull(buf, 0, 10); + if (!getEnvVar("STEAMSHIM_READHANDLE", buf, sizeof(buf))) + return 0; + GPipeRead = (PipeType)strtoull(buf, 0, 10); - if (!getEnvVar("STEAMSHIM_WRITEHANDLE", buf, sizeof (buf))) - return 0; - GPipeWrite = (PipeType) strtoull(buf, 0, 10); + if (!getEnvVar("STEAMSHIM_WRITEHANDLE", buf, sizeof(buf))) + return 0; + GPipeWrite = (PipeType)strtoull(buf, 0, 10); - return ((GPipeRead != NULLPIPE) && (GPipeWrite != NULLPIPE)); + return ((GPipeRead != NULLPIPE) && (GPipeWrite != NULLPIPE)); } /* initPipes */ - -int STEAMSHIM_init(void) -{ - printf("Initializing Steam Shim...\n"); - dbgpipe("Child init start.\n"); - if (!initPipes()) - { - dbgpipe("Child init failed.\n"); - return 0; - } /* if */ +int STEAMSHIM_init(void) { + printf("Initializing Steam Shim...\n"); + dbgpipe("Child init start.\n"); + if (!initPipes()) { + dbgpipe("Child init failed.\n"); + return 0; + } /* if */ #ifndef _WIN32 - signal(SIGPIPE, SIG_IGN); + signal(SIGPIPE, SIG_IGN); #endif - printf("Init of Steam Shim successful!\n"); - dbgpipe("Child init success!\n"); - return 1; + printf("Init of Steam Shim successful!\n"); + dbgpipe("Child init success!\n"); + return 1; } /* STEAMSHIM_init */ -void STEAMSHIM_deinit(void) -{ - dbgpipe("Child deinit.\n"); - if (GPipeWrite != NULLPIPE) - { - writeBye(); - closePipe(GPipeWrite); - } /* if */ +void STEAMSHIM_deinit(void) { + dbgpipe("Child deinit.\n"); + if (GPipeWrite != NULLPIPE) { + writeBye(); + closePipe(GPipeWrite); + } /* if */ - if (GPipeRead != NULLPIPE) - closePipe(GPipeRead); + if (GPipeRead != NULLPIPE) + closePipe(GPipeRead); - GPipeRead = GPipeWrite = NULLPIPE; + GPipeRead = GPipeWrite = NULLPIPE; #ifndef _WIN32 - signal(SIGPIPE, SIG_DFL); + signal(SIGPIPE, SIG_DFL); #endif } /* STEAMSHIM_deinit */ -static inline int isAlive(void) -{ - return ((GPipeRead != NULLPIPE) && (GPipeWrite != NULLPIPE)); +static inline int isAlive(void) { + return ((GPipeRead != NULLPIPE) && (GPipeWrite != NULLPIPE)); } /* isAlive */ -static inline int isDead(void) -{ - return !isAlive(); -} /* isDead */ - -int STEAMSHIM_alive(void) -{ - return isAlive(); -} /* STEAMSHIM_alive */ - -static const STEAMSHIM_Event *processEvent(const uint8 *buf, size_t buflen) -{ - static STEAMSHIM_Event event; - const STEAMSHIM_EventType type = (STEAMSHIM_EventType) *(buf++); - buflen--; - - memset(&event, '\0', sizeof (event)); - event.type = type; - event.okay = 1; - - #ifdef STEAMSHIM_DEBUG - if (0) {} - #define PRINTGOTEVENT(x) else if (type == x) printf("Child got " #x ".\n") - PRINTGOTEVENT(SHIMEVENT_BYE); - PRINTGOTEVENT(SHIMEVENT_STATSRECEIVED); - PRINTGOTEVENT(SHIMEVENT_STATSSTORED); - PRINTGOTEVENT(SHIMEVENT_SETACHIEVEMENT); - PRINTGOTEVENT(SHIMEVENT_GETACHIEVEMENT); - PRINTGOTEVENT(SHIMEVENT_RESETSTATS); - PRINTGOTEVENT(SHIMEVENT_SETSTATI); - PRINTGOTEVENT(SHIMEVENT_GETSTATI); - PRINTGOTEVENT(SHIMEVENT_SETSTATF); - PRINTGOTEVENT(SHIMEVENT_GETSTATF); - PRINTGOTEVENT(SHIMEVENT_GETPERSONANAME); - PRINTGOTEVENT(SHIMEVENT_GETCURRENTGAMELANGUAGE); - #undef PRINTGOTEVENT - else printf("Child got unknown shimevent %d.\n", (int) type); - #endif - - switch (type) - { - case SHIMEVENT_BYE: - break; - - case SHIMEVENT_STATSRECEIVED: - case SHIMEVENT_STATSSTORED: - if (!buflen) return NULL; - event.okay = *(buf++) ? 1 : 0; - break; - - case SHIMEVENT_SETACHIEVEMENT: - if (buflen < 3) return NULL; - event.ivalue = *(buf++) ? 1 : 0; - event.okay = *(buf++) ? 1 : 0; - strcpy(event.name, (const char *) buf); - break; - - case SHIMEVENT_GETACHIEVEMENT: - if (buflen < 10) return NULL; - event.ivalue = (int) *(buf++); - if (event.ivalue == 2) - event.ivalue = event.okay = 0; - event.epochsecs = (long long unsigned) *((uint64 *) buf); - buf += sizeof (uint64); - strcpy(event.name, (const char *) buf); - break; - - case SHIMEVENT_RESETSTATS: - if (buflen != 2) return NULL; - event.ivalue = *(buf++) ? 1 : 0; - event.okay = *(buf++) ? 1 : 0; - break; - - case SHIMEVENT_SETSTATI: - case SHIMEVENT_GETSTATI: - event.okay = *(buf++) ? 1 : 0; - event.ivalue = (int) *((int32 *) buf); - buf += sizeof (int32); - strcpy(event.name, (const char *) buf); - break; - - case SHIMEVENT_SETSTATF: - case SHIMEVENT_GETSTATF: - event.okay = *(buf++) ? 1 : 0; - event.fvalue = (int) *((float *) buf); - buf += sizeof (float); - strcpy(event.name, (const char *) buf); - break; - - case SHIMEVENT_GETPERSONANAME: - case SHIMEVENT_GETCURRENTGAMELANGUAGE: - strcpy(event.name, (const char *) buf); - break; - - default: /* uh oh */ - return NULL; - } /* switch */ - - return &event; +static inline int isDead(void) { return !isAlive(); } /* isDead */ + +int STEAMSHIM_alive(void) { return isAlive(); } /* STEAMSHIM_alive */ + +static const STEAMSHIM_Event *processEvent(const uint8 *buf, size_t buflen) { + static STEAMSHIM_Event event; + const STEAMSHIM_EventType type = (STEAMSHIM_EventType) * (buf++); + buflen--; + + memset(&event, '\0', sizeof(event)); + event.type = type; + event.okay = 1; + +#ifdef STEAMSHIM_DEBUG + if (0) { + } +#define PRINTGOTEVENT(x) else if (type == x) printf("Child got " #x ".\n") + PRINTGOTEVENT(SHIMEVENT_BYE); + PRINTGOTEVENT(SHIMEVENT_STATSRECEIVED); + PRINTGOTEVENT(SHIMEVENT_STATSSTORED); + PRINTGOTEVENT(SHIMEVENT_SETACHIEVEMENT); + PRINTGOTEVENT(SHIMEVENT_GETACHIEVEMENT); + PRINTGOTEVENT(SHIMEVENT_RESETSTATS); + PRINTGOTEVENT(SHIMEVENT_SETSTATI); + PRINTGOTEVENT(SHIMEVENT_GETSTATI); + PRINTGOTEVENT(SHIMEVENT_SETSTATF); + PRINTGOTEVENT(SHIMEVENT_GETSTATF); + PRINTGOTEVENT(SHIMEVENT_GETPERSONANAME); + PRINTGOTEVENT(SHIMEVENT_GETCURRENTGAMELANGUAGE); +#undef PRINTGOTEVENT + else printf("Child got unknown shimevent %d.\n", (int)type); +#endif + + switch (type) { + case SHIMEVENT_BYE: + break; + + case SHIMEVENT_STATSRECEIVED: + case SHIMEVENT_STATSSTORED: + if (!buflen) + return NULL; + event.okay = *(buf++) ? 1 : 0; + break; + + case SHIMEVENT_SETACHIEVEMENT: + if (buflen < 3) + return NULL; + event.ivalue = *(buf++) ? 1 : 0; + event.okay = *(buf++) ? 1 : 0; + strcpy(event.name, (const char *)buf); + break; + + case SHIMEVENT_GETACHIEVEMENT: + if (buflen < 10) + return NULL; + event.ivalue = (int)*(buf++); + if (event.ivalue == 2) + event.ivalue = event.okay = 0; + event.epochsecs = (long long unsigned)*((uint64 *)buf); + buf += sizeof(uint64); + strcpy(event.name, (const char *)buf); + break; + + case SHIMEVENT_RESETSTATS: + if (buflen != 2) + return NULL; + event.ivalue = *(buf++) ? 1 : 0; + event.okay = *(buf++) ? 1 : 0; + break; + + case SHIMEVENT_SETSTATI: + case SHIMEVENT_GETSTATI: + event.okay = *(buf++) ? 1 : 0; + event.ivalue = (int)*((int32 *)buf); + buf += sizeof(int32); + strcpy(event.name, (const char *)buf); + break; + + case SHIMEVENT_SETSTATF: + case SHIMEVENT_GETSTATF: + event.okay = *(buf++) ? 1 : 0; + event.fvalue = (int)*((float *)buf); + buf += sizeof(float); + strcpy(event.name, (const char *)buf); + break; + + case SHIMEVENT_GETPERSONANAME: + case SHIMEVENT_GETCURRENTGAMELANGUAGE: + strcpy(event.name, (const char *)buf); + break; + + default: /* uh oh */ + return NULL; + } /* switch */ + + return &event; } /* processEvent */ -const STEAMSHIM_Event *STEAMSHIM_pump(void) -{ - static uint8 buf[256]; - static int br = 0; - int evlen = (br > 0) ? ((int) buf[0]) : 0; - - if (isDead()) - return NULL; - - if (br <= evlen) /* we have an incomplete commmand. Try to read more. */ - { - if (pipeReady(GPipeRead)) - { - const int morebr = readPipe(GPipeRead, buf + br, sizeof (buf) - br); - if (morebr > 0) - br += morebr; - else /* uh oh */ - { - dbgpipe("Child readPipe failed! Shutting down.\n"); - STEAMSHIM_deinit(); /* kill it all. */ - } /* else */ - } /* if */ - } /* if */ - - if (evlen && (br > evlen)) - { - const STEAMSHIM_Event *retval = processEvent(buf+1, evlen); - br -= evlen + 1; - if (br > 0) - memmove(buf, buf+evlen+1, br); - return retval; - } /* if */ - - /* Run Steam event loop. */ - if (br == 0) - { - dbgpipe("Child sending SHIMCMD_PUMP().\n"); - write1ByteCmd(SHIMCMD_PUMP); - } /* if */ +const STEAMSHIM_Event *STEAMSHIM_pump(void) { + static uint8 buf[256]; + static int br = 0; + int evlen = (br > 0) ? ((int)buf[0]) : 0; + if (isDead()) return NULL; + + if (br <= evlen) /* we have an incomplete commmand. Try to read more. */ + { + if (pipeReady(GPipeRead)) { + const int morebr = readPipe(GPipeRead, buf + br, sizeof(buf) - br); + if (morebr > 0) + br += morebr; + else /* uh oh */ + { + dbgpipe("Child readPipe failed! Shutting down.\n"); + STEAMSHIM_deinit(); /* kill it all. */ + } /* else */ + } /* if */ + } /* if */ + + if (evlen && (br > evlen)) { + const STEAMSHIM_Event *retval = processEvent(buf + 1, evlen); + br -= evlen + 1; + if (br > 0) + memmove(buf, buf + evlen + 1, br); + return retval; + } /* if */ + + /* Run Steam event loop. */ + if (br == 0) { + dbgpipe("Child sending SHIMCMD_PUMP().\n"); + write1ByteCmd(SHIMCMD_PUMP); + } /* if */ + + return NULL; } /* STEAMSHIM_pump */ -void STEAMSHIM_requestStats(void) -{ - if (isDead()) return; - dbgpipe("Child sending SHIMCMD_REQUESTSTATS().\n"); - write1ByteCmd(SHIMCMD_REQUESTSTATS); +void STEAMSHIM_requestStats(void) { + if (isDead()) + return; + dbgpipe("Child sending SHIMCMD_REQUESTSTATS().\n"); + write1ByteCmd(SHIMCMD_REQUESTSTATS); } /* STEAMSHIM_requestStats */ -void STEAMSHIM_storeStats(void) -{ - if (isDead()) return; - dbgpipe("Child sending SHIMCMD_STORESTATS().\n"); - write1ByteCmd(SHIMCMD_STORESTATS); +void STEAMSHIM_storeStats(void) { + if (isDead()) + return; + dbgpipe("Child sending SHIMCMD_STORESTATS().\n"); + write1ByteCmd(SHIMCMD_STORESTATS); } /* STEAMSHIM_storeStats */ -void STEAMSHIM_setAchievement(const char *name, const int enable) -{ - uint8 buf[256]; - uint8 *ptr = buf+1; - if (isDead()) return; - dbgpipe("Child sending SHIMCMD_SETACHIEVEMENT('%s', %senable).\n", name, enable ? "" : "!"); - *(ptr++) = (uint8) SHIMCMD_SETACHIEVEMENT; - *(ptr++) = enable ? 1 : 0; - strcpy((char *) ptr, name); - ptr += strlen(name) + 1; - buf[0] = (uint8) ((ptr-1) - buf); - writePipe(GPipeWrite, buf, buf[0] + 1); +void STEAMSHIM_setAchievement(const char *name, const int enable) { + uint8 buf[256]; + uint8 *ptr = buf + 1; + if (isDead()) + return; + dbgpipe("Child sending SHIMCMD_SETACHIEVEMENT('%s', %senable).\n", name, + enable ? "" : "!"); + *(ptr++) = (uint8)SHIMCMD_SETACHIEVEMENT; + *(ptr++) = enable ? 1 : 0; + strcpy((char *)ptr, name); + ptr += strlen(name) + 1; + buf[0] = (uint8)((ptr - 1) - buf); + writePipe(GPipeWrite, buf, buf[0] + 1); } /* STEAMSHIM_setAchievement */ -void STEAMSHIM_getAchievement(const char *name) -{ - uint8 buf[256]; - uint8 *ptr = buf+1; - if (isDead()) return; - dbgpipe("Child sending SHIMCMD_GETACHIEVEMENT('%s').\n", name); - *(ptr++) = (uint8) SHIMCMD_GETACHIEVEMENT; - strcpy((char *) ptr, name); - ptr += strlen(name) + 1; - buf[0] = (uint8) ((ptr-1) - buf); - writePipe(GPipeWrite, buf, buf[0] + 1); +void STEAMSHIM_getAchievement(const char *name) { + uint8 buf[256]; + uint8 *ptr = buf + 1; + if (isDead()) + return; + dbgpipe("Child sending SHIMCMD_GETACHIEVEMENT('%s').\n", name); + *(ptr++) = (uint8)SHIMCMD_GETACHIEVEMENT; + strcpy((char *)ptr, name); + ptr += strlen(name) + 1; + buf[0] = (uint8)((ptr - 1) - buf); + writePipe(GPipeWrite, buf, buf[0] + 1); } /* STEAMSHIM_getAchievement */ -void STEAMSHIM_resetStats(const int bAlsoAchievements) -{ - if (isDead()) return; - dbgpipe("Child sending SHIMCMD_RESETSTATS(%salsoAchievements).\n", bAlsoAchievements ? "" : "!"); - write2ByteCmd(SHIMCMD_RESETSTATS, bAlsoAchievements ? 1 : 0); +void STEAMSHIM_resetStats(const int bAlsoAchievements) { + if (isDead()) + return; + dbgpipe("Child sending SHIMCMD_RESETSTATS(%salsoAchievements).\n", + bAlsoAchievements ? "" : "!"); + write2ByteCmd(SHIMCMD_RESETSTATS, bAlsoAchievements ? 1 : 0); } /* STEAMSHIM_resetStats */ -static void writeStatThing(const ShimCmd cmd, const char *name, const void *val, const size_t vallen) -{ - uint8 buf[256]; - uint8 *ptr = buf+1; - if (isDead()) return; - *(ptr++) = (uint8) cmd; - if (vallen) - { - memcpy(ptr, val, vallen); - ptr += vallen; - } /* if */ - strcpy((char *) ptr, name); - ptr += strlen(name) + 1; - buf[0] = (uint8) ((ptr-1) - buf); - writePipe(GPipeWrite, buf, buf[0] + 1); +static void writeStatThing(const ShimCmd cmd, const char *name, const void *val, + const size_t vallen) { + uint8 buf[256]; + uint8 *ptr = buf + 1; + if (isDead()) + return; + *(ptr++) = (uint8)cmd; + if (vallen) { + memcpy(ptr, val, vallen); + ptr += vallen; + } /* if */ + strcpy((char *)ptr, name); + ptr += strlen(name) + 1; + buf[0] = (uint8)((ptr - 1) - buf); + writePipe(GPipeWrite, buf, buf[0] + 1); } /* writeStatThing */ -void STEAMSHIM_setStatI(const char *name, const int _val) -{ - const int32 val = (int32) _val; - dbgpipe("Child sending SHIMCMD_SETSTATI('%s', val %d).\n", name, val); - writeStatThing(SHIMCMD_SETSTATI, name, &val, sizeof (val)); +void STEAMSHIM_setStatI(const char *name, const int _val) { + const int32 val = (int32)_val; + dbgpipe("Child sending SHIMCMD_SETSTATI('%s', val %d).\n", name, val); + writeStatThing(SHIMCMD_SETSTATI, name, &val, sizeof(val)); } /* STEAMSHIM_setStatI */ -void STEAMSHIM_getStatI(const char *name) -{ - dbgpipe("Child sending SHIMCMD_GETSTATI('%s').\n", name); - writeStatThing(SHIMCMD_GETSTATI, name, NULL, 0); +void STEAMSHIM_getStatI(const char *name) { + dbgpipe("Child sending SHIMCMD_GETSTATI('%s').\n", name); + writeStatThing(SHIMCMD_GETSTATI, name, NULL, 0); } /* STEAMSHIM_getStatI */ -void STEAMSHIM_setStatF(const char *name, const float val) -{ - dbgpipe("Child sending SHIMCMD_SETSTATF('%s', val %f).\n", name, val); - writeStatThing(SHIMCMD_SETSTATF, name, &val, sizeof (val)); +void STEAMSHIM_setStatF(const char *name, const float val) { + dbgpipe("Child sending SHIMCMD_SETSTATF('%s', val %f).\n", name, val); + writeStatThing(SHIMCMD_SETSTATF, name, &val, sizeof(val)); } /* STEAMSHIM_setStatF */ -void STEAMSHIM_getStatF(const char *name) -{ - dbgpipe("Child sending SHIMCMD_GETSTATF('%s').\n", name); - writeStatThing(SHIMCMD_GETSTATF, name, NULL, 0); +void STEAMSHIM_getStatF(const char *name) { + dbgpipe("Child sending SHIMCMD_GETSTATF('%s').\n", name); + writeStatThing(SHIMCMD_GETSTATF, name, NULL, 0); } /* STEAMSHIM_getStatF */ -void STEAMSHIM_getPersonaName() -{ - if (isDead()) return; - dbgpipe("Child sending SHIMCMD_GETPERSONANAME().\n"); - write1ByteCmd(SHIMCMD_GETPERSONANAME); +void STEAMSHIM_getPersonaName() { + if (isDead()) + return; + dbgpipe("Child sending SHIMCMD_GETPERSONANAME().\n"); + write1ByteCmd(SHIMCMD_GETPERSONANAME); } /* STEAMSHIM_getPersonaName */ -void STEAMSHIM_getCurrentGameLanguage() -{ - if (isDead()) return; - dbgpipe("Child sending SHIMCMD_GETCURRENTGAMELANGUAGE().\n"); - write1ByteCmd(SHIMCMD_GETCURRENTGAMELANGUAGE); +void STEAMSHIM_getCurrentGameLanguage() { + if (isDead()) + return; + dbgpipe("Child sending SHIMCMD_GETCURRENTGAMELANGUAGE().\n"); + write1ByteCmd(SHIMCMD_GETCURRENTGAMELANGUAGE); } /* STEAMSHIM_getCurrentGameLanguage */ /* end of steamshim_child.c ... */ diff --git a/source/glest_game/steamshim/steamshim_child.h b/source/glest_game/steamshim/steamshim_child.h index 0e3d3a9d3..3f9443b52 100644 --- a/source/glest_game/steamshim/steamshim_child.h +++ b/source/glest_game/steamshim/steamshim_child.h @@ -5,34 +5,32 @@ extern "C" { #endif -typedef enum STEAMSHIM_EventType -{ - SHIMEVENT_BYE, - SHIMEVENT_STATSRECEIVED, - SHIMEVENT_STATSSTORED, - SHIMEVENT_SETACHIEVEMENT, - SHIMEVENT_GETACHIEVEMENT, - SHIMEVENT_RESETSTATS, - SHIMEVENT_SETSTATI, - SHIMEVENT_GETSTATI, - SHIMEVENT_SETSTATF, - SHIMEVENT_GETSTATF, - SHIMEVENT_GETPERSONANAME, - SHIMEVENT_GETCURRENTGAMELANGUAGE, +typedef enum STEAMSHIM_EventType { + SHIMEVENT_BYE, + SHIMEVENT_STATSRECEIVED, + SHIMEVENT_STATSSTORED, + SHIMEVENT_SETACHIEVEMENT, + SHIMEVENT_GETACHIEVEMENT, + SHIMEVENT_RESETSTATS, + SHIMEVENT_SETSTATI, + SHIMEVENT_GETSTATI, + SHIMEVENT_SETSTATF, + SHIMEVENT_GETSTATF, + SHIMEVENT_GETPERSONANAME, + SHIMEVENT_GETCURRENTGAMELANGUAGE, } STEAMSHIM_EventType; /* not all of these fields make sense in a given event. */ -typedef struct STEAMSHIM_Event -{ - STEAMSHIM_EventType type; - int okay; - int ivalue; - float fvalue; - unsigned long long epochsecs; - char name[256]; +typedef struct STEAMSHIM_Event { + STEAMSHIM_EventType type; + int okay; + int ivalue; + float fvalue; + unsigned long long epochsecs; + char name[256]; } STEAMSHIM_Event; -int STEAMSHIM_init(void); /* non-zero on success, zero on failure. */ +int STEAMSHIM_init(void); /* non-zero on success, zero on failure. */ void STEAMSHIM_deinit(void); int STEAMSHIM_alive(void); const STEAMSHIM_Event *STEAMSHIM_pump(void); @@ -52,6 +50,6 @@ void STEAMSHIM_getCurrentGameLanguage(); } #endif -#endif /* include-once blocker */ +#endif /* include-once blocker */ /* end of steamshim_child.h ... */ diff --git a/source/glest_game/type_instances/command.cpp b/source/glest_game/type_instances/command.cpp index 56f45b501..01973699a 100644 --- a/source/glest_game/type_instances/command.cpp +++ b/source/glest_game/type_instances/command.cpp @@ -12,225 +12,249 @@ #include "command.h" #include "command_type.h" -#include "util.h" #include "conversion.h" -#include "unit_type.h" #include "faction.h" -#include "world.h" #include "leak_dumper.h" +#include "unit_type.h" +#include "util.h" +#include "world.h" using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class Command // ===================================================== Command::Command() : unitRef() { - this->commandType= NULL; - unitType= NULL; - stateType = cst_None; - stateValue = -1; - unitCommandGroupId = -1; + this->commandType = NULL; + unitType = NULL; + stateType = cst_None; + stateValue = -1; + unitCommandGroupId = -1; } -Command::Command(const CommandType *ct, const Vec2i &pos) :unitRef() { - //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] ct = [%p]\n",__FILE__,__FUNCTION__,__LINE__,ct); - - this->commandType= ct; - this->pos= pos; - this->originalPos = this->pos; - unitType= NULL; - stateType = cst_None; - stateValue = -1; - unitCommandGroupId = -1; +Command::Command(const CommandType *ct, const Vec2i &pos) : unitRef() { + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] ct + // = [%p]\n",__FILE__,__FUNCTION__,__LINE__,ct); + + this->commandType = ct; + this->pos = pos; + this->originalPos = this->pos; + unitType = NULL; + stateType = cst_None; + stateValue = -1; + unitCommandGroupId = -1; } -Command::Command(const CommandType *ct, Unit* unit) { - this->commandType= ct; - this->pos= Vec2i(0); - this->originalPos = this->pos; - this->unitRef= unit; - unitType= NULL; - if(unit!=NULL) { - //unit->resetHighlight(); is in gui now - pos= unit->getCellPos(); - } - stateType = cst_None; - stateValue = -1; - unitCommandGroupId = -1; +Command::Command(const CommandType *ct, Unit *unit) { + this->commandType = ct; + this->pos = Vec2i(0); + this->originalPos = this->pos; + this->unitRef = unit; + unitType = NULL; + if (unit != NULL) { + // unit->resetHighlight(); is in gui now + pos = unit->getCellPos(); + } + stateType = cst_None; + stateValue = -1; + unitCommandGroupId = -1; } -Command::Command(const CommandType *ct, const Vec2i &pos, const UnitType *unitType, CardinalDir facing) : unitRef() { - this->commandType= ct; - this->pos= pos; - this->originalPos = this->pos; - this->unitType= unitType; - this->facing = facing; - stateType = cst_None; - stateValue = -1; - unitCommandGroupId = -1; - - //if(this->unitType != NULL) { - // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] unitType = [%s]\n",__FILE__,__FUNCTION__,__LINE__,this->unitType->toString().c_str()); - //} +Command::Command(const CommandType *ct, const Vec2i &pos, + const UnitType *unitType, CardinalDir facing) + : unitRef() { + this->commandType = ct; + this->pos = pos; + this->originalPos = this->pos; + this->unitType = unitType; + this->facing = facing; + stateType = cst_None; + stateValue = -1; + unitCommandGroupId = -1; + + // if(this->unitType != NULL) { + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] + // unitType = + //[%s]\n",__FILE__,__FUNCTION__,__LINE__,this->unitType->toString().c_str()); + // } } -int Command::getPriority(){ - if(this->commandType->commandTypeClass==ccAttack && getUnit()==NULL){ - return 5; // attacks to the ground have low priority - } - return this->commandType->getTypePriority(); +int Command::getPriority() { + if (this->commandType->commandTypeClass == ccAttack && getUnit() == NULL) { + return 5; // attacks to the ground have low priority + } + return this->commandType->getTypePriority(); } // =============== set =============== void Command::setCommandType(const CommandType *commandType) { - this->commandType= commandType; + this->commandType = commandType; } -void Command::setPos(const Vec2i &pos){ - this->pos= pos; -} +void Command::setPos(const Vec2i &pos) { this->pos = pos; } -//void Command::setOriginalPos(const Vec2i &pos) { -// this->originalPos= pos; -//} +// void Command::setOriginalPos(const Vec2i &pos) { +// this->originalPos= pos; +// } -void Command::setPosToOriginalPos() { - this->pos= this->originalPos; -} +void Command::setPosToOriginalPos() { this->pos = this->originalPos; } -void Command::setUnit(Unit *unit){ - this->unitRef= unit; -} +void Command::setUnit(Unit *unit) { this->unitRef = unit; } std::string Command::toString(bool translatedValue) const { - //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__, __LINE__); - - std::string result = ""; - if(commandType != NULL) { - result = "commandType id = " + intToStr(commandType->getId()) + ", desc = " + commandType->toString(translatedValue); - } - else { - result = "commandType = NULL"; - } - //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__, __LINE__); + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",__FILE__,__FUNCTION__, __LINE__); - result += ", pos = " + pos.getString() + ", originalPos = " + originalPos.getString() + ", facing = " + intToStr(facing.asInt()); + std::string result = ""; + if (commandType != NULL) { + result = "commandType id = " + intToStr(commandType->getId()) + + ", desc = " + commandType->toString(translatedValue); + } else { + result = "commandType = NULL"; + } + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",__FILE__,__FUNCTION__, __LINE__); - //if(unitRef.getUnit() != NULL) { - if(unitRef.getUnitId() >= 0) { - //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__, __LINE__); + result += ", pos = " + pos.getString() + + ", originalPos = " + originalPos.getString() + + ", facing = " + intToStr(facing.asInt()); - result += ", unitRef.getUnit() id = " + intToStr(unitRef.getUnitId()); + // if(unitRef.getUnit() != NULL) { + if (unitRef.getUnitId() >= 0) { + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",__FILE__,__FUNCTION__, __LINE__); - // The code below causes a STACK OVERFLOW! - //if(unitRef.getUnit() != NULL) { - // result += ", unitRef.getUnit() = " + unitRef.getUnit()->toString(); - //} - } + result += ", unitRef.getUnit() id = " + intToStr(unitRef.getUnitId()); - //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__, __LINE__); + // The code below causes a STACK OVERFLOW! + // if(unitRef.getUnit() != NULL) { + // result += ", unitRef.getUnit() = " + unitRef.getUnit()->toString(); + //} + } - if(unitType != NULL) { - result += ", unitTypeId = " + intToStr(unitType->getId()); - result += ", unitTypeDesc = " + unitType->getReqDesc(translatedValue); - } + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",__FILE__,__FUNCTION__, __LINE__); - //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__, __LINE__); + if (unitType != NULL) { + result += ", unitTypeId = " + intToStr(unitType->getId()); + result += ", unitTypeDesc = " + unitType->getReqDesc(translatedValue); + } - result += ", stateType = " + intToStr(stateType) + ", stateValue = " + intToStr(stateValue); + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",__FILE__,__FUNCTION__, __LINE__); + result += ", stateType = " + intToStr(stateType) + + ", stateValue = " + intToStr(stateValue); - result += ", unitCommandGroupId = " + intToStr(unitCommandGroupId); + result += ", unitCommandGroupId = " + intToStr(unitCommandGroupId); - return result; + return result; } Checksum Command::getCRC() { - Checksum crcForCmd; - - crcForCmd.addInt(commandType->getId()); - crcForCmd.addInt(originalPos.x); - crcForCmd.addInt(originalPos.y); - crcForCmd.addInt(pos.x); - crcForCmd.addInt(pos.y); - crcForCmd.addInt(unitRef.getUnitId()); - crcForCmd.addInt(facing); - if(unitType != NULL) { - crcForCmd.addInt(unitType->getId()); - } - crcForCmd.addInt(stateType); - crcForCmd.addInt(stateValue); - crcForCmd.addInt(unitCommandGroupId); - - return crcForCmd; + Checksum crcForCmd; + + crcForCmd.addInt(commandType->getId()); + crcForCmd.addInt(originalPos.x); + crcForCmd.addInt(originalPos.y); + crcForCmd.addInt(pos.x); + crcForCmd.addInt(pos.y); + crcForCmd.addInt(unitRef.getUnitId()); + crcForCmd.addInt(facing); + if (unitType != NULL) { + crcForCmd.addInt(unitType->getId()); + } + crcForCmd.addInt(stateType); + crcForCmd.addInt(stateValue); + crcForCmd.addInt(unitCommandGroupId); + + return crcForCmd; } void Command::saveGame(XmlNode *rootNode, Faction *faction) { - std::map mapTagReplacements; - XmlNode *commandNode = rootNode->addChild("Command"); - -// const CommandType *commandType; - if(commandType != NULL) { - commandNode->addAttribute("commandType",intToStr(commandType->getId()), mapTagReplacements); - } -// Vec2i originalPos; - commandNode->addAttribute("originalPos",originalPos.getString(), mapTagReplacements); -// Vec2i pos; - commandNode->addAttribute("pos",pos.getString(), mapTagReplacements); -// UnitReference unitRef; //target unit, used to move and attack optionally - unitRef.saveGame(commandNode); -// CardinalDir facing; // facing, for build command - commandNode->addAttribute("facing",intToStr(facing), mapTagReplacements); -// const UnitType *unitType; //used for build - if(unitType != NULL) { - commandNode->addAttribute("unitTypeId",intToStr(unitType->getId()), mapTagReplacements); - commandNode->addAttribute("unitTypeFactionIndex",intToStr(faction->getIndex()), mapTagReplacements); - } -// CommandStateType stateType; - commandNode->addAttribute("stateType",intToStr(stateType), mapTagReplacements); -// int stateValue; - commandNode->addAttribute("stateValue",intToStr(stateValue), mapTagReplacements); -// int unitCommandGroupId; - commandNode->addAttribute("unitCommandGroupId",intToStr(unitCommandGroupId), mapTagReplacements); + std::map mapTagReplacements; + XmlNode *commandNode = rootNode->addChild("Command"); + + // const CommandType *commandType; + if (commandType != NULL) { + commandNode->addAttribute("commandType", intToStr(commandType->getId()), + mapTagReplacements); + } + // Vec2i originalPos; + commandNode->addAttribute("originalPos", originalPos.getString(), + mapTagReplacements); + // Vec2i pos; + commandNode->addAttribute("pos", pos.getString(), mapTagReplacements); + // UnitReference unitRef; //target unit, used to move and attack + // optionally + unitRef.saveGame(commandNode); + // CardinalDir facing; // facing, for build command + commandNode->addAttribute("facing", intToStr(facing), mapTagReplacements); + // const UnitType *unitType; //used for build + if (unitType != NULL) { + commandNode->addAttribute("unitTypeId", intToStr(unitType->getId()), + mapTagReplacements); + commandNode->addAttribute("unitTypeFactionIndex", + intToStr(faction->getIndex()), + mapTagReplacements); + } + // CommandStateType stateType; + commandNode->addAttribute("stateType", intToStr(stateType), + mapTagReplacements); + // int stateValue; + commandNode->addAttribute("stateValue", intToStr(stateValue), + mapTagReplacements); + // int unitCommandGroupId; + commandNode->addAttribute("unitCommandGroupId", intToStr(unitCommandGroupId), + mapTagReplacements); } -Command * Command::loadGame(const XmlNode *rootNode,const UnitType *ut,World *world) { - Command *result = new Command(); - const XmlNode *commandNode = rootNode; - - //description = commandNode->getAttribute("description")->getValue(); - - // const CommandType *commandType; - if(commandNode->hasAttribute("commandType") == true) { - int cmdTypeId = commandNode->getAttribute("commandType")->getIntValue(); - result->commandType = ut->findCommandTypeById(cmdTypeId); - } - // Vec2i originalPos; - result->originalPos = Vec2i::strToVec2(commandNode->getAttribute("originalPos")->getValue()); - // Vec2i pos; - result->pos = Vec2i::strToVec2(commandNode->getAttribute("pos")->getValue()); - // UnitReference unitRef; //target unit, used to move and attack optionally - result->unitRef.loadGame(commandNode,world); - // CardinalDir facing; // facing, for build command - result->facing = static_cast(commandNode->getAttribute("facing")->getIntValue()); - // const UnitType *unitType; //used for build - if(commandNode->hasAttribute("unitTypeId") == true) { - //result->unitType = ut; - int unitTypeId = commandNode->getAttribute("unitTypeId")->getIntValue(); - int unitTypeFactionIndex = commandNode->getAttribute("unitTypeFactionIndex")->getIntValue(); - Faction *faction = world->getFaction(unitTypeFactionIndex); - result->unitType = world->findUnitTypeById(faction->getType(),unitTypeId); - } - // CommandStateType stateType; - result->stateType = static_cast(commandNode->getAttribute("stateType")->getIntValue()); - // int stateValue; - result->stateValue = commandNode->getAttribute("stateValue")->getIntValue(); - // int unitCommandGroupId; - result->unitCommandGroupId = commandNode->getAttribute("unitCommandGroupId")->getIntValue(); - - return result; +Command *Command::loadGame(const XmlNode *rootNode, const UnitType *ut, + World *world) { + Command *result = new Command(); + const XmlNode *commandNode = rootNode; + + // description = commandNode->getAttribute("description")->getValue(); + + // const CommandType *commandType; + if (commandNode->hasAttribute("commandType") == true) { + int cmdTypeId = commandNode->getAttribute("commandType")->getIntValue(); + result->commandType = ut->findCommandTypeById(cmdTypeId); + } + // Vec2i originalPos; + result->originalPos = + Vec2i::strToVec2(commandNode->getAttribute("originalPos")->getValue()); + // Vec2i pos; + result->pos = Vec2i::strToVec2(commandNode->getAttribute("pos")->getValue()); + // UnitReference unitRef; //target unit, used to move and attack + // optionally + result->unitRef.loadGame(commandNode, world); + // CardinalDir facing; // facing, for build command + result->facing = static_cast( + commandNode->getAttribute("facing")->getIntValue()); + // const UnitType *unitType; //used for build + if (commandNode->hasAttribute("unitTypeId") == true) { + // result->unitType = ut; + int unitTypeId = commandNode->getAttribute("unitTypeId")->getIntValue(); + int unitTypeFactionIndex = + commandNode->getAttribute("unitTypeFactionIndex")->getIntValue(); + Faction *faction = world->getFaction(unitTypeFactionIndex); + result->unitType = world->findUnitTypeById(faction->getType(), unitTypeId); + } + // CommandStateType stateType; + result->stateType = static_cast( + commandNode->getAttribute("stateType")->getIntValue()); + // int stateValue; + result->stateValue = commandNode->getAttribute("stateValue")->getIntValue(); + // int unitCommandGroupId; + result->unitCommandGroupId = + commandNode->getAttribute("unitCommandGroupId")->getIntValue(); + + return result; } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/type_instances/command.h b/source/glest_game/type_instances/command.h index 8c04fea40..87ad9f071 100644 --- a/source/glest_game/type_instances/command.h +++ b/source/glest_game/type_instances/command.h @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,27 +13,24 @@ #define _GLEST_GAME_COMMAND_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include -#include "unit.h" -#include "vec.h" #include "game_constants.h" #include "leak_dumper.h" +#include "unit.h" +#include "vec.h" +#include -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { using Shared::Graphics::Vec2i; class CommandType; -enum CommandStateType { - cst_None, - cst_linkedUnit, - cst_EmergencyReturnResource -}; +enum CommandStateType { cst_None, cst_linkedUnit, cst_EmergencyReturnResource }; // ===================================================== // class Command @@ -43,62 +40,67 @@ enum CommandStateType { class Command { private: - const CommandType *commandType; - Vec2i originalPos; - Vec2i pos; - UnitReference unitRef; //target unit, used to move and attack optionally - CardinalDir facing; // facing, for build command - const UnitType *unitType; //used for build + const CommandType *commandType; + Vec2i originalPos; + Vec2i pos; + UnitReference unitRef; // target unit, used to move and attack optionally + CardinalDir facing; // facing, for build command + const UnitType *unitType; // used for build + + CommandStateType stateType; + int stateValue; - CommandStateType stateType; - int stateValue; + int unitCommandGroupId; - int unitCommandGroupId; + Command(); - Command(); public: - //constructor - Command(const CommandType *ct, const Vec2i &pos=Vec2i(0)); - Command(const CommandType *ct, Unit *unit); - Command(const CommandType *ct, const Vec2i &pos, const UnitType *unitType, CardinalDir facing); - - virtual ~Command() {} - //get - inline const CommandType *getCommandType() const {return commandType;} - inline Vec2i getPos() const {return pos;} - inline Vec2i getOriginalPos() const {return originalPos;} - inline Unit* getUnit() const {return unitRef.getUnit();} - inline const UnitType* getUnitType() const {return unitType;} - inline CardinalDir getFacing() const {return facing;} - - //Priority: commands of higher priority will cancel commands of lower priority - virtual int getPriority(); - - //set - void setCommandType(const CommandType *commandType); - void setPos(const Vec2i &pos); - //void setOriginalPos(const Vec2i &pos); - void setPosToOriginalPos(); - - void setUnit(Unit *unit); - - inline void setStateType(CommandStateType value) { stateType = value; } - inline CommandStateType getStateType() const { return stateType; } - - inline void setStateValue(int value) { stateValue = value; } - inline int getStateValue() const { return stateValue; } - - inline void setUnitCommandGroupId(int value) { unitCommandGroupId = value; } - inline int getUnitCommandGroupId() const { return unitCommandGroupId; } - - std::string toString(bool translatedValue) const; - - void saveGame(XmlNode *rootNode, Faction *faction); - static Command * loadGame(const XmlNode *rootNode,const UnitType *ut,World *world); - - Checksum getCRC(); -}; - -}}//end namespace + // constructor + Command(const CommandType *ct, const Vec2i &pos = Vec2i(0)); + Command(const CommandType *ct, Unit *unit); + Command(const CommandType *ct, const Vec2i &pos, const UnitType *unitType, + CardinalDir facing); + + virtual ~Command() {} + // get + inline const CommandType *getCommandType() const { return commandType; } + inline Vec2i getPos() const { return pos; } + inline Vec2i getOriginalPos() const { return originalPos; } + inline Unit *getUnit() const { return unitRef.getUnit(); } + inline const UnitType *getUnitType() const { return unitType; } + inline CardinalDir getFacing() const { return facing; } + + // Priority: commands of higher priority will cancel commands of lower + // priority + virtual int getPriority(); + + // set + void setCommandType(const CommandType *commandType); + void setPos(const Vec2i &pos); + // void setOriginalPos(const Vec2i &pos); + void setPosToOriginalPos(); + + void setUnit(Unit *unit); + + inline void setStateType(CommandStateType value) { stateType = value; } + inline CommandStateType getStateType() const { return stateType; } + + inline void setStateValue(int value) { stateValue = value; } + inline int getStateValue() const { return stateValue; } + + inline void setUnitCommandGroupId(int value) { unitCommandGroupId = value; } + inline int getUnitCommandGroupId() const { return unitCommandGroupId; } + + std::string toString(bool translatedValue) const; + + void saveGame(XmlNode *rootNode, Faction *faction); + static Command *loadGame(const XmlNode *rootNode, const UnitType *ut, + World *world); + + Checksum getCRC(); +}; + +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/type_instances/faction.cpp b/source/glest_game/type_instances/faction.cpp index f934e49c8..128810ae7 100644 --- a/source/glest_game/type_instances/faction.cpp +++ b/source/glest_game/type_instances/faction.cpp @@ -14,198 +14,214 @@ #include #include +#include "config.h" +#include "game.h" +#include "leak_dumper.h" +#include "randomgen.h" +#include "renderer.h" #include "resource_type.h" -#include "unit.h" -#include "util.h" #include "sound_renderer.h" -#include "renderer.h" #include "tech_tree.h" -#include "game.h" -#include "config.h" -#include "randomgen.h" -#include "leak_dumper.h" +#include "unit.h" +#include "util.h" using namespace Shared::Util; using Shared::Util::RandomGen; -namespace Glest { namespace Game { +namespace Glest { +namespace Game { bool CommandGroupUnitSorterId::operator()(const int l, const int r) { - const Unit *lUnit = faction->findUnit(l); - const Unit *rUnit = faction->findUnit(r); - - if(!lUnit) { - printf("Error lUnit == NULL for id = %d factionIndex = %d\n",l,faction->getIndex()); + const Unit *lUnit = faction->findUnit(l); + const Unit *rUnit = faction->findUnit(r); - for(unsigned int i = 0; i < (unsigned int)faction->getUnitCount(); ++i) { - printf("%u / %d id = %d [%s]\n",i,faction->getUnitCount(),faction->getUnit(i)->getId(),faction->getUnit(i)->getType()->getName(false).c_str()); - } - } - if(!rUnit) { - printf("Error rUnit == NULL for id = %d factionIndex = %d\n",r,faction->getIndex()); + if (!lUnit) { + printf("Error lUnit == NULL for id = %d factionIndex = %d\n", l, + faction->getIndex()); - for(unsigned int i = 0; i < (unsigned int)faction->getUnitCount(); ++i) { - printf("%u / %d id = %d [%s]\n",i,faction->getUnitCount(),faction->getUnit(i)->getId(),faction->getUnit(i)->getType()->getName(false).c_str()); - } - } + for (unsigned int i = 0; i < (unsigned int)faction->getUnitCount(); ++i) { + printf("%u / %d id = %d [%s]\n", i, faction->getUnitCount(), + faction->getUnit(i)->getId(), + faction->getUnit(i)->getType()->getName(false).c_str()); + } + } + if (!rUnit) { + printf("Error rUnit == NULL for id = %d factionIndex = %d\n", r, + faction->getIndex()); + + for (unsigned int i = 0; i < (unsigned int)faction->getUnitCount(); ++i) { + printf("%u / %d id = %d [%s]\n", i, faction->getUnitCount(), + faction->getUnit(i)->getId(), + faction->getUnit(i)->getType()->getName(false).c_str()); + } + } - CommandGroupUnitSorter sorter; - return sorter.compare(lUnit, rUnit); + CommandGroupUnitSorter sorter; + return sorter.compare(lUnit, rUnit); } bool CommandGroupUnitSorter::operator()(const Unit *l, const Unit *r) { - return compare(l, r); + return compare(l, r); } bool CommandGroupUnitSorter::compare(const Unit *l, const Unit *r) { - //printf("l [%p] r [%p] <>",l,r); - - if(!l) { - printf("Error l == NULL\n"); - } - if(!r) { - printf("Error r == NULL\n"); - } - - assert(l && r); - - if(l == NULL || r == NULL) - printf("Unit l [%s - %d] r [%s - %d]\n", - (l != NULL ? l->getType()->getName(false).c_str() : "null"), - (l != NULL ? l->getId() : -1), - (r != NULL ? r->getType()->getName(false).c_str() : "null"), - (r != NULL ? r->getId() : -1)); - - - bool result = false; - // If comparer is null or dead - if(r == NULL || r->isAlive() == false) { - // if source is null or dead also - if((l == NULL || l->isAlive() == false)) { - return false; - } - return true; - } - else if((l == NULL || l->isAlive() == false)) { - return false; - } - -// const Command *command= l->getCurrrentCommandThreadSafe(); -// const Command *commandPeer = r->getCurrrentCommandThreadSafe(); - const Command *command= l->getCurrCommand(); - const Command *commandPeer = r->getCurrCommand(); - - //Command *command= this->unit->getCurrCommand(); - - // Are we moving or attacking - if( command != NULL && command->getCommandType() != NULL && - (command->getCommandType()->getClass() == ccMove || - command->getCommandType()->getClass() == ccAttack) && - command->getUnitCommandGroupId() > 0) { - int curCommandGroupId = command->getUnitCommandGroupId(); - - //Command *commandPeer = j.unit->getCurrrentCommandThreadSafe(); - //Command *commandPeer = j.unit->getCurrCommand(); - - // is comparer a valid command - if(commandPeer == NULL || commandPeer->getCommandType() == NULL) { - result = true; - } - // is comparer command the same type? - else if(commandPeer->getCommandType()->getClass() != - command->getCommandType()->getClass()) { - result = true; - } - // is comparer command groupid invalid? - else if(commandPeer->getUnitCommandGroupId() < 0) { - result = true; - } - // If comparer command group id is less than current group id - else if(curCommandGroupId != commandPeer->getUnitCommandGroupId()) { - result = curCommandGroupId < commandPeer->getUnitCommandGroupId(); - } - else { - float unitDist = l->getCenteredPos().dist(command->getPos()); - float unitDistPeer = r->getCenteredPos().dist(commandPeer->getPos()); - - // Closest unit in commandgroup - result = (unitDist < unitDistPeer); - } - } - else if(command == NULL && commandPeer != NULL) { - result = false; - } -// else if(command == NULL && j.unit->getCurrrentCommandThreadSafe() == NULL) { -// return this->unit->getId() < j.unit->getId(); -// } - else { - //Command *commandPeer = j.unit->getCurrrentCommandThreadSafe(); - //if( commandPeer != NULL && commandPeer->getCommandType() != NULL && - // (commandPeer->getCommandType()->getClass() != ccMove && - // commandPeer->getCommandType()->getClass() != ccAttack)) { - result = (l->getId() < r->getId()); - //} - //else { - // result = (l->getId() < r->getId()); - //} - } - - //printf("Sorting, unit [%d - %s] cmd [%s] | unit2 [%d - %s] cmd [%s] result = %d\n",this->unit->getId(),this->unit->getFullName().c_str(),(this->unit->getCurrCommand() == NULL ? "NULL" : this->unit->getCurrCommand()->toString().c_str()),j.unit->getId(),j.unit->getFullName().c_str(),(j.unit->getCurrCommand() == NULL ? "NULL" : j.unit->getCurrCommand()->toString().c_str()),result); - - return result; + // printf("l [%p] r [%p] <>",l,r); + + if (!l) { + printf("Error l == NULL\n"); + } + if (!r) { + printf("Error r == NULL\n"); + } + + assert(l && r); + + if (l == NULL || r == NULL) + printf("Unit l [%s - %d] r [%s - %d]\n", + (l != NULL ? l->getType()->getName(false).c_str() : "null"), + (l != NULL ? l->getId() : -1), + (r != NULL ? r->getType()->getName(false).c_str() : "null"), + (r != NULL ? r->getId() : -1)); + + bool result = false; + // If comparer is null or dead + if (r == NULL || r->isAlive() == false) { + // if source is null or dead also + if ((l == NULL || l->isAlive() == false)) { + return false; + } + return true; + } else if ((l == NULL || l->isAlive() == false)) { + return false; + } + + // const Command *command= l->getCurrrentCommandThreadSafe(); + // const Command *commandPeer = r->getCurrrentCommandThreadSafe(); + const Command *command = l->getCurrCommand(); + const Command *commandPeer = r->getCurrCommand(); + + // Command *command= this->unit->getCurrCommand(); + + // Are we moving or attacking + if (command != NULL && command->getCommandType() != NULL && + (command->getCommandType()->getClass() == ccMove || + command->getCommandType()->getClass() == ccAttack) && + command->getUnitCommandGroupId() > 0) { + int curCommandGroupId = command->getUnitCommandGroupId(); + + // Command *commandPeer = j.unit->getCurrrentCommandThreadSafe(); + // Command *commandPeer = j.unit->getCurrCommand(); + + // is comparer a valid command + if (commandPeer == NULL || commandPeer->getCommandType() == NULL) { + result = true; + } + // is comparer command the same type? + else if (commandPeer->getCommandType()->getClass() != + command->getCommandType()->getClass()) { + result = true; + } + // is comparer command groupid invalid? + else if (commandPeer->getUnitCommandGroupId() < 0) { + result = true; + } + // If comparer command group id is less than current group id + else if (curCommandGroupId != commandPeer->getUnitCommandGroupId()) { + result = curCommandGroupId < commandPeer->getUnitCommandGroupId(); + } else { + float unitDist = l->getCenteredPos().dist(command->getPos()); + float unitDistPeer = r->getCenteredPos().dist(commandPeer->getPos()); + + // Closest unit in commandgroup + result = (unitDist < unitDistPeer); + } + } else if (command == NULL && commandPeer != NULL) { + result = false; + } + // else if(command == NULL && j.unit->getCurrrentCommandThreadSafe() == + // NULL) { return this->unit->getId() < j.unit->getId(); + // } + else { + // Command *commandPeer = j.unit->getCurrrentCommandThreadSafe(); + // if( commandPeer != NULL && commandPeer->getCommandType() != NULL && + // (commandPeer->getCommandType()->getClass() != ccMove && + // commandPeer->getCommandType()->getClass() != ccAttack)) { + result = (l->getId() < r->getId()); + //} + // else { + // result = (l->getId() < r->getId()); + //} + } + + // printf("Sorting, unit [%d - %s] cmd [%s] | unit2 [%d - %s] cmd [%s] result + // = + // %d\n",this->unit->getId(),this->unit->getFullName().c_str(),(this->unit->getCurrCommand() + // == NULL ? "NULL" : + // this->unit->getCurrCommand()->toString().c_str()),j.unit->getId(),j.unit->getFullName().c_str(),(j.unit->getCurrCommand() + // == NULL ? "NULL" : j.unit->getCurrCommand()->toString().c_str()),result); + + return result; } void Faction::sortUnitsByCommandGroups() { - MutexSafeWrapper safeMutex(unitsMutex,string(__FILE__) + "_" + intToStr(__LINE__)); - //printf("====== sortUnitsByCommandGroups for faction # %d [%s] unitCount = %d\n",this->getIndex(),this->getType()->getName().c_str(),units.size()); - //for(unsigned int i = 0; i < units.size(); ++i) { - // printf("%d / %d [%p] <>",i,units.size(),&units[i]); -// // printf("i = %d [%p]\n",i,&units[i]); -// if(Unit::isUnitDeleted(units[i]) == true) { -// printf("i = %d [%p]\n",i,&units[i]); -// throw megaglest_runtime_error("unit already deleted!"); -// } - //} - //printf("\nSorting\n"); - - //std::sort(units.begin(),units.end(),CommandGroupUnitSorter()); - - //printf("====== Done sorting for faction # %d [%s] unitCount = %d\n",this->getIndex(),this->getType()->getName().c_str(),units.size()); - - //unsigned int originalUnitSize = (unsigned int)units.size(); - - std::vector unitIds; - for(unsigned int i = 0; i < units.size(); ++i) { - int unitId = units[i]->getId(); - if(this->findUnit(unitId) == NULL) { - printf("#1 Error unitId not found for id = %d [%s] factionIndex = %d\n",unitId,units[i]->getType()->getName(false).c_str(),this->getIndex()); - - for(unsigned int j = 0; j < units.size(); ++j) { - printf("%u / %d id = %d [%s]\n",j,(int)units.size(),units[j]->getId(),units[j]->getType()->getName(false).c_str()); - } - } - unitIds.push_back(unitId); - } - CommandGroupUnitSorterId sorter; - sorter.faction = this; - std::stable_sort(unitIds.begin(),unitIds.end(),sorter); - - units.clear(); - for(unsigned int i = 0; i < unitIds.size(); ++i) { - - int unitId = unitIds[i]; - if(this->findUnit(unitId) == NULL) { - printf("#2 Error unitId not found for id = %d factionIndex = %d\n",unitId,this->getIndex()); - - for(unsigned int j = 0; j < units.size(); ++j) { - printf("%u / %d id = %d [%s]\n",j,(int)units.size(),units[j]->getId(),units[j]->getType()->getName(false).c_str()); - } - } + MutexSafeWrapper safeMutex(unitsMutex, + string(__FILE__) + "_" + intToStr(__LINE__)); + // printf("====== sortUnitsByCommandGroups for faction # %d [%s] unitCount = + // %d\n",this->getIndex(),this->getType()->getName().c_str(),units.size()); + // for(unsigned int i = 0; i < units.size(); ++i) { + // printf("%d / %d [%p] <>",i,units.size(),&units[i]); + // // printf("i = %d [%p]\n",i,&units[i]); + // if(Unit::isUnitDeleted(units[i]) == true) { + // printf("i = %d [%p]\n",i,&units[i]); + // throw megaglest_runtime_error("unit already deleted!"); + // } + //} + // printf("\nSorting\n"); + + // std::sort(units.begin(),units.end(),CommandGroupUnitSorter()); + + // printf("====== Done sorting for faction # %d [%s] unitCount = + // %d\n",this->getIndex(),this->getType()->getName().c_str(),units.size()); + + // unsigned int originalUnitSize = (unsigned int)units.size(); + + std::vector unitIds; + for (unsigned int i = 0; i < units.size(); ++i) { + int unitId = units[i]->getId(); + if (this->findUnit(unitId) == NULL) { + printf("#1 Error unitId not found for id = %d [%s] factionIndex = %d\n", + unitId, units[i]->getType()->getName(false).c_str(), + this->getIndex()); + + for (unsigned int j = 0; j < units.size(); ++j) { + printf("%u / %d id = %d [%s]\n", j, (int)units.size(), + units[j]->getId(), units[j]->getType()->getName(false).c_str()); + } + } + unitIds.push_back(unitId); + } + CommandGroupUnitSorterId sorter; + sorter.faction = this; + std::stable_sort(unitIds.begin(), unitIds.end(), sorter); + + units.clear(); + for (unsigned int i = 0; i < unitIds.size(); ++i) { + + int unitId = unitIds[i]; + if (this->findUnit(unitId) == NULL) { + printf("#2 Error unitId not found for id = %d factionIndex = %d\n", + unitId, this->getIndex()); + + for (unsigned int j = 0; j < units.size(); ++j) { + printf("%u / %d id = %d [%s]\n", j, (int)units.size(), + units[j]->getId(), units[j]->getType()->getName(false).c_str()); + } + } - units.push_back(this->findUnit(unitId)); - } + units.push_back(this->findUnit(unitId)); + } - //assert(originalUnitSize == units.size()); + // assert(originalUnitSize == units.size()); } // ===================================================== @@ -213,1685 +229,1962 @@ void Faction::sortUnitsByCommandGroups() { // ===================================================== FactionThread::FactionThread(Faction *faction) : BaseThread() { - this->triggerIdMutex = new Mutex(CODE_AT_LINE); - this->faction = faction; - this->masterController = NULL; - uniqueID = "FactionThread"; + this->triggerIdMutex = new Mutex(CODE_AT_LINE); + this->faction = faction; + this->masterController = NULL; + uniqueID = "FactionThread"; } FactionThread::~FactionThread() { - this->faction = NULL; - this->masterController = NULL; - delete this->triggerIdMutex; - this->triggerIdMutex = NULL; + this->faction = NULL; + this->masterController = NULL; + delete this->triggerIdMutex; + this->triggerIdMutex = NULL; } void FactionThread::setQuitStatus(bool value) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d value = %d\n",__FILE__,__FUNCTION__,__LINE__,value); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s] Line: %d value = %d\n", __FILE__, + __FUNCTION__, __LINE__, value); - BaseThread::setQuitStatus(value); - if(value == true) { - signalPathfinder(-1); - } + BaseThread::setQuitStatus(value); + if (value == true) { + signalPathfinder(-1); + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] Line: %d\n", + __FILE__, __FUNCTION__, __LINE__); } void FactionThread::signalPathfinder(int frameIndex) { - if(frameIndex >= 0) { - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(triggerIdMutex,mutexOwnerId); - this->frameIndex.first = frameIndex; - this->frameIndex.second = false; + if (frameIndex >= 0) { + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(triggerIdMutex, mutexOwnerId); + this->frameIndex.first = frameIndex; + this->frameIndex.second = false; - safeMutex.ReleaseLock(); - } - semTaskSignalled.signal(); + safeMutex.ReleaseLock(); + } + semTaskSignalled.signal(); } void FactionThread::setTaskCompleted(int frameIndex) { - if(frameIndex >= 0) { - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(triggerIdMutex,mutexOwnerId); - if(this->frameIndex.first == frameIndex) { - this->frameIndex.second = true; - } - safeMutex.ReleaseLock(); - } + if (frameIndex >= 0) { + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(triggerIdMutex, mutexOwnerId); + if (this->frameIndex.first == frameIndex) { + this->frameIndex.second = true; + } + safeMutex.ReleaseLock(); + } } bool FactionThread::canShutdown(bool deleteSelfIfShutdownDelayed) { - bool ret = (getExecutingTask() == false); - if(ret == false && deleteSelfIfShutdownDelayed == true) { - setDeleteSelfOnExecutionDone(deleteSelfIfShutdownDelayed); - deleteSelfIfRequired(); - signalQuit(); - } + bool ret = (getExecutingTask() == false); + if (ret == false && deleteSelfIfShutdownDelayed == true) { + setDeleteSelfOnExecutionDone(deleteSelfIfShutdownDelayed); + deleteSelfIfRequired(); + signalQuit(); + } - return ret; + return ret; } bool FactionThread::isSignalPathfinderCompleted(int frameIndex) { - if(getRunningStatus() == false) { - return true; - } - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(triggerIdMutex,mutexOwnerId); - //bool result = (event != NULL ? event->eventCompleted : true); - bool result = (this->frameIndex.first == frameIndex && this->frameIndex.second == true); + if (getRunningStatus() == false) { + return true; + } + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(triggerIdMutex, mutexOwnerId); + // bool result = (event != NULL ? event->eventCompleted : true); + bool result = + (this->frameIndex.first == frameIndex && this->frameIndex.second == true); - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] worker thread this = %p, this->frameIndex.first = %d, this->frameIndex.second = %d\n",__FILE__,__FUNCTION__,__LINE__,this,this->frameIndex.first,this->frameIndex.second); + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] worker + // thread this = %p, this->frameIndex.first = %d, this->frameIndex.second = + // %d\n",__FILE__,__FUNCTION__,__LINE__,this,this->frameIndex.first,this->frameIndex.second); - safeMutex.ReleaseLock(); - return result; + safeMutex.ReleaseLock(); + return result; } void FactionThread::execute() { - string codeLocation = "1"; - RunningStatusSafeWrapper runningStatus(this); - try { - //setRunningStatus(true); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] ****************** STARTING worker thread this = %p\n",__FILE__,__FUNCTION__,__LINE__,this); - - bool minorDebugPerformance = false; - Chrono chrono; - - codeLocation = "2"; - //unsigned int idx = 0; - for(;this->faction != NULL;) { - if(getQuitStatus() == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - break; - } - - semTaskSignalled.waitTillSignalled(); - - codeLocation = "3"; - //printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - static string masterSlaveOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MasterSlaveThreadControllerSafeWrapper safeMasterController(masterController,20000,masterSlaveOwnerId); - //printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(getQuitStatus() == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - break; - } - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(triggerIdMutex,mutexOwnerId); - bool executeTask = (this->frameIndex.first >= 0); - int currentTriggeredFrameIndex = this->frameIndex.first; - - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] frameIndex = %d this = %p executeTask = %d\n",__FILE__,__FUNCTION__,__LINE__,frameIndex.first, this, executeTask); - - safeMutex.ReleaseLock(); - - codeLocation = "5"; - //printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(executeTask == true) { - codeLocation = "6"; - ExecutingTaskSafeWrapper safeExecutingTaskMutex(this); - - if(this->faction == NULL) { - throw megaglest_runtime_error("this->faction == NULL"); - } - World *world = this->faction->getWorld(); - if(world == NULL) { - throw megaglest_runtime_error("world == NULL"); - } - - codeLocation = "7"; - //Config &config= Config::getInstance(); - //bool sortedUnitsAllowed = config.getBool("AllowGroupedUnitCommands","true"); - //bool sortedUnitsAllowed = false; - //if(sortedUnitsAllowed == true) { - - /// TODO: Why does this cause an OOS? - //this->faction->sortUnitsByCommandGroups(); - - //} - - codeLocation = "8"; - static string mutexOwnerId2 = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(faction->getUnitMutex(),mutexOwnerId2); - - //if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); - if(minorDebugPerformance) chrono.start(); - - //printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - codeLocation = "9"; - int unitCount = this->faction->getUnitCount(); - for(int j = 0; j < unitCount; ++j) { - codeLocation = "10"; - Unit *unit = this->faction->getUnit(j); - if(unit == NULL) { - throw megaglest_runtime_error("unit == NULL"); - } - - codeLocation = "11"; - int64 elapsed1 = 0; - if(minorDebugPerformance) elapsed1 = chrono.getMillis(); - - bool update = unit->needToUpdate(); - - codeLocation = "12"; - if(minorDebugPerformance && (chrono.getMillis() - elapsed1) >= 1) printf("Faction [%d - %s] #1-unit threaded updates on frame: %d for [%d] unit # %d, unitCount = %d, took [%lld] msecs\n",faction->getStartLocationIndex(),faction->getType()->getName(false).c_str(),currentTriggeredFrameIndex,faction->getUnitPathfindingListCount(),j,unitCount,(long long int)chrono.getMillis() - elapsed1); - - //update = true; - if(update == true) - { - codeLocation = "13"; - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true) { - int64 updateProgressValue = unit->getUpdateProgress(); - int64 speed = unit->getCurrSkill()->getTotalSpeed(unit->getTotalUpgrade()); - int64 df = unit->getDiagonalFactor(); - int64 hf = unit->getHeightFactor(); - bool changedActiveCommand = unit->isChangedActiveCommand(); - - char szBuf[8096]=""; - snprintf(szBuf,8096,"unit->needToUpdate() returned: %d updateProgressValue: %lld speed: %lld changedActiveCommand: %d df: %lld hf: %lld",update,(long long int)updateProgressValue,(long long int)speed,changedActiveCommand,(long long int)df,(long long int)hf); - unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); - } - - int64 elapsed2 = 0; - if(minorDebugPerformance) elapsed2 = chrono.getMillis(); - - if(world->getUnitUpdater() == NULL) { - throw megaglest_runtime_error("world->getUnitUpdater() == NULL"); - } - - world->getUnitUpdater()->updateUnitCommand(unit,currentTriggeredFrameIndex); - - codeLocation = "15"; - if(minorDebugPerformance && (chrono.getMillis() - elapsed2) >= 1) printf("Faction [%d - %s] #2-unit threaded updates on frame: %d for [%d] unit # %d, unitCount = %d, took [%lld] msecs\n",faction->getStartLocationIndex(),faction->getType()->getName(false).c_str(),currentTriggeredFrameIndex,faction->getUnitPathfindingListCount(),j,unitCount,(long long int)chrono.getMillis() - elapsed2); - } - else { - codeLocation = "16"; - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true) { - int64 updateProgressValue = unit->getUpdateProgress(); - int64 speed = unit->getCurrSkill()->getTotalSpeed(unit->getTotalUpgrade()); - int64 df = unit->getDiagonalFactor(); - int64 hf = unit->getHeightFactor(); - bool changedActiveCommand = unit->isChangedActiveCommand(); - - char szBuf[8096]=""; - snprintf(szBuf,8096,"unit->needToUpdate() returned: %d updateProgressValue: %lld speed: %lld changedActiveCommand: %d df: %lld hf: %lld",update,(long long int)updateProgressValue,(long long int)speed,changedActiveCommand,(long long int)df,(long long int)hf); - unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); - } - } - } - - codeLocation = "17"; - if(minorDebugPerformance && chrono.getMillis() >= 1) printf("Faction [%d - %s] threaded updates on frame: %d for [%d] units took [%lld] msecs\n",faction->getStartLocationIndex(),faction->getType()->getName(false).c_str(),currentTriggeredFrameIndex,faction->getUnitPathfindingListCount(),(long long int)chrono.getMillis()); - - //printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - safeMutex.ReleaseLock(); - - codeLocation = "18"; - //printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - setTaskCompleted(currentTriggeredFrameIndex); - - //printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + string codeLocation = "1"; + RunningStatusSafeWrapper runningStatus(this); + try { + // setRunningStatus(true); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] ****************** STARTING worker thread " + "this = %p\n", + __FILE__, __FUNCTION__, __LINE__, this); + + bool minorDebugPerformance = false; + Chrono chrono; + + codeLocation = "2"; + // unsigned int idx = 0; + for (; this->faction != NULL;) { + if (getQuitStatus() == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + break; + } + + semTaskSignalled.waitTillSignalled(); + + codeLocation = "3"; + // printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + static string masterSlaveOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MasterSlaveThreadControllerSafeWrapper safeMasterController( + masterController, 20000, masterSlaveOwnerId); + // printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + + if (getQuitStatus() == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + break; + } + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(triggerIdMutex, mutexOwnerId); + bool executeTask = (this->frameIndex.first >= 0); + int currentTriggeredFrameIndex = this->frameIndex.first; + + // if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] + // frameIndex = %d this = %p executeTask = + // %d\n",__FILE__,__FUNCTION__,__LINE__,frameIndex.first, this, + // executeTask); + + safeMutex.ReleaseLock(); + + codeLocation = "5"; + // printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + + if (executeTask == true) { + codeLocation = "6"; + ExecutingTaskSafeWrapper safeExecutingTaskMutex(this); + + if (this->faction == NULL) { + throw megaglest_runtime_error("this->faction == NULL"); + } + World *world = this->faction->getWorld(); + if (world == NULL) { + throw megaglest_runtime_error("world == NULL"); + } + + codeLocation = "7"; + // Config &config= Config::getInstance(); + // bool sortedUnitsAllowed = + // config.getBool("AllowGroupedUnitCommands","true"); bool + // sortedUnitsAllowed = false; if(sortedUnitsAllowed == true) { + + /// TODO: Why does this cause an OOS? + // this->faction->sortUnitsByCommandGroups(); + + //} + + codeLocation = "8"; + static string mutexOwnerId2 = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(faction->getUnitMutex(), mutexOwnerId2); + + // if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) + // chrono.start(); + if (minorDebugPerformance) + chrono.start(); + + // printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + + codeLocation = "9"; + int unitCount = this->faction->getUnitCount(); + for (int j = 0; j < unitCount; ++j) { + codeLocation = "10"; + Unit *unit = this->faction->getUnit(j); + if (unit == NULL) { + throw megaglest_runtime_error("unit == NULL"); + } + + codeLocation = "11"; + int64 elapsed1 = 0; + if (minorDebugPerformance) + elapsed1 = chrono.getMillis(); + + bool update = unit->needToUpdate(); + + codeLocation = "12"; + if (minorDebugPerformance && (chrono.getMillis() - elapsed1) >= 1) + printf("Faction [%d - %s] #1-unit threaded updates on frame: %d " + "for [%d] unit # %d, unitCount = %d, took [%lld] msecs\n", + faction->getStartLocationIndex(), + faction->getType()->getName(false).c_str(), + currentTriggeredFrameIndex, + faction->getUnitPathfindingListCount(), j, unitCount, + (long long int)chrono.getMillis() - elapsed1); + + // update = true; + if (update == true) { + codeLocation = "13"; + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true) { + int64 updateProgressValue = unit->getUpdateProgress(); + int64 speed = + unit->getCurrSkill()->getTotalSpeed(unit->getTotalUpgrade()); + int64 df = unit->getDiagonalFactor(); + int64 hf = unit->getHeightFactor(); + bool changedActiveCommand = unit->isChangedActiveCommand(); + + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "unit->needToUpdate() returned: %d updateProgressValue: %lld " + "speed: %lld changedActiveCommand: %d df: %lld hf: %lld", + update, (long long int)updateProgressValue, + (long long int)speed, changedActiveCommand, (long long int)df, + (long long int)hf); + unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf); } - //printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + int64 elapsed2 = 0; + if (minorDebugPerformance) + elapsed2 = chrono.getMillis(); - codeLocation = "19"; - if(getQuitStatus() == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - break; - } - } + if (world->getUnitUpdater() == NULL) { + throw megaglest_runtime_error("world->getUnitUpdater() == NULL"); + } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] ****************** ENDING worker thread this = %p\n",__FILE__,__FUNCTION__,__LINE__,this); - } - catch(const exception &ex) { - //setRunningStatus(false); + world->getUnitUpdater()->updateUnitCommand( + unit, currentTriggeredFrameIndex); + + codeLocation = "15"; + if (minorDebugPerformance && (chrono.getMillis() - elapsed2) >= 1) + printf("Faction [%d - %s] #2-unit threaded updates on frame: %d " + "for [%d] unit # %d, unitCount = %d, took [%lld] msecs\n", + faction->getStartLocationIndex(), + faction->getType()->getName(false).c_str(), + currentTriggeredFrameIndex, + faction->getUnitPathfindingListCount(), j, unitCount, + (long long int)chrono.getMillis() - elapsed2); + } else { + codeLocation = "16"; + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true) { + int64 updateProgressValue = unit->getUpdateProgress(); + int64 speed = + unit->getCurrSkill()->getTotalSpeed(unit->getTotalUpgrade()); + int64 df = unit->getDiagonalFactor(); + int64 hf = unit->getHeightFactor(); + bool changedActiveCommand = unit->isChangedActiveCommand(); + + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "unit->needToUpdate() returned: %d updateProgressValue: %lld " + "speed: %lld changedActiveCommand: %d df: %lld hf: %lld", + update, (long long int)updateProgressValue, + (long long int)speed, changedActiveCommand, (long long int)df, + (long long int)hf); + unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf); + } + } + } - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Loc [%s] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,codeLocation.c_str(),ex.what()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + codeLocation = "17"; + if (minorDebugPerformance && chrono.getMillis() >= 1) + printf("Faction [%d - %s] threaded updates on frame: %d for [%d] " + "units took [%lld] msecs\n", + faction->getStartLocationIndex(), + faction->getType()->getName(false).c_str(), + currentTriggeredFrameIndex, + faction->getUnitPathfindingListCount(), + (long long int)chrono.getMillis()); - throw megaglest_runtime_error(ex.what()); - } - catch(...) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d] UNKNOWN error Loc [%s]\n",__FILE__,__FUNCTION__,__LINE__,codeLocation.c_str()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - throw megaglest_runtime_error(szBuf); - } + // printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); -} + safeMutex.ReleaseLock(); + codeLocation = "18"; + // printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + + setTaskCompleted(currentTriggeredFrameIndex); + + // printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + } + + // printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + + codeLocation = "19"; + if (getQuitStatus() == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + break; + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] ****************** ENDING worker thread " + "this = %p\n", + __FILE__, __FUNCTION__, __LINE__, this); + } catch (const exception &ex) { + // setRunningStatus(false); + + SystemFlags::OutputDebug( + SystemFlags::debugError, "In [%s::%s Line: %d] Loc [%s] Error [%s]\n", + __FILE__, __FUNCTION__, __LINE__, codeLocation.c_str(), ex.what()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + throw megaglest_runtime_error(ex.what()); + } catch (...) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d] UNKNOWN error Loc [%s]\n", __FILE__, + __FUNCTION__, __LINE__, codeLocation.c_str()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + throw megaglest_runtime_error(szBuf); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s] Line: %d\n", + __FILE__, __FUNCTION__, __LINE__); +} // ===================================================== // class Faction // ===================================================== -Faction::Faction() { - init(); -} +Faction::Faction() { init(); } void Faction::init() { - unitsMutex = new Mutex(CODE_AT_LINE); - texture = NULL; - //lastResourceTargettListPurge = 0; - cachingDisabled=false; - factionDisconnectHandled=false; - workerThread = NULL; + unitsMutex = new Mutex(CODE_AT_LINE); + texture = NULL; + // lastResourceTargettListPurge = 0; + cachingDisabled = false; + factionDisconnectHandled = false; + workerThread = NULL; - world=NULL; - scriptManager=NULL; - factionType=NULL; - index=0; - teamIndex=0; - startLocationIndex=0; - thisFaction=false; - currentSwitchTeamVoteFactionIndex = -1; - allowSharedTeamUnits = false; + world = NULL; + scriptManager = NULL; + factionType = NULL; + index = 0; + teamIndex = 0; + startLocationIndex = 0; + thisFaction = false; + currentSwitchTeamVoteFactionIndex = -1; + allowSharedTeamUnits = false; - loadWorldNode = NULL; - techTree = NULL; + loadWorldNode = NULL; + techTree = NULL; - control = ctClosed; + control = ctClosed; - overridePersonalityType = fpt_EndCount; + overridePersonalityType = fpt_EndCount; - upgradeManager = UpgradeManager(); + upgradeManager = UpgradeManager(); } Faction::~Faction() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - //Renderer &renderer= Renderer::getInstance(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - //renderer.endTexture(rsGame,texture); - //texture->end(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(workerThread != NULL) { - workerThread->signalQuit(); - if(workerThread->shutdownAndWait() == true) { - delete workerThread; - } - workerThread = NULL; - } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + // Renderer &renderer= Renderer::getInstance(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + // renderer.endTexture(rsGame,texture); + // texture->end(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + if (workerThread != NULL) { + workerThread->signalQuit(); + if (workerThread->shutdownAndWait() == true) { + delete workerThread; + } + workerThread = NULL; + } - MutexSafeWrapper safeMutex(unitsMutex,string(__FILE__) + "_" + intToStr(__LINE__)); - deleteValues(units.begin(), units.end()); - units.clear(); + MutexSafeWrapper safeMutex(unitsMutex, + string(__FILE__) + "_" + intToStr(__LINE__)); + deleteValues(units.begin(), units.end()); + units.clear(); - safeMutex.ReleaseLock(); + safeMutex.ReleaseLock(); - //delete texture; - texture = NULL; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + // delete texture; + texture = NULL; + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); - delete unitsMutex; - unitsMutex = NULL; + delete unitsMutex; + unitsMutex = NULL; - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); } void Faction::end() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - if(workerThread != NULL) { - workerThread->signalQuit(); - if(workerThread->shutdownAndWait() == true) { - delete workerThread; - } - workerThread = NULL; - } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + if (workerThread != NULL) { + workerThread->signalQuit(); + if (workerThread->shutdownAndWait() == true) { + delete workerThread; + } + workerThread = NULL; + } - MutexSafeWrapper safeMutex(unitsMutex,string(__FILE__) + "_" + intToStr(__LINE__)); - deleteValues(units.begin(), units.end()); - units.clear(); + MutexSafeWrapper safeMutex(unitsMutex, + string(__FILE__) + "_" + intToStr(__LINE__)); + deleteValues(units.begin(), units.end()); + units.clear(); - safeMutex.ReleaseLock(); + safeMutex.ReleaseLock(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); } void Faction::notifyUnitAliveStatusChange(const Unit *unit) { - if(unit != NULL) { - if(unit->isAlive() == true) { - aliveUnitListCache[unit->getId()] = unit; - - if(unit->getType()->isMobile() == true) { - mobileUnitListCache[unit->getId()] = unit; - } - } - else { - aliveUnitListCache.erase(unit->getId()); - mobileUnitListCache.erase(unit->getId()); - beingBuiltUnitListCache.erase(unit->getId()); - } - } + if (unit != NULL) { + if (unit->isAlive() == true) { + aliveUnitListCache[unit->getId()] = unit; + + if (unit->getType()->isMobile() == true) { + mobileUnitListCache[unit->getId()] = unit; + } + } else { + aliveUnitListCache.erase(unit->getId()); + mobileUnitListCache.erase(unit->getId()); + beingBuiltUnitListCache.erase(unit->getId()); + } + } } void Faction::notifyUnitTypeChange(const Unit *unit, const UnitType *newType) { - if(unit != NULL) { - if(unit->getType()->isMobile() == true) { - mobileUnitListCache.erase(unit->getId()); - } - - if(newType != NULL && newType->isMobile() == true) { - mobileUnitListCache[unit->getId()] = unit; - } - } -} - -void Faction::notifyUnitSkillTypeChange(const Unit *unit, const SkillType *newType) { - if(unit != NULL) { - if(unit->isBeingBuilt() == true) { - beingBuiltUnitListCache.erase(unit->getId()); - } - if(newType != NULL && newType->getClass() == scBeBuilt) { - beingBuiltUnitListCache[unit->getId()] = unit; - } - } -} - -bool Faction::hasAliveUnits(bool filterMobileUnits, bool filterBuiltUnits) const { - bool result = false; - if(aliveUnitListCache.empty() == false) { - if(filterMobileUnits == true) { - result = (mobileUnitListCache.empty() == false); - } - else { - result = true; - } - - if(result == true && filterBuiltUnits == true) { - result = (beingBuiltUnitListCache.empty() == true); - } - } - return result; + if (unit != NULL) { + if (unit->getType()->isMobile() == true) { + mobileUnitListCache.erase(unit->getId()); + } + + if (newType != NULL && newType->isMobile() == true) { + mobileUnitListCache[unit->getId()] = unit; + } + } +} + +void Faction::notifyUnitSkillTypeChange(const Unit *unit, + const SkillType *newType) { + if (unit != NULL) { + if (unit->isBeingBuilt() == true) { + beingBuiltUnitListCache.erase(unit->getId()); + } + if (newType != NULL && newType->getClass() == scBeBuilt) { + beingBuiltUnitListCache[unit->getId()] = unit; + } + } +} + +bool Faction::hasAliveUnits(bool filterMobileUnits, + bool filterBuiltUnits) const { + bool result = false; + if (aliveUnitListCache.empty() == false) { + if (filterMobileUnits == true) { + result = (mobileUnitListCache.empty() == false); + } else { + result = true; + } + + if (result == true && filterBuiltUnits == true) { + result = (beingBuiltUnitListCache.empty() == true); + } + } + return result; } FactionPersonalityType Faction::getPersonalityType() const { - if(overridePersonalityType != fpt_EndCount) { - return overridePersonalityType; - } - return factionType->getPersonalityType(); + if (overridePersonalityType != fpt_EndCount) { + return overridePersonalityType; + } + return factionType->getPersonalityType(); } -int Faction::getAIBehaviorStaticOverideValue(AIBehaviorStaticValueCategory type) const { - return factionType->getAIBehaviorStaticOverideValue(type); +int Faction::getAIBehaviorStaticOverideValue( + AIBehaviorStaticValueCategory type) const { + return factionType->getAIBehaviorStaticOverideValue(type); } void Faction::addUnitToMovingList(int unitId) { - unitsMovingList[unitId] = getWorld()->getFrameCount(); + unitsMovingList[unitId] = getWorld()->getFrameCount(); } void Faction::removeUnitFromMovingList(int unitId) { - unitsMovingList.erase(unitId); + unitsMovingList.erase(unitId); } -//int Faction::getUnitMovingListCount() { +// int Faction::getUnitMovingListCount() { // return (int)unitsMovingList.size(); -//} +// } void Faction::addUnitToPathfindingList(int unitId) { - //printf("ADD (1) Faction [%d - %s] threaded updates for [%d] units\n",this->getStartLocationIndex(),this->getType()->getName().c_str(),unitsPathfindingList.size()); - unitsPathfindingList[unitId] = getWorld()->getFrameCount(); - //printf("ADD (2) Faction [%d - %s] threaded updates for [%d] units\n",this->getStartLocationIndex(),this->getType()->getName().c_str(),unitsPathfindingList.size()); + // printf("ADD (1) Faction [%d - %s] threaded updates for [%d] + // units\n",this->getStartLocationIndex(),this->getType()->getName().c_str(),unitsPathfindingList.size()); + unitsPathfindingList[unitId] = getWorld()->getFrameCount(); + // printf("ADD (2) Faction [%d - %s] threaded updates for [%d] + // units\n",this->getStartLocationIndex(),this->getType()->getName().c_str(),unitsPathfindingList.size()); } -//void Faction::removeUnitFromPathfindingList(int unitId) { +// void Faction::removeUnitFromPathfindingList(int unitId) { // unitsPathfindingList.erase(unitId); -//} +// } int Faction::getUnitPathfindingListCount() { - //printf("GET Faction [%d - %s] threaded updates for [%d] units\n",this->getStartLocationIndex(),this->getType()->getName().c_str(),unitsPathfindingList.size()); - return (int)unitsPathfindingList.size(); + // printf("GET Faction [%d - %s] threaded updates for [%d] + // units\n",this->getStartLocationIndex(),this->getType()->getName().c_str(),unitsPathfindingList.size()); + return (int)unitsPathfindingList.size(); } void Faction::clearUnitsPathfinding() { - //printf("CLEAR Faction [%d - %s] threaded updates for [%d] units\n",this->getStartLocationIndex(),this->getType()->getName().c_str(),unitsPathfindingList.size()); - if(unitsPathfindingList.empty() == false) { - unitsPathfindingList.clear(); - } + // printf("CLEAR Faction [%d - %s] threaded updates for [%d] + // units\n",this->getStartLocationIndex(),this->getType()->getName().c_str(),unitsPathfindingList.size()); + if (unitsPathfindingList.empty() == false) { + unitsPathfindingList.clear(); + } } bool Faction::canUnitsPathfind() { - bool result = true; - if(control == ctCpuEasy || control == ctCpu || - control == ctCpuUltra || control == ctCpuMega) { - //printf("AI player for faction index: %d (%s) current pathfinding: %d\n",index,factionType->getName().c_str(),getUnitPathfindingListCount()); - - const int MAX_UNITS_PATHFINDING_PER_FRAME = 10; - result = (getUnitPathfindingListCount() <= MAX_UNITS_PATHFINDING_PER_FRAME); - if(result == false) { - //printf("WARNING limited AI player for faction index: %d (%s) current pathfinding: %d\n",index,factionType->getName().c_str(),getUnitPathfindingListCount()); - } - } - return result; + bool result = true; + if (control == ctCpuEasy || control == ctCpu || control == ctCpuUltra || + control == ctCpuMega) { + // printf("AI player for faction index: %d (%s) current pathfinding: + // %d\n",index,factionType->getName().c_str(),getUnitPathfindingListCount()); + + const int MAX_UNITS_PATHFINDING_PER_FRAME = 10; + result = (getUnitPathfindingListCount() <= MAX_UNITS_PATHFINDING_PER_FRAME); + if (result == false) { + // printf("WARNING limited AI player for faction index: %d (%s) current + // pathfinding: + // %d\n",index,factionType->getName().c_str(),getUnitPathfindingListCount()); + } + } + return result; } void Faction::setLockedUnitForFaction(const UnitType *ut, bool lock) { - if (lock) { - lockedUnits.insert(ut); - } else { - std::set::iterator it; - it=lockedUnits.find(ut); - if(it!=lockedUnits.end()) { - lockedUnits.erase(it); - } - } - + if (lock) { + lockedUnits.insert(ut); + } else { + std::set::iterator it; + it = lockedUnits.find(ut); + if (it != lockedUnits.end()) { + lockedUnits.erase(it); + } + } } void Faction::signalWorkerThread(int frameIndex) { - if(workerThread != NULL) { - workerThread->signalPathfinder(frameIndex); - } + if (workerThread != NULL) { + workerThread->signalPathfinder(frameIndex); + } } bool Faction::isWorkerThreadSignalCompleted(int frameIndex) { - if(workerThread != NULL) { - return workerThread->isSignalPathfinderCompleted(frameIndex); - } - return true; -} - - -void Faction::init( - FactionType *factionType, ControlType control, TechTree *techTree, Game *game, - int factionIndex, int teamIndex, int startLocationIndex, bool thisFaction, bool giveResources, - const XmlNode *loadWorldNode) -{ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - this->techTree = techTree; - this->loadWorldNode = loadWorldNode; - this->control= control; - this->factionType= factionType; - this->startLocationIndex= startLocationIndex; - this->index= factionIndex; - this->teamIndex= teamIndex; - this->thisFaction= thisFaction; - this->world= game->getWorld(); - this->scriptManager= game->getScriptManager(); - //cachingDisabled = (Config::getInstance().getBool("DisableCaching","false") == true); - cachingDisabled = false; - - resources.resize(techTree->getResourceTypeCount()); - store.resize(techTree->getResourceTypeCount()); - - if(loadWorldNode == NULL) { - for(int index = 0; index < techTree->getResourceTypeCount(); ++index) { - const ResourceType *rt = techTree->getResourceType(index); - int resourceAmount = giveResources ? factionType->getStartingResourceAmount(rt): 0; - resources[index].init(rt, resourceAmount); - store[index].init(rt, 0); - - this->world->initTeamResource(rt,this->teamIndex,0); - } - } - //initialize cache - for(int index = 0; index < techTree->getResourceTypeCount(); ++index) { - const ResourceType *rt = techTree->getResourceType(index); - this->updateUnitTypeWithResourceCostCache(rt); - } - - texture= Renderer::getInstance().newTexture2D(rsGame); - string data_path = getGameReadWritePath(GameConstants::path_data_CacheLookupKey); - if(texture) { - string playerTexture = getGameCustomCoreDataPath(data_path, "data/core/faction_textures/faction" + intToStr(startLocationIndex) + ".tga"); - texture->load(playerTexture); - } - - if(loadWorldNode != NULL) { - loadGame(loadWorldNode, this->index,game->getGameSettings(),game->getWorld()); - } - - if( game->getGameSettings()->getPathFinderType() == pfBasic) { - if(workerThread != NULL) { - workerThread->signalQuit(); - if(workerThread->shutdownAndWait() == true) { - delete workerThread; - } - workerThread = NULL; - } - static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); - this->workerThread = new FactionThread(this); - this->workerThread->setUniqueID(mutexOwnerId); - this->workerThread->start(); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (workerThread != NULL) { + return workerThread->isSignalPathfinderCompleted(frameIndex); + } + return true; +} + +void Faction::init(FactionType *factionType, ControlType control, + TechTree *techTree, Game *game, int factionIndex, + int teamIndex, int startLocationIndex, bool thisFaction, + bool giveResources, const XmlNode *loadWorldNode) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + this->techTree = techTree; + this->loadWorldNode = loadWorldNode; + this->control = control; + this->factionType = factionType; + this->startLocationIndex = startLocationIndex; + this->index = factionIndex; + this->teamIndex = teamIndex; + this->thisFaction = thisFaction; + this->world = game->getWorld(); + this->scriptManager = game->getScriptManager(); + // cachingDisabled = (Config::getInstance().getBool("DisableCaching","false") + // == true); + cachingDisabled = false; + + resources.resize(techTree->getResourceTypeCount()); + store.resize(techTree->getResourceTypeCount()); + + if (loadWorldNode == NULL) { + for (int index = 0; index < techTree->getResourceTypeCount(); ++index) { + const ResourceType *rt = techTree->getResourceType(index); + int resourceAmount = + giveResources ? factionType->getStartingResourceAmount(rt) : 0; + resources[index].init(rt, resourceAmount); + store[index].init(rt, 0); + + this->world->initTeamResource(rt, this->teamIndex, 0); + } + } + // initialize cache + for (int index = 0; index < techTree->getResourceTypeCount(); ++index) { + const ResourceType *rt = techTree->getResourceType(index); + this->updateUnitTypeWithResourceCostCache(rt); + } + + texture = Renderer::getInstance().newTexture2D(rsGame); + string data_path = + getGameReadWritePath(GameConstants::path_data_CacheLookupKey); + if (texture) { + string playerTexture = getGameCustomCoreDataPath( + data_path, "data/core/faction_textures/faction" + + intToStr(startLocationIndex) + ".tga"); + texture->load(playerTexture); + } + + if (loadWorldNode != NULL) { + loadGame(loadWorldNode, this->index, game->getGameSettings(), + game->getWorld()); + } + + if (game->getGameSettings()->getPathFinderType() == pfBasic) { + if (workerThread != NULL) { + workerThread->signalQuit(); + if (workerThread->shutdownAndWait() == true) { + delete workerThread; + } + workerThread = NULL; + } + static string mutexOwnerId = + string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + + intToStr(__LINE__); + this->workerThread = new FactionThread(this); + this->workerThread->setUniqueID(mutexOwnerId); + this->workerThread->start(); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); } // ================== get ================== bool Faction::hasUnitTypeWithResourceCostInCache(const ResourceType *rt) const { - std::string resourceTypeName = rt->getName(false); - std::map::const_iterator iterFind = resourceTypeCostCache.find(resourceTypeName); - if(iterFind != resourceTypeCostCache.end()) { - return iterFind->second; - } - return false; + std::string resourceTypeName = rt->getName(false); + std::map::const_iterator iterFind = + resourceTypeCostCache.find(resourceTypeName); + if (iterFind != resourceTypeCostCache.end()) { + return iterFind->second; + } + return false; } void Faction::updateUnitTypeWithResourceCostCache(const ResourceType *rt) { - std::string resourceTypeName = rt->getName(false); + std::string resourceTypeName = rt->getName(false); - if(resourceTypeCostCache.find(resourceTypeName) == resourceTypeCostCache.end()) { - resourceTypeCostCache[resourceTypeName] = hasUnitTypeWithResouceCost(rt); - } + if (resourceTypeCostCache.find(resourceTypeName) == + resourceTypeCostCache.end()) { + resourceTypeCostCache[resourceTypeName] = hasUnitTypeWithResouceCost(rt); + } } bool Faction::hasUnitTypeWithResouceCost(const ResourceType *rt) { - for(int factionUnitTypeIndex = 0; - factionUnitTypeIndex < getType()->getUnitTypeCount(); - ++factionUnitTypeIndex) { - - const UnitType *ut = getType()->getUnitType(factionUnitTypeIndex); - if(ut->getCost(rt) != NULL) { - return true; - } - } - return false; -} - -const Resource *Faction::getResource(const ResourceType *rt,bool localFactionOnly) const { - - if(localFactionOnly == false && - world != NULL && - world->getGame() != NULL) { - - Game *game = world->getGame(); - if(game->isFlagType1BitEnabled(ft1_allow_shared_team_resources) == true) { - return world->getResourceForTeam(rt, this->getTeam()); - } - } - - for(int index = 0; index < (int)resources.size(); ++index) { - if(rt == resources[index].getType()) { - return &resources[index]; - } - } - - printf("ERROR cannot find resource type [%s] in list:\n",(rt != NULL ? rt->getName().c_str() : "null")); - for(int i=0; i < (int)resources.size(); ++i){ - printf("Index %d [%s]",i,resources[i].getType()->getName().c_str()); - } - - assert(false); - return NULL; -} - -int Faction::getStoreAmount(const ResourceType *rt,bool localFactionOnly) const { - - if(localFactionOnly == false && - world != NULL && - world->getGame() != NULL) { - - Game *game = world->getGame(); - if(game->isFlagType1BitEnabled(ft1_allow_shared_team_resources) == true) { - return world->getStoreAmountForTeam(rt, this->getTeam()); - } - } - - for(int index =0 ; index < (int)store.size(); ++index) { - if(rt == store[index].getType()) { - return store[index].getAmount(); - } - } - printf("ERROR cannot find store type [%s] in list:\n",(rt != NULL ? rt->getName().c_str() : "null")); - for(int i=0; i < (int)store.size(); ++i){ - printf("Index %d [%s]",i,store[i].getType()->getName().c_str()); - } - - assert(false); - return 0; -} - -bool Faction::getCpuControl(bool enableServerControlledAI,bool isNetworkGame, NetworkRole role) const { - bool result = false; - if(enableServerControlledAI == false || isNetworkGame == false) { - result = (control == ctCpuEasy ||control == ctCpu || control == ctCpuUltra || control == ctCpuMega); - } - else { - if(isNetworkGame == true) { - if(role == nrServer) { - result = (control == ctCpuEasy ||control == ctCpu || control == ctCpuUltra || control == ctCpuMega); - } - else { - result = (control == ctNetworkCpuEasy ||control == ctNetworkCpu || control == ctNetworkCpuUltra || control == ctNetworkCpuMega); - } - } - } - - return result; + for (int factionUnitTypeIndex = 0; + factionUnitTypeIndex < getType()->getUnitTypeCount(); + ++factionUnitTypeIndex) { + + const UnitType *ut = getType()->getUnitType(factionUnitTypeIndex); + if (ut->getCost(rt) != NULL) { + return true; + } + } + return false; +} + +const Resource *Faction::getResource(const ResourceType *rt, + bool localFactionOnly) const { + + if (localFactionOnly == false && world != NULL && world->getGame() != NULL) { + + Game *game = world->getGame(); + if (game->isFlagType1BitEnabled(ft1_allow_shared_team_resources) == true) { + return world->getResourceForTeam(rt, this->getTeam()); + } + } + + for (int index = 0; index < (int)resources.size(); ++index) { + if (rt == resources[index].getType()) { + return &resources[index]; + } + } + + printf("ERROR cannot find resource type [%s] in list:\n", + (rt != NULL ? rt->getName().c_str() : "null")); + for (int i = 0; i < (int)resources.size(); ++i) { + printf("Index %d [%s]", i, resources[i].getType()->getName().c_str()); + } + + assert(false); + return NULL; +} + +int Faction::getStoreAmount(const ResourceType *rt, + bool localFactionOnly) const { + + if (localFactionOnly == false && world != NULL && world->getGame() != NULL) { + + Game *game = world->getGame(); + if (game->isFlagType1BitEnabled(ft1_allow_shared_team_resources) == true) { + return world->getStoreAmountForTeam(rt, this->getTeam()); + } + } + + for (int index = 0; index < (int)store.size(); ++index) { + if (rt == store[index].getType()) { + return store[index].getAmount(); + } + } + printf("ERROR cannot find store type [%s] in list:\n", + (rt != NULL ? rt->getName().c_str() : "null")); + for (int i = 0; i < (int)store.size(); ++i) { + printf("Index %d [%s]", i, store[i].getType()->getName().c_str()); + } + + assert(false); + return 0; +} + +bool Faction::getCpuControl(bool enableServerControlledAI, bool isNetworkGame, + NetworkRole role) const { + bool result = false; + if (enableServerControlledAI == false || isNetworkGame == false) { + result = (control == ctCpuEasy || control == ctCpu || + control == ctCpuUltra || control == ctCpuMega); + } else { + if (isNetworkGame == true) { + if (role == nrServer) { + result = (control == ctCpuEasy || control == ctCpu || + control == ctCpuUltra || control == ctCpuMega); + } else { + result = (control == ctNetworkCpuEasy || control == ctNetworkCpu || + control == ctNetworkCpuUltra || control == ctNetworkCpuMega); + } + } + } + + return result; } bool Faction::getCpuControl() const { - return control == ctCpuEasy ||control == ctCpu || control == ctCpuUltra || control == ctCpuMega || - control == ctNetworkCpuEasy ||control == ctNetworkCpu || control == ctNetworkCpuUltra || control == ctNetworkCpuMega; + return control == ctCpuEasy || control == ctCpu || control == ctCpuUltra || + control == ctCpuMega || control == ctNetworkCpuEasy || + control == ctNetworkCpu || control == ctNetworkCpuUltra || + control == ctNetworkCpuMega; } // ==================== upgrade manager ==================== -void Faction::startUpgrade(const UpgradeType *ut){ - upgradeManager.startUpgrade(ut, index); +void Faction::startUpgrade(const UpgradeType *ut) { + upgradeManager.startUpgrade(ut, index); } -void Faction::cancelUpgrade(const UpgradeType *ut){ - upgradeManager.cancelUpgrade(ut); +void Faction::cancelUpgrade(const UpgradeType *ut) { + upgradeManager.cancelUpgrade(ut); } -void Faction::finishUpgrade(const UpgradeType *ut){ - upgradeManager.finishUpgrade(ut); - if(world->getThisFaction()!=NULL && this->getIndex()==world->getThisFaction()->getIndex()){ - Console *console=world->getGame()->getConsole(); - console->addStdMessage("UpgradeFinished",": " + formatString(ut->getName(true))); - } - for(int i=0; iapplyUpgrade(ut); - } +void Faction::finishUpgrade(const UpgradeType *ut) { + upgradeManager.finishUpgrade(ut); + if (world->getThisFaction() != NULL && + this->getIndex() == world->getThisFaction()->getIndex()) { + Console *console = world->getGame()->getConsole(); + console->addStdMessage("UpgradeFinished", + ": " + formatString(ut->getName(true))); + } + for (int i = 0; i < getUnitCount(); ++i) { + getUnit(i)->applyUpgrade(ut); + } } // ==================== reqs ==================== -//checks if all required units and upgrades are present and maxUnitCount is within limit +// checks if all required units and upgrades are present and maxUnitCount is +// within limit bool Faction::reqsOk(const RequirableType *rt) const { - assert(rt != NULL); - //required units - for(int i = 0; i < rt->getUnitReqCount(); ++i) { - bool found = false; - for(int j = 0; j < getUnitCount(); ++j) { - Unit *unit= getUnit(j); - const UnitType *ut= unit->getType(); - if(rt->getUnitReq(i) == ut && unit->isOperative()) { - found= true; - break; - } - } - if(found == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__, __LINE__); - return false; - } + assert(rt != NULL); + // required units + for (int i = 0; i < rt->getUnitReqCount(); ++i) { + bool found = false; + for (int j = 0; j < getUnitCount(); ++j) { + Unit *unit = getUnit(j); + const UnitType *ut = unit->getType(); + if (rt->getUnitReq(i) == ut && unit->isOperative()) { + found = true; + break; + } + } + if (found == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + return false; + } + } + + // required upgrades + for (int i = 0; i < rt->getUpgradeReqCount(); ++i) { + if (upgradeManager.isUpgraded(rt->getUpgradeReq(i)) == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + return false; + } + } + + if (dynamic_cast(rt) != NULL) { + const UnitType *producedUnitType = dynamic_cast(rt); + if (producedUnitType != NULL && producedUnitType->getMaxUnitCount() > 0) { + if (producedUnitType->getMaxUnitCount() <= + getCountForMaxUnitCount(producedUnitType)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d]\n", __FILE__, + __FUNCTION__, __LINE__); + return false; + } } - //required upgrades - for(int i = 0; i < rt->getUpgradeReqCount(); ++i) { - if(upgradeManager.isUpgraded(rt->getUpgradeReq(i)) == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__, __LINE__); - return false; - } + if (producedUnitType != NULL && isUnitLocked(producedUnitType)) { + return false; } + } + + return true; +} - if(dynamic_cast(rt) != NULL ) { - const UnitType *producedUnitType= dynamic_cast(rt); - if(producedUnitType != NULL && producedUnitType->getMaxUnitCount() > 0) { - if(producedUnitType->getMaxUnitCount() <= getCountForMaxUnitCount(producedUnitType)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__, __LINE__); - return false; - } - } +int Faction::getCountForMaxUnitCount(const UnitType *unitType) const { + int count = 0; + // calculate current unit count + for (int j = 0; j < getUnitCount(); ++j) { + Unit *unit = getUnit(j); + const UnitType *currentUt = unit->getType(); + if (unitType == currentUt && (unit->isAlive())) { + count++; + } + // check if there is any command active which already produces this unit + count = count + unit->getCountOfProducedUnitsPreExistence(unitType); + } + return count; +} - if(producedUnitType != NULL && isUnitLocked(producedUnitType)) { - return false; - } +bool Faction::reqsOk(const CommandType *ct) const { + assert(ct != NULL); + if (ct == NULL) { + throw megaglest_runtime_error("In [Faction::reqsOk] ct == NULL"); + } + + if (ct->getProduced() != NULL && reqsOk(ct->getProduced()) == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d] reqsOk FAILED\n", __FILE__, + __FUNCTION__, __LINE__); + return false; + } + + if (ct->getClass() == ccUpgrade) { + const UpgradeCommandType *uct = static_cast(ct); + if (upgradeManager.isUpgradingOrUpgraded(uct->getProducedUpgrade())) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d] upgrade check FAILED\n", + __FILE__, __FUNCTION__, __LINE__); + return false; } + } - return true; + return reqsOk(static_cast(ct)); } -int Faction::getCountForMaxUnitCount(const UnitType *unitType) const{ - int count=0; - //calculate current unit count - for(int j=0; jgetType(); - if(unitType==currentUt && ( unit->isAlive())){ - count++; +// ================== cost application ================== + +// apply costs except static production (start building/production) +bool Faction::applyCosts(const ProducibleType *p, const CommandType *ct) { + bool ignoreResourceCosts = false; + if (ct != NULL && ct->getClass() == ccMorph) { + const MorphCommandType *mct = dynamic_cast(ct); + if (mct != NULL) { + ignoreResourceCosts = mct->getIgnoreResourceRequirements(); + } + } + + if (ignoreResourceCosts == false) { + if (checkCosts(p, ct) == false) { + return false; + } + + assert(p != NULL); + // for each unit cost spend it + // pass 2, decrease resources, except negative static costs (ie: farms) + for (int i = 0; i < p->getCostCount(); ++i) { + const Resource *r = p->getCost(i); + if (r == NULL) { + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "cannot apply costs for p [%s] %d of %d costs resource is null", + p->getName(false).c_str(), i, p->getCostCount()); + throw megaglest_runtime_error(szBuf); + } + + const ResourceType *rt = r->getType(); + if (rt == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "cannot apply costs for p [%s] %d of %d costs resourcetype " + "[%s] is null", + p->getName(false).c_str(), i, p->getCostCount(), + r->getDescription(false).c_str()); + throw megaglest_runtime_error(szBuf); + } + int cost = r->getAmount(); + if ((cost > 0 || (rt->getClass() != rcStatic)) && + rt->getClass() != rcConsumable) { + incResourceAmount(rt, -(cost)); + } + } + } + return true; +} + +// apply discount (when a morph ends) +void Faction::applyDiscount(const ProducibleType *p, int discount) { + assert(p != NULL); + // increase resources + for (int i = 0; i < p->getCostCount(); ++i) { + const ResourceType *rt = p->getCost(i)->getType(); + assert(rt != NULL); + int cost = p->getCost(i)->getAmount(); + if ((cost > 0 || (rt->getClass() != rcStatic)) && + rt->getClass() != rcConsumable) { + incResourceAmount(rt, cost * discount / 100); + } + } +} + +// apply static production (for starting units) +void Faction::applyStaticCosts(const ProducibleType *p, const CommandType *ct) { + assert(p != NULL); + bool ignoreResourceCosts = false; + if (ct != NULL && ct->getClass() == ccMorph) { + const MorphCommandType *mct = dynamic_cast(ct); + if (mct != NULL) { + ignoreResourceCosts = mct->getIgnoreResourceRequirements(); + } + } + + if (ignoreResourceCosts == false) { + // decrease static resources + for (int i = 0; i < p->getCostCount(); ++i) { + const ResourceType *rt = p->getCost(i)->getType(); + // assert(rt != NULL); + if (rt == NULL) { + throw megaglest_runtime_error( + string(__FUNCTION__) + " rt == NULL for ProducibleType [" + + p->getName(false) + "] index: " + intToStr(i)); + } + if (rt->getClass() == rcStatic) { + int cost = p->getCost(i)->getAmount(); + if (cost > 0) { + incResourceAmount(rt, -cost); } - //check if there is any command active which already produces this unit - count=count+unit->getCountOfProducedUnitsPreExistence(unitType); + } } - return count; + } } +// apply static production (when a mana source is done) +void Faction::applyStaticProduction(const ProducibleType *p, + const CommandType *ct) { + assert(p != NULL); -bool Faction::reqsOk(const CommandType *ct) const { - assert(ct != NULL); - if(ct == NULL) { - throw megaglest_runtime_error("In [Faction::reqsOk] ct == NULL"); - } + bool ignoreResourceCosts = false; + if (ct != NULL && ct->getClass() == ccMorph) { + const MorphCommandType *mct = dynamic_cast(ct); + if (mct != NULL) { + ignoreResourceCosts = mct->getIgnoreResourceRequirements(); + } + } + + if (ignoreResourceCosts == false) { + // decrease static resources + for (int i = 0; i < p->getCostCount(); ++i) { + const ResourceType *rt = p->getCost(i)->getType(); + assert(rt != NULL); + if (rt->getClass() == rcStatic) { + int cost = p->getCost(i)->getAmount(); + if (cost < 0) { + incResourceAmount(rt, -cost); + } + } + } + } +} - if(ct->getProduced() != NULL && reqsOk(ct->getProduced()) == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] reqsOk FAILED\n",__FILE__,__FUNCTION__,__LINE__); - return false; - } +// deapply all costs except static production (usually when a building is +// cancelled) +void Faction::deApplyCosts(const ProducibleType *p, const CommandType *ct) { + assert(p != NULL); + + bool ignoreResourceCosts = false; + if (ct != NULL && ct->getClass() == ccMorph) { + const MorphCommandType *mct = dynamic_cast(ct); + if (mct != NULL) { + ignoreResourceCosts = mct->getIgnoreResourceRequirements(); + } + } + + if (ignoreResourceCosts == false) { + // increase resources + for (int i = 0; i < p->getCostCount(); ++i) { + const ResourceType *rt = p->getCost(i)->getType(); + assert(rt != NULL); + int cost = p->getCost(i)->getAmount(); + if ((cost > 0 || (rt->getClass() != rcStatic)) && + rt->getClass() != rcConsumable) { + incResourceAmount(rt, cost); + } + } + } +} - if(ct->getClass() == ccUpgrade) { - const UpgradeCommandType *uct= static_cast(ct); - if(upgradeManager.isUpgradingOrUpgraded(uct->getProducedUpgrade())) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] upgrade check FAILED\n",__FILE__,__FUNCTION__,__LINE__); - return false; - } - } +// deapply static costs (usually when a unit dies) +void Faction::deApplyStaticCosts(const ProducibleType *p, + const CommandType *ct) { + assert(p != NULL); - return reqsOk(static_cast(ct)); + bool ignoreResourceCosts = false; + if (ct != NULL && ct->getClass() == ccMorph) { + const MorphCommandType *mct = dynamic_cast(ct); + if (mct != NULL) { + ignoreResourceCosts = mct->getIgnoreResourceRequirements(); + } + } + + if (ignoreResourceCosts == false) { + // decrease resources + for (int i = 0; i < p->getCostCount(); ++i) { + const ResourceType *rt = p->getCost(i)->getType(); + assert(rt != NULL); + if (rt->getClass() == rcStatic) { + if (rt->getRecoup_cost() == true) { + int cost = p->getCost(i)->getAmount(); + incResourceAmount(rt, cost); + } + } + } + } } -// ================== cost application ================== +// deapply static costs, but not negative costs, for when building gets killed +void Faction::deApplyStaticConsumption(const ProducibleType *p, + const CommandType *ct) { + assert(p != NULL); -//apply costs except static production (start building/production) -bool Faction::applyCosts(const ProducibleType *p,const CommandType *ct) { - bool ignoreResourceCosts = false; - if(ct != NULL && ct->getClass() == ccMorph) { - const MorphCommandType *mct = dynamic_cast(ct); - if(mct != NULL) { - ignoreResourceCosts = mct->getIgnoreResourceRequirements(); - } - } - - if(ignoreResourceCosts == false) { - if(checkCosts(p,ct) == false) { - return false; - } - - assert(p != NULL); - //for each unit cost spend it - //pass 2, decrease resources, except negative static costs (ie: farms) - for(int i=0; igetCostCount(); ++i) { - const Resource *r= p->getCost(i); - if(r == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"cannot apply costs for p [%s] %d of %d costs resource is null",p->getName(false).c_str(),i,p->getCostCount()); - throw megaglest_runtime_error(szBuf); - } - - const ResourceType *rt= r->getType(); - if(rt == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"cannot apply costs for p [%s] %d of %d costs resourcetype [%s] is null",p->getName(false).c_str(),i,p->getCostCount(),r->getDescription(false).c_str()); - throw megaglest_runtime_error(szBuf); - } - int cost= r->getAmount(); - if((cost > 0 || (rt->getClass() != rcStatic)) && rt->getClass() != rcConsumable) { - incResourceAmount(rt, -(cost)); - } - - } - } - return true; + bool ignoreResourceCosts = false; + if (ct != NULL && ct->getClass() == ccMorph) { + const MorphCommandType *mct = dynamic_cast(ct); + if (mct != NULL) { + ignoreResourceCosts = mct->getIgnoreResourceRequirements(); + } + } + + if (ignoreResourceCosts == false) { + // decrease resources + for (int i = 0; i < p->getCostCount(); ++i) { + const ResourceType *rt = p->getCost(i)->getType(); + assert(rt != NULL); + if (rt->getClass() == rcStatic) { + int cost = p->getCost(i)->getAmount(); + if (cost > 0) { + incResourceAmount(rt, cost); + } + } + } + } } -//apply discount (when a morph ends) -void Faction::applyDiscount(const ProducibleType *p, int discount) -{ - assert(p != NULL); - //increase resources - for(int i=0; igetCostCount(); ++i) - { - const ResourceType *rt= p->getCost(i)->getType(); - assert(rt != NULL); - int cost= p->getCost(i)->getAmount(); - if((cost > 0 || (rt->getClass() != rcStatic)) && rt->getClass() != rcConsumable) - { - incResourceAmount(rt, cost*discount/100); - } - } -} - -//apply static production (for starting units) -void Faction::applyStaticCosts(const ProducibleType *p,const CommandType *ct) { - assert(p != NULL); - bool ignoreResourceCosts = false; - if(ct != NULL && ct->getClass() == ccMorph) { - const MorphCommandType *mct = dynamic_cast(ct); - if(mct != NULL) { - ignoreResourceCosts = mct->getIgnoreResourceRequirements(); - } - } - - if(ignoreResourceCosts == false) { - //decrease static resources - for(int i=0; i < p->getCostCount(); ++i) { - const ResourceType *rt= p->getCost(i)->getType(); - //assert(rt != NULL); - if(rt == NULL) { - throw megaglest_runtime_error(string(__FUNCTION__) + " rt == NULL for ProducibleType [" + p->getName(false) + "] index: " + intToStr(i)); - } - if(rt->getClass() == rcStatic) { - int cost= p->getCost(i)->getAmount(); - if(cost > 0) { - incResourceAmount(rt, -cost); - } - } - } - } -} - -//apply static production (when a mana source is done) -void Faction::applyStaticProduction(const ProducibleType *p,const CommandType *ct) { - assert(p != NULL); - - bool ignoreResourceCosts = false; - if(ct != NULL && ct->getClass() == ccMorph) { - const MorphCommandType *mct = dynamic_cast(ct); - if(mct != NULL) { - ignoreResourceCosts = mct->getIgnoreResourceRequirements(); - } - } - - if(ignoreResourceCosts == false) { - //decrease static resources - for(int i=0; igetCostCount(); ++i) { - const ResourceType *rt= p->getCost(i)->getType(); - assert(rt != NULL); - if(rt->getClass() == rcStatic) { - int cost= p->getCost(i)->getAmount(); - if(cost < 0) { - incResourceAmount(rt, -cost); - } - } - } - } -} - -//deapply all costs except static production (usually when a building is cancelled) -void Faction::deApplyCosts(const ProducibleType *p,const CommandType *ct) { - assert(p != NULL); - - bool ignoreResourceCosts = false; - if(ct != NULL && ct->getClass() == ccMorph) { - const MorphCommandType *mct = dynamic_cast(ct); - if(mct != NULL) { - ignoreResourceCosts = mct->getIgnoreResourceRequirements(); - } - } - - if(ignoreResourceCosts == false) { - //increase resources - for(int i=0; igetCostCount(); ++i) { - const ResourceType *rt= p->getCost(i)->getType(); - assert(rt != NULL); - int cost= p->getCost(i)->getAmount(); - if((cost > 0 || (rt->getClass() != rcStatic)) && rt->getClass() != rcConsumable) { - incResourceAmount(rt, cost); - } - } - } -} - -//deapply static costs (usually when a unit dies) -void Faction::deApplyStaticCosts(const ProducibleType *p,const CommandType *ct) { - assert(p != NULL); - - bool ignoreResourceCosts = false; - if(ct != NULL && ct->getClass() == ccMorph) { - const MorphCommandType *mct = dynamic_cast(ct); - if(mct != NULL) { - ignoreResourceCosts = mct->getIgnoreResourceRequirements(); - } - } - - if(ignoreResourceCosts == false) { - //decrease resources - for(int i=0; igetCostCount(); ++i) { - const ResourceType *rt= p->getCost(i)->getType(); - assert(rt != NULL); - if(rt->getClass() == rcStatic) { - if(rt->getRecoup_cost() == true) { - int cost= p->getCost(i)->getAmount(); - incResourceAmount(rt, cost); - } - } - } - } -} - -//deapply static costs, but not negative costs, for when building gets killed -void Faction::deApplyStaticConsumption(const ProducibleType *p,const CommandType *ct) { - assert(p != NULL); - - bool ignoreResourceCosts = false; - if(ct != NULL && ct->getClass() == ccMorph) { - const MorphCommandType *mct = dynamic_cast(ct); - if(mct != NULL) { - ignoreResourceCosts = mct->getIgnoreResourceRequirements(); - } - } - - if(ignoreResourceCosts == false) { - //decrease resources - for(int i=0; igetCostCount(); ++i) { - const ResourceType *rt= p->getCost(i)->getType(); - assert(rt != NULL); - if(rt->getClass() == rcStatic) { - int cost= p->getCost(i)->getAmount(); - if(cost > 0) { - incResourceAmount(rt, cost); - } - } - } - } -} - -//apply resource on interval (cosumable resouces) -// returns true if warning sound for food etc is needed +// apply resource on interval (cosumable resouces) +// returns true if warning sound for food etc is needed bool Faction::applyCostsOnInterval(const ResourceType *rtApply) { - bool warningSoundNeeded=false; - // For each Resource type we store in the int a total consumed value, then - // a vector of units that consume the resource type - std::map > > resourceIntervalUsage; - - // count up consumables usage for the interval - for(int j = 0; j < getUnitCount(); ++j) { - Unit *unit = getUnit(j); - if(unit->isOperative() == true) { - for(int k = 0; k < unit->getType()->getCostCount(); ++k) { - const Resource *resource = unit->getType()->getCost(k); - if(resource->getType() == rtApply && resource->getType()->getClass() == rcConsumable && resource->getAmount() != 0) { - if(resourceIntervalUsage.find(resource->getType()) == resourceIntervalUsage.end()) { - resourceIntervalUsage[resource->getType()] = make_pair >(0,std::vector()); - } - // Negative cost means accumulate the resource type - resourceIntervalUsage[resource->getType()].first += -resource->getAmount(); - - // If the cost > 0 then the unit is a consumer - if(resource->getAmount() > 0) { - resourceIntervalUsage[resource->getType()].second.push_back(unit); - } - } - } - } - } - - // Apply consumable resource usage - if(resourceIntervalUsage.empty() == false) { - for(std::map > >::iterator iter = resourceIntervalUsage.begin(); - iter != resourceIntervalUsage.end(); - ++iter) { - // Apply resource type usage to faction resource store - const ResourceType *rt = iter->first; - int resourceTypeUsage = iter->second.first; - incResourceAmount(rt, resourceTypeUsage); - - if (rt->getClass() == rcConsumable ) { - const Resource *r = getResource(rt); - if (r->getBalance() * 5 + r->getAmount() < 0 && r->getAmount() >= 0) { - // warning for player and team( if shared resources or control ) - bool sharedTeamResources = world->getGame()->isFlagType1BitEnabled(ft1_allow_shared_team_resources); - bool sharedTeamUnits = world->getGame()->isFlagType1BitEnabled(ft1_allow_shared_team_units); - bool isTeam = ( this->getTeam() == world->getThisTeamIndex()); - - if (this->getIndex() == world->getThisFactionIndex() || (isTeam && (sharedTeamResources || sharedTeamUnits))) { - warningSoundNeeded=true; - } - } - } - - // Check if we have any unit consumers - if(getResource(rt)->getAmount() < 0) { - resetResourceAmount(rt); - - // Apply consequences to consumer units of this resource type - std::vector &resourceConsumers = iter->second.second; - - for(int i = 0; i < (int)resourceConsumers.size(); ++i) { - Unit *unit = resourceConsumers[i]; - - //decrease unit hp - if(scriptManager->getPlayerModifiers(this->index)->getConsumeEnabled() == true) { - bool decHpResult = unit->decHp(unit->getType()->getTotalMaxHp(unit->getTotalUpgrade()) / 3); - if(decHpResult) { - unit->setCauseOfDeath(ucodStarvedResource); - world->getStats()->die(unit->getFactionIndex(),unit->getType()->getCountUnitDeathInStats()); - scriptManager->onUnitDied(unit); - } - StaticSound *sound= static_cast(unit->getType()->getFirstStOfClass(scDie))->getSound(); - if(sound != NULL && - (thisFaction == true || world->showWorldForPlayer(world->getThisTeamIndex()) == true)) { - SoundRenderer::getInstance().playFx(sound); - } - } - } - } - } - } - return warningSoundNeeded; -} - -int Faction::getAmountOfProducable(const ProducibleType *pt,const CommandType *ct) { - assert(pt != NULL); - - bool ignoreResourceCosts = false; - if(ct != NULL && ct->getClass() == ccMorph) { - const MorphCommandType *mct = dynamic_cast(ct); - if(mct != NULL) { - ignoreResourceCosts = mct->getIgnoreResourceRequirements(); - } - //printf("Checking costs = %d for commandtype:\n%s\n",ignoreResourceCosts,mct->getDesc(NULL).c_str()); - } - - int maxAmount=INT_MAX; - if(ignoreResourceCosts == false) { - //for each unit cost check if enough resources - for(int i = 0; i < pt->getCostCount(); ++i) { - const ResourceType *rt= pt->getCost(i)->getType(); - int cost= pt->getCost(i)->getAmount(); - if(cost > 0) { - int available= getResource(rt)->getAmount(); - int possibleCount=available/cost; - if( maxAmount>possibleCount) - maxAmount=possibleCount; - if(maxAmount==0){ - break; - } - } - } - } - - return maxAmount; -} - - -bool Faction::checkCosts(const ProducibleType *pt,const CommandType *ct) { - return getAmountOfProducable(pt,ct)>0; + bool warningSoundNeeded = false; + // For each Resource type we store in the int a total consumed value, then + // a vector of units that consume the resource type + std::map>> + resourceIntervalUsage; + + // count up consumables usage for the interval + for (int j = 0; j < getUnitCount(); ++j) { + Unit *unit = getUnit(j); + if (unit->isOperative() == true) { + for (int k = 0; k < unit->getType()->getCostCount(); ++k) { + const Resource *resource = unit->getType()->getCost(k); + if (resource->getType() == rtApply && + resource->getType()->getClass() == rcConsumable && + resource->getAmount() != 0) { + if (resourceIntervalUsage.find(resource->getType()) == + resourceIntervalUsage.end()) { + resourceIntervalUsage[resource->getType()] = + make_pair>(0, std::vector()); + } + // Negative cost means accumulate the resource type + resourceIntervalUsage[resource->getType()].first += + -resource->getAmount(); + + // If the cost > 0 then the unit is a consumer + if (resource->getAmount() > 0) { + resourceIntervalUsage[resource->getType()].second.push_back(unit); + } + } + } + } + } + + // Apply consumable resource usage + if (resourceIntervalUsage.empty() == false) { + for (std::map>>::iterator iter = + resourceIntervalUsage.begin(); + iter != resourceIntervalUsage.end(); ++iter) { + // Apply resource type usage to faction resource store + const ResourceType *rt = iter->first; + int resourceTypeUsage = iter->second.first; + incResourceAmount(rt, resourceTypeUsage); + + if (rt->getClass() == rcConsumable) { + const Resource *r = getResource(rt); + if (r->getBalance() * 5 + r->getAmount() < 0 && r->getAmount() >= 0) { + // warning for player and team( if shared resources or control ) + bool sharedTeamResources = world->getGame()->isFlagType1BitEnabled( + ft1_allow_shared_team_resources); + bool sharedTeamUnits = world->getGame()->isFlagType1BitEnabled( + ft1_allow_shared_team_units); + bool isTeam = (this->getTeam() == world->getThisTeamIndex()); + + if (this->getIndex() == world->getThisFactionIndex() || + (isTeam && (sharedTeamResources || sharedTeamUnits))) { + warningSoundNeeded = true; + } + } + } + + // Check if we have any unit consumers + if (getResource(rt)->getAmount() < 0) { + resetResourceAmount(rt); + + // Apply consequences to consumer units of this resource type + std::vector &resourceConsumers = iter->second.second; + + for (int i = 0; i < (int)resourceConsumers.size(); ++i) { + Unit *unit = resourceConsumers[i]; + + // decrease unit hp + if (scriptManager->getPlayerModifiers(this->index) + ->getConsumeEnabled() == true) { + bool decHpResult = unit->decHp( + unit->getType()->getTotalMaxHp(unit->getTotalUpgrade()) / 3); + if (decHpResult) { + unit->setCauseOfDeath(ucodStarvedResource); + world->getStats()->die( + unit->getFactionIndex(), + unit->getType()->getCountUnitDeathInStats()); + scriptManager->onUnitDied(unit); + } + StaticSound *sound = static_cast( + unit->getType()->getFirstStOfClass(scDie)) + ->getSound(); + if (sound != NULL && (thisFaction == true || + world->showWorldForPlayer( + world->getThisTeamIndex()) == true)) { + SoundRenderer::getInstance().playFx(sound); + } + } + } + } + } + } + return warningSoundNeeded; +} + +int Faction::getAmountOfProducable(const ProducibleType *pt, + const CommandType *ct) { + assert(pt != NULL); + + bool ignoreResourceCosts = false; + if (ct != NULL && ct->getClass() == ccMorph) { + const MorphCommandType *mct = dynamic_cast(ct); + if (mct != NULL) { + ignoreResourceCosts = mct->getIgnoreResourceRequirements(); + } + // printf("Checking costs = %d for + // commandtype:\n%s\n",ignoreResourceCosts,mct->getDesc(NULL).c_str()); + } + + int maxAmount = INT_MAX; + if (ignoreResourceCosts == false) { + // for each unit cost check if enough resources + for (int i = 0; i < pt->getCostCount(); ++i) { + const ResourceType *rt = pt->getCost(i)->getType(); + int cost = pt->getCost(i)->getAmount(); + if (cost > 0) { + int available = getResource(rt)->getAmount(); + int possibleCount = available / cost; + if (maxAmount > possibleCount) + maxAmount = possibleCount; + if (maxAmount == 0) { + break; + } + } + } + } + + return maxAmount; +} + +bool Faction::checkCosts(const ProducibleType *pt, const CommandType *ct) { + return getAmountOfProducable(pt, ct) > 0; } // ================== diplomacy ================== bool Faction::isAlly(const Faction *faction) { - assert(faction != NULL); - return (teamIndex == faction->getTeam() || - faction->getTeam() == GameConstants::maxPlayers -1 + fpt_Observer); + assert(faction != NULL); + return (teamIndex == faction->getTeam() || + faction->getTeam() == GameConstants::maxPlayers - 1 + fpt_Observer); } // ================== misc ================== void Faction::incResourceAmount(const ResourceType *rt, int amount) { - if (world != NULL && world->getGame() != NULL - && world->getGame()->isFlagType1BitEnabled( - ft1_allow_shared_team_resources) == true) { - for(int i=0; i < (int)resources.size(); ++i) { - Resource *r= &resources[i]; - if(r->getType()==rt) { - r->setAmount(r->getAmount()+amount); - if(r->getType()->getClass() != rcStatic && (getResource(rt,false)->getAmount()+amount)>getStoreAmount(rt,false)) { - r->setAmount(getStoreAmount(rt,false)-(getResource(rt,false)->getAmount()-r->getAmount())); - } - return; - } - } - } else { - for(int i=0; i < (int)resources.size(); ++i) { - Resource *r= &resources[i]; - if(r->getType()==rt) { - r->setAmount(r->getAmount()+amount); - if(r->getType()->getClass() != rcStatic && r->getAmount()>getStoreAmount(rt)) { - r->setAmount(getStoreAmount(rt)); - } - return; - } - } - } - assert(false); -} - -void Faction::setResourceBalance(const ResourceType *rt, int balance){ - for(int i=0; i < (int)resources.size(); ++i){ - Resource *r= &resources[i]; - if(r->getType()==rt){ - r->setBalance(balance); - return; - } - } - assert(false); + if (world != NULL && world->getGame() != NULL && + world->getGame()->isFlagType1BitEnabled( + ft1_allow_shared_team_resources) == true) { + for (int i = 0; i < (int)resources.size(); ++i) { + Resource *r = &resources[i]; + if (r->getType() == rt) { + r->setAmount(r->getAmount() + amount); + if (r->getType()->getClass() != rcStatic && + (getResource(rt, false)->getAmount() + amount) > + getStoreAmount(rt, false)) { + r->setAmount(getStoreAmount(rt, false) - + (getResource(rt, false)->getAmount() - r->getAmount())); + } + return; + } + } + } else { + for (int i = 0; i < (int)resources.size(); ++i) { + Resource *r = &resources[i]; + if (r->getType() == rt) { + r->setAmount(r->getAmount() + amount); + if (r->getType()->getClass() != rcStatic && + r->getAmount() > getStoreAmount(rt)) { + r->setAmount(getStoreAmount(rt)); + } + return; + } + } + } + assert(false); +} + +void Faction::setResourceBalance(const ResourceType *rt, int balance) { + for (int i = 0; i < (int)resources.size(); ++i) { + Resource *r = &resources[i]; + if (r->getType() == rt) { + r->setBalance(balance); + return; + } + } + assert(false); } Unit *Faction::findUnit(int id) const { - UnitMap::const_iterator itFound = unitMap.find(id); - if(itFound == unitMap.end()) { - return NULL; - } - return itFound->second; + UnitMap::const_iterator itFound = unitMap.find(id); + if (itFound == unitMap.end()) { + return NULL; + } + return itFound->second; } void Faction::addUnit(Unit *unit) { - MutexSafeWrapper safeMutex(unitsMutex,string(__FILE__) + "_" + intToStr(__LINE__)); - units.push_back(unit); - unitMap[unit->getId()] = unit; + MutexSafeWrapper safeMutex(unitsMutex, + string(__FILE__) + "_" + intToStr(__LINE__)); + units.push_back(unit); + unitMap[unit->getId()] = unit; } -void Faction::removeUnit(Unit *unit){ - MutexSafeWrapper safeMutex(unitsMutex,string(__FILE__) + "_" + intToStr(__LINE__)); +void Faction::removeUnit(Unit *unit) { + MutexSafeWrapper safeMutex(unitsMutex, + string(__FILE__) + "_" + intToStr(__LINE__)); - assert(units.size()==unitMap.size()); + assert(units.size() == unitMap.size()); - int unitId = unit->getId(); - for(int i=0; i < (int)units.size(); ++i) { - if(units[i]->getId() == unitId) { - units.erase(units.begin()+i); - unitMap.erase(unitId); - assert(units.size() == unitMap.size()); - return; - } - } + int unitId = unit->getId(); + for (int i = 0; i < (int)units.size(); ++i) { + if (units[i]->getId() == unitId) { + units.erase(units.begin() + i); + unitMap.erase(unitId); + assert(units.size() == unitMap.size()); + return; + } + } - throw megaglest_runtime_error("Could not remove unit from faction!"); - //assert(false); + throw megaglest_runtime_error("Could not remove unit from faction!"); + // assert(false); } void Faction::addStore(const UnitType *unitType) { - assert(unitType != NULL); - for(int newUnitStoredResourceIndex = 0; - newUnitStoredResourceIndex < unitType->getStoredResourceCount(); - ++newUnitStoredResourceIndex) { - const Resource *newUnitStoredResource = unitType->getStoredResource(newUnitStoredResourceIndex); - - for(int currentStoredResourceIndex = 0; - currentStoredResourceIndex < (int)store.size(); - ++currentStoredResourceIndex) { - Resource *storedResource= &store[currentStoredResourceIndex]; - - if(storedResource->getType() == newUnitStoredResource->getType()) { - storedResource->setAmount(storedResource->getAmount() + newUnitStoredResource->getAmount()); - } - } - } -} - -void Faction::removeStore(const UnitType *unitType){ - assert(unitType != NULL); - for(int i=0; igetStoredResourceCount(); ++i){ - const Resource *r= unitType->getStoredResource(i); - for(int j=0; j < (int)store.size(); ++j){ - Resource *storedResource= &store[j]; - if(storedResource->getType() == r->getType()){ - storedResource->setAmount(storedResource->getAmount() - r->getAmount()); - } - } - } - limitResourcesToStore(); + assert(unitType != NULL); + for (int newUnitStoredResourceIndex = 0; + newUnitStoredResourceIndex < unitType->getStoredResourceCount(); + ++newUnitStoredResourceIndex) { + const Resource *newUnitStoredResource = + unitType->getStoredResource(newUnitStoredResourceIndex); + + for (int currentStoredResourceIndex = 0; + currentStoredResourceIndex < (int)store.size(); + ++currentStoredResourceIndex) { + Resource *storedResource = &store[currentStoredResourceIndex]; + + if (storedResource->getType() == newUnitStoredResource->getType()) { + storedResource->setAmount(storedResource->getAmount() + + newUnitStoredResource->getAmount()); + } + } + } +} + +void Faction::removeStore(const UnitType *unitType) { + assert(unitType != NULL); + for (int i = 0; i < unitType->getStoredResourceCount(); ++i) { + const Resource *r = unitType->getStoredResource(i); + for (int j = 0; j < (int)store.size(); ++j) { + Resource *storedResource = &store[j]; + if (storedResource->getType() == r->getType()) { + storedResource->setAmount(storedResource->getAmount() - r->getAmount()); + } + } + } + limitResourcesToStore(); } void Faction::limitResourcesToStore() { - if (world != NULL && world->getGame() != NULL - && world->getGame()->isFlagType1BitEnabled( - ft1_allow_shared_team_resources) == true) { - for(int i=0; i < (int)resources.size(); ++i) { - Resource *r= &resources[i]; - const ResourceType *rt= r->getType(); - if(rt->getClass() != rcStatic && (getResource(rt,false)->getAmount())>getStoreAmount(rt,false)) { - r->setAmount(getStoreAmount(rt,false)-(getResource(rt,false)->getAmount()-r->getAmount())); - } - } - } else { - for(int i=0; i < (int)resources.size(); ++i) { - Resource *r= &resources[i]; - Resource *s= &store[i]; - if(r->getType()->getClass() != rcStatic && r->getAmount()>s->getAmount()) { - r->setAmount(s->getAmount()); - } - } - } -} - -void Faction::resetResourceAmount(const ResourceType *rt){ - for(int i=0; i < (int)resources.size(); ++i){ - if(resources[i].getType()==rt){ - resources[i].setAmount(0); - return; - } - } - assert(false); -} - -bool Faction::isResourceTargetInCache(const Vec2i &pos, bool incrementUseCounter) { - bool result = false; - - if(cachingDisabled == false) { - if(cacheResourceTargetList.empty() == false) { - std::map::iterator iter = cacheResourceTargetList.find(pos); - - result = (iter != cacheResourceTargetList.end()); - if(result == true && incrementUseCounter == true) { - iter->second++; - } - } - } - - return result; -} - -void Faction::addResourceTargetToCache(const Vec2i &pos,bool incrementUseCounter) { - if(cachingDisabled == false) { - - bool duplicateEntry = isResourceTargetInCache(pos,incrementUseCounter); - //bool duplicateEntry = false; - - if(duplicateEntry == false) { - cacheResourceTargetList[pos] = 1; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"[addResourceTargetToCache] pos [%s]cacheResourceTargetList.size() [" MG_SIZE_T_SPECIFIER "]", - pos.getString().c_str(),cacheResourceTargetList.size()); - - //unit->logSynchData(szBuf); - SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"----------------------------------- START [%d] ------------------------------------------------\n",getFrameCount()); - SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"[%s::%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"%s\n",szBuf); - SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"------------------------------------ END [%d] -------------------------------------------------\n",getFrameCount()); - } - } - } + if (world != NULL && world->getGame() != NULL && + world->getGame()->isFlagType1BitEnabled( + ft1_allow_shared_team_resources) == true) { + for (int i = 0; i < (int)resources.size(); ++i) { + Resource *r = &resources[i]; + const ResourceType *rt = r->getType(); + if (rt->getClass() != rcStatic && + (getResource(rt, false)->getAmount()) > getStoreAmount(rt, false)) { + r->setAmount(getStoreAmount(rt, false) - + (getResource(rt, false)->getAmount() - r->getAmount())); + } + } + } else { + for (int i = 0; i < (int)resources.size(); ++i) { + Resource *r = &resources[i]; + Resource *s = &store[i]; + if (r->getType()->getClass() != rcStatic && + r->getAmount() > s->getAmount()) { + r->setAmount(s->getAmount()); + } + } + } } -void Faction::removeResourceTargetFromCache(const Vec2i &pos) { - if(cachingDisabled == false) { - if(cacheResourceTargetList.empty() == false) { - std::map::iterator iter = cacheResourceTargetList.find(pos); +void Faction::resetResourceAmount(const ResourceType *rt) { + for (int i = 0; i < (int)resources.size(); ++i) { + if (resources[i].getType() == rt) { + resources[i].setAmount(0); + return; + } + } + assert(false); +} - if(iter != cacheResourceTargetList.end()) { - cacheResourceTargetList.erase(pos); +bool Faction::isResourceTargetInCache(const Vec2i &pos, + bool incrementUseCounter) { + bool result = false; - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"[removeResourceTargetFromCache] pos [%s]cacheResourceTargetList.size() [" MG_SIZE_T_SPECIFIER "]", - pos.getString().c_str(),cacheResourceTargetList.size()); + if (cachingDisabled == false) { + if (cacheResourceTargetList.empty() == false) { + std::map::iterator iter = cacheResourceTargetList.find(pos); - //unit->logSynchData(szBuf); - SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"----------------------------------- START [%d] ------------------------------------------------\n",getFrameCount()); - SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"[%s::%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"%s\n",szBuf); - SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"------------------------------------ END [%d] -------------------------------------------------\n",getFrameCount()); - } - } - } - } + result = (iter != cacheResourceTargetList.end()); + if (result == true && incrementUseCounter == true) { + iter->second++; + } + } + } + + return result; +} + +void Faction::addResourceTargetToCache(const Vec2i &pos, + bool incrementUseCounter) { + if (cachingDisabled == false) { + + bool duplicateEntry = isResourceTargetInCache(pos, incrementUseCounter); + // bool duplicateEntry = false; + + if (duplicateEntry == false) { + cacheResourceTargetList[pos] = 1; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "[addResourceTargetToCache] pos " + "[%s]cacheResourceTargetList.size() [" MG_SIZE_T_SPECIFIER "]", + pos.getString().c_str(), cacheResourceTargetList.size()); + + // unit->logSynchData(szBuf); + SystemFlags::OutputDebug( + SystemFlags::debugWorldSynch, + "----------------------------------- START [%d] " + "------------------------------------------------\n", + getFrameCount()); + SystemFlags::OutputDebug(SystemFlags::debugWorldSynch, "[%s::%d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__); + SystemFlags::OutputDebug(SystemFlags::debugWorldSynch, "%s\n", szBuf); + SystemFlags::OutputDebug( + SystemFlags::debugWorldSynch, + "------------------------------------ END [%d] " + "-------------------------------------------------\n", + getFrameCount()); + } + } + } +} + +void Faction::removeResourceTargetFromCache(const Vec2i &pos) { + if (cachingDisabled == false) { + if (cacheResourceTargetList.empty() == false) { + std::map::iterator iter = cacheResourceTargetList.find(pos); + + if (iter != cacheResourceTargetList.end()) { + cacheResourceTargetList.erase(pos); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "[removeResourceTargetFromCache] pos " + "[%s]cacheResourceTargetList.size() [" MG_SIZE_T_SPECIFIER + "]", + pos.getString().c_str(), cacheResourceTargetList.size()); + + // unit->logSynchData(szBuf); + SystemFlags::OutputDebug( + SystemFlags::debugWorldSynch, + "----------------------------------- START [%d] " + "------------------------------------------------\n", + getFrameCount()); + SystemFlags::OutputDebug( + SystemFlags::debugWorldSynch, "[%s::%d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __LINE__); + SystemFlags::OutputDebug(SystemFlags::debugWorldSynch, "%s\n", szBuf); + SystemFlags::OutputDebug( + SystemFlags::debugWorldSynch, + "------------------------------------ END [%d] " + "-------------------------------------------------\n", + getFrameCount()); + } + } + } + } } void Faction::addCloseResourceTargetToCache(const Vec2i &pos) { - if(cachingDisabled == false) { - if(cachedCloseResourceTargetLookupList.find(pos) == cachedCloseResourceTargetLookupList.end()) { - const Map *map = world->getMap(); - const int harvestDistance = 5; - - for(int j = -harvestDistance; j <= harvestDistance; ++j) { - for(int k = -harvestDistance; k <= harvestDistance; ++k) { - Vec2i newPos = pos + Vec2i(j,k); - if(isResourceTargetInCache(newPos) == false) { - if(map->isInside(newPos.x, newPos.y)) { - Resource *r = map->getSurfaceCell(map->toSurfCoords(newPos))->getResource(); - if(r != NULL) { - addResourceTargetToCache(newPos); - //cacheResourceTargetList[newPos] = 1; - } - } - } - } - } - - cachedCloseResourceTargetLookupList[pos] = true; - } - } -} - -Vec2i Faction::getClosestResourceTypeTargetFromCache(Unit *unit, const ResourceType *type, int frameIndex) { - Vec2i result(-1); - - if(cachingDisabled == false) { - if(cacheResourceTargetList.empty() == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"cacheResourceTargetList.size() [" MG_SIZE_T_SPECIFIER "]",cacheResourceTargetList.size()); - - if(frameIndex < 0) { - unit->logSynchData(__FILE__,__LINE__,szBuf); - } - else { - unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); - } - } - - - std::vector deleteList; - - const int harvestDistance = 5; - const Map *map = world->getMap(); - Vec2i pos = unit->getPos(); - - bool foundCloseResource = false; - // First look immediately around the unit's position - - // 0 means start looking leftbottom to top right -// if(Thread::isCurrentThreadMainThread() == false) { -// throw megaglest_runtime_error("#1 Invalid access to Faction random from outside main thread current id = " + -// intToStr(Thread::getCurrentThreadId()) + " main = " + intToStr(Thread::getMainThreadId())); -// } - int tryRadius = random.randRange(0,1); - //int tryRadius = unit->getRandom(true)->randRange(0,1); - //int tryRadius = 0; - if(tryRadius == 0) { - for(int j = -harvestDistance; j <= harvestDistance && foundCloseResource == false; ++j) { - for(int k = -harvestDistance; k <= harvestDistance && foundCloseResource == false; ++k) { - Vec2i newPos = pos + Vec2i(j,k); - if(map->isInside(newPos) == true && isResourceTargetInCache(newPos) == false) { - const SurfaceCell *sc = map->getSurfaceCell(map->toSurfCoords(newPos)); - if( sc != NULL && sc->getResource() != NULL) { - const Resource *resource = sc->getResource(); - if(resource->getType() != NULL && resource->getType() == type) { - if(result.x < 0 || unit->getPos().dist(newPos) < unit->getPos().dist(result)) { - if(unit->isBadHarvestPos(newPos) == false) { - result = newPos; - foundCloseResource = true; - break; - } - } - } - } - else { - deleteList.push_back(newPos); - } - } - } - } - } - // start looking topright to leftbottom - else { - for(int j = harvestDistance; j >= -harvestDistance && foundCloseResource == false; --j) { - for(int k = harvestDistance; k >= -harvestDistance && foundCloseResource == false; --k) { - Vec2i newPos = pos + Vec2i(j,k); - if(map->isInside(newPos) == true && isResourceTargetInCache(newPos) == false) { - const SurfaceCell *sc = map->getSurfaceCell(map->toSurfCoords(newPos)); - if( sc != NULL && sc->getResource() != NULL) { - const Resource *resource = sc->getResource(); - if(resource->getType() != NULL && resource->getType() == type) { - if(result.x < 0 || unit->getPos().dist(newPos) < unit->getPos().dist(result)) { - if(unit->isBadHarvestPos(newPos) == false) { - result = newPos; - foundCloseResource = true; - break; - } - } - } - } - else { - deleteList.push_back(newPos); - } - } - } - } - } - - if(foundCloseResource == false) { - // Now check the whole cache - for(std::map::iterator iter = cacheResourceTargetList.begin(); - iter != cacheResourceTargetList.end() && foundCloseResource == false; - ++iter) { - const Vec2i &cache = iter->first; - if(map->isInside(cache) == true) { - const SurfaceCell *sc = map->getSurfaceCell(map->toSurfCoords(cache)); - if( sc != NULL && sc->getResource() != NULL) { - const Resource *resource = sc->getResource(); - if(resource->getType() != NULL && resource->getType() == type) { - if(result.x < 0 || unit->getPos().dist(cache) < unit->getPos().dist(result)) { - if(unit->isBadHarvestPos(cache) == false) { - result = cache; - // Close enough to our position, no more looking - if(unit->getPos().dist(result) <= (harvestDistance * 2)) { - foundCloseResource = true; - break; - } - } - } - } - } - else { - deleteList.push_back(cache); - } - } - else { - deleteList.push_back(cache); - } - } - } - - if(deleteList.empty() == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"[cleaning old resource targets] deleteList.size() [" MG_SIZE_T_SPECIFIER "] cacheResourceTargetList.size() [" MG_SIZE_T_SPECIFIER "] result [%s]", - deleteList.size(),cacheResourceTargetList.size(),result.getString().c_str()); - - if(frameIndex < 0) { - unit->logSynchData(__FILE__,__LINE__,szBuf); - } - else { - unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); - } - } - - cleanupResourceTypeTargetCache(&deleteList,frameIndex); - } - } - } - - return result; -} - -// CANNOT MODIFY the cache here since the AI calls this method and the AI is only controlled -// by the server for network games and it would cause out of synch since clients do not call -// this method so DO NOT modify the cache here! -Vec2i Faction::getClosestResourceTypeTargetFromCache(const Vec2i &pos, const ResourceType *type) { - Vec2i result(-1); - if(cachingDisabled == false) { - if(cacheResourceTargetList.empty() == false) { - //std::vector deleteList; - - const int harvestDistance = 5; - const Map *map = world->getMap(); - - bool foundCloseResource = false; - - // 0 means start looking leftbottom to top right -// if(Thread::isCurrentThreadMainThread() == false) { -// throw megaglest_runtime_error("#2 Invalid access to Faction random from outside main thread current id = " + -// intToStr(Thread::getCurrentThreadId()) + " main = " + intToStr(Thread::getMainThreadId())); -// } - int tryRadius = random.randRange(0,1); - if(tryRadius == 0) { - // First look immediately around the given position - for(int j = -harvestDistance; j <= harvestDistance && foundCloseResource == false; ++j) { - for(int k = -harvestDistance; k <= harvestDistance && foundCloseResource == false; ++k) { - Vec2i newPos = pos + Vec2i(j,k); - if(map->isInside(newPos) == true && isResourceTargetInCache(newPos) == false) { - const SurfaceCell *sc = map->getSurfaceCell(map->toSurfCoords(newPos)); - if( sc != NULL && sc->getResource() != NULL) { - const Resource *resource = sc->getResource(); - if(resource->getType() != NULL && resource->getType() == type) { - if(result.x < 0 || pos.dist(newPos) < pos.dist(result)) { - result = newPos; - foundCloseResource = true; - break; - } - } - } - //else { - // deleteList.push_back(newPos); - //} - } - } - } - } - else { - // First look immediately around the given position - for(int j = harvestDistance; j >= -harvestDistance && foundCloseResource == false; --j) { - for(int k = harvestDistance; k >= -harvestDistance && foundCloseResource == false; --k) { - Vec2i newPos = pos + Vec2i(j,k); - if(map->isInside(newPos) == true && isResourceTargetInCache(newPos) == false) { - const SurfaceCell *sc = map->getSurfaceCell(map->toSurfCoords(newPos)); - if( sc != NULL && sc->getResource() != NULL) { - const Resource *resource = sc->getResource(); - if(resource->getType() != NULL && resource->getType() == type) { - if(result.x < 0 || pos.dist(newPos) < pos.dist(result)) { - result = newPos; - foundCloseResource = true; - break; - } - } - } - //else { - // deleteList.push_back(newPos); - //} - } - } - } - } - - if(foundCloseResource == false) { - // Now check the whole cache - for(std::map::iterator iter = cacheResourceTargetList.begin(); - iter != cacheResourceTargetList.end() && foundCloseResource == false; - ++iter) { - const Vec2i &cache = iter->first; - if(map->isInside(cache) == true) { - const SurfaceCell *sc = map->getSurfaceCell(map->toSurfCoords(cache)); - if( sc != NULL && sc->getResource() != NULL) { - const Resource *resource = sc->getResource(); - if(resource->getType() != NULL && resource->getType() == type) { - if(result.x < 0 || pos.dist(cache) < pos.dist(result)) { - result = cache; - // Close enough to our position, no more looking - if(pos.dist(result) <= (harvestDistance * 2)) { - foundCloseResource = true; - break; - } - } - } - } - //else { - // deleteList.push_back(cache); - //} - } - //else { - // deleteList.push_back(cache); - //} - } - } - } - } - - return result; -} - -void Faction::cleanupResourceTypeTargetCache(std::vector *deleteListPtr,int frameIndex) { - if(cachingDisabled == false) { - if(cacheResourceTargetList.empty() == false) { - const int cleanupInterval = (GameConstants::updateFps * 5); - bool needToCleanup = (getFrameCount() % cleanupInterval == 0); - - if(deleteListPtr != NULL || needToCleanup == true) { - std::vector deleteList; - - if(deleteListPtr != NULL) { - deleteList = *deleteListPtr; - } - else { - for(std::map::iterator iter = cacheResourceTargetList.begin(); - iter != cacheResourceTargetList.end(); ++iter) { - const Vec2i &cache = iter->first; - - if(world->getMap()->getSurfaceCell(world->getMap()->toSurfCoords(cache)) != NULL) { - Resource *resource = world->getMap()->getSurfaceCell(world->getMap()->toSurfCoords(cache))->getResource(); - if(resource == NULL) { - deleteList.push_back(cache); - } - } - else { - deleteList.push_back(cache); - } - } - } - - if(deleteList.empty() == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true) { - char szBuf[8095]=""; - snprintf(szBuf,8095,"[cleaning old resource targets] deleteList.size() [" MG_SIZE_T_SPECIFIER "] cacheResourceTargetList.size() [" MG_SIZE_T_SPECIFIER "], needToCleanup [%d]", - deleteList.size(),cacheResourceTargetList.size(),needToCleanup); - //unit->logSynchData(szBuf); - - char szBuf1[8096]=""; - snprintf(szBuf1,8096,"----------------------------------- START [%d] ------------------------------------------------\n",getFrameCount()); - string logDataText = szBuf1; - - snprintf(szBuf1,8096,"[%s::%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - logDataText += szBuf1; - - snprintf(szBuf1,8096,"%s\n",szBuf); - logDataText += szBuf1; - - snprintf(szBuf1,8096,"------------------------------------ END [%d] -------------------------------------------------\n",getFrameCount()); - logDataText += szBuf1; - - if(frameIndex < 0) { - SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"%s",logDataText.c_str()); - } - else { - addWorldSynchThreadedLogList(logDataText); - } - } - - for(int i = 0; i < (int)deleteList.size(); ++i) { - Vec2i &cache = deleteList[i]; - cacheResourceTargetList.erase(cache); - } - } - } - } - } -} - -//std::vector Faction::findCachedPath(const Vec2i &target, Unit *unit) { + if (cachingDisabled == false) { + if (cachedCloseResourceTargetLookupList.find(pos) == + cachedCloseResourceTargetLookupList.end()) { + const Map *map = world->getMap(); + const int harvestDistance = 5; + + for (int j = -harvestDistance; j <= harvestDistance; ++j) { + for (int k = -harvestDistance; k <= harvestDistance; ++k) { + Vec2i newPos = pos + Vec2i(j, k); + if (isResourceTargetInCache(newPos) == false) { + if (map->isInside(newPos.x, newPos.y)) { + Resource *r = + map->getSurfaceCell(map->toSurfCoords(newPos))->getResource(); + if (r != NULL) { + addResourceTargetToCache(newPos); + // cacheResourceTargetList[newPos] = 1; + } + } + } + } + } + + cachedCloseResourceTargetLookupList[pos] = true; + } + } +} + +Vec2i Faction::getClosestResourceTypeTargetFromCache(Unit *unit, + const ResourceType *type, + int frameIndex) { + Vec2i result(-1); + + if (cachingDisabled == false) { + if (cacheResourceTargetList.empty() == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "cacheResourceTargetList.size() [" MG_SIZE_T_SPECIFIER "]", + cacheResourceTargetList.size()); + + if (frameIndex < 0) { + unit->logSynchData(__FILE__, __LINE__, szBuf); + } else { + unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf); + } + } + + std::vector deleteList; + + const int harvestDistance = 5; + const Map *map = world->getMap(); + Vec2i pos = unit->getPos(); + + bool foundCloseResource = false; + // First look immediately around the unit's position + + // 0 means start looking leftbottom to top right + // if(Thread::isCurrentThreadMainThread() == false) + //{ throw megaglest_runtime_error("#1 + //Invalid access to Faction random from outside main thread current id = " + // + intToStr(Thread::getCurrentThreadId()) + //+ " main = " + intToStr(Thread::getMainThreadId())); + // } + int tryRadius = random.randRange(0, 1); + // int tryRadius = unit->getRandom(true)->randRange(0,1); + // int tryRadius = 0; + if (tryRadius == 0) { + for (int j = -harvestDistance; + j <= harvestDistance && foundCloseResource == false; ++j) { + for (int k = -harvestDistance; + k <= harvestDistance && foundCloseResource == false; ++k) { + Vec2i newPos = pos + Vec2i(j, k); + if (map->isInside(newPos) == true && + isResourceTargetInCache(newPos) == false) { + const SurfaceCell *sc = + map->getSurfaceCell(map->toSurfCoords(newPos)); + if (sc != NULL && sc->getResource() != NULL) { + const Resource *resource = sc->getResource(); + if (resource->getType() != NULL && + resource->getType() == type) { + if (result.x < 0 || unit->getPos().dist(newPos) < + unit->getPos().dist(result)) { + if (unit->isBadHarvestPos(newPos) == false) { + result = newPos; + foundCloseResource = true; + break; + } + } + } + } else { + deleteList.push_back(newPos); + } + } + } + } + } + // start looking topright to leftbottom + else { + for (int j = harvestDistance; + j >= -harvestDistance && foundCloseResource == false; --j) { + for (int k = harvestDistance; + k >= -harvestDistance && foundCloseResource == false; --k) { + Vec2i newPos = pos + Vec2i(j, k); + if (map->isInside(newPos) == true && + isResourceTargetInCache(newPos) == false) { + const SurfaceCell *sc = + map->getSurfaceCell(map->toSurfCoords(newPos)); + if (sc != NULL && sc->getResource() != NULL) { + const Resource *resource = sc->getResource(); + if (resource->getType() != NULL && + resource->getType() == type) { + if (result.x < 0 || unit->getPos().dist(newPos) < + unit->getPos().dist(result)) { + if (unit->isBadHarvestPos(newPos) == false) { + result = newPos; + foundCloseResource = true; + break; + } + } + } + } else { + deleteList.push_back(newPos); + } + } + } + } + } + + if (foundCloseResource == false) { + // Now check the whole cache + for (std::map::iterator iter = + cacheResourceTargetList.begin(); + iter != cacheResourceTargetList.end() && + foundCloseResource == false; + ++iter) { + const Vec2i &cache = iter->first; + if (map->isInside(cache) == true) { + const SurfaceCell *sc = + map->getSurfaceCell(map->toSurfCoords(cache)); + if (sc != NULL && sc->getResource() != NULL) { + const Resource *resource = sc->getResource(); + if (resource->getType() != NULL && resource->getType() == type) { + if (result.x < 0 || + unit->getPos().dist(cache) < unit->getPos().dist(result)) { + if (unit->isBadHarvestPos(cache) == false) { + result = cache; + // Close enough to our position, no more looking + if (unit->getPos().dist(result) <= (harvestDistance * 2)) { + foundCloseResource = true; + break; + } + } + } + } + } else { + deleteList.push_back(cache); + } + } else { + deleteList.push_back(cache); + } + } + } + + if (deleteList.empty() == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "[cleaning old resource targets] deleteList.size() " + "[" MG_SIZE_T_SPECIFIER + "] cacheResourceTargetList.size() [" MG_SIZE_T_SPECIFIER + "] result [%s]", + deleteList.size(), cacheResourceTargetList.size(), + result.getString().c_str()); + + if (frameIndex < 0) { + unit->logSynchData(__FILE__, __LINE__, szBuf); + } else { + unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf); + } + } + + cleanupResourceTypeTargetCache(&deleteList, frameIndex); + } + } + } + + return result; +} + +// CANNOT MODIFY the cache here since the AI calls this method and the AI is +// only controlled by the server for network games and it would cause out of +// synch since clients do not call this method so DO NOT modify the cache here! +Vec2i Faction::getClosestResourceTypeTargetFromCache(const Vec2i &pos, + const ResourceType *type) { + Vec2i result(-1); + if (cachingDisabled == false) { + if (cacheResourceTargetList.empty() == false) { + // std::vector deleteList; + + const int harvestDistance = 5; + const Map *map = world->getMap(); + + bool foundCloseResource = false; + + // 0 means start looking leftbottom to top right + // if(Thread::isCurrentThreadMainThread() == false) + //{ throw megaglest_runtime_error("#2 + //Invalid access to Faction random from outside main thread current id = " + // + intToStr(Thread::getCurrentThreadId()) + //+ " main = " + intToStr(Thread::getMainThreadId())); + // } + int tryRadius = random.randRange(0, 1); + if (tryRadius == 0) { + // First look immediately around the given position + for (int j = -harvestDistance; + j <= harvestDistance && foundCloseResource == false; ++j) { + for (int k = -harvestDistance; + k <= harvestDistance && foundCloseResource == false; ++k) { + Vec2i newPos = pos + Vec2i(j, k); + if (map->isInside(newPos) == true && + isResourceTargetInCache(newPos) == false) { + const SurfaceCell *sc = + map->getSurfaceCell(map->toSurfCoords(newPos)); + if (sc != NULL && sc->getResource() != NULL) { + const Resource *resource = sc->getResource(); + if (resource->getType() != NULL && + resource->getType() == type) { + if (result.x < 0 || pos.dist(newPos) < pos.dist(result)) { + result = newPos; + foundCloseResource = true; + break; + } + } + } + // else { + // deleteList.push_back(newPos); + // } + } + } + } + } else { + // First look immediately around the given position + for (int j = harvestDistance; + j >= -harvestDistance && foundCloseResource == false; --j) { + for (int k = harvestDistance; + k >= -harvestDistance && foundCloseResource == false; --k) { + Vec2i newPos = pos + Vec2i(j, k); + if (map->isInside(newPos) == true && + isResourceTargetInCache(newPos) == false) { + const SurfaceCell *sc = + map->getSurfaceCell(map->toSurfCoords(newPos)); + if (sc != NULL && sc->getResource() != NULL) { + const Resource *resource = sc->getResource(); + if (resource->getType() != NULL && + resource->getType() == type) { + if (result.x < 0 || pos.dist(newPos) < pos.dist(result)) { + result = newPos; + foundCloseResource = true; + break; + } + } + } + // else { + // deleteList.push_back(newPos); + // } + } + } + } + } + + if (foundCloseResource == false) { + // Now check the whole cache + for (std::map::iterator iter = + cacheResourceTargetList.begin(); + iter != cacheResourceTargetList.end() && + foundCloseResource == false; + ++iter) { + const Vec2i &cache = iter->first; + if (map->isInside(cache) == true) { + const SurfaceCell *sc = + map->getSurfaceCell(map->toSurfCoords(cache)); + if (sc != NULL && sc->getResource() != NULL) { + const Resource *resource = sc->getResource(); + if (resource->getType() != NULL && resource->getType() == type) { + if (result.x < 0 || pos.dist(cache) < pos.dist(result)) { + result = cache; + // Close enough to our position, no more looking + if (pos.dist(result) <= (harvestDistance * 2)) { + foundCloseResource = true; + break; + } + } + } + } + // else { + // deleteList.push_back(cache); + // } + } + // else { + // deleteList.push_back(cache); + // } + } + } + } + } + + return result; +} + +void Faction::cleanupResourceTypeTargetCache(std::vector *deleteListPtr, + int frameIndex) { + if (cachingDisabled == false) { + if (cacheResourceTargetList.empty() == false) { + const int cleanupInterval = (GameConstants::updateFps * 5); + bool needToCleanup = (getFrameCount() % cleanupInterval == 0); + + if (deleteListPtr != NULL || needToCleanup == true) { + std::vector deleteList; + + if (deleteListPtr != NULL) { + deleteList = *deleteListPtr; + } else { + for (std::map::iterator iter = + cacheResourceTargetList.begin(); + iter != cacheResourceTargetList.end(); ++iter) { + const Vec2i &cache = iter->first; + + if (world->getMap()->getSurfaceCell( + world->getMap()->toSurfCoords(cache)) != NULL) { + Resource *resource = + world->getMap() + ->getSurfaceCell(world->getMap()->toSurfCoords(cache)) + ->getResource(); + if (resource == NULL) { + deleteList.push_back(cache); + } + } else { + deleteList.push_back(cache); + } + } + } + + if (deleteList.empty() == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true) { + char szBuf[8095] = ""; + snprintf(szBuf, 8095, + "[cleaning old resource targets] deleteList.size() " + "[" MG_SIZE_T_SPECIFIER + "] cacheResourceTargetList.size() [" MG_SIZE_T_SPECIFIER + "], needToCleanup [%d]", + deleteList.size(), cacheResourceTargetList.size(), + needToCleanup); + // unit->logSynchData(szBuf); + + char szBuf1[8096] = ""; + snprintf(szBuf1, 8096, + "----------------------------------- START [%d] " + "------------------------------------------------\n", + getFrameCount()); + string logDataText = szBuf1; + + snprintf(szBuf1, 8096, "[%s::%d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __LINE__); + logDataText += szBuf1; + + snprintf(szBuf1, 8096, "%s\n", szBuf); + logDataText += szBuf1; + + snprintf(szBuf1, 8096, + "------------------------------------ END [%d] " + "-------------------------------------------------\n", + getFrameCount()); + logDataText += szBuf1; + + if (frameIndex < 0) { + SystemFlags::OutputDebug(SystemFlags::debugWorldSynch, "%s", + logDataText.c_str()); + } else { + addWorldSynchThreadedLogList(logDataText); + } + } + + for (int i = 0; i < (int)deleteList.size(); ++i) { + Vec2i &cache = deleteList[i]; + cacheResourceTargetList.erase(cache); + } + } + } + } + } +} + +// std::vector Faction::findCachedPath(const Vec2i &target, Unit *unit) { // std::vector result; // if(cachingDisabled == false) { -// if(successfulPathFinderTargetList.find(target) == successfulPathFinderTargetList.end()) { -// // Lets find the shortest and most successful path already taken by a +// if(successfulPathFinderTargetList.find(target) == +// successfulPathFinderTargetList.end()) { +// // Lets find the shortest and most successful path +//already taken by a // // similar sized unit // // bool foundCachedPath = false; -// std::vector &cacheList = successfulPathFinderTargetList[target]; -// int unitSize = unit->getType()->getSize(); -// for(int i = 0; i < cacheList.size(); ++i) { -// FactionPathSuccessCache &cache = cacheList[i]; +// std::vector &cacheList = +// successfulPathFinderTargetList[target]; int unitSize = +// unit->getType()->getSize(); for(int i = 0; i < +// cacheList.size(); ++i) { FactionPathSuccessCache &cache = cacheList[i]; // if(cache.unitSize <= unitSize) { -// vector, int> > &pathQueue = cache.pathQueue; +// vector, int> > +//&pathQueue = cache.pathQueue; // -// for(int j = 0; j < pathQueue.size(); ++j) { -// // Now start at the end of the path and see how many nodes -// // until we reach a cell near the unit's current position -// std::pair, int> &path = pathQueue[j]; +// for(int j = 0; j < pathQueue.size(); +//++j) +//{ +// // Now start at the end of the path +//and see how many nodes +// // until we reach a cell near the +//unit's current position +// std::pair, int> &path = pathQueue[j]; // -// for(int k = path.first.size() - 1; k >= 0; --k) { -// if(world->getMap()->canMove(unit, unit->getPos(), path.first[k]) == true) { -// if(foundCachedPath == false) { -// for(int l = k; l < path.first.size(); ++l) { -// result.push_back(path.first[l]); +// for(int k = path.first.size() - 1; k >= +//0; +//--k) { +//if(world->getMap()->canMove(unit, unit->getPos(), path.first[k]) == true) { +// if(foundCachedPath == false) { +// for(int l = k; l < path.first.size(); +//++l) { +//result.push_back(path.first[l]); // } // } // else { -// if(result.size() > (path.first.size() - k)) { -// for(int l = k; l < path.first.size(); ++l) { -// result.push_back(path.first[l]); +// if(result.size() +//> +//(path.first.size() - k)) { +//for(int l = k; l < path.first.size(); ++l) { result.push_back(path.first[l]); // } // } // } -// foundCachedPath = true; +// foundCachedPath +//= true; // // break; // } @@ -1903,101 +2196,119 @@ void Faction::cleanupResourceTypeTargetCache(std::vector *deleteListPtr,i // } // // return result; -//} +// } -//void Faction::addCachedPath(const Vec2i &target, Unit *unit) { +// void Faction::addCachedPath(const Vec2i &target, Unit *unit) { // if(cachingDisabled == false) { -// if(successfulPathFinderTargetList.find(target) == successfulPathFinderTargetList.end()) { -// FactionPathSuccessCache cache; -// cache.unitSize = unit->getType()->getSize(); -// cache.pathQueue.push_back(make_pair, int>(unit->getCurrentTargetPathTaken().second,1)); +// if(successfulPathFinderTargetList.find(target) == +// successfulPathFinderTargetList.end()) { +// FactionPathSuccessCache cache; cache.unitSize = unit->getType()->getSize(); +// cache.pathQueue.push_back(make_pair, +// int>(unit->getCurrentTargetPathTaken().second,1)); // successfulPathFinderTargetList[target].push_back(cache); // } // else { // bool finishedAdd = false; -// std::pair > currentTargetPathTaken = unit->getCurrentTargetPathTaken(); -// std::vector &cacheList = successfulPathFinderTargetList[target]; -// int unitSize = unit->getType()->getSize(); +// std::pair > +//currentTargetPathTaken = unit->getCurrentTargetPathTaken(); +//std::vector &cacheList = +//successfulPathFinderTargetList[target]; int unitSize = +// unit->getType()->getSize(); // -// for(int i = 0; i < cacheList.size() && finishedAdd == false; ++i) { -// FactionPathSuccessCache &cache = cacheList[i]; -// if(cache.unitSize <= unitSize) { -// vector, int> > &pathQueue = cache.pathQueue; +// for(int i = 0; i < cacheList.size() && finishedAdd == +//false; +//++i) { FactionPathSuccessCache &cache = cacheList[i]; +//if(cache.unitSize <= +// unitSize) { vector, int> > +// &pathQueue = cache.pathQueue; // -// for(int j = 0; j < pathQueue.size() && finishedAdd == false; ++j) { -// // Now start at the end of the path and see how many nodes are the same -// std::pair, int> &path = pathQueue[j]; -// int minPathSize = std::min(path.first.size(),currentTargetPathTaken.second.size()); -// int intersectIndex = -1; +// for(int j = 0; j < pathQueue.size() && +// finishedAdd == false; ++j) { +// // Now start at the end of the path +//and +// see how many nodes are the same +// std::pair, int> &path = pathQueue[j]; +// int minPathSize = +// std::min(path.first.size(),currentTargetPathTaken.second.size()); +// int intersectIndex = -1; // -// for(int k = 0; k < minPathSize; ++k) { -// if(path.first[path.first.size() - k - 1] != currentTargetPathTaken.second[currentTargetPathTaken.second.size() - k - 1]) { -// intersectIndex = k; -// break; +// for(int k = 0; k < minPathSize; +//++k) +//{ if(path.first[path.first.size() - +//k - 1] != currentTargetPathTaken.second[currentTargetPathTaken.second.size() - +// k - 1]) { intersectIndex = k; +// break; // } // } // -// // New path is same or longer than old path so replace +// // New path is same or longer than +//old path so replace // // old path with new -// if(intersectIndex + 1 == path.first.size()) { -// path.first = currentTargetPathTaken.second; -// path.second++; -// finishedAdd = true; +// if(intersectIndex + 1 == +// path.first.size()) { path.first = +// currentTargetPathTaken.second; path.second++; finishedAdd = true; // } -// // Old path is same or longer than new path so +// // Old path is same or longer than +//new path so // // do nothing -// else if(intersectIndex + 1 == currentTargetPathTaken.second.size()) { -// path.second++; -// finishedAdd = true; +// else if(intersectIndex + 1 == +// currentTargetPathTaken.second.size()) { +// path.second++; finishedAdd = +// true; // } // } // // // If new path is >= 10 cells add it -// if(finishedAdd == false && currentTargetPathTaken.second.size() >= 10) { -// pathQueue.push_back(make_pair, int>(currentTargetPathTaken.second,1)); +// if(finishedAdd == false && +// currentTargetPathTaken.second.size() >= 10) { +// pathQueue.push_back(make_pair, +// int>(currentTargetPathTaken.second,1)); // } // } // } // } // } -//} +// } void Faction::deletePixels() { - if(factionType != NULL) { - factionType->deletePixels(); - } + if (factionType != NULL) { + factionType->deletePixels(); + } } -//Unit * Faction::findClosestUnitWithSkillClass( const Vec2i &pos,const CommandClass &cmdClass, -// const std::vector &skillClassList, -// const UnitType *unitType) { -// Unit *result = NULL; +// Unit * Faction::findClosestUnitWithSkillClass( const Vec2i &pos,const +// CommandClass &cmdClass, +// const std::vector &skillClassList, +// const +// UnitType *unitType) { Unit *result = NULL; // ///* -// std::map >::iterator iterFind = cacheUnitCommandClassList.find(cmdClass); -// if(iterFind != cacheUnitCommandClassList.end()) { -// for(std::map::iterator iter = iterFind->second.begin(); -// iter != iterFind->second.end(); ++iter) { -// Unit *curUnit = findUnit(iter->second); -// if(curUnit != NULL) { +// std::map >::iterator iterFind = +// cacheUnitCommandClassList.find(cmdClass); if(iterFind != +// cacheUnitCommandClassList.end()) { for(std::map::iterator +// iter = iterFind->second.begin(); iter != +// iterFind->second.end(); ++iter) { Unit *curUnit = +//findUnit(iter->second); if(curUnit != NULL) { // -// const CommandType *cmdType = curUnit->getType()->getFirstCtOfClass(cmdClass); -// bool isUnitPossibleCandidate = (cmdType != NULL); -// if(skillClassList.empty() == false) { -// isUnitPossibleCandidate = false; +// const CommandType *cmdType = +// curUnit->getType()->getFirstCtOfClass(cmdClass); bool +// isUnitPossibleCandidate = (cmdType != NULL); +//if(skillClassList.empty() == false) { isUnitPossibleCandidate = false; // -// for(int j = 0; j < skillClassList.size(); ++j) { -// SkillClass skValue = skillClassList[j]; -// if(curUnit->getCurrSkill()->getClass() == skValue) { -// isUnitPossibleCandidate = true; -// break; +// for(int j = 0; j < skillClassList.size(); +//++j) { SkillClass skValue = +//skillClassList[j]; if(curUnit->getCurrSkill()->getClass() == skValue) { +// isUnitPossibleCandidate = true; +// break; // } // } // } // // if(isUnitPossibleCandidate == true) { -// if(result == NULL || curUnit->getPos().dist(pos) < result->getPos().dist(pos)) { -// result = curUnit; +// if(result == NULL || +//curUnit->getPos().dist(pos) +//< result->getPos().dist(pos)) { result = +//curUnit; // } // } // } @@ -2011,35 +2322,38 @@ void Faction::deletePixels() { // // bool isUnitPossibleCandidate = false; // -// const CommandType *cmdType = curUnit->getType()->getFirstCtOfClass(cmdClass); -// if(cmdType != NULL) { -// const RepairCommandType *rct = dynamic_cast(cmdType); -// if(rct != NULL && rct->isRepairableUnitType(unitType)) { -// isUnitPossibleCandidate = true; +// const CommandType *cmdType = +// curUnit->getType()->getFirstCtOfClass(cmdClass); if(cmdType != +// NULL) { const RepairCommandType *rct = +// dynamic_cast(cmdType); if(rct != NULL && +//rct->isRepairableUnitType(unitType)) +//{ isUnitPossibleCandidate = true; // } // } // else { // isUnitPossibleCandidate = false; // } // -// if(isUnitPossibleCandidate == true && skillClassList.empty() == false) { -// isUnitPossibleCandidate = false; +// if(isUnitPossibleCandidate == true && +//skillClassList.empty() +//== false) { isUnitPossibleCandidate = false; // -// for(int j = 0; j < (int)skillClassList.size(); ++j) { -// SkillClass skValue = skillClassList[j]; -// if(curUnit->getCurrSkill()->getClass() == skValue) { -// isUnitPossibleCandidate = true; -// break; +// for(int j = 0; j < (int)skillClassList.size(); +//++j) { SkillClass skValue = +//skillClassList[j]; if(curUnit->getCurrSkill()->getClass() == skValue) { +// isUnitPossibleCandidate = true; break; // } // } // } // // // if(isUnitPossibleCandidate == true) { -// //cacheUnitCommandClassList[cmdClass][curUnit->getId()] = curUnit->getId(); +// //cacheUnitCommandClassList[cmdClass][curUnit->getId()] +//= curUnit->getId(); // -// if(result == NULL || curUnit->getPos().dist(pos) < result->getPos().dist(pos)) { -// result = curUnit; +// if(result == NULL || curUnit->getPos().dist(pos) +//< result->getPos().dist(pos)) { result = +// curUnit; // } // } // } @@ -2048,523 +2362,596 @@ void Faction::deletePixels() { //} int Faction::getFrameCount() { - int frameCount = 0; - const Game *game = Renderer::getInstance().getGame(); - if(game != NULL && game->getWorld() != NULL) { - frameCount = game->getWorld()->getFrameCount(); - } - - return frameCount; -} - -const SwitchTeamVote * Faction::getFirstSwitchTeamVote() const { - const SwitchTeamVote *vote = NULL; - if(switchTeamVotes.empty() == false) { - for(std::map::const_iterator iterMap = switchTeamVotes.begin(); - iterMap != switchTeamVotes.end(); ++iterMap) { - const SwitchTeamVote &curVote = iterMap->second; - if(curVote.voted == false) { - vote = &curVote; - break; - } - } - } + int frameCount = 0; + const Game *game = Renderer::getInstance().getGame(); + if (game != NULL && game->getWorld() != NULL) { + frameCount = game->getWorld()->getFrameCount(); + } + + return frameCount; +} + +const SwitchTeamVote *Faction::getFirstSwitchTeamVote() const { + const SwitchTeamVote *vote = NULL; + if (switchTeamVotes.empty() == false) { + for (std::map::const_iterator iterMap = + switchTeamVotes.begin(); + iterMap != switchTeamVotes.end(); ++iterMap) { + const SwitchTeamVote &curVote = iterMap->second; + if (curVote.voted == false) { + vote = &curVote; + break; + } + } + } - return vote; + return vote; } -SwitchTeamVote * Faction::getSwitchTeamVote(int factionIndex) { - SwitchTeamVote *vote = NULL; - if(switchTeamVotes.find(factionIndex) != switchTeamVotes.end()) { - vote = &switchTeamVotes[factionIndex]; - } +SwitchTeamVote *Faction::getSwitchTeamVote(int factionIndex) { + SwitchTeamVote *vote = NULL; + if (switchTeamVotes.find(factionIndex) != switchTeamVotes.end()) { + vote = &switchTeamVotes[factionIndex]; + } - return vote; + return vote; } void Faction::setSwitchTeamVote(SwitchTeamVote &vote) { - switchTeamVotes[vote.factionIndex] = vote; -} - -bool Faction::canCreateUnit(const UnitType *ut, bool checkBuild, bool checkProduce, bool checkMorph) const { - // Now check that at least 1 other unit can produce, build or morph this unit - bool foundUnit = false; - for(int l = 0; l < this->getUnitCount() && foundUnit == false; ++l) { - const UnitType *unitType2 = this->getUnit(l)->getType(); - - for(int j = 0; j < unitType2->getCommandTypeCount() && foundUnit == false; ++j) { - const CommandType *cmdType = unitType2->getCommandType(j); - if(cmdType != NULL) { - // Check if this is a produce command - if(checkProduce == true && cmdType->getClass() == ccProduce) { - const ProduceCommandType *produce = dynamic_cast(cmdType); - if(produce != NULL) { - const UnitType *produceUnit = produce->getProducedUnit(); - - if( produceUnit != NULL && - ut->getId() != unitType2->getId() && - ut->getName(false) == produceUnit->getName(false)) { - foundUnit = true; - break; - } - } - } - // Check if this is a build command - else if(checkBuild == true && cmdType->getClass() == ccBuild) { - const BuildCommandType *build = dynamic_cast(cmdType); - if(build != NULL) { - for(int k = 0; k < build->getBuildingCount() && foundUnit == false; ++k) { - const UnitType *buildUnit = build->getBuilding(k); - - if( buildUnit != NULL && - ut->getId() != unitType2->getId() && - ut->getName(false) == buildUnit->getName(false)) { - foundUnit = true; - break; - } - } - } - } - // Check if this is a morph command - else if(checkMorph == true && cmdType->getClass() == ccMorph) { - const MorphCommandType *morph = dynamic_cast(cmdType); - if(morph != NULL) { - const UnitType *morphUnit = morph->getMorphUnit(); - - if( morphUnit != NULL && - ut->getId() != unitType2->getId() && - ut->getName(false) == morphUnit->getName(false)) { - foundUnit = true; - break; - } - } - } - } - } - } - - return foundUnit; + switchTeamVotes[vote.factionIndex] = vote; +} + +bool Faction::canCreateUnit(const UnitType *ut, bool checkBuild, + bool checkProduce, bool checkMorph) const { + // Now check that at least 1 other unit can produce, build or morph this unit + bool foundUnit = false; + for (int l = 0; l < this->getUnitCount() && foundUnit == false; ++l) { + const UnitType *unitType2 = this->getUnit(l)->getType(); + + for (int j = 0; j < unitType2->getCommandTypeCount() && foundUnit == false; + ++j) { + const CommandType *cmdType = unitType2->getCommandType(j); + if (cmdType != NULL) { + // Check if this is a produce command + if (checkProduce == true && cmdType->getClass() == ccProduce) { + const ProduceCommandType *produce = + dynamic_cast(cmdType); + if (produce != NULL) { + const UnitType *produceUnit = produce->getProducedUnit(); + + if (produceUnit != NULL && ut->getId() != unitType2->getId() && + ut->getName(false) == produceUnit->getName(false)) { + foundUnit = true; + break; + } + } + } + // Check if this is a build command + else if (checkBuild == true && cmdType->getClass() == ccBuild) { + const BuildCommandType *build = + dynamic_cast(cmdType); + if (build != NULL) { + for (int k = 0; k < build->getBuildingCount() && foundUnit == false; + ++k) { + const UnitType *buildUnit = build->getBuilding(k); + + if (buildUnit != NULL && ut->getId() != unitType2->getId() && + ut->getName(false) == buildUnit->getName(false)) { + foundUnit = true; + break; + } + } + } + } + // Check if this is a morph command + else if (checkMorph == true && cmdType->getClass() == ccMorph) { + const MorphCommandType *morph = + dynamic_cast(cmdType); + if (morph != NULL) { + const UnitType *morphUnit = morph->getMorphUnit(); + + if (morphUnit != NULL && ut->getId() != unitType2->getId() && + ut->getName(false) == morphUnit->getName(false)) { + foundUnit = true; + break; + } + } + } + } + } + } + + return foundUnit; } void Faction::clearCaches() { - cacheResourceTargetList.clear(); - cachedCloseResourceTargetLookupList.clear(); - - //aliveUnitListCache.clear(); - //mobileUnitListCache.clear(); - //beingBuiltUnitListCache.clear(); - - unsigned int unitCount = this->getUnitCount(); - for(unsigned int i = 0; i < unitCount; ++i) { - Unit *unit = this->getUnit(i); - if(unit != NULL) { - unit->clearCaches(); - } - } -} - -uint64 Faction::getCacheKBytes(uint64 *cache1Size, uint64 *cache2Size, uint64 *cache3Size, uint64 *cache4Size, uint64 *cache5Size) { - uint64 cache1Count = 0; - uint64 cache2Count = 0; - uint64 cache3Count = 0; - uint64 cache4Count = 0; - uint64 cache5Count = 0; - - for(std::map::iterator iterMap1 = cacheResourceTargetList.begin(); - iterMap1 != cacheResourceTargetList.end(); ++iterMap1) { - cache1Count++; - } - for(std::map::iterator iterMap1 = cachedCloseResourceTargetLookupList.begin(); - iterMap1 != cachedCloseResourceTargetLookupList.end(); ++iterMap1) { - cache2Count++; - } - for(std::map::iterator iterMap1 = aliveUnitListCache.begin(); - iterMap1 != aliveUnitListCache.end(); ++iterMap1) { - cache3Count++; - } - for(std::map::iterator iterMap1 = mobileUnitListCache.begin(); - iterMap1 != mobileUnitListCache.end(); ++iterMap1) { - cache4Count++; - } - for(std::map::iterator iterMap1 = beingBuiltUnitListCache.begin(); - iterMap1 != beingBuiltUnitListCache.end(); ++iterMap1) { - cache5Count++; - } - - if(cache1Size) { - *cache1Size = cache1Count; - } - if(cache2Size) { - *cache2Size = cache2Count; - } - if(cache3Size) { - *cache3Size = cache3Count; - } - if(cache4Size) { - *cache4Size = cache4Count; - } - if(cache5Size) { - *cache5Size = cache5Count; - } - - uint64 totalBytes = cache1Count * sizeof(int); - totalBytes += cache2Count * sizeof(bool); - totalBytes += cache3Count * (sizeof(int) + sizeof(const Unit *)); - totalBytes += cache4Count * (sizeof(int) + sizeof(const Unit *)); - totalBytes += cache5Count * (sizeof(int) + sizeof(const Unit *)); - - totalBytes /= 1000; - - return totalBytes; + cacheResourceTargetList.clear(); + cachedCloseResourceTargetLookupList.clear(); + + // aliveUnitListCache.clear(); + // mobileUnitListCache.clear(); + // beingBuiltUnitListCache.clear(); + + unsigned int unitCount = this->getUnitCount(); + for (unsigned int i = 0; i < unitCount; ++i) { + Unit *unit = this->getUnit(i); + if (unit != NULL) { + unit->clearCaches(); + } + } +} + +uint64 Faction::getCacheKBytes(uint64 *cache1Size, uint64 *cache2Size, + uint64 *cache3Size, uint64 *cache4Size, + uint64 *cache5Size) { + uint64 cache1Count = 0; + uint64 cache2Count = 0; + uint64 cache3Count = 0; + uint64 cache4Count = 0; + uint64 cache5Count = 0; + + for (std::map::iterator iterMap1 = + cacheResourceTargetList.begin(); + iterMap1 != cacheResourceTargetList.end(); ++iterMap1) { + cache1Count++; + } + for (std::map::iterator iterMap1 = + cachedCloseResourceTargetLookupList.begin(); + iterMap1 != cachedCloseResourceTargetLookupList.end(); ++iterMap1) { + cache2Count++; + } + for (std::map::iterator iterMap1 = + aliveUnitListCache.begin(); + iterMap1 != aliveUnitListCache.end(); ++iterMap1) { + cache3Count++; + } + for (std::map::iterator iterMap1 = + mobileUnitListCache.begin(); + iterMap1 != mobileUnitListCache.end(); ++iterMap1) { + cache4Count++; + } + for (std::map::iterator iterMap1 = + beingBuiltUnitListCache.begin(); + iterMap1 != beingBuiltUnitListCache.end(); ++iterMap1) { + cache5Count++; + } + + if (cache1Size) { + *cache1Size = cache1Count; + } + if (cache2Size) { + *cache2Size = cache2Count; + } + if (cache3Size) { + *cache3Size = cache3Count; + } + if (cache4Size) { + *cache4Size = cache4Count; + } + if (cache5Size) { + *cache5Size = cache5Count; + } + + uint64 totalBytes = cache1Count * sizeof(int); + totalBytes += cache2Count * sizeof(bool); + totalBytes += cache3Count * (sizeof(int) + sizeof(const Unit *)); + totalBytes += cache4Count * (sizeof(int) + sizeof(const Unit *)); + totalBytes += cache5Count * (sizeof(int) + sizeof(const Unit *)); + + totalBytes /= 1000; + + return totalBytes; } string Faction::getCacheStats() { - string result = ""; + string result = ""; - int cache1Count = 0; - int cache2Count = 0; + int cache1Count = 0; + int cache2Count = 0; - for(std::map::iterator iterMap1 = cacheResourceTargetList.begin(); - iterMap1 != cacheResourceTargetList.end(); ++iterMap1) { - cache1Count++; - } - for(std::map::iterator iterMap1 = cachedCloseResourceTargetLookupList.begin(); - iterMap1 != cachedCloseResourceTargetLookupList.end(); ++iterMap1) { - cache2Count++; - } + for (std::map::iterator iterMap1 = + cacheResourceTargetList.begin(); + iterMap1 != cacheResourceTargetList.end(); ++iterMap1) { + cache1Count++; + } + for (std::map::iterator iterMap1 = + cachedCloseResourceTargetLookupList.begin(); + iterMap1 != cachedCloseResourceTargetLookupList.end(); ++iterMap1) { + cache2Count++; + } - uint64 totalBytes = cache1Count * sizeof(int); - totalBytes += cache2Count * sizeof(bool); + uint64 totalBytes = cache1Count * sizeof(int); + totalBytes += cache2Count * sizeof(bool); - totalBytes /= 1000; + totalBytes /= 1000; - char szBuf[8096]=""; - snprintf(szBuf,8096,"cache1Count [%d] cache2Count [%d] total KB: %s",cache1Count,cache2Count,formatNumber(totalBytes).c_str()); - result = szBuf; - return result; + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "cache1Count [%d] cache2Count [%d] total KB: %s", + cache1Count, cache2Count, formatNumber(totalBytes).c_str()); + result = szBuf; + return result; } std::string Faction::toString(bool crcMode) const { - std::string result = "FactionIndex = " + intToStr(this->index) + "\n"; - result += "teamIndex = " + intToStr(this->teamIndex) + "\n"; - result += "startLocationIndex = " + intToStr(this->startLocationIndex) + "\n"; - if(crcMode == false) { - result += "thisFaction = " + intToStr(this->thisFaction) + "\n"; - result += "control = " + intToStr(this->control) + "\n"; + std::string result = "FactionIndex = " + intToStr(this->index) + "\n"; + result += "teamIndex = " + intToStr(this->teamIndex) + "\n"; + result += "startLocationIndex = " + intToStr(this->startLocationIndex) + "\n"; + if (crcMode == false) { + result += "thisFaction = " + intToStr(this->thisFaction) + "\n"; + result += "control = " + intToStr(this->control) + "\n"; + } + + if (this->factionType != NULL) { + result += this->factionType->toString() + "\n"; + } + + result += this->upgradeManager.toString() + "\n"; + + result += "ResourceCount = " + intToStr(resources.size()) + "\n"; + for (int idx = 0; idx < (int)resources.size(); idx++) { + result += + "index = " + intToStr(idx) + " " + resources[idx].toString() + "\n"; + } + + result += "StoreCount = " + intToStr(store.size()) + "\n"; + for (int idx = 0; idx < (int)store.size(); idx++) { + result += "index = " + intToStr(idx) + " " + store[idx].toString() + "\n"; + } + + result += "Allies = " + intToStr(allies.size()) + "\n"; + for (int idx = 0; idx < (int)allies.size(); idx++) { + result += "index = " + intToStr(idx) + + " name: " + allies[idx]->factionType->getName(false) + + " factionindex = " + intToStr(allies[idx]->index) + "\n"; + } + + result += "Units = " + intToStr(units.size()) + "\n"; + for (int idx = 0; idx < (int)units.size(); idx++) { + result += units[idx]->toString(crcMode) + "\n"; + } + + return result; +} + +void Faction::saveGame(XmlNode *rootNode) { + std::map mapTagReplacements; + XmlNode *factionNode = rootNode->addChild("Faction"); + + upgradeManager.saveGame(factionNode); + for (unsigned int i = 0; i < resources.size(); ++i) { + Resource &resource = resources[i]; + resource.saveGame(factionNode); + } + XmlNode *storeNode = factionNode->addChild("Store"); + for (unsigned int i = 0; i < store.size(); ++i) { + Resource &resource = store[i]; + resource.saveGame(storeNode); + } + + for (unsigned int i = 0; i < allies.size(); ++i) { + Faction *ally = allies[i]; + XmlNode *allyNode = factionNode->addChild("Ally"); + allyNode->addAttribute("allyFactionIndex", intToStr(ally->getIndex()), + mapTagReplacements); + } + for (unsigned int i = 0; i < units.size(); ++i) { + Unit *unit = units[i]; + unit->saveGame(factionNode); + } + + factionNode->addAttribute("control", intToStr(control), mapTagReplacements); + + factionNode->addAttribute("overridePersonalityType", + intToStr(overridePersonalityType), + mapTagReplacements); + factionNode->addAttribute("factiontype", factionType->getName(false), + mapTagReplacements); + factionNode->addAttribute("index", intToStr(index), mapTagReplacements); + factionNode->addAttribute("teamIndex", intToStr(teamIndex), + mapTagReplacements); + factionNode->addAttribute("startLocationIndex", intToStr(startLocationIndex), + mapTagReplacements); + factionNode->addAttribute("thisFaction", intToStr(thisFaction), + mapTagReplacements); + + for (std::map::iterator iterMap = cacheResourceTargetList.begin(); + iterMap != cacheResourceTargetList.end(); ++iterMap) { + XmlNode *cacheResourceTargetListNode = + factionNode->addChild("cacheResourceTargetList"); + + cacheResourceTargetListNode->addAttribute("key", iterMap->first.getString(), + mapTagReplacements); + cacheResourceTargetListNode->addAttribute( + "value", intToStr(iterMap->second), mapTagReplacements); + } + + for (std::map::iterator iterMap = + cachedCloseResourceTargetLookupList.begin(); + iterMap != cachedCloseResourceTargetLookupList.end(); ++iterMap) { + XmlNode *cachedCloseResourceTargetLookupListNode = + factionNode->addChild("cachedCloseResourceTargetLookupList"); + + cachedCloseResourceTargetLookupListNode->addAttribute( + "key", iterMap->first.getString(), mapTagReplacements); + cachedCloseResourceTargetLookupListNode->addAttribute( + "value", intToStr(iterMap->second), mapTagReplacements); + } + + factionNode->addAttribute("random", intToStr(random.getLastNumber()), + mapTagReplacements); + factionNode->addAttribute("currentSwitchTeamVoteFactionIndex", + intToStr(currentSwitchTeamVoteFactionIndex), + mapTagReplacements); + factionNode->addAttribute("allowSharedTeamUnits", + intToStr(allowSharedTeamUnits), mapTagReplacements); + + for (std::set::iterator iterMap = lockedUnits.begin(); + iterMap != lockedUnits.end(); ++iterMap) { + XmlNode *lockedUnitsListNode = factionNode->addChild("lockedUnitList"); + const UnitType *ut = *iterMap; + + lockedUnitsListNode->addAttribute("value", ut->getName(false), + mapTagReplacements); + } + + for (std::map::iterator iterMap = unitsMovingList.begin(); + iterMap != unitsMovingList.end(); ++iterMap) { + XmlNode *unitsMovingListNode = factionNode->addChild("unitsMovingList"); + + unitsMovingListNode->addAttribute("key", intToStr(iterMap->first), + mapTagReplacements); + unitsMovingListNode->addAttribute("value", intToStr(iterMap->second), + mapTagReplacements); + } + + for (std::map::iterator iterMap = unitsPathfindingList.begin(); + iterMap != unitsPathfindingList.end(); ++iterMap) { + XmlNode *unitsPathfindingListNode = + factionNode->addChild("unitsPathfindingList"); + + unitsPathfindingListNode->addAttribute("key", intToStr(iterMap->first), + mapTagReplacements); + unitsPathfindingListNode->addAttribute("value", intToStr(iterMap->second), + mapTagReplacements); + } +} + +void Faction::loadGame(const XmlNode *rootNode, int factionIndex, + GameSettings *settings, World *world) { + XmlNode *factionNode = NULL; + vector factionNodeList = rootNode->getChildList("Faction"); + for (unsigned int i = 0; i < factionNodeList.size(); ++i) { + XmlNode *node = factionNodeList[i]; + if (node->getAttribute("index")->getIntValue() == factionIndex) { + factionNode = node; + break; } + } + + if (factionNode != NULL) { + + allies.clear(); + vector allyNodeList = factionNode->getChildList("Ally"); + for (unsigned int i = 0; i < allyNodeList.size(); ++i) { + XmlNode *allyNode = allyNodeList[i]; - if(this->factionType != NULL) { - result += this->factionType->toString() + "\n"; + int allyFactionIndex = + allyNode->getAttribute("allyFactionIndex")->getIntValue(); + allies.push_back(world->getFaction(allyFactionIndex)); } - result += this->upgradeManager.toString() + "\n"; + vector unitNodeList = factionNode->getChildList("Unit"); + for (unsigned int i = 0; i < unitNodeList.size(); ++i) { + XmlNode *unitNode = unitNodeList[i]; + Unit *unit = Unit::loadGame(unitNode, settings, this, world); + this->addUnit(unit); + } - result += "ResourceCount = " + intToStr(resources.size()) + "\n"; - for(int idx = 0; idx < (int)resources.size(); idx ++) { - result += "index = " + intToStr(idx) + " " + resources[idx].toString() + "\n"; - } + for (unsigned int i = 0; i < resources.size(); ++i) { + Resource &resource = resources[i]; + resource.loadGame(factionNode, i, techTree); + } + XmlNode *storeNode = factionNode->getChild("Store"); + for (unsigned int i = 0; i < store.size(); ++i) { + Resource &resource = store[i]; + resource.loadGame(storeNode, i, techTree); + } - result += "StoreCount = " + intToStr(store.size()) + "\n"; - for(int idx = 0; idx < (int)store.size(); idx ++) { - result += "index = " + intToStr(idx) + " " + store[idx].toString() + "\n"; - } + upgradeManager.loadGame(factionNode, this); - result += "Allies = " + intToStr(allies.size()) + "\n"; - for(int idx = 0; idx < (int)allies.size(); idx ++) { - result += "index = " + intToStr(idx) + " name: " + allies[idx]->factionType->getName(false) + " factionindex = " + intToStr(allies[idx]->index) + "\n"; - } + control = static_cast( + factionNode->getAttribute("control")->getIntValue()); - result += "Units = " + intToStr(units.size()) + "\n"; - for(int idx = 0; idx < (int)units.size(); idx ++) { - result += units[idx]->toString(crcMode) + "\n"; - } + if (factionNode->hasAttribute("overridePersonalityType") == true) { + overridePersonalityType = static_cast( + factionNode->getAttribute("overridePersonalityType")->getIntValue()); + } - return result; -} + teamIndex = factionNode->getAttribute("teamIndex")->getIntValue(); -void Faction::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *factionNode = rootNode->addChild("Faction"); - - upgradeManager.saveGame(factionNode); - for(unsigned int i = 0; i < resources.size(); ++i) { - Resource &resource = resources[i]; - resource.saveGame(factionNode); - } - XmlNode *storeNode = factionNode->addChild("Store"); - for(unsigned int i = 0; i < store.size(); ++i) { - Resource &resource = store[i]; - resource.saveGame(storeNode); - } - - for(unsigned int i = 0; i < allies.size(); ++i) { - Faction *ally = allies[i]; - XmlNode *allyNode = factionNode->addChild("Ally"); - allyNode->addAttribute("allyFactionIndex",intToStr(ally->getIndex()), mapTagReplacements); - } - for(unsigned int i = 0; i < units.size(); ++i) { - Unit *unit = units[i]; - unit->saveGame(factionNode); - } - - factionNode->addAttribute("control",intToStr(control), mapTagReplacements); - - factionNode->addAttribute("overridePersonalityType",intToStr(overridePersonalityType), mapTagReplacements); - factionNode->addAttribute("factiontype",factionType->getName(false), mapTagReplacements); - factionNode->addAttribute("index",intToStr(index), mapTagReplacements); - factionNode->addAttribute("teamIndex",intToStr(teamIndex), mapTagReplacements); - factionNode->addAttribute("startLocationIndex",intToStr(startLocationIndex), mapTagReplacements); - factionNode->addAttribute("thisFaction",intToStr(thisFaction), mapTagReplacements); - - for(std::map::iterator iterMap = cacheResourceTargetList.begin(); - iterMap != cacheResourceTargetList.end(); ++iterMap) { - XmlNode *cacheResourceTargetListNode = factionNode->addChild("cacheResourceTargetList"); - - cacheResourceTargetListNode->addAttribute("key",iterMap->first.getString(), mapTagReplacements); - cacheResourceTargetListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); - } - - for(std::map::iterator iterMap = cachedCloseResourceTargetLookupList.begin(); - iterMap != cachedCloseResourceTargetLookupList.end(); ++iterMap) { - XmlNode *cachedCloseResourceTargetLookupListNode = factionNode->addChild("cachedCloseResourceTargetLookupList"); - - cachedCloseResourceTargetLookupListNode->addAttribute("key",iterMap->first.getString(), mapTagReplacements); - cachedCloseResourceTargetLookupListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); - } - - factionNode->addAttribute("random",intToStr(random.getLastNumber()), mapTagReplacements); - factionNode->addAttribute("currentSwitchTeamVoteFactionIndex",intToStr(currentSwitchTeamVoteFactionIndex), mapTagReplacements); - factionNode->addAttribute("allowSharedTeamUnits",intToStr(allowSharedTeamUnits), mapTagReplacements); - - for(std::set::iterator iterMap = lockedUnits.begin(); - iterMap != lockedUnits.end(); ++iterMap) { - XmlNode *lockedUnitsListNode = factionNode->addChild("lockedUnitList"); - const UnitType *ut=*iterMap; - - lockedUnitsListNode->addAttribute("value",ut->getName(false), mapTagReplacements); - } - - for(std::map::iterator iterMap = unitsMovingList.begin(); - iterMap != unitsMovingList.end(); ++iterMap) { - XmlNode *unitsMovingListNode = factionNode->addChild("unitsMovingList"); - - unitsMovingListNode->addAttribute("key",intToStr(iterMap->first), mapTagReplacements); - unitsMovingListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); - } - - for(std::map::iterator iterMap = unitsPathfindingList.begin(); - iterMap != unitsPathfindingList.end(); ++iterMap) { - XmlNode *unitsPathfindingListNode = factionNode->addChild("unitsPathfindingList"); - - unitsPathfindingListNode->addAttribute("key",intToStr(iterMap->first), mapTagReplacements); - unitsPathfindingListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); - } -} - -void Faction::loadGame(const XmlNode *rootNode, int factionIndex,GameSettings *settings,World *world) { - XmlNode *factionNode = NULL; - vector factionNodeList = rootNode->getChildList("Faction"); - for(unsigned int i = 0; i < factionNodeList.size(); ++i) { - XmlNode *node = factionNodeList[i]; - if(node->getAttribute("index")->getIntValue() == factionIndex) { - factionNode = node; - break; - } - } - - if(factionNode != NULL) { - - allies.clear(); - vector allyNodeList = factionNode->getChildList("Ally"); - for(unsigned int i = 0; i < allyNodeList.size(); ++i) { - XmlNode *allyNode = allyNodeList[i]; - - int allyFactionIndex = allyNode->getAttribute("allyFactionIndex")->getIntValue(); - allies.push_back(world->getFaction(allyFactionIndex)); - } - - vector unitNodeList = factionNode->getChildList("Unit"); - for(unsigned int i = 0; i < unitNodeList.size(); ++i) { - XmlNode *unitNode = unitNodeList[i]; - Unit *unit = Unit::loadGame(unitNode,settings,this, world); - this->addUnit(unit); - } - - for(unsigned int i = 0; i < resources.size(); ++i) { - Resource &resource = resources[i]; - resource.loadGame(factionNode,i,techTree); - } - XmlNode *storeNode = factionNode->getChild("Store"); - for(unsigned int i = 0; i < store.size(); ++i) { - Resource &resource = store[i]; - resource.loadGame(storeNode,i,techTree); - } - - upgradeManager.loadGame(factionNode,this); - - control = static_cast(factionNode->getAttribute("control")->getIntValue()); - - if(factionNode->hasAttribute("overridePersonalityType") == true) { - overridePersonalityType = static_cast(factionNode->getAttribute("overridePersonalityType")->getIntValue()); - } - - teamIndex = factionNode->getAttribute("teamIndex")->getIntValue(); - - startLocationIndex = factionNode->getAttribute("startLocationIndex")->getIntValue(); - - thisFaction = factionNode->getAttribute("thisFaction")->getIntValue() != 0; + startLocationIndex = + factionNode->getAttribute("startLocationIndex")->getIntValue(); - if(factionNode->hasAttribute("allowSharedTeamUnits") == true) { - allowSharedTeamUnits = factionNode->getAttribute("allowSharedTeamUnits")->getIntValue() != 0; - } + thisFaction = factionNode->getAttribute("thisFaction")->getIntValue() != 0; + + if (factionNode->hasAttribute("allowSharedTeamUnits") == true) { + allowSharedTeamUnits = + factionNode->getAttribute("allowSharedTeamUnits")->getIntValue() != 0; + } - vector cacheResourceTargetListNodeList = factionNode->getChildList("cacheResourceTargetList"); - for(unsigned int i = 0; i < cacheResourceTargetListNodeList.size(); ++i) { - XmlNode *cacheResourceTargetListNode = cacheResourceTargetListNodeList[i]; + vector cacheResourceTargetListNodeList = + factionNode->getChildList("cacheResourceTargetList"); + for (unsigned int i = 0; i < cacheResourceTargetListNodeList.size(); ++i) { + XmlNode *cacheResourceTargetListNode = cacheResourceTargetListNodeList[i]; - Vec2i vec = Vec2i::strToVec2(cacheResourceTargetListNode->getAttribute("key")->getValue()); - cacheResourceTargetList[vec] = cacheResourceTargetListNode->getAttribute("value")->getIntValue(); - } - vector cachedCloseResourceTargetLookupListNodeList = factionNode->getChildList("cachedCloseResourceTargetLookupList"); - for(unsigned int i = 0; i < cachedCloseResourceTargetLookupListNodeList.size(); ++i) { - XmlNode *cachedCloseResourceTargetLookupListNode = cachedCloseResourceTargetLookupListNodeList[i]; - - Vec2i vec = Vec2i::strToVec2(cachedCloseResourceTargetLookupListNode->getAttribute("key")->getValue()); - cachedCloseResourceTargetLookupList[vec] = cachedCloseResourceTargetLookupListNode->getAttribute("value")->getIntValue() != 0; - } - - random.setLastNumber(factionNode->getAttribute("random")->getIntValue()); + Vec2i vec = Vec2i::strToVec2( + cacheResourceTargetListNode->getAttribute("key")->getValue()); + cacheResourceTargetList[vec] = + cacheResourceTargetListNode->getAttribute("value")->getIntValue(); + } + vector cachedCloseResourceTargetLookupListNodeList = + factionNode->getChildList("cachedCloseResourceTargetLookupList"); + for (unsigned int i = 0; + i < cachedCloseResourceTargetLookupListNodeList.size(); ++i) { + XmlNode *cachedCloseResourceTargetLookupListNode = + cachedCloseResourceTargetLookupListNodeList[i]; + + Vec2i vec = Vec2i::strToVec2( + cachedCloseResourceTargetLookupListNode->getAttribute("key") + ->getValue()); + cachedCloseResourceTargetLookupList[vec] = + cachedCloseResourceTargetLookupListNode->getAttribute("value") + ->getIntValue() != 0; + } - vector lockedUnitsListNodeList = factionNode->getChildList("lockedUnitList"); - for(unsigned int i = 0; i < lockedUnitsListNodeList.size(); ++i) { - XmlNode *lockedUnitsListNode = lockedUnitsListNodeList[i]; + random.setLastNumber(factionNode->getAttribute("random")->getIntValue()); - string unitName = lockedUnitsListNode->getAttribute("value")->getValue(); - lockedUnits.insert(getType()->getUnitType(unitName)); - } + vector lockedUnitsListNodeList = + factionNode->getChildList("lockedUnitList"); + for (unsigned int i = 0; i < lockedUnitsListNodeList.size(); ++i) { + XmlNode *lockedUnitsListNode = lockedUnitsListNodeList[i]; - vector unitsMovingListNodeList = factionNode->getChildList("unitsMovingList"); - for(unsigned int i = 0; i < unitsMovingListNodeList.size(); ++i) { - XmlNode *unitsMovingListNode = unitsMovingListNodeList[i]; + string unitName = lockedUnitsListNode->getAttribute("value")->getValue(); + lockedUnits.insert(getType()->getUnitType(unitName)); + } - int unitId = unitsMovingListNode->getAttribute("key")->getIntValue(); - unitsMovingList[unitId] = unitsMovingListNode->getAttribute("value")->getIntValue(); - } - vector unitsPathfindingListNodeList = factionNode->getChildList("unitsPathfindingList"); - for(unsigned int i = 0; i < unitsPathfindingListNodeList.size(); ++i) { - XmlNode *unitsPathfindingListNode = unitsPathfindingListNodeList[i]; + vector unitsMovingListNodeList = + factionNode->getChildList("unitsMovingList"); + for (unsigned int i = 0; i < unitsMovingListNodeList.size(); ++i) { + XmlNode *unitsMovingListNode = unitsMovingListNodeList[i]; - int unitId = unitsPathfindingListNode->getAttribute("key")->getIntValue(); - unitsPathfindingList[unitId] = unitsPathfindingListNode->getAttribute("value")->getIntValue(); - } - } + int unitId = unitsMovingListNode->getAttribute("key")->getIntValue(); + unitsMovingList[unitId] = + unitsMovingListNode->getAttribute("value")->getIntValue(); + } + vector unitsPathfindingListNodeList = + factionNode->getChildList("unitsPathfindingList"); + for (unsigned int i = 0; i < unitsPathfindingListNodeList.size(); ++i) { + XmlNode *unitsPathfindingListNode = unitsPathfindingListNodeList[i]; + + int unitId = unitsPathfindingListNode->getAttribute("key")->getIntValue(); + unitsPathfindingList[unitId] = + unitsPathfindingListNode->getAttribute("value")->getIntValue(); + } + } } Checksum Faction::getCRC() { - const bool consoleDebug = false; - - Checksum crcForFaction; - - // UpgradeManager upgradeManager; - - for(unsigned int i = 0; i < resources.size(); ++i) { - Resource &resource = resources[i]; - //crcForFaction.addSum(resource.getCRC().getSum()); - uint32 crc = resource.getCRC().getSum(); - crcForFaction.addBytes(&crc,sizeof(uint32)); - } - - if(consoleDebug) { - if(getWorld()->getFrameCount() % 40 == 0) { - printf("#1 Frame #: %d Faction: %d CRC: %u\n",getWorld()->getFrameCount(),index,crcForFaction.getSum()); - } - } - - for(unsigned int i = 0; i < store.size(); ++i) { - Resource &resource = store[i]; - //crcForFaction.addSum(resource.getCRC().getSum()); - uint32 crc = resource.getCRC().getSum(); - crcForFaction.addBytes(&crc,sizeof(uint32)); - } - - if(consoleDebug) { - if(getWorld()->getFrameCount() % 40 == 0) { - printf("#2 Frame #: %d Faction: %d CRC: %u\n",getWorld()->getFrameCount(),index,crcForFaction.getSum()); - } - } - - for(unsigned int i = 0; i < units.size(); ++i) { - Unit *unit = units[i]; - //crcForFaction.addSum(unit->getCRC().getSum()); - uint32 crc = unit->getCRC().getSum(); - crcForFaction.addBytes(&crc,sizeof(uint32)); - } - - if(consoleDebug) { - if(getWorld()->getFrameCount() % 40 == 0) { - printf("#3 Frame #: %d Faction: %d CRC: %u\n",getWorld()->getFrameCount(),index,crcForFaction.getSum()); - } - } - - return crcForFaction; -} - -void Faction::addCRC_DetailsForWorldFrame(int worldFrameCount,bool isNetworkServer) { - unsigned int MAX_FRAME_CACHE = 250; - if(isNetworkServer == true) { - MAX_FRAME_CACHE += 250; - } - crcWorldFrameDetails[worldFrameCount] = this->toString(true); - //if(worldFrameCount <= 0) printf("Adding world frame: %d log entries: %lld\n",worldFrameCount,(long long int)crcWorldFrameDetails.size()); - - for(unsigned int i = 0; i < units.size(); ++i) { - Unit *unit = units[i]; - - unit->getRandom()->clearLastCaller(); - unit->clearNetworkCRCDecHpList(); - unit->clearParticleInfo(); - } - - if((unsigned int)crcWorldFrameDetails.size() > MAX_FRAME_CACHE) { - //printf("===> Removing older world frame log entries: %lld\n",(long long int)crcWorldFrameDetails.size()); - - for(;(unsigned int)crcWorldFrameDetails.size() - MAX_FRAME_CACHE > 0;) { - crcWorldFrameDetails.erase(crcWorldFrameDetails.begin()); - } - } + const bool consoleDebug = false; + + Checksum crcForFaction; + + // UpgradeManager upgradeManager; + + for (unsigned int i = 0; i < resources.size(); ++i) { + Resource &resource = resources[i]; + // crcForFaction.addSum(resource.getCRC().getSum()); + uint32 crc = resource.getCRC().getSum(); + crcForFaction.addBytes(&crc, sizeof(uint32)); + } + + if (consoleDebug) { + if (getWorld()->getFrameCount() % 40 == 0) { + printf("#1 Frame #: %d Faction: %d CRC: %u\n", + getWorld()->getFrameCount(), index, crcForFaction.getSum()); + } + } + + for (unsigned int i = 0; i < store.size(); ++i) { + Resource &resource = store[i]; + // crcForFaction.addSum(resource.getCRC().getSum()); + uint32 crc = resource.getCRC().getSum(); + crcForFaction.addBytes(&crc, sizeof(uint32)); + } + + if (consoleDebug) { + if (getWorld()->getFrameCount() % 40 == 0) { + printf("#2 Frame #: %d Faction: %d CRC: %u\n", + getWorld()->getFrameCount(), index, crcForFaction.getSum()); + } + } + + for (unsigned int i = 0; i < units.size(); ++i) { + Unit *unit = units[i]; + // crcForFaction.addSum(unit->getCRC().getSum()); + uint32 crc = unit->getCRC().getSum(); + crcForFaction.addBytes(&crc, sizeof(uint32)); + } + + if (consoleDebug) { + if (getWorld()->getFrameCount() % 40 == 0) { + printf("#3 Frame #: %d Faction: %d CRC: %u\n", + getWorld()->getFrameCount(), index, crcForFaction.getSum()); + } + } + + return crcForFaction; +} + +void Faction::addCRC_DetailsForWorldFrame(int worldFrameCount, + bool isNetworkServer) { + unsigned int MAX_FRAME_CACHE = 250; + if (isNetworkServer == true) { + MAX_FRAME_CACHE += 250; + } + crcWorldFrameDetails[worldFrameCount] = this->toString(true); + // if(worldFrameCount <= 0) printf("Adding world frame: %d log entries: + // %lld\n",worldFrameCount,(long long int)crcWorldFrameDetails.size()); + + for (unsigned int i = 0; i < units.size(); ++i) { + Unit *unit = units[i]; + + unit->getRandom()->clearLastCaller(); + unit->clearNetworkCRCDecHpList(); + unit->clearParticleInfo(); + } + + if ((unsigned int)crcWorldFrameDetails.size() > MAX_FRAME_CACHE) { + // printf("===> Removing older world frame log entries: %lld\n",(long long + // int)crcWorldFrameDetails.size()); + + for (; (unsigned int)crcWorldFrameDetails.size() - MAX_FRAME_CACHE > 0;) { + crcWorldFrameDetails.erase(crcWorldFrameDetails.begin()); + } + } } string Faction::getCRC_DetailsForWorldFrame(int worldFrameCount) { - if(crcWorldFrameDetails.empty()) { - return ""; - } - return crcWorldFrameDetails[worldFrameCount]; + if (crcWorldFrameDetails.empty()) { + return ""; + } + return crcWorldFrameDetails[worldFrameCount]; } -std::pair Faction::getCRC_DetailsForWorldFrameIndex(int worldFrameIndex) const { - if(crcWorldFrameDetails.empty()) { - return make_pair(0,""); - } - std::map::const_iterator iterMap = crcWorldFrameDetails.begin(); - std::advance( iterMap, worldFrameIndex ); - if(iterMap == crcWorldFrameDetails.end()) { - return make_pair(0,""); - } - return std::pair(iterMap->first,iterMap->second); +std::pair +Faction::getCRC_DetailsForWorldFrameIndex(int worldFrameIndex) const { + if (crcWorldFrameDetails.empty()) { + return make_pair(0, ""); + } + std::map::const_iterator iterMap = crcWorldFrameDetails.begin(); + std::advance(iterMap, worldFrameIndex); + if (iterMap == crcWorldFrameDetails.end()) { + return make_pair(0, ""); + } + return std::pair(iterMap->first, iterMap->second); } string Faction::getCRC_DetailsForWorldFrames() const { - string result = ""; - for(std::map::const_iterator iterMap = crcWorldFrameDetails.begin(); - iterMap != crcWorldFrameDetails.end(); ++iterMap) { - result += string("============================================================================\n"); - result += string("** world frame: ") + intToStr(iterMap->first) + string(" detail: ") + iterMap->second; - } - return result; + string result = ""; + for (std::map::const_iterator iterMap = + crcWorldFrameDetails.begin(); + iterMap != crcWorldFrameDetails.end(); ++iterMap) { + result += string("=========================================================" + "===================\n"); + result += string("** world frame: ") + intToStr(iterMap->first) + + string(" detail: ") + iterMap->second; + } + return result; } uint64 Faction::getCRC_DetailsForWorldFrameCount() const { - return crcWorldFrameDetails.size(); + return crcWorldFrameDetails.size(); } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/type_instances/faction.h b/source/glest_game/type_instances/faction.h index 57056b001..3bff9ca18 100644 --- a/source/glest_game/type_instances/faction.h +++ b/source/glest_game/type_instances/faction.h @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,30 +13,31 @@ #define _GLEST_GAME_FACTION_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include -#include -#include "upgrade.h" -#include "texture.h" -#include "resource.h" -#include "game_constants.h" -#include "command_type.h" #include "base_thread.h" -#include +#include "command_type.h" #include "faction_type.h" +#include "game_constants.h" #include "leak_dumper.h" +#include "resource.h" +#include "texture.h" +#include "upgrade.h" +#include +#include +#include using std::map; -using std::vector; using std::set; +using std::vector; using Shared::Graphics::Texture2D; using namespace Shared::PlatformCommon; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { class Unit; class TechTree; @@ -54,21 +55,17 @@ class SurfaceCell; class FowAlphaCellsLookupItem { public: - - std::map surfPosAlphaList; + std::map surfPosAlphaList; }; class ExploredCellsLookupItem { public: + ExploredCellsLookupItem() { ExploredCellsLookupItemCacheTimerCountIndex = 0; } + int ExploredCellsLookupItemCacheTimerCountIndex; + std::vector exploredCellList; + std::vector visibleCellList; - ExploredCellsLookupItem() { - ExploredCellsLookupItemCacheTimerCountIndex = 0; - } - int ExploredCellsLookupItemCacheTimerCountIndex; - std::vector exploredCellList; - std::vector visibleCellList; - - static time_t lastDebug; + static time_t lastDebug; }; // ===================================================== @@ -78,321 +75,362 @@ class ExploredCellsLookupItem { // ===================================================== struct CommandGroupUnitSorter { - bool operator()(const Unit *l, const Unit *r); - bool compare(const Unit *l, const Unit *r); + bool operator()(const Unit *l, const Unit *r); + bool compare(const Unit *l, const Unit *r); }; struct CommandGroupUnitSorterId { - Faction *faction; - bool operator()(const int l, const int r); + Faction *faction; + bool operator()(const int l, const int r); }; class FactionThread : public BaseThread, public SlaveThreadControllerInterface { protected: + Faction *faction; + Semaphore semTaskSignalled; + Mutex *triggerIdMutex; + std::pair frameIndex; + MasterSlaveThreadController *masterController; - Faction *faction; - Semaphore semTaskSignalled; - Mutex *triggerIdMutex; - std::pair frameIndex; - MasterSlaveThreadController *masterController; - - virtual void setQuitStatus(bool value); - virtual void setTaskCompleted(int frameIndex); - virtual bool canShutdown(bool deleteSelfIfShutdownDelayed=false); + virtual void setQuitStatus(bool value); + virtual void setTaskCompleted(int frameIndex); + virtual bool canShutdown(bool deleteSelfIfShutdownDelayed = false); public: - explicit FactionThread(Faction *faction); - virtual ~FactionThread(); - virtual void execute(); - - virtual void setMasterController(MasterSlaveThreadController *master) { masterController = master; } - virtual void signalSlave(void *userdata) { signalPathfinder(*((int *)(userdata))); } - - void signalPathfinder(int frameIndex); - bool isSignalPathfinderCompleted(int frameIndex); + explicit FactionThread(Faction *faction); + virtual ~FactionThread(); + virtual void execute(); + + virtual void setMasterController(MasterSlaveThreadController *master) { + masterController = master; + } + virtual void signalSlave(void *userdata) { + signalPathfinder(*((int *)(userdata))); + } + + void signalPathfinder(int frameIndex); + bool isSignalPathfinderCompleted(int frameIndex); }; class SwitchTeamVote { public: - - int factionIndex; - int oldTeam; - int newTeam; - bool voted; - bool allowSwitchTeam; + int factionIndex; + int oldTeam; + int newTeam; + bool voted; + bool allowSwitchTeam; }; class Faction { private: - typedef vector Resources; - typedef vector Store; - typedef vector Allies; - typedef vector Units; - typedef map UnitMap; + typedef vector Resources; + typedef vector Store; + typedef vector Allies; + typedef vector Units; + typedef map UnitMap; private: - UpgradeManager upgradeManager; + UpgradeManager upgradeManager; + + Resources resources; + Store store; + Allies allies; - Resources resources; - Store store; - Allies allies; + Mutex *unitsMutex; + Units units; + UnitMap unitMap; + World *world; + ScriptManager *scriptManager; - Mutex *unitsMutex; - Units units; - UnitMap unitMap; - World *world; - ScriptManager *scriptManager; - - FactionPersonalityType overridePersonalityType; - ControlType control; + FactionPersonalityType overridePersonalityType; + ControlType control; - Texture2D *texture; - FactionType *factionType; + Texture2D *texture; + FactionType *factionType; - int index; - int teamIndex; - int startLocationIndex; + int index; + int teamIndex; + int startLocationIndex; - bool thisFaction; + bool thisFaction; - bool factionDisconnectHandled; + bool factionDisconnectHandled; - bool cachingDisabled; - std::map cacheResourceTargetList; - std::map cachedCloseResourceTargetLookupList; + bool cachingDisabled; + std::map cacheResourceTargetList; + std::map cachedCloseResourceTargetLookupList; - RandomGen random; - FactionThread *workerThread; + RandomGen random; + FactionThread *workerThread; - std::map switchTeamVotes; - int currentSwitchTeamVoteFactionIndex; + std::map switchTeamVotes; + int currentSwitchTeamVoteFactionIndex; - bool allowSharedTeamUnits; - set livingUnits; - set livingUnitsp; + bool allowSharedTeamUnits; + set livingUnits; + set livingUnitsp; - std::map unitsMovingList; - std::map unitsPathfindingList; + std::map unitsMovingList; + std::map unitsPathfindingList; - std::set lockedUnits; + std::set lockedUnits; - TechTree *techTree; - const XmlNode *loadWorldNode; + TechTree *techTree; + const XmlNode *loadWorldNode; - std::vector worldSynchThreadedLogList; + std::vector worldSynchThreadedLogList; - std::map crcWorldFrameDetails; + std::map crcWorldFrameDetails; - std::map aliveUnitListCache; - std::map mobileUnitListCache; - std::map beingBuiltUnitListCache; + std::map aliveUnitListCache; + std::map mobileUnitListCache; + std::map beingBuiltUnitListCache; - std::map resourceTypeCostCache; + std::map resourceTypeCostCache; public: - Faction(); - ~Faction(); - - Faction(const Faction& obj) { - init(); - throw megaglest_runtime_error("class Faction is NOT safe to copy!"); - } - Faction & operator=(const Faction& obj) { - init(); - throw megaglest_runtime_error("class Faction is NOT safe to assign!"); - } - - void notifyUnitAliveStatusChange(const Unit *unit); - void notifyUnitTypeChange(const Unit *unit, const UnitType *newType); - void notifyUnitSkillTypeChange(const Unit *unit, const SkillType *newType); - bool hasAliveUnits(bool filterMobileUnits, bool filterBuiltUnits) const; - - inline void addWorldSynchThreadedLogList(const string &data) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true) { - worldSynchThreadedLogList.push_back(data); - } - } - inline void clearWorldSynchThreadedLogList() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true) { - worldSynchThreadedLogList.clear(); - } - } - inline void dumpWorldSynchThreadedLogList() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true) { - if(worldSynchThreadedLogList.empty() == false) { - for(unsigned int index = 0; index < worldSynchThreadedLogList.size(); ++index) { - SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,worldSynchThreadedLogList[index].c_str()); - } - worldSynchThreadedLogList.clear(); - } - } - } - - inline void addLivingUnits(int id) { livingUnits.insert(id); } - inline void addLivingUnitsp(Unit *unit) { livingUnitsp.insert(unit); } - - inline bool isUnitInLivingUnitsp(Unit *unit) { return (livingUnitsp.find(unit) != livingUnitsp.end()); } - inline void deleteLivingUnits(int id) { livingUnits.erase(id); } - inline void deleteLivingUnitsp(Unit *unit) { livingUnitsp.erase(unit); } - - //std::map unitsMovingList; - void addUnitToMovingList(int unitId); - void removeUnitFromMovingList(int unitId); - //int getUnitMovingListCount(); - - void addUnitToPathfindingList(int unitId); - //void removeUnitFromPathfindingList(int unitId); - int getUnitPathfindingListCount(); - void clearUnitsPathfinding(); - bool canUnitsPathfind(); - - void setLockedUnitForFaction(const UnitType *ut, bool lock); - bool isUnitLocked(const UnitType *ut) const { return lockedUnits.find(ut)!=lockedUnits.end(); } - - void init( - FactionType *factionType, ControlType control, TechTree *techTree, Game *game, - int factionIndex, int teamIndex, int startLocationIndex, bool thisFaction, - bool giveResources, const XmlNode *loadWorldNode=NULL); - void end(); - - inline bool getFactionDisconnectHandled() const { return factionDisconnectHandled;} - void setFactionDisconnectHandled(bool value) { factionDisconnectHandled=value;} - - //get - const Resource *getResource(const ResourceType *rt,bool localFactionOnly=false) const; - inline const Resource *getResource(int i) const {return &resources[i];} - int getStoreAmount(const ResourceType *rt,bool localFactionOnly=false) const; - inline const FactionType *getType() const {return factionType;} - inline int getIndex() const {return index;} - - inline int getTeam() const {return teamIndex;} - void setTeam(int team) {teamIndex=team;} - - inline TechTree * getTechTree() const { return techTree; } - const SwitchTeamVote * getFirstSwitchTeamVote() const; - SwitchTeamVote * getSwitchTeamVote(int factionIndex); - void setSwitchTeamVote(SwitchTeamVote &vote); - inline int getCurrentSwitchTeamVoteFactionIndex() const { return currentSwitchTeamVoteFactionIndex; } - void setCurrentSwitchTeamVoteFactionIndex(int index) { currentSwitchTeamVoteFactionIndex = index; } - - bool getCpuControl(bool enableServerControlledAI, bool isNetworkGame, NetworkRole role) const; - bool getCpuControl() const; - inline bool getCpuEasyControl() const {return control==ctCpuEasy;} - inline bool getCpuUltraControl() const {return control==ctCpuUltra;} - inline bool getCpuMegaControl() const {return control==ctCpuMega;} - inline ControlType getControlType() const {return control;} - - FactionPersonalityType getPersonalityType() const; - void setPersonalityType(FactionPersonalityType pType) { overridePersonalityType=pType; } - int getAIBehaviorStaticOverideValue(AIBehaviorStaticValueCategory type) const; - - inline Unit *getUnit(int i) const { - Unit *result = units[i]; - return result; - } - inline int getUnitCount() const { - int result = (int)units.size(); - return result; - } - inline Mutex * getUnitMutex() {return unitsMutex;} - - inline const UpgradeManager *getUpgradeManager() const {return &upgradeManager;} - inline const Texture2D *getTexture() const {return texture;} - inline int getStartLocationIndex() const {return startLocationIndex;} - inline bool getThisFaction() const {return thisFaction;} - - //upgrades - void startUpgrade(const UpgradeType *ut); - void cancelUpgrade(const UpgradeType *ut); - void finishUpgrade(const UpgradeType *ut); - - //cost application - bool applyCosts(const ProducibleType *p,const CommandType *ct); - void applyDiscount(const ProducibleType *p, int discount); - void applyStaticCosts(const ProducibleType *p,const CommandType *ct); - void applyStaticProduction(const ProducibleType *p,const CommandType *ct); - void deApplyCosts(const ProducibleType *p,const CommandType *ct); - void deApplyStaticCosts(const ProducibleType *p,const CommandType *ct); - void deApplyStaticConsumption(const ProducibleType *p,const CommandType *ct); - bool applyCostsOnInterval(const ResourceType *rtApply); - bool checkCosts(const ProducibleType *pt,const CommandType *ct); - int getAmountOfProducable(const ProducibleType *pt,const CommandType *ct); - - //reqs - bool reqsOk(const RequirableType *rt) const; - bool reqsOk(const CommandType *ct) const; - int getCountForMaxUnitCount(const UnitType *unitType) const; - - //diplomacy - bool isAlly(const Faction *faction); - - //other - Unit *findUnit(int id) const; - void addUnit(Unit *unit); - void removeUnit(Unit *unit); - void addStore(const UnitType *unitType); - void removeStore(const UnitType *unitType); - - //resources - void incResourceAmount(const ResourceType *rt, int amount); - void setResourceBalance(const ResourceType *rt, int balance); - - void setControlType(ControlType value) { control = value; } - - bool isResourceTargetInCache(const Vec2i &pos,bool incrementUseCounter=false); - void addResourceTargetToCache(const Vec2i &pos,bool incrementUseCounter=true); - void removeResourceTargetFromCache(const Vec2i &pos); - void addCloseResourceTargetToCache(const Vec2i &pos); - Vec2i getClosestResourceTypeTargetFromCache(Unit *unit, const ResourceType *type,int frameIndex); - Vec2i getClosestResourceTypeTargetFromCache(const Vec2i &pos, const ResourceType *type); - void cleanupResourceTypeTargetCache(std::vector *deleteListPtr,int frameIndex); - inline int getCacheResourceTargetListSize() const { return (int)cacheResourceTargetList.size(); } - -// Unit * findClosestUnitWithSkillClass(const Vec2i &pos,const CommandClass &cmdClass, -// const std::vector &skillClassList, -// const UnitType *unitType); - - void deletePixels(); - - inline World * getWorld() { return world; } - int getFrameCount(); - - void signalWorkerThread(int frameIndex); - bool isWorkerThreadSignalCompleted(int frameIndex); - FactionThread *getWorkerThread() { return workerThread; } - - void limitResourcesToStore(); - - void sortUnitsByCommandGroups(); - - bool canCreateUnit(const UnitType *ut, bool checkBuild, bool checkProduce, bool checkMorph) const; - - string getCacheStats(); - uint64 getCacheKBytes(uint64 *cache1Size, uint64 *cache2Size, uint64 *cache3Size, uint64 *cache4Size, uint64 *cache5Size); - - std::string toString(bool crcMode=false) const; - - void saveGame(XmlNode *rootNode); - void loadGame(const XmlNode *rootNode, int factionIndex,GameSettings *settings,World *world); - - void clearCaches(); - - Checksum getCRC(); - void addCRC_DetailsForWorldFrame(int worldFrameCount,bool isNetworkServer); - string getCRC_DetailsForWorldFrame(int worldFrameCount); - std::pair getCRC_DetailsForWorldFrameIndex(int worldFrameIndex) const; - string getCRC_DetailsForWorldFrames() const; - uint64 getCRC_DetailsForWorldFrameCount() const; - - void updateUnitTypeWithResourceCostCache(const ResourceType *rt); - bool hasUnitTypeWithResourceCostInCache(const ResourceType *rt) const; + Faction(); + ~Faction(); + + Faction(const Faction &obj) { + init(); + throw megaglest_runtime_error("class Faction is NOT safe to copy!"); + } + Faction &operator=(const Faction &obj) { + init(); + throw megaglest_runtime_error("class Faction is NOT safe to assign!"); + } + + void notifyUnitAliveStatusChange(const Unit *unit); + void notifyUnitTypeChange(const Unit *unit, const UnitType *newType); + void notifyUnitSkillTypeChange(const Unit *unit, const SkillType *newType); + bool hasAliveUnits(bool filterMobileUnits, bool filterBuiltUnits) const; + + inline void addWorldSynchThreadedLogList(const string &data) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true) { + worldSynchThreadedLogList.push_back(data); + } + } + inline void clearWorldSynchThreadedLogList() { + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true) { + worldSynchThreadedLogList.clear(); + } + } + inline void dumpWorldSynchThreadedLogList() { + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true) { + if (worldSynchThreadedLogList.empty() == false) { + for (unsigned int index = 0; index < worldSynchThreadedLogList.size(); + ++index) { + SystemFlags::OutputDebug(SystemFlags::debugWorldSynch, + worldSynchThreadedLogList[index].c_str()); + } + worldSynchThreadedLogList.clear(); + } + } + } + + inline void addLivingUnits(int id) { livingUnits.insert(id); } + inline void addLivingUnitsp(Unit *unit) { livingUnitsp.insert(unit); } + + inline bool isUnitInLivingUnitsp(Unit *unit) { + return (livingUnitsp.find(unit) != livingUnitsp.end()); + } + inline void deleteLivingUnits(int id) { livingUnits.erase(id); } + inline void deleteLivingUnitsp(Unit *unit) { livingUnitsp.erase(unit); } + + // std::map unitsMovingList; + void addUnitToMovingList(int unitId); + void removeUnitFromMovingList(int unitId); + // int getUnitMovingListCount(); + + void addUnitToPathfindingList(int unitId); + // void removeUnitFromPathfindingList(int unitId); + int getUnitPathfindingListCount(); + void clearUnitsPathfinding(); + bool canUnitsPathfind(); + + void setLockedUnitForFaction(const UnitType *ut, bool lock); + bool isUnitLocked(const UnitType *ut) const { + return lockedUnits.find(ut) != lockedUnits.end(); + } + + void init(FactionType *factionType, ControlType control, TechTree *techTree, + Game *game, int factionIndex, int teamIndex, int startLocationIndex, + bool thisFaction, bool giveResources, + const XmlNode *loadWorldNode = NULL); + void end(); + + inline bool getFactionDisconnectHandled() const { + return factionDisconnectHandled; + } + void setFactionDisconnectHandled(bool value) { + factionDisconnectHandled = value; + } + + // get + const Resource *getResource(const ResourceType *rt, + bool localFactionOnly = false) const; + inline const Resource *getResource(int i) const { return &resources[i]; } + int getStoreAmount(const ResourceType *rt, + bool localFactionOnly = false) const; + inline const FactionType *getType() const { return factionType; } + inline int getIndex() const { return index; } + + inline int getTeam() const { return teamIndex; } + void setTeam(int team) { teamIndex = team; } + + inline TechTree *getTechTree() const { return techTree; } + const SwitchTeamVote *getFirstSwitchTeamVote() const; + SwitchTeamVote *getSwitchTeamVote(int factionIndex); + void setSwitchTeamVote(SwitchTeamVote &vote); + inline int getCurrentSwitchTeamVoteFactionIndex() const { + return currentSwitchTeamVoteFactionIndex; + } + void setCurrentSwitchTeamVoteFactionIndex(int index) { + currentSwitchTeamVoteFactionIndex = index; + } + + bool getCpuControl(bool enableServerControlledAI, bool isNetworkGame, + NetworkRole role) const; + bool getCpuControl() const; + inline bool getCpuEasyControl() const { return control == ctCpuEasy; } + inline bool getCpuUltraControl() const { return control == ctCpuUltra; } + inline bool getCpuMegaControl() const { return control == ctCpuMega; } + inline ControlType getControlType() const { return control; } + + FactionPersonalityType getPersonalityType() const; + void setPersonalityType(FactionPersonalityType pType) { + overridePersonalityType = pType; + } + int getAIBehaviorStaticOverideValue(AIBehaviorStaticValueCategory type) const; + + inline Unit *getUnit(int i) const { + Unit *result = units[i]; + return result; + } + inline int getUnitCount() const { + int result = (int)units.size(); + return result; + } + inline Mutex *getUnitMutex() { return unitsMutex; } + + inline const UpgradeManager *getUpgradeManager() const { + return &upgradeManager; + } + inline const Texture2D *getTexture() const { return texture; } + inline int getStartLocationIndex() const { return startLocationIndex; } + inline bool getThisFaction() const { return thisFaction; } + + // upgrades + void startUpgrade(const UpgradeType *ut); + void cancelUpgrade(const UpgradeType *ut); + void finishUpgrade(const UpgradeType *ut); + + // cost application + bool applyCosts(const ProducibleType *p, const CommandType *ct); + void applyDiscount(const ProducibleType *p, int discount); + void applyStaticCosts(const ProducibleType *p, const CommandType *ct); + void applyStaticProduction(const ProducibleType *p, const CommandType *ct); + void deApplyCosts(const ProducibleType *p, const CommandType *ct); + void deApplyStaticCosts(const ProducibleType *p, const CommandType *ct); + void deApplyStaticConsumption(const ProducibleType *p, const CommandType *ct); + bool applyCostsOnInterval(const ResourceType *rtApply); + bool checkCosts(const ProducibleType *pt, const CommandType *ct); + int getAmountOfProducable(const ProducibleType *pt, const CommandType *ct); + + // reqs + bool reqsOk(const RequirableType *rt) const; + bool reqsOk(const CommandType *ct) const; + int getCountForMaxUnitCount(const UnitType *unitType) const; + + // diplomacy + bool isAlly(const Faction *faction); + + // other + Unit *findUnit(int id) const; + void addUnit(Unit *unit); + void removeUnit(Unit *unit); + void addStore(const UnitType *unitType); + void removeStore(const UnitType *unitType); + + // resources + void incResourceAmount(const ResourceType *rt, int amount); + void setResourceBalance(const ResourceType *rt, int balance); + + void setControlType(ControlType value) { control = value; } + + bool isResourceTargetInCache(const Vec2i &pos, + bool incrementUseCounter = false); + void addResourceTargetToCache(const Vec2i &pos, + bool incrementUseCounter = true); + void removeResourceTargetFromCache(const Vec2i &pos); + void addCloseResourceTargetToCache(const Vec2i &pos); + Vec2i getClosestResourceTypeTargetFromCache(Unit *unit, + const ResourceType *type, + int frameIndex); + Vec2i getClosestResourceTypeTargetFromCache(const Vec2i &pos, + const ResourceType *type); + void cleanupResourceTypeTargetCache(std::vector *deleteListPtr, + int frameIndex); + inline int getCacheResourceTargetListSize() const { + return (int)cacheResourceTargetList.size(); + } + + // Unit * findClosestUnitWithSkillClass(const Vec2i &pos,const CommandClass + //&cmdClass, const + //std::vector &skillClassList, + //const UnitType *unitType); + + void deletePixels(); + + inline World *getWorld() { return world; } + int getFrameCount(); + + void signalWorkerThread(int frameIndex); + bool isWorkerThreadSignalCompleted(int frameIndex); + FactionThread *getWorkerThread() { return workerThread; } + + void limitResourcesToStore(); + + void sortUnitsByCommandGroups(); + + bool canCreateUnit(const UnitType *ut, bool checkBuild, bool checkProduce, + bool checkMorph) const; + + string getCacheStats(); + uint64 getCacheKBytes(uint64 *cache1Size, uint64 *cache2Size, + uint64 *cache3Size, uint64 *cache4Size, + uint64 *cache5Size); + + std::string toString(bool crcMode = false) const; + + void saveGame(XmlNode *rootNode); + void loadGame(const XmlNode *rootNode, int factionIndex, + GameSettings *settings, World *world); + + void clearCaches(); + + Checksum getCRC(); + void addCRC_DetailsForWorldFrame(int worldFrameCount, bool isNetworkServer); + string getCRC_DetailsForWorldFrame(int worldFrameCount); + std::pair + getCRC_DetailsForWorldFrameIndex(int worldFrameIndex) const; + string getCRC_DetailsForWorldFrames() const; + uint64 getCRC_DetailsForWorldFrameCount() const; + + void updateUnitTypeWithResourceCostCache(const ResourceType *rt); + bool hasUnitTypeWithResourceCostInCache(const ResourceType *rt) const; private: - void init(); - void resetResourceAmount(const ResourceType *rt); - bool hasUnitTypeWithResouceCost(const ResourceType *rt); + void init(); + void resetResourceAmount(const ResourceType *rt); + bool hasUnitTypeWithResouceCost(const ResourceType *rt); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/type_instances/object.cpp b/source/glest_game/type_instances/object.cpp index 29b565b00..d79e3134b 100644 --- a/source/glest_game/type_instances/object.cpp +++ b/source/glest_game/type_instances/object.cpp @@ -3,308 +3,333 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== #include "object.h" -#include "faction_type.h" #include "config.h" -#include "tech_tree.h" -#include "resource.h" -#include "upgrade.h" +#include "faction_type.h" +#include "game.h" +#include "leak_dumper.h" #include "object_type.h" -#include "resource.h" -#include "util.h" #include "randomgen.h" #include "renderer.h" -#include "leak_dumper.h" -#include "game.h" +#include "resource.h" +#include "tech_tree.h" +#include "upgrade.h" +#include "util.h" using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { -ObjectStateInterface *Object::stateCallback=NULL; +ObjectStateInterface *Object::stateCallback = NULL; // ===================================================== // class Object // ===================================================== -Object::Object(ObjectType *objectType, const Vec3f &pos, const Vec2i &mapPos) : BaseColorPickEntity() { - RandomGen random; - - random.init(static_cast(pos.x * pos.z)); - this->lastRenderFrame = 0; - this->objectType= objectType; - resource= NULL; - highlight= 0.f; - animated= false; - this->mapPos = mapPos; - this->pos= pos + Vec3f(random.randRange(-0.6f, 0.6f), 0.0f, random.randRange(-0.6f, 0.6f)); - rotation= random.randRange(0.f, 360.f); - if(objectType!=NULL){ - variation = random.randRange(0, objectType->getModelCount()-1); - TilesetModelType *tmt=objectType->getTilesetModelType(variation); - if(tmt->getRotationAllowed() != true) { - rotation=0; - } - if(tmt->getRandomPositionEnabled() != true) { - this->pos = pos; - } - animated=tmt->getAnimSpeed()>0; - } - else { - variation=0; - } - visible=false; - animProgress=0.0f; +Object::Object(ObjectType *objectType, const Vec3f &pos, const Vec2i &mapPos) + : BaseColorPickEntity() { + RandomGen random; + + random.init(static_cast(pos.x * pos.z)); + this->lastRenderFrame = 0; + this->objectType = objectType; + resource = NULL; + highlight = 0.f; + animated = false; + this->mapPos = mapPos; + this->pos = pos + Vec3f(random.randRange(-0.6f, 0.6f), 0.0f, + random.randRange(-0.6f, 0.6f)); + rotation = random.randRange(0.f, 360.f); + if (objectType != NULL) { + variation = random.randRange(0, objectType->getModelCount() - 1); + TilesetModelType *tmt = objectType->getTilesetModelType(variation); + if (tmt->getRotationAllowed() != true) { + rotation = 0; + } + if (tmt->getRandomPositionEnabled() != true) { + this->pos = pos; + } + animated = tmt->getAnimSpeed() > 0; + } else { + variation = 0; + } + visible = false; + animProgress = 0.0f; } Object::~Object() { - Renderer &renderer = Renderer::getInstance(); - // fade(and by this remove) all unit particle systems - while(unitParticleSystems.empty() == false) { - bool particleValid = renderer.validateParticleSystemStillExists(unitParticleSystems.back(),rsGame); - if(particleValid == true) { - unitParticleSystems.back()->fade(); - } - unitParticleSystems.pop_back(); - } - Renderer::getInstance().removeParticleSystemsForParticleOwner(this,rsGame); - renderer.removeObjectFromQuadCache(this); - if(stateCallback) { - stateCallback->removingObjectEvent(this); - } - delete resource; - resource = NULL; - + Renderer &renderer = Renderer::getInstance(); + // fade(and by this remove) all unit particle systems + while (unitParticleSystems.empty() == false) { + bool particleValid = renderer.validateParticleSystemStillExists( + unitParticleSystems.back(), rsGame); + if (particleValid == true) { + unitParticleSystems.back()->fade(); + } + unitParticleSystems.pop_back(); + } + Renderer::getInstance().removeParticleSystemsForParticleOwner(this, rsGame); + renderer.removeObjectFromQuadCache(this); + if (stateCallback) { + stateCallback->removingObjectEvent(this); + } + delete resource; + resource = NULL; } void Object::end() { - // set Objects to fading and remove them from list. - // its needed because otherwise they will be accessed from the destructor - while(unitParticleSystems.empty() == false) { - bool particleValid = Renderer::getInstance().validateParticleSystemStillExists(unitParticleSystems.back(),rsGame); - if(particleValid == true) { - unitParticleSystems.back()->fade(); - } - unitParticleSystems.pop_back(); - } + // set Objects to fading and remove them from list. + // its needed because otherwise they will be accessed from the destructor + while (unitParticleSystems.empty() == false) { + bool particleValid = + Renderer::getInstance().validateParticleSystemStillExists( + unitParticleSystems.back(), rsGame); + if (particleValid == true) { + unitParticleSystems.back()->fade(); + } + unitParticleSystems.pop_back(); + } } void Object::initParticles() { - if(this->objectType == NULL) { - return; - } - if(this->objectType->getTilesetModelType(variation)->hasParticles()) { - ModelParticleSystemTypes *particleTypes= this->objectType->getTilesetModelType(variation)->getParticleTypes(); - initParticlesFromTypes(particleTypes); - } + if (this->objectType == NULL) { + return; + } + if (this->objectType->getTilesetModelType(variation)->hasParticles()) { + ModelParticleSystemTypes *particleTypes = + this->objectType->getTilesetModelType(variation)->getParticleTypes(); + initParticlesFromTypes(particleTypes); + } } -void Object::initParticlesFromTypes(const ModelParticleSystemTypes *particleTypes) { - bool showTilesetParticles = Config::getInstance().getBool("TilesetParticles", "true"); - if(showTilesetParticles == true && GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && - particleTypes->empty() == false && unitParticleSystems.empty() == true) { - for(ObjectParticleSystemTypes::const_iterator it= particleTypes->begin(); it != particleTypes->end(); ++it){ - UnitParticleSystem *ups= new UnitParticleSystem(200); - ups->setParticleOwner(this); - ups->setParticleType((*it)); - (*it)->setValues(ups); - ups->setPos(this->pos); - ups->setRotation(this->rotation); - ups->setFactionColor(Vec3f(0, 0, 0)); - ups->setVisible(false); - this->unitParticleSystems.push_back(ups); - Renderer::getInstance().manageParticleSystem(ups, rsGame); - } - } +void Object::initParticlesFromTypes( + const ModelParticleSystemTypes *particleTypes) { + bool showTilesetParticles = + Config::getInstance().getBool("TilesetParticles", "true"); + if (showTilesetParticles == true && + GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && + particleTypes->empty() == false && unitParticleSystems.empty() == true) { + for (ObjectParticleSystemTypes::const_iterator it = particleTypes->begin(); + it != particleTypes->end(); ++it) { + UnitParticleSystem *ups = new UnitParticleSystem(200); + ups->setParticleOwner(this); + ups->setParticleType((*it)); + (*it)->setValues(ups); + ups->setPos(this->pos); + ups->setRotation(this->rotation); + ups->setFactionColor(Vec3f(0, 0, 0)); + ups->setVisible(false); + this->unitParticleSystems.push_back(ups); + Renderer::getInstance().manageParticleSystem(ups, rsGame); + } + } } void Object::end(ParticleSystem *particleSystem) { - vector::iterator iterFind = find(unitParticleSystems.begin(),unitParticleSystems.end(),particleSystem); - if(iterFind != unitParticleSystems.end()) { - unitParticleSystems.erase(iterFind); - } + vector::iterator iterFind = find( + unitParticleSystems.begin(), unitParticleSystems.end(), particleSystem); + if (iterFind != unitParticleSystems.end()) { + unitParticleSystems.erase(iterFind); + } } void Object::setHeight(float height) { - pos.y = height; - - for(UnitParticleSystems::iterator it= unitParticleSystems.begin(); it != unitParticleSystems.end(); ++it) { - bool particleValid = Renderer::getInstance().validateParticleSystemStillExists((*it),rsGame); - if(particleValid == true) { - (*it)->setPos(this->pos); - } - } + pos.y = height; + + for (UnitParticleSystems::iterator it = unitParticleSystems.begin(); + it != unitParticleSystems.end(); ++it) { + bool particleValid = + Renderer::getInstance().validateParticleSystemStillExists((*it), + rsGame); + if (particleValid == true) { + (*it)->setPos(this->pos); + } + } } void Object::updateHighlight() { - //highlight - if(highlight > 0.f) { - //const Game *game = Renderer::getInstance().getGame(); - //highlight -= 1.f / (Game::highlightTime * game->getWorld()->getUpdateFps(-1)); - highlight -= 1.f / (Game::highlightTime * GameConstants::updateFps); - } + // highlight + if (highlight > 0.f) { + // const Game *game = Renderer::getInstance().getGame(); + // highlight -= 1.f / (Game::highlightTime * + // game->getWorld()->getUpdateFps(-1)); + highlight -= 1.f / (Game::highlightTime * GameConstants::updateFps); + } } void Object::update() { - //if(objectType != NULL && objectType->getTilesetModelType(variation) != NULL && - // objectType->getTilesetModelType(variation)->getAnimSpeed() != 0.0) { - if(animated == true) { -// printf("#1 Object updating [%s] Speed [%d] animProgress [%f]\n",this->objectType->getTilesetModelType(variation)->getModel()->getFileName().c_str(),objectType->getTilesetModelType(variation)->getAnimSpeed(),animProgress); - - if(objectType != NULL && objectType->getTilesetModelType(variation) != NULL) { - float heightFactor = 1.f; - const float speedDivider= 100.f; - float speedDenominator = (speedDivider * GameConstants::updateFps); - - // smooth TwoFrameanimations - float f=1.0f; - if(objectType->getTilesetModelType(variation)->getSmoothTwoFrameAnim()==true){ - f=abs(std::sin(animProgress*2*3.16))+0.4f; - } - - float newAnimProgress = animProgress + f*(((float)objectType->getTilesetModelType(variation)->getAnimSpeed() * heightFactor) / speedDenominator); - - animProgress = newAnimProgress; - if(animProgress > 1.f) { - animProgress = 0.f; - } - } - } + // if(objectType != NULL && objectType->getTilesetModelType(variation) != NULL + // && objectType->getTilesetModelType(variation)->getAnimSpeed() != 0.0) + // { + if (animated == true) { + // printf("#1 Object updating [%s] Speed [%d] animProgress + //[%f]\n",this->objectType->getTilesetModelType(variation)->getModel()->getFileName().c_str(),objectType->getTilesetModelType(variation)->getAnimSpeed(),animProgress); + + if (objectType != NULL && + objectType->getTilesetModelType(variation) != NULL) { + float heightFactor = 1.f; + const float speedDivider = 100.f; + float speedDenominator = (speedDivider * GameConstants::updateFps); + + // smooth TwoFrameanimations + float f = 1.0f; + if (objectType->getTilesetModelType(variation)->getSmoothTwoFrameAnim() == + true) { + f = abs(std::sin(animProgress * 2 * 3.16)) + 0.4f; + } + + float newAnimProgress = + animProgress + f * (((float)objectType->getTilesetModelType(variation) + ->getAnimSpeed() * + heightFactor) / + speedDenominator); + + animProgress = newAnimProgress; + if (animProgress > 1.f) { + animProgress = 0.f; + } + } + } } -void Object::resetHighlight(){ - highlight= 1.f; -} +void Object::resetHighlight() { highlight = 1.f; } Model *Object::getModelPtr() const { - Model* result = NULL; - if(objectType==NULL) { - if(resource != NULL && resource->getType() != NULL){ - result = resource->getType()->getModel(); - } - } - else { - result=objectType->getTilesetModelType(variation)->getModel(); - } - return result; + Model *result = NULL; + if (objectType == NULL) { + if (resource != NULL && resource->getType() != NULL) { + result = resource->getType()->getModel(); + } + } else { + result = objectType->getTilesetModelType(variation)->getModel(); + } + return result; } const Model *Object::getModel() const { - Model* result = NULL; - if(objectType == NULL){ - if(resource != NULL && resource->getType() != NULL){ - result=resource->getType()->getModel(); - } - } - else { - result=objectType->getTilesetModelType(variation)->getModel(); - } - return result; + Model *result = NULL; + if (objectType == NULL) { + if (resource != NULL && resource->getType() != NULL) { + result = resource->getType()->getModel(); + } + } else { + result = objectType->getTilesetModelType(variation)->getModel(); + } + return result; } -bool Object::getWalkable() const{ - return objectType==NULL? false: objectType->getWalkable(); +bool Object::getWalkable() const { + return objectType == NULL ? false : objectType->getWalkable(); } -void Object::setResource(const ResourceType *resourceType, const Vec2i &pos){ - delete resource; - resource= new Resource(); - resource->init(resourceType, pos); - initParticlesFromTypes(resourceType->getObjectParticleSystemTypes()); +void Object::setResource(const ResourceType *resourceType, const Vec2i &pos) { + delete resource; + resource = new Resource(); + resource->init(resourceType, pos); + initParticlesFromTypes(resourceType->getObjectParticleSystemTypes()); } -void Object::setVisible( bool visible) -{ - this->visible=visible; - for(UnitParticleSystems::iterator it= unitParticleSystems.begin(); it != unitParticleSystems.end(); ++it) { - bool particleValid = Renderer::getInstance().validateParticleSystemStillExists((*it),rsGame); - if(particleValid == true) { - (*it)->setVisible(visible); - } - } +void Object::setVisible(bool visible) { + this->visible = visible; + for (UnitParticleSystems::iterator it = unitParticleSystems.begin(); + it != unitParticleSystems.end(); ++it) { + bool particleValid = + Renderer::getInstance().validateParticleSystemStillExists((*it), + rsGame); + if (particleValid == true) { + (*it)->setVisible(visible); + } + } } string Object::getUniquePickName() const { - string result = ""; - if(resource != NULL) { - result += resource->getDescription(false) + " : "; - } - result += mapPos.getString(); - return result; + string result = ""; + if (resource != NULL) { + result += resource->getDescription(false) + " : "; + } + result += mapPos.getString(); + return result; } void Object::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *objectNode = rootNode->addChild("Object"); - -// ObjectType *objectType; - if(objectType != NULL) { - objectNode->addAttribute("objectType",intToStr(objectType->getClass()), mapTagReplacements); - } -// vector unitParticleSystems; - for(unsigned int i = 0; i < unitParticleSystems.size(); ++i) { - UnitParticleSystem *ptr= unitParticleSystems[i]; - if(ptr != NULL) { - ptr->saveGame(objectNode); - } - } -// Resource *resource; - if(resource != NULL) { - resource->saveGame(objectNode); - } -// Vec3f pos; - objectNode->addAttribute("pos",pos.getString(), mapTagReplacements); -// float rotation; - objectNode->addAttribute("rotation",floatToStr(rotation,6), mapTagReplacements); -// int variation; - objectNode->addAttribute("variation",intToStr(variation), mapTagReplacements); -// int lastRenderFrame; - objectNode->addAttribute("lastRenderFrame",intToStr(lastRenderFrame), mapTagReplacements); -// Vec2i mapPos; - objectNode->addAttribute("mapPos",mapPos.getString(), mapTagReplacements); -// bool visible; - objectNode->addAttribute("visible",intToStr(visible), mapTagReplacements); + std::map mapTagReplacements; + XmlNode *objectNode = rootNode->addChild("Object"); + + // ObjectType *objectType; + if (objectType != NULL) { + objectNode->addAttribute("objectType", intToStr(objectType->getClass()), + mapTagReplacements); + } + // vector unitParticleSystems; + for (unsigned int i = 0; i < unitParticleSystems.size(); ++i) { + UnitParticleSystem *ptr = unitParticleSystems[i]; + if (ptr != NULL) { + ptr->saveGame(objectNode); + } + } + // Resource *resource; + if (resource != NULL) { + resource->saveGame(objectNode); + } + // Vec3f pos; + objectNode->addAttribute("pos", pos.getString(), mapTagReplacements); + // float rotation; + objectNode->addAttribute("rotation", floatToStr(rotation, 6), + mapTagReplacements); + // int variation; + objectNode->addAttribute("variation", intToStr(variation), + mapTagReplacements); + // int lastRenderFrame; + objectNode->addAttribute("lastRenderFrame", intToStr(lastRenderFrame), + mapTagReplacements); + // Vec2i mapPos; + objectNode->addAttribute("mapPos", mapPos.getString(), mapTagReplacements); + // bool visible; + objectNode->addAttribute("visible", intToStr(visible), mapTagReplacements); } -void Object::loadGame(const XmlNode *rootNode,const TechTree *techTree) { - const XmlNode *objectNode = rootNode->getChild("Object"); - - //description = objectNode->getAttribute("description")->getValue(); - - // ObjectType *objectType; -// if(objectType != NULL) { -// objectNode->addAttribute("objectType",intToStr(objectType->getClass()), mapTagReplacements); -// } -// // vector unitParticleSystems; -// for(unsigned int i = 0; i < unitParticleSystems.size(); ++i) { -// UnitParticleSystem *ptr= unitParticleSystems[i]; -// if(ptr != NULL) { -// ptr->saveGame(objectNode); -// } -// } - // Resource *resource; - if(resource != NULL) { - resource->loadGame(objectNode,0,techTree); - } - // Vec3f pos; - pos = Vec3f::strToVec3(objectNode->getAttribute("pos")->getValue()); - // float rotation; - rotation = objectNode->getAttribute("rotation")->getFloatValue(); - // int variation; - variation = objectNode->getAttribute("variation")->getIntValue(); - // int lastRenderFrame; - lastRenderFrame = objectNode->getAttribute("lastRenderFrame")->getIntValue(); - // Vec2i mapPos; - mapPos = Vec2i::strToVec2(objectNode->getAttribute("mapPos")->getValue()); - // bool visible; - visible = objectNode->getAttribute("visible")->getIntValue() != 0; +void Object::loadGame(const XmlNode *rootNode, const TechTree *techTree) { + const XmlNode *objectNode = rootNode->getChild("Object"); + + // description = objectNode->getAttribute("description")->getValue(); + + // ObjectType *objectType; + // if(objectType != NULL) { + // objectNode->addAttribute("objectType",intToStr(objectType->getClass()), + // mapTagReplacements); + // } + // // vector unitParticleSystems; + // for(unsigned int i = 0; i < unitParticleSystems.size(); ++i) { + // UnitParticleSystem *ptr= unitParticleSystems[i]; + // if(ptr != NULL) { + // ptr->saveGame(objectNode); + // } + // } + // Resource *resource; + if (resource != NULL) { + resource->loadGame(objectNode, 0, techTree); + } + // Vec3f pos; + pos = Vec3f::strToVec3(objectNode->getAttribute("pos")->getValue()); + // float rotation; + rotation = objectNode->getAttribute("rotation")->getFloatValue(); + // int variation; + variation = objectNode->getAttribute("variation")->getIntValue(); + // int lastRenderFrame; + lastRenderFrame = objectNode->getAttribute("lastRenderFrame")->getIntValue(); + // Vec2i mapPos; + mapPos = Vec2i::strToVec2(objectNode->getAttribute("mapPos")->getValue()); + // bool visible; + visible = objectNode->getAttribute("visible")->getIntValue() != 0; } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/type_instances/object.h b/source/glest_game/type_instances/object.h index 9a430899f..e4a694045 100644 --- a/source/glest_game/type_instances/object.h +++ b/source/glest_game/type_instances/object.h @@ -3,27 +3,28 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== #ifndef _GLEST_GAME_OBJECT_H_ #define _GLEST_GAME_OBJECT_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include "model.h" -#include "vec.h" #include "leak_dumper.h" -#include "particle.h" +#include "model.h" #include "object_type.h" +#include "particle.h" #include "tileset_model_type.h" +#include "vec.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { class ObjectType; class ResourceType; @@ -31,9 +32,9 @@ class Resource; class TechTree; using Shared::Graphics::Model; +using Shared::Graphics::UnitParticleSystem; using Shared::Graphics::Vec2i; using Shared::Graphics::Vec3f; -using Shared::Graphics::UnitParticleSystem; // ===================================================== // class Object @@ -45,75 +46,78 @@ class Object; class ObjectStateInterface { public: - virtual void removingObjectEvent(Object *object) = 0; - virtual ~ObjectStateInterface() {} + virtual void removingObjectEvent(Object *object) = 0; + virtual ~ObjectStateInterface() {} }; class Object : public BaseColorPickEntity, public ParticleOwner { private: - typedef vector UnitParticleSystems; + typedef vector UnitParticleSystems; private: - ObjectType *objectType; - vector unitParticleSystems; - Resource *resource; - Vec3f pos; - float rotation; - int variation; - int lastRenderFrame; - Vec2i mapPos; - bool visible; - bool animated; - float animProgress; - float highlight; - - static ObjectStateInterface *stateCallback; + ObjectType *objectType; + vector unitParticleSystems; + Resource *resource; + Vec3f pos; + float rotation; + int variation; + int lastRenderFrame; + Vec2i mapPos; + bool visible; + bool animated; + float animProgress; + float highlight; + + static ObjectStateInterface *stateCallback; public: - Object(ObjectType *objectType, const Vec3f &pos, const Vec2i &mapPos); - virtual ~Object(); - - virtual void end(); //to kill particles - virtual void logParticleInfo(string info) {}; - void initParticles(); - void initParticlesFromTypes(const ModelParticleSystemTypes *particleTypes); - static void setStateCallback(ObjectStateInterface *value) { stateCallback=value; } - - const ObjectType *getType() const {return objectType;} - Resource *getResource() const {return resource;} - Vec3f getPos() const {return pos;} - bool isVisible() const {return visible;} - const Vec3f & getConstPos() const {return pos;} - float getRotation() const {return rotation;} - const Model *getModel() const; - Model *getModelPtr() const; - bool getWalkable() const; - bool isAnimated() const {return animated;} - - float getHightlight() const {return highlight;} - bool isHighlighted() const {return highlight>0.f;} - void resetHighlight(); - - void setResource(const ResourceType *resourceType, const Vec2i &pos); - void setHeight(float height); - void setVisible(bool visible); - - int getLastRenderFrame() const { return lastRenderFrame; } - void setLastRenderFrame(int value) { lastRenderFrame = value; } - - const Vec2i & getMapPos() const { return mapPos; } - - void updateHighlight(); - void update(); - float getAnimProgress() const { return animProgress;} - - virtual string getUniquePickName() const; - void saveGame(XmlNode *rootNode); - void loadGame(const XmlNode *rootNode,const TechTree *techTree); - - virtual void end(ParticleSystem *particleSystem); + Object(ObjectType *objectType, const Vec3f &pos, const Vec2i &mapPos); + virtual ~Object(); + + virtual void end(); // to kill particles + virtual void logParticleInfo(string info){}; + void initParticles(); + void initParticlesFromTypes(const ModelParticleSystemTypes *particleTypes); + static void setStateCallback(ObjectStateInterface *value) { + stateCallback = value; + } + + const ObjectType *getType() const { return objectType; } + Resource *getResource() const { return resource; } + Vec3f getPos() const { return pos; } + bool isVisible() const { return visible; } + const Vec3f &getConstPos() const { return pos; } + float getRotation() const { return rotation; } + const Model *getModel() const; + Model *getModelPtr() const; + bool getWalkable() const; + bool isAnimated() const { return animated; } + + float getHightlight() const { return highlight; } + bool isHighlighted() const { return highlight > 0.f; } + void resetHighlight(); + + void setResource(const ResourceType *resourceType, const Vec2i &pos); + void setHeight(float height); + void setVisible(bool visible); + + int getLastRenderFrame() const { return lastRenderFrame; } + void setLastRenderFrame(int value) { lastRenderFrame = value; } + + const Vec2i &getMapPos() const { return mapPos; } + + void updateHighlight(); + void update(); + float getAnimProgress() const { return animProgress; } + + virtual string getUniquePickName() const; + void saveGame(XmlNode *rootNode); + void loadGame(const XmlNode *rootNode, const TechTree *techTree); + + virtual void end(ParticleSystem *particleSystem); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/type_instances/resource.cpp b/source/glest_game/type_instances/resource.cpp index fa76d2bc9..2659a82e8 100644 --- a/source/glest_game/type_instances/resource.cpp +++ b/source/glest_game/type_instances/resource.cpp @@ -3,153 +3,159 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== #include "resource.h" +#include "checksum.h" #include "conversion.h" +#include "leak_dumper.h" #include "resource_type.h" -#include "checksum.h" -#include -#include "util.h" #include "tech_tree.h" -#include "leak_dumper.h" +#include "util.h" +#include using namespace Shared::Graphics; using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class Resource // ===================================================== Resource::Resource() { - this->type= NULL; - this->amount= 0; - pos= Vec2i(0); - balance= 0; + this->type = NULL; + this->amount = 0; + pos = Vec2i(0); + balance = 0; - addItemToVault(&this->amount,this->amount); - addItemToVault(&this->balance,this->balance); + addItemToVault(&this->amount, this->amount); + addItemToVault(&this->balance, this->balance); } void Resource::init(const ResourceType *rt, int amount) { - this->type= rt; - this->amount= amount; - pos= Vec2i(0); - balance= 0; + this->type = rt; + this->amount = amount; + pos = Vec2i(0); + balance = 0; - addItemToVault(&this->amount,this->amount); - addItemToVault(&this->balance,this->balance); + addItemToVault(&this->amount, this->amount); + addItemToVault(&this->balance, this->balance); } void Resource::init(const ResourceType *rt, const Vec2i &pos) { - this->type=rt; - amount=rt->getDefResPerPatch(); - this->pos= pos; + this->type = rt; + amount = rt->getDefResPerPatch(); + this->pos = pos; - addItemToVault(&this->amount,this->amount); - addItemToVault(&this->balance,this->balance); + addItemToVault(&this->amount, this->amount); + addItemToVault(&this->balance, this->balance); } string Resource::getDescription(bool translatedValue) const { - string str; + string str; - str+= type->getName(translatedValue); - str+="\n"; - str+= intToStr(amount); - str+="/"; - str+= intToStr(type->getDefResPerPatch()); + str += type->getName(translatedValue); + str += "\n"; + str += intToStr(amount); + str += "/"; + str += intToStr(type->getDefResPerPatch()); - return str; + return str; } int Resource::getAmount() const { - checkItemInVault(&this->amount,this->amount); - return amount; + checkItemInVault(&this->amount, this->amount); + return amount; } int Resource::getBalance() const { - checkItemInVault(&this->balance,this->balance); - return balance; + checkItemInVault(&this->balance, this->balance); + return balance; } void Resource::setAmount(int amount) { - checkItemInVault(&this->amount,this->amount); - this->amount= amount; - addItemToVault(&this->amount,this->amount); + checkItemInVault(&this->amount, this->amount); + this->amount = amount; + addItemToVault(&this->amount, this->amount); } void Resource::setBalance(int balance) { - checkItemInVault(&this->balance,this->balance); - this->balance= balance; - addItemToVault(&this->balance,this->balance); + checkItemInVault(&this->balance, this->balance); + this->balance = balance; + addItemToVault(&this->balance, this->balance); } bool Resource::decAmount(int i) { - checkItemInVault(&this->amount,this->amount); - amount -= i; - addItemToVault(&this->amount,this->amount); - - if(amount > 0) { - return false; - } - return true; + checkItemInVault(&this->amount, this->amount); + amount -= i; + addItemToVault(&this->amount, this->amount); + + if (amount > 0) { + return false; + } + return true; } void Resource::saveGame(XmlNode *rootNode) const { - std::map mapTagReplacements; - XmlNode *resourceNode = rootNode->addChild("Resource"); - -// int amount; - resourceNode->addAttribute("amount",intToStr(amount), mapTagReplacements); -// const ResourceType *type; - resourceNode->addAttribute("type",type->getName(), mapTagReplacements); -// Vec2i pos; - resourceNode->addAttribute("pos",pos.getString(), mapTagReplacements); -// int balance; - resourceNode->addAttribute("balance",intToStr(balance), mapTagReplacements); + std::map mapTagReplacements; + XmlNode *resourceNode = rootNode->addChild("Resource"); + + // int amount; + resourceNode->addAttribute("amount", intToStr(amount), mapTagReplacements); + // const ResourceType *type; + resourceNode->addAttribute("type", type->getName(), mapTagReplacements); + // Vec2i pos; + resourceNode->addAttribute("pos", pos.getString(), mapTagReplacements); + // int balance; + resourceNode->addAttribute("balance", intToStr(balance), mapTagReplacements); } -void Resource::loadGame(const XmlNode *rootNode, int index,const TechTree *techTree) { - vector resourceNodeList = rootNode->getChildList("Resource"); +void Resource::loadGame(const XmlNode *rootNode, int index, + const TechTree *techTree) { + vector resourceNodeList = rootNode->getChildList("Resource"); - if(index < (int)resourceNodeList.size()) { - XmlNode *resourceNode = resourceNodeList[index]; + if (index < (int)resourceNodeList.size()) { + XmlNode *resourceNode = resourceNodeList[index]; - amount = resourceNode->getAttribute("amount")->getIntValue(); - type = techTree->getResourceType(resourceNode->getAttribute("type")->getValue()); - pos = Vec2i::strToVec2(resourceNode->getAttribute("pos")->getValue()); - balance = resourceNode->getAttribute("balance")->getIntValue(); - } + amount = resourceNode->getAttribute("amount")->getIntValue(); + type = techTree->getResourceType( + resourceNode->getAttribute("type")->getValue()); + pos = Vec2i::strToVec2(resourceNode->getAttribute("pos")->getValue()); + balance = resourceNode->getAttribute("balance")->getIntValue(); + } } std::string Resource::toString() const { - std::string result = "resource name = " + this->getDescription(false) + "\n"; - result += "amount = " + intToStr(this->amount) + "\n"; - result += "type = " + this->type->getName(false) + "\n"; - result += "type resources per patch = " + intToStr(type->getDefResPerPatch()) + "\n"; - result += "pos = " + this->pos.getString() + "\n"; - result += "balance = " + intToStr(this->balance) + "\n"; - - return result; + std::string result = "resource name = " + this->getDescription(false) + "\n"; + result += "amount = " + intToStr(this->amount) + "\n"; + result += "type = " + this->type->getName(false) + "\n"; + result += + "type resources per patch = " + intToStr(type->getDefResPerPatch()) + + "\n"; + result += "pos = " + this->pos.getString() + "\n"; + result += "balance = " + intToStr(this->balance) + "\n"; + + return result; } Checksum Resource::getCRC() { - Checksum crcForResource; + Checksum crcForResource; - crcForResource.addInt(amount); - crcForResource.addString(type->getName(false)); - crcForResource.addInt(pos.x); - crcForResource.addInt(pos.y); - crcForResource.addInt(balance); + crcForResource.addInt(amount); + crcForResource.addString(type->getName(false)); + crcForResource.addInt(pos.x); + crcForResource.addInt(pos.y); + crcForResource.addInt(balance); - return crcForResource; + return crcForResource; } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/type_instances/resource.h b/source/glest_game/type_instances/resource.h index 4f5b64599..cd85a6d01 100644 --- a/source/glest_game/type_instances/resource.h +++ b/source/glest_game/type_instances/resource.h @@ -3,30 +3,31 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== #ifndef _GLEST_GAME_RESOURCE_H_ #define _GLEST_GAME_RESOURCE_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include -#include "vec.h" +#include "leak_dumper.h" #include "platform_common.h" +#include "vec.h" #include "xml_parser.h" -#include "leak_dumper.h" +#include -using std::string; -using std::map; using Shared::Xml::XmlNode; +using std::map; +using std::string; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { using Shared::Graphics::Vec2i; using Shared::PlatformCommon::ValueCheckerVault; @@ -34,42 +35,43 @@ using Shared::PlatformCommon::ValueCheckerVault; class ResourceType; class TechTree; // ===================================================== -// class Resource +// class Resource // /// Amount of a given ResourceType // ===================================================== class Resource : public ValueCheckerVault { private: - int amount; - const ResourceType *type; - Vec2i pos; - int balance; + int amount; + const ResourceType *type; + Vec2i pos; + int balance; public: - Resource(); - void init(const ResourceType *rt, int amount); - void init(const ResourceType *rt, const Vec2i &pos); + Resource(); + void init(const ResourceType *rt, int amount); + void init(const ResourceType *rt, const Vec2i &pos); - const ResourceType * getType() const {return type;} - Vec2i getPos() const {return pos;} + const ResourceType *getType() const { return type; } + Vec2i getPos() const { return pos; } - int getAmount() const; - int getBalance() const; - string getDescription(bool translatedValue) const; + int getAmount() const; + int getBalance() const; + string getDescription(bool translatedValue) const; - void setAmount(int amount); - void setBalance(int balance); + void setAmount(int amount); + void setBalance(int balance); - bool decAmount(int i); + bool decAmount(int i); - void saveGame(XmlNode *rootNode) const; - void loadGame(const XmlNode *rootNode, int index,const TechTree *techTree); + void saveGame(XmlNode *rootNode) const; + void loadGame(const XmlNode *rootNode, int index, const TechTree *techTree); - std::string toString() const; - Checksum getCRC(); + std::string toString() const; + Checksum getCRC(); }; -}}// end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/type_instances/unit.cpp b/source/glest_game/type_instances/unit.cpp index dc81399c1..0ee146404 100644 --- a/source/glest_game/type_instances/unit.cpp +++ b/source/glest_game/type_instances/unit.cpp @@ -11,191 +11,207 @@ #define NOMINMAX -#include #include "unit.h" -#include "unit_particle_type.h" -#include "world.h" -#include "upgrade.h" -#include "map.h" #include "command.h" -#include "object.h" #include "config.h" -#include "skill_type.h" #include "core_data.h" -#include "renderer.h" #include "game.h" +#include "map.h" +#include "object.h" +#include "renderer.h" +#include "skill_type.h" #include "socket.h" #include "sound_renderer.h" +#include "unit_particle_type.h" +#include "upgrade.h" +#include "world.h" +#include #include "leak_dumper.h" using namespace Shared::Graphics; using namespace Shared::Util; +namespace Glest { +namespace Game { -namespace Glest{ namespace Game{ - -const int CHANGE_COMMAND_SPEED = 325; -const uint32 MIN_FRAMECOUNT_CHANGE_COMMAND_SPEED = 160; +const int CHANGE_COMMAND_SPEED = 325; +const uint32 MIN_FRAMECOUNT_CHANGE_COMMAND_SPEED = 160; -//Mutex Unit::mutexDeletedUnits; -//map Unit::deletedUnits; +// Mutex Unit::mutexDeletedUnits; +// map Unit::deletedUnits; -const int UnitPathBasic::maxBlockCount= GameConstants::updateFps / 2; +const int UnitPathBasic::maxBlockCount = GameConstants::updateFps / 2; #ifdef LEAK_CHECK_UNITS -std::map UnitPathBasic::mapMemoryList; -std::map Unit::mapMemoryList; -std::map Unit::mapMemoryList2; +std::map UnitPathBasic::mapMemoryList; +std::map Unit::mapMemoryList; +std::map Unit::mapMemoryList2; #endif UnitPathBasic::UnitPathBasic() : UnitPathInterface() { #ifdef LEAK_CHECK_UNITS - UnitPathBasic::mapMemoryList[this]=true; + UnitPathBasic::mapMemoryList[this] = true; #endif - this->blockCount = 0; - this->pathQueue.clear(); - this->map = NULL; + this->blockCount = 0; + this->pathQueue.clear(); + this->map = NULL; } UnitPathBasic::~UnitPathBasic() { - this->blockCount = 0; - this->pathQueue.clear(); - this->map = NULL; + this->blockCount = 0; + this->pathQueue.clear(); + this->map = NULL; #ifdef LEAK_CHECK_UNITS - UnitPathBasic::mapMemoryList.erase(this); + UnitPathBasic::mapMemoryList.erase(this); #endif } #ifdef LEAK_CHECK_UNITS void UnitPathBasic::dumpMemoryList() { - printf("===== START report of Unfreed UnitPathBasic pointers =====\n"); - for(std::map::iterator iterMap = UnitPathBasic::mapMemoryList.begin(); - iterMap != UnitPathBasic::mapMemoryList.end(); ++iterMap) { - printf("************** ==> Unfreed UnitPathBasic pointer [%p]\n",iterMap->first); - - if(Unit::mapMemoryList2.find(iterMap->first) != Unit::mapMemoryList2.end()) { - printf("Found owner unit id [%d]\n",Unit::mapMemoryList2[iterMap->first]); - } - } + printf("===== START report of Unfreed UnitPathBasic pointers =====\n"); + for (std::map::iterator iterMap = + UnitPathBasic::mapMemoryList.begin(); + iterMap != UnitPathBasic::mapMemoryList.end(); ++iterMap) { + printf("************** ==> Unfreed UnitPathBasic pointer [%p]\n", + iterMap->first); + + if (Unit::mapMemoryList2.find(iterMap->first) != + Unit::mapMemoryList2.end()) { + printf("Found owner unit id [%d]\n", + Unit::mapMemoryList2[iterMap->first]); + } + } } #endif void UnitPathBasic::clearCaches() { - this->blockCount = 0; - this->pathQueue.clear(); + this->blockCount = 0; + this->pathQueue.clear(); } -bool UnitPathBasic::isEmpty() const { - return pathQueue.empty(); -} +bool UnitPathBasic::isEmpty() const { return pathQueue.empty(); } -bool UnitPathBasic::isBlocked() const { - return blockCount >= maxBlockCount; -} +bool UnitPathBasic::isBlocked() const { return blockCount >= maxBlockCount; } bool UnitPathBasic::isStuck() const { - return (isBlocked() == true && blockCount >= (maxBlockCount * 2)); + return (isBlocked() == true && blockCount >= (maxBlockCount * 2)); } void UnitPathBasic::clear() { - pathQueue.clear(); - blockCount= 0; + pathQueue.clear(); + blockCount = 0; } void UnitPathBasic::incBlockCount() { - pathQueue.clear(); - blockCount++; + pathQueue.clear(); + blockCount++; } void UnitPathBasic::add(const Vec2i &path) { - if(this->map != NULL) { - if(this->map->isInside(path) == false) { - throw megaglest_runtime_error("Invalid map path position = " + path.getString() + " map w x h = " + intToStr(map->getW()) + " " + intToStr(map->getH())); - } - else if(this->map->isInsideSurface(this->map->toSurfCoords(path)) == false) { - throw megaglest_runtime_error("Invalid map surface path position = " + path.getString() + " map surface w x h = " + intToStr(map->getSurfaceW()) + " " + intToStr(map->getSurfaceH())); - } - } + if (this->map != NULL) { + if (this->map->isInside(path) == false) { + throw megaglest_runtime_error( + "Invalid map path position = " + path.getString() + " map w x h = " + + intToStr(map->getW()) + " " + intToStr(map->getH())); + } else if (this->map->isInsideSurface(this->map->toSurfCoords(path)) == + false) { + throw megaglest_runtime_error( + "Invalid map surface path position = " + path.getString() + + " map surface w x h = " + intToStr(map->getSurfaceW()) + " " + + intToStr(map->getSurfaceH())); + } + } - if(Thread::isCurrentThreadMainThread() == false) { - throw megaglest_runtime_error("Invalid access to UnitPathBasic add from outside main thread current id = " + - intToStr(Thread::getCurrentThreadId()) + " main = " + intToStr(Thread::getMainThreadId())); - } + if (Thread::isCurrentThreadMainThread() == false) { + throw megaglest_runtime_error( + "Invalid access to UnitPathBasic add from outside main thread current " + "id = " + + intToStr(Thread::getCurrentThreadId()) + + " main = " + intToStr(Thread::getMainThreadId())); + } - pathQueue.push_back(path); + pathQueue.push_back(path); } Vec2i UnitPathBasic::pop(bool removeFrontPos) { - if(pathQueue.empty() == true) { - throw megaglest_runtime_error("pathQueue.size() = " + intToStr(pathQueue.size())); - } - Vec2i p= pathQueue.front(); - if(removeFrontPos == true) { - if(Thread::isCurrentThreadMainThread() == false) { - throw megaglest_runtime_error("Invalid access to UnitPathBasic delete from outside main thread current id = " + - intToStr(Thread::getCurrentThreadId()) + " main = " + intToStr(Thread::getMainThreadId())); - } - - pathQueue.erase(pathQueue.begin()); - } - return p; + if (pathQueue.empty() == true) { + throw megaglest_runtime_error("pathQueue.size() = " + + intToStr(pathQueue.size())); + } + Vec2i p = pathQueue.front(); + if (removeFrontPos == true) { + if (Thread::isCurrentThreadMainThread() == false) { + throw megaglest_runtime_error( + "Invalid access to UnitPathBasic delete from outside main thread " + "current id = " + + intToStr(Thread::getCurrentThreadId()) + + " main = " + intToStr(Thread::getMainThreadId())); + } + + pathQueue.erase(pathQueue.begin()); + } + return p; } std::string UnitPathBasic::toString() const { - std::string result = "unit path blockCount = " + intToStr(blockCount) + "\npathQueue size = " + intToStr(pathQueue.size()); - for(int idx = 0; idx < (int)pathQueue.size(); ++idx) { - result += " index = " + intToStr(idx) + " value = " + pathQueue[idx].getString(); - } + std::string result = "unit path blockCount = " + intToStr(blockCount) + + "\npathQueue size = " + intToStr(pathQueue.size()); + for (int idx = 0; idx < (int)pathQueue.size(); ++idx) { + result += + " index = " + intToStr(idx) + " value = " + pathQueue[idx].getString(); + } - return result; + return result; } void UnitPathBasic::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *unitPathBasicNode = rootNode->addChild("UnitPathBasic"); + std::map mapTagReplacements; + XmlNode *unitPathBasicNode = rootNode->addChild("UnitPathBasic"); -// int blockCount; - unitPathBasicNode->addAttribute("blockCount",intToStr(blockCount), mapTagReplacements); -// vector pathQueue; - for(unsigned int i = 0; i < pathQueue.size(); ++i) { - Vec2i &vec = pathQueue[i]; + // int blockCount; + unitPathBasicNode->addAttribute("blockCount", intToStr(blockCount), + mapTagReplacements); + // vector pathQueue; + for (unsigned int i = 0; i < pathQueue.size(); ++i) { + Vec2i &vec = pathQueue[i]; - XmlNode *pathQueueNode = unitPathBasicNode->addChild("pathQueue"); - pathQueueNode->addAttribute("vec",vec.getString(), mapTagReplacements); - } + XmlNode *pathQueueNode = unitPathBasicNode->addChild("pathQueue"); + pathQueueNode->addAttribute("vec", vec.getString(), mapTagReplacements); + } } void UnitPathBasic::loadGame(const XmlNode *rootNode) { - const XmlNode *unitPathBasicNode = rootNode->getChild("UnitPathBasic"); + const XmlNode *unitPathBasicNode = rootNode->getChild("UnitPathBasic"); - blockCount = unitPathBasicNode->getAttribute("blockCount")->getIntValue(); + blockCount = unitPathBasicNode->getAttribute("blockCount")->getIntValue(); - pathQueue.clear(); - vector pathqueueNodeList = unitPathBasicNode->getChildList("pathQueue"); - for(unsigned int i = 0; i < pathqueueNodeList.size(); ++i) { - XmlNode *node = pathqueueNodeList[i]; + pathQueue.clear(); + vector pathqueueNodeList = + unitPathBasicNode->getChildList("pathQueue"); + for (unsigned int i = 0; i < pathqueueNodeList.size(); ++i) { + XmlNode *node = pathqueueNodeList[i]; - Vec2i vec = Vec2i::strToVec2(node->getAttribute("vec")->getValue()); - pathQueue.push_back(vec); - } + Vec2i vec = Vec2i::strToVec2(node->getAttribute("vec")->getValue()); + pathQueue.push_back(vec); + } } Checksum UnitPathBasic::getCRC() { - Checksum crcForPath; + Checksum crcForPath; - crcForPath.addInt(blockCount); - crcForPath.addInt((int)pathQueue.size()); + crcForPath.addInt(blockCount); + crcForPath.addInt((int)pathQueue.size()); - return crcForPath; + return crcForPath; } // ===================================================== // class UnitPath // ===================================================== -//void WaypointPath::condense() { +// void WaypointPath::condense() { // if (size() < 2) { // return; // } @@ -208,300 +224,358 @@ Checksum UnitPathBasic::getCRC() { // ++prev; // } // } -//} +// } std::string UnitPath::toString() const { - std::string result = "unit path blockCount = " + intToStr(blockCount) + " pathQueue size = " + intToStr(size()); - result += " path = "; - for (const_iterator it = begin(); it != end(); ++it) { - result += " [" + intToStr(it->x) + "," + intToStr(it->y) + "]"; - } + std::string result = "unit path blockCount = " + intToStr(blockCount) + + " pathQueue size = " + intToStr(size()); + result += " path = "; + for (const_iterator it = begin(); it != end(); ++it) { + result += " [" + intToStr(it->x) + "," + intToStr(it->y) + "]"; + } - return result; + return result; } // ===================================================== // class UnitReference // ===================================================== -UnitReference::UnitReference(){ - id= -1; - faction= NULL; +UnitReference::UnitReference() { + id = -1; + faction = NULL; } -UnitReference & UnitReference::operator=(const Unit *unit){ - if(unit==NULL){ - id= -1; - faction= NULL; - } - else{ - id= unit->getId(); - faction= unit->getFaction(); - } +UnitReference &UnitReference::operator=(const Unit *unit) { + if (unit == NULL) { + id = -1; + faction = NULL; + } else { + id = unit->getId(); + faction = unit->getFaction(); + } - return *this; + return *this; } -Unit *UnitReference::getUnit() const{ - if(faction!=NULL){ - return faction->findUnit(id); - } - return NULL; +Unit *UnitReference::getUnit() const { + if (faction != NULL) { + return faction->findUnit(id); + } + return NULL; } void UnitReference::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *unitRefNode = rootNode->addChild("UnitReference"); - - unitRefNode->addAttribute("id",intToStr(id), mapTagReplacements); - if(faction != NULL) { - unitRefNode->addAttribute("factionIndex",intToStr(faction->getIndex()), mapTagReplacements); - } + std::map mapTagReplacements; + XmlNode *unitRefNode = rootNode->addChild("UnitReference"); + + unitRefNode->addAttribute("id", intToStr(id), mapTagReplacements); + if (faction != NULL) { + unitRefNode->addAttribute("factionIndex", intToStr(faction->getIndex()), + mapTagReplacements); + } +} + +void UnitReference::loadGame(const XmlNode *rootNode, World *world) { + const XmlNode *unitRefNode = rootNode->getChild("UnitReference"); + + id = unitRefNode->getAttribute("id")->getIntValue(); + if (unitRefNode->hasAttribute("factionIndex") == true) { + int factionIndex = unitRefNode->getAttribute("factionIndex")->getIntValue(); + if (factionIndex >= world->getFactionCount()) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "factionIndex >= world->getFactionCount() [%d] : [%d]", + factionIndex, world->getFactionCount()); + throw megaglest_runtime_error(szBuf); + } + faction = world->getFaction(factionIndex); + } } -void UnitReference::loadGame(const XmlNode *rootNode,World *world) { - const XmlNode *unitRefNode = rootNode->getChild("UnitReference"); +const bool checkMemory = false; +static map memoryObjectList; - id = unitRefNode->getAttribute("id")->getIntValue(); - if(unitRefNode->hasAttribute("factionIndex") == true) { - int factionIndex = unitRefNode->getAttribute("factionIndex")->getIntValue(); - if(factionIndex >= world->getFactionCount()) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"factionIndex >= world->getFactionCount() [%d] : [%d]",factionIndex,world->getFactionCount()); - throw megaglest_runtime_error(szBuf); - } - faction = world->getFaction(factionIndex); - } +UnitAttackBoostEffect::UnitAttackBoostEffect() { + if (checkMemory) { + printf("++ Create UnitAttackBoostEffect [%p] before count = %d\n", this, + memoryObjectList[this]); + memoryObjectList[this]++; + printf("++ Create UnitAttackBoostEffect [%p] after count = %d\n", this, + memoryObjectList[this]); + } + + unitId = -1; + unitPtr = NULL; + boost = NULL; + source = NULL; + ups = NULL; + upst = NULL; } -const bool checkMemory = false; -static map memoryObjectList; +UnitAttackBoostEffect::~UnitAttackBoostEffect() { + if (checkMemory) { + printf("-- Delete UnitAttackBoostEffect [%p] count = %d\n", this, + memoryObjectList[this]); + memoryObjectList[this]--; + assert(memoryObjectList[this] == 0); + } + + if (ups != NULL) { + bool particleValid = + Renderer::getInstance().validateParticleSystemStillExists(ups, rsGame); + if (particleValid == true) { + ups->fade(); + + vector particleSystemToRemove; + particleSystemToRemove.push_back(ups); + + Renderer::getInstance().cleanupUnitParticleSystems(particleSystemToRemove, + rsGame); + ups = NULL; + } + } -UnitAttackBoostEffect::UnitAttackBoostEffect() { - if(checkMemory) { - printf("++ Create UnitAttackBoostEffect [%p] before count = %d\n",this,memoryObjectList[this]); - memoryObjectList[this]++; - printf("++ Create UnitAttackBoostEffect [%p] after count = %d\n",this,memoryObjectList[this]); - } + delete upst; + upst = NULL; +} + +const Unit *UnitAttackBoostEffect::getSource() { + if (source == NULL && unitPtr != NULL && unitId > 0) { + source = unitPtr->getFaction()->findUnit(unitId); - unitId = -1; - unitPtr = NULL; - boost = NULL; - source = NULL; - ups = NULL; - upst = NULL; + // printf("#1 Get source - boost effect unitId = %d unitPtr = %s source = + // %p\n",unitId,unitPtr->getFullName(false).c_str(),source); + } + // printf("#2 Get source - boost effect unitId = %d unitPtr = %s source = + // %p\n",unitId,unitPtr->getFullName(false).c_str(),source); + return source; } -UnitAttackBoostEffect::~UnitAttackBoostEffect() { - if(checkMemory) { - printf("-- Delete UnitAttackBoostEffect [%p] count = %d\n",this,memoryObjectList[this]); - memoryObjectList[this]--; - assert(memoryObjectList[this] == 0); - } - - if(ups != NULL) { - bool particleValid = Renderer::getInstance().validateParticleSystemStillExists(ups,rsGame); - if(particleValid == true) { - ups->fade(); - - vector particleSystemToRemove; - particleSystemToRemove.push_back(ups); - - Renderer::getInstance().cleanupUnitParticleSystems(particleSystemToRemove,rsGame); - ups = NULL; - } - } - - delete upst; - upst = NULL; -} - -const Unit * UnitAttackBoostEffect::getSource() { - if(source == NULL && unitPtr != NULL && unitId > 0) { - source = unitPtr->getFaction()->findUnit(unitId); - - //printf("#1 Get source - boost effect unitId = %d unitPtr = %s source = %p\n",unitId,unitPtr->getFullName(false).c_str(),source); - } - //printf("#2 Get source - boost effect unitId = %d unitPtr = %s source = %p\n",unitId,unitPtr->getFullName(false).c_str(),source); - return source; -} - -void UnitAttackBoostEffect::setSource(const Unit *unit) { - source = unit; -} - -void UnitAttackBoostEffect::applyLoadedAttackBoostParticles(UnitParticleSystemType *upstPtr,const XmlNode *node, Unit* unit) { - if (upstPtr != NULL) { - bool showUnitParticles = Config::getInstance().getBool("UnitParticles","true"); - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - showUnitParticles = false; - } - if (showUnitParticles == true) { - upst = new UnitParticleSystemType(); - *upst = *upstPtr; - upst->loadGame(node); - - ups = new UnitParticleSystem(200); - //ups->loadGame(node2); - ups->setParticleOwner(unit); - ups->setParticleType(upst); - - upst->setValues(ups); - ups->setPos(unit->getCurrVectorForParticlesystems()); - ups->setRotation(unit->getRotation()); - unit->setMeshPosInParticleSystem(ups); - if (unit->getFaction()->getTexture()) { - ups->setFactionColor(unit->getFaction()->getTexture()->getPixmapConst()->getPixel3f(0, 0)); - } - //printf("Adding attack boost particle to deferred buffer: %p\n",ups); - Renderer::getInstance().addToDeferredParticleSystemList(make_pair(ups, rsGame)); - } - } -} - -void UnitAttackBoostEffect::loadGame(const XmlNode *rootNode, Unit *unit, World *world, bool applyToOriginator) { - const XmlNode *unitAttackBoostEffectNode = rootNode; - - if(unitAttackBoostEffectNode->hasAttribute("source") == true) { - unitId = unitAttackBoostEffectNode->getAttribute("source")->getIntValue(); - unitPtr = unit; - source = unit->getFaction()->findUnit(unitId); - -// printf("#1 Loaded boost effect unitId = %d unitPtr = [%d - %s] source = %p\n", -// unitId,unitPtr->getId(),unitPtr->getType()->getName(false).c_str(),source); - } - - // Lets determine the originator unit's attack boost based on the skill used to trigger it - if(unitAttackBoostEffectNode->hasAttribute("source-faction") == true) { - string factionName = unitAttackBoostEffectNode->getAttribute("source-faction")->getValue(); - string unitTypeName = unitAttackBoostEffectNode->getAttribute("source-unit-type")->getValue(); - string skillTypeName = unitAttackBoostEffectNode->getAttribute("source-skill-type")->getValue(); - SkillClass skillClass = static_cast(unitAttackBoostEffectNode->getAttribute("source-skill-class")->getIntValue()); - - const UnitType *unitType = world->findUnitTypeByName(factionName, unitTypeName); - if(unitType != NULL) { - const SkillType *skillType = unitType->getSkillType(skillTypeName,skillClass); - if(skillType != NULL) { - boost = skillType->getAttackBoost(); - -// printf("#2 boost effect unitId = %d unitPtr = [%d - %s] source = %p attackBoost src [%p] dest [%p]\n", -// unitId,unitPtr->getId(),unitPtr->getType()->getName(false).c_str(), -// source,boost->unitParticleSystemTypeForSourceUnit,boost->unitParticleSystemTypeForAffectedUnit); - } - } - } - - if(boost != NULL) { -// printf("unit [%d - %s] applyToOriginator: %d src [%p] dest [%p] Boost attackBoost->enabled = %d:\n%s\n", -// unit->getId(),unit->getType()->getName(false).c_str(),applyToOriginator,boost->unitParticleSystemTypeForSourceUnit,boost->unitParticleSystemTypeForAffectedUnit,boost->enabled,boost->getDesc(false).c_str()); - - if(applyToOriginator == true) { - applyLoadedAttackBoostParticles(boost->unitParticleSystemTypeForSourceUnit, - unitAttackBoostEffectNode, unit); - } - else { - applyLoadedAttackBoostParticles(boost->unitParticleSystemTypeForAffectedUnit, - unitAttackBoostEffectNode, unit); - } - } - else { - printf("******!!!! unit [%d - %s] applyToOriginator: %d NO BOOST FOUND!!!\n",unit->getId(),unit->getType()->getName(false).c_str(),applyToOriginator); - } +void UnitAttackBoostEffect::setSource(const Unit *unit) { source = unit; } + +void UnitAttackBoostEffect::applyLoadedAttackBoostParticles( + UnitParticleSystemType *upstPtr, const XmlNode *node, Unit *unit) { + if (upstPtr != NULL) { + bool showUnitParticles = + Config::getInstance().getBool("UnitParticles", "true"); + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + showUnitParticles = false; + } + if (showUnitParticles == true) { + upst = new UnitParticleSystemType(); + *upst = *upstPtr; + upst->loadGame(node); + + ups = new UnitParticleSystem(200); + // ups->loadGame(node2); + ups->setParticleOwner(unit); + ups->setParticleType(upst); + + upst->setValues(ups); + ups->setPos(unit->getCurrVectorForParticlesystems()); + ups->setRotation(unit->getRotation()); + unit->setMeshPosInParticleSystem(ups); + if (unit->getFaction()->getTexture()) { + ups->setFactionColor( + unit->getFaction()->getTexture()->getPixmapConst()->getPixel3f(0, + 0)); + } + // printf("Adding attack boost particle to deferred buffer: %p\n",ups); + Renderer::getInstance().addToDeferredParticleSystemList( + make_pair(ups, rsGame)); + } + } +} + +void UnitAttackBoostEffect::loadGame(const XmlNode *rootNode, Unit *unit, + World *world, bool applyToOriginator) { + const XmlNode *unitAttackBoostEffectNode = rootNode; + + if (unitAttackBoostEffectNode->hasAttribute("source") == true) { + unitId = unitAttackBoostEffectNode->getAttribute("source")->getIntValue(); + unitPtr = unit; + source = unit->getFaction()->findUnit(unitId); + + // printf("#1 Loaded boost effect unitId = %d unitPtr = [%d - %s] + //source = %p\n", + // unitId,unitPtr->getId(),unitPtr->getType()->getName(false).c_str(),source); + } + + // Lets determine the originator unit's attack boost based on the skill used + // to trigger it + if (unitAttackBoostEffectNode->hasAttribute("source-faction") == true) { + string factionName = + unitAttackBoostEffectNode->getAttribute("source-faction")->getValue(); + string unitTypeName = + unitAttackBoostEffectNode->getAttribute("source-unit-type")->getValue(); + string skillTypeName = + unitAttackBoostEffectNode->getAttribute("source-skill-type") + ->getValue(); + SkillClass skillClass = static_cast( + unitAttackBoostEffectNode->getAttribute("source-skill-class") + ->getIntValue()); + + const UnitType *unitType = + world->findUnitTypeByName(factionName, unitTypeName); + if (unitType != NULL) { + const SkillType *skillType = + unitType->getSkillType(skillTypeName, skillClass); + if (skillType != NULL) { + boost = skillType->getAttackBoost(); + + // printf("#2 boost effect unitId = %d unitPtr + //= + //[%d - %s] source = %p attackBoost src [%p] dest [%p]\n", + // unitId,unitPtr->getId(),unitPtr->getType()->getName(false).c_str(), + // source,boost->unitParticleSystemTypeForSourceUnit,boost->unitParticleSystemTypeForAffectedUnit); + } + } + } + + if (boost != NULL) { + // printf("unit [%d - %s] applyToOriginator: %d src [%p] dest [%p] + //Boost attackBoost->enabled = %d:\n%s\n", + // unit->getId(),unit->getType()->getName(false).c_str(),applyToOriginator,boost->unitParticleSystemTypeForSourceUnit,boost->unitParticleSystemTypeForAffectedUnit,boost->enabled,boost->getDesc(false).c_str()); + + if (applyToOriginator == true) { + applyLoadedAttackBoostParticles( + boost->unitParticleSystemTypeForSourceUnit, unitAttackBoostEffectNode, + unit); + } else { + applyLoadedAttackBoostParticles( + boost->unitParticleSystemTypeForAffectedUnit, + unitAttackBoostEffectNode, unit); + } + } else { + printf( + "******!!!! unit [%d - %s] applyToOriginator: %d NO BOOST FOUND!!!\n", + unit->getId(), unit->getType()->getName(false).c_str(), + applyToOriginator); + } } void UnitAttackBoostEffect::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *unitAttackBoostEffectNode = rootNode->addChild("UnitAttackBoostEffect"); - -// const AttackBoost *boost; - if(boost != NULL) { - boost->saveGame(unitAttackBoostEffectNode); - } -// const Unit *source; - if(getSource() != NULL) { - unitAttackBoostEffectNode->addAttribute("source",intToStr(getSource()->getId()), mapTagReplacements); - - unitAttackBoostEffectNode->addAttribute("source-faction",getSource()->getFaction()->getType()->getName(false), mapTagReplacements); - unitAttackBoostEffectNode->addAttribute("source-unit-type",getSource()->getType()->getName(false), mapTagReplacements); - unitAttackBoostEffectNode->addAttribute("source-skill-type",getSource()->getCurrSkill()->getName(), mapTagReplacements); - unitAttackBoostEffectNode->addAttribute("source-skill-class",intToStr(getSource()->getCurrSkill()->getClass()), mapTagReplacements); - } -// UnitParticleSystem *ups; - if(ups != NULL && Renderer::getInstance().validateParticleSystemStillExists(ups,rsGame) == true) { - ups->saveGame(unitAttackBoostEffectNode); - } - -// UnitParticleSystemType *upst; - if(upst != NULL) { - upst->saveGame(unitAttackBoostEffectNode); - } + std::map mapTagReplacements; + XmlNode *unitAttackBoostEffectNode = + rootNode->addChild("UnitAttackBoostEffect"); + + // const AttackBoost *boost; + if (boost != NULL) { + boost->saveGame(unitAttackBoostEffectNode); + } + // const Unit *source; + if (getSource() != NULL) { + unitAttackBoostEffectNode->addAttribute( + "source", intToStr(getSource()->getId()), mapTagReplacements); + + unitAttackBoostEffectNode->addAttribute( + "source-faction", getSource()->getFaction()->getType()->getName(false), + mapTagReplacements); + unitAttackBoostEffectNode->addAttribute( + "source-unit-type", getSource()->getType()->getName(false), + mapTagReplacements); + unitAttackBoostEffectNode->addAttribute( + "source-skill-type", getSource()->getCurrSkill()->getName(), + mapTagReplacements); + unitAttackBoostEffectNode->addAttribute( + "source-skill-class", intToStr(getSource()->getCurrSkill()->getClass()), + mapTagReplacements); + } + // UnitParticleSystem *ups; + if (ups != NULL && Renderer::getInstance().validateParticleSystemStillExists( + ups, rsGame) == true) { + ups->saveGame(unitAttackBoostEffectNode); + } + + // UnitParticleSystemType *upst; + if (upst != NULL) { + upst->saveGame(unitAttackBoostEffectNode); + } } UnitAttackBoostEffectOriginator::UnitAttackBoostEffectOriginator() { - skillType = NULL; - currentAppliedEffect = NULL; + skillType = NULL; + currentAppliedEffect = NULL; } UnitAttackBoostEffectOriginator::~UnitAttackBoostEffectOriginator() { - delete currentAppliedEffect; - currentAppliedEffect = NULL; -} - -void UnitAttackBoostEffectOriginator::loadGame(const XmlNode *rootNode, Unit *unit, World *world) { - const XmlNode *unitAttackBoostEffectOriginatorNode = rootNode->getChild("UnitAttackBoostEffectOriginator"); - - SkillClass skillClass = scStop; - string skillTypeName = unitAttackBoostEffectOriginatorNode->getAttribute("skillType")->getValue(); - if(unitAttackBoostEffectOriginatorNode->hasAttribute("skillClass") == false) { - int skillCount = unit->getType()->getSkillTypeCount(); - for(int index = 0; index < skillCount; ++index) { - const SkillType *st = unit->getType()->getSkillType(index); - if(st->getName() == skillTypeName) { - skillClass = st->getClass(); - break; - } - } - } - else { - skillClass = static_cast(unitAttackBoostEffectOriginatorNode->getAttribute("skillClass")->getIntValue()); - } - - this->skillType = unit->getType()->getSkillType(skillTypeName,skillClass); - - if(unitAttackBoostEffectOriginatorNode->hasChild("currentAttackBoostUnits") == true) { - vector currentAttackBoostUnitsNodeList = unitAttackBoostEffectOriginatorNode->getChildList("currentAttackBoostUnits"); - for(unsigned int i = 0; i < currentAttackBoostUnitsNodeList.size(); ++i) { - XmlNode *node = currentAttackBoostUnitsNodeList[i]; - - int unitId = node->getAttribute("value")->getIntValue(); - currentAttackBoostUnits.push_back(unitId); - } - } - - if(unitAttackBoostEffectOriginatorNode->hasChild("UnitAttackBoostEffect") == true) { - currentAppliedEffect = new UnitAttackBoostEffect(); - currentAppliedEffect->loadGame(unitAttackBoostEffectOriginatorNode, unit,world, true); - } + delete currentAppliedEffect; + currentAppliedEffect = NULL; +} + +void UnitAttackBoostEffectOriginator::loadGame(const XmlNode *rootNode, + Unit *unit, World *world) { + const XmlNode *unitAttackBoostEffectOriginatorNode = + rootNode->getChild("UnitAttackBoostEffectOriginator"); + + SkillClass skillClass = scStop; + string skillTypeName = + unitAttackBoostEffectOriginatorNode->getAttribute("skillType") + ->getValue(); + if (unitAttackBoostEffectOriginatorNode->hasAttribute("skillClass") == + false) { + int skillCount = unit->getType()->getSkillTypeCount(); + for (int index = 0; index < skillCount; ++index) { + const SkillType *st = unit->getType()->getSkillType(index); + if (st->getName() == skillTypeName) { + skillClass = st->getClass(); + break; + } + } + } else { + skillClass = static_cast( + unitAttackBoostEffectOriginatorNode->getAttribute("skillClass") + ->getIntValue()); + } + + this->skillType = unit->getType()->getSkillType(skillTypeName, skillClass); + + if (unitAttackBoostEffectOriginatorNode->hasChild( + "currentAttackBoostUnits") == true) { + vector currentAttackBoostUnitsNodeList = + unitAttackBoostEffectOriginatorNode->getChildList( + "currentAttackBoostUnits"); + for (unsigned int i = 0; i < currentAttackBoostUnitsNodeList.size(); ++i) { + XmlNode *node = currentAttackBoostUnitsNodeList[i]; + + int unitId = node->getAttribute("value")->getIntValue(); + currentAttackBoostUnits.push_back(unitId); + } + } + + if (unitAttackBoostEffectOriginatorNode->hasChild("UnitAttackBoostEffect") == + true) { + currentAppliedEffect = new UnitAttackBoostEffect(); + currentAppliedEffect->loadGame(unitAttackBoostEffectOriginatorNode, unit, + world, true); + } } void UnitAttackBoostEffectOriginator::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *unitAttackBoostEffectOriginatorNode = rootNode->addChild("UnitAttackBoostEffectOriginator"); - -// const SkillType *skillType; - if(skillType != NULL) { - unitAttackBoostEffectOriginatorNode->addAttribute("skillType",skillType->getName(), mapTagReplacements); - unitAttackBoostEffectOriginatorNode->addAttribute("skillClass",intToStr(skillType->getClass()), mapTagReplacements); - } -// std::vector currentAttackBoostUnits; - for(unsigned int i = 0; i < currentAttackBoostUnits.size(); ++i) { - XmlNode *currentAttackBoostUnitsNode = unitAttackBoostEffectOriginatorNode->addChild("currentAttackBoostUnits"); - currentAttackBoostUnitsNode->addAttribute("value",intToStr(currentAttackBoostUnits[i]), mapTagReplacements); - } -// UnitAttackBoostEffect *currentAppliedEffect; - if(currentAppliedEffect != NULL) { - currentAppliedEffect->saveGame(unitAttackBoostEffectOriginatorNode); - } + std::map mapTagReplacements; + XmlNode *unitAttackBoostEffectOriginatorNode = + rootNode->addChild("UnitAttackBoostEffectOriginator"); + + // const SkillType *skillType; + if (skillType != NULL) { + unitAttackBoostEffectOriginatorNode->addAttribute( + "skillType", skillType->getName(), mapTagReplacements); + unitAttackBoostEffectOriginatorNode->addAttribute( + "skillClass", intToStr(skillType->getClass()), mapTagReplacements); + } + // std::vector currentAttackBoostUnits; + for (unsigned int i = 0; i < currentAttackBoostUnits.size(); ++i) { + XmlNode *currentAttackBoostUnitsNode = + unitAttackBoostEffectOriginatorNode->addChild( + "currentAttackBoostUnits"); + currentAttackBoostUnitsNode->addAttribute( + "value", intToStr(currentAttackBoostUnits[i]), mapTagReplacements); + } + // UnitAttackBoostEffect *currentAppliedEffect; + if (currentAppliedEffect != NULL) { + currentAppliedEffect->saveGame(unitAttackBoostEffectOriginatorNode); + } } // ===================================================== @@ -509,5412 +583,6391 @@ void UnitAttackBoostEffectOriginator::saveGame(XmlNode *rootNode) { // ===================================================== const float Unit::ANIMATION_SPEED_MULTIPLIER = 100000.f; -//const float Unit::PROGRESS_SPEED_MULTIPLIER = 100000.f; -const int64 Unit::PROGRESS_SPEED_MULTIPLIER = 100000; +// const float Unit::PROGRESS_SPEED_MULTIPLIER = 100000.f; +const int64 Unit::PROGRESS_SPEED_MULTIPLIER = 100000; -const int Unit::speedDivider= 100; -const int Unit::maxDeadCount= 1000; //time in until the corpse disapears - should be about 40 seconds -const int Unit::invalidId= -1; +const int Unit::speedDivider = 100; +const int Unit::maxDeadCount = + 1000; // time in until the corpse disapears - should be about 40 seconds +const int Unit::invalidId = -1; -//set Unit::livingUnits; -//set Unit::livingUnitsp; +// set Unit::livingUnits; +// set Unit::livingUnitsp; -// ============================ Constructor & destructor ============================= +// ============================ Constructor & destructor +// ============================= Game *Unit::game = NULL; Unit::Unit(int id, UnitPathInterface *unitpath, const Vec2i &pos, - const UnitType *type, Faction *faction, Map *map, CardinalDir placeFacing) : BaseColorPickEntity(), id(id) { + const UnitType *type, Faction *faction, Map *map, + CardinalDir placeFacing) + : BaseColorPickEntity(), id(id) { #ifdef LEAK_CHECK_UNITS - Unit::mapMemoryList[this]=true; + Unit::mapMemoryList[this] = true; #endif - mutexCommands = new Mutex(CODE_AT_LINE); - changedActiveCommand = false; - lastChangedActiveCommandFrame = 0; - changedActiveCommandFrame = 0; - - lastSynchDataString=""; - modelFacing = CardinalDir(CardinalDir::NORTH); - lastStuckFrame = 0; - lastStuckPos = Vec2i(0,0); - lastPathfindFailedFrame = 0; - lastPathfindFailedPos = Vec2i(0,0); - usePathfinderExtendedMaxNodes = false; - this->currentAttackBoostOriginatorEffect.skillType = NULL; - lastAttackerUnitId = -1; - lastAttackedUnitId = -1; - causeOfDeath = ucodNone; - pathfindFailedConsecutiveFrameCount = 0; - - lastSynchDataString = ""; - lastFile = ""; - lastLine = 0; - lastSource = ""; - - targetRotationZ=.0f; - targetRotationX=.0f; - rotationZ=.0f; - rotationX=.0f; - - this->fire= NULL; - this->unitPath = unitpath; - this->unitPath->setMap(map); - - //RandomGen random; + mutexCommands = new Mutex(CODE_AT_LINE); + changedActiveCommand = false; + lastChangedActiveCommandFrame = 0; + changedActiveCommandFrame = 0; + + lastSynchDataString = ""; + modelFacing = CardinalDir(CardinalDir::NORTH); + lastStuckFrame = 0; + lastStuckPos = Vec2i(0, 0); + lastPathfindFailedFrame = 0; + lastPathfindFailedPos = Vec2i(0, 0); + usePathfinderExtendedMaxNodes = false; + this->currentAttackBoostOriginatorEffect.skillType = NULL; + lastAttackerUnitId = -1; + lastAttackedUnitId = -1; + causeOfDeath = ucodNone; + pathfindFailedConsecutiveFrameCount = 0; + + lastSynchDataString = ""; + lastFile = ""; + lastLine = 0; + lastSource = ""; + + targetRotationZ = .0f; + targetRotationX = .0f; + rotationZ = .0f; + rotationX = .0f; + + this->fire = NULL; + this->unitPath = unitpath; + this->unitPath->setMap(map); + + // RandomGen random; + random.init(id); + random.setDisableLastCallerTracking(isNetworkCRCEnabled() == false); + pathFindRefreshCellCount = random.randRange(10, 20, intToStr(__LINE__)); + + if (map->isInside(pos) == false || + map->isInsideSurface(map->toSurfCoords(pos)) == false) { + throw megaglest_runtime_error("#2 Invalid path position = " + + pos.getString()); + } + + this->pos = pos; + + this->faction = faction; + this->preMorph_type = NULL; + this->type = type; + setType(this->type); + + this->map = map; + this->targetRef = NULL; + this->targetField = fLand; + this->targetVec = Vec3f(0.0); + this->targetPos = Vec2i(0); + this->lastRenderFrame = 0; + this->visible = true; + this->retryCurrCommandCount = 0; + this->screenPos = Vec3f(0.0); + this->ignoreCheckCommand = false; + this->inBailOutAttempt = false; + this->lastHarvestResourceTarget.first = Vec2i(0); + this->morphFieldsBlocked = false; + // this->lastBadHarvestListPurge = 0; + this->oldTotalSight = 0; + + level = NULL; + loadType = NULL; + + setModelFacing(placeFacing); + + Config &config = Config::getInstance(); + showUnitParticles = config.getBool("UnitParticles", "true"); + maxQueuedCommandDisplayCount = + config.getInt("MaxQueuedCommandDisplayCount", "15"); + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + showUnitParticles = false; + } + + lastPos = pos; + progress = 0; + this->lastAnimProgress = 0; + this->animProgress = 0; + progress2 = 0; + kills = 0; + enemyKills = 0; + loadCount = 0; + ep = 0; + deadCount = 0; + hp = type->getMaxHp() / 20; + toBeUndertaken = false; + + highlight = 0.f; + meetingPos = pos; + setAlive(true); + + if (type->hasSkillClass(scBeBuilt) == false) { + float rot = 0.f; random.init(id); - random.setDisableLastCallerTracking(isNetworkCRCEnabled() == false); - pathFindRefreshCellCount = random.randRange(10,20,intToStr(__LINE__)); - - if(map->isInside(pos) == false || map->isInsideSurface(map->toSurfCoords(pos)) == false) { - throw megaglest_runtime_error("#2 Invalid path position = " + pos.getString()); - } - - this->pos=pos; - - this->faction=faction; - this->preMorph_type = NULL; - this->type=type; - setType(this->type); - - this->map= map; - this->targetRef = NULL; - this->targetField = fLand; - this->targetVec = Vec3f(0.0); - this->targetPos = Vec2i(0); - this->lastRenderFrame = 0; - this->visible = true; - this->retryCurrCommandCount=0; - this->screenPos = Vec3f(0.0); - this->ignoreCheckCommand = false; - this->inBailOutAttempt = false; - this->lastHarvestResourceTarget.first = Vec2i(0); - this->morphFieldsBlocked=false; - //this->lastBadHarvestListPurge = 0; - this->oldTotalSight = 0; - - level= NULL; - loadType= NULL; - - setModelFacing(placeFacing); - - Config &config= Config::getInstance(); - showUnitParticles = config.getBool("UnitParticles","true"); - maxQueuedCommandDisplayCount = config.getInt("MaxQueuedCommandDisplayCount","15"); - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { - showUnitParticles = false; - } - - lastPos= pos; - progress= 0; - this->lastAnimProgress= 0; - this->animProgress= 0; - progress2= 0; - kills= 0; - enemyKills = 0; - loadCount= 0; - ep= 0; - deadCount= 0; - hp= type->getMaxHp() / 20; - toBeUndertaken= false; - - highlight= 0.f; - meetingPos= pos; - setAlive(true); - - if (type->hasSkillClass(scBeBuilt) == false) { - float rot= 0.f; - random.init(id); - rot += random.randRange(-5, 5,intToStr(__LINE__)); - rotation= rot; - lastRotation= rot; - targetRotation= rot; - } - // else it was set appropriately in setModelFacing() - - if(getType()->getField(fAir)) { - currField = fAir; - } - if(getType()->getField(fLand)) { - currField = fLand; - } - - computeTotalUpgrade(); - - //starting skill - this->lastModelIndexForCurrSkillType = -1; - this->animationRandomCycleCount = 0; - this->currSkill = getType()->getFirstStOfClass(scStop); - this->setCurrSkill(this->currSkill); - this->currentAttackBoostOriginatorEffect.skillType = this->currSkill; - - this->faction->addLivingUnits(id); - this->faction->addLivingUnitsp(this); - - addItemToVault(&this->hp,this->hp); - addItemToVault(&this->ep,this->ep); - - calculateFogOfWarRadius(); - -// if(isUnitDeleted(this) == true) { -// MutexSafeWrapper safeMutex(&mutexDeletedUnits,string(__FILE__) + "_" + intToStr(__LINE__)); -// deletedUnits.erase(this); -// } + rot += random.randRange(-5, 5, intToStr(__LINE__)); + rotation = rot; + lastRotation = rot; + targetRotation = rot; + } + // else it was set appropriately in setModelFacing() + + if (getType()->getField(fAir)) { + currField = fAir; + } + if (getType()->getField(fLand)) { + currField = fLand; + } - logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + computeTotalUpgrade(); + + // starting skill + this->lastModelIndexForCurrSkillType = -1; + this->animationRandomCycleCount = 0; + this->currSkill = getType()->getFirstStOfClass(scStop); + this->setCurrSkill(this->currSkill); + this->currentAttackBoostOriginatorEffect.skillType = this->currSkill; + + this->faction->addLivingUnits(id); + this->faction->addLivingUnitsp(this); + + addItemToVault(&this->hp, this->hp); + addItemToVault(&this->ep, this->ep); + + calculateFogOfWarRadius(); + + // if(isUnitDeleted(this) == true) { + // MutexSafeWrapper safeMutex(&mutexDeletedUnits,string(__FILE__) + + //"_" + //+ intToStr(__LINE__)); deletedUnits.erase(this); + // } + + logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), __LINE__); } Unit::~Unit() { - badHarvestPosList.clear(); - - this->faction->deleteLivingUnits(id); - this->faction->deleteLivingUnitsp(this); + badHarvestPosList.clear(); - //remove commands - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(mutexCommands,mutexOwnerId); + this->faction->deleteLivingUnits(id); + this->faction->deleteLivingUnitsp(this); - changedActiveCommand = false; - while(commands.empty() == false) { - delete commands.back(); - commands.pop_back(); - } - safeMutex.ReleaseLock(); + // remove commands + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(mutexCommands, mutexOwnerId); - cleanupAllParticlesystems(); + changedActiveCommand = false; + while (commands.empty() == false) { + delete commands.back(); + commands.pop_back(); + } + safeMutex.ReleaseLock(); - while(currentAttackBoostEffects.empty() == false) { - //UnitAttackBoostEffect &effect = currentAttackBoostEffects.back(); - UnitAttackBoostEffect *ab = currentAttackBoostEffects.back(); - delete ab; - currentAttackBoostEffects.pop_back(); - } + cleanupAllParticlesystems(); - delete currentAttackBoostOriginatorEffect.currentAppliedEffect; - currentAttackBoostOriginatorEffect.currentAppliedEffect = NULL; + while (currentAttackBoostEffects.empty() == false) { + // UnitAttackBoostEffect &effect = currentAttackBoostEffects.back(); + UnitAttackBoostEffect *ab = currentAttackBoostEffects.back(); + delete ab; + currentAttackBoostEffects.pop_back(); + } - //Renderer::getInstance().cleanupParticleSystems(attackParticleSystems,rsGame); - Renderer::getInstance().removeParticleSystemsForParticleOwner(this,rsGame); + delete currentAttackBoostOriginatorEffect.currentAppliedEffect; + currentAttackBoostOriginatorEffect.currentAppliedEffect = NULL; + // Renderer::getInstance().cleanupParticleSystems(attackParticleSystems,rsGame); + Renderer::getInstance().removeParticleSystemsForParticleOwner(this, rsGame); #ifdef LEAK_CHECK_UNITS - Unit::mapMemoryList2[this->unitPath] = this->getId(); + Unit::mapMemoryList2[this->unitPath] = this->getId(); #endif - delete this->unitPath; - this->unitPath = NULL; + delete this->unitPath; + this->unitPath = NULL; - Renderer &renderer= Renderer::getInstance(); - renderer.removeUnitFromQuadCache(this); - if(game != NULL) { - game->removeUnitFromSelection(this); - } + Renderer &renderer = Renderer::getInstance(); + renderer.removeUnitFromQuadCache(this); + if (game != NULL) { + game->removeUnitFromSelection(this); + } - //MutexSafeWrapper safeMutex1(&mutexDeletedUnits,string(__FILE__) + "_" + intToStr(__LINE__)); - //deletedUnits[this]=true; + // MutexSafeWrapper safeMutex1(&mutexDeletedUnits,string(__FILE__) + "_" + + // intToStr(__LINE__)); deletedUnits[this]=true; - delete mutexCommands; - mutexCommands=NULL; + delete mutexCommands; + mutexCommands = NULL; #ifdef LEAK_CHECK_UNITS - Unit::mapMemoryList.erase(this); + Unit::mapMemoryList.erase(this); #endif } void Unit::cleanupAllParticlesystems() { - Renderer::getInstance().cleanupUnitParticleSystems(unitParticleSystems,rsGame); + Renderer::getInstance().cleanupUnitParticleSystems(unitParticleSystems, + rsGame); - Renderer::getInstance().cleanupParticleSystems(fireParticleSystems,rsGame); - // Must set this to null of it will be used below in stopDamageParticles() + Renderer::getInstance().cleanupParticleSystems(fireParticleSystems, rsGame); + // Must set this to null of it will be used below in stopDamageParticles() - if(Renderer::getInstance().validateParticleSystemStillExists(this->fire,rsGame) == false) { - this->fire = NULL; - } - - // fade(and by this remove) all unit particle systems - queuedUnitParticleSystemTypes.clear(); - while(unitParticleSystems.empty() == false) { - if(Renderer::getInstance().validateParticleSystemStillExists(unitParticleSystems.back(),rsGame) == true) { - unitParticleSystems.back()->fade(); - } - unitParticleSystems.pop_back(); - } - stopDamageParticles(true); + if (Renderer::getInstance().validateParticleSystemStillExists( + this->fire, rsGame) == false) { + this->fire = NULL; + } + // fade(and by this remove) all unit particle systems + queuedUnitParticleSystemTypes.clear(); + while (unitParticleSystems.empty() == false) { + if (Renderer::getInstance().validateParticleSystemStillExists( + unitParticleSystems.back(), rsGame) == true) { + unitParticleSystems.back()->fade(); + } + unitParticleSystems.pop_back(); + } + stopDamageParticles(true); } -ParticleSystem * Unit::getFire() const { - if(this->fire != NULL && - Renderer::getInstance().validateParticleSystemStillExists(this->fire,rsGame) == false) { - return NULL; - } - return this->fire; +ParticleSystem *Unit::getFire() const { + if (this->fire != NULL && + Renderer::getInstance().validateParticleSystemStillExists( + this->fire, rsGame) == false) { + return NULL; + } + return this->fire; } void Unit::setType(const UnitType *newType) { - this->faction->notifyUnitTypeChange(this, newType); - this->type = newType; + this->faction->notifyUnitTypeChange(this, newType); + this->type = newType; } void Unit::setAlive(bool value) { - this->alive = value; - this->faction->notifyUnitAliveStatusChange(this); + this->alive = value; + this->faction->notifyUnitAliveStatusChange(this); } #ifdef LEAK_CHECK_UNITS void Unit::dumpMemoryList() { - printf("===== START report of Unfreed Unit pointers =====\n"); - for(std::map::iterator iterMap = Unit::mapMemoryList.begin(); - iterMap != Unit::mapMemoryList.end(); ++iterMap) { - printf("************** ==> Unfreed Unit pointer [%p]\n",iterMap->first); - } + printf("===== START report of Unfreed Unit pointers =====\n"); + for (std::map::iterator iterMap = Unit::mapMemoryList.begin(); + iterMap != Unit::mapMemoryList.end(); ++iterMap) { + printf("************** ==> Unfreed Unit pointer [%p]\n", iterMap->first); + } } #endif bool Unit::isNetworkCRCEnabled() { - bool isNetworkCRCEnabled = false; + bool isNetworkCRCEnabled = false; - if(game != NULL) { - if(game->isFlagType1BitEnabled(ft1_network_synch_checks_verbose) == true) { - isNetworkCRCEnabled = true; - } - else if(game->isFlagType1BitEnabled(ft1_network_synch_checks) == true) { - isNetworkCRCEnabled = true; - } - } - return isNetworkCRCEnabled; + if (game != NULL) { + if (game->isFlagType1BitEnabled(ft1_network_synch_checks_verbose) == true) { + isNetworkCRCEnabled = true; + } else if (game->isFlagType1BitEnabled(ft1_network_synch_checks) == true) { + isNetworkCRCEnabled = true; + } + } + return isNetworkCRCEnabled; } void Unit::clearNetworkCRCDecHpList() { - if(networkCRCDecHpList.empty() == false) { - networkCRCDecHpList.clear(); - } + if (networkCRCDecHpList.empty() == false) { + networkCRCDecHpList.clear(); + } } void Unit::clearParticleInfo() { - if(networkCRCParticleInfoList.empty() == false) { - networkCRCParticleInfoList.clear(); - } + if (networkCRCParticleInfoList.empty() == false) { + networkCRCParticleInfoList.clear(); + } } void Unit::addNetworkCRCDecHp(string info) { - if(isNetworkCRCEnabled() == true) { - networkCRCDecHpList.push_back(info); - } + if (isNetworkCRCEnabled() == true) { + networkCRCDecHpList.push_back(info); + } } void Unit::logParticleInfo(string info) { - if(isNetworkCRCEnabled() == true) { - networkCRCParticleInfoList.push_back(info); - } + if (isNetworkCRCEnabled() == true) { + networkCRCParticleInfoList.push_back(info); + } } string Unit::getParticleInfo() const { - string result = ""; - if(networkCRCParticleInfoList.empty() == false) { - for(unsigned int index = 0; index < networkCRCParticleInfoList.size(); ++index) { - result += networkCRCParticleInfoList[index] + "|"; - } - } - return result; + string result = ""; + if (networkCRCParticleInfoList.empty() == false) { + for (unsigned int index = 0; index < networkCRCParticleInfoList.size(); + ++index) { + result += networkCRCParticleInfoList[index] + "|"; + } + } + return result; } void Unit::end(ParticleSystem *particleSystem) { - if(particleSystem == fire) { - fire = NULL; - } - - vector::iterator iterFind = find(attackParticleSystems.begin(),attackParticleSystems.end(),particleSystem); - if(iterFind != attackParticleSystems.end()) { - attackParticleSystems.erase(iterFind); - return; - } - vector::iterator iterFind1 = find(smokeParticleSystems.begin(),smokeParticleSystems.end(),particleSystem); - if(iterFind1 != smokeParticleSystems.end()) { - smokeParticleSystems.erase(iterFind1); - return; - } - iterFind = find(fireParticleSystems.begin(),fireParticleSystems.end(),particleSystem); - if(iterFind != fireParticleSystems.end()) { - fireParticleSystems.erase(iterFind); - return; - } - iterFind1 = find(damageParticleSystems.begin(),damageParticleSystems.end(),particleSystem); - if(iterFind1 != damageParticleSystems.end()) { - damageParticleSystems.erase(iterFind1); - return; - } - - iterFind1 = find(unitParticleSystems.begin(),unitParticleSystems.end(),particleSystem); - if(iterFind1 != unitParticleSystems.end()) { - unitParticleSystems.erase(iterFind1); - return; - } -} - -//bool Unit::isUnitDeleted(void *unit) { + if (particleSystem == fire) { + fire = NULL; + } + + vector::iterator iterFind = + find(attackParticleSystems.begin(), attackParticleSystems.end(), + particleSystem); + if (iterFind != attackParticleSystems.end()) { + attackParticleSystems.erase(iterFind); + return; + } + vector::iterator iterFind1 = find( + smokeParticleSystems.begin(), smokeParticleSystems.end(), particleSystem); + if (iterFind1 != smokeParticleSystems.end()) { + smokeParticleSystems.erase(iterFind1); + return; + } + iterFind = find(fireParticleSystems.begin(), fireParticleSystems.end(), + particleSystem); + if (iterFind != fireParticleSystems.end()) { + fireParticleSystems.erase(iterFind); + return; + } + iterFind1 = find(damageParticleSystems.begin(), damageParticleSystems.end(), + particleSystem); + if (iterFind1 != damageParticleSystems.end()) { + damageParticleSystems.erase(iterFind1); + return; + } + + iterFind1 = find(unitParticleSystems.begin(), unitParticleSystems.end(), + particleSystem); + if (iterFind1 != unitParticleSystems.end()) { + unitParticleSystems.erase(iterFind1); + return; + } +} + +// bool Unit::isUnitDeleted(void *unit) { // bool result = false; -// MutexSafeWrapper safeMutex(&mutexDeletedUnits,string(__FILE__) + "_" + intToStr(__LINE__)); -// if(deletedUnits.find(unit) != deletedUnits.end()) { -// result = true; +// MutexSafeWrapper safeMutex(&mutexDeletedUnits,string(__FILE__) + "_" + +// intToStr(__LINE__)); if(deletedUnits.find(unit) != deletedUnits.end()) +// { result = true; // } // return result; -//} +// } void Unit::setModelFacing(CardinalDir value) { - modelFacing = value; - lastRotation = targetRotation = rotation = value * 90.f; + modelFacing = value; + lastRotation = targetRotation = rotation = value * 90.f; } -//void Unit::setCurrField(Field currField) { +// void Unit::setCurrField(Field currField) { // Field original_field = this->currField; // // this->currField = currField; // // if(original_field != this->currField) { -// //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); +// //printf("File: %s line: +//%d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); // game->getScriptManager()->onUnitTriggerEvent(this,utet_FieldChanged); -// //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); +// //printf("File: %s line: +//%d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); // } -//} -// ====================================== get ====================================== +// } +// ====================================== get +// ====================================== Vec2i Unit::getCenteredPos() const { - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(mutexCommands,mutexOwnerId); + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(mutexCommands, mutexOwnerId); - if(type == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } + if (type == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } - return pos + Vec2i(type->getSize()/2, type->getSize()/2); + return pos + Vec2i(type->getSize() / 2, type->getSize() / 2); } Vec2f Unit::getFloatCenteredPos() const { - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(mutexCommands,mutexOwnerId); + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(mutexCommands, mutexOwnerId); - if(type == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } + if (type == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } - return Vec2f(truncateDecimal(pos.x-0.5f+type->getSize()/2.f,6), - truncateDecimal(pos.y-0.5f+type->getSize()/2.f,6)); + return Vec2f(truncateDecimal(pos.x - 0.5f + type->getSize() / 2.f, 6), + truncateDecimal(pos.y - 0.5f + type->getSize() / 2.f, 6)); } Vec2i Unit::getCellPos() const { - if(type == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - if(type->hasCellMap()) { - if( type->hasEmptyCellMap() == false || - type->getAllowEmptyCellMap() == true) { - - //find nearest pos to center that is free - Vec2i centeredPos= getCenteredPos(); - float nearestDist= -1.f; - Vec2i nearestPos= pos; - - for(int i=0; igetSize(); ++i){ - for(int j=0; jgetSize(); ++j){ - if(type->getCellMapCell(i, j, modelFacing)){ - Vec2i currPos= pos + Vec2i(i, j); - float dist= currPos.dist(centeredPos); - if(nearestDist == -1.f || dist < nearestDist) { - nearestDist= dist; - nearestPos= currPos; - } - } - } - } - return nearestPos; - } - } - return pos; -} - - - -void Unit::calculateXZRotation(){ - //if(type->getProperty(UnitType::pRotatedClimb) && currSkill->getClass()==scMove){ - //if(currSkill->getClass()==scMove) - if(lastPos != pos){ // targetPosCalc ( maybe also sometimes needed if no move ? terrain flatting... ) - SurfaceCell* sc= map->getSurfaceCell(Map::toSurfCoords(pos)); - const Vec3f normal= sc->getNormal(); + if (type == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + if (type->hasCellMap()) { + if (type->hasEmptyCellMap() == false || + type->getAllowEmptyCellMap() == true) { + + // find nearest pos to center that is free + Vec2i centeredPos = getCenteredPos(); + float nearestDist = -1.f; + Vec2i nearestPos = pos; + + for (int i = 0; i < type->getSize(); ++i) { + for (int j = 0; j < type->getSize(); ++j) { + if (type->getCellMapCell(i, j, modelFacing)) { + Vec2i currPos = pos + Vec2i(i, j); + float dist = currPos.dist(centeredPos); + if (nearestDist == -1.f || dist < nearestDist) { + nearestDist = dist; + nearestPos = currPos; + } + } + } + } + return nearestPos; + } + } + return pos; +} + +void Unit::calculateXZRotation() { + // if(type->getProperty(UnitType::pRotatedClimb) && + // currSkill->getClass()==scMove){ if(currSkill->getClass()==scMove) + if (lastPos != pos) { // targetPosCalc ( maybe also sometimes needed if no + // move ? terrain flatting... ) + SurfaceCell *sc = map->getSurfaceCell(Map::toSurfCoords(pos)); + const Vec3f normal = sc->getNormal(); #ifdef USE_STREFLOP - targetRotationZ= radToDeg(streflop::atan2(static_cast(abs(normal.x)), static_cast(abs(normal.y)))); + targetRotationZ = + radToDeg(streflop::atan2(static_cast(abs(normal.x)), + static_cast(abs(normal.y)))); #else - targetRotationZ= radToDeg(atan2(abs(normal.x), abs(normal.y))); + targetRotationZ = radToDeg(atan2(abs(normal.x), abs(normal.y))); #endif - if((normal.y < 0 || normal.x < 0) && !(normal.y < 0 && normal.x < 0)){ - targetRotationZ= targetRotationZ * -1; - } - targetRotationZ= targetRotationZ * -1; + if ((normal.y < 0 || normal.x < 0) && !(normal.y < 0 && normal.x < 0)) { + targetRotationZ = targetRotationZ * -1; + } + targetRotationZ = targetRotationZ * -1; #ifdef USE_STREFLOP - targetRotationX= radToDeg(streflop::atan2(static_cast(abs(normal.z)), static_cast(abs(normal.y)))); + targetRotationX = + radToDeg(streflop::atan2(static_cast(abs(normal.z)), + static_cast(abs(normal.y)))); #else - targetRotationX= radToDeg(atan2(abs(normal.z), abs(normal.y))); + targetRotationX = radToDeg(atan2(abs(normal.z), abs(normal.y))); #endif - if((normal.y < 0 || normal.z < 0) && !(normal.y < 0 && normal.z < 0)){ - targetRotationX= targetRotationX * -1; - } - } - - //For smooth rotation we now softly adjust the angle - int adjustStep= 1; - if(rotationZ < targetRotationZ){ - if(rotationZ + adjustStep > targetRotationZ){ - rotationZ= targetRotationZ; - } - else{ - rotationZ= rotationZ + adjustStep; - } - } - else if(rotationZ > targetRotationZ){ - if(rotationZ - adjustStep < targetRotationZ){ - rotationZ= targetRotationZ; - } - else{ - rotationZ= rotationZ - adjustStep; - } - } - - if(rotationX < targetRotationX){ - if(rotationX + adjustStep > targetRotationX){ - rotationX= targetRotationX; - } - else{ - rotationX= rotationX + adjustStep; - } - } - else if(rotationX > targetRotationX){ - if(rotationX - adjustStep < targetRotationX){ - rotationX= targetRotationX; - } - else{ - rotationX= rotationX - adjustStep; - } - } -} - -float Unit::getRotationZ() const{ - return rotationZ; -} - -float Unit::getRotationX() const{ - return rotationX; -} - -int Unit::getProductionPercent() const{ - if(anyCommand()){ - const ProducibleType *produced= commands.front()->getCommandType()->getProduced(); - if(produced != NULL) { - if(produced->getProductionTime() == 0) { - return 0; - } - return clamp(progress2 * 100 / produced->getProductionTime(), 0, 100); - } - } - return -1; -} - -float Unit::getProgressRatio() const{ - if(anyCommand()){ - const ProducibleType *produced= commands.front()->getCommandType()->getProduced(); - if(produced != NULL){ - if(produced->getProductionTime() == 0) { - return 0.f; - } - - float help = progress2; - return clamp(help / produced->getProductionTime(), 0.f, 1.f); - } - } - return -1; + if ((normal.y < 0 || normal.z < 0) && !(normal.y < 0 && normal.z < 0)) { + targetRotationX = targetRotationX * -1; + } + } + + // For smooth rotation we now softly adjust the angle + int adjustStep = 1; + if (rotationZ < targetRotationZ) { + if (rotationZ + adjustStep > targetRotationZ) { + rotationZ = targetRotationZ; + } else { + rotationZ = rotationZ + adjustStep; + } + } else if (rotationZ > targetRotationZ) { + if (rotationZ - adjustStep < targetRotationZ) { + rotationZ = targetRotationZ; + } else { + rotationZ = rotationZ - adjustStep; + } + } + + if (rotationX < targetRotationX) { + if (rotationX + adjustStep > targetRotationX) { + rotationX = targetRotationX; + } else { + rotationX = rotationX + adjustStep; + } + } else if (rotationX > targetRotationX) { + if (rotationX - adjustStep < targetRotationX) { + rotationX = targetRotationX; + } else { + rotationX = rotationX - adjustStep; + } + } } -float Unit::getHpRatio() const { - if(type == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } +float Unit::getRotationZ() const { return rotationZ; } - float maxHpAllowed = type->getTotalMaxHp(&totalUpgrade); - if(maxHpAllowed == 0.f) { - return 0.f; - } - return clamp(static_cast(hp) / maxHpAllowed, 0.f, 1.f); +float Unit::getRotationX() const { return rotationX; } + +int Unit::getProductionPercent() const { + if (anyCommand()) { + const ProducibleType *produced = + commands.front()->getCommandType()->getProduced(); + if (produced != NULL) { + if (produced->getProductionTime() == 0) { + return 0; + } + return clamp(progress2 * 100 / produced->getProductionTime(), 0, 100); + } + } + return -1; } -float Unit::getEpRatio() const { - if(type == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - if(type->getTotalMaxHp(&totalUpgrade) == 0) { - return 0.f; - } - else { - float maxEpAllowed = type->getTotalMaxEp(&totalUpgrade); - if(maxEpAllowed == 0.f) { - return 0.f; - } - return clamp(static_cast(ep) / maxEpAllowed, 0.f, 1.f); - } -} - -const Level *Unit::getNextLevel() const{ - if(type == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - if(level == NULL && type->getLevelCount() > 0) { - return type->getLevel(0); - } - else { - for(int i=1; igetLevelCount(); ++i){ - if(type->getLevel(i-1)==level){ - return type->getLevel(i); - } - } - } - return NULL; -} - -string Unit::getFullName(bool translatedValue) const{ - string str=""; - if(level != NULL){ - str += (level->getName(translatedValue) + " "); - } - if(type == NULL) { - throw megaglest_runtime_error("type == NULL in Unit::getFullName()!"); - } - str += type->getName(translatedValue); - return str; -} - -// ====================================== is ====================================== - -bool Unit::isOperative() const{ - return isAlive() && isBuilt(); -} - -bool Unit::isAnimProgressBound() const{ - if(currSkill == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: currSkill == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - bool result = false; - if(currSkill->getClass() == scBeBuilt) { - const BeBuiltSkillType *skill = dynamic_cast(currSkill); - if(skill != NULL) { - result = skill->getAnimProgressBound(); - } - } - else if(currSkill->getClass() == scProduce) { - const ProduceSkillType *skill = dynamic_cast(currSkill); - if(skill != NULL) { - result = skill->getAnimProgressBound(); - } - } - else if(currSkill->getClass() == scUpgrade) { - const UpgradeSkillType *skill = dynamic_cast(currSkill); - if(skill != NULL) { - result = skill->getAnimProgressBound(); - } - } - else if(currSkill->getClass() == scMorph) { - const MorphSkillType *skill = dynamic_cast(currSkill); - if(skill != NULL) { - result = skill->getAnimProgressBound(); - } +float Unit::getProgressRatio() const { + if (anyCommand()) { + const ProducibleType *produced = + commands.front()->getCommandType()->getProduced(); + if (produced != NULL) { + if (produced->getProductionTime() == 0) { + return 0.f; + } + + float help = progress2; + return clamp(help / produced->getProductionTime(), 0.f, 1.f); } - return result; + } + return -1; } -bool Unit::isBeingBuilt() const{ - if(currSkill == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: currSkill == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } +float Unit::getHpRatio() const { + if (type == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + float maxHpAllowed = type->getTotalMaxHp(&totalUpgrade); + if (maxHpAllowed == 0.f) { + return 0.f; + } + return clamp(static_cast(hp) / maxHpAllowed, 0.f, 1.f); +} - return (currSkill->getClass() == scBeBuilt); +float Unit::getEpRatio() const { + if (type == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + if (type->getTotalMaxHp(&totalUpgrade) == 0) { + return 0.f; + } else { + float maxEpAllowed = type->getTotalMaxEp(&totalUpgrade); + if (maxEpAllowed == 0.f) { + return 0.f; + } + return clamp(static_cast(ep) / maxEpAllowed, 0.f, 1.f); + } +} + +const Level *Unit::getNextLevel() const { + if (type == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + if (level == NULL && type->getLevelCount() > 0) { + return type->getLevel(0); + } else { + for (int i = 1; i < type->getLevelCount(); ++i) { + if (type->getLevel(i - 1) == level) { + return type->getLevel(i); + } + } + } + return NULL; +} + +string Unit::getFullName(bool translatedValue) const { + string str = ""; + if (level != NULL) { + str += (level->getName(translatedValue) + " "); + } + if (type == NULL) { + throw megaglest_runtime_error("type == NULL in Unit::getFullName()!"); + } + str += type->getName(translatedValue); + return str; +} + +// ====================================== is +// ====================================== + +bool Unit::isOperative() const { return isAlive() && isBuilt(); } + +bool Unit::isAnimProgressBound() const { + if (currSkill == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: currSkill == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + bool result = false; + if (currSkill->getClass() == scBeBuilt) { + const BeBuiltSkillType *skill = + dynamic_cast(currSkill); + if (skill != NULL) { + result = skill->getAnimProgressBound(); + } + } else if (currSkill->getClass() == scProduce) { + const ProduceSkillType *skill = + dynamic_cast(currSkill); + if (skill != NULL) { + result = skill->getAnimProgressBound(); + } + } else if (currSkill->getClass() == scUpgrade) { + const UpgradeSkillType *skill = + dynamic_cast(currSkill); + if (skill != NULL) { + result = skill->getAnimProgressBound(); + } + } else if (currSkill->getClass() == scMorph) { + const MorphSkillType *skill = + dynamic_cast(currSkill); + if (skill != NULL) { + result = skill->getAnimProgressBound(); + } + } + return result; } -bool Unit::isBuilt() const{ - return (isBeingBuilt() == false); +bool Unit::isBeingBuilt() const { + if (currSkill == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: currSkill == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + return (currSkill->getClass() == scBeBuilt); } -bool Unit::isBuildCommandPending() const { - bool result = false; +bool Unit::isBuilt() const { return (isBeingBuilt() == false); } - Command *command= this->getCurrCommand(); - if(command != NULL) { - const BuildCommandType *bct= dynamic_cast(command->getCommandType()); - if(bct != NULL) { - if(this->getCurrSkill()->getClass() != scBuild) { - result = true; - } - } - } +bool Unit::isBuildCommandPending() const { + bool result = false; + + Command *command = this->getCurrCommand(); + if (command != NULL) { + const BuildCommandType *bct = + dynamic_cast(command->getCommandType()); + if (bct != NULL) { + if (this->getCurrSkill()->getClass() != scBuild) { + result = true; + } + } + } - return result; + return result; } UnitBuildInfo Unit::getBuildCommandPendingInfo() const { - UnitBuildInfo result; - - Command *command= this->getCurrCommand(); - if(command != NULL) { - const BuildCommandType *bct= dynamic_cast(command->getCommandType()); - if(bct != NULL) { - result.pos = command->getOriginalPos(); - result.facing = command->getFacing(); - result.buildUnit = command->getUnitType(); - result.unit = this; - } - } + UnitBuildInfo result; + + Command *command = this->getCurrCommand(); + if (command != NULL) { + const BuildCommandType *bct = + dynamic_cast(command->getCommandType()); + if (bct != NULL) { + result.pos = command->getOriginalPos(); + result.facing = command->getFacing(); + result.buildUnit = command->getUnitType(); + result.unit = this; + } + } - return result; + return result; } bool Unit::isAlly(const Unit *unit) const { - if(unit == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: unit == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } + if (unit == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: unit == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } - return faction->isAlly(unit->getFaction()); + return faction->isAlly(unit->getFaction()); } bool Unit::isDamaged() const { - if(type == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } + if (type == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } - return hp < type->getTotalMaxHp(&totalUpgrade); + return hp < type->getTotalMaxHp(&totalUpgrade); } bool Unit::isInteresting(InterestingUnitType iut) const { - if(type == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - switch(iut) { - case iutIdleHarvester: - if(type->hasCommandClass(ccHarvest)) { - if(commands.empty() == false) { - const CommandType *ct= commands.front()->getCommandType(); - if(ct != NULL){ - return ct->getClass() == ccStop; - } - } - } - return false; - - case iutBuiltBuilding: - return type->hasSkillClass(scBeBuilt) && isBuilt(); - case iutProducer: - return type->hasSkillClass(scProduce); - case iutDamaged: - return isDamaged(); - case iutStore: - return type->getStoredResourceCount()>0; - default: - return false; - } -} - -// ====================================== set ====================================== + if (type == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + switch (iut) { + case iutIdleHarvester: + if (type->hasCommandClass(ccHarvest)) { + if (commands.empty() == false) { + const CommandType *ct = commands.front()->getCommandType(); + if (ct != NULL) { + return ct->getClass() == ccStop; + } + } + } + return false; -void Unit::setCurrSkill(const SkillType *currSkill) { - if(currSkill == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: currSkill == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - if(this->currSkill == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: this->currSkill == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - if(this->currSkill->getClass() == scMove && - currSkill->getClass() != scMove) { - faction->removeUnitFromMovingList(this->getId()); - } - else if(this->currSkill->getClass() != scMove && - currSkill->getClass() == scMove) { - faction->addUnitToMovingList(this->getId()); - } - - changedActiveCommand = false; - if( currSkill->getClass() != this->currSkill->getClass() || - currSkill->getName() != this->currSkill->getName()) { - this->animProgress= 0; - this->lastAnimProgress= 0; - - queuedUnitParticleSystemTypes.clear(); - while(unitParticleSystems.empty() == false) { - if(Renderer::getInstance().validateParticleSystemStillExists(unitParticleSystems.back(),rsGame) == true) { - unitParticleSystems.back()->fade(); - } - unitParticleSystems.pop_back(); - } - - Command *cmd = getCurrrentCommandThreadSafe(); - - // Set mew fog of war skill type if need be - if(cmd != NULL && cmd->getCommandType() != NULL && - cmd->getCommandType()->hasFogOfWarSkillType(currSkill->getName())) { - const FogOfWarSkillType *fowst = cmd->getCommandType()->getFogOfWarSkillType(); - - // Remove old fog of war skill type if need be - game->getWorld()->removeFogOfWarSkillTypeFromList(this); - - game->getWorld()->addFogOfWarSkillType(this,fowst); - } - else { - // Remove old fog of war skill type if need be - game->getWorld()->removeFogOfWarSkillType(this); - } - } - if(showUnitParticles == true && - currSkill->unitParticleSystemTypes.empty() == false && - unitParticleSystems.empty() == true) { - //printf("START - particle system type\n"); - - /* - for(UnitParticleSystemTypes::const_iterator it= currSkill->unitParticleSystemTypes.begin(); - it != currSkill->unitParticleSystemTypes.end(); ++it) { - if((*it)->getStartTime() == 0.0) { - //printf("Adding NON-queued particle system type [%s] [%f] [%f]\n",(*it)->getType().c_str(),(*it)->getStartTime(),(*it)->getEndTime()); - - UnitParticleSystem *ups = new UnitParticleSystem(200); - ups->setParticleOwner(this); - ups->setParticleType((*it)); - - (*it)->setValues(ups); - ups->setPos(getCurrVector()); - ups->setRotation(getRotation()); - ups->setUnitModel(getCurrentModelPtr()); - if(getFaction()->getTexture()) { - ups->setFactionColor(getFaction()->getTexture()->getPixmapConst()->getPixel3f(0,0)); - } - unitParticleSystems.push_back(ups); - Renderer::getInstance().manageParticleSystem(ups, rsGame); - } - else { - //printf("Adding queued particle system type [%s] [%f] [%f]\n",(*it)->getType().c_str(),(*it)->getStartTime(),(*it)->getEndTime()); - - queuedUnitParticleSystemTypes.push_back(*it); - } - } - */ - checkCustomizedUnitParticleListTriggers(currSkill->unitParticleSystemTypes,true); - } - progress2= 0; - if(this->currSkill != currSkill) { - this->lastModelIndexForCurrSkillType = -1; - this->animationRandomCycleCount = 0; - } - - if(faction != NULL) faction->notifyUnitSkillTypeChange(this, currSkill); - const SkillType *original_skill = this->currSkill; - this->currSkill= currSkill; - - if(original_skill != this->currSkill) { - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - game->getScriptManager()->onUnitTriggerEvent(this,utet_SkillChanged); - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } + case iutBuiltBuilding: + return type->hasSkillClass(scBeBuilt) && isBuilt(); + case iutProducer: + return type->hasSkillClass(scProduce); + case iutDamaged: + return isDamaged(); + case iutStore: + return type->getStoredResourceCount() > 0; + default: + return false; + } } -void Unit::setCurrSkill(SkillClass sc) { - if(getType() == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: getType() == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } +// ====================================== set +// ====================================== - setCurrSkill(getType()->getFirstStOfClass(sc)); -} +void Unit::setCurrSkill(const SkillType *currSkill) { + if (currSkill == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: currSkill == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + if (this->currSkill == NULL) { + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "In [%s::%s Line: %d] ERROR: this->currSkill == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + if (this->currSkill->getClass() == scMove && + currSkill->getClass() != scMove) { + faction->removeUnitFromMovingList(this->getId()); + } else if (this->currSkill->getClass() != scMove && + currSkill->getClass() == scMove) { + faction->addUnitToMovingList(this->getId()); + } + + changedActiveCommand = false; + if (currSkill->getClass() != this->currSkill->getClass() || + currSkill->getName() != this->currSkill->getName()) { + this->animProgress = 0; + this->lastAnimProgress = 0; + + queuedUnitParticleSystemTypes.clear(); + while (unitParticleSystems.empty() == false) { + if (Renderer::getInstance().validateParticleSystemStillExists( + unitParticleSystems.back(), rsGame) == true) { + unitParticleSystems.back()->fade(); + } + unitParticleSystems.pop_back(); + } -void Unit::setTarget(const Unit *unit){ + Command *cmd = getCurrrentCommandThreadSafe(); - if(unit == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: unit == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } + // Set mew fog of war skill type if need be + if (cmd != NULL && cmd->getCommandType() != NULL && + cmd->getCommandType()->hasFogOfWarSkillType(currSkill->getName())) { + const FogOfWarSkillType *fowst = + cmd->getCommandType()->getFogOfWarSkillType(); - //find a free pos in cellmap - setTargetPos(unit->getCellPos()); + // Remove old fog of war skill type if need be + game->getWorld()->removeFogOfWarSkillTypeFromList(this); - //ser field and vector - targetField= unit->getCurrField(); - targetVec= unit->getCurrVectorAsTarget(); - targetRef= unit; -} - -RandomGen* Unit::getRandom(bool threadAccessAllowed) { - if(threadAccessAllowed == false && Thread::isCurrentThreadMainThread() == false) { - throw megaglest_runtime_error("Invalid access to unit random from outside main thread current id = " + - intToStr(Thread::getCurrentThreadId()) + " main = " + intToStr(Thread::getMainThreadId())); - } - return &random; + game->getWorld()->addFogOfWarSkillType(this, fowst); + } else { + // Remove old fog of war skill type if need be + game->getWorld()->removeFogOfWarSkillType(this); + } + } + if (showUnitParticles == true && + currSkill->unitParticleSystemTypes.empty() == false && + unitParticleSystems.empty() == true) { + // printf("START - particle system type\n"); + + /* + for(UnitParticleSystemTypes::const_iterator it= + currSkill->unitParticleSystemTypes.begin(); it != + currSkill->unitParticleSystemTypes.end(); ++it) { if((*it)->getStartTime() + == 0.0) { + //printf("Adding NON-queued particle system type [%s] [%f] + [%f]\n",(*it)->getType().c_str(),(*it)->getStartTime(),(*it)->getEndTime()); + + UnitParticleSystem *ups = new UnitParticleSystem(200); + ups->setParticleOwner(this); + ups->setParticleType((*it)); + + (*it)->setValues(ups); + ups->setPos(getCurrVector()); + ups->setRotation(getRotation()); + ups->setUnitModel(getCurrentModelPtr()); + if(getFaction()->getTexture()) { + ups->setFactionColor(getFaction()->getTexture()->getPixmapConst()->getPixel3f(0,0)); + } + unitParticleSystems.push_back(ups); + Renderer::getInstance().manageParticleSystem(ups, rsGame); + } + else { + //printf("Adding queued particle system type [%s] [%f] + [%f]\n",(*it)->getType().c_str(),(*it)->getStartTime(),(*it)->getEndTime()); + + queuedUnitParticleSystemTypes.push_back(*it); + } + } + */ + checkCustomizedUnitParticleListTriggers(currSkill->unitParticleSystemTypes, + true); + } + progress2 = 0; + if (this->currSkill != currSkill) { + this->lastModelIndexForCurrSkillType = -1; + this->animationRandomCycleCount = 0; + } + + if (faction != NULL) + faction->notifyUnitSkillTypeChange(this, currSkill); + const SkillType *original_skill = this->currSkill; + this->currSkill = currSkill; + + if (original_skill != this->currSkill) { + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + game->getScriptManager()->onUnitTriggerEvent(this, utet_SkillChanged); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + } } -void Unit::setPos(const Vec2i &pos, bool clearPathFinder, bool threaded) { - if(map->isInside(pos) == false || map->isInsideSurface(map->toSurfCoords(pos)) == false) { - throw megaglest_runtime_error("#3 Invalid path position = " + pos.getString()); - } +void Unit::setCurrSkill(SkillClass sc) { + if (getType() == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: getType() == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(mutexCommands,mutexOwnerId); + setCurrSkill(getType()->getFirstStOfClass(sc)); +} - if(threaded) { - logSynchDataThreaded(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } - else { - logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } +void Unit::setTarget(const Unit *unit) { - if(clearPathFinder == true && this->unitPath != NULL) { - this->unitPath->clear(); - } - //Vec2i oldLastPos = this->lastPos; - this->lastPos= this->pos; - this->pos= pos; + if (unit == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: unit == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } - map->clampPos(this->pos); - this->meetingPos= pos - Vec2i(1); - map->clampPos(this->meetingPos); + // find a free pos in cellmap + setTargetPos(unit->getCellPos()); - safeMutex.ReleaseLock(); + // ser field and vector + targetField = unit->getCurrField(); + targetVec = unit->getCurrVectorAsTarget(); + targetRef = unit; +} - refreshPos(); +RandomGen *Unit::getRandom(bool threadAccessAllowed) { + if (threadAccessAllowed == false && + Thread::isCurrentThreadMainThread() == false) { + throw megaglest_runtime_error( + "Invalid access to unit random from outside main thread current id = " + + intToStr(Thread::getCurrentThreadId()) + + " main = " + intToStr(Thread::getMainThreadId())); + } + return &random; +} - if(threaded) { - logSynchDataThreaded(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } - else { - logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } +void Unit::setPos(const Vec2i &pos, bool clearPathFinder, bool threaded) { + if (map->isInside(pos) == false || + map->isInsideSurface(map->toSurfCoords(pos)) == false) { + throw megaglest_runtime_error("#3 Invalid path position = " + + pos.getString()); + } + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(mutexCommands, mutexOwnerId); + + if (threaded) { + logSynchDataThreaded(extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__); + } else { + logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), __LINE__); + } + + if (clearPathFinder == true && this->unitPath != NULL) { + this->unitPath->clear(); + } + // Vec2i oldLastPos = this->lastPos; + this->lastPos = this->pos; + this->pos = pos; + + map->clampPos(this->pos); + this->meetingPos = pos - Vec2i(1); + map->clampPos(this->meetingPos); + + safeMutex.ReleaseLock(); + + refreshPos(); + + if (threaded) { + logSynchDataThreaded(extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__); + } else { + logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), __LINE__); + } } void Unit::refreshPos(bool forceRefresh) { - // Attempt to improve performance - this->exploreCells(forceRefresh); - calculateFogOfWarRadius(forceRefresh); + // Attempt to improve performance + this->exploreCells(forceRefresh); + calculateFogOfWarRadius(forceRefresh); } FowAlphaCellsLookupItem Unit::getFogOfWarRadius(bool useCache) const { - if(useCache == true) { - return cachedFow; - } - - //iterate through all cells - int sightRange= this->getType()->getTotalSight(this->getTotalUpgrade()); - int radius = sightRange + World::indirectSightRange; - PosCircularIterator pci(map, this->getPosNotThreadSafe(), radius); - FowAlphaCellsLookupItem result; - while(pci.next()){ - const Vec2i sightpos= pci.getPos(); - Vec2i surfPos= Map::toSurfCoords(sightpos); - - //compute max alpha - float maxAlpha= 0.0f; - if(surfPos.x > 1 && surfPos.y > 1 && - surfPos.x < map->getSurfaceW() -2 && - surfPos.y < map->getSurfaceH() -2) { - maxAlpha= 1.f; - } - else if(surfPos.x > 0 && surfPos.y > 0 && - surfPos.x < map->getSurfaceW() -1 && - surfPos.y < map->getSurfaceH() -1) { - maxAlpha= 0.3f; - } - - //compute alpha - float alpha = maxAlpha; - float dist = this->getPosNotThreadSafe().dist(sightpos); - if(dist > sightRange) { - alpha= clamp(1.f-(dist - sightRange) / (World::indirectSightRange), 0.f, maxAlpha); - } - result.surfPosAlphaList[surfPos] = alpha; - } - return result; + if (useCache == true) { + return cachedFow; + } + + // iterate through all cells + int sightRange = this->getType()->getTotalSight(this->getTotalUpgrade()); + int radius = sightRange + World::indirectSightRange; + PosCircularIterator pci(map, this->getPosNotThreadSafe(), radius); + FowAlphaCellsLookupItem result; + while (pci.next()) { + const Vec2i sightpos = pci.getPos(); + Vec2i surfPos = Map::toSurfCoords(sightpos); + + // compute max alpha + float maxAlpha = 0.0f; + if (surfPos.x > 1 && surfPos.y > 1 && surfPos.x < map->getSurfaceW() - 2 && + surfPos.y < map->getSurfaceH() - 2) { + maxAlpha = 1.f; + } else if (surfPos.x > 0 && surfPos.y > 0 && + surfPos.x < map->getSurfaceW() - 1 && + surfPos.y < map->getSurfaceH() - 1) { + maxAlpha = 0.3f; + } + + // compute alpha + float alpha = maxAlpha; + float dist = this->getPosNotThreadSafe().dist(sightpos); + if (dist > sightRange) { + alpha = clamp(1.f - (dist - sightRange) / (World::indirectSightRange), + 0.f, maxAlpha); + } + result.surfPosAlphaList[surfPos] = alpha; + } + return result; } void Unit::calculateFogOfWarRadius(bool forceRefresh) { - if(game->getWorld()->getFogOfWar() == true) { - if(forceRefresh || this->pos != this->cachedFowPos) { - cachedFow = getFogOfWarRadius(false); - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(mutexCommands,mutexOwnerId); - this->cachedFowPos = this->pos; - } - } + if (game->getWorld()->getFogOfWar() == true) { + if (forceRefresh || this->pos != this->cachedFowPos) { + cachedFow = getFogOfWarRadius(false); + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(mutexCommands, mutexOwnerId); + this->cachedFowPos = this->pos; + } + } } void Unit::setTargetPos(const Vec2i &targetPos, bool threaded) { - if(map->isInside(targetPos) == false || map->isInsideSurface(map->toSurfCoords(targetPos)) == false) { - throw megaglest_runtime_error("#4 Invalid path position = " + targetPos.getString()); - } + if (map->isInside(targetPos) == false || + map->isInsideSurface(map->toSurfCoords(targetPos)) == false) { + throw megaglest_runtime_error("#4 Invalid path position = " + + targetPos.getString()); + } - Vec2i relPos= targetPos - pos; - //map->clampPos(relPos); + Vec2i relPos = targetPos - pos; + // map->clampPos(relPos); - Vec2f relPosf= Vec2f((float)relPos.x, (float)relPos.y); + Vec2f relPosf = Vec2f((float)relPos.x, (float)relPos.y); #ifdef USE_STREFLOP - targetRotation= radToDeg(streflop::atan2(static_cast(relPosf.x), static_cast(relPosf.y))); + targetRotation = + radToDeg(streflop::atan2(static_cast(relPosf.x), + static_cast(relPosf.y))); #else - targetRotation= radToDeg(atan2(relPosf.x, relPosf.y)); + targetRotation = radToDeg(atan2(relPosf.x, relPosf.y)); #endif - targetRotation = truncateDecimal(targetRotation,6); + targetRotation = truncateDecimal(targetRotation, 6); - targetRef= NULL; + targetRef = NULL; - this->targetPos= targetPos; - map->clampPos(this->targetPos); + this->targetPos = targetPos; + map->clampPos(this->targetPos); - if(threaded) { - logSynchDataThreaded(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } - else { - logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } + if (threaded) { + logSynchDataThreaded(extractFileFromDirectoryPath(__FILE__).c_str(), + __LINE__); + } else { + logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), __LINE__); + } } void Unit::addAttackParticleSystem(ParticleSystem *ps) { - attackParticleSystems.push_back(ps); + attackParticleSystems.push_back(ps); } void Unit::setVisible(const bool visible) { - this->visible = visible; - - if(unitParticleSystems.empty() == false) { - for(UnitParticleSystems::iterator it= unitParticleSystems.begin(); it != unitParticleSystems.end(); ++it) { - if(Renderer::getInstance().validateParticleSystemStillExists((*it),rsGame) == true) { - (*it)->setVisible(visible); - } - } - } - if(damageParticleSystems.empty() == false) { - for(UnitParticleSystems::iterator it= damageParticleSystems.begin(); it != damageParticleSystems.end(); ++it) { - if(Renderer::getInstance().validateParticleSystemStillExists((*it),rsGame) == true) { - (*it)->setVisible(visible); - } - } - } - if(smokeParticleSystems.empty() == false) { - for(UnitParticleSystems::iterator it= smokeParticleSystems.begin(); it != smokeParticleSystems.end(); ++it) { - if(Renderer::getInstance().validateParticleSystemStillExists((*it),rsGame) == true) { - if((*it)->getVisible() != visible) { - //printf("Changing visibility for smoke particle system to: %d\n",visible); - (*it)->setVisible(visible); - } - } - } - } - - //if(attackParticleSystems.empty() == false) { - // for(vector::iterator it= attackParticleSystems.begin(); it != attackParticleSystems.end(); ++it) { - // if(Renderer::getInstance().validateParticleSystemStillExists((*it),rsGame) == true) { - // Not sure this is a good idea since the unit be not be visible but the attack particle might be. - // This means you won't see the attacking projectile until the unit moves into view. - //(*it)->setVisible(visible); - // } - // } - //} - - if(currentAttackBoostEffects.empty() == false) { - for(unsigned int i = 0; i < currentAttackBoostEffects.size(); ++i) { - UnitAttackBoostEffect *effect = currentAttackBoostEffects[i]; - if(effect != NULL && effect->ups != NULL) { - bool particleValid = Renderer::getInstance().validateParticleSystemStillExists(effect->ups,rsGame); - if(particleValid == true) { - effect->ups->setVisible(visible); - } - } - } - } - if(currentAttackBoostOriginatorEffect.currentAppliedEffect != NULL) { - if(currentAttackBoostOriginatorEffect.currentAppliedEffect->ups != NULL) { - bool particleValid = Renderer::getInstance().validateParticleSystemStillExists(currentAttackBoostOriginatorEffect.currentAppliedEffect->ups,rsGame); - if(particleValid == true) { - currentAttackBoostOriginatorEffect.currentAppliedEffect->ups->setVisible(visible); - } - } - } -} - -// =============================== Render related ================================== + this->visible = visible; + + if (unitParticleSystems.empty() == false) { + for (UnitParticleSystems::iterator it = unitParticleSystems.begin(); + it != unitParticleSystems.end(); ++it) { + if (Renderer::getInstance().validateParticleSystemStillExists( + (*it), rsGame) == true) { + (*it)->setVisible(visible); + } + } + } + if (damageParticleSystems.empty() == false) { + for (UnitParticleSystems::iterator it = damageParticleSystems.begin(); + it != damageParticleSystems.end(); ++it) { + if (Renderer::getInstance().validateParticleSystemStillExists( + (*it), rsGame) == true) { + (*it)->setVisible(visible); + } + } + } + if (smokeParticleSystems.empty() == false) { + for (UnitParticleSystems::iterator it = smokeParticleSystems.begin(); + it != smokeParticleSystems.end(); ++it) { + if (Renderer::getInstance().validateParticleSystemStillExists( + (*it), rsGame) == true) { + if ((*it)->getVisible() != visible) { + // printf("Changing visibility for smoke particle system to: + // %d\n",visible); + (*it)->setVisible(visible); + } + } + } + } + + // if(attackParticleSystems.empty() == false) { + // for(vector::iterator it= attackParticleSystems.begin(); + // it != attackParticleSystems.end(); ++it) { + // if(Renderer::getInstance().validateParticleSystemStillExists((*it),rsGame) + //== true) { + // Not sure this is a good idea since the unit be not be visible but the + // attack particle might be. This means you won't see the attacking + // projectile until the unit moves into view. + //(*it)->setVisible(visible); + // } + // } + //} + + if (currentAttackBoostEffects.empty() == false) { + for (unsigned int i = 0; i < currentAttackBoostEffects.size(); ++i) { + UnitAttackBoostEffect *effect = currentAttackBoostEffects[i]; + if (effect != NULL && effect->ups != NULL) { + bool particleValid = + Renderer::getInstance().validateParticleSystemStillExists( + effect->ups, rsGame); + if (particleValid == true) { + effect->ups->setVisible(visible); + } + } + } + } + if (currentAttackBoostOriginatorEffect.currentAppliedEffect != NULL) { + if (currentAttackBoostOriginatorEffect.currentAppliedEffect->ups != NULL) { + bool particleValid = + Renderer::getInstance().validateParticleSystemStillExists( + currentAttackBoostOriginatorEffect.currentAppliedEffect->ups, + rsGame); + if (particleValid == true) { + currentAttackBoostOriginatorEffect.currentAppliedEffect->ups + ->setVisible(visible); + } + } + } +} + +// =============================== Render related +// ================================== Model *Unit::getCurrentModelPtr() { - if(currSkill == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: currSkill == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - int currentModelIndexForCurrSkillType = lastModelIndexForCurrSkillType; - Model *result = currSkill->getAnimation(getAnimProgressAsFloat(),this,&lastModelIndexForCurrSkillType, &animationRandomCycleCount); - if(currentModelIndexForCurrSkillType != lastModelIndexForCurrSkillType) { - animationRandomCycleCount++; - if(currSkill != NULL && animationRandomCycleCount >= currSkill->getAnimationCount()) { - animationRandomCycleCount = 0; - } - } - return result; -} - -//const Model *Unit::getCurrentModel() { + if (currSkill == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: currSkill == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + int currentModelIndexForCurrSkillType = lastModelIndexForCurrSkillType; + Model *result = currSkill->getAnimation(getAnimProgressAsFloat(), this, + &lastModelIndexForCurrSkillType, + &animationRandomCycleCount); + if (currentModelIndexForCurrSkillType != lastModelIndexForCurrSkillType) { + animationRandomCycleCount++; + if (currSkill != NULL && + animationRandomCycleCount >= currSkill->getAnimationCount()) { + animationRandomCycleCount = 0; + } + } + return result; +} + +// const Model *Unit::getCurrentModel() { // if(currSkill == NULL) { // char szBuf[8096]=""; -// snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: currSkill == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); +// snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: currSkill == +// NULL, Unit = +//[%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); // throw megaglest_runtime_error(szBuf); // } // // int currentModelIndexForCurrSkillType = lastModelIndexForCurrSkillType; -// const Model *result = currSkill->getAnimation(getAnimProgressAsFloat(),this,&lastModelIndexForCurrSkillType, &animationRandomCycleCount); -// if(currentModelIndexForCurrSkillType != lastModelIndexForCurrSkillType) { -// animationRandomCycleCount++; -// if(currSkill != NULL && animationRandomCycleCount >= currSkill->getAnimationCount()) { -// animationRandomCycleCount = 0; +// const Model *result = +// currSkill->getAnimation(getAnimProgressAsFloat(),this,&lastModelIndexForCurrSkillType, +//&animationRandomCycleCount); if(currentModelIndexForCurrSkillType != +// lastModelIndexForCurrSkillType) { animationRandomCycleCount++; +// if(currSkill != NULL && animationRandomCycleCount >= +// currSkill->getAnimationCount()) { animationRandomCycleCount = 0; // } // } // return result; -//} +// } bool Unit::checkModelStateInfoForNewHpValue() { - bool result = false; - if(currSkill != NULL && currSkill->getAnimationCount() > 1) { - if(lastModelIndexForCurrSkillType >= 0) { - const AnimationAttributes attributes = currSkill->getAnimationAttribute(lastModelIndexForCurrSkillType); - if(attributes.fromHp != 0 || attributes.toHp != 0) { - //printf("Check for RESET model state for [%d - %s] HP = %d [%d to %d]\n",this->id,this->getType()->getName().c_str(),this->getHp(),attributes.fromHp,attributes.toHp); - //if(this->getHp() >= attributes.fromHp && this->getHp() <= attributes.toHp) { - if(this->getHp() < attributes.fromHp || this->getHp() > attributes.toHp) { - //printf("RESET model state for [%d - %s] HP = %d [%d to %d]\n",this->id,this->getType()->getName().c_str(),this->getHp(),attributes.fromHp,attributes.toHp); - - lastModelIndexForCurrSkillType = -1; - animationRandomCycleCount = 0; - result = true; - } - } - else { - //printf("Check for RESET #2 model state for [%d - %s] HP = %d [%d to %d] for skill [%s]\n",this->id,this->getType()->getName().c_str(),this->getHp(),attributes.fromHp,attributes.toHp,currSkill->getName().c_str()); - } - } - } + bool result = false; + if (currSkill != NULL && currSkill->getAnimationCount() > 1) { + if (lastModelIndexForCurrSkillType >= 0) { + const AnimationAttributes attributes = + currSkill->getAnimationAttribute(lastModelIndexForCurrSkillType); + if (attributes.fromHp != 0 || attributes.toHp != 0) { + // printf("Check for RESET model state for [%d - %s] HP = %d [%d to + // %d]\n",this->id,this->getType()->getName().c_str(),this->getHp(),attributes.fromHp,attributes.toHp); + // if(this->getHp() >= attributes.fromHp && this->getHp() <= + // attributes.toHp) { + if (this->getHp() < attributes.fromHp || + this->getHp() > attributes.toHp) { + // printf("RESET model state for [%d - %s] HP = %d [%d to + // %d]\n",this->id,this->getType()->getName().c_str(),this->getHp(),attributes.fromHp,attributes.toHp); + + lastModelIndexForCurrSkillType = -1; + animationRandomCycleCount = 0; + result = true; + } + } else { + // printf("Check for RESET #2 model state for [%d - %s] HP = %d [%d to + // %d] for skill + // [%s]\n",this->id,this->getType()->getName().c_str(),this->getHp(),attributes.fromHp,attributes.toHp,currSkill->getName().c_str()); + } + } + } - return result; + return result; } -Vec3f Unit::getCurrVectorForParticlesystems() const{ - if(getFaction()->getType()->isFlatParticlePositions()){ - return getCurrVectorFlat(); - } - else { - return getCurrMidHeightVector(); - } +Vec3f Unit::getCurrVectorForParticlesystems() const { + if (getFaction()->getType()->isFlatParticlePositions()) { + return getCurrVectorFlat(); + } else { + return getCurrMidHeightVector(); + } } -Vec3f Unit::getCurrMidHeightVector() const{ - if(type == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } +Vec3f Unit::getCurrMidHeightVector() const { + if (type == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } - Vec3f result = getCurrVectorFlat() + Vec3f(0.f, type->getHeight() / 2.f, 0.f); - result.x = truncateDecimal(result.x,6); - result.y = truncateDecimal(result.y,6); - result.z = truncateDecimal(result.z,6); + Vec3f result = getCurrVectorFlat() + Vec3f(0.f, type->getHeight() / 2.f, 0.f); + result.x = truncateDecimal(result.x, 6); + result.y = truncateDecimal(result.y, 6); + result.z = truncateDecimal(result.z, 6); - return result; + return result; } -Vec3f Unit::getCurrVectorAsTarget() const{ - if(type == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } +Vec3f Unit::getCurrVectorAsTarget() const { + if (type == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } - Vec3f result = getCurrVectorFlat() + Vec3f(0.f, type->getTargetHeight() / 2.f, 0.f); - result.x = truncateDecimal(result.x,6); - result.y = truncateDecimal(result.y,6); - result.z = truncateDecimal(result.z,6); + Vec3f result = + getCurrVectorFlat() + Vec3f(0.f, type->getTargetHeight() / 2.f, 0.f); + result.x = truncateDecimal(result.x, 6); + result.y = truncateDecimal(result.y, 6); + result.z = truncateDecimal(result.z, 6); - return result; + return result; } -Vec3f Unit::getCurrBurnVector() const{ - if(type == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } +Vec3f Unit::getCurrBurnVector() const { + if (type == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } - Vec3f result = getCurrVectorFlat() + Vec3f(0.f, type->getBurnHeight() / 2.f, 0.f); - result.x = truncateDecimal(result.x,6); - result.y = truncateDecimal(result.y,6); - result.z = truncateDecimal(result.z,6); + Vec3f result = + getCurrVectorFlat() + Vec3f(0.f, type->getBurnHeight() / 2.f, 0.f); + result.x = truncateDecimal(result.x, 6); + result.y = truncateDecimal(result.y, 6); + result.z = truncateDecimal(result.z, 6); - return result; + return result; } -Vec3f Unit::getCurrVectorFlat() const{ - return getVectorFlat(lastPos, pos); -} +Vec3f Unit::getCurrVectorFlat() const { return getVectorFlat(lastPos, pos); } float Unit::getProgressAsFloat() const { - float result = (static_cast(progress) / static_cast(PROGRESS_SPEED_MULTIPLIER)); - result = truncateDecimal(result,6); - return result; + float result = (static_cast(progress) / + static_cast(PROGRESS_SPEED_MULTIPLIER)); + result = truncateDecimal(result, 6); + return result; } -Vec3f Unit::getVectorFlat(const Vec2i &lastPosValue, const Vec2i &curPosValue) const { - Vec3f v; +Vec3f Unit::getVectorFlat(const Vec2i &lastPosValue, + const Vec2i &curPosValue) const { + Vec3f v; - float y1= computeHeight(lastPosValue); - float y2= computeHeight(curPosValue); + float y1 = computeHeight(lastPosValue); + float y2 = computeHeight(curPosValue); - if(currSkill->getClass() == scMove) { - float progressAsFloat = getProgressAsFloat(); + if (currSkill->getClass() == scMove) { + float progressAsFloat = getProgressAsFloat(); - v.x = lastPosValue.x + progressAsFloat * (curPosValue.x - lastPosValue.x); - v.z = lastPosValue.y + progressAsFloat * (curPosValue.y - lastPosValue.y); - v.y = y1 + progressAsFloat * (y2-y1); + v.x = lastPosValue.x + progressAsFloat * (curPosValue.x - lastPosValue.x); + v.z = lastPosValue.y + progressAsFloat * (curPosValue.y - lastPosValue.y); + v.y = y1 + progressAsFloat * (y2 - y1); - v.x = truncateDecimal(v.x,6); - v.y = truncateDecimal(v.y,6); - v.z = truncateDecimal(v.z,6); - } - else { - v.x = static_cast(curPosValue.x); - v.z = static_cast(curPosValue.y); - v.y = y2; + v.x = truncateDecimal(v.x, 6); + v.y = truncateDecimal(v.y, 6); + v.z = truncateDecimal(v.z, 6); + } else { + v.x = static_cast(curPosValue.x); + v.z = static_cast(curPosValue.y); + v.y = y2; - v.x = truncateDecimal(v.x,6); - v.y = truncateDecimal(v.y,6); - v.z = truncateDecimal(v.z,6); - } - v.x += type->getSize() / 2.f - 0.5f; - v.z += type->getSize() / 2.f - 0.5f; + v.x = truncateDecimal(v.x, 6); + v.y = truncateDecimal(v.y, 6); + v.z = truncateDecimal(v.z, 6); + } + v.x += type->getSize() / 2.f - 0.5f; + v.z += type->getSize() / 2.f - 0.5f; - v.x = truncateDecimal(v.x,6); - v.z = truncateDecimal(v.z,6); + v.x = truncateDecimal(v.x, 6); + v.z = truncateDecimal(v.z, 6); - return v; + return v; } // =================== Command list related =================== -//any command +// any command bool Unit::anyCommand(bool validateCommandtype) const { - bool result = false; - if(validateCommandtype == false) { - result = (commands.empty() == false); - } - else { - for(Commands::const_iterator it= commands.begin(); it != commands.end(); ++it) { - const CommandType *ct = (*it)->getCommandType(); - if(ct != NULL && ct->getClass() != ccStop) { - result = true; - break; - } - } - } - - return result; -} - -//return current command, assert that there is always one command + bool result = false; + if (validateCommandtype == false) { + result = (commands.empty() == false); + } else { + for (Commands::const_iterator it = commands.begin(); it != commands.end(); + ++it) { + const CommandType *ct = (*it)->getCommandType(); + if (ct != NULL && ct->getClass() != ccStop) { + result = true; + break; + } + } + } + + return result; +} + +// return current command, assert that there is always one command Command *Unit::getCurrrentCommandThreadSafe() { - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(mutexCommands,mutexOwnerId); + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(mutexCommands, mutexOwnerId); - if(commands.empty() == false) { - return commands.front(); - } + if (commands.empty() == false) { + return commands.front(); + } - return NULL; + return NULL; } void Unit::replaceCurrCommand(Command *cmd) { - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(mutexCommands,mutexOwnerId); + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(mutexCommands, mutexOwnerId); - assert(commands.empty() == false); - commands.front() = cmd; - this->setCurrentUnitTitle(""); + assert(commands.empty() == false); + commands.front() = cmd; + this->setCurrentUnitTitle(""); } -//returns the size of the commands +// returns the size of the commands unsigned int Unit::getCommandSize() const { - return (unsigned int)commands.size(); + return (unsigned int)commands.size(); } /* * (this is meant for MaxUnitCount) */ -int Unit::getCountOfProducedUnitsPreExistence(const UnitType *ut) const{ - int count=0; - for(Commands::const_iterator it= commands.begin(); it!=commands.end(); ++it){ - const CommandType* ct=(*it)->getCommandType(); - if(ct->getClass()==ccProduce || ct->getClass()==ccMorph ){ - const UnitType *producedUnitType= static_cast(ct->getProduced()); - if(producedUnitType==ut) - { - count++; - } - } - if(ct->getClass()==ccBuild){ - const UnitType *builtUnitType= (*it)->getUnitType(); - // we dont count builded units if they are already exist. So we just count the units that will be build. - // otherwise we will get double counts of alive units and units beeing build. - if(builtUnitType==ut && (*it)->getUnit()==NULL) - { - count++; - } - } - } - return count; -} - -//give one command (clear, and push back) -std::pair Unit::giveCommand(Command *command, bool tryQueue) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugUnitCommands).enabled) SystemFlags::OutputDebug(SystemFlags::debugUnitCommands,"\n======================\nUnit Command tryQueue = %d\nUnit Info:\n%s\nCommand Info:\n%s\n",tryQueue,this->toString().c_str(),command->toString(false).c_str()); - - std::pair result(crFailUndefined,""); - changedActiveCommand = false; - - Chrono chrono; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); - - if(command == NULL) { - throw megaglest_runtime_error("command == NULL"); - } - if(command->getCommandType() == NULL) { - throw megaglest_runtime_error("command->getCommandType() == NULL"); - } - - const int command_priority = command->getPriority(); - - 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()); - - //printf("In [%s::%s] Line: %d unit [%d - %s] command [%s] tryQueue = %d command->getCommandType()->isQueuable(tryQueue) = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->getId(),this->getType()->getName().c_str(), command->getCommandType()->getName().c_str(), tryQueue,command->getCommandType()->isQueuable(tryQueue)); - - - if(command->getCommandType()->isQueuable(tryQueue)) { - 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()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugUnitCommands).enabled) SystemFlags::OutputDebug(SystemFlags::debugUnitCommands,"In [%s::%s Line: %d] Command is Queable\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - if(command->getCommandType()->isQueuable() == qAlways && tryQueue){ - // Its a produce or upgrade command called without queued key - // in this case we must NOT delete lower priority commands! - // we just queue it! - - } - else { - //Delete all lower-prioirty commands - for(list::iterator i= commands.begin(); i != commands.end();){ - if((*i)->getPriority() < command_priority){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugUnitCommands).enabled) - SystemFlags::OutputDebug(SystemFlags::debugUnitCommands,"In [%s::%s Line: %d] Deleting lower priority command [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,(*i)->toString(false).c_str()); - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(mutexCommands,mutexOwnerId); - - deleteQueuedCommand(*i); - i= commands.erase(i); - - safeMutex.ReleaseLock(); - } - else { - ++i; - } - } - } - 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()); - - //cancel current command if it is not queuable - if(commands.empty() == false && - commands.back()->getCommandType()->isQueueAppendable() == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugUnitCommands).enabled) SystemFlags::OutputDebug(SystemFlags::debugUnitCommands,"In [%s::%s Line: %d] Cancel command because last one is NOT queable [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,commands.back()->toString(false).c_str()); - - cancelCommand(); - } - - 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()); - } - else { - //empty command queue - if(SystemFlags::getSystemSettingType(SystemFlags::debugUnitCommands).enabled) SystemFlags::OutputDebug(SystemFlags::debugUnitCommands,"In [%s::%s Line: %d] Clear commands because current is NOT queable.\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - bool willChangedActiveCommand = (commands.empty() == false); - if(willChangedActiveCommand == true) { - - CommandClass currCommandClass = getCurrCommand()->getCommandType()->getClass(); - CommandClass commandClass = command->getCommandType()->getClass(); - if(currCommandClass == commandClass) { - - willChangedActiveCommand = false; - } - else if(currCommandClass == ccAttack || - currCommandClass == ccAttackStopped || - commandClass == ccAttack || - commandClass == ccAttackStopped) { - - willChangedActiveCommand= true; - } - else { - willChangedActiveCommand= false; - } - } - - if(willChangedActiveCommand == true) { - - lastChangedActiveCommandFrame = changedActiveCommandFrame; - changedActiveCommandFrame = getFrameCount(); - - //printf("Line: %d getCurrCommand() [%s] command [%s]\n",__LINE__,getCurrCommand()->toString(false).c_str(),command->toString(false).c_str()); - } - - clearCommands(); - changedActiveCommand = willChangedActiveCommand; - - //printf("In [%s::%s] Line: %d cleared existing commands\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - 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()); - } - - 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()); - - //check command - result= checkCommand(command); - if(SystemFlags::getSystemSettingType(SystemFlags::debugUnitCommands).enabled) SystemFlags::OutputDebug(SystemFlags::debugUnitCommands,"In [%s::%s Line: %d] checkCommand returned: [%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,result.first); - - //printf("In [%s::%s] Line: %d check command returned %d, commands.size() = %d\n[%s]\n\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,result,commands.size(),command->toString().c_str()); - - 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()); - - if(result.first == crSuccess) { - applyCommand(command); - } +int Unit::getCountOfProducedUnitsPreExistence(const UnitType *ut) const { + int count = 0; + for (Commands::const_iterator it = commands.begin(); it != commands.end(); + ++it) { + const CommandType *ct = (*it)->getCommandType(); + if (ct->getClass() == ccProduce || ct->getClass() == ccMorph) { + const UnitType *producedUnitType = + static_cast(ct->getProduced()); + if (producedUnitType == ut) { + count++; + } + } + if (ct->getClass() == ccBuild) { + const UnitType *builtUnitType = (*it)->getUnitType(); + // we dont count builded units if they are already exist. So we just count + // the units that will be build. otherwise we will get double counts of + // alive units and units beeing build. + if (builtUnitType == ut && (*it)->getUnit() == NULL) { + count++; + } + } + } + return count; +} + +// give one command (clear, and push back) +std::pair Unit::giveCommand(Command *command, + bool tryQueue) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugUnitCommands).enabled) + SystemFlags::OutputDebug(SystemFlags::debugUnitCommands, + "\n======================\nUnit Command tryQueue " + "= %d\nUnit Info:\n%s\nCommand Info:\n%s\n", + tryQueue, this->toString().c_str(), + command->toString(false).c_str()); + + std::pair result(crFailUndefined, ""); + changedActiveCommand = false; + + Chrono chrono; + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) + chrono.start(); + + if (command == NULL) { + throw megaglest_runtime_error("command == NULL"); + } + if (command->getCommandType() == NULL) { + throw megaglest_runtime_error("command->getCommandType() == NULL"); + } + + const int command_priority = command->getPriority(); + + 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()); + + // printf("In [%s::%s] Line: %d unit [%d - %s] command [%s] tryQueue = %d + // command->getCommandType()->isQueuable(tryQueue) = + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->getId(),this->getType()->getName().c_str(), + // command->getCommandType()->getName().c_str(), + // tryQueue,command->getCommandType()->isQueuable(tryQueue)); + + if (command->getCommandType()->isQueuable(tryQueue)) { + 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()); + if (SystemFlags::getSystemSettingType(SystemFlags::debugUnitCommands) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugUnitCommands, + "In [%s::%s Line: %d] Command is Queable\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + if (command->getCommandType()->isQueuable() == qAlways && tryQueue) { + // Its a produce or upgrade command called without queued key + // in this case we must NOT delete lower priority commands! + // we just queue it! + + } else { + // Delete all lower-prioirty commands + for (list::iterator i = commands.begin(); + i != commands.end();) { + if ((*i)->getPriority() < command_priority) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugUnitCommands) + .enabled) + SystemFlags::OutputDebug( + SystemFlags::debugUnitCommands, + "In [%s::%s Line: %d] Deleting lower priority command [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, (*i)->toString(false).c_str()); + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(mutexCommands, mutexOwnerId); + + deleteQueuedCommand(*i); + i = commands.erase(i); + + safeMutex.ReleaseLock(); + } else { + ++i; + } + } + } + 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()); + + // cancel current command if it is not queuable + if (commands.empty() == false && + commands.back()->getCommandType()->isQueueAppendable() == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugUnitCommands) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugUnitCommands, + "In [%s::%s Line: %d] Cancel command because " + "last one is NOT queable [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, + commands.back()->toString(false).c_str()); + + cancelCommand(); + } - 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()); + 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()); + } else { + // empty command queue + if (SystemFlags::getSystemSettingType(SystemFlags::debugUnitCommands) + .enabled) + SystemFlags::OutputDebug(SystemFlags::debugUnitCommands, + "In [%s::%s Line: %d] Clear commands because " + "current is NOT queable.\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + bool willChangedActiveCommand = (commands.empty() == false); + if (willChangedActiveCommand == true) { + + CommandClass currCommandClass = + getCurrCommand()->getCommandType()->getClass(); + CommandClass commandClass = command->getCommandType()->getClass(); + if (currCommandClass == commandClass) { + + willChangedActiveCommand = false; + } else if (currCommandClass == ccAttack || + currCommandClass == ccAttackStopped || + commandClass == ccAttack || commandClass == ccAttackStopped) { + + willChangedActiveCommand = true; + } else { + willChangedActiveCommand = false; + } + } - //push back command - if(result.first == crSuccess) { - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(mutexCommands,mutexOwnerId); + if (willChangedActiveCommand == true) { - commands.push_back(command); + lastChangedActiveCommandFrame = changedActiveCommandFrame; + changedActiveCommandFrame = getFrameCount(); - safeMutex.ReleaseLock(); - } - else { - delete command; - changedActiveCommand = false; - } + // printf("Line: %d getCurrCommand() [%s] command + // [%s]\n",__LINE__,getCurrCommand()->toString(false).c_str(),command->toString(false).c_str()); + } - 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()); + clearCommands(); + changedActiveCommand = willChangedActiveCommand; + + // printf("In [%s::%s] Line: %d cleared existing + // commands\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + + 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()); + } + + 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()); + + // check command + result = checkCommand(command); + if (SystemFlags::getSystemSettingType(SystemFlags::debugUnitCommands).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugUnitCommands, + "In [%s::%s Line: %d] checkCommand returned: [%d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + result.first); + + // printf("In [%s::%s] Line: %d check command returned %d, commands.size() = + // %d\n[%s]\n\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,result,commands.size(),command->toString().c_str()); + + 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()); + + if (result.first == crSuccess) { + applyCommand(command); + } + + 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()); + + // push back command + if (result.first == crSuccess) { + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(mutexCommands, mutexOwnerId); + + commands.push_back(command); + + safeMutex.ReleaseLock(); + } else { + delete command; + changedActiveCommand = false; + } + + 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()); + + return result; +} + +// pop front (used when order is done) +CommandResult Unit::finishCommand() { + changedActiveCommand = false; + retryCurrCommandCount = 0; + this->setCurrentUnitTitle(""); + // is empty? + if (commands.empty()) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + return crFailUndefined; + } + + // pop front + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(mutexCommands, mutexOwnerId); + + delete commands.front(); + commands.erase(commands.begin()); + + safeMutex.ReleaseLock(true); + + this->unitPath->clear(); + + while (commands.empty() == false) { + if (commands.front()->getUnit() != NULL && + this->faction->isUnitInLivingUnitsp(commands.front()->getUnit()) == + false) { + safeMutex.Lock(); + delete commands.front(); + commands.erase(commands.begin()); + safeMutex.ReleaseLock(true); + } else { + break; + } + } - return result; + return crSuccess; } -//pop front (used when order is done) -CommandResult Unit::finishCommand() { - changedActiveCommand = false; - retryCurrCommandCount=0; - this->setCurrentUnitTitle(""); - //is empty? - if(commands.empty()) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__, __LINE__); - return crFailUndefined; - } - - //pop front - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(mutexCommands,mutexOwnerId); - - delete commands.front(); - commands.erase(commands.begin()); - - safeMutex.ReleaseLock(true); - - this->unitPath->clear(); - - while (commands.empty() == false) { - if (commands.front()->getUnit() != NULL && this->faction->isUnitInLivingUnitsp(commands.front()->getUnit()) == false) { - safeMutex.Lock(); - delete commands.front(); - commands.erase(commands.begin()); - safeMutex.ReleaseLock(true); - } - else { - break; - } - } - - return crSuccess; -} - -//to cancel a command +// to cancel a command CommandResult Unit::cancelCommand() { - changedActiveCommand = false; - retryCurrCommandCount=0; - this->setCurrentUnitTitle(""); - - //is empty? - if(commands.empty()){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__, __LINE__); - return crFailUndefined; - } - - //undo command - undoCommand(commands.back()); + changedActiveCommand = false; + retryCurrCommandCount = 0; + this->setCurrentUnitTitle(""); - //delete ans pop command - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(mutexCommands,mutexOwnerId); + // is empty? + if (commands.empty()) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + return crFailUndefined; + } - delete commands.back(); - commands.pop_back(); + // undo command + undoCommand(commands.back()); - safeMutex.ReleaseLock(); + // delete ans pop command + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(mutexCommands, mutexOwnerId); - //clear routes - this->unitPath->clear(); + delete commands.back(); + commands.pop_back(); + safeMutex.ReleaseLock(); + // clear routes + this->unitPath->clear(); - return crSuccess; + return crSuccess; } // =================== route stack =================== void Unit::create(bool startingUnit) { - faction->addUnit(this); - map->putUnitCells(this, pos); - if(startingUnit) { - faction->applyStaticCosts(type,NULL); - } + faction->addUnit(this); + map->putUnitCells(this, pos); + if (startingUnit) { + faction->applyStaticCosts(type, NULL); + } } void Unit::born(const CommandType *ct) { - if(type == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - faction->addStore(type); - faction->applyStaticProduction(type,ct); - setCurrSkill(scStop); - - checkItemInVault(&this->hp,this->hp); - int original_hp = this->hp; - - - //set hp from start hp - checkItemInVault(&this->ep,this->ep); - if(type->getStartHpType() == UnitType::stValue) { - this->hp= type->getStartHpValue(); - } - else { - this->hp= type->getTotalMaxHp(&totalUpgrade) * type->getStartHpPercentage() / 100; - } - - if(original_hp != this->hp) { - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - game->getScriptManager()->onUnitTriggerEvent(this,utet_HPChanged); - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } - addItemToVault(&this->hp,this->hp); - - //set ep from start ep - checkItemInVault(&this->ep,this->ep); - if(type->getStartEpType() == UnitType::stValue) { - this->ep= type->getStartEpValue(); - } - else { - this->ep= type->getTotalMaxEp(&totalUpgrade) * type->getStartEpPercentage() / 100; - } + if (type == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + faction->addStore(type); + faction->applyStaticProduction(type, ct); + setCurrSkill(scStop); + + checkItemInVault(&this->hp, this->hp); + int original_hp = this->hp; + + // set hp from start hp + checkItemInVault(&this->ep, this->ep); + if (type->getStartHpType() == UnitType::stValue) { + this->hp = type->getStartHpValue(); + } else { + this->hp = + type->getTotalMaxHp(&totalUpgrade) * type->getStartHpPercentage() / 100; + } + + if (original_hp != this->hp) { + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + game->getScriptManager()->onUnitTriggerEvent(this, utet_HPChanged); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + } + addItemToVault(&this->hp, this->hp); + + // set ep from start ep + checkItemInVault(&this->ep, this->ep); + if (type->getStartEpType() == UnitType::stValue) { + this->ep = type->getStartEpValue(); + } else { + this->ep = + type->getTotalMaxEp(&totalUpgrade) * type->getStartEpPercentage() / 100; + } } void Unit::kill() { - //no longer needs static resources - if(isBeingBuilt()) { - faction->deApplyStaticConsumption(type,(getCurrCommand() != NULL ? getCurrCommand()->getCommandType() : NULL)); - } - else { - faction->deApplyStaticCosts(type,(getCurrCommand() != NULL ? getCurrCommand()->getCommandType() : NULL)); - } - - //do the cleaning - //clear commands ( and their blocking fields ) - clearCommands(); - - map->clearUnitCells(this, pos, true); - if(isBeingBuilt() == false) { - faction->removeStore(type); - } - setCurrSkill(scDie); + // no longer needs static resources + if (isBeingBuilt()) { + faction->deApplyStaticConsumption( + type, + (getCurrCommand() != NULL ? getCurrCommand()->getCommandType() : NULL)); + } else { + faction->deApplyStaticCosts( + type, + (getCurrCommand() != NULL ? getCurrCommand()->getCommandType() : NULL)); + } + + // do the cleaning + // clear commands ( and their blocking fields ) + clearCommands(); + + map->clearUnitCells(this, pos, true); + if (isBeingBuilt() == false) { + faction->removeStore(type); + } + setCurrSkill(scDie); + + notifyObservers(UnitObserver::eKill); + + UnitUpdater *unitUpdater = game->getWorld()->getUnitUpdater(); + // unitUpdater->clearUnitPrecache(this); + unitUpdater->removeUnitPrecache(this); +} - notifyObservers(UnitObserver::eKill); +void Unit::undertake() { + try { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] about to undertake unit id = %d [%s] [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->id, this->getFullName(false).c_str(), + this->getDesc(false).c_str()); + + // Remove any units that were previously in attack-boost range + if (currentAttackBoostOriginatorEffect.currentAttackBoostUnits.empty() == + false && + currentAttackBoostOriginatorEffect.skillType != NULL) { + for (unsigned int i = 0; + i < + currentAttackBoostOriginatorEffect.currentAttackBoostUnits.size(); + ++i) { + // Remove attack boost upgrades from unit + int findUnitId = + currentAttackBoostOriginatorEffect.currentAttackBoostUnits[i]; + Unit *affectedUnit = game->getWorld()->findUnitById(findUnitId); + if (affectedUnit != NULL) { + affectedUnit->deapplyAttackBoost( + currentAttackBoostOriginatorEffect.skillType->getAttackBoost(), + this); + } + + // printf("!!!! DE-APPLY ATTACK BOOST from unit [%s - + // %d]\n",affectedUnit->getType()->getName().c_str(),affectedUnit->getId()); + } + currentAttackBoostOriginatorEffect.currentAttackBoostUnits.clear(); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + UnitUpdater *unitUpdater = game->getWorld()->getUnitUpdater(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + // unitUpdater->clearUnitPrecache(this); + unitUpdater->removeUnitPrecache(this); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + this->faction->deleteLivingUnits(id); + this->faction->deleteLivingUnitsp(this); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + faction->removeUnit(this); + } catch (const megaglest_runtime_error &ex) { + string sErrBuf = ""; + if (ex.wantStackTrace() == true) { + char szErrBuf[8096] = ""; + snprintf(szErrBuf, 8096, "In [%s::%s %d]", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + sErrBuf = string(szErrBuf) + string("\nerror [") + string(ex.what()) + + string("]\n"); + } else { + sErrBuf = ex.what(); + } + SystemFlags::OutputDebug(SystemFlags::debugError, sErrBuf.c_str()); - UnitUpdater *unitUpdater = game->getWorld()->getUnitUpdater(); - //unitUpdater->clearUnitPrecache(this); - unitUpdater->removeUnitPrecache(this); -} + throw; + } catch (const std::exception &ex) { + char szErrBuf[8096] = ""; + snprintf(szErrBuf, 8096, "In [%s::%s %d]", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__); + string sErrBuf = string(szErrBuf) + string("\nerror [") + + string(ex.what()) + string("]\n"); + SystemFlags::OutputDebug(SystemFlags::debugError, sErrBuf.c_str()); -void Unit::undertake() { - try { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] about to undertake unit id = %d [%s] [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->id, this->getFullName(false).c_str(),this->getDesc(false).c_str()); - - // Remove any units that were previously in attack-boost range - if(currentAttackBoostOriginatorEffect.currentAttackBoostUnits.empty() == false && currentAttackBoostOriginatorEffect.skillType != NULL) { - for(unsigned int i = 0; i < currentAttackBoostOriginatorEffect.currentAttackBoostUnits.size(); ++i) { - // Remove attack boost upgrades from unit - int findUnitId = currentAttackBoostOriginatorEffect.currentAttackBoostUnits[i]; - Unit *affectedUnit = game->getWorld()->findUnitById(findUnitId); - if(affectedUnit != NULL) { - affectedUnit->deapplyAttackBoost(currentAttackBoostOriginatorEffect.skillType->getAttackBoost(), this); - } - - //printf("!!!! DE-APPLY ATTACK BOOST from unit [%s - %d]\n",affectedUnit->getType()->getName().c_str(),affectedUnit->getId()); - } - currentAttackBoostOriginatorEffect.currentAttackBoostUnits.clear(); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - UnitUpdater *unitUpdater = game->getWorld()->getUnitUpdater(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - //unitUpdater->clearUnitPrecache(this); - unitUpdater->removeUnitPrecache(this); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - this->faction->deleteLivingUnits(id); - this->faction->deleteLivingUnitsp(this); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - faction->removeUnit(this); - } - catch(const megaglest_runtime_error &ex) { - string sErrBuf = ""; - if(ex.wantStackTrace() == true) { - char szErrBuf[8096]=""; - snprintf(szErrBuf,8096,"In [%s::%s %d]",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - sErrBuf = string(szErrBuf) + string("\nerror [") + string(ex.what()) + string("]\n"); - } - else { - sErrBuf = ex.what(); - } - SystemFlags::OutputDebug(SystemFlags::debugError,sErrBuf.c_str()); - - throw; - } - catch(const std::exception &ex) { - char szErrBuf[8096]=""; - snprintf(szErrBuf,8096,"In [%s::%s %d]",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - string sErrBuf = string(szErrBuf) + string("\nerror [") + string(ex.what()) + string("]\n"); - SystemFlags::OutputDebug(SystemFlags::debugError,sErrBuf.c_str()); - - throw; - } + throw; + } } // =================== Referencers =================== -void Unit::addObserver(UnitObserver *unitObserver){ - observers.push_back(unitObserver); +void Unit::addObserver(UnitObserver *unitObserver) { + observers.push_back(unitObserver); } -//void Unit::removeObserver(UnitObserver *unitObserver){ +// void Unit::removeObserver(UnitObserver *unitObserver){ // observers.remove(unitObserver); -//} +// } -void Unit::notifyObservers(UnitObserver::Event event){ - for(Observers::iterator it= observers.begin(); it!=observers.end(); ++it){ - (*it)->unitEvent(event, this); - } +void Unit::notifyObservers(UnitObserver::Event event) { + for (Observers::iterator it = observers.begin(); it != observers.end(); + ++it) { + (*it)->unitEvent(event, this); + } } // =================== Other =================== -void Unit::resetHighlight(){ - highlight= 1.f; -} - -const CommandType *Unit::computeCommandType(const Vec2i &pos, const Unit *targetUnit) const{ - const CommandType *commandType= NULL; - - if(map->isInside(pos) == false || map->isInsideSurface(map->toSurfCoords(pos)) == false) { - throw megaglest_runtime_error("#6 Invalid path position = " + pos.getString()); - } - - SurfaceCell *sc= map->getSurfaceCell(Map::toSurfCoords(pos)); - - if(type == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - //printf("Line: %d Unit::computeCommandType pos [%s] targetUnit [%s]\n",__LINE__,pos.getString().c_str(),(targetUnit != NULL ? targetUnit->getType()->getName().c_str() : "(null)")); - if(targetUnit != NULL) { - //attack enemies - if(isAlly(targetUnit) == false) { - commandType= type->getFirstAttackCommand(targetUnit->getCurrField()); - } - //repair allies - else { - if(targetUnit->isBuilt() == false || targetUnit->isDamaged() == true) { - commandType= type->getFirstRepairCommand(targetUnit->getType()); - } - - //printf("Line: %d Unit::computeCommandType pos [%s] targetUnit [%s] commandType [%p]\n",__LINE__,pos.getString().c_str(),(targetUnit != NULL ? targetUnit->getType()->getName().c_str() : "(null)"),commandType); - - if(commandType == NULL && targetUnit != NULL) { - //Command *command= this->getCurrCommand(); - //const HarvestCommandType *hct= dynamic_cast((command != NULL ? command->getCommandType() : NULL)); - - // Check if we can return whatever resources we have - if(targetUnit->getFactionIndex() == this->getFactionIndex() && - targetUnit->isOperative() == true && - this->getLoadType() != NULL && this->getLoadCount() != 0 && - targetUnit->getType() != NULL && - targetUnit->getType()->getStore(this->getLoadType()) > 0) { - - commandType = type->getFirstHarvestEmergencyReturnCommand(); - } - } - } - } - else { - //check harvest command - Resource *resource= sc->getResource(); - if(resource != NULL) { - commandType= type->getFirstHarvestCommand(resource->getType(),this->getFaction()); - } - } - - if(targetUnit == NULL && commandType == NULL) { - const Vec2i unitTargetPos = pos; - Cell *cell= map->getCell(unitTargetPos); - if(cell != NULL && cell->getUnit(this->getCurrField()) != NULL) { - Unit *targetUnit = cell->getUnit(this->getCurrField()); - if(targetUnit != NULL) { - // Check if we want to help build (repair) any buildings instead of just moving - if(targetUnit->getFactionIndex() == this->getFactionIndex() && - (targetUnit->isBuilt() == false || targetUnit->isDamaged() == true)) { - const RepairCommandType *rct= this->getType()->getFirstRepairCommand(targetUnit->getType()); - if(rct != NULL) { - commandType= type->getFirstRepairCommand(targetUnit->getType()); - //printf("************ Unit will repair building built = %d, repair = %d\n",targetUnit->isBuilt(),targetUnit->isDamaged()); - } - } - } - } - } - - //default command is move command - if(commandType == NULL) { - commandType= type->getFirstCtOfClass(ccMove); - } - - return commandType; +void Unit::resetHighlight() { highlight = 1.f; } + +const CommandType *Unit::computeCommandType(const Vec2i &pos, + const Unit *targetUnit) const { + const CommandType *commandType = NULL; + + if (map->isInside(pos) == false || + map->isInsideSurface(map->toSurfCoords(pos)) == false) { + throw megaglest_runtime_error("#6 Invalid path position = " + + pos.getString()); + } + + SurfaceCell *sc = map->getSurfaceCell(Map::toSurfCoords(pos)); + + if (type == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + // printf("Line: %d Unit::computeCommandType pos [%s] targetUnit + // [%s]\n",__LINE__,pos.getString().c_str(),(targetUnit != NULL ? + // targetUnit->getType()->getName().c_str() : "(null)")); + if (targetUnit != NULL) { + // attack enemies + if (isAlly(targetUnit) == false) { + commandType = type->getFirstAttackCommand(targetUnit->getCurrField()); + } + // repair allies + else { + if (targetUnit->isBuilt() == false || targetUnit->isDamaged() == true) { + commandType = type->getFirstRepairCommand(targetUnit->getType()); + } + + // printf("Line: %d Unit::computeCommandType pos [%s] targetUnit [%s] + // commandType [%p]\n",__LINE__,pos.getString().c_str(),(targetUnit != + // NULL ? targetUnit->getType()->getName().c_str() : + // "(null)"),commandType); + + if (commandType == NULL && targetUnit != NULL) { + // Command *command= this->getCurrCommand(); + // const HarvestCommandType *hct= dynamic_cast((command != NULL ? command->getCommandType() : + // NULL)); + + // Check if we can return whatever resources we have + if (targetUnit->getFactionIndex() == this->getFactionIndex() && + targetUnit->isOperative() == true && this->getLoadType() != NULL && + this->getLoadCount() != 0 && targetUnit->getType() != NULL && + targetUnit->getType()->getStore(this->getLoadType()) > 0) { + + commandType = type->getFirstHarvestEmergencyReturnCommand(); + } + } + } + } else { + // check harvest command + Resource *resource = sc->getResource(); + if (resource != NULL) { + commandType = + type->getFirstHarvestCommand(resource->getType(), this->getFaction()); + } + } + + if (targetUnit == NULL && commandType == NULL) { + const Vec2i unitTargetPos = pos; + Cell *cell = map->getCell(unitTargetPos); + if (cell != NULL && cell->getUnit(this->getCurrField()) != NULL) { + Unit *targetUnit = cell->getUnit(this->getCurrField()); + if (targetUnit != NULL) { + // Check if we want to help build (repair) any buildings instead of just + // moving + if (targetUnit->getFactionIndex() == this->getFactionIndex() && + (targetUnit->isBuilt() == false || + targetUnit->isDamaged() == true)) { + const RepairCommandType *rct = + this->getType()->getFirstRepairCommand(targetUnit->getType()); + if (rct != NULL) { + commandType = type->getFirstRepairCommand(targetUnit->getType()); + // printf("************ Unit will repair building built = %d, repair + // = %d\n",targetUnit->isBuilt(),targetUnit->isDamaged()); + } + } + } + } + } + + // default command is move command + if (commandType == NULL) { + commandType = type->getFirstCtOfClass(ccMove); + } + + return commandType; } int64 Unit::getUpdateProgress() { - if(progress > PROGRESS_SPEED_MULTIPLIER) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: progress > " MG_I64_SPECIFIER ", progress = [" MG_I64_SPECIFIER "]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,PROGRESS_SPEED_MULTIPLIER,progress); - throw megaglest_runtime_error(szBuf); - } - - if(currSkill == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: currSkill == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - int64 newProgress = progress; - if(currSkill->getClass() != scDie) { - //speed - int speed = currSkill->getTotalSpeed(&totalUpgrade); - - if(changedActiveCommand == true) { - if(changedActiveCommandFrame - lastChangedActiveCommandFrame >= MIN_FRAMECOUNT_CHANGE_COMMAND_SPEED) { - //printf("Line: %d speed = %d changedActiveCommandFrame [%u] lastChangedActiveCommandFrame [%u] skill [%s] command [%s]\n",__LINE__,speed,changedActiveCommandFrame,lastChangedActiveCommandFrame,currSkill->toString(false).c_str(),getCurrCommand()->toString(false).c_str()); - //printf("Line: %d speed = %d changedActiveCommandFrame [%u] lastChangedActiveCommandFrame [%u] total = %u\n",__LINE__,speed,changedActiveCommandFrame,lastChangedActiveCommandFrame,(changedActiveCommandFrame - lastChangedActiveCommandFrame)); - speed = CHANGE_COMMAND_SPEED; - } - } - - //speed modifier - int64 diagonalFactor = getDiagonalFactor(); - int64 heightFactor = getHeightFactor(PROGRESS_SPEED_MULTIPLIER); - - //update progresses -// const Game *game = Renderer::getInstance().getGame(); -// if(game == NULL) { -// throw megaglest_runtime_error("game == NULL"); -// } -// if(game->getWorld() == NULL) { -// throw megaglest_runtime_error("game->getWorld() == NULL"); -// } + if (progress > PROGRESS_SPEED_MULTIPLIER) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: progress > " MG_I64_SPECIFIER + ", progress = [" MG_I64_SPECIFIER "]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, PROGRESS_SPEED_MULTIPLIER, progress); + throw megaglest_runtime_error(szBuf); + } + + if (currSkill == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: currSkill == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + int64 newProgress = progress; + if (currSkill->getClass() != scDie) { + // speed + int speed = currSkill->getTotalSpeed(&totalUpgrade); + + if (changedActiveCommand == true) { + if (changedActiveCommandFrame - lastChangedActiveCommandFrame >= + MIN_FRAMECOUNT_CHANGE_COMMAND_SPEED) { + // printf("Line: %d speed = %d changedActiveCommandFrame [%u] + // lastChangedActiveCommandFrame [%u] skill [%s] command + // [%s]\n",__LINE__,speed,changedActiveCommandFrame,lastChangedActiveCommandFrame,currSkill->toString(false).c_str(),getCurrCommand()->toString(false).c_str()); + // printf("Line: %d speed = %d changedActiveCommandFrame [%u] + // lastChangedActiveCommandFrame [%u] total = + // %u\n",__LINE__,speed,changedActiveCommandFrame,lastChangedActiveCommandFrame,(changedActiveCommandFrame + // - lastChangedActiveCommandFrame)); + speed = CHANGE_COMMAND_SPEED; + } + } + + // speed modifier + int64 diagonalFactor = getDiagonalFactor(); + int64 heightFactor = getHeightFactor(PROGRESS_SPEED_MULTIPLIER); - newProgress = getUpdatedProgress(progress, GameConstants::updateFps, - speed, diagonalFactor, heightFactor); + // update progresses + // const Game *game = Renderer::getInstance().getGame(); + // if(game == NULL) { + // throw megaglest_runtime_error("game == NULL"); + // } + // if(game->getWorld() == NULL) { + // throw megaglest_runtime_error("game->getWorld() == + // NULL"); + // } - } - return newProgress; + newProgress = getUpdatedProgress(progress, GameConstants::updateFps, speed, + diagonalFactor, heightFactor); + } + return newProgress; } bool Unit::needToUpdate() { - bool return_value = false; - if(currSkill->getClass() != scDie) { - int newProgress = getUpdateProgress(); - if(newProgress >= PROGRESS_SPEED_MULTIPLIER) { - return_value = true; - } - } - return return_value; + bool return_value = false; + if (currSkill->getClass() != scDie) { + int newProgress = getUpdateProgress(); + if (newProgress >= PROGRESS_SPEED_MULTIPLIER) { + return_value = true; + } + } + return return_value; } int64 Unit::getDiagonalFactor() { - //speed modifier - int64 diagonalFactor= PROGRESS_SPEED_MULTIPLIER; - if(currSkill->getClass() == scMove) { - //if moving in diagonal move slower - Vec2i dest= pos - lastPos; - if(abs(dest.x) + abs(dest.y) == 2) { - //diagonalFactor = 0.71f * PROGRESS_SPEED_MULTIPLIER; - diagonalFactor = 71 * (PROGRESS_SPEED_MULTIPLIER / 100); - } - } - return diagonalFactor; + // speed modifier + int64 diagonalFactor = PROGRESS_SPEED_MULTIPLIER; + if (currSkill->getClass() == scMove) { + // if moving in diagonal move slower + Vec2i dest = pos - lastPos; + if (abs(dest.x) + abs(dest.y) == 2) { + // diagonalFactor = 0.71f * PROGRESS_SPEED_MULTIPLIER; + diagonalFactor = 71 * (PROGRESS_SPEED_MULTIPLIER / 100); + } + } + return diagonalFactor; } int64 Unit::getHeightFactor(int64 speedMultiplier) { - int64 heightFactor = speedMultiplier; - if(currSkill->getClass() == scMove) { - //if moving to an higher cell move slower else move faster - Cell *unitCell = map->getCell(pos); - if(unitCell == NULL) { - throw megaglest_runtime_error("unitCell == NULL"); - } + int64 heightFactor = speedMultiplier; + if (currSkill->getClass() == scMove) { + // if moving to an higher cell move slower else move faster + Cell *unitCell = map->getCell(pos); + if (unitCell == NULL) { + throw megaglest_runtime_error("unitCell == NULL"); + } - Cell *targetCell = map->getCell(targetPos); - if(targetCell == NULL) { - throw megaglest_runtime_error("targetCell == NULL"); - } + Cell *targetCell = map->getCell(targetPos); + if (targetCell == NULL) { + throw megaglest_runtime_error("targetCell == NULL"); + } - int64 heightDiff= ((truncateDecimal(unitCell->getHeight(),2) * speedMultiplier) - - (truncateDecimal(targetCell->getHeight(),2) * speedMultiplier)); - //heightFactor= clamp(speedMultiplier + heightDiff / (5.f * speedMultiplier), 0.2f * speedMultiplier, 5.f * speedMultiplier); - heightFactor= clamp(speedMultiplier + heightDiff / (5 * speedMultiplier), (2 * (speedMultiplier / 10)), 5 * speedMultiplier); - } + int64 heightDiff = + ((truncateDecimal(unitCell->getHeight(), 2) * speedMultiplier) - + (truncateDecimal(targetCell->getHeight(), 2) * + speedMultiplier)); + // heightFactor= clamp(speedMultiplier + heightDiff / (5.f * + // speedMultiplier), 0.2f * speedMultiplier, 5.f * speedMultiplier); + heightFactor = clamp(speedMultiplier + heightDiff / (5 * speedMultiplier), + (2 * (speedMultiplier / 10)), 5 * speedMultiplier); + } - return heightFactor; + return heightFactor; } int64 Unit::getSpeedDenominator(int64 updateFPS) { - int64 speedDenominator = (speedDivider * updateFPS) * PROGRESS_SPEED_MULTIPLIER; - return speedDenominator; -} -int64 Unit::getUpdatedProgress(int64 currentProgress, int64 updateFPS, int64 speed, - int64 diagonalFactor, int64 heightFactor) { - - int64 speedDenominator = getSpeedDenominator(updateFPS); - int64 newProgress = currentProgress; - int64 progressIncrease = ((speed * diagonalFactor * heightFactor) / speedDenominator); - // Ensure we increment at least a value of 1 of the action will be stuck infinitely - if(speed > 0 && diagonalFactor > 0 && heightFactor > 0 && progressIncrease == 0) { - progressIncrease = 1; - } - - if(isNetworkCRCEnabled() == true) { - float height = map->getCell(pos)->getHeight(); - float airHeight = game->getWorld()->getTileset()->getAirHeight(); - int cellUnitHeight = -1; - int cellObjectHeight = -1; - - Unit *unit = map->getCell(pos)->getUnit(fLand); - if(unit != NULL && unit->getType()->getHeight() > airHeight) { - cellUnitHeight = unit->getType()->getHeight(); - } - else { - SurfaceCell *sc = map->getSurfaceCell(map->toSurfCoords(pos)); - if(sc != NULL && sc->getObject() != NULL && sc->getObject()->getType() != NULL) { - if(sc->getObject()->getType()->getHeight() > airHeight) { - cellObjectHeight = sc->getObject()->getType()->getHeight(); - } - } - } - - - char szBuf[8096]=""; - snprintf(szBuf,8095,"currentProgress = " MG_I64_SPECIFIER " updateFPS = " MG_I64_SPECIFIER " speed = " MG_I64_SPECIFIER " diagonalFactor = " MG_I64_SPECIFIER " heightFactor = " MG_I64_SPECIFIER " speedDenominator = " MG_I64_SPECIFIER " progressIncrease = " MG_I64_SPECIFIER " [" MG_I64_SPECIFIER "] height [%f] airHeight [%f] cellUnitHeight [%d] cellObjectHeight [%d] skill [%s] pos [%s] lastpos [%s]", - currentProgress,updateFPS,speed,diagonalFactor,heightFactor,speedDenominator,progressIncrease,((speed * diagonalFactor * heightFactor) / speedDenominator),height,airHeight,cellUnitHeight,cellObjectHeight,(currSkill != NULL ? currSkill->getName().c_str() : "none"),pos.getString().c_str(),lastPos.getString().c_str()); - networkCRCLogInfo = szBuf; - - //printf("%s\n",szBuf); - } - - newProgress += progressIncrease; - -// if(currSkill->getClass() == scMove || (currSkill->getClass() == scStop && this->loadCount > 0)) { -// printf("speedDenominator: " MG_I64_SPECIFIER " currentProgress: " MG_I64_SPECIFIER " speed: " MG_I64_SPECIFIER " diagonalFactor: " MG_I64_SPECIFIER " heightFactor: " MG_I64_SPECIFIER " progressIncrease: " MG_I64_SPECIFIER " newProgress: " MG_I64_SPECIFIER " TOP #: " MG_I64_SPECIFIER "\n",speedDenominator,currentProgress,speed,diagonalFactor,heightFactor,progressIncrease,newProgress,(speed * diagonalFactor * heightFactor)); -// } + int64 speedDenominator = + (speedDivider * updateFPS) * PROGRESS_SPEED_MULTIPLIER; + return speedDenominator; +} +int64 Unit::getUpdatedProgress(int64 currentProgress, int64 updateFPS, + int64 speed, int64 diagonalFactor, + int64 heightFactor) { + + int64 speedDenominator = getSpeedDenominator(updateFPS); + int64 newProgress = currentProgress; + int64 progressIncrease = + ((speed * diagonalFactor * heightFactor) / speedDenominator); + // Ensure we increment at least a value of 1 of the action will be stuck + // infinitely + if (speed > 0 && diagonalFactor > 0 && heightFactor > 0 && + progressIncrease == 0) { + progressIncrease = 1; + } + + if (isNetworkCRCEnabled() == true) { + float height = map->getCell(pos)->getHeight(); + float airHeight = game->getWorld()->getTileset()->getAirHeight(); + int cellUnitHeight = -1; + int cellObjectHeight = -1; + + Unit *unit = map->getCell(pos)->getUnit(fLand); + if (unit != NULL && unit->getType()->getHeight() > airHeight) { + cellUnitHeight = unit->getType()->getHeight(); + } else { + SurfaceCell *sc = map->getSurfaceCell(map->toSurfCoords(pos)); + if (sc != NULL && sc->getObject() != NULL && + sc->getObject()->getType() != NULL) { + if (sc->getObject()->getType()->getHeight() > airHeight) { + cellObjectHeight = sc->getObject()->getType()->getHeight(); + } + } + } + + char szBuf[8096] = ""; + snprintf(szBuf, 8095, + "currentProgress = " MG_I64_SPECIFIER + " updateFPS = " MG_I64_SPECIFIER " speed = " MG_I64_SPECIFIER + " diagonalFactor = " MG_I64_SPECIFIER + " heightFactor = " MG_I64_SPECIFIER + " speedDenominator = " MG_I64_SPECIFIER + " progressIncrease = " MG_I64_SPECIFIER " [" MG_I64_SPECIFIER + "] height [%f] airHeight [%f] cellUnitHeight [%d] " + "cellObjectHeight [%d] skill [%s] pos [%s] lastpos [%s]", + currentProgress, updateFPS, speed, diagonalFactor, heightFactor, + speedDenominator, progressIncrease, + ((speed * diagonalFactor * heightFactor) / speedDenominator), + height, airHeight, cellUnitHeight, cellObjectHeight, + (currSkill != NULL ? currSkill->getName().c_str() : "none"), + pos.getString().c_str(), lastPos.getString().c_str()); + networkCRCLogInfo = szBuf; + + // printf("%s\n",szBuf); + } + + newProgress += progressIncrease; + + // if(currSkill->getClass() == scMove || (currSkill->getClass() == scStop + //&& this->loadCount > 0)) { printf("speedDenominator: " + //MG_I64_SPECIFIER " currentProgress: " MG_I64_SPECIFIER " speed: " + // MG_I64_SPECIFIER " diagonalFactor: " MG_I64_SPECIFIER " heightFactor: " + // MG_I64_SPECIFIER " progressIncrease: " MG_I64_SPECIFIER " newProgress: " + // MG_I64_SPECIFIER " TOP + // #: " MG_I64_SPECIFIER + //"\n",speedDenominator,currentProgress,speed,diagonalFactor,heightFactor,progressIncrease,newProgress,(speed + //* diagonalFactor * heightFactor)); + // } + + return newProgress; +} + +void Unit::updateAttackBoostProgress(const Game *game) { + const bool debugBoost = false; + if (debugBoost) + printf("===================== START Unit [%d - %s] skill: %s affected unit " + "size: " MG_SIZE_T_SPECIFIER "\n", + this->id, this->getType()->getName(false).c_str(), + currSkill->getBoostDesc(false).c_str(), + currentAttackBoostOriginatorEffect.currentAttackBoostUnits.size()); + + if (currSkill != currentAttackBoostOriginatorEffect.skillType) { + + if (debugBoost) + printf("Line: %d new [%s]\n", __LINE__, + (currentAttackBoostOriginatorEffect.skillType != NULL + ? currentAttackBoostOriginatorEffect.skillType + ->getBoostDesc(false) + .c_str() + : "")); + + if (currentAttackBoostOriginatorEffect.currentAppliedEffect != NULL) { + delete currentAttackBoostOriginatorEffect.currentAppliedEffect; + currentAttackBoostOriginatorEffect.currentAppliedEffect = NULL; + + // printf("- #1 DE-APPLY ATTACK BOOST SELF PARTICLE to unit [%s - + // %d]\n",this->getType()->getName().c_str(),this->getId()); + } + + // Remove any units that were previously in range + if (currentAttackBoostOriginatorEffect.currentAttackBoostUnits.empty() == + false && + currentAttackBoostOriginatorEffect.skillType != NULL) { + for (unsigned int i = 0; + i < + currentAttackBoostOriginatorEffect.currentAttackBoostUnits.size(); + ++i) { + // Remove attack boost upgrades from unit + + int findUnitId = + currentAttackBoostOriginatorEffect.currentAttackBoostUnits[i]; + Unit *affectedUnit = game->getWorld()->findUnitById(findUnitId); + if (affectedUnit != NULL) { + affectedUnit->deapplyAttackBoost( + currentAttackBoostOriginatorEffect.skillType->getAttackBoost(), + this); + } + + // printf("- #1 DE-APPLY ATTACK BOOST from unit [%s - + // %d]\n",affectedUnit->getType()->getName().c_str(),affectedUnit->getId()); + } + currentAttackBoostOriginatorEffect.currentAttackBoostUnits.clear(); + } - return newProgress; -} - -void Unit::updateAttackBoostProgress(const Game* game) { - const bool debugBoost = false; - if(debugBoost) printf("===================== START Unit [%d - %s] skill: %s affected unit size: " MG_SIZE_T_SPECIFIER "\n", - this->id,this->getType()->getName(false).c_str(),currSkill->getBoostDesc(false).c_str(), - currentAttackBoostOriginatorEffect.currentAttackBoostUnits.size()); - - if (currSkill != currentAttackBoostOriginatorEffect.skillType) { - - if(debugBoost) printf("Line: %d new [%s]\n",__LINE__,(currentAttackBoostOriginatorEffect.skillType != NULL ? currentAttackBoostOriginatorEffect.skillType->getBoostDesc(false).c_str() : "")); - - if (currentAttackBoostOriginatorEffect.currentAppliedEffect != NULL) { - delete currentAttackBoostOriginatorEffect.currentAppliedEffect; - currentAttackBoostOriginatorEffect.currentAppliedEffect = NULL; - - //printf("- #1 DE-APPLY ATTACK BOOST SELF PARTICLE to unit [%s - %d]\n",this->getType()->getName().c_str(),this->getId()); - } - - // Remove any units that were previously in range - if (currentAttackBoostOriginatorEffect.currentAttackBoostUnits.empty() == false && - currentAttackBoostOriginatorEffect.skillType != NULL) { - for (unsigned int i = 0; - i < currentAttackBoostOriginatorEffect.currentAttackBoostUnits.size(); - ++i) { - // Remove attack boost upgrades from unit - - int findUnitId = currentAttackBoostOriginatorEffect.currentAttackBoostUnits[i]; - Unit *affectedUnit = game->getWorld()->findUnitById(findUnitId); - if (affectedUnit != NULL) { - affectedUnit->deapplyAttackBoost( - currentAttackBoostOriginatorEffect.skillType->getAttackBoost(), - this); - } - - //printf("- #1 DE-APPLY ATTACK BOOST from unit [%s - %d]\n",affectedUnit->getType()->getName().c_str(),affectedUnit->getId()); - } - currentAttackBoostOriginatorEffect.currentAttackBoostUnits.clear(); - } - - if(debugBoost) printf("Line: %d affected unit size: " MG_SIZE_T_SPECIFIER "\n",__LINE__,currentAttackBoostOriginatorEffect.currentAttackBoostUnits.size()); - - currentAttackBoostOriginatorEffect.skillType = currSkill; - - if (currSkill->isAttackBoostEnabled() == true) { - if(debugBoost) printf("Line: %d affected unit size: " MG_SIZE_T_SPECIFIER "\n",__LINE__,currentAttackBoostOriginatorEffect.currentAttackBoostUnits.size()); - - // Search for units in range of this unit which apply to the - // attack-boost and temporarily upgrade them - UnitUpdater *unitUpdater = this->game->getWorld()->getUnitUpdater(); - - const AttackBoost *attackBoost = currSkill->getAttackBoost(); - vector candidates = unitUpdater->findUnitsInRange(this, - attackBoost->radius); - - if(debugBoost) printf("Line: %d candidates unit size: " MG_SIZE_T_SPECIFIER " attackBoost: %s\n",__LINE__,candidates.size(),attackBoost->getDesc(false).c_str()); - for (unsigned int i = 0; i < candidates.size(); ++i) { - Unit *affectedUnit = candidates[i]; - if (attackBoost->isAffected(this, affectedUnit) == true) { - if (affectedUnit->applyAttackBoost(attackBoost, this) == true) { - currentAttackBoostOriginatorEffect.currentAttackBoostUnits.push_back(affectedUnit->getId()); - //printf("+ #1 APPLY ATTACK BOOST to unit [%s - %d]\n",affectedUnit->getType()->getName().c_str(),affectedUnit->getId()); - } - } - } - - if(debugBoost) printf("Line: %d affected unit size: " MG_SIZE_T_SPECIFIER "\n",__LINE__,currentAttackBoostOriginatorEffect.currentAttackBoostUnits.size()); - - if (showUnitParticles == true) { - if (currentAttackBoostOriginatorEffect.currentAttackBoostUnits.empty() == false) { - if (attackBoost->unitParticleSystemTypeForSourceUnit != NULL) { - currentAttackBoostOriginatorEffect.currentAppliedEffect = new UnitAttackBoostEffect(); - currentAttackBoostOriginatorEffect.currentAppliedEffect->upst = new UnitParticleSystemType(); - *currentAttackBoostOriginatorEffect.currentAppliedEffect->upst = *attackBoost->unitParticleSystemTypeForSourceUnit; - //effect.upst = boost->unitParticleSystemTypeForAffectedUnit; - - currentAttackBoostOriginatorEffect.currentAppliedEffect->ups = new UnitParticleSystem(200); - currentAttackBoostOriginatorEffect.currentAppliedEffect->ups->setParticleOwner(this); - currentAttackBoostOriginatorEffect.currentAppliedEffect->ups->setParticleType(currentAttackBoostOriginatorEffect.currentAppliedEffect->upst); - - currentAttackBoostOriginatorEffect.currentAppliedEffect->upst->setValues( - currentAttackBoostOriginatorEffect.currentAppliedEffect->ups); - currentAttackBoostOriginatorEffect.currentAppliedEffect->ups->setPos( - getCurrVectorForParticlesystems()); - currentAttackBoostOriginatorEffect.currentAppliedEffect->ups->setRotation(getRotation()); - setMeshPosInParticleSystem(currentAttackBoostOriginatorEffect.currentAppliedEffect->ups); - - if (getFaction()->getTexture()) { - currentAttackBoostOriginatorEffect. - currentAppliedEffect->ups->setFactionColor( - getFaction()->getTexture()-> - getPixmapConst()->getPixel3f( - 0, 0)); - } - Renderer::getInstance().manageParticleSystem( - currentAttackBoostOriginatorEffect.currentAppliedEffect->ups, - rsGame); - //printf("+ #1 APPLY ATTACK BOOST SELF PARTICLE to unit [%s - %d]\n",this->getType()->getName().c_str(),this->getId()); - } - } - } - } - } - else { - if (currSkill->isAttackBoostEnabled() == true) { - if(debugBoost) printf("Line: %d affected unit size: " MG_SIZE_T_SPECIFIER "\n",__LINE__,currentAttackBoostOriginatorEffect.currentAttackBoostUnits.size()); - - // Search for units in range of this unit which apply to the - // attack-boost and temporarily upgrade them - UnitUpdater *unitUpdater = this->game->getWorld()->getUnitUpdater(); - - const AttackBoost *attackBoost = currSkill->getAttackBoost(); - vector candidates = unitUpdater->findUnitsInRange(this,attackBoost->radius); - vector candidateValidIdList; - candidateValidIdList.reserve(candidates.size()); - - if(debugBoost) printf("Line: %d candidates unit size: " MG_SIZE_T_SPECIFIER " attackBoost: %s\n",__LINE__,candidates.size(),attackBoost->getDesc(false).c_str()); - - for (unsigned int i = 0; i < candidates.size(); ++i) { - Unit *affectedUnit = candidates[i]; - candidateValidIdList.push_back(affectedUnit->getId()); - - std::vector::iterator iterFound = std::find( - currentAttackBoostOriginatorEffect.currentAttackBoostUnits.begin(), - currentAttackBoostOriginatorEffect.currentAttackBoostUnits.end(), - affectedUnit->getId()); - - if (attackBoost->isAffected(this, affectedUnit) == true) { - if (iterFound == currentAttackBoostOriginatorEffect.currentAttackBoostUnits.end()) { - if (affectedUnit->applyAttackBoost(attackBoost, this) == true) { - currentAttackBoostOriginatorEffect.currentAttackBoostUnits.push_back( - affectedUnit->getId()); - - //printf("+ #2 APPLY ATTACK BOOST to unit [%s - %d]\n",affectedUnit->getType()->getName().c_str(),affectedUnit->getId()); - } - } - } - else { - if (iterFound != currentAttackBoostOriginatorEffect.currentAttackBoostUnits.end()) { - affectedUnit->deapplyAttackBoost( - currentAttackBoostOriginatorEffect.skillType->getAttackBoost(), - this); - currentAttackBoostOriginatorEffect.currentAttackBoostUnits.erase( - iterFound); - - //printf("- #2 DE-APPLY ATTACK BOOST from unit [%s - %d]\n",affectedUnit->getType()->getName().c_str(),affectedUnit->getId()); - } - } - } - - // Now remove any units that were in the list of boosted units but - // are no longer in range - if(currentAttackBoostOriginatorEffect.currentAttackBoostUnits.empty() == false) { - for (int i = (int)currentAttackBoostOriginatorEffect.currentAttackBoostUnits.size() -1; i >= 0; --i) { - int findUnitId = currentAttackBoostOriginatorEffect.currentAttackBoostUnits[i]; - - std::vector::iterator iterFound = std::find( - candidateValidIdList.begin(), - candidateValidIdList.end(), - findUnitId); - if(iterFound == candidateValidIdList.end()) { - Unit *affectedUnit = game->getWorld()->findUnitById(findUnitId); - if (affectedUnit != NULL) { - affectedUnit->deapplyAttackBoost( - currentAttackBoostOriginatorEffect.skillType->getAttackBoost(), - this); - - if(debugBoost) printf("Removed attack boost from Unit [%d - %s] since they are NO LONGER in range\n", - affectedUnit->id,affectedUnit->getType()->getName(false).c_str()); - - } - currentAttackBoostOriginatorEffect.currentAttackBoostUnits.erase( - currentAttackBoostOriginatorEffect.currentAttackBoostUnits.begin()+i); - } - } - } - - if(debugBoost) printf("Line: %d affected unit size: " MG_SIZE_T_SPECIFIER "\n",__LINE__,currentAttackBoostOriginatorEffect.currentAttackBoostUnits.size()); - - if (showUnitParticles == true) { - if (currentAttackBoostOriginatorEffect.currentAttackBoostUnits.empty() == false) { - if (attackBoost->unitParticleSystemTypeForSourceUnit != NULL - && currentAttackBoostOriginatorEffect.currentAppliedEffect == NULL) { - - currentAttackBoostOriginatorEffect.currentAppliedEffect = new UnitAttackBoostEffect(); - currentAttackBoostOriginatorEffect.currentAppliedEffect->upst = new UnitParticleSystemType(); - *currentAttackBoostOriginatorEffect.currentAppliedEffect->upst = *attackBoost->unitParticleSystemTypeForSourceUnit; - //effect.upst = boost->unitParticleSystemTypeForAffectedUnit; - - currentAttackBoostOriginatorEffect.currentAppliedEffect->ups = new UnitParticleSystem(200); - currentAttackBoostOriginatorEffect.currentAppliedEffect->ups->setParticleOwner(this); - currentAttackBoostOriginatorEffect.currentAppliedEffect->ups->setParticleType(currentAttackBoostOriginatorEffect.currentAppliedEffect->upst); - - currentAttackBoostOriginatorEffect.currentAppliedEffect->upst->setValues( - currentAttackBoostOriginatorEffect.currentAppliedEffect->ups); - currentAttackBoostOriginatorEffect.currentAppliedEffect->ups->setPos( - getCurrVectorForParticlesystems()); - currentAttackBoostOriginatorEffect.currentAppliedEffect->ups->setRotation(getRotation()); - setMeshPosInParticleSystem(currentAttackBoostOriginatorEffect.currentAppliedEffect->ups); - - if (getFaction()->getTexture()) { - currentAttackBoostOriginatorEffect.currentAppliedEffect->ups->setFactionColor( - getFaction()->getTexture()->getPixmapConst()->getPixel3f( - 0, 0)); - } - Renderer::getInstance().manageParticleSystem( - currentAttackBoostOriginatorEffect.currentAppliedEffect->ups, - rsGame); - - //printf("+ #2 APPLY ATTACK BOOST SELF PARTICLE to unit [%s - %d]\n",this->getType()->getName().c_str(),this->getId()); - } - } - else if (currentAttackBoostOriginatorEffect.currentAttackBoostUnits.empty() == true) { - if (currentAttackBoostOriginatorEffect.currentAppliedEffect != NULL) { - delete currentAttackBoostOriginatorEffect.currentAppliedEffect; - currentAttackBoostOriginatorEffect.currentAppliedEffect = NULL; - - //printf("- #2 DE-APPLY ATTACK BOOST SELF PARTICLE to unit [%s - %d]\n",this->getType()->getName().c_str(),this->getId()); - } - } - } - } - } - - if(debugBoost) { - if (currSkill->isAttackBoostEnabled() == true) { - printf("Unit [%d - %s] has attackboost enabled: %s\n",this->id,this->getType()->getName(false).c_str(),currSkill->getBoostDesc(false).c_str()); - - if (currentAttackBoostOriginatorEffect.currentAttackBoostUnits.empty() == false) { - printf("Found affected units currentAttackBoostOriginatorEffect.skillType [%p]\n",currentAttackBoostOriginatorEffect.skillType); - - for(unsigned int i = 0; i < currentAttackBoostOriginatorEffect.currentAttackBoostUnits.size(); ++i) { - int unitnum = currentAttackBoostOriginatorEffect.currentAttackBoostUnits[i]; - printf("affected unit #: %u - %d\n",i,unitnum); - } - } - } - } + if (debugBoost) + printf("Line: %d affected unit size: " MG_SIZE_T_SPECIFIER "\n", __LINE__, + currentAttackBoostOriginatorEffect.currentAttackBoostUnits.size()); + + currentAttackBoostOriginatorEffect.skillType = currSkill; + + if (currSkill->isAttackBoostEnabled() == true) { + if (debugBoost) + printf( + "Line: %d affected unit size: " MG_SIZE_T_SPECIFIER "\n", __LINE__, + currentAttackBoostOriginatorEffect.currentAttackBoostUnits.size()); + + // Search for units in range of this unit which apply to the + // attack-boost and temporarily upgrade them + UnitUpdater *unitUpdater = this->game->getWorld()->getUnitUpdater(); + + const AttackBoost *attackBoost = currSkill->getAttackBoost(); + vector candidates = + unitUpdater->findUnitsInRange(this, attackBoost->radius); + + if (debugBoost) + printf("Line: %d candidates unit size: " MG_SIZE_T_SPECIFIER + " attackBoost: %s\n", + __LINE__, candidates.size(), + attackBoost->getDesc(false).c_str()); + for (unsigned int i = 0; i < candidates.size(); ++i) { + Unit *affectedUnit = candidates[i]; + if (attackBoost->isAffected(this, affectedUnit) == true) { + if (affectedUnit->applyAttackBoost(attackBoost, this) == true) { + currentAttackBoostOriginatorEffect.currentAttackBoostUnits + .push_back(affectedUnit->getId()); + // printf("+ #1 APPLY ATTACK BOOST to unit [%s - + // %d]\n",affectedUnit->getType()->getName().c_str(),affectedUnit->getId()); + } + } + } + + if (debugBoost) + printf( + "Line: %d affected unit size: " MG_SIZE_T_SPECIFIER "\n", __LINE__, + currentAttackBoostOriginatorEffect.currentAttackBoostUnits.size()); + + if (showUnitParticles == true) { + if (currentAttackBoostOriginatorEffect.currentAttackBoostUnits + .empty() == false) { + if (attackBoost->unitParticleSystemTypeForSourceUnit != NULL) { + currentAttackBoostOriginatorEffect.currentAppliedEffect = + new UnitAttackBoostEffect(); + currentAttackBoostOriginatorEffect.currentAppliedEffect->upst = + new UnitParticleSystemType(); + *currentAttackBoostOriginatorEffect.currentAppliedEffect->upst = + *attackBoost->unitParticleSystemTypeForSourceUnit; + // effect.upst = boost->unitParticleSystemTypeForAffectedUnit; + + currentAttackBoostOriginatorEffect.currentAppliedEffect->ups = + new UnitParticleSystem(200); + currentAttackBoostOriginatorEffect.currentAppliedEffect->ups + ->setParticleOwner(this); + currentAttackBoostOriginatorEffect.currentAppliedEffect->ups + ->setParticleType(currentAttackBoostOriginatorEffect + .currentAppliedEffect->upst); + + currentAttackBoostOriginatorEffect.currentAppliedEffect->upst + ->setValues(currentAttackBoostOriginatorEffect + .currentAppliedEffect->ups); + currentAttackBoostOriginatorEffect.currentAppliedEffect->ups + ->setPos(getCurrVectorForParticlesystems()); + currentAttackBoostOriginatorEffect.currentAppliedEffect->ups + ->setRotation(getRotation()); + setMeshPosInParticleSystem( + currentAttackBoostOriginatorEffect.currentAppliedEffect->ups); + + if (getFaction()->getTexture()) { + currentAttackBoostOriginatorEffect.currentAppliedEffect->ups + ->setFactionColor( + getFaction()->getTexture()->getPixmapConst()->getPixel3f( + 0, 0)); + } + Renderer::getInstance().manageParticleSystem( + currentAttackBoostOriginatorEffect.currentAppliedEffect->ups, + rsGame); + // printf("+ #1 APPLY ATTACK BOOST SELF PARTICLE to unit [%s - + // %d]\n",this->getType()->getName().c_str(),this->getId()); + } + } + } + } + } else { + if (currSkill->isAttackBoostEnabled() == true) { + if (debugBoost) + printf( + "Line: %d affected unit size: " MG_SIZE_T_SPECIFIER "\n", __LINE__, + currentAttackBoostOriginatorEffect.currentAttackBoostUnits.size()); + + // Search for units in range of this unit which apply to the + // attack-boost and temporarily upgrade them + UnitUpdater *unitUpdater = this->game->getWorld()->getUnitUpdater(); + + const AttackBoost *attackBoost = currSkill->getAttackBoost(); + vector candidates = + unitUpdater->findUnitsInRange(this, attackBoost->radius); + vector candidateValidIdList; + candidateValidIdList.reserve(candidates.size()); + + if (debugBoost) + printf("Line: %d candidates unit size: " MG_SIZE_T_SPECIFIER + " attackBoost: %s\n", + __LINE__, candidates.size(), + attackBoost->getDesc(false).c_str()); + + for (unsigned int i = 0; i < candidates.size(); ++i) { + Unit *affectedUnit = candidates[i]; + candidateValidIdList.push_back(affectedUnit->getId()); + + std::vector::iterator iterFound = std::find( + currentAttackBoostOriginatorEffect.currentAttackBoostUnits.begin(), + currentAttackBoostOriginatorEffect.currentAttackBoostUnits.end(), + affectedUnit->getId()); + + if (attackBoost->isAffected(this, affectedUnit) == true) { + if (iterFound == currentAttackBoostOriginatorEffect + .currentAttackBoostUnits.end()) { + if (affectedUnit->applyAttackBoost(attackBoost, this) == true) { + currentAttackBoostOriginatorEffect.currentAttackBoostUnits + .push_back(affectedUnit->getId()); + + // printf("+ #2 APPLY ATTACK BOOST to unit [%s - + // %d]\n",affectedUnit->getType()->getName().c_str(),affectedUnit->getId()); + } + } + } else { + if (iterFound != currentAttackBoostOriginatorEffect + .currentAttackBoostUnits.end()) { + affectedUnit->deapplyAttackBoost( + currentAttackBoostOriginatorEffect.skillType->getAttackBoost(), + this); + currentAttackBoostOriginatorEffect.currentAttackBoostUnits.erase( + iterFound); + + // printf("- #2 DE-APPLY ATTACK BOOST from unit [%s - + // %d]\n",affectedUnit->getType()->getName().c_str(),affectedUnit->getId()); + } + } + } + + // Now remove any units that were in the list of boosted units but + // are no longer in range + if (currentAttackBoostOriginatorEffect.currentAttackBoostUnits.empty() == + false) { + for (int i = (int)currentAttackBoostOriginatorEffect + .currentAttackBoostUnits.size() - + 1; + i >= 0; --i) { + int findUnitId = + currentAttackBoostOriginatorEffect.currentAttackBoostUnits[i]; + + std::vector::iterator iterFound = + std::find(candidateValidIdList.begin(), + candidateValidIdList.end(), findUnitId); + if (iterFound == candidateValidIdList.end()) { + Unit *affectedUnit = game->getWorld()->findUnitById(findUnitId); + if (affectedUnit != NULL) { + affectedUnit->deapplyAttackBoost( + currentAttackBoostOriginatorEffect.skillType + ->getAttackBoost(), + this); + + if (debugBoost) + printf("Removed attack boost from Unit [%d - %s] since they " + "are NO LONGER in range\n", + affectedUnit->id, + affectedUnit->getType()->getName(false).c_str()); + } + currentAttackBoostOriginatorEffect.currentAttackBoostUnits.erase( + currentAttackBoostOriginatorEffect.currentAttackBoostUnits + .begin() + + i); + } + } + } + + if (debugBoost) + printf( + "Line: %d affected unit size: " MG_SIZE_T_SPECIFIER "\n", __LINE__, + currentAttackBoostOriginatorEffect.currentAttackBoostUnits.size()); + + if (showUnitParticles == true) { + if (currentAttackBoostOriginatorEffect.currentAttackBoostUnits + .empty() == false) { + if (attackBoost->unitParticleSystemTypeForSourceUnit != NULL && + currentAttackBoostOriginatorEffect.currentAppliedEffect == NULL) { + + currentAttackBoostOriginatorEffect.currentAppliedEffect = + new UnitAttackBoostEffect(); + currentAttackBoostOriginatorEffect.currentAppliedEffect->upst = + new UnitParticleSystemType(); + *currentAttackBoostOriginatorEffect.currentAppliedEffect->upst = + *attackBoost->unitParticleSystemTypeForSourceUnit; + // effect.upst = boost->unitParticleSystemTypeForAffectedUnit; + + currentAttackBoostOriginatorEffect.currentAppliedEffect->ups = + new UnitParticleSystem(200); + currentAttackBoostOriginatorEffect.currentAppliedEffect->ups + ->setParticleOwner(this); + currentAttackBoostOriginatorEffect.currentAppliedEffect->ups + ->setParticleType(currentAttackBoostOriginatorEffect + .currentAppliedEffect->upst); + + currentAttackBoostOriginatorEffect.currentAppliedEffect->upst + ->setValues(currentAttackBoostOriginatorEffect + .currentAppliedEffect->ups); + currentAttackBoostOriginatorEffect.currentAppliedEffect->ups + ->setPos(getCurrVectorForParticlesystems()); + currentAttackBoostOriginatorEffect.currentAppliedEffect->ups + ->setRotation(getRotation()); + setMeshPosInParticleSystem( + currentAttackBoostOriginatorEffect.currentAppliedEffect->ups); + + if (getFaction()->getTexture()) { + currentAttackBoostOriginatorEffect.currentAppliedEffect->ups + ->setFactionColor( + getFaction()->getTexture()->getPixmapConst()->getPixel3f( + 0, 0)); + } + Renderer::getInstance().manageParticleSystem( + currentAttackBoostOriginatorEffect.currentAppliedEffect->ups, + rsGame); + + // printf("+ #2 APPLY ATTACK BOOST SELF PARTICLE to unit [%s - + // %d]\n",this->getType()->getName().c_str(),this->getId()); + } + } else if (currentAttackBoostOriginatorEffect.currentAttackBoostUnits + .empty() == true) { + if (currentAttackBoostOriginatorEffect.currentAppliedEffect != NULL) { + delete currentAttackBoostOriginatorEffect.currentAppliedEffect; + currentAttackBoostOriginatorEffect.currentAppliedEffect = NULL; + + // printf("- #2 DE-APPLY ATTACK BOOST SELF PARTICLE to unit [%s - + // %d]\n",this->getType()->getName().c_str(),this->getId()); + } + } + } + } + } + + if (debugBoost) { + if (currSkill->isAttackBoostEnabled() == true) { + printf("Unit [%d - %s] has attackboost enabled: %s\n", this->id, + this->getType()->getName(false).c_str(), + currSkill->getBoostDesc(false).c_str()); + + if (currentAttackBoostOriginatorEffect.currentAttackBoostUnits.empty() == + false) { + printf("Found affected units " + "currentAttackBoostOriginatorEffect.skillType [%p]\n", + currentAttackBoostOriginatorEffect.skillType); + + for (unsigned int i = 0; + i < + currentAttackBoostOriginatorEffect.currentAttackBoostUnits.size(); + ++i) { + int unitnum = + currentAttackBoostOriginatorEffect.currentAttackBoostUnits[i]; + printf("affected unit #: %u - %d\n", i, unitnum); + } + } + } + } } bool Unit::update() { - assert(progress <= PROGRESS_SPEED_MULTIPLIER); - - //highlight - if(highlight > 0.f) { - const Game *game = Renderer::getInstance().getGame(); - highlight -= 1.f / (Game::highlightTime * game->getWorld()->getUpdateFps(this->getFactionIndex())); - } - - if(currSkill == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: currSkill == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - //speed - int speed= currSkill->getTotalSpeed(&totalUpgrade); - - if( oldTotalSight != getType()->getTotalSight(this->getTotalUpgrade())){ - oldTotalSight= getType()->getTotalSight(this->getTotalUpgrade()); - // refresh FogOfWar and so on, because sight ha changed since last update - refreshPos(true); - } - - if(changedActiveCommand) { - if(changedActiveCommandFrame - lastChangedActiveCommandFrame >= MIN_FRAMECOUNT_CHANGE_COMMAND_SPEED) { - //printf("Line: %d speed = %d changedActiveCommandFrame [%u] lastChangedActiveCommandFrame [%u] skill [%s] command [%s]\n",__LINE__,speed,changedActiveCommandFrame,lastChangedActiveCommandFrame,currSkill->toString(false).c_str(),getCurrCommand()->toString(false).c_str()); - //printf("Line: %d speed = %d changedActiveCommandFrame [%u] lastChangedActiveCommandFrame [%u] total = %u\n",__LINE__,speed,changedActiveCommandFrame,lastChangedActiveCommandFrame,(changedActiveCommandFrame - lastChangedActiveCommandFrame)); - speed = CHANGE_COMMAND_SPEED; - } - } - - //speed modifier - int64 diagonalFactor = getDiagonalFactor(); - int64 heightFactor = getHeightFactor(PROGRESS_SPEED_MULTIPLIER); - - //update progresses - this->lastAnimProgress= this->animProgress; - const Game *game = Renderer::getInstance().getGame(); - - if(animProgress==0){ - AnimCycleStarts(); - } - progress = getUpdatedProgress(progress, - GameConstants::updateFps, - speed, diagonalFactor, heightFactor); - - //printf("Test progress = %d for unit [%d - %s]\n",progress,id,getType()->getName().c_str()); - - if(isAnimProgressBound() == true) { - float targetProgress=0; - if(currSkill->getClass() == scBeBuilt) { - targetProgress = this->getHpRatio(); - } - if(currSkill->getClass() == scProduce) { - targetProgress = this->getProgressRatio(); - } - if(currSkill->getClass() == scUpgrade) { - targetProgress = this->getProgressRatio(); - } - if(currSkill->getClass() == scMorph) { - targetProgress = this->getProgressRatio(); - } - - float targetProgressIntValue = targetProgress * ANIMATION_SPEED_MULTIPLIER; - if(this->animProgress < targetProgressIntValue) { - float diff = targetProgressIntValue - this->animProgress; - float progressIncrease = static_cast(this->animProgress) + diff / static_cast(GameConstants::updateFps); - // Ensure we increment at least a value of 1 of the action will be stuck infinitely - if(diff > 0.f && GameConstants::updateFps > 0 && progressIncrease == 0.f) { - progressIncrease = 1.f; - } - - //if(currSkill->getClass() == scBeBuilt) { - // printf("targetProgress: %.10f this->animProgress: %d diff: %.10f GameConstants::updateFps: %d progressIncrease: %.10f\n",targetProgress,this->animProgress,diff,GameConstants::updateFps,progressIncrease); - //} - - this->animProgress = progressIncrease; - - //if(currSkill->getClass() == scBeBuilt) { - // printf("Unit build progress: %d anim: %d\n",progress,this->animProgress); - //} - } - } - else { - int64 heightFactor = getHeightFactor(ANIMATION_SPEED_MULTIPLIER); - int64 speedDenominator = speedDivider * - game->getWorld()->getUpdateFps(this->getFactionIndex()); - - // Override the animation speed for attacks that have upgraded the attack speed - int animSpeed = currSkill->getAnimSpeed(); - if(currSkill->getClass() == scAttack) { - int animSpeedBoost = ((AttackSkillType *) currSkill)->getAnimSpeedBoost(&totalUpgrade); - animSpeed += animSpeedBoost; - } - - int64 progressIncrease = (animSpeed * heightFactor) / speedDenominator; - // Ensure we increment at least a value of 1 of the action will be stuck infinitely - if(currSkill->getAnimSpeed() > 0 && heightFactor > 0 && progressIncrease == 0) { - progressIncrease = 1; - } - this->animProgress += progressIncrease; - //this->animProgress += (currSkill->getAnimSpeed() * heightFactor) / speedDenominator; - - //if(currSkill->getClass() == scDie) { - // printf("Unit died progress: %d anim: %d\n",progress,this->animProgress); - //} - } - //update target - updateTarget(); - - //rotation - if(currSkill->getClass() != scStop) { - const int rotFactor= 2; - if(getProgressAsFloat() < 1.f / rotFactor) { - if(type->getFirstStOfClass(scMove)){ - if(abs((int)(lastRotation-targetRotation)) < 180) - rotation= lastRotation + (targetRotation - lastRotation) * - getProgressAsFloat() * rotFactor; - else { - float rotationTerm = targetRotation > lastRotation ? -360.f: +360.f; - rotation = lastRotation + (targetRotation - lastRotation + rotationTerm) * - getProgressAsFloat() * rotFactor; - } - } - } - } - - if(type->getProperty(UnitType::pRotatedClimb)){ - calculateXZRotation(); - } - else { - rotationZ=.0f; - rotationX=.0f; - } - - if(Renderer::getInstance().validateParticleSystemStillExists(this->fire,rsGame) == false) { - this->fire = NULL; - } - - if (this->fire != NULL) { - this->fire->setPos(getCurrBurnVector()); - } - for(UnitParticleSystems::iterator it= unitParticleSystems.begin(); it != unitParticleSystems.end(); ++it) { - if(Renderer::getInstance().validateParticleSystemStillExists((*it),rsGame) == true) { - (*it)->setPos(getCurrVectorForParticlesystems()); - (*it)->setRotation(getRotation()); - setMeshPosInParticleSystem(*it); - } - } - for(UnitParticleSystems::iterator it= damageParticleSystems.begin(); it != damageParticleSystems.end(); ++it) { - if(Renderer::getInstance().validateParticleSystemStillExists((*it),rsGame) == true) { - (*it)->setPos(getCurrVectorForParticlesystems()); - (*it)->setRotation(getRotation()); - setMeshPosInParticleSystem(*it); - } - } - - for(UnitParticleSystems::iterator it= smokeParticleSystems.begin(); it != smokeParticleSystems.end(); ++it) { - if(Renderer::getInstance().validateParticleSystemStillExists((*it),rsGame) == true) { - (*it)->setPos(getCurrMidHeightVector()); - (*it)->setRotation(getRotation()); - setMeshPosInParticleSystem(*it); - } - } - - //printf("Unit has attack boost? unit = [%d - %s] size = %d\n",this->getId(), this->getType()->getName(false).c_str(),(int)currentAttackBoostEffects.size()); - for(unsigned int i = 0; i < currentAttackBoostEffects.size(); ++i) { - UnitAttackBoostEffect *effect = currentAttackBoostEffects[i]; - if(effect != NULL && effect->ups != NULL) { - bool particleValid = Renderer::getInstance().validateParticleSystemStillExists(effect->ups,rsGame); - if(particleValid == true) { - effect->ups->setPos(getCurrVectorForParticlesystems()); - effect->ups->setRotation(getRotation()); - setMeshPosInParticleSystem(effect->ups); - } - - //printf("i = %d particleValid = %d\n",i,particleValid); - } - //printf("i = %d effect = %p effect->ups = %p\n",i,effect,(effect ? effect->ups : NULL)); - } - - - if(currentAttackBoostOriginatorEffect.currentAppliedEffect != NULL) { - if(currentAttackBoostOriginatorEffect.currentAppliedEffect->ups != NULL) { - bool particleValid = Renderer::getInstance().validateParticleSystemStillExists(currentAttackBoostOriginatorEffect.currentAppliedEffect->ups,rsGame); - if(particleValid == true) { - currentAttackBoostOriginatorEffect.currentAppliedEffect->ups->setPos(getCurrVectorForParticlesystems()); - currentAttackBoostOriginatorEffect.currentAppliedEffect->ups->setRotation(getRotation()); - setMeshPosInParticleSystem(currentAttackBoostOriginatorEffect.currentAppliedEffect->ups); - } - } - } - - //checks - if(this->animProgress > ANIMATION_SPEED_MULTIPLIER) { - bool canCycle = currSkill->CanCycleNextRandomAnimation(&animationRandomCycleCount); - this->animProgress = currSkill->getClass() == scDie ? ANIMATION_SPEED_MULTIPLIER : 0; - if(canCycle == true) { - this->lastModelIndexForCurrSkillType = -1; - } - } - - bool return_value = false; - //checks - if(progress >= PROGRESS_SPEED_MULTIPLIER) { - lastRotation= targetRotation; - if(currSkill->getClass() != scDie) { - progress = 0; - return_value = true; - } - else { - progress= PROGRESS_SPEED_MULTIPLIER; - deadCount++; - if(deadCount >= maxDeadCount) { - toBeUndertaken= true; - return_value = false; - } - } - } - - updateAttackBoostProgress(game); - - if(return_value) { - changedActiveCommand = false; - } - - return return_value; + assert(progress <= PROGRESS_SPEED_MULTIPLIER); + + // highlight + if (highlight > 0.f) { + const Game *game = Renderer::getInstance().getGame(); + highlight -= 1.f / (Game::highlightTime * game->getWorld()->getUpdateFps( + this->getFactionIndex())); + } + + if (currSkill == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: currSkill == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + // speed + int speed = currSkill->getTotalSpeed(&totalUpgrade); + + if (oldTotalSight != getType()->getTotalSight(this->getTotalUpgrade())) { + oldTotalSight = getType()->getTotalSight(this->getTotalUpgrade()); + // refresh FogOfWar and so on, because sight ha changed since last update + refreshPos(true); + } + + if (changedActiveCommand) { + if (changedActiveCommandFrame - lastChangedActiveCommandFrame >= + MIN_FRAMECOUNT_CHANGE_COMMAND_SPEED) { + // printf("Line: %d speed = %d changedActiveCommandFrame [%u] + // lastChangedActiveCommandFrame [%u] skill [%s] command + // [%s]\n",__LINE__,speed,changedActiveCommandFrame,lastChangedActiveCommandFrame,currSkill->toString(false).c_str(),getCurrCommand()->toString(false).c_str()); + // printf("Line: %d speed = %d changedActiveCommandFrame [%u] + // lastChangedActiveCommandFrame [%u] total = + // %u\n",__LINE__,speed,changedActiveCommandFrame,lastChangedActiveCommandFrame,(changedActiveCommandFrame + // - lastChangedActiveCommandFrame)); + speed = CHANGE_COMMAND_SPEED; + } + } + + // speed modifier + int64 diagonalFactor = getDiagonalFactor(); + int64 heightFactor = getHeightFactor(PROGRESS_SPEED_MULTIPLIER); + + // update progresses + this->lastAnimProgress = this->animProgress; + const Game *game = Renderer::getInstance().getGame(); + + if (animProgress == 0) { + AnimCycleStarts(); + } + progress = getUpdatedProgress(progress, GameConstants::updateFps, speed, + diagonalFactor, heightFactor); + + // printf("Test progress = %d for unit [%d - + // %s]\n",progress,id,getType()->getName().c_str()); + + if (isAnimProgressBound() == true) { + float targetProgress = 0; + if (currSkill->getClass() == scBeBuilt) { + targetProgress = this->getHpRatio(); + } + if (currSkill->getClass() == scProduce) { + targetProgress = this->getProgressRatio(); + } + if (currSkill->getClass() == scUpgrade) { + targetProgress = this->getProgressRatio(); + } + if (currSkill->getClass() == scMorph) { + targetProgress = this->getProgressRatio(); + } + + float targetProgressIntValue = targetProgress * ANIMATION_SPEED_MULTIPLIER; + if (this->animProgress < targetProgressIntValue) { + float diff = targetProgressIntValue - this->animProgress; + float progressIncrease = + static_cast(this->animProgress) + + diff / static_cast(GameConstants::updateFps); + // Ensure we increment at least a value of 1 of the action will be stuck + // infinitely + if (diff > 0.f && GameConstants::updateFps > 0 && + progressIncrease == 0.f) { + progressIncrease = 1.f; + } + + // if(currSkill->getClass() == scBeBuilt) { + // printf("targetProgress: %.10f this->animProgress: %d diff: %.10f + // GameConstants::updateFps: %d progressIncrease: + //%.10f\n",targetProgress,this->animProgress,diff,GameConstants::updateFps,progressIncrease); + // } + + this->animProgress = progressIncrease; + + // if(currSkill->getClass() == scBeBuilt) { + // printf("Unit build progress: %d anim: + //%d\n",progress,this->animProgress); + // } + } + } else { + int64 heightFactor = getHeightFactor(ANIMATION_SPEED_MULTIPLIER); + int64 speedDenominator = + speedDivider * game->getWorld()->getUpdateFps(this->getFactionIndex()); + + // Override the animation speed for attacks that have upgraded the attack + // speed + int animSpeed = currSkill->getAnimSpeed(); + if (currSkill->getClass() == scAttack) { + int animSpeedBoost = + ((AttackSkillType *)currSkill)->getAnimSpeedBoost(&totalUpgrade); + animSpeed += animSpeedBoost; + } + + int64 progressIncrease = (animSpeed * heightFactor) / speedDenominator; + // Ensure we increment at least a value of 1 of the action will be stuck + // infinitely + if (currSkill->getAnimSpeed() > 0 && heightFactor > 0 && + progressIncrease == 0) { + progressIncrease = 1; + } + this->animProgress += progressIncrease; + // this->animProgress += (currSkill->getAnimSpeed() * heightFactor) / + // speedDenominator; + + // if(currSkill->getClass() == scDie) { + // printf("Unit died progress: %d anim: %d\n",progress,this->animProgress); + // } + } + // update target + updateTarget(); + + // rotation + if (currSkill->getClass() != scStop) { + const int rotFactor = 2; + if (getProgressAsFloat() < 1.f / rotFactor) { + if (type->getFirstStOfClass(scMove)) { + if (abs((int)(lastRotation - targetRotation)) < 180) + rotation = lastRotation + (targetRotation - lastRotation) * + getProgressAsFloat() * rotFactor; + else { + float rotationTerm = targetRotation > lastRotation ? -360.f : +360.f; + rotation = + lastRotation + (targetRotation - lastRotation + rotationTerm) * + getProgressAsFloat() * rotFactor; + } + } + } + } + + if (type->getProperty(UnitType::pRotatedClimb)) { + calculateXZRotation(); + } else { + rotationZ = .0f; + rotationX = .0f; + } + + if (Renderer::getInstance().validateParticleSystemStillExists( + this->fire, rsGame) == false) { + this->fire = NULL; + } + + if (this->fire != NULL) { + this->fire->setPos(getCurrBurnVector()); + } + for (UnitParticleSystems::iterator it = unitParticleSystems.begin(); + it != unitParticleSystems.end(); ++it) { + if (Renderer::getInstance().validateParticleSystemStillExists( + (*it), rsGame) == true) { + (*it)->setPos(getCurrVectorForParticlesystems()); + (*it)->setRotation(getRotation()); + setMeshPosInParticleSystem(*it); + } + } + for (UnitParticleSystems::iterator it = damageParticleSystems.begin(); + it != damageParticleSystems.end(); ++it) { + if (Renderer::getInstance().validateParticleSystemStillExists( + (*it), rsGame) == true) { + (*it)->setPos(getCurrVectorForParticlesystems()); + (*it)->setRotation(getRotation()); + setMeshPosInParticleSystem(*it); + } + } + + for (UnitParticleSystems::iterator it = smokeParticleSystems.begin(); + it != smokeParticleSystems.end(); ++it) { + if (Renderer::getInstance().validateParticleSystemStillExists( + (*it), rsGame) == true) { + (*it)->setPos(getCurrMidHeightVector()); + (*it)->setRotation(getRotation()); + setMeshPosInParticleSystem(*it); + } + } + + // printf("Unit has attack boost? unit = [%d - %s] size = %d\n",this->getId(), + // this->getType()->getName(false).c_str(),(int)currentAttackBoostEffects.size()); + for (unsigned int i = 0; i < currentAttackBoostEffects.size(); ++i) { + UnitAttackBoostEffect *effect = currentAttackBoostEffects[i]; + if (effect != NULL && effect->ups != NULL) { + bool particleValid = + Renderer::getInstance().validateParticleSystemStillExists(effect->ups, + rsGame); + if (particleValid == true) { + effect->ups->setPos(getCurrVectorForParticlesystems()); + effect->ups->setRotation(getRotation()); + setMeshPosInParticleSystem(effect->ups); + } + + // printf("i = %d particleValid = %d\n",i,particleValid); + } + // printf("i = %d effect = %p effect->ups = %p\n",i,effect,(effect ? + // effect->ups : NULL)); + } + + if (currentAttackBoostOriginatorEffect.currentAppliedEffect != NULL) { + if (currentAttackBoostOriginatorEffect.currentAppliedEffect->ups != NULL) { + bool particleValid = + Renderer::getInstance().validateParticleSystemStillExists( + currentAttackBoostOriginatorEffect.currentAppliedEffect->ups, + rsGame); + if (particleValid == true) { + currentAttackBoostOriginatorEffect.currentAppliedEffect->ups->setPos( + getCurrVectorForParticlesystems()); + currentAttackBoostOriginatorEffect.currentAppliedEffect->ups + ->setRotation(getRotation()); + setMeshPosInParticleSystem( + currentAttackBoostOriginatorEffect.currentAppliedEffect->ups); + } + } + } + + // checks + if (this->animProgress > ANIMATION_SPEED_MULTIPLIER) { + bool canCycle = + currSkill->CanCycleNextRandomAnimation(&animationRandomCycleCount); + this->animProgress = + currSkill->getClass() == scDie ? ANIMATION_SPEED_MULTIPLIER : 0; + if (canCycle == true) { + this->lastModelIndexForCurrSkillType = -1; + } + } + + bool return_value = false; + // checks + if (progress >= PROGRESS_SPEED_MULTIPLIER) { + lastRotation = targetRotation; + if (currSkill->getClass() != scDie) { + progress = 0; + return_value = true; + } else { + progress = PROGRESS_SPEED_MULTIPLIER; + deadCount++; + if (deadCount >= maxDeadCount) { + toBeUndertaken = true; + return_value = false; + } + } + } + + updateAttackBoostProgress(game); + + if (return_value) { + changedActiveCommand = false; + } + + return return_value; } void Unit::updateTimedParticles() { - //!!! - // Start new particle systems based on start time - if(queuedUnitParticleSystemTypes.empty() == false) { - for(int i = (int)queuedUnitParticleSystemTypes.size() - 1; i >= 0; i--) { - UnitParticleSystemType *pst = queuedUnitParticleSystemTypes[i]; - if(pst != NULL) { - if(truncateDecimal(pst->getStartTime(),6) <= truncateDecimal(getAnimProgressAsFloat(),6)) { - - UnitParticleSystem *ups = new UnitParticleSystem(200); - ups->setParticleOwner(this); - ups->setParticleType(pst); - - pst->setValues(ups); - ups->setPos(getCurrVectorForParticlesystems()); - ups->setRotation(getRotation()); - setMeshPosInParticleSystem(ups); - - if(getFaction()->getTexture()) { - ups->setFactionColor(getFaction()->getTexture()->getPixmapConst()->getPixel3f(0,0)); - } - unitParticleSystems.push_back(ups); - Renderer::getInstance().manageParticleSystem(ups, rsGame); - - queuedUnitParticleSystemTypes.erase(queuedUnitParticleSystemTypes.begin() + i); - } - } - else { - queuedUnitParticleSystemTypes.erase(queuedUnitParticleSystemTypes.begin() + i); - } - } - } - - // End existing systems based on end time - if(unitParticleSystems.empty() == false) { - for(int i = (int)unitParticleSystems.size() - 1; i >= 0; i--) { - UnitParticleSystem *ps = unitParticleSystems[i]; - if(ps != NULL) { - if(Renderer::getInstance().validateParticleSystemStillExists(ps,rsGame) == true) { - float pst = ps->getStartTime(); - float pet = ps->getEndTime(); - float particleStartTime = truncateDecimal(pst,6); - float particleEndTime = truncateDecimal(pet,6); - - if(particleStartTime != 0.0 || particleEndTime != 1.0) { - float animProgressTime = truncateDecimal(getAnimProgressAsFloat(),6); - if(animProgressTime >= 0.99 || animProgressTime >= particleEndTime) { - - ps->fade(); - unitParticleSystems.erase(unitParticleSystems.begin() + i); - } - } - } - } - } - } + //!!! + // Start new particle systems based on start time + if (queuedUnitParticleSystemTypes.empty() == false) { + for (int i = (int)queuedUnitParticleSystemTypes.size() - 1; i >= 0; i--) { + UnitParticleSystemType *pst = queuedUnitParticleSystemTypes[i]; + if (pst != NULL) { + if (truncateDecimal(pst->getStartTime(), 6) <= + truncateDecimal(getAnimProgressAsFloat(), 6)) { + + UnitParticleSystem *ups = new UnitParticleSystem(200); + ups->setParticleOwner(this); + ups->setParticleType(pst); + + pst->setValues(ups); + ups->setPos(getCurrVectorForParticlesystems()); + ups->setRotation(getRotation()); + setMeshPosInParticleSystem(ups); + + if (getFaction()->getTexture()) { + ups->setFactionColor( + getFaction()->getTexture()->getPixmapConst()->getPixel3f(0, 0)); + } + unitParticleSystems.push_back(ups); + Renderer::getInstance().manageParticleSystem(ups, rsGame); + + queuedUnitParticleSystemTypes.erase( + queuedUnitParticleSystemTypes.begin() + i); + } + } else { + queuedUnitParticleSystemTypes.erase( + queuedUnitParticleSystemTypes.begin() + i); + } + } + } + + // End existing systems based on end time + if (unitParticleSystems.empty() == false) { + for (int i = (int)unitParticleSystems.size() - 1; i >= 0; i--) { + UnitParticleSystem *ps = unitParticleSystems[i]; + if (ps != NULL) { + if (Renderer::getInstance().validateParticleSystemStillExists( + ps, rsGame) == true) { + float pst = ps->getStartTime(); + float pet = ps->getEndTime(); + float particleStartTime = truncateDecimal(pst, 6); + float particleEndTime = truncateDecimal(pet, 6); + + if (particleStartTime != 0.0 || particleEndTime != 1.0) { + float animProgressTime = + truncateDecimal(getAnimProgressAsFloat(), 6); + if (animProgressTime >= 0.99 || + animProgressTime >= particleEndTime) { + + ps->fade(); + unitParticleSystems.erase(unitParticleSystems.begin() + i); + } + } + } + } + } + } } bool Unit::unitHasAttackBoost(const AttackBoost *boost, const Unit *source) { - bool result = false; - for(unsigned int i = 0; i < currentAttackBoostEffects.size(); ++i) { - UnitAttackBoostEffect *effect = currentAttackBoostEffects[i]; - if( effect != NULL && effect->boost->name == boost->name && - effect->getSource()->getType()->getId() == source->getType()->getId()) { - result = true; - break; - } - } + bool result = false; + for (unsigned int i = 0; i < currentAttackBoostEffects.size(); ++i) { + UnitAttackBoostEffect *effect = currentAttackBoostEffects[i]; + if (effect != NULL && effect->boost->name == boost->name && + effect->getSource()->getType()->getId() == source->getType()->getId()) { + result = true; + break; + } + } - //printf("Unit has attack boost? source = [%d - %s] [%p] boost [%s] result = %d\n",source->getId(), source->getType()->getName(false).c_str(),source,boost->name.c_str(),result); + // printf("Unit has attack boost? source = [%d - %s] [%p] boost [%s] result = + // %d\n",source->getId(), + // source->getType()->getName(false).c_str(),source,boost->name.c_str(),result); - return result; + return result; } bool Unit::applyAttackBoost(const AttackBoost *boost, const Unit *source) { - if(boost == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: boost == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - //printf("APPLYING ATTACK BOOST to unit [%s - %d] from unit [%s - %d]\n",this->getType()->getName().c_str(),this->getId(),source->getType()->getName().c_str(),source->getId()); - - bool shouldApplyAttackBoost = true; - if(boost->allowMultipleBoosts == false) { - // Check if we already have this boost from this unit type and multiples - // are not allowed - bool alreadyHasAttackBoost = this->unitHasAttackBoost(boost, source); - if(alreadyHasAttackBoost == true) { - shouldApplyAttackBoost = false; - } - } - - if(shouldApplyAttackBoost == true) { - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("=== APPLYING ATTACK BOOST START to unit [%s - %d] from unit [%s - %d] hp: %d\n",this->getType()->getName(false).c_str(),this->getId(),source->getType()->getName(false).c_str(),source->getId(),hp); - - UnitAttackBoostEffect *effect = new UnitAttackBoostEffect(); - effect->boost = boost; - effect->setSource(source); - - bool wasAlive = alive; - int originalHp = hp; - int prevMaxHp = totalUpgrade.getMaxHp(); - int prevMaxHpRegen = totalUpgrade.getMaxHpRegeneration(); - //printf("#1 wasAlive = %d hp = %d boosthp = %d\n",wasAlive,hp,boost->boostUpgrade.getMaxHp()); - - totalUpgrade.apply(source->getId(),&boost->boostUpgrade, this); - - checkItemInVault(&this->hp,this->hp); - //hp += boost->boostUpgrade.getMaxHp(); - int original_hp = this->hp; - this->hp += (totalUpgrade.getMaxHp() - prevMaxHp); - if(original_hp != this->hp) { - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - game->getScriptManager()->onUnitTriggerEvent(this,utet_HPChanged); - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } - addItemToVault(&this->hp,this->hp); - - //regenerate hp upgrade / or boost - if(totalUpgrade.getMaxHpRegeneration() != 0) { - checkItemInVault(&this->hp,this->hp); - - //printf("BEFORE Apply Hp Regen max = %d, prev = %d, hp = %d\n",totalUpgrade.getMaxHpRegeneration(),prevMaxHpRegen,hp); - int original_hp = this->hp; - this->hp += (totalUpgrade.getMaxHpRegeneration() - prevMaxHpRegen); - if(original_hp != this->hp) { - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - game->getScriptManager()->onUnitTriggerEvent(this,utet_HPChanged); - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } - //if(hp > type->getTotalMaxHp(&totalUpgrade)) { - // hp = type->getTotalMaxHp(&totalUpgrade); - //} - addItemToVault(&this->hp,this->hp); - - //printf("AFTER Apply Hp Regen max = %d, prev = %d, hp = %d\n",totalUpgrade.getMaxHpRegeneration(),prevMaxHpRegen,hp); - } - - checkModelStateInfoForNewHpValue(); - - if(originalHp < hp) { - this->setLastAttackerUnitId(source->getId()); - } - //printf("#2 wasAlive = %d hp = %d boosthp = %d\n",wasAlive,hp,boost->boostUpgrade.getMaxHp()); - - if(showUnitParticles == true) { - if(boost->unitParticleSystemTypeForAffectedUnit != NULL) { - effect->upst = new UnitParticleSystemType(); - *effect->upst = *boost->unitParticleSystemTypeForAffectedUnit; - //effect.upst = boost->unitParticleSystemTypeForAffectedUnit; - - effect->ups = new UnitParticleSystem(200); - effect->ups->setParticleOwner(this); - effect->ups->setParticleType(effect->upst); - - effect->upst->setValues(effect->ups); - effect->ups->setPos(getCurrVectorForParticlesystems()); - effect->ups->setRotation(getRotation()); - setMeshPosInParticleSystem(effect->ups); - if(getFaction()->getTexture()) { - effect->ups->setFactionColor(getFaction()->getTexture()->getPixmapConst()->getPixel3f(0,0)); - } - Renderer::getInstance().manageParticleSystem(effect->ups, rsGame); - } - } - currentAttackBoostEffects.push_back(effect); - - if(wasAlive == true) { - //startDamageParticles - - if(originalHp > this->hp) { - startDamageParticles(); - } - - //stop DamageParticles on death - if(this->hp <= 0) { - setAlive(false); - this->hp=0; - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - game->getScriptManager()->onUnitTriggerEvent(this,utet_HPChanged); - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - addItemToVault(&this->hp,this->hp); - checkModelStateInfoForNewHpValue(); - - stopDamageParticles(true); - - this->setLastAttackerUnitId(source->getId()); - this->setCauseOfDeath(ucodAttackBoost); - Unit::game->getWorld()->getStats()->die(getFactionIndex(),getType()->getCountUnitDeathInStats()); - game->getScriptManager()->onUnitDied(this); - - StaticSound *sound= static_cast(this->getType()->getFirstStOfClass(scDie))->getSound(); - if(sound != NULL && - (this->getFactionIndex() == Unit::game->getWorld()->getThisFactionIndex() || - (game->getWorld()->showWorldForPlayer(game->getWorld()->getThisTeamIndex()) == true))) { - SoundRenderer::getInstance().playFx(sound); - } - - if(this->isDead() && this->getCurrSkill()->getClass() != scDie) { - this->kill(); - } - } - } - - //printf("APPLYING ATTACK BOOST END to unit [%s - %d] from unit [%s - %d]\n",this->getType()->getName().c_str(),this->getId(),source->getType()->getName().c_str(),source->getId()); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("APPLIED ATTACK BOOST START to unit [%s - %d] from unit [%s - %d] hp: %d\n",this->getType()->getName(false).c_str(),this->getId(),source->getType()->getName(false).c_str(),source->getId(),hp); - - return shouldApplyAttackBoost; + if (boost == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: boost == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + // printf("APPLYING ATTACK BOOST to unit [%s - %d] from unit [%s - + // %d]\n",this->getType()->getName().c_str(),this->getId(),source->getType()->getName().c_str(),source->getId()); + + bool shouldApplyAttackBoost = true; + if (boost->allowMultipleBoosts == false) { + // Check if we already have this boost from this unit type and multiples + // are not allowed + bool alreadyHasAttackBoost = this->unitHasAttackBoost(boost, source); + if (alreadyHasAttackBoost == true) { + shouldApplyAttackBoost = false; + } + } + + if (shouldApplyAttackBoost == true) { + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("=== APPLYING ATTACK BOOST START to unit [%s - %d] from unit [%s " + "- %d] hp: %d\n", + this->getType()->getName(false).c_str(), this->getId(), + source->getType()->getName(false).c_str(), source->getId(), hp); + + UnitAttackBoostEffect *effect = new UnitAttackBoostEffect(); + effect->boost = boost; + effect->setSource(source); + + bool wasAlive = alive; + int originalHp = hp; + int prevMaxHp = totalUpgrade.getMaxHp(); + int prevMaxHpRegen = totalUpgrade.getMaxHpRegeneration(); + // printf("#1 wasAlive = %d hp = %d boosthp = + // %d\n",wasAlive,hp,boost->boostUpgrade.getMaxHp()); + + totalUpgrade.apply(source->getId(), &boost->boostUpgrade, this); + + checkItemInVault(&this->hp, this->hp); + // hp += boost->boostUpgrade.getMaxHp(); + int original_hp = this->hp; + this->hp += (totalUpgrade.getMaxHp() - prevMaxHp); + if (original_hp != this->hp) { + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + game->getScriptManager()->onUnitTriggerEvent(this, utet_HPChanged); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + } + addItemToVault(&this->hp, this->hp); + + // regenerate hp upgrade / or boost + if (totalUpgrade.getMaxHpRegeneration() != 0) { + checkItemInVault(&this->hp, this->hp); + + // printf("BEFORE Apply Hp Regen max = %d, prev = %d, hp = + // %d\n",totalUpgrade.getMaxHpRegeneration(),prevMaxHpRegen,hp); + int original_hp = this->hp; + this->hp += (totalUpgrade.getMaxHpRegeneration() - prevMaxHpRegen); + if (original_hp != this->hp) { + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + game->getScriptManager()->onUnitTriggerEvent(this, utet_HPChanged); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + } + // if(hp > type->getTotalMaxHp(&totalUpgrade)) { + // hp = type->getTotalMaxHp(&totalUpgrade); + // } + addItemToVault(&this->hp, this->hp); + + // printf("AFTER Apply Hp Regen max = %d, prev = %d, hp = + // %d\n",totalUpgrade.getMaxHpRegeneration(),prevMaxHpRegen,hp); + } + + checkModelStateInfoForNewHpValue(); + + if (originalHp < hp) { + this->setLastAttackerUnitId(source->getId()); + } + // printf("#2 wasAlive = %d hp = %d boosthp = + // %d\n",wasAlive,hp,boost->boostUpgrade.getMaxHp()); + + if (showUnitParticles == true) { + if (boost->unitParticleSystemTypeForAffectedUnit != NULL) { + effect->upst = new UnitParticleSystemType(); + *effect->upst = *boost->unitParticleSystemTypeForAffectedUnit; + // effect.upst = boost->unitParticleSystemTypeForAffectedUnit; + + effect->ups = new UnitParticleSystem(200); + effect->ups->setParticleOwner(this); + effect->ups->setParticleType(effect->upst); + + effect->upst->setValues(effect->ups); + effect->ups->setPos(getCurrVectorForParticlesystems()); + effect->ups->setRotation(getRotation()); + setMeshPosInParticleSystem(effect->ups); + if (getFaction()->getTexture()) { + effect->ups->setFactionColor( + getFaction()->getTexture()->getPixmapConst()->getPixel3f(0, 0)); + } + Renderer::getInstance().manageParticleSystem(effect->ups, rsGame); + } + } + currentAttackBoostEffects.push_back(effect); + + if (wasAlive == true) { + // startDamageParticles + + if (originalHp > this->hp) { + startDamageParticles(); + } + + // stop DamageParticles on death + if (this->hp <= 0) { + setAlive(false); + this->hp = 0; + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + game->getScriptManager()->onUnitTriggerEvent(this, utet_HPChanged); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + addItemToVault(&this->hp, this->hp); + checkModelStateInfoForNewHpValue(); + + stopDamageParticles(true); + + this->setLastAttackerUnitId(source->getId()); + this->setCauseOfDeath(ucodAttackBoost); + Unit::game->getWorld()->getStats()->die( + getFactionIndex(), getType()->getCountUnitDeathInStats()); + game->getScriptManager()->onUnitDied(this); + + StaticSound *sound = static_cast( + this->getType()->getFirstStOfClass(scDie)) + ->getSound(); + if (sound != NULL && + (this->getFactionIndex() == + Unit::game->getWorld()->getThisFactionIndex() || + (game->getWorld()->showWorldForPlayer( + game->getWorld()->getThisTeamIndex()) == true))) { + SoundRenderer::getInstance().playFx(sound); + } + + if (this->isDead() && this->getCurrSkill()->getClass() != scDie) { + this->kill(); + } + } + } + + // printf("APPLYING ATTACK BOOST END to unit [%s - %d] from unit [%s - + // %d]\n",this->getType()->getName().c_str(),this->getId(),source->getType()->getName().c_str(),source->getId()); + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("APPLIED ATTACK BOOST START to unit [%s - %d] from unit [%s - %d] " + "hp: %d\n", + this->getType()->getName(false).c_str(), this->getId(), + source->getType()->getName(false).c_str(), source->getId(), hp); + + return shouldApplyAttackBoost; } void Unit::deapplyAttackBoost(const AttackBoost *boost, const Unit *source) { - if(boost == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: boost == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("=== DE-APPLYING ATTACK BOOST START to unit [%s - %d] from unit [%s - %d] hp: %d\n",this->getType()->getName(false).c_str(),this->getId(),source->getType()->getName(false).c_str(),source->getId(),hp); - - bool wasAlive = alive; - int originalHp = hp; - int prevMaxHp = totalUpgrade.getMaxHp(); - int prevMaxHpRegen = totalUpgrade.getMaxHpRegeneration(); - totalUpgrade.deapply(source->getId(),&boost->boostUpgrade, this->getId()); - - checkItemInVault(&this->hp,this->hp); - int original_hp = this->hp; - //hp -= boost->boostUpgrade.getMaxHp(); - this->hp -= (prevMaxHp - totalUpgrade.getMaxHp()); - if(original_hp != this->hp) { - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - game->getScriptManager()->onUnitTriggerEvent(this,utet_HPChanged); - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } - addItemToVault(&this->hp,this->hp); - - //regenerate hp upgrade / or boost - if(totalUpgrade.getMaxHpRegeneration() != 0) { - checkItemInVault(&this->hp,this->hp); - - //printf("BEFORE DeApply Hp Regen max = %d, prev = %d, hp = %d\n",totalUpgrade.getMaxHpRegeneration(),prevMaxHpRegen,hp); - int original_hp = this->hp; - this->hp -= (totalUpgrade.getMaxHpRegeneration() - prevMaxHpRegen); - if(original_hp != this->hp) { - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - game->getScriptManager()->onUnitTriggerEvent(this,utet_HPChanged); - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } - //if(hp > totalUpgrade.getMaxHp()) { - // hp = totalUpgrade.getMaxHp(); - //} - addItemToVault(&this->hp,this->hp); - - //printf("AFTER DeApply Hp Regen max = %d, prev = %d, hp = %d\n",totalUpgrade.getMaxHpRegeneration(),prevMaxHpRegen,hp); - } - - if(originalHp < hp) { - this->setLastAttackerUnitId(source->getId()); - } - - if(wasAlive == true) { - //printf("DE-APPLYING ATTACK BOOST wasalive = true to unit [%s - %d] from unit [%s - %d]\n",this->getType()->getName().c_str(),this->getId(),source->getType()->getName().c_str(),source->getId()); - - //startDamageParticles - if(originalHp > this->hp) { - startDamageParticles(); - } - - //stop DamageParticles on death - if(this->hp <= 0) { - setAlive(false); - this->hp=0; - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - game->getScriptManager()->onUnitTriggerEvent(this,utet_HPChanged); - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - addItemToVault(&this->hp,this->hp); - - checkModelStateInfoForNewHpValue(); - - stopDamageParticles(true); - - this->setLastAttackerUnitId(source->getId()); - this->setCauseOfDeath(ucodAttackBoost); - - Unit::game->getWorld()->getStats()->die(getFactionIndex(),getType()->getCountUnitDeathInStats()); - game->getScriptManager()->onUnitDied(this); - - StaticSound *sound= static_cast(this->getType()->getFirstStOfClass(scDie))->getSound(); - if(sound != NULL && - (this->getFactionIndex() == Unit::game->getWorld()->getThisFactionIndex() || - (game->getWorld()->showWorldForPlayer(game->getWorld()->getThisTeamIndex()) == true))) { - SoundRenderer::getInstance().playFx(sound); - } - - if(this->isDead() && this->getCurrSkill()->getClass() != scDie) { - this->kill(); - } - } - } - - checkModelStateInfoForNewHpValue(); - - //printf("DE-APPLYING ATTACK BOOST BEFORE END to unit [%s - %d] from unit [%s - %d]\n",this->getType()->getName().c_str(),this->getId(),source->getType()->getName().c_str(),source->getId()); - - for(unsigned int i = 0; i < currentAttackBoostEffects.size(); ++i) { - UnitAttackBoostEffect *effect = currentAttackBoostEffects[i]; - if(effect != NULL && effect->boost == boost && effect->getSource() == source) { - delete effect; - currentAttackBoostEffects.erase(currentAttackBoostEffects.begin() + i); - break; - } - } - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("DE-APPLIED ATTACK BOOST START to unit [%s - %d] from unit [%s - %d] hp: %d\n",this->getType()->getName(false).c_str(),this->getId(),source->getType()->getName(false).c_str(),source->getId(),hp); - - //printf("DE-APPLYING ATTACK BOOST END to unit [%s - %d] from unit [%s - %d]\n",this->getType()->getName().c_str(),this->getId(),source->getType()->getName().c_str(),source->getId()); + if (boost == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: boost == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("=== DE-APPLYING ATTACK BOOST START to unit [%s - %d] from unit [%s " + "- %d] hp: %d\n", + this->getType()->getName(false).c_str(), this->getId(), + source->getType()->getName(false).c_str(), source->getId(), hp); + + bool wasAlive = alive; + int originalHp = hp; + int prevMaxHp = totalUpgrade.getMaxHp(); + int prevMaxHpRegen = totalUpgrade.getMaxHpRegeneration(); + totalUpgrade.deapply(source->getId(), &boost->boostUpgrade, this->getId()); + + checkItemInVault(&this->hp, this->hp); + int original_hp = this->hp; + // hp -= boost->boostUpgrade.getMaxHp(); + this->hp -= (prevMaxHp - totalUpgrade.getMaxHp()); + if (original_hp != this->hp) { + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + game->getScriptManager()->onUnitTriggerEvent(this, utet_HPChanged); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + } + addItemToVault(&this->hp, this->hp); + + // regenerate hp upgrade / or boost + if (totalUpgrade.getMaxHpRegeneration() != 0) { + checkItemInVault(&this->hp, this->hp); + + // printf("BEFORE DeApply Hp Regen max = %d, prev = %d, hp = + // %d\n",totalUpgrade.getMaxHpRegeneration(),prevMaxHpRegen,hp); + int original_hp = this->hp; + this->hp -= (totalUpgrade.getMaxHpRegeneration() - prevMaxHpRegen); + if (original_hp != this->hp) { + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + game->getScriptManager()->onUnitTriggerEvent(this, utet_HPChanged); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + } + // if(hp > totalUpgrade.getMaxHp()) { + // hp = totalUpgrade.getMaxHp(); + // } + addItemToVault(&this->hp, this->hp); + + // printf("AFTER DeApply Hp Regen max = %d, prev = %d, hp = + // %d\n",totalUpgrade.getMaxHpRegeneration(),prevMaxHpRegen,hp); + } + + if (originalHp < hp) { + this->setLastAttackerUnitId(source->getId()); + } + + if (wasAlive == true) { + // printf("DE-APPLYING ATTACK BOOST wasalive = true to unit [%s - %d] from + // unit [%s - + // %d]\n",this->getType()->getName().c_str(),this->getId(),source->getType()->getName().c_str(),source->getId()); + + // startDamageParticles + if (originalHp > this->hp) { + startDamageParticles(); + } + + // stop DamageParticles on death + if (this->hp <= 0) { + setAlive(false); + this->hp = 0; + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + game->getScriptManager()->onUnitTriggerEvent(this, utet_HPChanged); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + addItemToVault(&this->hp, this->hp); + + checkModelStateInfoForNewHpValue(); + + stopDamageParticles(true); + + this->setLastAttackerUnitId(source->getId()); + this->setCauseOfDeath(ucodAttackBoost); + + Unit::game->getWorld()->getStats()->die( + getFactionIndex(), getType()->getCountUnitDeathInStats()); + game->getScriptManager()->onUnitDied(this); + + StaticSound *sound = static_cast( + this->getType()->getFirstStOfClass(scDie)) + ->getSound(); + if (sound != NULL && + (this->getFactionIndex() == + Unit::game->getWorld()->getThisFactionIndex() || + (game->getWorld()->showWorldForPlayer( + game->getWorld()->getThisTeamIndex()) == true))) { + SoundRenderer::getInstance().playFx(sound); + } + + if (this->isDead() && this->getCurrSkill()->getClass() != scDie) { + this->kill(); + } + } + } + + checkModelStateInfoForNewHpValue(); + + // printf("DE-APPLYING ATTACK BOOST BEFORE END to unit [%s - %d] from unit [%s + // - + // %d]\n",this->getType()->getName().c_str(),this->getId(),source->getType()->getName().c_str(),source->getId()); + + for (unsigned int i = 0; i < currentAttackBoostEffects.size(); ++i) { + UnitAttackBoostEffect *effect = currentAttackBoostEffects[i]; + if (effect != NULL && effect->boost == boost && + effect->getSource() == source) { + delete effect; + currentAttackBoostEffects.erase(currentAttackBoostEffects.begin() + i); + break; + } + } + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("DE-APPLIED ATTACK BOOST START to unit [%s - %d] from unit [%s - " + "%d] hp: %d\n", + this->getType()->getName(false).c_str(), this->getId(), + source->getType()->getName(false).c_str(), source->getId(), hp); + + // printf("DE-APPLYING ATTACK BOOST END to unit [%s - %d] from unit [%s - + // %d]\n",this->getType()->getName().c_str(),this->getId(),source->getType()->getName().c_str(),source->getId()); } void Unit::tick() { - if(isAlive()) { - if(type == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - //if(this->getType()->getName() == "spearman") printf("Unit [%d - %s] start tick hp = %d\n",this->getId(),this->getType()->getName().c_str(),hp); - - - //regenerate hp upgrade / or boost - if(type->getTotalMaxHpRegeneration(&totalUpgrade) != 0) { - if( currSkill->getClass() != scBeBuilt){ - if(type->getTotalMaxHpRegeneration(&totalUpgrade) >= 0) { - checkItemInVault(&this->hp,this->hp); - int original_hp = this->hp; - this->hp += type->getTotalMaxHpRegeneration(&totalUpgrade); - if(this->hp > type->getTotalMaxHp(&totalUpgrade)) { - this->hp = type->getTotalMaxHp(&totalUpgrade); - } - if(original_hp != this->hp) { - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - game->getScriptManager()->onUnitTriggerEvent(this,utet_HPChanged); - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } - addItemToVault(&this->hp,this->hp); - - checkModelStateInfoForNewHpValue(); - //if(this->getType()->getName() == "spearman") printf("tick hp#2 [type->getTotalMaxHpRegeneration(&totalUpgrade)] = %d type->getTotalMaxHp(&totalUpgrade) [%d] newhp = %d\n",type->getTotalMaxHpRegeneration(&totalUpgrade),type->getTotalMaxHp(&totalUpgrade),hp); - } - // If we have negative regeneration then check if the unit should die - else { - bool decHpResult = decHp(-type->getTotalMaxHpRegeneration(&totalUpgrade)); - if(decHpResult) { - this->setCauseOfDeath(ucodStarvedRegeneration); - - Unit::game->getWorld()->getStats()->die(getFactionIndex(),getType()->getCountUnitDeathInStats()); - game->getScriptManager()->onUnitDied(this); - } - StaticSound *sound= static_cast(this->getType()->getFirstStOfClass(scDie))->getSound(); - if(sound != NULL && - (this->getFactionIndex() == Unit::game->getWorld()->getThisFactionIndex() || - (game->getWorld()->showWorldForPlayer(game->getWorld()->getThisTeamIndex()) == true))) { - SoundRenderer::getInstance().playFx(sound); - } - } - } - } - //regenerate hp - else { - if(type->getTotalMaxHpRegeneration(&totalUpgrade) >= 0) { - if( currSkill->getClass() != scBeBuilt){ - checkItemInVault(&this->hp,this->hp); - int original_hp = this->hp; - this->hp += type->getTotalMaxHpRegeneration(&totalUpgrade); - if(this->hp > type->getTotalMaxHp(&totalUpgrade)) { - this->hp = type->getTotalMaxHp(&totalUpgrade); - } - if(original_hp != this->hp) { - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - game->getScriptManager()->onUnitTriggerEvent(this,utet_HPChanged); - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } - addItemToVault(&this->hp,this->hp); - - checkModelStateInfoForNewHpValue(); - //if(this->getType()->getName() == "spearman") printf("tick hp#1 [type->getHpRegeneration()] = %d type->getTotalMaxHp(&totalUpgrade) [%d] newhp = %d\n",type->getHpRegeneration(),type->getTotalMaxHp(&totalUpgrade),hp); - } - } - // If we have negative regeneration then check if the unit should die - else { - bool decHpResult = decHp(-type->getTotalMaxHpRegeneration(&totalUpgrade)); - if(decHpResult) { - this->setCauseOfDeath(ucodStarvedRegeneration); - - Unit::game->getWorld()->getStats()->die(getFactionIndex(),getType()->getCountUnitDeathInStats()); - game->getScriptManager()->onUnitDied(this); - } - StaticSound *sound= static_cast(this->getType()->getFirstStOfClass(scDie))->getSound(); - if(sound != NULL && - (this->getFactionIndex() == Unit::game->getWorld()->getThisFactionIndex() || - (game->getWorld()->showWorldForPlayer(game->getWorld()->getThisTeamIndex()) == true))) { - SoundRenderer::getInstance().playFx(sound); - } - } - } - - //stop DamageParticles - stopDamageParticles(false); - - checkItemInVault(&this->ep,this->ep); - //regenerate ep -// ep += type->getEpRegeneration(); -// if(ep > type->getTotalMaxEp(&totalUpgrade)){ -// ep = type->getTotalMaxEp(&totalUpgrade); -// } -// addItemToVault(&this->ep,this->ep); - - if(!isBeingBuilt()){ - //regenerate ep upgrade / or boost - checkItemInVault(&this->ep,this->ep); - //regenerate ep - int original_ep = this->ep; - this->ep += type->getTotalMaxEpRegeneration(&totalUpgrade); - if(this->ep > type->getTotalMaxEp(&totalUpgrade)){ - this->ep = type->getTotalMaxEp(&totalUpgrade); - } - if(original_ep != this->ep) { - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - game->getScriptManager()->onUnitTriggerEvent(this,utet_EPChanged); - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } - addItemToVault(&this->ep,this->ep); - } - } + if (isAlive()) { + if (type == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + // if(this->getType()->getName() == "spearman") printf("Unit [%d - %s] start + // tick hp = %d\n",this->getId(),this->getType()->getName().c_str(),hp); + + // regenerate hp upgrade / or boost + if (type->getTotalMaxHpRegeneration(&totalUpgrade) != 0) { + if (currSkill->getClass() != scBeBuilt) { + if (type->getTotalMaxHpRegeneration(&totalUpgrade) >= 0) { + checkItemInVault(&this->hp, this->hp); + int original_hp = this->hp; + this->hp += type->getTotalMaxHpRegeneration(&totalUpgrade); + if (this->hp > type->getTotalMaxHp(&totalUpgrade)) { + this->hp = type->getTotalMaxHp(&totalUpgrade); + } + if (original_hp != this->hp) { + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + game->getScriptManager()->onUnitTriggerEvent(this, utet_HPChanged); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + } + addItemToVault(&this->hp, this->hp); + + checkModelStateInfoForNewHpValue(); + // if(this->getType()->getName() == "spearman") printf("tick hp#2 + // [type->getTotalMaxHpRegeneration(&totalUpgrade)] = %d + // type->getTotalMaxHp(&totalUpgrade) [%d] newhp = + // %d\n",type->getTotalMaxHpRegeneration(&totalUpgrade),type->getTotalMaxHp(&totalUpgrade),hp); + } + // If we have negative regeneration then check if the unit should die + else { + bool decHpResult = + decHp(-type->getTotalMaxHpRegeneration(&totalUpgrade)); + if (decHpResult) { + this->setCauseOfDeath(ucodStarvedRegeneration); + + Unit::game->getWorld()->getStats()->die( + getFactionIndex(), getType()->getCountUnitDeathInStats()); + game->getScriptManager()->onUnitDied(this); + } + StaticSound *sound = static_cast( + this->getType()->getFirstStOfClass(scDie)) + ->getSound(); + if (sound != NULL && + (this->getFactionIndex() == + Unit::game->getWorld()->getThisFactionIndex() || + (game->getWorld()->showWorldForPlayer( + game->getWorld()->getThisTeamIndex()) == true))) { + SoundRenderer::getInstance().playFx(sound); + } + } + } + } + // regenerate hp + else { + if (type->getTotalMaxHpRegeneration(&totalUpgrade) >= 0) { + if (currSkill->getClass() != scBeBuilt) { + checkItemInVault(&this->hp, this->hp); + int original_hp = this->hp; + this->hp += type->getTotalMaxHpRegeneration(&totalUpgrade); + if (this->hp > type->getTotalMaxHp(&totalUpgrade)) { + this->hp = type->getTotalMaxHp(&totalUpgrade); + } + if (original_hp != this->hp) { + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + game->getScriptManager()->onUnitTriggerEvent(this, utet_HPChanged); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + } + addItemToVault(&this->hp, this->hp); + + checkModelStateInfoForNewHpValue(); + // if(this->getType()->getName() == "spearman") printf("tick hp#1 + // [type->getHpRegeneration()] = %d type->getTotalMaxHp(&totalUpgrade) + // [%d] newhp = + // %d\n",type->getHpRegeneration(),type->getTotalMaxHp(&totalUpgrade),hp); + } + } + // If we have negative regeneration then check if the unit should die + else { + bool decHpResult = + decHp(-type->getTotalMaxHpRegeneration(&totalUpgrade)); + if (decHpResult) { + this->setCauseOfDeath(ucodStarvedRegeneration); + + Unit::game->getWorld()->getStats()->die( + getFactionIndex(), getType()->getCountUnitDeathInStats()); + game->getScriptManager()->onUnitDied(this); + } + StaticSound *sound = static_cast( + this->getType()->getFirstStOfClass(scDie)) + ->getSound(); + if (sound != NULL && + (this->getFactionIndex() == + Unit::game->getWorld()->getThisFactionIndex() || + (game->getWorld()->showWorldForPlayer( + game->getWorld()->getThisTeamIndex()) == true))) { + SoundRenderer::getInstance().playFx(sound); + } + } + } + + // stop DamageParticles + stopDamageParticles(false); + + checkItemInVault(&this->ep, this->ep); + // regenerate ep + // ep += type->getEpRegeneration(); + // if(ep > type->getTotalMaxEp(&totalUpgrade)){ + // ep = type->getTotalMaxEp(&totalUpgrade); + // } + // addItemToVault(&this->ep,this->ep); + + if (!isBeingBuilt()) { + // regenerate ep upgrade / or boost + checkItemInVault(&this->ep, this->ep); + // regenerate ep + int original_ep = this->ep; + this->ep += type->getTotalMaxEpRegeneration(&totalUpgrade); + if (this->ep > type->getTotalMaxEp(&totalUpgrade)) { + this->ep = type->getTotalMaxEp(&totalUpgrade); + } + if (original_ep != this->ep) { + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + game->getScriptManager()->onUnitTriggerEvent(this, utet_EPChanged); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + } + addItemToVault(&this->ep, this->ep); + } + } } int Unit::update2() { - progress2++; - return progress2; + progress2++; + return progress2; } bool Unit::computeEp() { - if(currSkill == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: currSkill == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - //if not enough ep - if(this->ep - currSkill->getEpCost() < 0) { - return true; - } - - checkItemInVault(&this->ep,this->ep); - int original_ep = this->ep; - //decrease ep - this->ep -= currSkill->getEpCost(); - if(original_ep != this->ep) { - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - game->getScriptManager()->onUnitTriggerEvent(this,utet_EPChanged); - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } - addItemToVault(&this->ep,this->ep); - - if(getType() == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: getType() == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - if(this->ep > getType()->getTotalMaxEp(&totalUpgrade)){ - int original_ep = this->ep; - this->ep = getType()->getTotalMaxEp(&totalUpgrade); - if(original_ep != this->ep) { - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - game->getScriptManager()->onUnitTriggerEvent(this,utet_EPChanged); - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } - } - addItemToVault(&this->ep,this->ep); + if (currSkill == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: currSkill == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + // if not enough ep + if (this->ep - currSkill->getEpCost() < 0) { + return true; + } + + checkItemInVault(&this->ep, this->ep); + int original_ep = this->ep; + // decrease ep + this->ep -= currSkill->getEpCost(); + if (original_ep != this->ep) { + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + game->getScriptManager()->onUnitTriggerEvent(this, utet_EPChanged); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + } + addItemToVault(&this->ep, this->ep); + + if (getType() == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: getType() == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + if (this->ep > getType()->getTotalMaxEp(&totalUpgrade)) { + int original_ep = this->ep; + this->ep = getType()->getTotalMaxEp(&totalUpgrade); + if (original_ep != this->ep) { + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + game->getScriptManager()->onUnitTriggerEvent(this, utet_EPChanged); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + } + } + addItemToVault(&this->ep, this->ep); + + return false; +} + +bool Unit::repair() { + + if (type == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + // increase hp + checkItemInVault(&this->hp, this->hp); + int original_hp = this->hp; + if (type->getProductionTime() + 1 == 0) { + throw megaglest_runtime_error( + "Detected divide by 0 condition: type->getProductionTime() + 1 == 0"); + } + this->hp += getType()->getMaxHp() / type->getProductionTime() + 1; + if (this->hp > (getType()->getTotalMaxHp(&totalUpgrade))) { + this->hp = getType()->getTotalMaxHp(&totalUpgrade); + if (original_hp != this->hp) { + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + game->getScriptManager()->onUnitTriggerEvent(this, utet_HPChanged); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + } + addItemToVault(&this->hp, this->hp); + return true; + } + if (original_hp != this->hp) { + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + game->getScriptManager()->onUnitTriggerEvent(this, utet_HPChanged); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + } + addItemToVault(&this->hp, this->hp); - return false; -} + checkModelStateInfoForNewHpValue(); -bool Unit::repair(){ - - if(type == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - //increase hp - checkItemInVault(&this->hp,this->hp); - int original_hp = this->hp; - if(type->getProductionTime() + 1 == 0) { - throw megaglest_runtime_error("Detected divide by 0 condition: type->getProductionTime() + 1 == 0"); - } - this->hp += getType()->getMaxHp() / type->getProductionTime() + 1; - if(this->hp > (getType()->getTotalMaxHp(&totalUpgrade))) { - this->hp = getType()->getTotalMaxHp(&totalUpgrade); - if(original_hp != this->hp) { - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - game->getScriptManager()->onUnitTriggerEvent(this,utet_HPChanged); - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } - addItemToVault(&this->hp,this->hp); - return true; - } - if(original_hp != this->hp) { - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - game->getScriptManager()->onUnitTriggerEvent(this,utet_HPChanged); - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } - addItemToVault(&this->hp,this->hp); - - checkModelStateInfoForNewHpValue(); - - //stop DamageParticles - stopDamageParticles(false); + // stop DamageParticles + stopDamageParticles(false); - return false; + return false; } -//decrements HP and returns if dead +// decrements HP and returns if dead bool Unit::decHp(int decrementValue) { - char szBuf[8096]=""; - snprintf(szBuf,8095,"this->hp = %d, decrementValue = %d",this->hp,decrementValue); - addNetworkCRCDecHp(szBuf); - - if(this->hp == 0) { - return false; - } - - checkItemInVault(&this->hp,this->hp); - int original_hp = this->hp; - this->hp -= decrementValue; - if(original_hp != this->hp) { - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - game->getScriptManager()->onUnitTriggerEvent(this,utet_HPChanged); - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } - addItemToVault(&this->hp,this->hp); - - checkModelStateInfoForNewHpValue(); - - if(type == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - //startDamageParticles - startDamageParticles(); - - //stop DamageParticles on death - if(this->hp <= 0) { - setAlive(false); - this->hp = 0; - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - game->getScriptManager()->onUnitTriggerEvent(this,utet_HPChanged); - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - addItemToVault(&this->hp,this->hp); - - checkModelStateInfoForNewHpValue(); - - stopDamageParticles(true); - return true; - } + char szBuf[8096] = ""; + snprintf(szBuf, 8095, "this->hp = %d, decrementValue = %d", this->hp, + decrementValue); + addNetworkCRCDecHp(szBuf); + + if (this->hp == 0) { return false; + } + + checkItemInVault(&this->hp, this->hp); + int original_hp = this->hp; + this->hp -= decrementValue; + if (original_hp != this->hp) { + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + game->getScriptManager()->onUnitTriggerEvent(this, utet_HPChanged); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + } + addItemToVault(&this->hp, this->hp); + + checkModelStateInfoForNewHpValue(); + + if (type == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: type == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + // startDamageParticles + startDamageParticles(); + + // stop DamageParticles on death + if (this->hp <= 0) { + setAlive(false); + this->hp = 0; + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + game->getScriptManager()->onUnitTriggerEvent(this, utet_HPChanged); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + addItemToVault(&this->hp, this->hp); + + checkModelStateInfoForNewHpValue(); + + stopDamageParticles(true); + return true; + } + return false; +} + +string Unit::getDescExtension(bool translatedValue) const { + Lang &lang = Lang::getInstance(); + string str = "\n"; + + if (commands.empty() == false && commands.size() > 1) { + Commands::const_iterator it = commands.begin(); + for (unsigned int i = 0; + i < min((size_t)maxQueuedCommandDisplayCount, commands.size()); ++i) { + const CommandType *ct = (*it)->getCommandType(); + if (i == 0) { + str += "\n" + lang.getString("OrdersOnQueue") + ": "; + } + str += "\n#" + intToStr(i + 1) + " " + ct->getName(translatedValue); + ++it; + } + } + + return str; } -string Unit::getDescExtension(bool translatedValue) const{ - Lang &lang= Lang::getInstance(); - string str= "\n"; +string Unit::getDesc(bool translatedValue) const { - if(commands.empty() == false && commands.size() > 1 ){ - Commands::const_iterator it= commands.begin(); - for(unsigned int i= 0; i < min((size_t) maxQueuedCommandDisplayCount, commands.size()); ++i){ - const CommandType *ct= (*it)->getCommandType(); - if(i == 0){ - str+= "\n" + lang.getString("OrdersOnQueue") + ": "; - } - str+= "\n#" + intToStr(i + 1) + " " + ct->getName(translatedValue); - ++it; - } - } + Lang &lang = Lang::getInstance(); + + // hp + string str = "\n"; + + // maxUnitCount + if (type->getMaxUnitCount() > 0) { + str += lang.getString("MaxUnitCount") + ": " + + intToStr(faction->getCountForMaxUnitCount(type)) + "/" + + intToStr(type->getMaxUnitCount()); + } + + str += "\n" + lang.getString("Hp") + ": " + intToStr(hp) + "/" + + intToStr(type->getTotalMaxHp(&totalUpgrade)); + if (type->getHpRegeneration() != 0 || + totalUpgrade.getMaxHpRegeneration() != 0) { + str += " (" + lang.getString("Regeneration") + ": " + + intToStr(type->getHpRegeneration()); + if (totalUpgrade.getMaxHpRegeneration() != 0) { + str += "+" + intToStr(totalUpgrade.getMaxHpRegeneration()); + } + str += ")"; + } + + // ep + if (getType()->getMaxEp() != 0) { + str += "\n" + lang.getString("Ep") + ": " + intToStr(ep) + "/" + + intToStr(type->getTotalMaxEp(&totalUpgrade)); + } + if (type->getEpRegeneration() != 0 || + totalUpgrade.getMaxEpRegeneration() != 0) { + str += " (" + lang.getString("Regeneration") + ": " + + intToStr(type->getEpRegeneration()); + if (totalUpgrade.getMaxEpRegeneration() != 0) { + str += "+" + intToStr(totalUpgrade.getMaxEpRegeneration()); + } + str += ")"; + } + + // armor + str += + "\n" + lang.getString("Armor") + ": " + intToStr(getType()->getArmor()); + if (totalUpgrade.getArmor() != 0) { + str += "+" + intToStr(totalUpgrade.getArmor()); + } + str += " (" + getType()->getArmorType()->getName(translatedValue) + ")"; + + // sight + str += + "\n" + lang.getString("Sight") + ": " + intToStr(getType()->getSight()); + if (totalUpgrade.getSight() != 0) { + str += "+" + intToStr(totalUpgrade.getSight()); + } + + // kills + const Level *nextLevel = getNextLevel(); + if (enemyKills > 0 || nextLevel != NULL) { + str += "\n" + lang.getString("Kills") + ": " + intToStr(enemyKills); + if (nextLevel != NULL) { + str += " (" + nextLevel->getName(translatedValue) + ": " + + intToStr(nextLevel->getKills()) + ")"; + } + } + + // str+= "\nskl: "+scToStr(currSkill->getClass()); + + // load + if (loadCount != 0) { + str += "\n" + lang.getString("Load") + ": " + intToStr(loadCount) + " " + + loadType->getName(translatedValue); + } + + // consumable production + for (int i = 0; i < getType()->getCostCount(); ++i) { + const Resource *r = getType()->getCost(i); + if (r->getType()->getClass() == rcConsumable) { + str += "\n"; + str += r->getAmount() < 0 ? lang.getString("Produce") + ": " + : lang.getString("Consume") + ": "; + str += intToStr(abs(r->getAmount())) + " " + + r->getType()->getName(translatedValue); + } + } + + // command info + if (commands.empty() == false) { + str += "\n" + commands.front()->getCommandType()->getName(translatedValue); + if (commands.size() > 1) { + str += "\n" + lang.getString("OrdersOnQueue") + ": " + + intToStr(commands.size()); + } + } else { + // can store + if (getType()->getStoredResourceCount() > 0) { + for (int i = 0; i < getType()->getStoredResourceCount(); ++i) { + const Resource *r = getType()->getStoredResource(i); + str += "\n" + lang.getString("Store") + ": "; + str += intToStr(r->getAmount()) + " " + + r->getType()->getName(translatedValue); + } + } + } + + return str; +} + +void Unit::applyUpgrade(const UpgradeType *upgradeType) { + if (upgradeType == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: upgradeType == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + if (upgradeType->isAffected(type)) { + totalUpgrade.sum(upgradeType, this); + + checkItemInVault(&this->hp, this->hp); + int original_hp = this->hp; + this->hp += totalUpgrade.getMaxHp(); + this->hp = max(0, this->hp); + if (original_hp != this->hp) { + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + game->getScriptManager()->onUnitTriggerEvent(this, utet_HPChanged); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + } + addItemToVault(&this->hp, this->hp); - return str; + checkModelStateInfoForNewHpValue(); + } } -string Unit::getDesc(bool translatedValue) const { - - Lang &lang= Lang::getInstance(); - - //hp - string str= "\n"; - - //maxUnitCount - if(type->getMaxUnitCount()>0){ - str += lang.getString("MaxUnitCount")+ ": " + intToStr(faction->getCountForMaxUnitCount(type)) + "/" + intToStr(type->getMaxUnitCount()); - } - - str += "\n"+lang.getString("Hp")+ ": " + intToStr(hp) + "/" + intToStr(type->getTotalMaxHp(&totalUpgrade)); - if(type->getHpRegeneration() != 0 || totalUpgrade.getMaxHpRegeneration() != 0) { - str+= " (" + lang.getString("Regeneration") + ": " + intToStr(type->getHpRegeneration()); - if(totalUpgrade.getMaxHpRegeneration() != 0) { - str+= "+" + intToStr(totalUpgrade.getMaxHpRegeneration()); - } - str+= ")"; - } - - //ep - if(getType()->getMaxEp()!=0){ - str+= "\n" + lang.getString("Ep")+ ": " + intToStr(ep) + "/" + intToStr(type->getTotalMaxEp(&totalUpgrade)); - } - if(type->getEpRegeneration() != 0 || totalUpgrade.getMaxEpRegeneration() != 0) { - str+= " (" + lang.getString("Regeneration") + ": " + intToStr(type->getEpRegeneration()); - if(totalUpgrade.getMaxEpRegeneration() != 0) { - str += "+" + intToStr(totalUpgrade.getMaxEpRegeneration()); - } - str+= ")"; - } - - //armor - str+= "\n" + lang.getString("Armor")+ ": " + intToStr(getType()->getArmor()); - if(totalUpgrade.getArmor()!=0){ - str+="+"+intToStr(totalUpgrade.getArmor()); - } - str+= " ("+getType()->getArmorType()->getName(translatedValue)+")"; - - //sight - str+="\n"+ lang.getString("Sight")+ ": " + intToStr(getType()->getSight()); - if(totalUpgrade.getSight()!=0){ - str+="+"+intToStr(totalUpgrade.getSight()); - } - - //kills - const Level *nextLevel= getNextLevel(); - if(enemyKills > 0 || nextLevel != NULL) { - str+= "\n" + lang.getString("Kills") +": " + intToStr(enemyKills); - if(nextLevel != NULL) { - str+= " (" + nextLevel->getName(translatedValue) + ": " + intToStr(nextLevel->getKills()) + ")"; - } - } - - //str+= "\nskl: "+scToStr(currSkill->getClass()); - - //load - if(loadCount!=0){ - str+= "\n" + lang.getString("Load")+ ": " + intToStr(loadCount) +" " + loadType->getName(translatedValue); - } - - //consumable production - for(int i=0; i < getType()->getCostCount(); ++i) { - const Resource *r= getType()->getCost(i); - if(r->getType()->getClass() == rcConsumable) { - str+= "\n"; - str+= r->getAmount() < 0 ? lang.getString("Produce")+": ": lang.getString("Consume")+": "; - str+= intToStr(abs(r->getAmount())) + " " + r->getType()->getName(translatedValue); - } - } - - //command info - if(commands.empty() == false) { - str+= "\n" + commands.front()->getCommandType()->getName(translatedValue); - if(commands.size() > 1) { - str+= "\n" + lang.getString("OrdersOnQueue") + ": " + intToStr(commands.size()); - } - } - else{ - //can store - if(getType()->getStoredResourceCount() > 0) { - for(int i = 0; i < getType()->getStoredResourceCount(); ++i) { - const Resource *r= getType()->getStoredResource(i); - str+= "\n" + lang.getString("Store") + ": "; - str+= intToStr(r->getAmount()) + " " + r->getType()->getName(translatedValue); - } - } - } - - return str; -} - -void Unit::applyUpgrade(const UpgradeType *upgradeType){ - if(upgradeType == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: upgradeType == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - if(upgradeType->isAffected(type)){ - totalUpgrade.sum(upgradeType, this); - - checkItemInVault(&this->hp,this->hp); - int original_hp = this->hp; - this->hp += totalUpgrade.getMaxHp(); - this->hp = max(0,this->hp); - if(original_hp != this->hp) { - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - game->getScriptManager()->onUnitTriggerEvent(this,utet_HPChanged); - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } - addItemToVault(&this->hp,this->hp); - - checkModelStateInfoForNewHpValue(); - } -} - -void Unit::computeTotalUpgrade(){ - faction->getUpgradeManager()->computeTotalUpgrade(this, &totalUpgrade); +void Unit::computeTotalUpgrade() { + faction->getUpgradeManager()->computeTotalUpgrade(this, &totalUpgrade); } void Unit::incKills(int team) { - ++kills; - if(team != this->getTeam()) { - ++enemyKills; - } + ++kills; + if (team != this->getTeam()) { + ++enemyKills; + } - checkUnitLevel(); + checkUnitLevel(); } void Unit::checkUnitLevel() { - const Level *nextLevel= getNextLevel(); - if(nextLevel != NULL && this->enemyKills >= nextLevel->getKills()) { - this->level= nextLevel; - - int maxHp= this->totalUpgrade.getMaxHp(); - totalUpgrade.incLevel(type); - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - game->getScriptManager()->onUnitTriggerEvent(this,utet_LevelChanged); - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - - checkItemInVault(&this->hp,this->hp); - int original_hp = this->hp; - this->hp += totalUpgrade.getMaxHp() - maxHp; - if(original_hp != this->hp) { - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - game->getScriptManager()->onUnitTriggerEvent(this,utet_HPChanged); - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } - addItemToVault(&this->hp,this->hp); - - checkModelStateInfoForNewHpValue(); - } + const Level *nextLevel = getNextLevel(); + if (nextLevel != NULL && this->enemyKills >= nextLevel->getKills()) { + this->level = nextLevel; + + int maxHp = this->totalUpgrade.getMaxHp(); + totalUpgrade.incLevel(type); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + game->getScriptManager()->onUnitTriggerEvent(this, utet_LevelChanged); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + + checkItemInVault(&this->hp, this->hp); + int original_hp = this->hp; + this->hp += totalUpgrade.getMaxHp() - maxHp; + if (original_hp != this->hp) { + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + game->getScriptManager()->onUnitTriggerEvent(this, utet_HPChanged); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + } + addItemToVault(&this->hp, this->hp); + + checkModelStateInfoForNewHpValue(); + } } void Unit::morphAttackBoosts(Unit *unit) { - // Remove any units that were previously in range - if(currentAttackBoostOriginatorEffect.currentAttackBoostUnits.empty() == false && currentAttackBoostOriginatorEffect.skillType != NULL) { - for(int i = (int)currentAttackBoostOriginatorEffect.currentAttackBoostUnits.size() - 1; i >= 0; --i) { - // Remove attack boost upgrades from unit + // Remove any units that were previously in range + if (currentAttackBoostOriginatorEffect.currentAttackBoostUnits.empty() == + false && + currentAttackBoostOriginatorEffect.skillType != NULL) { + for (int i = (int)currentAttackBoostOriginatorEffect.currentAttackBoostUnits + .size() - + 1; + i >= 0; --i) { + // Remove attack boost upgrades from unit + + int findUnitId = + currentAttackBoostOriginatorEffect.currentAttackBoostUnits[i]; + Unit *affectedUnit = game->getWorld()->findUnitById(findUnitId); + if (affectedUnit != NULL && affectedUnit->getId() == unit->getId()) { + affectedUnit->deapplyAttackBoost( + currentAttackBoostOriginatorEffect.skillType->getAttackBoost(), + this); + + currentAttackBoostOriginatorEffect.currentAttackBoostUnits.erase( + currentAttackBoostOriginatorEffect.currentAttackBoostUnits.begin() + + i); + } + + // printf("- #1 DE-APPLY ATTACK BOOST from unit [%s - + // %d]\n",affectedUnit->getType()->getName().c_str(),affectedUnit->getId()); + } + } +} - int findUnitId = currentAttackBoostOriginatorEffect.currentAttackBoostUnits[i]; - Unit *affectedUnit = game->getWorld()->findUnitById(findUnitId); - if(affectedUnit != NULL && affectedUnit->getId() == unit->getId()) { - affectedUnit->deapplyAttackBoost(currentAttackBoostOriginatorEffect.skillType->getAttackBoost(), this); +bool Unit::morph(const MorphCommandType *mct, int frameIndex) { + + if (mct == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: mct == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + const UnitType *morphUnitType = mct->getMorphUnit(); + + if (morphUnitType == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: morphUnitType == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + Field morphUnitField = fLand; + if (morphUnitType->getField(fAir)) { + morphUnitField = fAir; + } + if (morphUnitType->getField(fLand)) { + morphUnitField = fLand; + } + + map->clearUnitCells(this, pos, false); + if (map->canMorph(pos, this, morphUnitType)) { + map->clearUnitCells(this, pos, true); + faction->deApplyStaticCosts(type, mct); + + // printf("Now unapply attack-boost for unit [%d - + // %s]\n",this->getId(),this->getType()->getName().c_str()); + // De apply attack boosts for morphed unit + for (int i = (int)currentAttackBoostEffects.size() - 1; i >= 0; --i) { + UnitAttackBoostEffect *effect = currentAttackBoostEffects[i]; + if (effect != NULL) { + Unit *sourceUnit = + game->getWorld()->findUnitById(effect->getSource()->getId()); + if (sourceUnit == NULL) { + throw megaglest_runtime_error("sourceUnit == NULL"); + } + sourceUnit->morphAttackBoosts(this); + } + } - currentAttackBoostOriginatorEffect.currentAttackBoostUnits.erase(currentAttackBoostOriginatorEffect.currentAttackBoostUnits.begin() + i); - } + // stopDamageParticles(true); + cleanupAllParticlesystems(); + + checkItemInVault(&this->hp, this->hp); + int original_hp = this->hp; + this->hp += morphUnitType->getMaxHp() - type->getMaxHp(); + if (original_hp != this->hp) { + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + game->getScriptManager()->onUnitTriggerEvent(this, utet_HPChanged); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + } + addItemToVault(&this->hp, this->hp); + + checkModelStateInfoForNewHpValue(); + + this->preMorph_type = this->type; + this->setType(morphUnitType); + Field original_field = this->currField; + this->currField = morphUnitField; + computeTotalUpgrade(); + map->putUnitCells(this, this->pos, false, frameIndex < 0); + + this->faction->applyDiscount(morphUnitType, mct->getDiscount()); + // add new storage + this->faction->addStore(this->type); + // remove former storage + this->faction->removeStore(this->preMorph_type); + this->faction->applyStaticProduction(morphUnitType, mct); + + this->level = NULL; + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + game->getScriptManager()->onUnitTriggerEvent(this, utet_LevelChanged); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + checkUnitLevel(); + + if (original_field != this->currField) { + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + game->getScriptManager()->onUnitTriggerEvent(this, utet_FieldChanged); + // printf("File: %s line: + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + } - //printf("- #1 DE-APPLY ATTACK BOOST from unit [%s - %d]\n",affectedUnit->getType()->getName().c_str(),affectedUnit->getId()); - } - } + return true; + } else { + return false; + } } -bool Unit::morph(const MorphCommandType *mct, int frameIndex) { +// ==================== PRIVATE ==================== + +float Unit::computeHeight(const Vec2i &pos) const { + // printf("CRASHING FOR UNIT: %d alive = %d\n",this->getId(),this->isAlive()); + // printf("[%s]\n",this->getType()->getName().c_str()); + if (map->isInside(pos) == false || + map->isInsideSurface(map->toSurfCoords(pos)) == false) { + // printf("CRASHING FOR UNIT: %d [%s] alive = + // %d\n",this->getId(),this->getType()->getName().c_str(),this->isAlive()); + // abort(); + throw megaglest_runtime_error("#7 Invalid path position = " + + pos.getString()); + } + + float height = map->getCell(pos)->getHeight(); + + if (currField == fAir) { + float airHeight = game->getWorld()->getTileset()->getAirHeight(); + airHeight = truncateDecimal(airHeight, 6); + + height += airHeight; + height = truncateDecimal(height, 6); + + Unit *unit = map->getCell(pos)->getUnit(fLand); + if (unit != NULL && unit->getType()->getHeight() > airHeight) { + height += (std::min((float)unit->getType()->getHeight(), + Tileset::standardAirHeight * 3) - + airHeight); + height = truncateDecimal(height, 6); + } else { + SurfaceCell *sc = map->getSurfaceCell(map->toSurfCoords(pos)); + if (sc != NULL && sc->getObject() != NULL && + sc->getObject()->getType() != NULL) { + if (sc->getObject()->getType()->getHeight() > airHeight) { + height += (std::min((float)sc->getObject()->getType()->getHeight(), + Tileset::standardAirHeight * 3) - + airHeight); + height = truncateDecimal(height, 6); + } + } + } + // for flying above water we use the water height + airHeight if it is + // higher than the normal height.. + if (map->getWaterLevel() + airHeight > height) { + height = map->getWaterLevel() + airHeight; + } + } - if(mct == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: mct == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - const UnitType *morphUnitType= mct->getMorphUnit(); - - if(morphUnitType == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: morphUnitType == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - Field morphUnitField = fLand; - if(morphUnitType->getField(fAir)) { - morphUnitField = fAir; - } - if(morphUnitType->getField(fLand)) { - morphUnitField = fLand; - } - - map->clearUnitCells(this, pos, false); - if(map->canMorph(pos,this,morphUnitType)) { - map->clearUnitCells(this, pos, true); - faction->deApplyStaticCosts(type,mct); - - //printf("Now unapply attack-boost for unit [%d - %s]\n",this->getId(),this->getType()->getName().c_str()); - // De apply attack boosts for morphed unit - for(int i = (int)currentAttackBoostEffects.size() - 1; i >= 0; --i) { - UnitAttackBoostEffect *effect = currentAttackBoostEffects[i]; - if(effect != NULL) { - Unit *sourceUnit = game->getWorld()->findUnitById(effect->getSource()->getId()); - if(sourceUnit == NULL) { - throw megaglest_runtime_error("sourceUnit == NULL"); - } - sourceUnit->morphAttackBoosts(this); - } - } - - //stopDamageParticles(true); - cleanupAllParticlesystems(); - - checkItemInVault(&this->hp,this->hp); - int original_hp = this->hp; - this->hp += morphUnitType->getMaxHp() - type->getMaxHp(); - if(original_hp != this->hp) { - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - game->getScriptManager()->onUnitTriggerEvent(this,utet_HPChanged); - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } - addItemToVault(&this->hp,this->hp); - - checkModelStateInfoForNewHpValue(); - - this->preMorph_type = this->type; - this->setType(morphUnitType); - Field original_field = this->currField; - this->currField=morphUnitField; - computeTotalUpgrade(); - map->putUnitCells(this, this->pos, false, frameIndex < 0); - - this->faction->applyDiscount(morphUnitType, mct->getDiscount()); - // add new storage - this->faction->addStore(this->type); - // remove former storage - this->faction->removeStore(this->preMorph_type); - this->faction->applyStaticProduction(morphUnitType,mct); - - this->level= NULL; - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - game->getScriptManager()->onUnitTriggerEvent(this,utet_LevelChanged); - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - checkUnitLevel(); - - if(original_field != this->currField) { - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - game->getScriptManager()->onUnitTriggerEvent(this,utet_FieldChanged); - //printf("File: %s line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); - } - - return true; - } - else{ - return false; - } + return height; } +void Unit::AnimCycleStarts() { + // we need to queue timed particles if progress starts + queueTimedParticles(currSkill->unitParticleSystemTypes); +} -// ==================== PRIVATE ==================== +void Unit::updateTarget() { + Unit *target = targetRef.getUnit(); + if (target != NULL) { -float Unit::computeHeight(const Vec2i &pos) const { - //printf("CRASHING FOR UNIT: %d alive = %d\n",this->getId(),this->isAlive()); - //printf("[%s]\n",this->getType()->getName().c_str()); - if(map->isInside(pos) == false || map->isInsideSurface(map->toSurfCoords(pos)) == false) { - //printf("CRASHING FOR UNIT: %d [%s] alive = %d\n",this->getId(),this->getType()->getName().c_str(),this->isAlive()); - //abort(); - throw megaglest_runtime_error("#7 Invalid path position = " + pos.getString()); - } - - float height= map->getCell(pos)->getHeight(); - - if(currField == fAir) { - float airHeight = game->getWorld()->getTileset()->getAirHeight(); - airHeight = truncateDecimal(airHeight,6); - - height += airHeight; - height = truncateDecimal(height,6); - - Unit *unit = map->getCell(pos)->getUnit(fLand); - if(unit != NULL && unit->getType()->getHeight() > airHeight) { - height += (std::min((float)unit->getType()->getHeight(),Tileset::standardAirHeight * 3) - airHeight); - height = truncateDecimal(height,6); - } - else { - SurfaceCell *sc = map->getSurfaceCell(map->toSurfCoords(pos)); - if(sc != NULL && sc->getObject() != NULL && sc->getObject()->getType() != NULL) { - if(sc->getObject()->getType()->getHeight() > airHeight) { - height += (std::min((float)sc->getObject()->getType()->getHeight(),Tileset::standardAirHeight * 3) - airHeight); - height = truncateDecimal(height,6); - } - } - } - // for flying above water we use the water height + airHeight if it is higher than the normal height.. - if( map->getWaterLevel()+airHeight>height) { - height=map->getWaterLevel()+airHeight; - } - } - - return height; -} - -void Unit::AnimCycleStarts(){ - // we need to queue timed particles if progress starts - queueTimedParticles(currSkill->unitParticleSystemTypes); -} - -void Unit::updateTarget(){ - Unit *target= targetRef.getUnit(); - if(target!=NULL){ - - //update target pos - targetPos= target->getCellPos(); - Vec2i relPos= targetPos - pos; - Vec2f relPosf= Vec2f((float)relPos.x, (float)relPos.y); + // update target pos + targetPos = target->getCellPos(); + Vec2i relPos = targetPos - pos; + Vec2f relPosf = Vec2f((float)relPos.x, (float)relPos.y); #ifdef USE_STREFLOP - targetRotation= radToDeg(streflop::atan2(static_cast(relPosf.x), static_cast(relPosf.y))); + targetRotation = + radToDeg(streflop::atan2(static_cast(relPosf.x), + static_cast(relPosf.y))); #else - targetRotation= radToDeg(atan2(relPosf.x, relPosf.y)); + targetRotation = radToDeg(atan2(relPosf.x, relPosf.y)); #endif - targetVec= target->getCurrVectorAsTarget(); - } + targetVec = target->getCurrVectorAsTarget(); + } } void Unit::clearCommands() { - this->setCurrentUnitTitle(""); - this->unitPath->clear(); - while(commands.empty() == false) { - undoCommand(commands.back()); + this->setCurrentUnitTitle(""); + this->unitPath->clear(); + while (commands.empty() == false) { + undoCommand(commands.back()); - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(mutexCommands,mutexOwnerId); + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(mutexCommands, mutexOwnerId); - delete commands.back(); - commands.pop_back(); + delete commands.back(); + commands.pop_back(); - safeMutex.ReleaseLock(); - } - changedActiveCommand = false; + safeMutex.ReleaseLock(); + } + changedActiveCommand = false; } void Unit::deleteQueuedCommand(Command *command) { - if(getCurrCommand() == command) { - this->setCurrentUnitTitle(""); - this->unitPath->clear(); - } - undoCommand(command); - delete command; -} - - -std::pair Unit::checkCommand(Command *command) const { - std::pair result(crSuccess,""); - - if(command == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: command == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - //if not operative or has not command type => fail - if(isOperative() == false || - command->getUnit() == this || - getType()->hasCommandType(command->getCommandType()) == false || - (ignoreCheckCommand == false && this->getFaction()->reqsOk(command->getCommandType()) == false)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d] isOperative() = %d, command->getUnit() = %p, getType()->hasCommandType(command->getCommandType()) = %d, this->getFaction()->reqsOk(command->getCommandType()) = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__, __LINE__,isOperative(),command->getUnit(),getType()->hasCommandType(command->getCommandType()),this->getFaction()->reqsOk(command->getCommandType())); - - // Allow self healing if able to heal own unit type - if( command->getUnit() == this && - command->getCommandType()->getClass() == ccRepair && - this->getType()->getFirstRepairCommand(this->getType()) != NULL) { - - } - else { - //printf("In [%s::%s Line: %d] command = %p\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,command); - - result.first = crFailUndefined; - return result; - } - } - - //if pos is not inside the world (if comand has not a pos, pos is (0, 0) and is inside world - if(map->isInside(command->getPos()) == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__, __LINE__); - //printf("In [%s::%s Line: %d] command = %p\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,command); - - result.first = crFailUndefined; - return result; - } - - //check produced - if(command->getCommandType() == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: command->getCommandType() == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - const ProducibleType *produced= command->getCommandType()->getProduced(); - if(produced != NULL) { - if(ignoreCheckCommand == false && faction->reqsOk(produced) == false) { - //printf("In [%s::%s Line: %d] command = %p\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,command); - //printf("To produce this unit you need:\n%s\n",produced->getUnitAndUpgradeReqDesc().c_str()); - result.first = crFailReqs; - - Lang &lang= Lang::getInstance(); - result.second = " - " + lang.getString("Reqs") + " : " + produced->getUnitAndUpgradeReqDesc(false,this->showTranslatedTechTree()); - return result; - } - - if(ignoreCheckCommand == false && - faction->checkCosts(produced,command->getCommandType()) == false) { - //printf("To produce this unit you need:\n%s\n",produced->getResourceReqDesc().c_str()); - //printf("In [%s::%s Line: %d] command = %p\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,command); - result.first = crFailRes; - Lang &lang= Lang::getInstance(); - result.second = " - " + lang.getString("Reqs") + " : " + produced->getResourceReqDesc(false,this->showTranslatedTechTree()); - return result; - } - } - - //build command specific, check resources and requirements for building - if(command->getCommandType()->getClass() == ccBuild) { - const UnitType *builtUnit= command->getUnitType(); - - if(builtUnit == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: builtUnit == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - if(faction->reqsOk(builtUnit) == false) { - //printf("To build this unit you need:\n%s\n",builtUnit->getUnitAndUpgradeReqDesc().c_str()); - //printf("In [%s::%s Line: %d] command = %p\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,command); - result.first = crFailReqs; - Lang &lang= Lang::getInstance(); - result.second = " - " + lang.getString("Reqs") + " : " + builtUnit->getUnitAndUpgradeReqDesc(false,this->showTranslatedTechTree()); - return result; - } - if(faction->checkCosts(builtUnit,NULL) == false) { - //printf("To build this unit you need:\n%s\n",builtUnit->getResourceReqDesc().c_str()); - //printf("In [%s::%s Line: %d] command = %p\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,command); - result.first = crFailRes; - Lang &lang= Lang::getInstance(); - result.second = " - " + lang.getString("Reqs") + " : " + builtUnit->getResourceReqDesc(false,this->showTranslatedTechTree()); - return result; - } - } - //upgrade command specific, check that upgrade is not upgraded - else if(command->getCommandType()->getClass() == ccUpgrade) { - const UpgradeCommandType *uct= static_cast(command->getCommandType()); - - if(uct == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: uct == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - if(faction->getUpgradeManager()->isUpgradingOrUpgraded(uct->getProducedUpgrade())){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__, __LINE__); - //printf("In [%s::%s Line: %d] command = %p\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,command); - result.first = crFailUndefined; - return result; - } - } - + if (getCurrCommand() == command) { + this->setCurrentUnitTitle(""); + this->unitPath->clear(); + } + undoCommand(command); + delete command; +} + +std::pair Unit::checkCommand(Command *command) const { + std::pair result(crSuccess, ""); + + if (command == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: command == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + // if not operative or has not command type => fail + if (isOperative() == false || command->getUnit() == this || + getType()->hasCommandType(command->getCommandType()) == false || + (ignoreCheckCommand == false && + this->getFaction()->reqsOk(command->getCommandType()) == false)) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugLUA, + "In [%s::%s Line: %d] isOperative() = %d, command->getUnit() = %p, " + "getType()->hasCommandType(command->getCommandType()) = %d, " + "this->getFaction()->reqsOk(command->getCommandType()) = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, isOperative(), command->getUnit(), + getType()->hasCommandType(command->getCommandType()), + this->getFaction()->reqsOk(command->getCommandType())); + + // Allow self healing if able to heal own unit type + if (command->getUnit() == this && + command->getCommandType()->getClass() == ccRepair && + this->getType()->getFirstRepairCommand(this->getType()) != NULL) { + + } else { + // printf("In [%s::%s Line: %d] command = + // %p\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,command); + + result.first = crFailUndefined; + return result; + } + } + + // if pos is not inside the world (if comand has not a pos, pos is (0, 0) and + // is inside world + if (map->isInside(command->getPos()) == false) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + // printf("In [%s::%s Line: %d] command = + // %p\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,command); + + result.first = crFailUndefined; return result; -} + } + + // check produced + if (command->getCommandType() == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: command->getCommandType() == NULL, " + "Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + const ProducibleType *produced = command->getCommandType()->getProduced(); + if (produced != NULL) { + if (ignoreCheckCommand == false && faction->reqsOk(produced) == false) { + // printf("In [%s::%s Line: %d] command = + // %p\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,command); + // printf("To produce this unit you + // need:\n%s\n",produced->getUnitAndUpgradeReqDesc().c_str()); + result.first = crFailReqs; + + Lang &lang = Lang::getInstance(); + result.second = " - " + lang.getString("Reqs") + " : " + + produced->getUnitAndUpgradeReqDesc( + false, this->showTranslatedTechTree()); + return result; + } + + if (ignoreCheckCommand == false && + faction->checkCosts(produced, command->getCommandType()) == false) { + // printf("To produce this unit you + // need:\n%s\n",produced->getResourceReqDesc().c_str()); printf("In + // [%s::%s Line: %d] command = + // %p\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,command); + result.first = crFailRes; + Lang &lang = Lang::getInstance(); + result.second = + " - " + lang.getString("Reqs") + " : " + + produced->getResourceReqDesc(false, this->showTranslatedTechTree()); + return result; + } + } + + // build command specific, check resources and requirements for building + if (command->getCommandType()->getClass() == ccBuild) { + const UnitType *builtUnit = command->getUnitType(); + + if (builtUnit == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: builtUnit == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } -void Unit::applyCommand(Command *command){ - if(command == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: command == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - else if(command->getCommandType() == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: command->getCommandType() == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - //check produced - const ProducibleType *produced= command->getCommandType()->getProduced(); - if(produced!=NULL) { - faction->applyCosts(produced,command->getCommandType()); - } - - //build command specific - if(command->getCommandType()->getClass()==ccBuild){ - faction->applyCosts(command->getUnitType(),command->getCommandType()); - } - //upgrade command specific - else if(command->getCommandType()->getClass()==ccUpgrade){ - const UpgradeCommandType *uct= static_cast(command->getCommandType()); - - if(uct == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: uct == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - faction->startUpgrade(uct->getProducedUpgrade()); - } -} - -CommandResult Unit::undoCommand(Command *command){ - - if(command == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: command == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - else if(command->getCommandType() == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: command->getCommandType() == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - if(getCurrCommand() == command && command->getCommandType()->getClass()==ccMorph - && this->currSkill->getClass() == scMorph ){ - // clear cells of morphed unit and set those of current unit! - map->clearUnitCells(this, this->getPos()); - map->putUnitCells(this, this->getPos(),true); - } - //return cost - const ProducibleType *produced= command->getCommandType()->getProduced(); - if(produced!=NULL){ - faction->deApplyCosts(produced,command->getCommandType()); - } - - //return building cost if not already building it or dead - if(command->getCommandType()->getClass() == ccBuild){ - if(currSkill->getClass() != scBuild && currSkill->getClass() != scDie) { - faction->deApplyCosts(command->getUnitType(),command->getCommandType()); - } - } - - //upgrade command cancel from list - if(command->getCommandType()->getClass() == ccUpgrade){ - const UpgradeCommandType *uct= static_cast(command->getCommandType()); - if(uct == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] ERROR: uct == NULL, Unit = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this->toString().c_str()); - throw megaglest_runtime_error(szBuf); - } - - faction->cancelUpgrade(uct->getProducedUpgrade()); - } - - retryCurrCommandCount=0; - this->setCurrentUnitTitle(""); - - return crSuccess; + if (faction->reqsOk(builtUnit) == false) { + // printf("To build this unit you + // need:\n%s\n",builtUnit->getUnitAndUpgradeReqDesc().c_str()); printf("In + // [%s::%s Line: %d] command = + // %p\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,command); + result.first = crFailReqs; + Lang &lang = Lang::getInstance(); + result.second = " - " + lang.getString("Reqs") + " : " + + builtUnit->getUnitAndUpgradeReqDesc( + false, this->showTranslatedTechTree()); + return result; + } + if (faction->checkCosts(builtUnit, NULL) == false) { + // printf("To build this unit you + // need:\n%s\n",builtUnit->getResourceReqDesc().c_str()); printf("In + // [%s::%s Line: %d] command = + // %p\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,command); + result.first = crFailRes; + Lang &lang = Lang::getInstance(); + result.second = + " - " + lang.getString("Reqs") + " : " + + builtUnit->getResourceReqDesc(false, this->showTranslatedTechTree()); + return result; + } + } + // upgrade command specific, check that upgrade is not upgraded + else if (command->getCommandType()->getClass() == ccUpgrade) { + const UpgradeCommandType *uct = + static_cast(command->getCommandType()); + + if (uct == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: uct == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + if (faction->getUpgradeManager()->isUpgradingOrUpgraded( + uct->getProducedUpgrade())) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) + SystemFlags::OutputDebug(SystemFlags::debugLUA, + "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + // printf("In [%s::%s Line: %d] command = + // %p\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,command); + result.first = crFailUndefined; + return result; + } + } + + return result; +} + +void Unit::applyCommand(Command *command) { + if (command == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: command == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } else if (command->getCommandType() == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: command->getCommandType() == NULL, " + "Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + // check produced + const ProducibleType *produced = command->getCommandType()->getProduced(); + if (produced != NULL) { + faction->applyCosts(produced, command->getCommandType()); + } + + // build command specific + if (command->getCommandType()->getClass() == ccBuild) { + faction->applyCosts(command->getUnitType(), command->getCommandType()); + } + // upgrade command specific + else if (command->getCommandType()->getClass() == ccUpgrade) { + const UpgradeCommandType *uct = + static_cast(command->getCommandType()); + + if (uct == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: uct == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + faction->startUpgrade(uct->getProducedUpgrade()); + } +} + +CommandResult Unit::undoCommand(Command *command) { + + if (command == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: command == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } else if (command->getCommandType() == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: command->getCommandType() == NULL, " + "Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + if (getCurrCommand() == command && + command->getCommandType()->getClass() == ccMorph && + this->currSkill->getClass() == scMorph) { + // clear cells of morphed unit and set those of current unit! + map->clearUnitCells(this, this->getPos()); + map->putUnitCells(this, this->getPos(), true); + } + // return cost + const ProducibleType *produced = command->getCommandType()->getProduced(); + if (produced != NULL) { + faction->deApplyCosts(produced, command->getCommandType()); + } + + // return building cost if not already building it or dead + if (command->getCommandType()->getClass() == ccBuild) { + if (currSkill->getClass() != scBuild && currSkill->getClass() != scDie) { + faction->deApplyCosts(command->getUnitType(), command->getCommandType()); + } + } + + // upgrade command cancel from list + if (command->getCommandType()->getClass() == ccUpgrade) { + const UpgradeCommandType *uct = + static_cast(command->getCommandType()); + if (uct == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] ERROR: uct == NULL, Unit = [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, this->toString().c_str()); + throw megaglest_runtime_error(szBuf); + } + + faction->cancelUpgrade(uct->getProducedUpgrade()); + } + + retryCurrCommandCount = 0; + this->setCurrentUnitTitle(""); + + return crSuccess; } void Unit::stopDamageParticles(bool force) { - if(force == true || (hp > type->getTotalMaxHp(&totalUpgrade) / 2) ) { - //printf("Checking to stop damageparticles for unit [%s - %d] hp = %d\n",this->getType()->getName().c_str(),this->getId(),hp); - - if(Renderer::getInstance().validateParticleSystemStillExists(this->fire,rsGame) == false) { - this->fire = NULL; - } - - // stop fire - if(this->fire != NULL) { - this->fire->fade(); - this->fire = NULL; - } - // stop additional particles - - - if(smokeParticleSystems.empty() == false) { - //printf("Checking to stop smokeparticles for unit [%s - %d] hp = %d\n",this->getType()->getName().c_str(),this->getId(),hp); - - for(int i = (int)smokeParticleSystems.size()-1; i >= 0; --i) { - UnitParticleSystem *ps = smokeParticleSystems[i]; - if(Renderer::getInstance().validateParticleSystemStillExists(ps,rsGame) == true) { - ps->fade(); - } - smokeParticleSystems.pop_back(); - } - } - - if(damageParticleSystems.empty() == false) { - //printf("Checking to stop damageparticles for unit [%s - %d] hp = %d\n",this->getType()->getName().c_str(),this->getId(),hp); - - for(int i = (int)damageParticleSystems.size()-1; i >= 0; --i) { - UnitParticleSystem *ps = damageParticleSystems[i]; - UnitParticleSystemType *pst = NULL; - int foundParticleIndexType = -2; - if(Renderer::getInstance().validateParticleSystemStillExists(ps,rsGame) == true) { - for(std::map::iterator iterMap = damageParticleSystemsInUse.begin(); - iterMap != damageParticleSystemsInUse.end(); ++iterMap) { - if(iterMap->second == ps) { - foundParticleIndexType = iterMap->first; - if(foundParticleIndexType >= 0) { - pst = type->damageParticleSystemTypes[foundParticleIndexType]; - break; - } - } - } - } - if(force == true || ( pst !=NULL && pst->getMinmaxEnabled() == false )) { - damageParticleSystemsInUse.erase(foundParticleIndexType); - if(Renderer::getInstance().validateParticleSystemStillExists(ps,rsGame) == true) { - ps->fade(); - } - damageParticleSystems.pop_back(); - } - } - } - } - - checkCustomizedParticleTriggers(force); -} - -void Unit::checkCustomizedUnitParticleListTriggers(const UnitParticleSystemTypes &unitParticleSystemTypesList, - bool applySkillChangeParticles) { - if(showUnitParticles == true) { - vector systemTypesInUse; - - if(unitParticleSystems.empty() == false) { - for(int index = (int)unitParticleSystems.size() - 1; index >= 0; index--) { - UnitParticleSystem *ps = unitParticleSystems[index]; - if(ps != NULL) { - if(Renderer::getInstance().validateParticleSystemStillExists(ps,rsGame) == true) { - - bool stopParticle = false; - if((ps->getParticleType() != NULL && - ps->getParticleType()->getMinmaxEnabled())) { - - if(ps->getParticleType() != NULL) { - if(ps->getParticleType()->getMinmaxIsPercent() == false) { - if(hp < ps->getParticleType()->getMinHp() || hp > ps->getParticleType()->getMaxHp()) { - stopParticle = true; - - //printf("STOP Particle line: %d\n",__LINE__); - } - } - else { - int hpPercent = (hp / type->getTotalMaxHp(&totalUpgrade) * 100); - if(hpPercent < ps->getParticleType()->getMinHp() || hpPercent > ps->getParticleType()->getMaxHp()) { - stopParticle = true; - - //printf("STOP Particle line: %d\n",__LINE__); - } - } - } - - if(stopParticle == true) { - ps->fade(); - unitParticleSystems.erase(unitParticleSystems.begin() + index); - } - } - - if(ps->getParticleType() != NULL && stopParticle == false) { - systemTypesInUse.push_back(ps->getParticleType()); - } - } - } - } - } - - //printf("Check Particle start line: %d size: %d\n",__LINE__,(int)unitParticleSystemTypesList.size()); - - if(unitParticleSystemTypesList.empty() == false) { - - //for(unsigned int index = 0; index < unitParticleSystemTypesList.size(); ++index) { - for(UnitParticleSystemTypes::const_iterator iterParticleType = unitParticleSystemTypesList.begin(); - iterParticleType != unitParticleSystemTypesList.end(); ++iterParticleType) { - UnitParticleSystemType *pst = *iterParticleType; - - vector::iterator iterFind = std::find(systemTypesInUse.begin(),systemTypesInUse.end(),pst); - - //printf("Check Particle line: %d isenabled: %d already in use: %d\n",__LINE__,pst->getMinmaxEnabled(),(iterFind == systemTypesInUse.end())); - - bool showParticle = applySkillChangeParticles; - if(pst->getMinmaxEnabled() == true) { - - //printf("Check Particle line: %d isenabled: %d already in use: %d\n",__LINE__,pst->getMinmaxEnabled(),(iterFind != systemTypesInUse.end())); - - showParticle = false; - if(iterFind == systemTypesInUse.end()) { - if(pst->getMinmaxIsPercent() == false) { - if(hp >= pst->getMinHp() && hp <= pst->getMaxHp()) { - showParticle = true; - - //printf("START Particle line: %d\n",__LINE__); - } - } - else { - int hpPercent = (hp / type->getTotalMaxHp(&totalUpgrade) * 100); - if(hpPercent >= pst->getMinHp() && hpPercent <= pst->getMaxHp()) { - showParticle = true; - - //printf("START Particle line: %d\n",__LINE__); - } - } - } - } - if(showParticle == true){ - if(pst->getStartTime() == 0.0) { - UnitParticleSystem *ups = new UnitParticleSystem(200); - ups->setParticleOwner(this); - ups->setParticleType(pst); - - pst->setValues(ups); - ups->setPos(getCurrVectorForParticlesystems()); - ups->setRotation(getRotation()); - setMeshPosInParticleSystem(ups); - if(getFaction()->getTexture()) { - ups->setFactionColor(getFaction()->getTexture()->getPixmapConst()->getPixel3f(0,0)); - } - unitParticleSystems.push_back(ups); - Renderer::getInstance().manageParticleSystem(ups, rsGame); - } - else { - // do nothing, timed particles are handled below in queueTimedParticles() - } - } - } - } - } -} - -void Unit::queueTimedParticles(const UnitParticleSystemTypes &unitParticleSystemTypesList){ - if(showUnitParticles == true) { - for(UnitParticleSystemTypes::const_iterator iterParticleType = unitParticleSystemTypesList.begin(); - iterParticleType != unitParticleSystemTypesList.end(); ++iterParticleType) { - UnitParticleSystemType *pst = *iterParticleType; - if(pst->getMinmaxEnabled() == false) { - if(pst->getStartTime() != 0.0) { - queuedUnitParticleSystemTypes.push_back(pst); - } - } - } - } -} - -void Unit::setMeshPosInParticleSystem(UnitParticleSystem *ups){ - if(ups->getMeshName()!=""){ - string meshName=ups->getMeshName(); - Model *model= getCurrentModelPtr(); - - // as it can happen that anim progress is a bit out of range we correct it to get something valid for the particle positions. - float currentAnimProgress=getAnimProgressAsFloat(); - if( currentAnimProgress>1.f || currentAnimProgress<0.f) { - currentAnimProgress=0.f; - } - model->updateInterpolationVertices(currentAnimProgress, isAlive() && !isAnimProgressBound()); - - bool foundMesh=false; - for(unsigned int i=0; igetMeshCount() ; i++){ - //printf("meshName=%s\n",unitModel->getMesh(i)->getName().c_str()); - if(model->getMesh(i)->getName()==meshName){ - const InterpolationData *data=model->getMesh(i)->getInterpolationData(); - const Vec3f *verticepos=data->getVertices(); - ups->setMeshPos(Vec3f(verticepos->x,verticepos->y,verticepos->z)); - foundMesh=true; - break; - } - } - if( foundMesh == false ) { - string meshesFound = model->getMesh(0)->getName(); - for(unsigned i=1; igetMeshCount() ; i++){ - meshesFound+= ", "+model->getMesh(i)->getName(); - } - - string errorString = "Warning: Particle system is trying to find mesh '"+meshName+"', but just found:\n'"+meshesFound+"' in file:\n'"+model->getFileName()+"'\n"; - //throw megaglest_runtime_error(errorString); - printf("%s",errorString.c_str()); - } - } + if (force == true || (hp > type->getTotalMaxHp(&totalUpgrade) / 2)) { + // printf("Checking to stop damageparticles for unit [%s - %d] hp = + // %d\n",this->getType()->getName().c_str(),this->getId(),hp); + + if (Renderer::getInstance().validateParticleSystemStillExists( + this->fire, rsGame) == false) { + this->fire = NULL; + } + + // stop fire + if (this->fire != NULL) { + this->fire->fade(); + this->fire = NULL; + } + // stop additional particles + + if (smokeParticleSystems.empty() == false) { + // printf("Checking to stop smokeparticles for unit [%s - %d] hp = + // %d\n",this->getType()->getName().c_str(),this->getId(),hp); + + for (int i = (int)smokeParticleSystems.size() - 1; i >= 0; --i) { + UnitParticleSystem *ps = smokeParticleSystems[i]; + if (Renderer::getInstance().validateParticleSystemStillExists( + ps, rsGame) == true) { + ps->fade(); + } + smokeParticleSystems.pop_back(); + } + } + + if (damageParticleSystems.empty() == false) { + // printf("Checking to stop damageparticles for unit [%s - %d] hp = + // %d\n",this->getType()->getName().c_str(),this->getId(),hp); + + for (int i = (int)damageParticleSystems.size() - 1; i >= 0; --i) { + UnitParticleSystem *ps = damageParticleSystems[i]; + UnitParticleSystemType *pst = NULL; + int foundParticleIndexType = -2; + if (Renderer::getInstance().validateParticleSystemStillExists( + ps, rsGame) == true) { + for (std::map::iterator iterMap = + damageParticleSystemsInUse.begin(); + iterMap != damageParticleSystemsInUse.end(); ++iterMap) { + if (iterMap->second == ps) { + foundParticleIndexType = iterMap->first; + if (foundParticleIndexType >= 0) { + pst = type->damageParticleSystemTypes[foundParticleIndexType]; + break; + } + } + } + } + if (force == true || + (pst != NULL && pst->getMinmaxEnabled() == false)) { + damageParticleSystemsInUse.erase(foundParticleIndexType); + if (Renderer::getInstance().validateParticleSystemStillExists( + ps, rsGame) == true) { + ps->fade(); + } + damageParticleSystems.pop_back(); + } + } + } + } + + checkCustomizedParticleTriggers(force); +} + +void Unit::checkCustomizedUnitParticleListTriggers( + const UnitParticleSystemTypes &unitParticleSystemTypesList, + bool applySkillChangeParticles) { + if (showUnitParticles == true) { + vector systemTypesInUse; + + if (unitParticleSystems.empty() == false) { + for (int index = (int)unitParticleSystems.size() - 1; index >= 0; + index--) { + UnitParticleSystem *ps = unitParticleSystems[index]; + if (ps != NULL) { + if (Renderer::getInstance().validateParticleSystemStillExists( + ps, rsGame) == true) { + + bool stopParticle = false; + if ((ps->getParticleType() != NULL && + ps->getParticleType()->getMinmaxEnabled())) { + + if (ps->getParticleType() != NULL) { + if (ps->getParticleType()->getMinmaxIsPercent() == false) { + if (hp < ps->getParticleType()->getMinHp() || + hp > ps->getParticleType()->getMaxHp()) { + stopParticle = true; + + // printf("STOP Particle line: %d\n",__LINE__); + } + } else { + int hpPercent = + (hp / type->getTotalMaxHp(&totalUpgrade) * 100); + if (hpPercent < ps->getParticleType()->getMinHp() || + hpPercent > ps->getParticleType()->getMaxHp()) { + stopParticle = true; + + // printf("STOP Particle line: %d\n",__LINE__); + } + } + } + + if (stopParticle == true) { + ps->fade(); + unitParticleSystems.erase(unitParticleSystems.begin() + index); + } + } + + if (ps->getParticleType() != NULL && stopParticle == false) { + systemTypesInUse.push_back(ps->getParticleType()); + } + } + } + } + } + + // printf("Check Particle start line: %d size: + // %d\n",__LINE__,(int)unitParticleSystemTypesList.size()); + + if (unitParticleSystemTypesList.empty() == false) { + + // for(unsigned int index = 0; index < unitParticleSystemTypesList.size(); + // ++index) { + for (UnitParticleSystemTypes::const_iterator iterParticleType = + unitParticleSystemTypesList.begin(); + iterParticleType != unitParticleSystemTypesList.end(); + ++iterParticleType) { + UnitParticleSystemType *pst = *iterParticleType; + + vector::iterator iterFind = + std::find(systemTypesInUse.begin(), systemTypesInUse.end(), pst); + + // printf("Check Particle line: %d isenabled: %d already in use: + // %d\n",__LINE__,pst->getMinmaxEnabled(),(iterFind == + // systemTypesInUse.end())); + + bool showParticle = applySkillChangeParticles; + if (pst->getMinmaxEnabled() == true) { + + // printf("Check Particle line: %d isenabled: %d already in use: + // %d\n",__LINE__,pst->getMinmaxEnabled(),(iterFind != + // systemTypesInUse.end())); + + showParticle = false; + if (iterFind == systemTypesInUse.end()) { + if (pst->getMinmaxIsPercent() == false) { + if (hp >= pst->getMinHp() && hp <= pst->getMaxHp()) { + showParticle = true; + + // printf("START Particle line: %d\n",__LINE__); + } + } else { + int hpPercent = (hp / type->getTotalMaxHp(&totalUpgrade) * 100); + if (hpPercent >= pst->getMinHp() && + hpPercent <= pst->getMaxHp()) { + showParticle = true; + + // printf("START Particle line: %d\n",__LINE__); + } + } + } + } + if (showParticle == true) { + if (pst->getStartTime() == 0.0) { + UnitParticleSystem *ups = new UnitParticleSystem(200); + ups->setParticleOwner(this); + ups->setParticleType(pst); + + pst->setValues(ups); + ups->setPos(getCurrVectorForParticlesystems()); + ups->setRotation(getRotation()); + setMeshPosInParticleSystem(ups); + if (getFaction()->getTexture()) { + ups->setFactionColor( + getFaction()->getTexture()->getPixmapConst()->getPixel3f(0, + 0)); + } + unitParticleSystems.push_back(ups); + Renderer::getInstance().manageParticleSystem(ups, rsGame); + } else { + // do nothing, timed particles are handled below in + // queueTimedParticles() + } + } + } + } + } +} + +void Unit::queueTimedParticles( + const UnitParticleSystemTypes &unitParticleSystemTypesList) { + if (showUnitParticles == true) { + for (UnitParticleSystemTypes::const_iterator iterParticleType = + unitParticleSystemTypesList.begin(); + iterParticleType != unitParticleSystemTypesList.end(); + ++iterParticleType) { + UnitParticleSystemType *pst = *iterParticleType; + if (pst->getMinmaxEnabled() == false) { + if (pst->getStartTime() != 0.0) { + queuedUnitParticleSystemTypes.push_back(pst); + } + } + } + } +} + +void Unit::setMeshPosInParticleSystem(UnitParticleSystem *ups) { + if (ups->getMeshName() != "") { + string meshName = ups->getMeshName(); + Model *model = getCurrentModelPtr(); + + // as it can happen that anim progress is a bit out of range we correct it + // to get something valid for the particle positions. + float currentAnimProgress = getAnimProgressAsFloat(); + if (currentAnimProgress > 1.f || currentAnimProgress < 0.f) { + currentAnimProgress = 0.f; + } + model->updateInterpolationVertices(currentAnimProgress, + isAlive() && !isAnimProgressBound()); + + bool foundMesh = false; + for (unsigned int i = 0; i < model->getMeshCount(); i++) { + // printf("meshName=%s\n",unitModel->getMesh(i)->getName().c_str()); + if (model->getMesh(i)->getName() == meshName) { + const InterpolationData *data = + model->getMesh(i)->getInterpolationData(); + const Vec3f *verticepos = data->getVertices(); + ups->setMeshPos(Vec3f(verticepos->x, verticepos->y, verticepos->z)); + foundMesh = true; + break; + } + } + if (foundMesh == false) { + string meshesFound = model->getMesh(0)->getName(); + for (unsigned i = 1; i < model->getMeshCount(); i++) { + meshesFound += ", " + model->getMesh(i)->getName(); + } + + string errorString = "Warning: Particle system is trying to find mesh '" + + meshName + "', but just found:\n'" + meshesFound + + "' in file:\n'" + model->getFileName() + "'\n"; + // throw megaglest_runtime_error(errorString); + printf("%s", errorString.c_str()); + } + } } void Unit::checkCustomizedUnitParticleTriggers() { - if(currSkill != NULL) { - checkCustomizedUnitParticleListTriggers(currSkill->unitParticleSystemTypes,false); - } + if (currSkill != NULL) { + checkCustomizedUnitParticleListTriggers(currSkill->unitParticleSystemTypes, + false); + } } void Unit::checkCustomizedParticleTriggers(bool force) { - // - // Now check if we have special pre-exisitng hp triggered particles and - // end those that should no longer display - // - // end s particles - if(damageParticleSystems.empty() == false) { - for(int i = (int)damageParticleSystems.size()-1; i >= 0; --i) { - UnitParticleSystem *ps = damageParticleSystems[i]; - UnitParticleSystemType *pst = NULL; - int foundParticleIndexType = -2; - if(Renderer::getInstance().validateParticleSystemStillExists(ps,rsGame) == true) { - for(std::map::iterator iterMap = damageParticleSystemsInUse.begin(); - iterMap != damageParticleSystemsInUse.end(); ++iterMap) { - if(iterMap->second == ps) { - foundParticleIndexType = iterMap->first; - if(foundParticleIndexType >= 0) { - pst = type->damageParticleSystemTypes[foundParticleIndexType]; - break; - } - } - } - } - - if(force == true || (pst != NULL && pst->getMinmaxEnabled() == true)) { - bool stopParticle = force; - if(force == false) { - if(pst->getMinmaxIsPercent() == false) { - if(hp < pst->getMinHp() || hp > pst->getMaxHp()) { - stopParticle = true; - } - } - else { - int hpPercent = (hp / type->getTotalMaxHp(&totalUpgrade) * 100); - if(hpPercent < pst->getMinHp() || hpPercent > pst->getMaxHp()) { - stopParticle = true; - } - } - } - - //printf("CHECKING to STOP customized particle trigger by HP [%d to %d percentbased = %d] current hp = %d stopParticle = %d\n",pst->getMinHp(),pst->getMaxHp(),pst->getMinmaxIsPercent(),hp,stopParticle); - - if(stopParticle == true) { - //printf("STOPPING customized particle trigger by HP [%d to %d] current hp = %d\n",pst->getMinHp(),pst->getMaxHp(),hp); - - damageParticleSystemsInUse.erase(foundParticleIndexType); - if(Renderer::getInstance().validateParticleSystemStillExists(ps,rsGame) == true) { - ps->fade(); - } - damageParticleSystems.pop_back(); - } - } - } - } - - // - // Now check if we have new special hp triggered particles to display - // - //start additional particles - if(showUnitParticles && - type->damageParticleSystemTypes.empty() == false && - force == false && alive == true) { - for(unsigned int i = 0; i < type->damageParticleSystemTypes.size(); ++i) { - UnitParticleSystemType *pst = type->damageParticleSystemTypes[i]; - - if(pst->getMinmaxEnabled() == true && damageParticleSystemsInUse.find(i) == damageParticleSystemsInUse.end()) { - bool showParticle = false; - if(pst->getMinmaxIsPercent() == false) { - if(hp >= pst->getMinHp() && hp <= pst->getMaxHp()) { - showParticle = true; - } - } - else { - int hpPercent = (hp / type->getTotalMaxHp(&totalUpgrade) * 100); - if(hpPercent >= pst->getMinHp() && hpPercent <= pst->getMaxHp()) { - showParticle = true; - } - } - - //printf("CHECKING to START customized particle trigger by HP [%d to %d percentbased = %d] current hp = %d showParticle = %d\n",pst->getMinHp(),pst->getMaxHp(),pst->getMinmaxIsPercent(),hp,showParticle); - - if(showParticle == true) { - //printf("STARTING customized particle trigger by HP [%d to %d] current hp = %d\n",pst->getMinHp(),pst->getMaxHp(),hp); - - UnitParticleSystem *ups = new UnitParticleSystem(200); - ups->setParticleOwner(this); - ups->setParticleType(pst); - - pst->setValues(ups); - ups->setPos(getCurrVectorForParticlesystems()); - ups->setRotation(getRotation()); - setMeshPosInParticleSystem(ups); - if(getFaction()->getTexture()) { - ups->setFactionColor(getFaction()->getTexture()->getPixmapConst()->getPixel3f(0,0)); - } - damageParticleSystems.push_back(ups); - damageParticleSystemsInUse[i] = ups; - Renderer::getInstance().manageParticleSystem(ups, rsGame); - } - } - } - } - - checkCustomizedUnitParticleTriggers(); + // + // Now check if we have special pre-exisitng hp triggered particles and + // end those that should no longer display + // + // end s particles + if (damageParticleSystems.empty() == false) { + for (int i = (int)damageParticleSystems.size() - 1; i >= 0; --i) { + UnitParticleSystem *ps = damageParticleSystems[i]; + UnitParticleSystemType *pst = NULL; + int foundParticleIndexType = -2; + if (Renderer::getInstance().validateParticleSystemStillExists( + ps, rsGame) == true) { + for (std::map::iterator iterMap = + damageParticleSystemsInUse.begin(); + iterMap != damageParticleSystemsInUse.end(); ++iterMap) { + if (iterMap->second == ps) { + foundParticleIndexType = iterMap->first; + if (foundParticleIndexType >= 0) { + pst = type->damageParticleSystemTypes[foundParticleIndexType]; + break; + } + } + } + } + + if (force == true || (pst != NULL && pst->getMinmaxEnabled() == true)) { + bool stopParticle = force; + if (force == false) { + if (pst->getMinmaxIsPercent() == false) { + if (hp < pst->getMinHp() || hp > pst->getMaxHp()) { + stopParticle = true; + } + } else { + int hpPercent = (hp / type->getTotalMaxHp(&totalUpgrade) * 100); + if (hpPercent < pst->getMinHp() || hpPercent > pst->getMaxHp()) { + stopParticle = true; + } + } + } + + // printf("CHECKING to STOP customized particle trigger by HP [%d to %d + // percentbased = %d] current hp = %d stopParticle = + // %d\n",pst->getMinHp(),pst->getMaxHp(),pst->getMinmaxIsPercent(),hp,stopParticle); + + if (stopParticle == true) { + // printf("STOPPING customized particle trigger by HP [%d to %d] + // current hp = %d\n",pst->getMinHp(),pst->getMaxHp(),hp); + + damageParticleSystemsInUse.erase(foundParticleIndexType); + if (Renderer::getInstance().validateParticleSystemStillExists( + ps, rsGame) == true) { + ps->fade(); + } + damageParticleSystems.pop_back(); + } + } + } + } + + // + // Now check if we have new special hp triggered particles to display + // + // start additional particles + if (showUnitParticles && type->damageParticleSystemTypes.empty() == false && + force == false && alive == true) { + for (unsigned int i = 0; i < type->damageParticleSystemTypes.size(); ++i) { + UnitParticleSystemType *pst = type->damageParticleSystemTypes[i]; + + if (pst->getMinmaxEnabled() == true && + damageParticleSystemsInUse.find(i) == + damageParticleSystemsInUse.end()) { + bool showParticle = false; + if (pst->getMinmaxIsPercent() == false) { + if (hp >= pst->getMinHp() && hp <= pst->getMaxHp()) { + showParticle = true; + } + } else { + int hpPercent = (hp / type->getTotalMaxHp(&totalUpgrade) * 100); + if (hpPercent >= pst->getMinHp() && hpPercent <= pst->getMaxHp()) { + showParticle = true; + } + } + + // printf("CHECKING to START customized particle trigger by HP [%d to %d + // percentbased = %d] current hp = %d showParticle = + // %d\n",pst->getMinHp(),pst->getMaxHp(),pst->getMinmaxIsPercent(),hp,showParticle); + + if (showParticle == true) { + // printf("STARTING customized particle trigger by HP [%d to %d] + // current hp = %d\n",pst->getMinHp(),pst->getMaxHp(),hp); + + UnitParticleSystem *ups = new UnitParticleSystem(200); + ups->setParticleOwner(this); + ups->setParticleType(pst); + + pst->setValues(ups); + ups->setPos(getCurrVectorForParticlesystems()); + ups->setRotation(getRotation()); + setMeshPosInParticleSystem(ups); + if (getFaction()->getTexture()) { + ups->setFactionColor( + getFaction()->getTexture()->getPixmapConst()->getPixel3f(0, 0)); + } + damageParticleSystems.push_back(ups); + damageParticleSystemsInUse[i] = ups; + Renderer::getInstance().manageParticleSystem(ups, rsGame); + } + } + } + } + + checkCustomizedUnitParticleTriggers(); } void Unit::startDamageParticles() { - if(hp < type->getTotalMaxHp(&totalUpgrade) / 2 && hp > 0 && alive == true) { - //start additional particles - if( showUnitParticles && - type->damageParticleSystemTypes.empty() == false ) { - for(unsigned int i = 0; i < type->damageParticleSystemTypes.size(); ++i) { - UnitParticleSystemType *pst = type->damageParticleSystemTypes[i]; - - if(pst->getMinmaxEnabled() == false && damageParticleSystemsInUse.find(i) == damageParticleSystemsInUse.end()) { - UnitParticleSystem *ups = new UnitParticleSystem(200); - ups->setParticleOwner(this); - ups->setParticleType(pst); - - pst->setValues(ups); - ups->setPos(getCurrVectorForParticlesystems()); - ups->setRotation(getRotation()); - setMeshPosInParticleSystem(ups); - if(getFaction()->getTexture()) { - ups->setFactionColor(getFaction()->getTexture()->getPixmapConst()->getPixel3f(0,0)); - } - damageParticleSystems.push_back(ups); - damageParticleSystemsInUse[i] = ups; - Renderer::getInstance().manageParticleSystem(ups, rsGame); - } - } - } - - // start fire - if(type->getProperty(UnitType::pBurnable) && this->fire == NULL) { - FireParticleSystem *fps = new FireParticleSystem(200); - fps->setParticleOwner(this); - const Game *game = Renderer::getInstance().getGame(); - fps->setSpeed(2.5f / game->getWorld()->getUpdateFps(this->getFactionIndex())); - fps->setPos(getCurrBurnVector()); - fps->setRadius(type->getSize()/3.f); - fps->setTexture(CoreData::getInstance().getFireTexture()); - fps->setParticleSize(type->getSize()/3.f); - this->fire= fps; - fireParticleSystems.push_back(fps); - - Renderer::getInstance().manageParticleSystem(fps, rsGame); - if(showUnitParticles == true) { - // smoke - UnitParticleSystem *ups= new UnitParticleSystem(400); - ups->setParticleOwner(this); - ups->setColorNoEnergy(Vec4f(0.0f, 0.0f, 0.0f, 0.13f)); - ups->setColor(Vec4f(0.115f, 0.115f, 0.115f, 0.22f)); - ups->setPos(getCurrBurnVector()); - ups->setRotation(getRotation()); - setMeshPosInParticleSystem(ups); - ups->setBlendMode(ups->strToBlendMode("black")); - ups->setOffset(Vec3f(0,2,0)); - ups->setDirection(Vec3f(0,1,-0.2f)); - ups->setRadius(type->getSize()/3.f); - ups->setShape(::Shared::Graphics::UnitParticleSystem::sLinear); - ups->setTexture(CoreData::getInstance().getFireTexture()); - const Game *game = Renderer::getInstance().getGame(); - ups->setSpeed(2.0f / game->getWorld()->getUpdateFps(this->getFactionIndex())); - ups->setGravity(0.0004f); - ups->setEmissionRate(1); - ups->setMaxParticleEnergy(150); - ups->setSizeNoEnergy(type->getSize()*0.6f); - ups->setParticleSize(type->getSize()*0.8f); - smokeParticleSystems.push_back(ups); - //damageParticleSystemsInUse[-1] = ups; - Renderer::getInstance().manageParticleSystem(ups, rsGame); - } - } - } - - checkCustomizedParticleTriggers(false); + if (hp < type->getTotalMaxHp(&totalUpgrade) / 2 && hp > 0 && alive == true) { + // start additional particles + if (showUnitParticles && type->damageParticleSystemTypes.empty() == false) { + for (unsigned int i = 0; i < type->damageParticleSystemTypes.size(); + ++i) { + UnitParticleSystemType *pst = type->damageParticleSystemTypes[i]; + + if (pst->getMinmaxEnabled() == false && + damageParticleSystemsInUse.find(i) == + damageParticleSystemsInUse.end()) { + UnitParticleSystem *ups = new UnitParticleSystem(200); + ups->setParticleOwner(this); + ups->setParticleType(pst); + + pst->setValues(ups); + ups->setPos(getCurrVectorForParticlesystems()); + ups->setRotation(getRotation()); + setMeshPosInParticleSystem(ups); + if (getFaction()->getTexture()) { + ups->setFactionColor( + getFaction()->getTexture()->getPixmapConst()->getPixel3f(0, 0)); + } + damageParticleSystems.push_back(ups); + damageParticleSystemsInUse[i] = ups; + Renderer::getInstance().manageParticleSystem(ups, rsGame); + } + } + } + + // start fire + if (type->getProperty(UnitType::pBurnable) && this->fire == NULL) { + FireParticleSystem *fps = new FireParticleSystem(200); + fps->setParticleOwner(this); + const Game *game = Renderer::getInstance().getGame(); + fps->setSpeed(2.5f / + game->getWorld()->getUpdateFps(this->getFactionIndex())); + fps->setPos(getCurrBurnVector()); + fps->setRadius(type->getSize() / 3.f); + fps->setTexture(CoreData::getInstance().getFireTexture()); + fps->setParticleSize(type->getSize() / 3.f); + this->fire = fps; + fireParticleSystems.push_back(fps); + + Renderer::getInstance().manageParticleSystem(fps, rsGame); + if (showUnitParticles == true) { + // smoke + UnitParticleSystem *ups = new UnitParticleSystem(400); + ups->setParticleOwner(this); + ups->setColorNoEnergy(Vec4f(0.0f, 0.0f, 0.0f, 0.13f)); + ups->setColor(Vec4f(0.115f, 0.115f, 0.115f, 0.22f)); + ups->setPos(getCurrBurnVector()); + ups->setRotation(getRotation()); + setMeshPosInParticleSystem(ups); + ups->setBlendMode(ups->strToBlendMode("black")); + ups->setOffset(Vec3f(0, 2, 0)); + ups->setDirection(Vec3f(0, 1, -0.2f)); + ups->setRadius(type->getSize() / 3.f); + ups->setShape(::Shared::Graphics::UnitParticleSystem::sLinear); + ups->setTexture(CoreData::getInstance().getFireTexture()); + const Game *game = Renderer::getInstance().getGame(); + ups->setSpeed(2.0f / + game->getWorld()->getUpdateFps(this->getFactionIndex())); + ups->setGravity(0.0004f); + ups->setEmissionRate(1); + ups->setMaxParticleEnergy(150); + ups->setSizeNoEnergy(type->getSize() * 0.6f); + ups->setParticleSize(type->getSize() * 0.8f); + smokeParticleSystems.push_back(ups); + // damageParticleSystemsInUse[-1] = ups; + Renderer::getInstance().manageParticleSystem(ups, rsGame); + } + } + } + + checkCustomizedParticleTriggers(false); } void Unit::setMeetingPos(const Vec2i &meetingPos) { - this->meetingPos= meetingPos; - map->clampPos(this->meetingPos); + this->meetingPos = meetingPos; + map->clampPos(this->meetingPos); - if(map->isInside(this->meetingPos) == false || map->isInsideSurface(map->toSurfCoords(this->meetingPos)) == false) { - throw megaglest_runtime_error("#8 Invalid path position = " + this->meetingPos.getString()); - } + if (map->isInside(this->meetingPos) == false || + map->isInsideSurface(map->toSurfCoords(this->meetingPos)) == false) { + throw megaglest_runtime_error("#8 Invalid path position = " + + this->meetingPos.getString()); + } - logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__); + logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), __LINE__); } bool Unit::isMeetingPointSettable() const { - return (type != NULL ? type->getMeetingPoint() : false); + return (type != NULL ? type->getMeetingPoint() : false); } uint32 Unit::getFrameCount() const { - uint32 frameCount = 0; - //const Game *game = Renderer::getInstance().getGame(); - if(game != NULL && game->getWorld() != NULL) { - int frameCountAsInt = game->getWorld()->getFrameCount(); - if(frameCountAsInt >= 0) { - frameCount = frameCountAsInt; - } - } + uint32 frameCount = 0; + // const Game *game = Renderer::getInstance().getGame(); + if (game != NULL && game->getWorld() != NULL) { + int frameCountAsInt = game->getWorld()->getFrameCount(); + if (frameCountAsInt >= 0) { + frameCount = frameCountAsInt; + } + } - return frameCount; + return frameCount; } void Unit::exploreCells(bool forceRefresh) { - if(this->isOperative() == true) { - const Vec2i &newPos = this->getCenteredPos(); - int sightRange = this->getType()->getTotalSight(this->getTotalUpgrade()); - int teamIndex = this->getTeam(); - - if(game == NULL) { - throw megaglest_runtime_error("game == NULL"); - } - else if(game->getWorld() == NULL) { - throw megaglest_runtime_error("game->getWorld() == NULL"); - } - - // Try the local unit exploration cache - if( !forceRefresh && - cacheExploredCellsKey.first == newPos && - cacheExploredCellsKey.second == sightRange) { - game->getWorld()->exploreCells(teamIndex, cacheExploredCells); - } - else { - // Try the world exploration scan or possible cache - cacheExploredCells = game->getWorld()->exploreCells(newPos, sightRange, teamIndex, this); - - // Cache the result for this unit - cacheExploredCellsKey.first = newPos; - cacheExploredCellsKey.second = sightRange; - } - } -} - -void Unit::logSynchData(string file,int line,string source) { - logSynchDataCommon(file,line,source,false); -} -void Unit::logSynchDataThreaded(string file,int line,string source) { - logSynchDataCommon(file,line,source,true); -} -void Unit::logSynchDataCommon(string file,int line,string source,bool threadedMode) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096, - "FrameCount [%d] Unit = %d [%s][%s] pos = %s, lastPos = %s, targetPos = %s, targetVec = %s, meetingPos = %s, progress [" MG_I64_SPECIFIER "], progress2 [%d] random [%d]\nUnit Path [%s]\n", - getFrameCount(), - id, - getFullName(false).c_str(), - faction->getType()->getName(false).c_str(), - //getDesc().c_str(), - pos.getString().c_str(), - lastPos.getString().c_str(), - targetPos.getString().c_str(), - targetVec.getString().c_str(), - meetingPos.getString().c_str(), -// lastRotation, -// targetRotation, -// rotation, - progress, - progress2, - random.getLastNumber(), - (unitPath != NULL ? unitPath->toString().c_str() : "NULL")); - - if( lastSynchDataString != string(szBuf) || - lastFile != file || - lastLine != line || - lastSource != source) { - lastSynchDataString = string(szBuf); - lastFile = file; - lastSource = source; - - char szBufDataText[8096]=""; - snprintf(szBufDataText,8096,"----------------------------------- START [FRAME %d UNIT: %d - %s] ------------------------------------------------\n",getFrameCount(),this->id,this->getType()->getName(false).c_str()); - string logDataText = szBufDataText; - - snprintf(szBufDataText,8096,"[%s::%d]\n",extractFileFromDirectoryPath(file).c_str(),line); - logDataText += szBufDataText; - - if(source != "") { - snprintf(szBufDataText,8096,"%s ",source.c_str()); - logDataText += szBufDataText; - } - snprintf(szBufDataText,8096,"%s\n",szBuf); - logDataText += szBufDataText; - snprintf(szBufDataText,8096,"------------------------------------ END [FRAME %d UNIT: %d - %s] ------------------------------------------------\n",getFrameCount(),this->id,this->getType()->getName(false).c_str()); - logDataText += szBufDataText; -/* - SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"----------------------------------- START [FRAME %d UNIT: %d - %s] ------------------------------------------------\n",getFrameCount(),this->id,this->getType()->getName().c_str()); - SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"[%s::%d]\n",extractFileFromDirectoryPath(file).c_str(),line); - if(source != "") { - SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"%s ",source.c_str()); - } - SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"%s\n",szBuf); - SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"------------------------------------ END [FRAME %d UNIT: %d - %s] ------------------------------------------------\n",getFrameCount(),this->id,this->getType()->getName().c_str()); -*/ - if(threadedMode == false) { - SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"%s",logDataText.c_str()); - } - else { - this->faction->addWorldSynchThreadedLogList(logDataText); - } - } - } + if (this->isOperative() == true) { + const Vec2i &newPos = this->getCenteredPos(); + int sightRange = this->getType()->getTotalSight(this->getTotalUpgrade()); + int teamIndex = this->getTeam(); + + if (game == NULL) { + throw megaglest_runtime_error("game == NULL"); + } else if (game->getWorld() == NULL) { + throw megaglest_runtime_error("game->getWorld() == NULL"); + } + + // Try the local unit exploration cache + if (!forceRefresh && cacheExploredCellsKey.first == newPos && + cacheExploredCellsKey.second == sightRange) { + game->getWorld()->exploreCells(teamIndex, cacheExploredCells); + } else { + // Try the world exploration scan or possible cache + cacheExploredCells = + game->getWorld()->exploreCells(newPos, sightRange, teamIndex, this); + + // Cache the result for this unit + cacheExploredCellsKey.first = newPos; + cacheExploredCellsKey.second = sightRange; + } + } +} + +void Unit::logSynchData(string file, int line, string source) { + logSynchDataCommon(file, line, source, false); +} +void Unit::logSynchDataThreaded(string file, int line, string source) { + logSynchDataCommon(file, line, source, true); +} +void Unit::logSynchDataCommon(string file, int line, string source, + bool threadedMode) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == + true) { + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "FrameCount [%d] Unit = %d [%s][%s] pos = %s, lastPos = %s, targetPos " + "= %s, targetVec = %s, meetingPos = %s, progress [" MG_I64_SPECIFIER + "], progress2 [%d] random [%d]\nUnit Path [%s]\n", + getFrameCount(), id, getFullName(false).c_str(), + faction->getType()->getName(false).c_str(), + // getDesc().c_str(), + pos.getString().c_str(), lastPos.getString().c_str(), + targetPos.getString().c_str(), targetVec.getString().c_str(), + meetingPos.getString().c_str(), + // lastRotation, + // targetRotation, + // rotation, + progress, progress2, random.getLastNumber(), + (unitPath != NULL ? unitPath->toString().c_str() : "NULL")); + + if (lastSynchDataString != string(szBuf) || lastFile != file || + lastLine != line || lastSource != source) { + lastSynchDataString = string(szBuf); + lastFile = file; + lastSource = source; + + char szBufDataText[8096] = ""; + snprintf(szBufDataText, 8096, + "----------------------------------- START [FRAME %d UNIT: %d - " + "%s] ------------------------------------------------\n", + getFrameCount(), this->id, + this->getType()->getName(false).c_str()); + string logDataText = szBufDataText; + + snprintf(szBufDataText, 8096, "[%s::%d]\n", + extractFileFromDirectoryPath(file).c_str(), line); + logDataText += szBufDataText; + + if (source != "") { + snprintf(szBufDataText, 8096, "%s ", source.c_str()); + logDataText += szBufDataText; + } + snprintf(szBufDataText, 8096, "%s\n", szBuf); + logDataText += szBufDataText; + snprintf(szBufDataText, 8096, + "------------------------------------ END [FRAME %d UNIT: %d - " + "%s] ------------------------------------------------\n", + getFrameCount(), this->id, + this->getType()->getName(false).c_str()); + logDataText += szBufDataText; + /* + SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"----------------------------------- + START [FRAME %d UNIT: %d - %s] + ------------------------------------------------\n",getFrameCount(),this->id,this->getType()->getName().c_str()); + SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"[%s::%d]\n",extractFileFromDirectoryPath(file).c_str(),line); + if(source != "") { + SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"%s + ",source.c_str()); + } + SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"%s\n",szBuf); + SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,"------------------------------------ + END [FRAME %d UNIT: %d - %s] + ------------------------------------------------\n",getFrameCount(),this->id,this->getType()->getName().c_str()); + */ + if (threadedMode == false) { + SystemFlags::OutputDebug(SystemFlags::debugWorldSynch, "%s", + logDataText.c_str()); + } else { + this->faction->addWorldSynchThreadedLogList(logDataText); + } + } + } } void Unit::addBadHarvestPos(const Vec2i &value) { - //Chrono chron; - //chron.start(); - badHarvestPosList[value] = getFrameCount(); - cleanupOldBadHarvestPos(); + // Chrono chron; + // chron.start(); + badHarvestPosList[value] = getFrameCount(); + cleanupOldBadHarvestPos(); } -//void Unit::removeBadHarvestPos(const Vec2i &value) { +// void Unit::removeBadHarvestPos(const Vec2i &value) { // std::map::iterator iter = badHarvestPosList.find(value); // if(iter != badHarvestPosList.end()) { // badHarvestPosList.erase(value); // } // cleanupOldBadHarvestPos(); -//} +// } void Unit::cleanupOldBadHarvestPos() { - const unsigned int cleanupInterval = (GameConstants::updateFps * 5); - bool needToCleanup = (getFrameCount() % cleanupInterval == 0); - - //printf("========================> cleanupOldBadHarvestPos() [%d] badHarvestPosList.size [%ld] cleanupInterval [%d] getFrameCount() [%d] needToCleanup [%d]\n",getFrameCount(),badHarvestPosList.size(),cleanupInterval,getFrameCount(),needToCleanup); - - if(needToCleanup == true) { - //printf("========================> cleanupOldBadHarvestPos() [%d] badHarvestPosList.size [%ld]\n",getFrameCount(),badHarvestPosList.size()); - - std::vector purgeList; - for(std::map::iterator iter = badHarvestPosList.begin(); iter != badHarvestPosList.end(); ++iter) { - if(getFrameCount() - iter->second >= cleanupInterval) { - //printf("cleanupOldBadHarvestPos() [%d][%d]\n",getFrameCount(),iter->second); - purgeList.push_back(iter->first); - } - } - - if(purgeList.empty() == false) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"[cleaning old bad harvest targets] purgeList.size() [" MG_SIZE_T_SPECIFIER "]",purgeList.size()); - logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf); + const unsigned int cleanupInterval = (GameConstants::updateFps * 5); + bool needToCleanup = (getFrameCount() % cleanupInterval == 0); + + // printf("========================> cleanupOldBadHarvestPos() [%d] + // badHarvestPosList.size [%ld] cleanupInterval [%d] getFrameCount() [%d] + // needToCleanup + // [%d]\n",getFrameCount(),badHarvestPosList.size(),cleanupInterval,getFrameCount(),needToCleanup); + + if (needToCleanup == true) { + // printf("========================> cleanupOldBadHarvestPos() [%d] + // badHarvestPosList.size + // [%ld]\n",getFrameCount(),badHarvestPosList.size()); + + std::vector purgeList; + for (std::map::iterator iter = badHarvestPosList.begin(); + iter != badHarvestPosList.end(); ++iter) { + if (getFrameCount() - iter->second >= cleanupInterval) { + // printf("cleanupOldBadHarvestPos() + // [%d][%d]\n",getFrameCount(),iter->second); + purgeList.push_back(iter->first); + } + } - for(int i = 0; i < (int)purgeList.size(); ++i) { - const Vec2i &item = purgeList[i]; - badHarvestPosList.erase(item); - } - } - } + if (purgeList.empty() == false) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "[cleaning old bad harvest targets] purgeList.size() " + "[" MG_SIZE_T_SPECIFIER "]", + purgeList.size()); + logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(), __LINE__, + szBuf); + + for (int i = 0; i < (int)purgeList.size(); ++i) { + const Vec2i &item = purgeList[i]; + badHarvestPosList.erase(item); + } + } + } } void Unit::setLastHarvestResourceTarget(const Vec2i *pos) { - if(pos == NULL) { - lastHarvestResourceTarget.first = Vec2i(0); - //lastHarvestResourceTarget.second = 0; - } - else { - const Vec2i resourceLocation = *pos; - if(resourceLocation != lastHarvestResourceTarget.first) { - lastHarvestResourceTarget.first = resourceLocation; - - //Chrono chron; - //chron.start(); - lastHarvestResourceTarget.second = getFrameCount(); - } - else { - // If we cannot harvest for > 10 seconds tag the position - // as a bad one - const unsigned int addInterval = (GameConstants::updateFps * 5); - if(lastHarvestResourceTarget.second - getFrameCount() >= addInterval) { - //printf("-----------------------> setLastHarvestResourceTarget() [%d][%d]\n",getFrameCount(),lastHarvestResourceTarget.second); - addBadHarvestPos(resourceLocation); - } - } - } -} - -//void Unit::addCurrentTargetPathTakenCell(const Vec2i &target,const Vec2i &cell) { -// if(currentTargetPathTaken.first != target) { + if (pos == NULL) { + lastHarvestResourceTarget.first = Vec2i(0); + // lastHarvestResourceTarget.second = 0; + } else { + const Vec2i resourceLocation = *pos; + if (resourceLocation != lastHarvestResourceTarget.first) { + lastHarvestResourceTarget.first = resourceLocation; + + // Chrono chron; + // chron.start(); + lastHarvestResourceTarget.second = getFrameCount(); + } else { + // If we cannot harvest for > 10 seconds tag the position + // as a bad one + const unsigned int addInterval = (GameConstants::updateFps * 5); + if (lastHarvestResourceTarget.second - getFrameCount() >= addInterval) { + // printf("-----------------------> setLastHarvestResourceTarget() + // [%d][%d]\n",getFrameCount(),lastHarvestResourceTarget.second); + addBadHarvestPos(resourceLocation); + } + } + } +} + +// void Unit::addCurrentTargetPathTakenCell(const Vec2i &target,const Vec2i +// &cell) { if(currentTargetPathTaken.first != target) { // currentTargetPathTaken.second.clear(); // } // currentTargetPathTaken.first = target; // currentTargetPathTaken.second.push_back(cell); -//} +// } void Unit::setLastPathfindFailedFrameToCurrentFrame() { - lastPathfindFailedFrame = getFrameCount(); + lastPathfindFailedFrame = getFrameCount(); } bool Unit::isLastPathfindFailedFrameWithinCurrentFrameTolerance() const { - //static const bool enablePathfinderEnlargeMaxNodes = Config::getInstance().getBool("EnablePathfinderEnlargeMaxNodes","false"); - static const bool enablePathfinderEnlargeMaxNodes = false; - bool result = enablePathfinderEnlargeMaxNodes; - if(enablePathfinderEnlargeMaxNodes) { - const uint32 MIN_FRAME_ELAPSED_RETRY = 960; - result = (getFrameCount() - lastPathfindFailedFrame >= MIN_FRAME_ELAPSED_RETRY); - } - return result; + // static const bool enablePathfinderEnlargeMaxNodes = + // Config::getInstance().getBool("EnablePathfinderEnlargeMaxNodes","false"); + static const bool enablePathfinderEnlargeMaxNodes = false; + bool result = enablePathfinderEnlargeMaxNodes; + if (enablePathfinderEnlargeMaxNodes) { + const uint32 MIN_FRAME_ELAPSED_RETRY = 960; + result = + (getFrameCount() - lastPathfindFailedFrame >= MIN_FRAME_ELAPSED_RETRY); + } + return result; } void Unit::setLastStuckFrameToCurrentFrame() { - lastStuckFrame = getFrameCount(); + lastStuckFrame = getFrameCount(); } bool Unit::isLastStuckFrameWithinCurrentFrameTolerance(bool evalMode) { - //const int MIN_FRAME_ELAPSED_RETRY = 300; - const uint32 MAX_BLOCKED_FRAME_THRESHOLD = 25000; - uint32 MIN_FRAME_ELAPSED_RETRY = 6; - if(lastStuckFrame < MAX_BLOCKED_FRAME_THRESHOLD) { - if(evalMode == true) { - MIN_FRAME_ELAPSED_RETRY = 4; - } - else { - MIN_FRAME_ELAPSED_RETRY = random.randRange(2,6,intToStr(__LINE__)); - } - } - else { - if(evalMode == true) { - MIN_FRAME_ELAPSED_RETRY = 7; - } - else { - MIN_FRAME_ELAPSED_RETRY = random.randRange(6,8,intToStr(__LINE__)); - } - } - bool result (getFrameCount() - lastStuckFrame <= (MIN_FRAME_ELAPSED_RETRY * 100)); - return result; + // const int MIN_FRAME_ELAPSED_RETRY = 300; + const uint32 MAX_BLOCKED_FRAME_THRESHOLD = 25000; + uint32 MIN_FRAME_ELAPSED_RETRY = 6; + if (lastStuckFrame < MAX_BLOCKED_FRAME_THRESHOLD) { + if (evalMode == true) { + MIN_FRAME_ELAPSED_RETRY = 4; + } else { + MIN_FRAME_ELAPSED_RETRY = random.randRange(2, 6, intToStr(__LINE__)); + } + } else { + if (evalMode == true) { + MIN_FRAME_ELAPSED_RETRY = 7; + } else { + MIN_FRAME_ELAPSED_RETRY = random.randRange(6, 8, intToStr(__LINE__)); + } + } + bool result(getFrameCount() - lastStuckFrame <= + (MIN_FRAME_ELAPSED_RETRY * 100)); + return result; } Vec2i Unit::getPosWithCellMapSet() const { - Vec2i cellMapPos = this->getType()->getFirstOccupiedCellInCellMap(pos); - return cellMapPos; + Vec2i cellMapPos = this->getType()->getFirstOccupiedCellInCellMap(pos); + return cellMapPos; } string Unit::getUniquePickName() const { - string result = intToStr(id) + " - " + type->getName(false) + " : "; - result += pos.getString(); - return result; + string result = intToStr(id) + " - " + type->getName(false) + " : "; + result += pos.getString(); + return result; } Vec2i Unit::getPos() { - Vec2i result; + Vec2i result; - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(mutexCommands,mutexOwnerId); - result = this->pos; - safeMutex.ReleaseLock(); + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(mutexCommands, mutexOwnerId); + result = this->pos; + safeMutex.ReleaseLock(); - return result; + return result; } void Unit::clearCaches() { - cachedFow.surfPosAlphaList.clear(); - cachedFowPos = Vec2i(0,0); + cachedFow.surfPosAlphaList.clear(); + cachedFowPos = Vec2i(0, 0); - cacheExploredCells.exploredCellList.clear(); - cacheExploredCells.visibleCellList.clear(); - cacheExploredCellsKey.first = Vec2i(-1,-1); - cacheExploredCellsKey.second = -1; + cacheExploredCells.exploredCellList.clear(); + cacheExploredCells.visibleCellList.clear(); + cacheExploredCellsKey.first = Vec2i(-1, -1); + cacheExploredCellsKey.second = -1; - if(unitPath != NULL) { - unitPath->clearCaches(); - } + if (unitPath != NULL) { + unitPath->clearCaches(); + } - lastHarvestedResourcePos = Vec2i(0,0); + lastHarvestedResourcePos = Vec2i(0, 0); } bool Unit::showTranslatedTechTree() const { - return (this->game != NULL ? this->game->showTranslatedTechTree() : true); + return (this->game != NULL ? this->game->showTranslatedTechTree() : true); } string Unit::getNetworkCRCDecHpList() const { - string result = ""; - if(networkCRCDecHpList.empty() == false) { - for(unsigned int index = 0; index < networkCRCDecHpList.size(); ++index) { - result += networkCRCDecHpList[index] + " "; - } - } - return result; + string result = ""; + if (networkCRCDecHpList.empty() == false) { + for (unsigned int index = 0; index < networkCRCDecHpList.size(); ++index) { + result += networkCRCDecHpList[index] + " "; + } + } + return result; } std::string Unit::toString(bool crcMode) const { - std::string result = ""; - - result += "id = " + intToStr(this->id); - if(this->type != NULL) { - result += " name [" + this->type->getName(false) + "][" + intToStr(this->type->getId()) + "]"; - } - - if(this->faction != NULL) { - result += "\nFactionIndex = " + intToStr(this->faction->getIndex()) + "\n"; - result += "teamIndex = " + intToStr(this->faction->getTeam()) + "\n"; - result += "startLocationIndex = " + intToStr(this->faction->getStartLocationIndex()) + "\n"; - if(crcMode == false) { - result += "thisFaction = " + intToStr(this->faction->getThisFaction()) + "\n"; - result += "control = " + intToStr(this->faction->getControlType()) + "\n"; - } - if(this->faction->getType() != NULL) { - result += "factionName = " + this->faction->getType()->getName(false) + "\n"; - } - } - - result += " hp = " + intToStr(this->hp); - result += " ep = " + intToStr(this->ep); - result += " loadCount = " + intToStr(this->loadCount); - result += " deadCount = " + intToStr(this->deadCount); - result += " progress = " + intToStr(this->progress); - result += "\n"; - result += "networkCRCLogInfo = " + networkCRCLogInfo; - result += "\n"; - if(crcMode == false) { - result += " lastAnimProgress = " + intToStr(this->lastAnimProgress); - result += " animProgress = " + intToStr(this->animProgress); - result += " highlight = " + floatToStr(this->highlight,6); - } - result += " progress2 = " + intToStr(this->progress2); - result += " kills = " + intToStr(this->kills); - result += " enemyKills = " + intToStr(this->enemyKills); - result += "\n"; - - // WARNING!!! Don't access the Unit pointer in this->targetRef in this method or it causes - // a stack overflow - if(this->targetRef.getUnitId() >= 0) { - //result += " targetRef = " + this->targetRef.getUnit()->toString(); - result += " targetRef = " + intToStr(this->targetRef.getUnitId()) + " - factionIndex = " + intToStr(this->targetRef.getUnitFaction()->getIndex()); - } - - result += " currField = " + intToStr(this->currField); - result += " targetField = " + intToStr(this->targetField); - if(level != NULL) { - result += " level = " + level->getName(); - } - result += "\n"; - result += " pos = " + pos.getString(); - result += " lastPos = " + lastPos.getString(); - result += "\n"; - result += " targetPos = " + targetPos.getString(); - result += " targetVec = " + targetVec.getString(); - result += " meetingPos = " + meetingPos.getString(); - result += "\n"; - - if(crcMode == false) { - result += " lastRotation = " + floatToStr(this->lastRotation,6); - result += " targetRotation = " + floatToStr(this->targetRotation,6); - result += " rotation = " + floatToStr(this->rotation,6); - } - - if(loadType != NULL) { - result += " loadType = " + loadType->getName(); - } - - if(currSkill != NULL) { - result += " currSkill = " + currSkill->getName(); - } - result += "\n"; - - result += " toBeUndertaken = " + intToStr(this->toBeUndertaken); - result += " alive = " + intToStr(this->alive); - result += " showUnitParticles = " + intToStr(this->showUnitParticles); - - result += " totalUpgrade = " + totalUpgrade.toString(); - result += " " + this->unitPath->toString() + "\n"; - result += "\n"; - - result += "Command count = " + intToStr(commands.size()) + "\n"; - - int cmdIdx = 0; - for(Commands::const_iterator iterList = commands.begin(); iterList != commands.end(); ++iterList) { - result += " index = " + intToStr(cmdIdx) + " "; - const Command *cmd = *iterList; - if(cmd != NULL) { - result += cmd->toString(false) + "\n"; - } - cmdIdx++; - } - result += "\n"; - -// int obsIdx = 0; -// for(Observers::const_iterator iterList = observers.begin(); iterList != observers.end(); ++iterList) { -// const UnitObserver *observer = *iterList; -// if(observer != NULL) { -// } -// -// obsIdx++; -// } - - result += "\n"; - - result += "modelFacing = " + intToStr(modelFacing.asInt()) + "\n"; - - result += "retryCurrCommandCount = " + intToStr(retryCurrCommandCount) + "\n"; - - result += "screenPos = " + screenPos.getString() + "\n"; - - result += "currentUnitTitle = " + currentUnitTitle + "\n"; - - result += "inBailOutAttempt = " + intToStr(inBailOutAttempt) + "\n"; - - result += "random = " + intToStr(random.getLastNumber()) + "\n"; - if(this->random.getLastCaller() != "") { - result += "randomlastCaller = " + random.getLastCaller() + "\n"; + std::string result = ""; + + result += "id = " + intToStr(this->id); + if (this->type != NULL) { + result += " name [" + this->type->getName(false) + "][" + + intToStr(this->type->getId()) + "]"; + } + + if (this->faction != NULL) { + result += "\nFactionIndex = " + intToStr(this->faction->getIndex()) + "\n"; + result += "teamIndex = " + intToStr(this->faction->getTeam()) + "\n"; + result += "startLocationIndex = " + + intToStr(this->faction->getStartLocationIndex()) + "\n"; + if (crcMode == false) { + result += + "thisFaction = " + intToStr(this->faction->getThisFaction()) + "\n"; + result += "control = " + intToStr(this->faction->getControlType()) + "\n"; } - result += "pathFindRefreshCellCount = " + intToStr(pathFindRefreshCellCount) + "\n"; - - result += "currentPathFinderDesiredFinalPos = " + currentPathFinderDesiredFinalPos.getString() + "\n"; - - result += "lastStuckFrame = " + uIntToStr(lastStuckFrame) + "\n"; - result += "lastStuckPos = " + lastStuckPos.getString() + "\n"; + if (this->faction->getType() != NULL) { + result += + "factionName = " + this->faction->getType()->getName(false) + "\n"; + } + } + + result += " hp = " + intToStr(this->hp); + result += " ep = " + intToStr(this->ep); + result += " loadCount = " + intToStr(this->loadCount); + result += " deadCount = " + intToStr(this->deadCount); + result += " progress = " + intToStr(this->progress); + result += "\n"; + result += "networkCRCLogInfo = " + networkCRCLogInfo; + result += "\n"; + if (crcMode == false) { + result += " lastAnimProgress = " + intToStr(this->lastAnimProgress); + result += " animProgress = " + intToStr(this->animProgress); + result += " highlight = " + floatToStr(this->highlight, 6); + } + result += " progress2 = " + intToStr(this->progress2); + result += " kills = " + intToStr(this->kills); + result += " enemyKills = " + intToStr(this->enemyKills); + result += "\n"; + + // WARNING!!! Don't access the Unit pointer in this->targetRef in this method + // or it causes a stack overflow + if (this->targetRef.getUnitId() >= 0) { + // result += " targetRef = " + this->targetRef.getUnit()->toString(); + result += " targetRef = " + intToStr(this->targetRef.getUnitId()) + + " - factionIndex = " + + intToStr(this->targetRef.getUnitFaction()->getIndex()); + } + + result += " currField = " + intToStr(this->currField); + result += " targetField = " + intToStr(this->targetField); + if (level != NULL) { + result += " level = " + level->getName(); + } + result += "\n"; + result += " pos = " + pos.getString(); + result += " lastPos = " + lastPos.getString(); + result += "\n"; + result += " targetPos = " + targetPos.getString(); + result += " targetVec = " + targetVec.getString(); + result += " meetingPos = " + meetingPos.getString(); + result += "\n"; + + if (crcMode == false) { + result += " lastRotation = " + floatToStr(this->lastRotation, 6); + result += " targetRotation = " + floatToStr(this->targetRotation, 6); + result += " rotation = " + floatToStr(this->rotation, 6); + } + + if (loadType != NULL) { + result += " loadType = " + loadType->getName(); + } + + if (currSkill != NULL) { + result += " currSkill = " + currSkill->getName(); + } + result += "\n"; + + result += " toBeUndertaken = " + intToStr(this->toBeUndertaken); + result += " alive = " + intToStr(this->alive); + result += " showUnitParticles = " + intToStr(this->showUnitParticles); + + result += " totalUpgrade = " + totalUpgrade.toString(); + result += " " + this->unitPath->toString() + "\n"; + result += "\n"; + + result += "Command count = " + intToStr(commands.size()) + "\n"; + + int cmdIdx = 0; + for (Commands::const_iterator iterList = commands.begin(); + iterList != commands.end(); ++iterList) { + result += " index = " + intToStr(cmdIdx) + " "; + const Command *cmd = *iterList; + if (cmd != NULL) { + result += cmd->toString(false) + "\n"; + } + cmdIdx++; + } + result += "\n"; + + // int obsIdx = 0; + // for(Observers::const_iterator iterList = observers.begin(); iterList != + // observers.end(); ++iterList) { const UnitObserver *observer = + // *iterList; if(observer != NULL) { + // } + // + // obsIdx++; + // } + + result += "\n"; + + result += "modelFacing = " + intToStr(modelFacing.asInt()) + "\n"; + + result += "retryCurrCommandCount = " + intToStr(retryCurrCommandCount) + "\n"; + + result += "screenPos = " + screenPos.getString() + "\n"; + + result += "currentUnitTitle = " + currentUnitTitle + "\n"; + + result += "inBailOutAttempt = " + intToStr(inBailOutAttempt) + "\n"; + + result += "random = " + intToStr(random.getLastNumber()) + "\n"; + if (this->random.getLastCaller() != "") { + result += "randomlastCaller = " + random.getLastCaller() + "\n"; + } + result += + "pathFindRefreshCellCount = " + intToStr(pathFindRefreshCellCount) + "\n"; + + result += "currentPathFinderDesiredFinalPos = " + + currentPathFinderDesiredFinalPos.getString() + "\n"; + + result += "lastStuckFrame = " + uIntToStr(lastStuckFrame) + "\n"; + result += "lastStuckPos = " + lastStuckPos.getString() + "\n"; + + if (attackParticleSystems.empty() == false) { + result += "attackParticleSystems count = " + + intToStr(attackParticleSystems.size()) + "\n"; + } + if (networkCRCParticleLogInfo != "") { + result += "networkCRCParticleLogInfo = " + networkCRCParticleLogInfo + "\n"; + } + if (networkCRCDecHpList.empty() == false) { + result += "getNetworkCRCDecHpList() = " + getNetworkCRCDecHpList() + "\n"; + } + + if (getParticleInfo() != "") { + result += "getParticleInfo() = " + getParticleInfo() + "\n"; + } + for (unsigned int index = 0; index < attackParticleSystems.size(); ++index) { + ParticleSystem *ps = attackParticleSystems[index]; + if (ps != NULL && Renderer::getInstance().validateParticleSystemStillExists( + ps, rsGame) == true) { + + result += "attackParticleSystems #" + intToStr(index) + " = " + + ps->toString() + "\n"; + } + } - if(attackParticleSystems.empty() == false) { - result += "attackParticleSystems count = " + intToStr(attackParticleSystems.size()) + "\n"; - } - if(networkCRCParticleLogInfo != "") { - result += "networkCRCParticleLogInfo = " + networkCRCParticleLogInfo + "\n"; - } - if(networkCRCDecHpList.empty() == false) { - result += "getNetworkCRCDecHpList() = " + getNetworkCRCDecHpList() + "\n"; - } + return result; +} - if(getParticleInfo() != "") { - result += "getParticleInfo() = " + getParticleInfo() + "\n"; - } - for(unsigned int index = 0; index < attackParticleSystems.size(); ++index) { - ParticleSystem *ps = attackParticleSystems[index]; - if(ps != NULL && - Renderer::getInstance().validateParticleSystemStillExists(ps,rsGame) == true) { +void Unit::saveGame(XmlNode *rootNode) { + std::map mapTagReplacements; + XmlNode *unitNode = rootNode->addChild("Unit"); + + // const int id; + unitNode->addAttribute("id", intToStr(id), mapTagReplacements); + // For info purposes only + unitNode->addAttribute("name", type->getName(false), mapTagReplacements); + + // int hp; + unitNode->addAttribute("hp", intToStr(hp), mapTagReplacements); + // int ep; + unitNode->addAttribute("ep", intToStr(ep), mapTagReplacements); + // int loadCount; + unitNode->addAttribute("loadCount", intToStr(loadCount), mapTagReplacements); + // int deadCount; + unitNode->addAttribute("deadCount", intToStr(deadCount), mapTagReplacements); + // float progress; //between 0 and 1 + unitNode->addAttribute("progress", intToStr(progress), mapTagReplacements); + // float lastAnimProgress; //between 0 and 1 + unitNode->addAttribute("lastAnimProgress", intToStr(lastAnimProgress), + mapTagReplacements); + // float animProgress; //between 0 and 1 + unitNode->addAttribute("animProgress", intToStr(animProgress), + mapTagReplacements); + // float highlight; + unitNode->addAttribute("highlight", floatToStr(highlight, 6), + mapTagReplacements); + // int progress2; + unitNode->addAttribute("progress2", intToStr(progress2), mapTagReplacements); + // int kills; + unitNode->addAttribute("kills", intToStr(kills), mapTagReplacements); + // int enemyKills; + unitNode->addAttribute("enemyKills", intToStr(enemyKills), + mapTagReplacements); + // UnitReference targetRef; + targetRef.saveGame(unitNode); + // + // Field currField; + unitNode->addAttribute("currField", intToStr(currField), mapTagReplacements); + // Field targetField; + unitNode->addAttribute("targetField", intToStr(targetField), + mapTagReplacements); + // const Level *level; + if (level != NULL) { + level->saveGame(unitNode); + } + // Vec2i pos; + unitNode->addAttribute("pos", pos.getString(), mapTagReplacements); + // Vec2i lastPos; + unitNode->addAttribute("lastPos", lastPos.getString(), mapTagReplacements); + // Vec2i targetPos; //absolute target pos + unitNode->addAttribute("targetPos", targetPos.getString(), + mapTagReplacements); + // Vec3f targetVec; + unitNode->addAttribute("targetVec", targetVec.getString(), + mapTagReplacements); + // Vec2i meetingPos; + unitNode->addAttribute("meetingPos", meetingPos.getString(), + mapTagReplacements); + // + // float lastRotation; //in degrees + unitNode->addAttribute("lastRotation", floatToStr(lastRotation, 6), + mapTagReplacements); + // float targetRotation; + unitNode->addAttribute("targetRotation", floatToStr(targetRotation, 6), + mapTagReplacements); + // float rotation; + unitNode->addAttribute("rotation", floatToStr(rotation, 6), + mapTagReplacements); + // float targetRotationZ; + unitNode->addAttribute("targetRotationZ", floatToStr(targetRotationZ, 6), + mapTagReplacements); + // float targetRotationX; + unitNode->addAttribute("targetRotationX", floatToStr(targetRotationX, 6), + mapTagReplacements); + // float rotationZ; + unitNode->addAttribute("rotationZ", floatToStr(rotationZ, 6), + mapTagReplacements); + // float rotationX; + unitNode->addAttribute("rotationX", floatToStr(rotationX, 6), + mapTagReplacements); + // const UnitType *type; + unitNode->addAttribute("type", type->getName(false), mapTagReplacements); + + unitNode->addAttribute( + "preMorph_type", + (preMorph_type != NULL ? preMorph_type->getName(false) : ""), + mapTagReplacements); + + // const ResourceType *loadType; + if (loadType != NULL) { + unitNode->addAttribute("loadType", loadType->getName(), mapTagReplacements); + } + // const SkillType *currSkill; + if (currSkill != NULL) { + unitNode->addAttribute("currSkillName", currSkill->getName(), + mapTagReplacements); + unitNode->addAttribute("currSkillClass", intToStr(currSkill->getClass()), + mapTagReplacements); + } + // int lastModelIndexForCurrSkillType; + unitNode->addAttribute("lastModelIndexForCurrSkillType", + intToStr(lastModelIndexForCurrSkillType), + mapTagReplacements); + // int animationRandomCycleCount; + unitNode->addAttribute("animationRandomCycleCount", + intToStr(animationRandomCycleCount), + mapTagReplacements); + // + // bool toBeUndertaken; + unitNode->addAttribute("toBeUndertaken", intToStr(toBeUndertaken), + mapTagReplacements); + // bool alive; + unitNode->addAttribute("alive", intToStr(alive), mapTagReplacements); + // bool showUnitParticles; + unitNode->addAttribute("showUnitParticles", intToStr(showUnitParticles), + mapTagReplacements); + // Faction *faction; + // ParticleSystem *fire; + int linkFireIndex = -1; + if (this->fire != NULL && + Renderer::getInstance().validateParticleSystemStillExists( + this->fire, rsGame) == true) { + // fire->saveGame(unitNode); + bool fireInSystemList = false; + if (fireParticleSystems.empty() == false) { + for (unsigned int i = 0; i < fireParticleSystems.size(); ++i) { + ParticleSystem *ps = fireParticleSystems[i]; + if (ps == this->fire) { + linkFireIndex = i; + fireInSystemList = true; + break; + } + } + } + if (fireInSystemList == false) { + this->fire->saveGame(unitNode); + } + } + // TotalUpgrade totalUpgrade; + totalUpgrade.saveGame(unitNode); + // Map *map; + // + // UnitPathInterface *unitPath; + unitPath->saveGame(unitNode); + // WaypointPath waypointPath; + // + // Commands commands; + for (Commands::iterator it = commands.begin(); it != commands.end(); ++it) { + (*it)->saveGame(unitNode, faction); + } + // Observers observers; + // for(Observers::iterator it = observers.begin(); it != observers.end(); + // ++it) { + // (*it)->saveGame(unitNode); + //} + + // vector unitParticleSystems; + if (unitParticleSystems.empty() == false) { + XmlNode *unitParticleSystemsNode = + unitNode->addChild("unitParticleSystems"); + + for (unsigned int i = 0; i < unitParticleSystems.size(); ++i) { + UnitParticleSystem *ups = unitParticleSystems[i]; + if (ups != NULL && + Renderer::getInstance().validateParticleSystemStillExists( + ups, rsGame) == true) { + ups->saveGame(unitParticleSystemsNode); + } + } + } + // vector queuedUnitParticleSystemTypes; + if (queuedUnitParticleSystemTypes.empty() == false) { + XmlNode *queuedUnitParticleSystemTypesNode = + unitNode->addChild("queuedUnitParticleSystemTypes"); + for (unsigned int i = 0; i < queuedUnitParticleSystemTypes.size(); ++i) { + UnitParticleSystemType *upst = queuedUnitParticleSystemTypes[i]; + if (upst != NULL) { + upst->saveGame(queuedUnitParticleSystemTypesNode); + } + } + } + // UnitParticleSystems damageParticleSystems; + if (damageParticleSystems.empty() == false) { + XmlNode *damageParticleSystemsNode = + unitNode->addChild("damageParticleSystems"); + for (unsigned int i = 0; i < damageParticleSystems.size(); ++i) { + UnitParticleSystem *ups = damageParticleSystems[i]; + if (ups != NULL && + Renderer::getInstance().validateParticleSystemStillExists( + ups, rsGame) == true) { + ups->saveGame(damageParticleSystemsNode); + } + } + } + // std::map damageParticleSystemsInUse; + if (damageParticleSystemsInUse.empty() == false) { + XmlNode *damageParticleSystemsInUseNode = + unitNode->addChild("damageParticleSystemsInUse"); + + for (std::map::const_iterator iterMap = + damageParticleSystemsInUse.begin(); + iterMap != damageParticleSystemsInUse.end(); ++iterMap) { + if (iterMap->second != NULL && + Renderer::getInstance().validateParticleSystemStillExists( + iterMap->second, rsGame) == true) { + XmlNode *damageParticleSystemsInUseNode2 = + damageParticleSystemsInUseNode->addChild( + "damageParticleSystemsInUse"); + + damageParticleSystemsInUseNode2->addAttribute( + "key", intToStr(iterMap->first), mapTagReplacements); + iterMap->second->saveGame(damageParticleSystemsInUseNode2); + } + } + } - result += "attackParticleSystems #" + intToStr(index) + " = " + ps->toString() + "\n"; - } - } + // vector fireParticleSystems; + if (fireParticleSystems.empty() == false) { + XmlNode *fireParticleSystemsNode = + unitNode->addChild("fireParticleSystems"); - return result; -} + if (linkFireIndex >= 0) { + fireParticleSystemsNode->addAttribute( + "fireParticleLink", intToStr(linkFireIndex), mapTagReplacements); + } -void Unit::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *unitNode = rootNode->addChild("Unit"); - -// const int id; - unitNode->addAttribute("id",intToStr(id), mapTagReplacements); - // For info purposes only - unitNode->addAttribute("name",type->getName(false), mapTagReplacements); - -// int hp; - unitNode->addAttribute("hp",intToStr(hp), mapTagReplacements); -// int ep; - unitNode->addAttribute("ep",intToStr(ep), mapTagReplacements); -// int loadCount; - unitNode->addAttribute("loadCount",intToStr(loadCount), mapTagReplacements); -// int deadCount; - unitNode->addAttribute("deadCount",intToStr(deadCount), mapTagReplacements); -// float progress; //between 0 and 1 - unitNode->addAttribute("progress",intToStr(progress), mapTagReplacements); -// float lastAnimProgress; //between 0 and 1 - unitNode->addAttribute("lastAnimProgress",intToStr(lastAnimProgress), mapTagReplacements); -// float animProgress; //between 0 and 1 - unitNode->addAttribute("animProgress",intToStr(animProgress), mapTagReplacements); -// float highlight; - unitNode->addAttribute("highlight",floatToStr(highlight,6), mapTagReplacements); -// int progress2; - unitNode->addAttribute("progress2",intToStr(progress2), mapTagReplacements); -// int kills; - unitNode->addAttribute("kills",intToStr(kills), mapTagReplacements); -// int enemyKills; - unitNode->addAttribute("enemyKills",intToStr(enemyKills), mapTagReplacements); -// UnitReference targetRef; - targetRef.saveGame(unitNode); -// -// Field currField; - unitNode->addAttribute("currField",intToStr(currField), mapTagReplacements); -// Field targetField; - unitNode->addAttribute("targetField",intToStr(targetField), mapTagReplacements); -// const Level *level; - if(level != NULL) { - level->saveGame(unitNode); - } -// Vec2i pos; - unitNode->addAttribute("pos",pos.getString(), mapTagReplacements); -// Vec2i lastPos; - unitNode->addAttribute("lastPos",lastPos.getString(), mapTagReplacements); -// Vec2i targetPos; //absolute target pos - unitNode->addAttribute("targetPos",targetPos.getString(), mapTagReplacements); -// Vec3f targetVec; - unitNode->addAttribute("targetVec",targetVec.getString(), mapTagReplacements); -// Vec2i meetingPos; - unitNode->addAttribute("meetingPos",meetingPos.getString(), mapTagReplacements); -// -// float lastRotation; //in degrees - unitNode->addAttribute("lastRotation",floatToStr(lastRotation,6), mapTagReplacements); -// float targetRotation; - unitNode->addAttribute("targetRotation",floatToStr(targetRotation,6), mapTagReplacements); -// float rotation; - unitNode->addAttribute("rotation",floatToStr(rotation,6), mapTagReplacements); -// float targetRotationZ; - unitNode->addAttribute("targetRotationZ",floatToStr(targetRotationZ,6), mapTagReplacements); -// float targetRotationX; - unitNode->addAttribute("targetRotationX",floatToStr(targetRotationX,6), mapTagReplacements); -// float rotationZ; - unitNode->addAttribute("rotationZ",floatToStr(rotationZ,6), mapTagReplacements); -// float rotationX; - unitNode->addAttribute("rotationX",floatToStr(rotationX,6), mapTagReplacements); -// const UnitType *type; - unitNode->addAttribute("type",type->getName(false), mapTagReplacements); - - unitNode->addAttribute("preMorph_type",(preMorph_type != NULL ? preMorph_type->getName(false) : ""), mapTagReplacements); - -// const ResourceType *loadType; - if(loadType != NULL) { - unitNode->addAttribute("loadType",loadType->getName(), mapTagReplacements); - } -// const SkillType *currSkill; - if(currSkill != NULL) { - unitNode->addAttribute("currSkillName",currSkill->getName(), mapTagReplacements); - unitNode->addAttribute("currSkillClass",intToStr(currSkill->getClass()), mapTagReplacements); - } -// int lastModelIndexForCurrSkillType; - unitNode->addAttribute("lastModelIndexForCurrSkillType",intToStr(lastModelIndexForCurrSkillType), mapTagReplacements); -// int animationRandomCycleCount; - unitNode->addAttribute("animationRandomCycleCount",intToStr(animationRandomCycleCount), mapTagReplacements); -// -// bool toBeUndertaken; - unitNode->addAttribute("toBeUndertaken",intToStr(toBeUndertaken), mapTagReplacements); -// bool alive; - unitNode->addAttribute("alive",intToStr(alive), mapTagReplacements); -// bool showUnitParticles; - unitNode->addAttribute("showUnitParticles",intToStr(showUnitParticles), mapTagReplacements); -// Faction *faction; -// ParticleSystem *fire; - int linkFireIndex = -1; - if(this->fire != NULL && Renderer::getInstance().validateParticleSystemStillExists(this->fire,rsGame) == true) { - //fire->saveGame(unitNode); - bool fireInSystemList = false; - if(fireParticleSystems.empty() == false) { - for(unsigned int i = 0; i < fireParticleSystems.size(); ++i) { - ParticleSystem *ps= fireParticleSystems[i]; - if(ps == this->fire) { - linkFireIndex = i; - fireInSystemList = true; - break; - } - } - } - if(fireInSystemList == false) { - this->fire->saveGame(unitNode); - } - } -// TotalUpgrade totalUpgrade; - totalUpgrade.saveGame(unitNode); -// Map *map; -// -// UnitPathInterface *unitPath; - unitPath->saveGame(unitNode); -// WaypointPath waypointPath; -// -// Commands commands; - for(Commands::iterator it = commands.begin(); it != commands.end(); ++it) { - (*it)->saveGame(unitNode,faction); - } -// Observers observers; - //for(Observers::iterator it = observers.begin(); it != observers.end(); ++it) { - // (*it)->saveGame(unitNode); - //} - -// vector unitParticleSystems; - if(unitParticleSystems.empty() == false) { - XmlNode *unitParticleSystemsNode = unitNode->addChild("unitParticleSystems"); - - for(unsigned int i = 0; i < unitParticleSystems.size(); ++i) { - UnitParticleSystem *ups= unitParticleSystems[i]; - if(ups != NULL && Renderer::getInstance().validateParticleSystemStillExists(ups,rsGame) == true) { - ups->saveGame(unitParticleSystemsNode); - } - } - } -// vector queuedUnitParticleSystemTypes; - if(queuedUnitParticleSystemTypes.empty() == false) { - XmlNode *queuedUnitParticleSystemTypesNode = unitNode->addChild("queuedUnitParticleSystemTypes"); - for(unsigned int i = 0; i < queuedUnitParticleSystemTypes.size(); ++i) { - UnitParticleSystemType *upst= queuedUnitParticleSystemTypes[i]; - if(upst != NULL) { - upst->saveGame(queuedUnitParticleSystemTypesNode); - } - } - } -// UnitParticleSystems damageParticleSystems; - if(damageParticleSystems.empty() == false) { - XmlNode *damageParticleSystemsNode = unitNode->addChild("damageParticleSystems"); - for(unsigned int i = 0; i < damageParticleSystems.size(); ++i) { - UnitParticleSystem *ups= damageParticleSystems[i]; - if(ups != NULL && Renderer::getInstance().validateParticleSystemStillExists(ups,rsGame) == true) { - ups->saveGame(damageParticleSystemsNode); - } - } - } -// std::map damageParticleSystemsInUse; - if(damageParticleSystemsInUse.empty() == false) { - XmlNode *damageParticleSystemsInUseNode = unitNode->addChild("damageParticleSystemsInUse"); - - for(std::map::const_iterator iterMap = damageParticleSystemsInUse.begin(); - iterMap != damageParticleSystemsInUse.end(); ++iterMap) { - if(iterMap->second != NULL && Renderer::getInstance().validateParticleSystemStillExists(iterMap->second,rsGame) == true) { - XmlNode *damageParticleSystemsInUseNode2 = damageParticleSystemsInUseNode->addChild("damageParticleSystemsInUse"); - - damageParticleSystemsInUseNode2->addAttribute("key",intToStr(iterMap->first), mapTagReplacements); - iterMap->second->saveGame(damageParticleSystemsInUseNode2); - } - } - } - -// vector fireParticleSystems; - if(fireParticleSystems.empty() == false) { - XmlNode *fireParticleSystemsNode = unitNode->addChild("fireParticleSystems"); - - if(linkFireIndex >= 0) { - fireParticleSystemsNode->addAttribute("fireParticleLink",intToStr(linkFireIndex), mapTagReplacements); - } - - for(unsigned int i = 0; i < fireParticleSystems.size(); ++i) { - ParticleSystem *ps= fireParticleSystems[i]; - if(ps != NULL && Renderer::getInstance().validateParticleSystemStillExists(ps,rsGame) == true) { - ps->saveGame(fireParticleSystemsNode); - } - } - } - -// vector smokeParticleSystems; - if(smokeParticleSystems.empty() == false) { - XmlNode *smokeParticleSystemsNode = unitNode->addChild("smokeParticleSystems"); - for(unsigned int i = 0; i < smokeParticleSystems.size(); ++i) { - UnitParticleSystem *ups= smokeParticleSystems[i]; - if(ups != NULL && Renderer::getInstance().validateParticleSystemStillExists(ups,rsGame) == true) { - ups->saveGame(smokeParticleSystemsNode); - //printf("Saving smoke particles:\n[%s]\n",ups->toString().c_str()); - } - } - } - -// CardinalDir modelFacing; - unitNode->addAttribute("modelFacing",intToStr(modelFacing), mapTagReplacements); - -// std::string lastSynchDataString; - unitNode->addAttribute("lastSynchDataString",lastSynchDataString, mapTagReplacements); -// std::string lastFile; - unitNode->addAttribute("lastFile",lastFile, mapTagReplacements); -// int lastLine; - unitNode->addAttribute("lastLine",intToStr(lastLine), mapTagReplacements); -// std::string lastSource; - unitNode->addAttribute("lastSource",lastSource, mapTagReplacements); -// int lastRenderFrame; - unitNode->addAttribute("lastRenderFrame",intToStr(lastRenderFrame), mapTagReplacements); -// bool visible; - unitNode->addAttribute("visible",intToStr(visible), mapTagReplacements); -// int retryCurrCommandCount; - unitNode->addAttribute("retryCurrCommandCount",intToStr(retryCurrCommandCount), mapTagReplacements); -// Vec3f screenPos; - unitNode->addAttribute("screenPos",screenPos.getString(), mapTagReplacements); -// string currentUnitTitle; - unitNode->addAttribute("currentUnitTitle",currentUnitTitle, mapTagReplacements); -// -// bool inBailOutAttempt; - unitNode->addAttribute("inBailOutAttempt",intToStr(inBailOutAttempt), mapTagReplacements); -// //std::vector > badHarvestPosList; -// std::map badHarvestPosList; - for(std::map::const_iterator iterMap = badHarvestPosList.begin(); - iterMap != badHarvestPosList.end(); ++iterMap) { - XmlNode *badHarvestPosListNode = unitNode->addChild("badHarvestPosList"); - - badHarvestPosListNode->addAttribute("key",iterMap->first.getString(), mapTagReplacements); - badHarvestPosListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); - } - -// //time_t lastBadHarvestListPurge; -// std::pair lastHarvestResourceTarget; - XmlNode *lastHarvestResourceTargetNode = unitNode->addChild("lastHarvestResourceTarget"); - lastHarvestResourceTargetNode->addAttribute("key",lastHarvestResourceTarget.first.getString(), mapTagReplacements); - lastHarvestResourceTargetNode->addAttribute("value",intToStr(lastHarvestResourceTarget.second), mapTagReplacements); - -// //std::pair > currentTargetPathTaken; -// static Game *game; -// -// bool ignoreCheckCommand; - unitNode->addAttribute("ignoreCheckCommand",intToStr(ignoreCheckCommand), mapTagReplacements); -// uint32 lastStuckFrame; - unitNode->addAttribute("lastStuckFrame",uIntToStr(lastStuckFrame), mapTagReplacements); -// Vec2i lastStuckPos; - unitNode->addAttribute("lastStuckPos",lastStuckPos.getString(), mapTagReplacements); -// uint32 lastPathfindFailedFrame; - unitNode->addAttribute("lastPathfindFailedFrame",intToStr(lastPathfindFailedFrame), mapTagReplacements); -// Vec2i lastPathfindFailedPos; - unitNode->addAttribute("lastPathfindFailedPos",lastPathfindFailedPos.getString(), mapTagReplacements); -// bool usePathfinderExtendedMaxNodes; - unitNode->addAttribute("usePathfinderExtendedMaxNodes",intToStr(usePathfinderExtendedMaxNodes), mapTagReplacements); -// int maxQueuedCommandDisplayCount; - unitNode->addAttribute("maxQueuedCommandDisplayCount",intToStr(maxQueuedCommandDisplayCount), mapTagReplacements); -// UnitAttackBoostEffectOriginator currentAttackBoostOriginatorEffect; - currentAttackBoostOriginatorEffect.saveGame(unitNode); -// std::vector currentAttackBoostEffects; - for(unsigned int i = 0; i < currentAttackBoostEffects.size(); ++i) { - UnitAttackBoostEffect *uabe= currentAttackBoostEffects[i]; - if(uabe != NULL) { - uabe->saveGame(unitNode); - } - } - -// Mutex *mutexCommands; -// -// //static Mutex mutexDeletedUnits; -// //static std::map deletedUnits; -// -// bool changedActiveCommand; - unitNode->addAttribute("changedActiveCommand",intToStr(changedActiveCommand), mapTagReplacements); -// int lastAttackerUnitId; - unitNode->addAttribute("lastAttackerUnitId",intToStr(lastAttackerUnitId), mapTagReplacements); -// int lastAttackedUnitId; - unitNode->addAttribute("lastAttackedUnitId",intToStr(lastAttackedUnitId), mapTagReplacements); -// CauseOfDeathType causeOfDeath; - unitNode->addAttribute("causeOfDeath",intToStr(causeOfDeath), mapTagReplacements); - - //pathfindFailedConsecutiveFrameCount - unitNode->addAttribute("pathfindFailedConsecutiveFrameCount",intToStr(pathfindFailedConsecutiveFrameCount), mapTagReplacements); - - unitNode->addAttribute("currentPathFinderDesiredFinalPos",currentPathFinderDesiredFinalPos.getString(), mapTagReplacements); - - unitNode->addAttribute("random",intToStr(random.getLastNumber()), mapTagReplacements); - unitNode->addAttribute("pathFindRefreshCellCount",intToStr(pathFindRefreshCellCount), mapTagReplacements); -} - -Unit * Unit::loadGame(const XmlNode *rootNode, GameSettings *settings, Faction *faction, World *world) { - const XmlNode *unitNode = rootNode; - - int newUnitId = unitNode->getAttribute("id")->getIntValue(); - Vec2i newUnitPos = Vec2i::strToVec2(unitNode->getAttribute("pos")->getValue()); - string newUnitType = unitNode->getAttribute("type")->getValue(); - const UnitType *ut = faction->getType()->getUnitType(newUnitType); - CardinalDir newModelFacing = static_cast(unitNode->getAttribute("modelFacing")->getIntValue()); - -// Unit *result = new Unit(int id, UnitPathInterface *unitpath, const Vec2i &pos, -// const UnitType *type, Faction *faction, Map *map, CardinalDir placeFacing) : BaseColorPickEntity(), id(id) { - - UnitPathInterface *newpath = NULL; - switch(settings->getPathFinderType()) { - case pfBasic: - newpath = new UnitPathBasic(); - break; - default: - throw megaglest_runtime_error("detected unsupported pathfinder type!"); - } - - newpath->loadGame(unitNode); - //Unit *result = new Unit(getNextUnitId(f), newpath, Vec2i(0), ut, f, &map, CardinalDir::NORTH); - //Unit(int id, UnitPathInterface *path, const Vec2i &pos, const UnitType *type, Faction *faction, Map *map, CardinalDir placeFacing); - Unit *result = new Unit(newUnitId, newpath, newUnitPos, ut, faction, world->getMapPtr(), newModelFacing); - - if(unitNode->hasAttribute("preMorph_name") == true) { - string newUnitType_preMorph = unitNode->getAttribute("preMorph_name")->getValue(); - const UnitType *ut_premorph = faction->getType()->getUnitType(newUnitType_preMorph); - result->preMorph_type = ut_premorph; - } - - result->lastRotation = unitNode->getAttribute("lastRotation")->getFloatValue(); - result->targetRotation = unitNode->getAttribute("targetRotation")->getFloatValue(); - result->rotation = unitNode->getAttribute("rotation")->getFloatValue(); - - //world->placeUnitAtLocation(newUnitPos, generationArea, unit, true); - //result->setPos(newUnitPos); - //Vec2i meetingPos = newUnitPos-Vec2i(1); - //result->setMeetingPos(meetingPos); - result->pos = newUnitPos; - result->lastPos = Vec2i::strToVec2(unitNode->getAttribute("lastPos")->getValue()); - result->meetingPos = Vec2i::strToVec2(unitNode->getAttribute("meetingPos")->getValue()); - // Attempt to improve performance - //result->exploreCells(); - //result->calculateFogOfWarRadius(); - // -------------------------- - - result->hp = unitNode->getAttribute("hp")->getIntValue(); -// int ep; - result->ep = unitNode->getAttribute("ep")->getIntValue(); -// int loadCount; - result->loadCount = unitNode->getAttribute("loadCount")->getIntValue(); -// int deadCount; - result->deadCount = unitNode->getAttribute("deadCount")->getIntValue(); -// float progress; //between 0 and 1 - try { - result->progress = unitNode->getAttribute("progress")->getIntValue(); - } + for (unsigned int i = 0; i < fireParticleSystems.size(); ++i) { + ParticleSystem *ps = fireParticleSystems[i]; + if (ps != NULL && + Renderer::getInstance().validateParticleSystemStillExists( + ps, rsGame) == true) { + ps->saveGame(fireParticleSystemsNode); + } + } + } + + // vector smokeParticleSystems; + if (smokeParticleSystems.empty() == false) { + XmlNode *smokeParticleSystemsNode = + unitNode->addChild("smokeParticleSystems"); + for (unsigned int i = 0; i < smokeParticleSystems.size(); ++i) { + UnitParticleSystem *ups = smokeParticleSystems[i]; + if (ups != NULL && + Renderer::getInstance().validateParticleSystemStillExists( + ups, rsGame) == true) { + ups->saveGame(smokeParticleSystemsNode); + // printf("Saving smoke particles:\n[%s]\n",ups->toString().c_str()); + } + } + } + + // CardinalDir modelFacing; + unitNode->addAttribute("modelFacing", intToStr(modelFacing), + mapTagReplacements); + + // std::string lastSynchDataString; + unitNode->addAttribute("lastSynchDataString", lastSynchDataString, + mapTagReplacements); + // std::string lastFile; + unitNode->addAttribute("lastFile", lastFile, mapTagReplacements); + // int lastLine; + unitNode->addAttribute("lastLine", intToStr(lastLine), mapTagReplacements); + // std::string lastSource; + unitNode->addAttribute("lastSource", lastSource, mapTagReplacements); + // int lastRenderFrame; + unitNode->addAttribute("lastRenderFrame", intToStr(lastRenderFrame), + mapTagReplacements); + // bool visible; + unitNode->addAttribute("visible", intToStr(visible), mapTagReplacements); + // int retryCurrCommandCount; + unitNode->addAttribute("retryCurrCommandCount", + intToStr(retryCurrCommandCount), mapTagReplacements); + // Vec3f screenPos; + unitNode->addAttribute("screenPos", screenPos.getString(), + mapTagReplacements); + // string currentUnitTitle; + unitNode->addAttribute("currentUnitTitle", currentUnitTitle, + mapTagReplacements); + // + // bool inBailOutAttempt; + unitNode->addAttribute("inBailOutAttempt", intToStr(inBailOutAttempt), + mapTagReplacements); + // //std::vector > badHarvestPosList; + // std::map badHarvestPosList; + for (std::map::const_iterator iterMap = badHarvestPosList.begin(); + iterMap != badHarvestPosList.end(); ++iterMap) { + XmlNode *badHarvestPosListNode = unitNode->addChild("badHarvestPosList"); + + badHarvestPosListNode->addAttribute("key", iterMap->first.getString(), + mapTagReplacements); + badHarvestPosListNode->addAttribute("value", intToStr(iterMap->second), + mapTagReplacements); + } + + // //time_t lastBadHarvestListPurge; + // std::pair lastHarvestResourceTarget; + XmlNode *lastHarvestResourceTargetNode = + unitNode->addChild("lastHarvestResourceTarget"); + lastHarvestResourceTargetNode->addAttribute( + "key", lastHarvestResourceTarget.first.getString(), mapTagReplacements); + lastHarvestResourceTargetNode->addAttribute( + "value", intToStr(lastHarvestResourceTarget.second), mapTagReplacements); + + // //std::pair > currentTargetPathTaken; + // static Game *game; + // + // bool ignoreCheckCommand; + unitNode->addAttribute("ignoreCheckCommand", intToStr(ignoreCheckCommand), + mapTagReplacements); + // uint32 lastStuckFrame; + unitNode->addAttribute("lastStuckFrame", uIntToStr(lastStuckFrame), + mapTagReplacements); + // Vec2i lastStuckPos; + unitNode->addAttribute("lastStuckPos", lastStuckPos.getString(), + mapTagReplacements); + // uint32 lastPathfindFailedFrame; + unitNode->addAttribute("lastPathfindFailedFrame", + intToStr(lastPathfindFailedFrame), mapTagReplacements); + // Vec2i lastPathfindFailedPos; + unitNode->addAttribute("lastPathfindFailedPos", + lastPathfindFailedPos.getString(), mapTagReplacements); + // bool usePathfinderExtendedMaxNodes; + unitNode->addAttribute("usePathfinderExtendedMaxNodes", + intToStr(usePathfinderExtendedMaxNodes), + mapTagReplacements); + // int maxQueuedCommandDisplayCount; + unitNode->addAttribute("maxQueuedCommandDisplayCount", + intToStr(maxQueuedCommandDisplayCount), + mapTagReplacements); + // UnitAttackBoostEffectOriginator currentAttackBoostOriginatorEffect; + currentAttackBoostOriginatorEffect.saveGame(unitNode); + // std::vector currentAttackBoostEffects; + for (unsigned int i = 0; i < currentAttackBoostEffects.size(); ++i) { + UnitAttackBoostEffect *uabe = currentAttackBoostEffects[i]; + if (uabe != NULL) { + uabe->saveGame(unitNode); + } + } + + // Mutex *mutexCommands; + // + // //static Mutex mutexDeletedUnits; + // //static std::map deletedUnits; + // + // bool changedActiveCommand; + unitNode->addAttribute("changedActiveCommand", intToStr(changedActiveCommand), + mapTagReplacements); + // int lastAttackerUnitId; + unitNode->addAttribute("lastAttackerUnitId", intToStr(lastAttackerUnitId), + mapTagReplacements); + // int lastAttackedUnitId; + unitNode->addAttribute("lastAttackedUnitId", intToStr(lastAttackedUnitId), + mapTagReplacements); + // CauseOfDeathType causeOfDeath; + unitNode->addAttribute("causeOfDeath", intToStr(causeOfDeath), + mapTagReplacements); + + // pathfindFailedConsecutiveFrameCount + unitNode->addAttribute("pathfindFailedConsecutiveFrameCount", + intToStr(pathfindFailedConsecutiveFrameCount), + mapTagReplacements); + + unitNode->addAttribute("currentPathFinderDesiredFinalPos", + currentPathFinderDesiredFinalPos.getString(), + mapTagReplacements); + + unitNode->addAttribute("random", intToStr(random.getLastNumber()), + mapTagReplacements); + unitNode->addAttribute("pathFindRefreshCellCount", + intToStr(pathFindRefreshCellCount), + mapTagReplacements); +} + +Unit *Unit::loadGame(const XmlNode *rootNode, GameSettings *settings, + Faction *faction, World *world) { + const XmlNode *unitNode = rootNode; + + int newUnitId = unitNode->getAttribute("id")->getIntValue(); + Vec2i newUnitPos = + Vec2i::strToVec2(unitNode->getAttribute("pos")->getValue()); + string newUnitType = unitNode->getAttribute("type")->getValue(); + const UnitType *ut = faction->getType()->getUnitType(newUnitType); + CardinalDir newModelFacing = static_cast( + unitNode->getAttribute("modelFacing")->getIntValue()); + + // Unit *result = new Unit(int id, UnitPathInterface *unitpath, const Vec2i + //&pos, const UnitType *type, Faction *faction, Map *map, + //CardinalDir placeFacing) : BaseColorPickEntity(), id(id) { + + UnitPathInterface *newpath = NULL; + switch (settings->getPathFinderType()) { + case pfBasic: + newpath = new UnitPathBasic(); + break; + default: + throw megaglest_runtime_error("detected unsupported pathfinder type!"); + } + + newpath->loadGame(unitNode); + // Unit *result = new Unit(getNextUnitId(f), newpath, Vec2i(0), ut, f, &map, + // CardinalDir::NORTH); Unit(int id, UnitPathInterface *path, const Vec2i + // &pos, const UnitType *type, Faction *faction, Map *map, CardinalDir + // placeFacing); + Unit *result = new Unit(newUnitId, newpath, newUnitPos, ut, faction, + world->getMapPtr(), newModelFacing); + + if (unitNode->hasAttribute("preMorph_name") == true) { + string newUnitType_preMorph = + unitNode->getAttribute("preMorph_name")->getValue(); + const UnitType *ut_premorph = + faction->getType()->getUnitType(newUnitType_preMorph); + result->preMorph_type = ut_premorph; + } + + result->lastRotation = + unitNode->getAttribute("lastRotation")->getFloatValue(); + result->targetRotation = + unitNode->getAttribute("targetRotation")->getFloatValue(); + result->rotation = unitNode->getAttribute("rotation")->getFloatValue(); + + // world->placeUnitAtLocation(newUnitPos, generationArea, unit, true); + // result->setPos(newUnitPos); + // Vec2i meetingPos = newUnitPos-Vec2i(1); + // result->setMeetingPos(meetingPos); + result->pos = newUnitPos; + result->lastPos = + Vec2i::strToVec2(unitNode->getAttribute("lastPos")->getValue()); + result->meetingPos = + Vec2i::strToVec2(unitNode->getAttribute("meetingPos")->getValue()); + // Attempt to improve performance + // result->exploreCells(); + // result->calculateFogOfWarRadius(); + // -------------------------- + + result->hp = unitNode->getAttribute("hp")->getIntValue(); + // int ep; + result->ep = unitNode->getAttribute("ep")->getIntValue(); + // int loadCount; + result->loadCount = unitNode->getAttribute("loadCount")->getIntValue(); + // int deadCount; + result->deadCount = unitNode->getAttribute("deadCount")->getIntValue(); + // float progress; //between 0 and 1 + try { + result->progress = unitNode->getAttribute("progress")->getIntValue(); + } #ifdef WIN32 - catch(const exception &) { + catch (const exception &) { #else - catch(const exception &ex) { + catch (const exception &ex) { #endif - result->progress = unitNode->getAttribute("progress")->getFloatValue(); - } -// float lastAnimProgress; //between 0 and 1 - try { - result->lastAnimProgress = unitNode->getAttribute("lastAnimProgress")->getIntValue(); - } + result->progress = unitNode->getAttribute("progress")->getFloatValue(); + } + // float lastAnimProgress; //between 0 and 1 + try { + result->lastAnimProgress = + unitNode->getAttribute("lastAnimProgress")->getIntValue(); + } #ifdef WIN32 - catch(const exception &) { + catch (const exception &) { #else - catch(const exception &ex) { + catch (const exception &ex) { #endif - result->lastAnimProgress = unitNode->getAttribute("lastAnimProgress")->getFloatValue(); - } - -// float animProgress; //between 0 and 1 - try { - result->animProgress = unitNode->getAttribute("animProgress")->getIntValue(); - } + result->lastAnimProgress = + unitNode->getAttribute("lastAnimProgress")->getFloatValue(); + } + + // float animProgress; //between 0 and 1 + try { + result->animProgress = + unitNode->getAttribute("animProgress")->getIntValue(); + } #ifdef WIN32 - catch(const exception &) { + catch (const exception &) { #else - catch(const exception &ex) { + catch (const exception &ex) { #endif - result->animProgress = unitNode->getAttribute("animProgress")->getFloatValue(); - } - -// float highlight; - result->highlight = unitNode->getAttribute("highlight")->getFloatValue(); -// int progress2; - result->progress2 = unitNode->getAttribute("progress2")->getIntValue(); -// int kills; - result->kills = unitNode->getAttribute("kills")->getIntValue(); -// int enemyKills; - result->enemyKills = unitNode->getAttribute("enemyKills")->getIntValue(); -// UnitReference targetRef; -// targetRef.saveGame(unitNode); - result->targetRef.loadGame(unitNode,world); -// -// Field currField; - result->currField = static_cast(unitNode->getAttribute("currField")->getIntValue()); -// Field targetField; - result->targetField = static_cast(unitNode->getAttribute("targetField")->getIntValue()); -// const Level *level; -// if(level != NULL) { -// level->saveGame(unitNode); -// } - result->level = Level::loadGame(unitNode,ut); -// Vec2i pos; - result->pos = Vec2i::strToVec2(unitNode->getAttribute("pos")->getValue()); -// Vec2i lastPos; - result->lastPos = Vec2i::strToVec2(unitNode->getAttribute("lastPos")->getValue()); -// Vec2i targetPos; //absolute target pos - result->targetPos = Vec2i::strToVec2(unitNode->getAttribute("targetPos")->getValue()); -// Vec3f targetVec; - result->targetVec = Vec3f::strToVec3(unitNode->getAttribute("targetVec")->getValue()); -// Vec2i meetingPos; - result->meetingPos = Vec2i::strToVec2(unitNode->getAttribute("meetingPos")->getValue()); -// -// float lastRotation; //in degrees - result->lastRotation = unitNode->getAttribute("lastRotation")->getFloatValue(); -// float targetRotation; - result->targetRotation = unitNode->getAttribute("targetRotation")->getFloatValue(); -// float rotation; - result->rotation = unitNode->getAttribute("rotation")->getFloatValue(); -// float targetRotationZ; - result->targetRotationZ = unitNode->getAttribute("targetRotationZ")->getFloatValue(); -// float targetRotationX; - result->targetRotationX = unitNode->getAttribute("targetRotationX")->getFloatValue(); -// float rotationZ; - result->rotationZ = unitNode->getAttribute("rotationZ")->getFloatValue(); -// float rotationX; - result->rotationX = unitNode->getAttribute("rotationX")->getFloatValue(); -// const UnitType *type; -// unitNode->addAttribute("type",type->getName(), mapTagReplacements); -// const ResourceType *loadType; -// if(loadType != NULL) { -// unitNode->addAttribute("loadType",loadType->getName(), mapTagReplacements); -// } - if(unitNode->hasAttribute("loadType") == true) { - string loadTypeName = unitNode->getAttribute("loadType")->getValue(); - result->loadType = world->getTechTree()->getResourceType(loadTypeName); - } -// const SkillType *currSkill; -// if(currSkill != NULL) { -// unitNode->addAttribute("currSkill",currSkill->getName(), mapTagReplacements); -// } - if(unitNode->hasAttribute("currSkillName") == true) { - string skillTypeName = unitNode->getAttribute("currSkillName")->getValue(); - SkillClass skillClass = static_cast(unitNode->getAttribute("currSkillClass")->getIntValue()); - result->currSkill = ut->getSkillType(skillTypeName,skillClass); - int tempProgress2 = result->progress2; // setCurrSkill overwrites progress2 - result->setCurrSkill(result->currSkill); - result->progress2 = tempProgress2; // restore it - } - -// int lastModelIndexForCurrSkillType; - result->lastModelIndexForCurrSkillType = unitNode->getAttribute("lastModelIndexForCurrSkillType")->getIntValue(); -// int animationRandomCycleCount; - result->animationRandomCycleCount = unitNode->getAttribute("animationRandomCycleCount")->getIntValue(); -// -// bool toBeUndertaken; - result->toBeUndertaken = unitNode->getAttribute("toBeUndertaken")->getIntValue() != 0; -// bool alive; - result->setAlive(unitNode->getAttribute("alive")->getIntValue() != 0); -// bool showUnitParticles; - result->showUnitParticles = unitNode->getAttribute("showUnitParticles")->getIntValue() != 0; -// Faction *faction; -// ParticleSystem *fire; -// if(fire != NULL) { -// fire->saveGame(unitNode); -// } - if(unitNode->hasChild("FireParticleSystem") == true) { - XmlNode *fireNode = unitNode->getChild("FireParticleSystem"); - result->fire = new FireParticleSystem(); - result->fire->setParticleOwner(result); - result->fire->loadGame(fireNode); - //result->fire->setTexture(CoreData::getInstance().getFireTexture()); - result->fireParticleSystems.push_back(result->fire); - - //printf("Load MAIN fire particle result->fire = %p\n",result->fire); - - Renderer::getInstance().addToDeferredParticleSystemList(make_pair(result->fire, rsGame)); - } - -// TotalUpgrade totalUpgrade; - result->totalUpgrade.loadGame(unitNode); -// Map *map; -// -// UnitPathInterface *unitPath; -// unitPath->saveGame(unitNode); -// WaypointPath waypointPath; -// -// Commands commands; -// for(Commands::iterator it = commands.begin(); it != commands.end(); ++it) { -// (*it)->saveGame(unitNode); -// } - vector commandNodeList = unitNode->getChildList("Command"); - for(unsigned int i = 0; i < commandNodeList.size(); ++i) { - XmlNode *node = commandNodeList[i]; - Command *command = Command::loadGame(node,ut,world); - - static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(result->mutexCommands,mutexOwnerId); - result->commands.push_back(command); - safeMutex.ReleaseLock(); - } -// Observers observers; - //for(Observers::iterator it = observers.begin(); it != observers.end(); ++it) { - // (*it)->saveGame(unitNode); - //} - -// vector unitParticleSystems; -// for(unsigned int i = 0; i < unitParticleSystems.size(); ++i) { -// UnitParticleSystem *ups= unitParticleSystems[i]; -// ups->saveGame(unitNode); -// } - if(unitNode->hasChild("unitParticleSystems") == true) { - XmlNode *unitParticleSystemsNode = unitNode->getChild("unitParticleSystems"); - vector unitParticleSystemNodeList = unitParticleSystemsNode->getChildList("UnitParticleSystem"); - for(unsigned int i = 0; i < unitParticleSystemNodeList.size(); ++i) { - XmlNode *node = unitParticleSystemNodeList[i]; - - UnitParticleSystem *ups = new UnitParticleSystem(); - ups->setParticleOwner(result); - ups->loadGame(node); - result->unitParticleSystems.push_back(ups); - - //Renderer::getInstance().manageParticleSystem(result->fire, rsGame); - Renderer::getInstance().addToDeferredParticleSystemList(make_pair(ups, rsGame)); - } - } - -// vector queuedUnitParticleSystemTypes; -// for(unsigned int i = 0; i < queuedUnitParticleSystemTypes.size(); ++i) { -// UnitParticleSystemType *upst= queuedUnitParticleSystemTypes[i]; -// upst->saveGame(unitNode); -// } - -// UnitParticleSystems damageParticleSystems; -// for(unsigned int i = 0; i < damageParticleSystems.size(); ++i) { -// UnitParticleSystem *ups= damageParticleSystems[i]; -// ups->saveGame(unitNode); -// } - if(unitNode->hasChild("damageParticleSystems") == true) { - XmlNode *damageParticleSystemsNode = unitNode->getChild("damageParticleSystems"); - vector unitParticleSystemNodeList = damageParticleSystemsNode->getChildList("UnitParticleSystem"); - for(unsigned int i = 0; i < unitParticleSystemNodeList.size(); ++i) { - XmlNode *node = unitParticleSystemNodeList[i]; - - UnitParticleSystem *ups = new UnitParticleSystem(); - ups->setParticleOwner(result); - ups->loadGame(node); - result->damageParticleSystems.push_back(ups); - result->damageParticleSystemsInUse[i]=ups; - - //Renderer::getInstance().manageParticleSystem(result->fire, rsGame); - Renderer::getInstance().addToDeferredParticleSystemList(make_pair(ups, rsGame)); - } - } - -// std::map damageParticleSystemsInUse; -// for(std::map::const_iterator iterMap = damageParticleSystemsInUse.begin(); -// iterMap != damageParticleSystemsInUse.end(); ++iterMap) { -// XmlNode *damageParticleSystemsInUseNode = unitNode->addChild("damageParticleSystemsInUse"); -// -// damageParticleSystemsInUseNode->addAttribute("key",intToStr(iterMap->first), mapTagReplacements); -// iterMap->second->saveGame(damageParticleSystemsInUseNode); -// } -// if(unitNode->hasChild("damageParticleSystemsInUse") == true) { -// XmlNode *damageParticleSystemsInUseNode = unitNode->getChild("damageParticleSystemsInUse"); -// vector damageParticleSystemsInUseNode2 = damageParticleSystemsInUseNode->getChildList("damageParticleSystemsInUse"); -// for(unsigned int i = 0; i < damageParticleSystemsInUseNode2.size(); ++i) { -// XmlNode *d2Node = damageParticleSystemsInUseNode2[i]; -// -// vector unitParticleSystemNodeList = damageParticleSystemsInUseNode->getChildList("UnitParticleSystem"); -// for(unsigned int i = 0; i < unitParticleSystemNodeList.size(); ++i) { -// XmlNode *node = unitParticleSystemNodeList[i]; -// -// UnitParticleSystem *ups = new UnitParticleSystem(); -// ups->loadGame(node); -// result->unitParticleSystems.push_back(ups); -// -// //Renderer::getInstance().manageParticleSystem(result->fire, rsGame); -// Renderer::getInstance().addToDeferredParticleSystemList(make_pair(ups, rsGame)); -// } -// -// } - -// vector fireParticleSystems; -// for(unsigned int i = 0; i < fireParticleSystems.size(); ++i) { -// ParticleSystem *ps= fireParticleSystems[i]; -// ps->saveGame(unitNode); -// } - if(unitNode->hasChild("fireParticleSystems") == true) { - XmlNode *fireParticleSystemsNode = unitNode->getChild("fireParticleSystems"); - - int linkFireIndex = -1; - if(fireParticleSystemsNode->hasAttribute("fireParticleLink") == true) { - linkFireIndex = fireParticleSystemsNode->getAttribute("fireParticleLink")->getIntValue(); - } - - vector unitParticleSystemNodeList = fireParticleSystemsNode->getChildList("FireParticleSystem"); - for(int i = 0; i < (int)unitParticleSystemNodeList.size(); ++i) { - XmlNode *node = unitParticleSystemNodeList[i]; - - if(result->fire == NULL || linkFireIndex != i) { - FireParticleSystem *ups = new FireParticleSystem(); - ups->setParticleOwner(result); - ups->loadGame(node); - //ups->setTexture(CoreData::getInstance().getFireTexture()); - result->fireParticleSystems.push_back(ups); - - //printf("Load fire particle i = %d linkFireIndex = %d result->fire = %p ups = %p\n",i,linkFireIndex,result->fire,ups); - - if(result->fire == NULL && linkFireIndex >= 0 && linkFireIndex == i) { - result->fire = ups; - } - Renderer::getInstance().addToDeferredParticleSystemList(make_pair(ups, rsGame)); - } - } - } - -// vector smokeParticleSystems; -// for(unsigned int i = 0; i < smokeParticleSystems.size(); ++i) { -// UnitParticleSystem *ups= smokeParticleSystems[i]; -// ups->saveGame(unitNode); -// } - if(unitNode->hasChild("smokeParticleSystems") == true) { - XmlNode *smokeParticleSystemsNode = unitNode->getChild("smokeParticleSystems"); - vector unitParticleSystemNodeList = smokeParticleSystemsNode->getChildList("UnitParticleSystem"); - for(unsigned int i = 0; i < unitParticleSystemNodeList.size(); ++i) { - XmlNode *node = unitParticleSystemNodeList[i]; - -// printf("Load Smoke particle i = %d\n",i); - UnitParticleSystem *ups = new UnitParticleSystem(); - ups->setParticleOwner(result); - ups->loadGame(node); - //ups->setTexture(CoreData::getInstance().getFireTexture()); - result->smokeParticleSystems.push_back(ups); - - Renderer::getInstance().addToDeferredParticleSystemList(make_pair(ups, rsGame)); - - //printf("Loading smoke particles:\n[%s]\n",ups->toString().c_str()); - } - } - -// CardinalDir modelFacing; -// unitNode->addAttribute("modelFacing",intToStr(modelFacing), mapTagReplacements); - -// std::string lastSynchDataString; -// unitNode->addAttribute("lastSynchDataString",lastSynchDataString, mapTagReplacements); -// std::string lastFile; -// unitNode->addAttribute("lastFile",lastFile, mapTagReplacements); -// int lastLine; -// unitNode->addAttribute("lastLine",intToStr(lastLine), mapTagReplacements); -// std::string lastSource; -// unitNode->addAttribute("lastSource",lastSource, mapTagReplacements); -// int lastRenderFrame; - result->lastRenderFrame = unitNode->getAttribute("lastRenderFrame")->getIntValue(); -// bool visible; - result->visible = unitNode->getAttribute("visible")->getIntValue() != 0; -// int retryCurrCommandCount; - result->retryCurrCommandCount = unitNode->getAttribute("retryCurrCommandCount")->getIntValue(); -// Vec3f screenPos; - result->screenPos = Vec3f::strToVec3(unitNode->getAttribute("screenPos")->getValue()); -// string currentUnitTitle; - result->currentUnitTitle = unitNode->getAttribute("currentUnitTitle")->getValue(); -// -// bool inBailOutAttempt; - result->inBailOutAttempt = unitNode->getAttribute("inBailOutAttempt")->getIntValue() != 0; -// //std::vector > badHarvestPosList; -// std::map badHarvestPosList; -// for(std::map::const_iterator iterMap = badHarvestPosList.begin(); -// iterMap != badHarvestPosList.end(); ++iterMap) { -// XmlNode *badHarvestPosListNode = unitNode->addChild("badHarvestPosList"); -// -// badHarvestPosListNode->addAttribute("key",iterMap->first.getString(), mapTagReplacements); -// badHarvestPosListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); -// } - -// //time_t lastBadHarvestListPurge; -// std::pair lastHarvestResourceTarget; - const XmlNode *lastHarvestResourceTargetNode = unitNode->getChild("lastHarvestResourceTarget"); -// lastHarvestResourceTargetNode->addAttribute("key",lastHarvestResourceTarget.first.getString(), mapTagReplacements); -// lastHarvestResourceTargetNode->addAttribute("value",intToStr(lastHarvestResourceTarget.second), mapTagReplacements); - - result->lastHarvestResourceTarget = - make_pair(Vec2i::strToVec2(lastHarvestResourceTargetNode->getAttribute("key")->getValue()), - lastHarvestResourceTargetNode->getAttribute("value")->getIntValue()); - -// //std::pair > currentTargetPathTaken; -// static Game *game; -// -// bool ignoreCheckCommand; - result->ignoreCheckCommand = unitNode->getAttribute("ignoreCheckCommand")->getIntValue() != 0; -// uint32 lastStuckFrame; - result->lastStuckFrame = unitNode->getAttribute("lastStuckFrame")->getIntValue(); -// Vec2i lastStuckPos; - result->lastStuckPos = Vec2i::strToVec2(unitNode->getAttribute("lastStuckPos")->getValue()); -// uint32 lastPathfindFailedFrame; - result->lastPathfindFailedFrame = unitNode->getAttribute("lastPathfindFailedFrame")->getIntValue(); -// Vec2i lastPathfindFailedPos; - result->lastPathfindFailedPos = Vec2i::strToVec2(unitNode->getAttribute("lastPathfindFailedPos")->getValue()); -// bool usePathfinderExtendedMaxNodes; - result->usePathfinderExtendedMaxNodes = unitNode->getAttribute("usePathfinderExtendedMaxNodes")->getIntValue() != 0; -// int maxQueuedCommandDisplayCount; - result->maxQueuedCommandDisplayCount = unitNode->getAttribute("maxQueuedCommandDisplayCount")->getIntValue(); -// UnitAttackBoostEffectOriginator currentAttackBoostOriginatorEffect; - - // !!! TODO: Softcoder - in progress work to load attack boosts, not working properly yet - result->currentAttackBoostOriginatorEffect.loadGame(unitNode,result, world); - -// std::vector currentAttackBoostEffects; -// for(unsigned int i = 0; i < currentAttackBoostEffects.size(); ++i) { -// UnitAttackBoostEffect *uabe= currentAttackBoostEffects[i]; -// uabe->saveGame(unitNode); -// } - - // !!! TODO: Softcoder - in progress work to load attack boosts, not working properly yet - if(unitNode->hasChild("UnitAttackBoostEffect") == true) { - vector unitParticleSystemNodeList = unitNode->getChildList("UnitAttackBoostEffect"); - for(unsigned int i = 0; i < unitParticleSystemNodeList.size(); ++i) { - XmlNode *node = unitParticleSystemNodeList[i]; - - UnitAttackBoostEffect *attackBoostEffect = new UnitAttackBoostEffect(); - attackBoostEffect->loadGame(node,result,world,false); - - result->currentAttackBoostEffects.push_back(attackBoostEffect); - } - } - //printf("Unit [%d - %s] has currentAttackBoostEffects count: %d\n",result->getId(),result->getType()->getName(false).c_str(),(int)result->currentAttackBoostEffects.size()); - - -// Mutex *mutexCommands; -// -// //static Mutex mutexDeletedUnits; -// //static std::map deletedUnits; -// -// bool changedActiveCommand; - result->changedActiveCommand = unitNode->getAttribute("changedActiveCommand")->getIntValue() != 0; -// int lastAttackerUnitId; - result->lastAttackerUnitId = unitNode->getAttribute("lastAttackerUnitId")->getIntValue(); -// int lastAttackedUnitId; - result->lastAttackedUnitId = unitNode->getAttribute("lastAttackedUnitId")->getIntValue(); -// CauseOfDeathType causeOfDeath; - result->causeOfDeath = static_cast(unitNode->getAttribute("causeOfDeath")->getIntValue()); - - result->pathfindFailedConsecutiveFrameCount = unitNode->getAttribute("pathfindFailedConsecutiveFrameCount")->getIntValue(); - - if(result->alive) { - world->getMapPtr()->putUnitCells(result, newUnitPos); - //result->born(); - } - - result->pos = newUnitPos; - result->lastPos = Vec2i::strToVec2(unitNode->getAttribute("lastPos")->getValue()); - result->meetingPos = Vec2i::strToVec2(unitNode->getAttribute("meetingPos")->getValue()); - - if(unitNode->hasAttribute("currentPathFinderDesiredFinalPos")) { - result->currentPathFinderDesiredFinalPos = Vec2i::strToVec2(unitNode->getAttribute("currentPathFinderDesiredFinalPos")->getValue()); - } - - if(unitNode->hasAttribute("random")) { - result->random.setLastNumber(unitNode->getAttribute("random")->getIntValue()); - } - if(unitNode->hasAttribute("pathFindRefreshCellCount")) { - result->pathFindRefreshCellCount = unitNode->getAttribute("pathFindRefreshCellCount")->getIntValue(); - } - - //result->exploreCells(); - //result->calculateFogOfWarRadius(); + result->animProgress = + unitNode->getAttribute("animProgress")->getFloatValue(); + } + + // float highlight; + result->highlight = unitNode->getAttribute("highlight")->getFloatValue(); + // int progress2; + result->progress2 = unitNode->getAttribute("progress2")->getIntValue(); + // int kills; + result->kills = unitNode->getAttribute("kills")->getIntValue(); + // int enemyKills; + result->enemyKills = unitNode->getAttribute("enemyKills")->getIntValue(); + // UnitReference targetRef; + // targetRef.saveGame(unitNode); + result->targetRef.loadGame(unitNode, world); + // + // Field currField; + result->currField = + static_cast(unitNode->getAttribute("currField")->getIntValue()); + // Field targetField; + result->targetField = + static_cast(unitNode->getAttribute("targetField")->getIntValue()); + // const Level *level; + // if(level != NULL) { + // level->saveGame(unitNode); + // } + result->level = Level::loadGame(unitNode, ut); + // Vec2i pos; + result->pos = Vec2i::strToVec2(unitNode->getAttribute("pos")->getValue()); + // Vec2i lastPos; + result->lastPos = + Vec2i::strToVec2(unitNode->getAttribute("lastPos")->getValue()); + // Vec2i targetPos; //absolute target pos + result->targetPos = + Vec2i::strToVec2(unitNode->getAttribute("targetPos")->getValue()); + // Vec3f targetVec; + result->targetVec = + Vec3f::strToVec3(unitNode->getAttribute("targetVec")->getValue()); + // Vec2i meetingPos; + result->meetingPos = + Vec2i::strToVec2(unitNode->getAttribute("meetingPos")->getValue()); + // + // float lastRotation; //in degrees + result->lastRotation = + unitNode->getAttribute("lastRotation")->getFloatValue(); + // float targetRotation; + result->targetRotation = + unitNode->getAttribute("targetRotation")->getFloatValue(); + // float rotation; + result->rotation = unitNode->getAttribute("rotation")->getFloatValue(); + // float targetRotationZ; + result->targetRotationZ = + unitNode->getAttribute("targetRotationZ")->getFloatValue(); + // float targetRotationX; + result->targetRotationX = + unitNode->getAttribute("targetRotationX")->getFloatValue(); + // float rotationZ; + result->rotationZ = unitNode->getAttribute("rotationZ")->getFloatValue(); + // float rotationX; + result->rotationX = unitNode->getAttribute("rotationX")->getFloatValue(); + // const UnitType *type; + // unitNode->addAttribute("type",type->getName(), mapTagReplacements); + // const ResourceType *loadType; + // if(loadType != NULL) { + // unitNode->addAttribute("loadType",loadType->getName(), + // mapTagReplacements); + // } + if (unitNode->hasAttribute("loadType") == true) { + string loadTypeName = unitNode->getAttribute("loadType")->getValue(); + result->loadType = world->getTechTree()->getResourceType(loadTypeName); + } + // const SkillType *currSkill; + // if(currSkill != NULL) { + // unitNode->addAttribute("currSkill",currSkill->getName(), + // mapTagReplacements); + // } + if (unitNode->hasAttribute("currSkillName") == true) { + string skillTypeName = unitNode->getAttribute("currSkillName")->getValue(); + SkillClass skillClass = static_cast( + unitNode->getAttribute("currSkillClass")->getIntValue()); + result->currSkill = ut->getSkillType(skillTypeName, skillClass); + int tempProgress2 = result->progress2; // setCurrSkill overwrites progress2 + result->setCurrSkill(result->currSkill); + result->progress2 = tempProgress2; // restore it + } + + // int lastModelIndexForCurrSkillType; + result->lastModelIndexForCurrSkillType = + unitNode->getAttribute("lastModelIndexForCurrSkillType")->getIntValue(); + // int animationRandomCycleCount; + result->animationRandomCycleCount = + unitNode->getAttribute("animationRandomCycleCount")->getIntValue(); + // + // bool toBeUndertaken; + result->toBeUndertaken = + unitNode->getAttribute("toBeUndertaken")->getIntValue() != 0; + // bool alive; + result->setAlive(unitNode->getAttribute("alive")->getIntValue() != 0); + // bool showUnitParticles; + result->showUnitParticles = + unitNode->getAttribute("showUnitParticles")->getIntValue() != 0; + // Faction *faction; + // ParticleSystem *fire; + // if(fire != NULL) { + // fire->saveGame(unitNode); + // } + if (unitNode->hasChild("FireParticleSystem") == true) { + XmlNode *fireNode = unitNode->getChild("FireParticleSystem"); + result->fire = new FireParticleSystem(); + result->fire->setParticleOwner(result); + result->fire->loadGame(fireNode); + // result->fire->setTexture(CoreData::getInstance().getFireTexture()); + result->fireParticleSystems.push_back(result->fire); + + // printf("Load MAIN fire particle result->fire = %p\n",result->fire); + + Renderer::getInstance().addToDeferredParticleSystemList( + make_pair(result->fire, rsGame)); + } + + // TotalUpgrade totalUpgrade; + result->totalUpgrade.loadGame(unitNode); + // Map *map; + // + // UnitPathInterface *unitPath; + // unitPath->saveGame(unitNode); + // WaypointPath waypointPath; + // + // Commands commands; + // for(Commands::iterator it = commands.begin(); it != commands.end(); + //++it) { + // (*it)->saveGame(unitNode); + // } + vector commandNodeList = unitNode->getChildList("Command"); + for (unsigned int i = 0; i < commandNodeList.size(); ++i) { + XmlNode *node = commandNodeList[i]; + Command *command = Command::loadGame(node, ut, world); + + static string mutexOwnerId = + string(__FILE__) + string("_") + intToStr(__LINE__); + MutexSafeWrapper safeMutex(result->mutexCommands, mutexOwnerId); + result->commands.push_back(command); + safeMutex.ReleaseLock(); + } + // Observers observers; + // for(Observers::iterator it = observers.begin(); it != observers.end(); + // ++it) { + // (*it)->saveGame(unitNode); + //} + + // vector unitParticleSystems; + // for(unsigned int i = 0; i < unitParticleSystems.size(); ++i) { + // UnitParticleSystem *ups= unitParticleSystems[i]; + // ups->saveGame(unitNode); + // } + if (unitNode->hasChild("unitParticleSystems") == true) { + XmlNode *unitParticleSystemsNode = + unitNode->getChild("unitParticleSystems"); + vector unitParticleSystemNodeList = + unitParticleSystemsNode->getChildList("UnitParticleSystem"); + for (unsigned int i = 0; i < unitParticleSystemNodeList.size(); ++i) { + XmlNode *node = unitParticleSystemNodeList[i]; + + UnitParticleSystem *ups = new UnitParticleSystem(); + ups->setParticleOwner(result); + ups->loadGame(node); + result->unitParticleSystems.push_back(ups); + + // Renderer::getInstance().manageParticleSystem(result->fire, rsGame); + Renderer::getInstance().addToDeferredParticleSystemList( + make_pair(ups, rsGame)); + } + } + + // vector queuedUnitParticleSystemTypes; + // for(unsigned int i = 0; i < queuedUnitParticleSystemTypes.size(); ++i) { + // UnitParticleSystemType *upst= queuedUnitParticleSystemTypes[i]; + // upst->saveGame(unitNode); + // } + + // UnitParticleSystems damageParticleSystems; + // for(unsigned int i = 0; i < damageParticleSystems.size(); ++i) { + // UnitParticleSystem *ups= damageParticleSystems[i]; + // ups->saveGame(unitNode); + // } + if (unitNode->hasChild("damageParticleSystems") == true) { + XmlNode *damageParticleSystemsNode = + unitNode->getChild("damageParticleSystems"); + vector unitParticleSystemNodeList = + damageParticleSystemsNode->getChildList("UnitParticleSystem"); + for (unsigned int i = 0; i < unitParticleSystemNodeList.size(); ++i) { + XmlNode *node = unitParticleSystemNodeList[i]; + + UnitParticleSystem *ups = new UnitParticleSystem(); + ups->setParticleOwner(result); + ups->loadGame(node); + result->damageParticleSystems.push_back(ups); + result->damageParticleSystemsInUse[i] = ups; + + // Renderer::getInstance().manageParticleSystem(result->fire, rsGame); + Renderer::getInstance().addToDeferredParticleSystemList( + make_pair(ups, rsGame)); + } + } + + // std::map damageParticleSystemsInUse; + // for(std::map::const_iterator iterMap = + // damageParticleSystemsInUse.begin(); iterMap != + // damageParticleSystemsInUse.end(); ++iterMap) { XmlNode + //*damageParticleSystemsInUseNode = + // unitNode->addChild("damageParticleSystemsInUse"); + // + // damageParticleSystemsInUseNode->addAttribute("key",intToStr(iterMap->first), + // mapTagReplacements); + // iterMap->second->saveGame(damageParticleSystemsInUseNode); + // } + // if(unitNode->hasChild("damageParticleSystemsInUse") == true) { + // XmlNode *damageParticleSystemsInUseNode = + // unitNode->getChild("damageParticleSystemsInUse"); vector damageParticleSystemsInUseNode2 = + // damageParticleSystemsInUseNode->getChildList("damageParticleSystemsInUse"); + // for(unsigned int i = 0; i < + //damageParticleSystemsInUseNode2.size(); + //++i) { XmlNode *d2Node = + //damageParticleSystemsInUseNode2[i]; + // + // vector unitParticleSystemNodeList = + // damageParticleSystemsInUseNode->getChildList("UnitParticleSystem"); + // for(unsigned int i = 0; i < + //unitParticleSystemNodeList.size(); + //++i) { XmlNode *node = + //unitParticleSystemNodeList[i]; + // + // UnitParticleSystem *ups = new + // UnitParticleSystem(); ups->loadGame(node); + // result->unitParticleSystems.push_back(ups); + // + // //Renderer::getInstance().manageParticleSystem(result->fire, + // rsGame); + // Renderer::getInstance().addToDeferredParticleSystemList(make_pair(ups, + // rsGame)); + // } + // + // } + + // vector fireParticleSystems; + // for(unsigned int i = 0; i < fireParticleSystems.size(); ++i) { + // ParticleSystem *ps= fireParticleSystems[i]; + // ps->saveGame(unitNode); + // } + if (unitNode->hasChild("fireParticleSystems") == true) { + XmlNode *fireParticleSystemsNode = + unitNode->getChild("fireParticleSystems"); + + int linkFireIndex = -1; + if (fireParticleSystemsNode->hasAttribute("fireParticleLink") == true) { + linkFireIndex = fireParticleSystemsNode->getAttribute("fireParticleLink") + ->getIntValue(); + } - return result; + vector unitParticleSystemNodeList = + fireParticleSystemsNode->getChildList("FireParticleSystem"); + for (int i = 0; i < (int)unitParticleSystemNodeList.size(); ++i) { + XmlNode *node = unitParticleSystemNodeList[i]; + + if (result->fire == NULL || linkFireIndex != i) { + FireParticleSystem *ups = new FireParticleSystem(); + ups->setParticleOwner(result); + ups->loadGame(node); + // ups->setTexture(CoreData::getInstance().getFireTexture()); + result->fireParticleSystems.push_back(ups); + + // printf("Load fire particle i = %d linkFireIndex = %d result->fire = + // %p ups = %p\n",i,linkFireIndex,result->fire,ups); + + if (result->fire == NULL && linkFireIndex >= 0 && linkFireIndex == i) { + result->fire = ups; + } + Renderer::getInstance().addToDeferredParticleSystemList( + make_pair(ups, rsGame)); + } + } + } + + // vector smokeParticleSystems; + // for(unsigned int i = 0; i < smokeParticleSystems.size(); ++i) { + // UnitParticleSystem *ups= smokeParticleSystems[i]; + // ups->saveGame(unitNode); + // } + if (unitNode->hasChild("smokeParticleSystems") == true) { + XmlNode *smokeParticleSystemsNode = + unitNode->getChild("smokeParticleSystems"); + vector unitParticleSystemNodeList = + smokeParticleSystemsNode->getChildList("UnitParticleSystem"); + for (unsigned int i = 0; i < unitParticleSystemNodeList.size(); ++i) { + XmlNode *node = unitParticleSystemNodeList[i]; + + // printf("Load Smoke particle i = %d\n",i); + UnitParticleSystem *ups = new UnitParticleSystem(); + ups->setParticleOwner(result); + ups->loadGame(node); + // ups->setTexture(CoreData::getInstance().getFireTexture()); + result->smokeParticleSystems.push_back(ups); + + Renderer::getInstance().addToDeferredParticleSystemList( + make_pair(ups, rsGame)); + + // printf("Loading smoke particles:\n[%s]\n",ups->toString().c_str()); + } + } + + // CardinalDir modelFacing; + // unitNode->addAttribute("modelFacing",intToStr(modelFacing), + // mapTagReplacements); + + // std::string lastSynchDataString; + // unitNode->addAttribute("lastSynchDataString",lastSynchDataString, + // mapTagReplacements); std::string lastFile; + // unitNode->addAttribute("lastFile",lastFile, mapTagReplacements); + // int lastLine; + // unitNode->addAttribute("lastLine",intToStr(lastLine), + // mapTagReplacements); std::string lastSource; + // unitNode->addAttribute("lastSource",lastSource, mapTagReplacements); + // int lastRenderFrame; + result->lastRenderFrame = + unitNode->getAttribute("lastRenderFrame")->getIntValue(); + // bool visible; + result->visible = unitNode->getAttribute("visible")->getIntValue() != 0; + // int retryCurrCommandCount; + result->retryCurrCommandCount = + unitNode->getAttribute("retryCurrCommandCount")->getIntValue(); + // Vec3f screenPos; + result->screenPos = + Vec3f::strToVec3(unitNode->getAttribute("screenPos")->getValue()); + // string currentUnitTitle; + result->currentUnitTitle = + unitNode->getAttribute("currentUnitTitle")->getValue(); + // + // bool inBailOutAttempt; + result->inBailOutAttempt = + unitNode->getAttribute("inBailOutAttempt")->getIntValue() != 0; + // //std::vector > badHarvestPosList; + // std::map badHarvestPosList; + // for(std::map::const_iterator iterMap = + // badHarvestPosList.begin(); iterMap != badHarvestPosList.end(); + // ++iterMap) { XmlNode *badHarvestPosListNode = + // unitNode->addChild("badHarvestPosList"); + // + // badHarvestPosListNode->addAttribute("key",iterMap->first.getString(), + // mapTagReplacements); + // badHarvestPosListNode->addAttribute("value",intToStr(iterMap->second), + // mapTagReplacements); + // } + + // //time_t lastBadHarvestListPurge; + // std::pair lastHarvestResourceTarget; + const XmlNode *lastHarvestResourceTargetNode = + unitNode->getChild("lastHarvestResourceTarget"); + // lastHarvestResourceTargetNode->addAttribute("key",lastHarvestResourceTarget.first.getString(), + // mapTagReplacements); + // lastHarvestResourceTargetNode->addAttribute("value",intToStr(lastHarvestResourceTarget.second), + // mapTagReplacements); + + result->lastHarvestResourceTarget = make_pair( + Vec2i::strToVec2( + lastHarvestResourceTargetNode->getAttribute("key")->getValue()), + lastHarvestResourceTargetNode->getAttribute("value")->getIntValue()); + + // //std::pair > currentTargetPathTaken; + // static Game *game; + // + // bool ignoreCheckCommand; + result->ignoreCheckCommand = + unitNode->getAttribute("ignoreCheckCommand")->getIntValue() != 0; + // uint32 lastStuckFrame; + result->lastStuckFrame = + unitNode->getAttribute("lastStuckFrame")->getIntValue(); + // Vec2i lastStuckPos; + result->lastStuckPos = + Vec2i::strToVec2(unitNode->getAttribute("lastStuckPos")->getValue()); + // uint32 lastPathfindFailedFrame; + result->lastPathfindFailedFrame = + unitNode->getAttribute("lastPathfindFailedFrame")->getIntValue(); + // Vec2i lastPathfindFailedPos; + result->lastPathfindFailedPos = Vec2i::strToVec2( + unitNode->getAttribute("lastPathfindFailedPos")->getValue()); + // bool usePathfinderExtendedMaxNodes; + result->usePathfinderExtendedMaxNodes = + unitNode->getAttribute("usePathfinderExtendedMaxNodes")->getIntValue() != + 0; + // int maxQueuedCommandDisplayCount; + result->maxQueuedCommandDisplayCount = + unitNode->getAttribute("maxQueuedCommandDisplayCount")->getIntValue(); + // UnitAttackBoostEffectOriginator currentAttackBoostOriginatorEffect; + + // !!! TODO: Softcoder - in progress work to load attack boosts, not working + // properly yet + result->currentAttackBoostOriginatorEffect.loadGame(unitNode, result, world); + + // std::vector currentAttackBoostEffects; + // for(unsigned int i = 0; i < currentAttackBoostEffects.size(); ++i) { + // UnitAttackBoostEffect *uabe= currentAttackBoostEffects[i]; + // uabe->saveGame(unitNode); + // } + + // !!! TODO: Softcoder - in progress work to load attack boosts, not working + // properly yet + if (unitNode->hasChild("UnitAttackBoostEffect") == true) { + vector unitParticleSystemNodeList = + unitNode->getChildList("UnitAttackBoostEffect"); + for (unsigned int i = 0; i < unitParticleSystemNodeList.size(); ++i) { + XmlNode *node = unitParticleSystemNodeList[i]; + + UnitAttackBoostEffect *attackBoostEffect = new UnitAttackBoostEffect(); + attackBoostEffect->loadGame(node, result, world, false); + + result->currentAttackBoostEffects.push_back(attackBoostEffect); + } + } + // printf("Unit [%d - %s] has currentAttackBoostEffects count: + // %d\n",result->getId(),result->getType()->getName(false).c_str(),(int)result->currentAttackBoostEffects.size()); + + // Mutex *mutexCommands; + // + // //static Mutex mutexDeletedUnits; + // //static std::map deletedUnits; + // + // bool changedActiveCommand; + result->changedActiveCommand = + unitNode->getAttribute("changedActiveCommand")->getIntValue() != 0; + // int lastAttackerUnitId; + result->lastAttackerUnitId = + unitNode->getAttribute("lastAttackerUnitId")->getIntValue(); + // int lastAttackedUnitId; + result->lastAttackedUnitId = + unitNode->getAttribute("lastAttackedUnitId")->getIntValue(); + // CauseOfDeathType causeOfDeath; + result->causeOfDeath = static_cast( + unitNode->getAttribute("causeOfDeath")->getIntValue()); + + result->pathfindFailedConsecutiveFrameCount = + unitNode->getAttribute("pathfindFailedConsecutiveFrameCount") + ->getIntValue(); + + if (result->alive) { + world->getMapPtr()->putUnitCells(result, newUnitPos); + // result->born(); + } + + result->pos = newUnitPos; + result->lastPos = + Vec2i::strToVec2(unitNode->getAttribute("lastPos")->getValue()); + result->meetingPos = + Vec2i::strToVec2(unitNode->getAttribute("meetingPos")->getValue()); + + if (unitNode->hasAttribute("currentPathFinderDesiredFinalPos")) { + result->currentPathFinderDesiredFinalPos = Vec2i::strToVec2( + unitNode->getAttribute("currentPathFinderDesiredFinalPos")->getValue()); + } + + if (unitNode->hasAttribute("random")) { + result->random.setLastNumber( + unitNode->getAttribute("random")->getIntValue()); + } + if (unitNode->hasAttribute("pathFindRefreshCellCount")) { + result->pathFindRefreshCellCount = + unitNode->getAttribute("pathFindRefreshCellCount")->getIntValue(); + } + + // result->exploreCells(); + // result->calculateFogOfWarRadius(); + + return result; } Checksum Unit::getCRC() { - const bool consoleDebug = false; - - Checksum crcForUnit; - - crcForUnit.addInt(id); - crcForUnit.addInt(hp); - crcForUnit.addInt(ep); - crcForUnit.addInt(loadCount); - crcForUnit.addInt(deadCount); - - if(consoleDebug) printf("#1 Unit: %d CRC: %u\n",id,crcForUnit.getSum()); - - crcForUnit.addInt64(progress); - crcForUnit.addInt64(lastAnimProgress); - crcForUnit.addInt64(animProgress); - - if(consoleDebug) printf("#2 Unit: %d CRC: %u\n",id,crcForUnit.getSum()); - - //float highlight; - crcForUnit.addInt(progress2); - crcForUnit.addInt(kills); - crcForUnit.addInt(enemyKills); - crcForUnit.addInt(morphFieldsBlocked); - - if(consoleDebug) printf("#3 Unit: %d CRC: %u\n",id,crcForUnit.getSum()); - - //UnitReference targetRef; - - crcForUnit.addInt(currField); - crcForUnit.addInt(targetField); - - if(consoleDebug) printf("#4 Unit: %d CRC: %u\n",id,crcForUnit.getSum()); - - //const Level *level; - if(level != NULL) { - crcForUnit.addString(level->getName(false)); - } + const bool consoleDebug = false; - if(consoleDebug) printf("#5 Unit: %d CRC: %u\n",id,crcForUnit.getSum()); + Checksum crcForUnit; - crcForUnit.addInt(pos.x); - crcForUnit.addInt(pos.y); - crcForUnit.addInt(lastPos.x); - crcForUnit.addInt(lastPos.y); - crcForUnit.addInt(targetPos.x); - crcForUnit.addInt(targetPos.y); + crcForUnit.addInt(id); + crcForUnit.addInt(hp); + crcForUnit.addInt(ep); + crcForUnit.addInt(loadCount); + crcForUnit.addInt(deadCount); - if(consoleDebug) printf("#6 Unit: %d CRC: %u\n",id,crcForUnit.getSum()); + if (consoleDebug) + printf("#1 Unit: %d CRC: %u\n", id, crcForUnit.getSum()); - //Vec3f targetVec; + crcForUnit.addInt64(progress); + crcForUnit.addInt64(lastAnimProgress); + crcForUnit.addInt64(animProgress); - crcForUnit.addInt(meetingPos.x); - crcForUnit.addInt(meetingPos.y); + if (consoleDebug) + printf("#2 Unit: %d CRC: %u\n", id, crcForUnit.getSum()); - if(consoleDebug) printf("#7 Unit: %d CRC: %u\n",id,crcForUnit.getSum()); + // float highlight; + crcForUnit.addInt(progress2); + crcForUnit.addInt(kills); + crcForUnit.addInt(enemyKills); + crcForUnit.addInt(morphFieldsBlocked); - //float lastRotation; - //float targetRotation; - //float rotation; - //float targetRotationZ; - //float targetRotationX; - //float rotationZ; - //float rotationX; + if (consoleDebug) + printf("#3 Unit: %d CRC: %u\n", id, crcForUnit.getSum()); - //const UnitType *preMorph_type; - if(preMorph_type != NULL) { - crcForUnit.addString(preMorph_type->getName(false)); - } + // UnitReference targetRef; - if(consoleDebug) printf("#8 Unit: %d CRC: %u\n",id,crcForUnit.getSum()); + crcForUnit.addInt(currField); + crcForUnit.addInt(targetField); - //const UnitType *type; - if(type != NULL) { - crcForUnit.addString(type->getName(false)); - } + if (consoleDebug) + printf("#4 Unit: %d CRC: %u\n", id, crcForUnit.getSum()); - //const ResourceType *loadType; - if(loadType != NULL) { - crcForUnit.addString(loadType->getName(false)); - } + // const Level *level; + if (level != NULL) { + crcForUnit.addString(level->getName(false)); + } - //const SkillType *currSkill; - if(currSkill != NULL) { - crcForUnit.addString(currSkill->getName()); - } - - //printf("#9 Unit: %d CRC: %u lastModelIndexForCurrSkillType: %d\n",id,crcForUnit.getSum(),lastModelIndexForCurrSkillType); - //printf("#9a Unit: %d CRC: %u\n",id,crcForUnit.getSum()); - //crcForUnit.addInt(lastModelIndexForCurrSkillType); - - if(consoleDebug) printf("#9 Unit: %d CRC: %u\n",id,crcForUnit.getSum()); - - //crcForUnit.addInt(animationRandomCycleCount); - //printf("#9b Unit: %d CRC: %u\n",id,crcForUnit.getSum()); - - crcForUnit.addInt(toBeUndertaken); - - if(consoleDebug) printf("#9c Unit: %d CRC: %u\n",id,crcForUnit.getSum()); - - crcForUnit.addInt(alive); - //bool showUnitParticles; - - if(consoleDebug) printf("#10 Unit: %d CRC: %u\n",id,crcForUnit.getSum()); - - //Faction *faction; - //ParticleSystem *fire; - if(fire != NULL) { - crcForUnit.addInt(fire->getActive()); - } - - //TotalUpgrade totalUpgrade; - uint32 crc = totalUpgrade.getCRC().getSum(); - crcForUnit.addBytes(&crc,sizeof(uint32)); - - //Map *map; - //UnitPathInterface *unitPath; - if(unitPath != NULL) { - uint32 crc = unitPath->getCRC().getSum(); - crcForUnit.addBytes(&crc,sizeof(uint32)); - } - //WaypointPath waypointPath; - - if(consoleDebug) printf("#11 Unit: %d CRC: %u commands.size(): " MG_SIZE_T_SPECIFIER "\n",id,crcForUnit.getSum(),commands.size()); - - //Commands commands; - if(commands.empty() == false) { - crcForUnit.addInt((int)commands.size()); - for(Commands::const_iterator it= commands.begin(); it != commands.end(); ++it) { - uint32 crc = (*it)->getCRC().getSum(); - crcForUnit.addBytes(&crc,sizeof(uint32)); - } - } + if (consoleDebug) + printf("#5 Unit: %d CRC: %u\n", id, crcForUnit.getSum()); + + crcForUnit.addInt(pos.x); + crcForUnit.addInt(pos.y); + crcForUnit.addInt(lastPos.x); + crcForUnit.addInt(lastPos.y); + crcForUnit.addInt(targetPos.x); + crcForUnit.addInt(targetPos.y); + + if (consoleDebug) + printf("#6 Unit: %d CRC: %u\n", id, crcForUnit.getSum()); + + // Vec3f targetVec; + + crcForUnit.addInt(meetingPos.x); + crcForUnit.addInt(meetingPos.y); + + if (consoleDebug) + printf("#7 Unit: %d CRC: %u\n", id, crcForUnit.getSum()); + + // float lastRotation; + // float targetRotation; + // float rotation; + // float targetRotationZ; + // float targetRotationX; + // float rotationZ; + // float rotationX; + + // const UnitType *preMorph_type; + if (preMorph_type != NULL) { + crcForUnit.addString(preMorph_type->getName(false)); + } + + if (consoleDebug) + printf("#8 Unit: %d CRC: %u\n", id, crcForUnit.getSum()); + + // const UnitType *type; + if (type != NULL) { + crcForUnit.addString(type->getName(false)); + } + + // const ResourceType *loadType; + if (loadType != NULL) { + crcForUnit.addString(loadType->getName(false)); + } + + // const SkillType *currSkill; + if (currSkill != NULL) { + crcForUnit.addString(currSkill->getName()); + } + + // printf("#9 Unit: %d CRC: %u lastModelIndexForCurrSkillType: + // %d\n",id,crcForUnit.getSum(),lastModelIndexForCurrSkillType); printf("#9a + // Unit: %d CRC: %u\n",id,crcForUnit.getSum()); + // crcForUnit.addInt(lastModelIndexForCurrSkillType); + + if (consoleDebug) + printf("#9 Unit: %d CRC: %u\n", id, crcForUnit.getSum()); + + // crcForUnit.addInt(animationRandomCycleCount); + // printf("#9b Unit: %d CRC: %u\n",id,crcForUnit.getSum()); + + crcForUnit.addInt(toBeUndertaken); + + if (consoleDebug) + printf("#9c Unit: %d CRC: %u\n", id, crcForUnit.getSum()); + + crcForUnit.addInt(alive); + // bool showUnitParticles; + + if (consoleDebug) + printf("#10 Unit: %d CRC: %u\n", id, crcForUnit.getSum()); + + // Faction *faction; + // ParticleSystem *fire; + if (fire != NULL) { + crcForUnit.addInt(fire->getActive()); + } + + // TotalUpgrade totalUpgrade; + uint32 crc = totalUpgrade.getCRC().getSum(); + crcForUnit.addBytes(&crc, sizeof(uint32)); + + // Map *map; + // UnitPathInterface *unitPath; + if (unitPath != NULL) { + uint32 crc = unitPath->getCRC().getSum(); + crcForUnit.addBytes(&crc, sizeof(uint32)); + } + // WaypointPath waypointPath; + + if (consoleDebug) + printf("#11 Unit: %d CRC: %u commands.size(): " MG_SIZE_T_SPECIFIER "\n", + id, crcForUnit.getSum(), commands.size()); + + // Commands commands; + if (commands.empty() == false) { + crcForUnit.addInt((int)commands.size()); + for (Commands::const_iterator it = commands.begin(); it != commands.end(); + ++it) { + uint32 crc = (*it)->getCRC().getSum(); + crcForUnit.addBytes(&crc, sizeof(uint32)); + } + } - //printf("#11 Unit: %d CRC: %u observers.size(): %ld\n",id,crcForUnit.getSum(),observers.size()); + // printf("#11 Unit: %d CRC: %u observers.size(): + // %ld\n",id,crcForUnit.getSum(),observers.size()); - //Observers observers; - //crcForUnit.addInt64((int64)observers.size()); + // Observers observers; + // crcForUnit.addInt64((int64)observers.size()); - if(consoleDebug) printf("#11 Unit: %d CRC: %u damageParticleSystems.size(): " MG_SIZE_T_SPECIFIER "\n",id,crcForUnit.getSum(),damageParticleSystems.size()); + if (consoleDebug) + printf("#11 Unit: %d CRC: %u " + "damageParticleSystems.size(): " MG_SIZE_T_SPECIFIER "\n", + id, crcForUnit.getSum(), damageParticleSystems.size()); - //vector unitParticleSystems; - //vector queuedUnitParticleSystemTypes; + // vector unitParticleSystems; + // vector queuedUnitParticleSystemTypes; - //UnitParticleSystems damageParticleSystems; - crcForUnit.addInt((int)damageParticleSystems.size()); + // UnitParticleSystems damageParticleSystems; + crcForUnit.addInt((int)damageParticleSystems.size()); - if(consoleDebug) printf("#12 Unit: %d CRC: %u\n",id,crcForUnit.getSum()); + if (consoleDebug) + printf("#12 Unit: %d CRC: %u\n", id, crcForUnit.getSum()); - //std::map damageParticleSystemsInUse; + // std::map damageParticleSystemsInUse; - //vector fireParticleSystems; - //vector smokeParticleSystems; + // vector fireParticleSystems; + // vector smokeParticleSystems; - //CardinalDir modelFacing; - crcForUnit.addInt(modelFacing); + // CardinalDir modelFacing; + crcForUnit.addInt(modelFacing); - //std::string lastSynchDataString; - //std::string lastFile; - //int lastLine; - //std::string lastSource; - //int lastRenderFrame; - //bool visible; + // std::string lastSynchDataString; + // std::string lastFile; + // int lastLine; + // std::string lastSource; + // int lastRenderFrame; + // bool visible; - //int retryCurrCommandCount; + // int retryCurrCommandCount; - //Vec3f screenPos; - //string currentUnitTitle; + // Vec3f screenPos; + // string currentUnitTitle; - if(consoleDebug) printf("#13 Unit: %d CRC: %u\n",id,crcForUnit.getSum()); + if (consoleDebug) + printf("#13 Unit: %d CRC: %u\n", id, crcForUnit.getSum()); - crcForUnit.addInt(inBailOutAttempt); + crcForUnit.addInt(inBailOutAttempt); - crcForUnit.addInt((int)badHarvestPosList.size()); - //crcForUnit.addInt(lastHarvestResourceTarget.first()); + crcForUnit.addInt((int)badHarvestPosList.size()); + // crcForUnit.addInt(lastHarvestResourceTarget.first()); - if(consoleDebug) printf("#14 Unit: %d CRC: %u\n",id,crcForUnit.getSum()); + if (consoleDebug) + printf("#14 Unit: %d CRC: %u\n", id, crcForUnit.getSum()); - //static Game *game; - //bool ignoreCheckCommand; + // static Game *game; + // bool ignoreCheckCommand; - //uint32 lastStuckFrame; - crcForUnit.addUInt(lastStuckFrame); - //Vec2i lastStuckPos; - crcForUnit.addInt(lastStuckPos.x); - crcForUnit.addInt(lastStuckPos.y); + // uint32 lastStuckFrame; + crcForUnit.addUInt(lastStuckFrame); + // Vec2i lastStuckPos; + crcForUnit.addInt(lastStuckPos.x); + crcForUnit.addInt(lastStuckPos.y); - //uint32 lastPathfindFailedFrame; - //Vec2i lastPathfindFailedPos; - //bool usePathfinderExtendedMaxNodes; - //int maxQueuedCommandDisplayCount; + // uint32 lastPathfindFailedFrame; + // Vec2i lastPathfindFailedPos; + // bool usePathfinderExtendedMaxNodes; + // int maxQueuedCommandDisplayCount; - //UnitAttackBoostEffectOriginator currentAttackBoostOriginatorEffect; - crcForUnit.addInt((int)currentAttackBoostOriginatorEffect.currentAttackBoostUnits.size()); + // UnitAttackBoostEffectOriginator currentAttackBoostOriginatorEffect; + crcForUnit.addInt( + (int)currentAttackBoostOriginatorEffect.currentAttackBoostUnits.size()); - if(consoleDebug) printf("#15 Unit: %d CRC: %u\n",id,crcForUnit.getSum()); + if (consoleDebug) + printf("#15 Unit: %d CRC: %u\n", id, crcForUnit.getSum()); - //std::vector currentAttackBoostEffects; + // std::vector currentAttackBoostEffects; - //Mutex *mutexCommands; + // Mutex *mutexCommands; - //bool changedActiveCommand; + // bool changedActiveCommand; - //int lastAttackerUnitId; - //int lastAttackedUnitId; - //CauseOfDeathType causeOfDeath; + // int lastAttackerUnitId; + // int lastAttackedUnitId; + // CauseOfDeathType causeOfDeath; - //uint32 pathfindFailedConsecutiveFrameCount; - crcForUnit.addString(this->currentPathFinderDesiredFinalPos.getString()); + // uint32 pathfindFailedConsecutiveFrameCount; + crcForUnit.addString(this->currentPathFinderDesiredFinalPos.getString()); - crcForUnit.addInt(random.getLastNumber()); - if(this->random.getLastCaller() != "") { - crcForUnit.addString(this->random.getLastCaller()); - } + crcForUnit.addInt(random.getLastNumber()); + if (this->random.getLastCaller() != "") { + crcForUnit.addString(this->random.getLastCaller()); + } - if(consoleDebug) printf("#16 Unit: %d CRC: %u\n",id,crcForUnit.getSum()); + if (consoleDebug) + printf("#16 Unit: %d CRC: %u\n", id, crcForUnit.getSum()); - //int pathFindRefreshCellCount; + // int pathFindRefreshCellCount; - //FowAlphaCellsLookupItem cachedFow; - //Vec2i cachedFowPos; + // FowAlphaCellsLookupItem cachedFow; + // Vec2i cachedFowPos; - crcForUnit.addInt(lastHarvestedResourcePos.x); - crcForUnit.addInt(lastHarvestedResourcePos.y); + crcForUnit.addInt(lastHarvestedResourcePos.x); + crcForUnit.addInt(lastHarvestedResourcePos.y); - if(consoleDebug) printf("#17 Unit: %d CRC: %u\n",id,crcForUnit.getSum()); + if (consoleDebug) + printf("#17 Unit: %d CRC: %u\n", id, crcForUnit.getSum()); - if(this->getParticleInfo() != "") { - crcForUnit.addString(this->getParticleInfo()); - } + if (this->getParticleInfo() != "") { + crcForUnit.addString(this->getParticleInfo()); + } - crcForUnit.addInt((int)attackParticleSystems.size()); - if(isNetworkCRCEnabled() == true) { - for(unsigned int index = 0; index < attackParticleSystems.size(); ++index) { - ParticleSystem *ps = attackParticleSystems[index]; - if(ps != NULL && - Renderer::getInstance().validateParticleSystemStillExists(ps,rsGame) == true) { - uint32 crc = ps->getCRC().getSum(); - crcForUnit.addBytes(&crc,sizeof(uint32)); - } - } - } + crcForUnit.addInt((int)attackParticleSystems.size()); + if (isNetworkCRCEnabled() == true) { + for (unsigned int index = 0; index < attackParticleSystems.size(); + ++index) { + ParticleSystem *ps = attackParticleSystems[index]; + if (ps != NULL && + Renderer::getInstance().validateParticleSystemStillExists( + ps, rsGame) == true) { + uint32 crc = ps->getCRC().getSum(); + crcForUnit.addBytes(&crc, sizeof(uint32)); + } + } + } - if(this->networkCRCParticleLogInfo != "") { - crcForUnit.addString(this->networkCRCParticleLogInfo); - } + if (this->networkCRCParticleLogInfo != "") { + crcForUnit.addString(this->networkCRCParticleLogInfo); + } - return crcForUnit; + return crcForUnit; } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/type_instances/unit.h b/source/glest_game/type_instances/unit.h index 1760f17eb..cd4b42602 100644 --- a/source/glest_game/type_instances/unit.h +++ b/source/glest_game/type_instances/unit.h @@ -12,36 +12,37 @@ #define _GLEST_GAME_UNIT_H_ #ifdef WIN32 - #include - #include +#include +#include #endif +#include "faction.h" +#include "game_constants.h" +#include "leak_dumper.h" #include "model.h" -#include "upgrade_type.h" #include "particle.h" -#include "skill_type.h" -#include "game_constants.h" #include "platform_common.h" +#include "skill_type.h" +#include "upgrade_type.h" #include -#include "faction.h" -#include "leak_dumper.h" -//#define LEAK_CHECK_UNITS +// #define LEAK_CHECK_UNITS -namespace Glest { namespace Game { +namespace Glest { +namespace Game { +using Shared::Graphics::Model; using Shared::Graphics::ParticleSystem; using Shared::Graphics::UnitParticleSystem; -using Shared::Graphics::Vec4f; using Shared::Graphics::Vec2f; -using Shared::Graphics::Vec3f; using Shared::Graphics::Vec2i; -using Shared::Graphics::Model; +using Shared::Graphics::Vec3f; +using Shared::Graphics::Vec4f; using Shared::PlatformCommon::Chrono; using Shared::PlatformCommon::ValueCheckerVault; class Map; -//class Faction; +// class Faction; class Unit; class Command; class SkillType; @@ -59,41 +60,41 @@ class GameSettings; class World; enum CommandResult { - crSuccess, - crFailRes, - crFailReqs, - crFailUnitCount, - crFailUndefined, - crSomeFailed + crSuccess, + crFailRes, + crFailReqs, + crFailUnitCount, + crFailUndefined, + crSomeFailed }; enum InterestingUnitType { - iutIdleHarvester, - iutBuiltBuilding, - iutProducer, - iutDamaged, - iutStore + iutIdleHarvester, + iutBuiltBuilding, + iutProducer, + iutDamaged, + iutStore }; enum CauseOfDeathType { - ucodNone, - ucodAttacked, - ucodAttackBoost, - ucodStarvedResource, - ucodStarvedRegeneration + ucodNone, + ucodAttacked, + ucodAttackBoost, + ucodStarvedResource, + ucodStarvedRegeneration }; class UnitBuildInfo { public: - UnitBuildInfo() { - unit = NULL; - //pos; - buildUnit = NULL; - } - const Unit *unit; - CardinalDir facing; - Vec2i pos; - const UnitType *buildUnit; + UnitBuildInfo() { + unit = NULL; + // pos; + buildUnit = NULL; + } + const Unit *unit; + CardinalDir facing; + Vec2i pos; + const UnitType *buildUnit; }; // ===================================================== @@ -102,15 +103,13 @@ class UnitBuildInfo { class UnitObserver { public: - enum Event{ - eKill - }; + enum Event { eKill }; public: - virtual ~UnitObserver() {} - virtual void unitEvent(Event event, const Unit *unit)=0; + virtual ~UnitObserver() {} + virtual void unitEvent(Event event, const Unit *unit) = 0; - virtual void saveGame(XmlNode *rootNode) const = 0; + virtual void saveGame(XmlNode *rootNode) const = 0; }; // ===================================================== @@ -119,175 +118,198 @@ class UnitObserver { class UnitReference { private: - int id; - Faction *faction; + int id; + Faction *faction; public: - UnitReference(); + UnitReference(); - UnitReference & operator=(const Unit *unit); - Unit *getUnit() const; + UnitReference &operator=(const Unit *unit); + Unit *getUnit() const; - int getUnitId() const { return id; } - Faction *getUnitFaction() const { return faction; } + int getUnitId() const { return id; } + Faction *getUnitFaction() const { return faction; } - void saveGame(XmlNode *rootNode); - void loadGame(const XmlNode *rootNode,World *world); + void saveGame(XmlNode *rootNode); + void loadGame(const XmlNode *rootNode, World *world); }; class UnitPathInterface { public: - UnitPathInterface() {} - virtual ~UnitPathInterface() {} + UnitPathInterface() {} + virtual ~UnitPathInterface() {} - virtual bool isBlocked() const = 0; - virtual bool isEmpty() const = 0; - virtual bool isStuck() const = 0; + virtual bool isBlocked() const = 0; + virtual bool isEmpty() const = 0; + virtual bool isStuck() const = 0; - virtual void clear() = 0; - virtual void clearBlockCount() = 0; - virtual void incBlockCount() = 0; - virtual void add(const Vec2i &path) = 0; - //virtual Vec2i pop() = 0; - virtual int getBlockCount() const = 0; - virtual int getQueueCount() const = 0; + virtual void clear() = 0; + virtual void clearBlockCount() = 0; + virtual void incBlockCount() = 0; + virtual void add(const Vec2i &path) = 0; + // virtual Vec2i pop() = 0; + virtual int getBlockCount() const = 0; + virtual int getQueueCount() const = 0; - virtual vector getQueue() const = 0; + virtual vector getQueue() const = 0; - virtual std::string toString() const = 0; + virtual std::string toString() const = 0; - virtual void setMap(Map *value) = 0; - virtual Map * getMap() = 0; + virtual void setMap(Map *value) = 0; + virtual Map *getMap() = 0; - virtual void saveGame(XmlNode *rootNode) = 0; - virtual void loadGame(const XmlNode *rootNode) = 0; + virtual void saveGame(XmlNode *rootNode) = 0; + virtual void loadGame(const XmlNode *rootNode) = 0; - virtual void clearCaches() = 0; + virtual void clearCaches() = 0; - virtual Checksum getCRC() = 0; + virtual Checksum getCRC() = 0; }; class UnitPathBasic : public UnitPathInterface { private: - static const int maxBlockCount; - Map *map; + static const int maxBlockCount; + Map *map; #ifdef LEAK_CHECK_UNITS - static std::map mapMemoryList; + static std::map mapMemoryList; #endif private: - int blockCount; - vector pathQueue; + int blockCount; + vector pathQueue; public: - UnitPathBasic(); - virtual ~UnitPathBasic(); + UnitPathBasic(); + virtual ~UnitPathBasic(); #ifdef LEAK_CHECK_UNITS - static void dumpMemoryList(); + static void dumpMemoryList(); #endif - virtual bool isBlocked() const; - virtual bool isEmpty() const; - virtual bool isStuck() const; + virtual bool isBlocked() const; + virtual bool isEmpty() const; + virtual bool isStuck() const; - virtual void clear(); - virtual void clearBlockCount() { blockCount = 0; } - virtual void incBlockCount(); - virtual void add(const Vec2i &path); - Vec2i pop(bool removeFrontPos=true); - virtual int getBlockCount() const { return blockCount; } - virtual int getQueueCount() const { return (int)pathQueue.size(); } + virtual void clear(); + virtual void clearBlockCount() { blockCount = 0; } + virtual void incBlockCount(); + virtual void add(const Vec2i &path); + Vec2i pop(bool removeFrontPos = true); + virtual int getBlockCount() const { return blockCount; } + virtual int getQueueCount() const { return (int)pathQueue.size(); } - virtual vector getQueue() const { return pathQueue; } + virtual vector getQueue() const { return pathQueue; } - virtual void setMap(Map *value) { map = value; } - virtual Map * getMap() { return map; } + virtual void setMap(Map *value) { map = value; } + virtual Map *getMap() { return map; } - virtual std::string toString() const; + virtual std::string toString() const; - virtual void saveGame(XmlNode *rootNode); - virtual void loadGame(const XmlNode *rootNode); - virtual void clearCaches(); + virtual void saveGame(XmlNode *rootNode); + virtual void loadGame(const XmlNode *rootNode); + virtual void clearCaches(); - virtual Checksum getCRC(); + virtual Checksum getCRC(); }; // ===================================================== // class UnitPath // ===================================================== /** Holds the next cells of a Unit movement - * @extends std::list - */ + * @extends std::list + */ class UnitPath : public list, public UnitPathInterface { private: - static const int maxBlockCount = 10; /**< number of command updates to wait on a blocked path */ + static const int maxBlockCount = + 10; /**< number of command updates to wait on a blocked path */ private: - int blockCount; /**< number of command updates this path has been blocked */ - Map *map; + int blockCount; /**< number of command updates this path has been blocked */ + Map *map; public: - UnitPath() : UnitPathInterface(), blockCount(0), map(NULL) {} /**< Construct path object */ - - virtual bool isBlocked() const {return blockCount >= maxBlockCount;} /**< is this path blocked */ - virtual bool isEmpty() const {return list::empty();} /**< is path empty */ - virtual bool isStuck() const {return false; } - - int size() const {return (int)list::size();} /**< size of path */ - virtual void clear() {list::clear(); blockCount = 0;} /**< clear the path */ - virtual void clearBlockCount() { blockCount = 0; } - virtual void incBlockCount() {++blockCount;} /**< increment block counter */ - virtual void push(Vec2i &pos) {push_front(pos);} /**< push onto front of path */ - bool empty() const {return list::empty();} /**< is path empty */ - virtual void add(const Vec2i &pos) { push_front(pos);} /**< push onto front of path */ - + UnitPath() + : UnitPathInterface(), blockCount(0), map(NULL) { + } /**< Construct path object */ + + virtual bool isBlocked() const { + return blockCount >= maxBlockCount; + } /**< is this path blocked */ + virtual bool isEmpty() const { + return list::empty(); + } /**< is path empty */ + virtual bool isStuck() const { return false; } + + int size() const { + return (int)list::size(); + } /**< size of path */ + virtual void clear() { + list::clear(); + blockCount = 0; + } /**< clear the path */ + virtual void clearBlockCount() { blockCount = 0; } + virtual void incBlockCount() { + ++blockCount; + } /**< increment block counter */ + virtual void push(Vec2i &pos) { + push_front(pos); + } /**< push onto front of path */ + bool empty() const { + return list::empty(); + } /**< is path empty */ + virtual void add(const Vec2i &pos) { + push_front(pos); + } /**< push onto front of path */ #if 0 // old style, to work with original PathFinder Vec2i peek() {return back();} /**< peek at the next position */ void pop() {this->pop_back();} /**< pop the next position off the path */ #else - // new style - Vec2i peek() {return front();} /**< peek at the next position */ - //virtual Vec2i pop() { Vec2i p= front(); erase(begin()); return p; } /**< pop the next position off the path */ - void pop() { erase(begin()); } /**< pop the next position off the path */ + // new style + Vec2i peek() { + return front(); + } /**< peek at the next position */ + // virtual Vec2i pop() { Vec2i p= front(); erase(begin()); return p; + // } + // /**< pop the next position off the path */ + void pop() { erase(begin()); } /**< pop the next position off the path */ #endif - virtual int getBlockCount() const { return blockCount; } - virtual int getQueueCount() const { return this->size(); } - - virtual vector getQueue() const { - vector result; - for(list::const_iterator iter = this->begin(); iter != this->end(); ++iter) { - result.push_back(*iter); - } - return result; - } + virtual int getBlockCount() const { return blockCount; } + virtual int getQueueCount() const { return this->size(); } + + virtual vector getQueue() const { + vector result; + for (list::const_iterator iter = this->begin(); iter != this->end(); + ++iter) { + result.push_back(*iter); + } + return result; + } - virtual void setMap(Map *value) { map = value; } - virtual Map * getMap() { return map; } + virtual void setMap(Map *value) { map = value; } + virtual Map *getMap() { return map; } - virtual std::string toString() const; + virtual std::string toString() const; - virtual void saveGame(XmlNode *rootNode) {}; - virtual void loadGame(const XmlNode *rootNode) {}; - virtual void clearCaches() {}; + virtual void saveGame(XmlNode *rootNode){}; + virtual void loadGame(const XmlNode *rootNode){}; + virtual void clearCaches(){}; - virtual Checksum getCRC() { return Checksum(); }; + virtual Checksum getCRC() { return Checksum(); }; }; class WaypointPath : public list { public: - WaypointPath() {} - void push(const Vec2i &pos) { push_front(pos); } - Vec2i peek() const {return front();} - void pop() {erase(begin());} - //void condense(); + WaypointPath() {} + void push(const Vec2i &pos) { push_front(pos); } + Vec2i peek() const { return front(); } + void pop() { erase(begin()); } + // void condense(); }; - // =============================== // class Unit // @@ -296,557 +318,611 @@ class WaypointPath : public list { class UnitAttackBoostEffect { private: - int unitId; - const Unit *unitPtr; - - const Unit *source; - - void applyLoadedAttackBoostParticles(UnitParticleSystemType *upstPtr,const XmlNode* node, Unit* unit); -public: + int unitId; + const Unit *unitPtr; - UnitAttackBoostEffect(); - virtual ~UnitAttackBoostEffect(); + const Unit *source; - const AttackBoost *boost; - //const Unit *source; - const Unit * getSource(); - void setSource(const Unit *unit); - UnitParticleSystem *ups; - UnitParticleSystemType *upst; + void applyLoadedAttackBoostParticles(UnitParticleSystemType *upstPtr, + const XmlNode *node, Unit *unit); - virtual void saveGame(XmlNode *rootNode); - virtual void loadGame(const XmlNode *rootNode, Unit *unit, World *world, bool applyToOriginator); +public: + UnitAttackBoostEffect(); + virtual ~UnitAttackBoostEffect(); + + const AttackBoost *boost; + // const Unit *source; + const Unit *getSource(); + void setSource(const Unit *unit); + UnitParticleSystem *ups; + UnitParticleSystemType *upst; + + virtual void saveGame(XmlNode *rootNode); + virtual void loadGame(const XmlNode *rootNode, Unit *unit, World *world, + bool applyToOriginator); }; class UnitAttackBoostEffectOriginator { public: + UnitAttackBoostEffectOriginator(); + virtual ~UnitAttackBoostEffectOriginator(); - UnitAttackBoostEffectOriginator(); - virtual ~UnitAttackBoostEffectOriginator(); - - const SkillType *skillType; - std::vector currentAttackBoostUnits; - UnitAttackBoostEffect *currentAppliedEffect; + const SkillType *skillType; + std::vector currentAttackBoostUnits; + UnitAttackBoostEffect *currentAppliedEffect; - virtual void saveGame(XmlNode *rootNode); - virtual void loadGame(const XmlNode *rootNode, Unit *unit, World *world); + virtual void saveGame(XmlNode *rootNode); + virtual void loadGame(const XmlNode *rootNode, Unit *unit, World *world); }; -class Unit : public BaseColorPickEntity, ValueCheckerVault, public ParticleOwner { +class Unit : public BaseColorPickEntity, + ValueCheckerVault, + public ParticleOwner { private: - typedef list Commands; - typedef list Observers; - typedef vector UnitParticleSystems; + typedef list Commands; + typedef list Observers; + typedef vector UnitParticleSystems; #ifdef LEAK_CHECK_UNITS - static std::map mapMemoryList; + static std::map mapMemoryList; #endif - static const float ANIMATION_SPEED_MULTIPLIER; - static const int64 PROGRESS_SPEED_MULTIPLIER; + static const float ANIMATION_SPEED_MULTIPLIER; + static const int64 PROGRESS_SPEED_MULTIPLIER; public: - static const int speedDivider; - static const int maxDeadCount; - static const int invalidId; + static const int speedDivider; + static const int maxDeadCount; + static const int invalidId; #ifdef LEAK_CHECK_UNITS - static std::map mapMemoryList2; - static void dumpMemoryList(); + static std::map mapMemoryList2; + static void dumpMemoryList(); #endif private: - const int32 id; - int32 hp; - int32 ep; - int32 loadCount; - int32 deadCount; - //float progress; //between 0 and 1 - int64 progress; //between 0 and 1 - int64 lastAnimProgress; //between 0 and 1 - int64 animProgress; //between 0 and 1 - float highlight; - int32 progress2; - int32 kills; - int32 enemyKills; - bool morphFieldsBlocked; - int oldTotalSight; - - UnitReference targetRef; - - Field currField; - Field targetField; - const Level *level; - - Vec2i pos; - Vec2i lastPos; - Vec2i targetPos; //absolute target pos - Vec3f targetVec; - Vec2i meetingPos; - - float lastRotation; //in degrees - float targetRotation; - float rotation; - float targetRotationZ; - float targetRotationX; - float rotationZ; - float rotationX; - - const UnitType *preMorph_type; - const UnitType *type; - const ResourceType *loadType; - const SkillType *currSkill; - int32 lastModelIndexForCurrSkillType; - int32 animationRandomCycleCount; - - bool toBeUndertaken; - bool alive; - bool showUnitParticles; - - Faction *faction; - ParticleSystem *fire; - TotalUpgrade totalUpgrade; - Map *map; - - UnitPathInterface *unitPath; - WaypointPath waypointPath; - - Commands commands; - Observers observers; - vector unitParticleSystems; - vector queuedUnitParticleSystemTypes; - - UnitParticleSystems damageParticleSystems; - std::map damageParticleSystemsInUse; - - vector fireParticleSystems; - vector smokeParticleSystems; - vector attackParticleSystems; - - CardinalDir modelFacing; - - std::string lastSynchDataString; - std::string lastFile; - int32 lastLine; - std::string lastSource; - int32 lastRenderFrame; - bool visible; - - int retryCurrCommandCount; - - Vec3f screenPos; - string currentUnitTitle; - - bool inBailOutAttempt; - // This buffer stores a list of bad harvest cells, along with the start - // time of when it was detected. Typically this may be due to a unit - // constantly getting blocked from getting to the resource so this - // list may be used to tell areas of the game to ignore those cells for a - // period of time - //std::vector > badHarvestPosList; - std::map badHarvestPosList; - //time_t lastBadHarvestListPurge; - std::pair lastHarvestResourceTarget; - - //std::pair > currentTargetPathTaken; - - static Game *game; - - bool ignoreCheckCommand; - - uint32 lastStuckFrame; - Vec2i lastStuckPos; - - uint32 lastPathfindFailedFrame; - Vec2i lastPathfindFailedPos; - bool usePathfinderExtendedMaxNodes; - int32 maxQueuedCommandDisplayCount; + const int32 id; + int32 hp; + int32 ep; + int32 loadCount; + int32 deadCount; + // float progress; //between 0 and 1 + int64 progress; // between 0 and 1 + int64 lastAnimProgress; // between 0 and 1 + int64 animProgress; // between 0 and 1 + float highlight; + int32 progress2; + int32 kills; + int32 enemyKills; + bool morphFieldsBlocked; + int oldTotalSight; + + UnitReference targetRef; + + Field currField; + Field targetField; + const Level *level; + + Vec2i pos; + Vec2i lastPos; + Vec2i targetPos; // absolute target pos + Vec3f targetVec; + Vec2i meetingPos; + + float lastRotation; // in degrees + float targetRotation; + float rotation; + float targetRotationZ; + float targetRotationX; + float rotationZ; + float rotationX; + + const UnitType *preMorph_type; + const UnitType *type; + const ResourceType *loadType; + const SkillType *currSkill; + int32 lastModelIndexForCurrSkillType; + int32 animationRandomCycleCount; + + bool toBeUndertaken; + bool alive; + bool showUnitParticles; + + Faction *faction; + ParticleSystem *fire; + TotalUpgrade totalUpgrade; + Map *map; + + UnitPathInterface *unitPath; + WaypointPath waypointPath; + + Commands commands; + Observers observers; + vector unitParticleSystems; + vector queuedUnitParticleSystemTypes; + + UnitParticleSystems damageParticleSystems; + std::map damageParticleSystemsInUse; + + vector fireParticleSystems; + vector smokeParticleSystems; + vector attackParticleSystems; + + CardinalDir modelFacing; + + std::string lastSynchDataString; + std::string lastFile; + int32 lastLine; + std::string lastSource; + int32 lastRenderFrame; + bool visible; + + int retryCurrCommandCount; + + Vec3f screenPos; + string currentUnitTitle; + + bool inBailOutAttempt; + // This buffer stores a list of bad harvest cells, along with the start + // time of when it was detected. Typically this may be due to a unit + // constantly getting blocked from getting to the resource so this + // list may be used to tell areas of the game to ignore those cells for a + // period of time + // std::vector > badHarvestPosList; + std::map badHarvestPosList; + // time_t lastBadHarvestListPurge; + std::pair lastHarvestResourceTarget; + + // std::pair > currentTargetPathTaken; + + static Game *game; + + bool ignoreCheckCommand; + + uint32 lastStuckFrame; + Vec2i lastStuckPos; + + uint32 lastPathfindFailedFrame; + Vec2i lastPathfindFailedPos; + bool usePathfinderExtendedMaxNodes; + int32 maxQueuedCommandDisplayCount; - UnitAttackBoostEffectOriginator currentAttackBoostOriginatorEffect; + UnitAttackBoostEffectOriginator currentAttackBoostOriginatorEffect; - std::vector currentAttackBoostEffects; + std::vector currentAttackBoostEffects; - Mutex *mutexCommands; + Mutex *mutexCommands; - //static Mutex mutexDeletedUnits; - //static std::map deletedUnits; + // static Mutex mutexDeletedUnits; + // static std::map deletedUnits; - bool changedActiveCommand; - uint32 lastChangedActiveCommandFrame; - uint32 changedActiveCommandFrame; + bool changedActiveCommand; + uint32 lastChangedActiveCommandFrame; + uint32 changedActiveCommandFrame; - int32 lastAttackerUnitId; - int32 lastAttackedUnitId; - CauseOfDeathType causeOfDeath; + int32 lastAttackerUnitId; + int32 lastAttackedUnitId; + CauseOfDeathType causeOfDeath; - uint32 pathfindFailedConsecutiveFrameCount; - Vec2i currentPathFinderDesiredFinalPos; + uint32 pathfindFailedConsecutiveFrameCount; + Vec2i currentPathFinderDesiredFinalPos; - RandomGen random; - int32 pathFindRefreshCellCount; + RandomGen random; + int32 pathFindRefreshCellCount; - FowAlphaCellsLookupItem cachedFow; - Vec2i cachedFowPos; + FowAlphaCellsLookupItem cachedFow; + Vec2i cachedFowPos; - ExploredCellsLookupItem cacheExploredCells; - std::pair cacheExploredCellsKey; + ExploredCellsLookupItem cacheExploredCells; + std::pair cacheExploredCellsKey; - Vec2i lastHarvestedResourcePos; + Vec2i lastHarvestedResourcePos; - string networkCRCLogInfo; - string networkCRCParticleLogInfo; - vector networkCRCDecHpList; - vector networkCRCParticleInfoList; + string networkCRCLogInfo; + string networkCRCParticleLogInfo; + vector networkCRCDecHpList; + vector networkCRCParticleInfoList; public: - Unit(int id, UnitPathInterface *path, const Vec2i &pos, const UnitType *type, Faction *faction, Map *map, CardinalDir placeFacing); - virtual ~Unit(); - - //static bool isUnitDeleted(void *unit); - - static void setGame(Game *value) { game=value;} - - inline int getPathFindRefreshCellCount() const { return pathFindRefreshCellCount; } - - void setCurrentPathFinderDesiredFinalPos(const Vec2i &finalPos) { currentPathFinderDesiredFinalPos = finalPos; } - Vec2i getCurrentPathFinderDesiredFinalPos() const { return currentPathFinderDesiredFinalPos; } - - const UnitAttackBoostEffectOriginator & getAttackBoostOriginatorEffect() const { return currentAttackBoostOriginatorEffect; } - bool unitHasAttackBoost(const AttackBoost *boost, const Unit *source); - - inline uint32 getPathfindFailedConsecutiveFrameCount() const { return pathfindFailedConsecutiveFrameCount; } - inline void incrementPathfindFailedConsecutiveFrameCount() { pathfindFailedConsecutiveFrameCount++; } - inline void resetPathfindFailedConsecutiveFrameCount() { pathfindFailedConsecutiveFrameCount=0; } - - const FowAlphaCellsLookupItem & getCachedFow() const { return cachedFow; } - FowAlphaCellsLookupItem getFogOfWarRadius(bool useCache) const; - void calculateFogOfWarRadius(bool forceRefresh=false); - - //queries - Command *getCurrrentCommandThreadSafe(); - void setIgnoreCheckCommand(bool value) { ignoreCheckCommand=value;} - inline bool getIgnoreCheckCommand() const {return ignoreCheckCommand;} - inline int getId() const {return id;} - inline Field getCurrField() const {return currField;} - inline int getLoadCount() const {return loadCount;} - - //inline int getLastAnimProgress() const {return lastAnimProgress;} - //inline int getAnimProgress() const {return animProgress;} - inline float getLastAnimProgressAsFloat() const {return static_cast(lastAnimProgress) / ANIMATION_SPEED_MULTIPLIER;} - inline float getAnimProgressAsFloat() const {return static_cast(animProgress) / ANIMATION_SPEED_MULTIPLIER;} - - inline float getHightlight() const {return highlight;} - inline int getProgress2() const {return progress2;} - inline int getFactionIndex() const { - return faction->getIndex(); - } - inline int getTeam() const { - return faction->getTeam(); - } - inline int getHp() const {return hp;} - inline int getEp() const {return ep;} - int getProductionPercent() const; - float getProgressRatio() const; - float getHpRatio() const; - float getEpRatio() const; - inline bool getToBeUndertaken() const {return toBeUndertaken;} - inline Vec2i getTargetPos() const {return targetPos;} - inline Vec3f getTargetVec() const {return targetVec;} - inline Field getTargetField() const {return targetField;} - inline Vec2i getMeetingPos() const {return meetingPos;} - inline Faction *getFaction() const {return faction;} - inline const ResourceType *getLoadType() const {return loadType;} - - inline const UnitType *getType() const {return type;} - void setType(const UnitType *newType); - inline const UnitType *getPreMorphType() const {return preMorph_type;} - - inline const SkillType *getCurrSkill() const {return currSkill;} - inline const TotalUpgrade *getTotalUpgrade() const {return &totalUpgrade;} - inline float getRotation() const {return rotation;} - float getRotationX() const; - float getRotationZ() const; - ParticleSystem *getFire() const; - inline int getKills() const {return kills;} - inline int getEnemyKills() const {return enemyKills;} - inline const Level *getLevel() const {return level;} - const Level *getNextLevel() const; - string getFullName(bool translatedValue) const; - inline const UnitPathInterface *getPath() const {return unitPath;} - inline UnitPathInterface *getPath() {return unitPath;} - inline WaypointPath *getWaypointPath() {return &waypointPath;} - - inline int getLastAttackerUnitId() const { return lastAttackerUnitId; } - inline void setLastAttackerUnitId(int unitId) { lastAttackerUnitId = unitId; } - - inline int getLastAttackedUnitId() const { return lastAttackedUnitId; } - inline void setLastAttackedUnitId(int unitId) { lastAttackedUnitId = unitId; } - - inline CauseOfDeathType getCauseOfDeath() const { return causeOfDeath; } - inline void setCauseOfDeath(CauseOfDeathType cause) { causeOfDeath = cause; } - - //pos - inline Vec2i getPosNotThreadSafe() const {return pos;} - Vec2i getPos(); - Vec2i getPosWithCellMapSet() const; - inline Vec2i getLastPos() const {return lastPos;} - Vec2i getCenteredPos() const; - Vec2f getFloatCenteredPos() const; - Vec2i getCellPos() const; - - //is - inline bool isHighlighted() const {return highlight>0.f;} - inline bool isDead() const {return !alive;} - inline bool isAlive() const {return alive;} - bool isOperative() const; - bool isBeingBuilt() const; - bool isBuilt() const; - bool isBuildCommandPending() const; - UnitBuildInfo getBuildCommandPendingInfo() const; - - bool isAnimProgressBound() const; - bool isPutrefacting() const { - return deadCount!=0; + Unit(int id, UnitPathInterface *path, const Vec2i &pos, const UnitType *type, + Faction *faction, Map *map, CardinalDir placeFacing); + virtual ~Unit(); + + // static bool isUnitDeleted(void *unit); + + static void setGame(Game *value) { game = value; } + + inline int getPathFindRefreshCellCount() const { + return pathFindRefreshCellCount; + } + + void setCurrentPathFinderDesiredFinalPos(const Vec2i &finalPos) { + currentPathFinderDesiredFinalPos = finalPos; + } + Vec2i getCurrentPathFinderDesiredFinalPos() const { + return currentPathFinderDesiredFinalPos; + } + + const UnitAttackBoostEffectOriginator & + getAttackBoostOriginatorEffect() const { + return currentAttackBoostOriginatorEffect; + } + bool unitHasAttackBoost(const AttackBoost *boost, const Unit *source); + + inline uint32 getPathfindFailedConsecutiveFrameCount() const { + return pathfindFailedConsecutiveFrameCount; + } + inline void incrementPathfindFailedConsecutiveFrameCount() { + pathfindFailedConsecutiveFrameCount++; + } + inline void resetPathfindFailedConsecutiveFrameCount() { + pathfindFailedConsecutiveFrameCount = 0; + } + + const FowAlphaCellsLookupItem &getCachedFow() const { return cachedFow; } + FowAlphaCellsLookupItem getFogOfWarRadius(bool useCache) const; + void calculateFogOfWarRadius(bool forceRefresh = false); + + // queries + Command *getCurrrentCommandThreadSafe(); + void setIgnoreCheckCommand(bool value) { ignoreCheckCommand = value; } + inline bool getIgnoreCheckCommand() const { return ignoreCheckCommand; } + inline int getId() const { return id; } + inline Field getCurrField() const { return currField; } + inline int getLoadCount() const { return loadCount; } + + // inline int getLastAnimProgress() const {return + // lastAnimProgress;} inline int getAnimProgress() const + // {return animProgress;} + inline float getLastAnimProgressAsFloat() const { + return static_cast(lastAnimProgress) / ANIMATION_SPEED_MULTIPLIER; + } + inline float getAnimProgressAsFloat() const { + return static_cast(animProgress) / ANIMATION_SPEED_MULTIPLIER; + } + + inline float getHightlight() const { return highlight; } + inline int getProgress2() const { return progress2; } + inline int getFactionIndex() const { return faction->getIndex(); } + inline int getTeam() const { return faction->getTeam(); } + inline int getHp() const { return hp; } + inline int getEp() const { return ep; } + int getProductionPercent() const; + float getProgressRatio() const; + float getHpRatio() const; + float getEpRatio() const; + inline bool getToBeUndertaken() const { return toBeUndertaken; } + inline Vec2i getTargetPos() const { return targetPos; } + inline Vec3f getTargetVec() const { return targetVec; } + inline Field getTargetField() const { return targetField; } + inline Vec2i getMeetingPos() const { return meetingPos; } + inline Faction *getFaction() const { return faction; } + inline const ResourceType *getLoadType() const { return loadType; } + + inline const UnitType *getType() const { return type; } + void setType(const UnitType *newType); + inline const UnitType *getPreMorphType() const { return preMorph_type; } + + inline const SkillType *getCurrSkill() const { return currSkill; } + inline const TotalUpgrade *getTotalUpgrade() const { return &totalUpgrade; } + inline float getRotation() const { return rotation; } + float getRotationX() const; + float getRotationZ() const; + ParticleSystem *getFire() const; + inline int getKills() const { return kills; } + inline int getEnemyKills() const { return enemyKills; } + inline const Level *getLevel() const { return level; } + const Level *getNextLevel() const; + string getFullName(bool translatedValue) const; + inline const UnitPathInterface *getPath() const { return unitPath; } + inline UnitPathInterface *getPath() { return unitPath; } + inline WaypointPath *getWaypointPath() { return &waypointPath; } + + inline int getLastAttackerUnitId() const { return lastAttackerUnitId; } + inline void setLastAttackerUnitId(int unitId) { lastAttackerUnitId = unitId; } + + inline int getLastAttackedUnitId() const { return lastAttackedUnitId; } + inline void setLastAttackedUnitId(int unitId) { lastAttackedUnitId = unitId; } + + inline CauseOfDeathType getCauseOfDeath() const { return causeOfDeath; } + inline void setCauseOfDeath(CauseOfDeathType cause) { causeOfDeath = cause; } + + // pos + inline Vec2i getPosNotThreadSafe() const { return pos; } + Vec2i getPos(); + Vec2i getPosWithCellMapSet() const; + inline Vec2i getLastPos() const { return lastPos; } + Vec2i getCenteredPos() const; + Vec2f getFloatCenteredPos() const; + Vec2i getCellPos() const; + + // is + inline bool isHighlighted() const { return highlight > 0.f; } + inline bool isDead() const { return !alive; } + inline bool isAlive() const { return alive; } + bool isOperative() const; + bool isBeingBuilt() const; + bool isBuilt() const; + bool isBuildCommandPending() const; + UnitBuildInfo getBuildCommandPendingInfo() const; + + bool isAnimProgressBound() const; + bool isPutrefacting() const { return deadCount != 0; } + bool isAlly(const Unit *unit) const; + bool isDamaged() const; + bool isInteresting(InterestingUnitType iut) const; + + // set + // void setCurrField(Field currField); + void setCurrSkill(const SkillType *currSkill); + void setCurrSkill(SkillClass sc); + + void setMorphFieldsBlocked(bool value) { this->morphFieldsBlocked = value; } + bool getMorphFieldsBlocked() const { return morphFieldsBlocked; } + + inline void setLastHarvestedResourcePos(Vec2i pos) { + this->lastHarvestedResourcePos = pos; + } + inline Vec2i getLastHarvestedResourcePos() const { + return this->lastHarvestedResourcePos; + } + + inline void setLoadCount(int loadCount) { this->loadCount = loadCount; } + inline void setLoadType(const ResourceType *loadType) { + this->loadType = loadType; + } + inline void setProgress2(int progress2) { this->progress2 = progress2; } + void setPos(const Vec2i &pos, bool clearPathFinder = false, + bool threaded = false); + void refreshPos(bool forceRefresh = false); + void setTargetPos(const Vec2i &targetPos, bool threaded = false); + void setTarget(const Unit *unit); + // void setTargetVec(const Vec3f &targetVec); + void setMeetingPos(const Vec2i &meetingPos); + void setVisible(const bool visible); + inline bool getVisible() const { return visible; } + + // render related + // const Model *getCurrentModel(); + Model *getCurrentModelPtr(); + Vec3f getCurrMidHeightVector() const; + Vec3f getCurrVectorForParticlesystems() const; + Vec3f getCurrVectorAsTarget() const; + Vec3f getCurrBurnVector() const; + Vec3f getCurrVectorFlat() const; + Vec3f getVectorFlat(const Vec2i &lastPosValue, + const Vec2i &curPosValue) const; + + // command related + bool anyCommand(bool validateCommandtype = false) const; + inline Command *getCurrCommand() const { + if (commands.empty() == false) { + return commands.front(); + } + return NULL; + } + void replaceCurrCommand(Command *cmd); + int getCountOfProducedUnitsPreExistence(const UnitType *ut) const; + unsigned int getCommandSize() const; + std::pair + giveCommand(Command *command, bool tryQueue = false); // give a command + CommandResult finishCommand(); // command finished + CommandResult cancelCommand(); // cancel canceled + + // lifecycle + void create(bool startingUnit = false); + void born(const CommandType *ct); + void kill(); + void undertake(); + + // observers + void addObserver(UnitObserver *unitObserver); + // void removeObserver(UnitObserver *unitObserver); + void notifyObservers(UnitObserver::Event event); + + // other + void resetHighlight(); + const CommandType *computeCommandType(const Vec2i &pos, + const Unit *targetUnit = NULL) const; + string getDesc(bool translatedValue) const; + string getDescExtension(bool translatedValue) const; + bool computeEp(); + // bool computeHp(); + bool repair(); + bool decHp(int i); + int update2(); + bool update(); + void tick(); + RandomGen *getRandom(bool threadAccessAllowed = false); + + bool applyAttackBoost(const AttackBoost *boost, const Unit *source); + void deapplyAttackBoost(const AttackBoost *boost, const Unit *source); + + void applyUpgrade(const UpgradeType *upgradeType); + void computeTotalUpgrade(); + void incKills(int team); + bool morph(const MorphCommandType *mct, int frameIndex); + std::pair checkCommand(Command *command) const; + void applyCommand(Command *command); + + void setModelFacing(CardinalDir value); + inline CardinalDir getModelFacing() const { return modelFacing; } + + bool isMeetingPointSettable() const; + + inline int getLastRenderFrame() const { return lastRenderFrame; } + inline void setLastRenderFrame(int value) { lastRenderFrame = value; } + + inline int getRetryCurrCommandCount() const { return retryCurrCommandCount; } + inline void setRetryCurrCommandCount(int value) { + retryCurrCommandCount = value; + } + + inline Vec3f getScreenPos() const { return screenPos; } + void setScreenPos(Vec3f value) { screenPos = value; } + + inline string getCurrentUnitTitle() const { return currentUnitTitle; } + void setCurrentUnitTitle(string value) { currentUnitTitle = value; } + + void exploreCells(bool forceRefresh = false); + + inline bool getInBailOutAttempt() const { return inBailOutAttempt; } + inline void setInBailOutAttempt(bool value) { inBailOutAttempt = value; } + + // std::vector > getBadHarvestPosList() const { return + // badHarvestPosList; } void + // setBadHarvestPosList(std::vector > value) { + // badHarvestPosList = value; } + void addBadHarvestPos(const Vec2i &value); + // void removeBadHarvestPos(const Vec2i &value); + inline bool isBadHarvestPos(const Vec2i &value, + bool checkPeerUnits = true) const { + bool result = false; + if (badHarvestPosList.empty() == true) { + return result; } - bool isAlly(const Unit *unit) const; - bool isDamaged() const; - bool isInteresting(InterestingUnitType iut) const; - - //set - //void setCurrField(Field currField); - void setCurrSkill(const SkillType *currSkill); - void setCurrSkill(SkillClass sc); - - void setMorphFieldsBlocked ( bool value ) {this->morphFieldsBlocked=value;} - bool getMorphFieldsBlocked() const { return morphFieldsBlocked; } - - inline void setLastHarvestedResourcePos(Vec2i pos) { this->lastHarvestedResourcePos = pos; } - inline Vec2i getLastHarvestedResourcePos() const { return this->lastHarvestedResourcePos; } - - inline void setLoadCount(int loadCount) {this->loadCount= loadCount;} - inline void setLoadType(const ResourceType *loadType) {this->loadType= loadType;} - inline void setProgress2(int progress2) {this->progress2= progress2;} - void setPos(const Vec2i &pos,bool clearPathFinder=false, bool threaded=false); - void refreshPos(bool forceRefresh=false); - void setTargetPos(const Vec2i &targetPos, bool threaded=false); - void setTarget(const Unit *unit); - //void setTargetVec(const Vec3f &targetVec); - void setMeetingPos(const Vec2i &meetingPos); - void setVisible(const bool visible); - inline bool getVisible() const { return visible; } - - //render related - //const Model *getCurrentModel(); - Model *getCurrentModelPtr(); - Vec3f getCurrMidHeightVector() const; - Vec3f getCurrVectorForParticlesystems() const; - Vec3f getCurrVectorAsTarget() const; - Vec3f getCurrBurnVector() const; - Vec3f getCurrVectorFlat() const; - Vec3f getVectorFlat(const Vec2i &lastPosValue, const Vec2i &curPosValue) const; - - //command related - bool anyCommand(bool validateCommandtype=false) const; - inline Command *getCurrCommand() const { - if(commands.empty() == false) { - return commands.front(); - } - return NULL; - } - void replaceCurrCommand(Command *cmd); - int getCountOfProducedUnitsPreExistence(const UnitType *ut) const; - unsigned int getCommandSize() const; - std::pair giveCommand(Command *command, bool tryQueue = false); //give a command - CommandResult finishCommand(); //command finished - CommandResult cancelCommand(); //cancel canceled - - //lifecycle - void create(bool startingUnit= false); - void born(const CommandType *ct); - void kill(); - void undertake(); - - //observers - void addObserver(UnitObserver *unitObserver) ; - //void removeObserver(UnitObserver *unitObserver); - void notifyObservers(UnitObserver::Event event); - - //other - void resetHighlight(); - const CommandType *computeCommandType(const Vec2i &pos, const Unit *targetUnit= NULL) const; - string getDesc(bool translatedValue) const; - string getDescExtension(bool translatedValue) const; - bool computeEp(); - //bool computeHp(); - bool repair(); - bool decHp(int i); - int update2(); - bool update(); - void tick(); - RandomGen* getRandom(bool threadAccessAllowed=false); - - bool applyAttackBoost(const AttackBoost *boost, const Unit *source); - void deapplyAttackBoost(const AttackBoost *boost, const Unit *source); - - void applyUpgrade(const UpgradeType *upgradeType); - void computeTotalUpgrade(); - void incKills(int team); - bool morph(const MorphCommandType *mct, int frameIndex); - std::pair checkCommand(Command *command) const; - void applyCommand(Command *command); - - void setModelFacing(CardinalDir value); - inline CardinalDir getModelFacing() const { return modelFacing; } - - bool isMeetingPointSettable() const; - - inline int getLastRenderFrame() const { return lastRenderFrame; } - inline void setLastRenderFrame(int value) { lastRenderFrame = value; } - - inline int getRetryCurrCommandCount() const { return retryCurrCommandCount; } - inline void setRetryCurrCommandCount(int value) { retryCurrCommandCount = value; } - - inline Vec3f getScreenPos() const { return screenPos; } - void setScreenPos(Vec3f value) { screenPos = value; } - - inline string getCurrentUnitTitle() const {return currentUnitTitle;} - void setCurrentUnitTitle(string value) { currentUnitTitle = value;} - - void exploreCells(bool forceRefresh=false); - - inline bool getInBailOutAttempt() const { return inBailOutAttempt; } - inline void setInBailOutAttempt(bool value) { inBailOutAttempt = value; } - - //std::vector > getBadHarvestPosList() const { return badHarvestPosList; } - //void setBadHarvestPosList(std::vector > value) { badHarvestPosList = value; } - void addBadHarvestPos(const Vec2i &value); - //void removeBadHarvestPos(const Vec2i &value); - inline bool isBadHarvestPos(const Vec2i &value,bool checkPeerUnits=true) const { - bool result = false; - if(badHarvestPosList.empty() == true) { - return result; - } - - std::map::const_iterator iter = badHarvestPosList.find(value); - if(iter != badHarvestPosList.end()) { - result = true; - } - else if(checkPeerUnits == true) { - // Check if any other units of similar type have this position tagged - // as bad? - for(int i = 0; i < this->getFaction()->getUnitCount(); ++i) { - Unit *peerUnit = this->getFaction()->getUnit(i); - if( peerUnit != NULL && peerUnit->getId() != this->getId() && - peerUnit->getType()->hasCommandClass(ccHarvest) == true && - peerUnit->getType()->getSize() <= this->getType()->getSize()) { - if(peerUnit->isBadHarvestPos(value,false) == true) { - result = true; - break; - } - } - } - } - - return result; - } - void cleanupOldBadHarvestPos(); - - void setLastHarvestResourceTarget(const Vec2i *pos); - inline std::pair getLastHarvestResourceTarget() const { return lastHarvestResourceTarget;} - - //std::pair > getCurrentTargetPathTaken() const { return currentTargetPathTaken; } - //void addCurrentTargetPathTakenCell(const Vec2i &target,const Vec2i &cell); - - void logSynchData(string file,int line,string source=""); - void logSynchDataThreaded(string file,int line,string source=""); - - std::string toString(bool crcMode=false) const; - bool needToUpdate(); - float getProgressAsFloat() const; - int64 getUpdateProgress(); - int64 getDiagonalFactor(); - int64 getHeightFactor(int64 speedMultiplier=PROGRESS_SPEED_MULTIPLIER); - int64 getSpeedDenominator(int64 updateFPS); - bool isChangedActiveCommand() const { return changedActiveCommand; } - - bool isLastStuckFrameWithinCurrentFrameTolerance(bool evalMode); - inline uint32 getLastStuckFrame() const { return lastStuckFrame; } - //inline void setLastStuckFrame(uint32 value) { lastStuckFrame = value; } - void setLastStuckFrameToCurrentFrame(); - - inline Vec2i getLastStuckPos() const { return lastStuckPos; } - inline void setLastStuckPos(Vec2i pos) { lastStuckPos = pos; } - - bool isLastPathfindFailedFrameWithinCurrentFrameTolerance() const; - inline uint32 getLastPathfindFailedFrame() const { return lastPathfindFailedFrame; } - inline void setLastPathfindFailedFrame(uint32 value) { lastPathfindFailedFrame = value; } - void setLastPathfindFailedFrameToCurrentFrame(); - - inline Vec2i getLastPathfindFailedPos() const { return lastPathfindFailedPos; } - inline void setLastPathfindFailedPos(Vec2i pos) { lastPathfindFailedPos = pos; } - - inline bool getUsePathfinderExtendedMaxNodes() const { return usePathfinderExtendedMaxNodes; } - inline void setUsePathfinderExtendedMaxNodes(bool value) { usePathfinderExtendedMaxNodes = value; } - - void updateTimedParticles(); - void setMeshPosInParticleSystem(UnitParticleSystem *ups); - - virtual string getUniquePickName() const; - void saveGame(XmlNode *rootNode); - static Unit * loadGame(const XmlNode *rootNode,GameSettings *settings,Faction *faction, World *world); - - void clearCaches(); - bool showTranslatedTechTree() const; - - void addAttackParticleSystem(ParticleSystem *ps); - - Checksum getCRC(); - - virtual void end(ParticleSystem *particleSystem); - virtual void logParticleInfo(string info); - void setNetworkCRCParticleLogInfo(string networkCRCParticleLogInfo) { this->networkCRCParticleLogInfo = networkCRCParticleLogInfo; } - void clearParticleInfo(); - void addNetworkCRCDecHp(string info); - void clearNetworkCRCDecHpList(); - -private: - - void cleanupAllParticlesystems(); - bool isNetworkCRCEnabled(); - string getNetworkCRCDecHpList() const; - string getParticleInfo() const; - - float computeHeight(const Vec2i &pos) const; - void calculateXZRotation(); - void AnimCycleStarts(); - void updateTarget(); - void clearCommands(); - void deleteQueuedCommand(Command *command); - CommandResult undoCommand(Command *command); - void stopDamageParticles(bool force); - void startDamageParticles(); - - uint32 getFrameCount() const; - - void checkCustomizedParticleTriggers(bool force); - void checkCustomizedUnitParticleTriggers(); - void checkCustomizedUnitParticleListTriggers(const UnitParticleSystemTypes &unitParticleSystemTypesList, - bool applySkillChangeParticles); - void queueTimedParticles(const UnitParticleSystemTypes &unitParticleSystemTypesList); - - bool checkModelStateInfoForNewHpValue(); - void checkUnitLevel(); - - void morphAttackBoosts(Unit *unit); - int64 getUpdatedProgress(int64 currentProgress, int64 updateFPS, int64 speed, int64 diagonalFactor, int64 heightFactor); + std::map::const_iterator iter = badHarvestPosList.find(value); + if (iter != badHarvestPosList.end()) { + result = true; + } else if (checkPeerUnits == true) { + // Check if any other units of similar type have this position tagged + // as bad? + for (int i = 0; i < this->getFaction()->getUnitCount(); ++i) { + Unit *peerUnit = this->getFaction()->getUnit(i); + if (peerUnit != NULL && peerUnit->getId() != this->getId() && + peerUnit->getType()->hasCommandClass(ccHarvest) == true && + peerUnit->getType()->getSize() <= this->getType()->getSize()) { + if (peerUnit->isBadHarvestPos(value, false) == true) { + result = true; + break; + } + } + } + } - void logSynchDataCommon(string file,int line,string source="",bool threadedMode=false); - void updateAttackBoostProgress(const Game* game); + return result; + } + void cleanupOldBadHarvestPos(); + + void setLastHarvestResourceTarget(const Vec2i *pos); + inline std::pair getLastHarvestResourceTarget() const { + return lastHarvestResourceTarget; + } + + // std::pair > getCurrentTargetPathTaken() const { + // return currentTargetPathTaken; } void addCurrentTargetPathTakenCell(const + // Vec2i &target,const Vec2i &cell); + + void logSynchData(string file, int line, string source = ""); + void logSynchDataThreaded(string file, int line, string source = ""); + + std::string toString(bool crcMode = false) const; + bool needToUpdate(); + float getProgressAsFloat() const; + int64 getUpdateProgress(); + int64 getDiagonalFactor(); + int64 getHeightFactor(int64 speedMultiplier = PROGRESS_SPEED_MULTIPLIER); + int64 getSpeedDenominator(int64 updateFPS); + bool isChangedActiveCommand() const { return changedActiveCommand; } + + bool isLastStuckFrameWithinCurrentFrameTolerance(bool evalMode); + inline uint32 getLastStuckFrame() const { return lastStuckFrame; } + // inline void setLastStuckFrame(uint32 value) { lastStuckFrame = value; } + void setLastStuckFrameToCurrentFrame(); + + inline Vec2i getLastStuckPos() const { return lastStuckPos; } + inline void setLastStuckPos(Vec2i pos) { lastStuckPos = pos; } + + bool isLastPathfindFailedFrameWithinCurrentFrameTolerance() const; + inline uint32 getLastPathfindFailedFrame() const { + return lastPathfindFailedFrame; + } + inline void setLastPathfindFailedFrame(uint32 value) { + lastPathfindFailedFrame = value; + } + void setLastPathfindFailedFrameToCurrentFrame(); + + inline Vec2i getLastPathfindFailedPos() const { + return lastPathfindFailedPos; + } + inline void setLastPathfindFailedPos(Vec2i pos) { + lastPathfindFailedPos = pos; + } + + inline bool getUsePathfinderExtendedMaxNodes() const { + return usePathfinderExtendedMaxNodes; + } + inline void setUsePathfinderExtendedMaxNodes(bool value) { + usePathfinderExtendedMaxNodes = value; + } + + void updateTimedParticles(); + void setMeshPosInParticleSystem(UnitParticleSystem *ups); + + virtual string getUniquePickName() const; + void saveGame(XmlNode *rootNode); + static Unit *loadGame(const XmlNode *rootNode, GameSettings *settings, + Faction *faction, World *world); + + void clearCaches(); + bool showTranslatedTechTree() const; + + void addAttackParticleSystem(ParticleSystem *ps); + + Checksum getCRC(); + + virtual void end(ParticleSystem *particleSystem); + virtual void logParticleInfo(string info); + void setNetworkCRCParticleLogInfo(string networkCRCParticleLogInfo) { + this->networkCRCParticleLogInfo = networkCRCParticleLogInfo; + } + void clearParticleInfo(); + void addNetworkCRCDecHp(string info); + void clearNetworkCRCDecHpList(); - void setAlive(bool value); +private: + void cleanupAllParticlesystems(); + bool isNetworkCRCEnabled(); + string getNetworkCRCDecHpList() const; + string getParticleInfo() const; + + float computeHeight(const Vec2i &pos) const; + void calculateXZRotation(); + void AnimCycleStarts(); + void updateTarget(); + void clearCommands(); + void deleteQueuedCommand(Command *command); + CommandResult undoCommand(Command *command); + void stopDamageParticles(bool force); + void startDamageParticles(); + + uint32 getFrameCount() const; + + void checkCustomizedParticleTriggers(bool force); + void checkCustomizedUnitParticleTriggers(); + void checkCustomizedUnitParticleListTriggers( + const UnitParticleSystemTypes &unitParticleSystemTypesList, + bool applySkillChangeParticles); + void queueTimedParticles( + const UnitParticleSystemTypes &unitParticleSystemTypesList); + + bool checkModelStateInfoForNewHpValue(); + void checkUnitLevel(); + + void morphAttackBoosts(Unit *unit); + + int64 getUpdatedProgress(int64 currentProgress, int64 updateFPS, int64 speed, + int64 diagonalFactor, int64 heightFactor); + + void logSynchDataCommon(string file, int line, string source = "", + bool threadedMode = false); + void updateAttackBoostProgress(const Game *game); + + void setAlive(bool value); }; -}}// end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/type_instances/upgrade.cpp b/source/glest_game/type_instances/upgrade.cpp index 2a0233fdd..3a3ea7b6d 100644 --- a/source/glest_game/type_instances/upgrade.cpp +++ b/source/glest_game/type_instances/upgrade.cpp @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,87 +13,84 @@ #include -#include "unit.h" -#include "util.h" -#include "upgrade_type.h" #include "conversion.h" #include "faction.h" #include "faction_type.h" #include "leak_dumper.h" +#include "unit.h" +#include "upgrade_type.h" +#include "util.h" using namespace std; using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class Upgrade // ===================================================== Upgrade::Upgrade() { - state= usUpgrading; - this->factionIndex= -1; - this->type= NULL; + state = usUpgrading; + this->factionIndex = -1; + this->type = NULL; } Upgrade::Upgrade(const UpgradeType *type, int factionIndex) { - state= usUpgrading; - this->factionIndex= factionIndex; - this->type= type; + state = usUpgrading; + this->factionIndex = factionIndex; + this->type = type; } // ============== get ============== -UpgradeState Upgrade::getState() const { - return state; -} +UpgradeState Upgrade::getState() const { return state; } -int Upgrade::getFactionIndex() const { - return factionIndex; -} +int Upgrade::getFactionIndex() const { return factionIndex; } -const UpgradeType * Upgrade::getType() const { - return type; -} +const UpgradeType *Upgrade::getType() const { return type; } // ============== set ============== -void Upgrade::setState(UpgradeState state) { - this->state= state; -} +void Upgrade::setState(UpgradeState state) { this->state = state; } std::string Upgrade::toString() const { - std::string result = ""; + std::string result = ""; - result += " state = " + intToStr(state) + " factionIndex = " + intToStr(factionIndex); - if(type != NULL) { - result += " type = " + type->getReqDesc(false); - } + result += " state = " + intToStr(state) + + " factionIndex = " + intToStr(factionIndex); + if (type != NULL) { + result += " type = " + type->getReqDesc(false); + } - return result; + return result; } void Upgrade::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *upgradeNode = rootNode->addChild("Upgrade"); + std::map mapTagReplacements; + XmlNode *upgradeNode = rootNode->addChild("Upgrade"); - upgradeNode->addAttribute("state",intToStr(state), mapTagReplacements); - upgradeNode->addAttribute("factionIndex",intToStr(factionIndex), mapTagReplacements); - upgradeNode->addAttribute("type",type->getName(), mapTagReplacements); + upgradeNode->addAttribute("state", intToStr(state), mapTagReplacements); + upgradeNode->addAttribute("factionIndex", intToStr(factionIndex), + mapTagReplacements); + upgradeNode->addAttribute("type", type->getName(), mapTagReplacements); } -Upgrade * Upgrade::loadGame(const XmlNode *rootNode,Faction *faction) { - Upgrade *newUpgrade = new Upgrade(); +Upgrade *Upgrade::loadGame(const XmlNode *rootNode, Faction *faction) { + Upgrade *newUpgrade = new Upgrade(); - const XmlNode *upgradeNode = rootNode; + const XmlNode *upgradeNode = rootNode; - //description = upgrademanagerNode->getAttribute("description")->getValue(); + // description = upgrademanagerNode->getAttribute("description")->getValue(); - newUpgrade->state = static_cast(upgradeNode->getAttribute("state")->getIntValue()); - newUpgrade->factionIndex = upgradeNode->getAttribute("factionIndex")->getIntValue(); - string unitTypeName = upgradeNode->getAttribute("type")->getValue(); - newUpgrade->type = faction->getType()->getUpgradeType(unitTypeName); + newUpgrade->state = static_cast( + upgradeNode->getAttribute("state")->getIntValue()); + newUpgrade->factionIndex = + upgradeNode->getAttribute("factionIndex")->getIntValue(); + string unitTypeName = upgradeNode->getAttribute("type")->getValue(); + newUpgrade->type = faction->getType()->getUpgradeType(unitTypeName); - return newUpgrade; + return newUpgrade; } // ===================================================== @@ -101,185 +98,200 @@ Upgrade * Upgrade::loadGame(const XmlNode *rootNode,Faction *faction) { // ===================================================== UpgradeManager::~UpgradeManager() { - upgradesLookup.clear(); - deleteValues(upgrades.begin(), upgrades.end()); + upgradesLookup.clear(); + deleteValues(upgrades.begin(), upgrades.end()); } -void UpgradeManager::startUpgrade(const UpgradeType *upgradeType, int factionIndex) { - Upgrade *upgrade = new Upgrade(upgradeType, factionIndex); - upgrades.push_back(upgrade); - upgradesLookup[upgradeType] = (int)upgrades.size()-1; +void UpgradeManager::startUpgrade(const UpgradeType *upgradeType, + int factionIndex) { + Upgrade *upgrade = new Upgrade(upgradeType, factionIndex); + upgrades.push_back(upgrade); + upgradesLookup[upgradeType] = (int)upgrades.size() - 1; } void UpgradeManager::cancelUpgrade(const UpgradeType *upgradeType) { - map::iterator iterFind = upgradesLookup.find(upgradeType); - if(iterFind != upgradesLookup.end()) { - if(iterFind->second >= (int)upgrades.size()) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Error canceling upgrade, iterFind->second >= upgrades.size() - [%d] : [%d]",iterFind->second,(int)upgrades.size()); - throw megaglest_runtime_error("Error canceling upgrade, upgrade not found in upgrade manager"); - } - int eraseIndex = iterFind->second; - upgrades.erase(upgrades.begin() + eraseIndex); - upgradesLookup.erase(upgradeType); - - for(map::iterator iterMap = upgradesLookup.begin(); - iterMap != upgradesLookup.end(); ++iterMap) { - if(iterMap->second >= (int)upgrades.size()) { - iterMap->second--; - } - if(iterMap->second < 0) { - upgradesLookup.erase(iterMap->first); - } - } - } - else { - throw megaglest_runtime_error("Error canceling upgrade, upgrade not found in upgrade manager"); - } - -/* - Upgrades::iterator it; - - for(it=upgrades.begin(); it!=upgrades.end(); it++){ - if((*it)->getType()==upgradeType){ - break; - } - } - - if(it!=upgrades.end()){ - upgrades.erase(it); - } - else{ - throw megaglest_runtime_error("Error canceling upgrade, upgrade not found in upgrade manager"); - } -*/ + map::iterator iterFind = + upgradesLookup.find(upgradeType); + if (iterFind != upgradesLookup.end()) { + if (iterFind->second >= (int)upgrades.size()) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "Error canceling upgrade, iterFind->second >= upgrades.size() - " + "[%d] : [%d]", + iterFind->second, (int)upgrades.size()); + throw megaglest_runtime_error( + "Error canceling upgrade, upgrade not found in upgrade manager"); + } + int eraseIndex = iterFind->second; + upgrades.erase(upgrades.begin() + eraseIndex); + upgradesLookup.erase(upgradeType); + + for (map::iterator iterMap = + upgradesLookup.begin(); + iterMap != upgradesLookup.end(); ++iterMap) { + if (iterMap->second >= (int)upgrades.size()) { + iterMap->second--; + } + if (iterMap->second < 0) { + upgradesLookup.erase(iterMap->first); + } + } + } else { + throw megaglest_runtime_error( + "Error canceling upgrade, upgrade not found in upgrade manager"); + } + + /* + Upgrades::iterator it; + + for(it=upgrades.begin(); it!=upgrades.end(); it++){ + if((*it)->getType()==upgradeType){ + break; + } + } + + if(it!=upgrades.end()){ + upgrades.erase(it); + } + else{ + throw megaglest_runtime_error("Error canceling upgrade, + upgrade not found in upgrade manager"); + } + */ } void UpgradeManager::finishUpgrade(const UpgradeType *upgradeType) { - map::iterator iterFind = upgradesLookup.find(upgradeType); - if(iterFind != upgradesLookup.end()) { - upgrades[iterFind->second]->setState(usUpgraded); - } - else { - throw megaglest_runtime_error("Error finishing upgrade, upgrade not found in upgrade manager"); - } - - -/* - Upgrades::iterator it; - - for(it=upgrades.begin(); it!=upgrades.end(); it++){ - if((*it)->getType()==upgradeType){ - break; - } - } - - if(it!=upgrades.end()){ - (*it)->setState(usUpgraded); - } - else{ - throw megaglest_runtime_error("Error finishing upgrade, upgrade not found in upgrade manager"); - } -*/ + map::iterator iterFind = + upgradesLookup.find(upgradeType); + if (iterFind != upgradesLookup.end()) { + upgrades[iterFind->second]->setState(usUpgraded); + } else { + throw megaglest_runtime_error( + "Error finishing upgrade, upgrade not found in upgrade manager"); + } + + /* + Upgrades::iterator it; + + for(it=upgrades.begin(); it!=upgrades.end(); it++){ + if((*it)->getType()==upgradeType){ + break; + } + } + + if(it!=upgrades.end()){ + (*it)->setState(usUpgraded); + } + else{ + throw megaglest_runtime_error("Error finishing upgrade, + upgrade not found in upgrade manager"); + } + */ } -bool UpgradeManager::isUpgradingOrUpgraded(const UpgradeType *upgradeType) const { - if(upgradesLookup.find(upgradeType) != upgradesLookup.end()) { - return true; - } +bool UpgradeManager::isUpgradingOrUpgraded( + const UpgradeType *upgradeType) const { + if (upgradesLookup.find(upgradeType) != upgradesLookup.end()) { + return true; + } + + return false; - return false; + /* + Upgrades::const_iterator it; -/* - Upgrades::const_iterator it; - - for(it= upgrades.begin(); it!=upgrades.end(); it++){ - if((*it)->getType()==upgradeType){ - return true; - } - } + for(it= upgrades.begin(); it!=upgrades.end(); it++){ + if((*it)->getType()==upgradeType){ + return true; + } + } - return false; -*/ + return false; + */ } bool UpgradeManager::isUpgraded(const UpgradeType *upgradeType) const { - map::const_iterator iterFind = upgradesLookup.find(upgradeType); - if(iterFind != upgradesLookup.end()) { - return (upgrades[iterFind->second]->getState() == usUpgraded); - } - return false; - -/* - for(Upgrades::const_iterator it= upgrades.begin(); it!=upgrades.end(); it++){ - if((*it)->getType()==upgradeType && (*it)->getState()==usUpgraded){ - return true; - } - } - return false; -*/ + map::const_iterator iterFind = + upgradesLookup.find(upgradeType); + if (iterFind != upgradesLookup.end()) { + return (upgrades[iterFind->second]->getState() == usUpgraded); + } + return false; + + /* + for(Upgrades::const_iterator it= upgrades.begin(); it!=upgrades.end(); + it++){ if((*it)->getType()==upgradeType && (*it)->getState()==usUpgraded){ + return true; + } + } + return false; + */ } bool UpgradeManager::isUpgrading(const UpgradeType *upgradeType) const { - map::const_iterator iterFind = upgradesLookup.find(upgradeType); - if(iterFind != upgradesLookup.end()) { - return (upgrades[iterFind->second]->getState() == usUpgrading); - } - return false; - -/* - for(Upgrades::const_iterator it= upgrades.begin(); it!=upgrades.end(); it++){ - if((*it)->getType()==upgradeType && (*it)->getState()==usUpgrading){ - return true; - } - } - return false; -*/ + map::const_iterator iterFind = + upgradesLookup.find(upgradeType); + if (iterFind != upgradesLookup.end()) { + return (upgrades[iterFind->second]->getState() == usUpgrading); + } + return false; + + /* + for(Upgrades::const_iterator it= upgrades.begin(); it!=upgrades.end(); + it++){ if((*it)->getType()==upgradeType && (*it)->getState()==usUpgrading){ + return true; + } + } + return false; + */ } -void UpgradeManager::computeTotalUpgrade(const Unit *unit, TotalUpgrade *totalUpgrade) const { - totalUpgrade->reset(); - for(Upgrades::const_iterator it= upgrades.begin(); it!=upgrades.end(); ++it) { - if((*it)->getFactionIndex() == unit->getFactionIndex() - && (*it)->getType()->isAffected(unit->getType()) - && (*it)->getState()==usUpgraded) - totalUpgrade->sum((*it)->getType(), unit); - } - +void UpgradeManager::computeTotalUpgrade(const Unit *unit, + TotalUpgrade *totalUpgrade) const { + totalUpgrade->reset(); + for (Upgrades::const_iterator it = upgrades.begin(); it != upgrades.end(); + ++it) { + if ((*it)->getFactionIndex() == unit->getFactionIndex() && + (*it)->getType()->isAffected(unit->getType()) && + (*it)->getState() == usUpgraded) + totalUpgrade->sum((*it)->getType(), unit); + } } std::string UpgradeManager::toString() const { - std::string result = "UpgradeCount: " + intToStr(this->getUpgradeCount()); - for(int idx = 0; idx < (int)upgrades.size(); idx++) { - result += " index = " + intToStr(idx) + " " + upgrades[idx]->toString(); - } - return result; + std::string result = "UpgradeCount: " + intToStr(this->getUpgradeCount()); + for (int idx = 0; idx < (int)upgrades.size(); idx++) { + result += " index = " + intToStr(idx) + " " + upgrades[idx]->toString(); + } + return result; } void UpgradeManager::saveGame(XmlNode *rootNode) { - //std::map mapTagReplacements; - XmlNode *upgrademanagerNode = rootNode->addChild("UpgradeManager"); + // std::map mapTagReplacements; + XmlNode *upgrademanagerNode = rootNode->addChild("UpgradeManager"); - for(unsigned int i = 0; i < upgrades.size(); ++i) { - upgrades[i]->saveGame(upgrademanagerNode); - } + for (unsigned int i = 0; i < upgrades.size(); ++i) { + upgrades[i]->saveGame(upgrademanagerNode); + } -// Upgrades upgrades; -// UgradesLookup upgradesLookup; + // Upgrades upgrades; + // UgradesLookup upgradesLookup; } -void UpgradeManager::loadGame(const XmlNode *rootNode,Faction *faction) { - const XmlNode *upgrademanagerNode = rootNode->getChild("UpgradeManager"); +void UpgradeManager::loadGame(const XmlNode *rootNode, Faction *faction) { + const XmlNode *upgrademanagerNode = rootNode->getChild("UpgradeManager"); - //description = upgrademanagerNode->getAttribute("description")->getValue(); + // description = upgrademanagerNode->getAttribute("description")->getValue(); - vector upgradeNodeList = upgrademanagerNode->getChildList("Upgrade"); - for(unsigned int i = 0; i < upgradeNodeList.size(); ++i) { - XmlNode *node = upgradeNodeList[i]; - Upgrade *newUpgrade = Upgrade::loadGame(node,faction); - upgrades.push_back(newUpgrade); - upgradesLookup[newUpgrade->getType()] = (int)upgrades.size()-1; - } + vector upgradeNodeList = + upgrademanagerNode->getChildList("Upgrade"); + for (unsigned int i = 0; i < upgradeNodeList.size(); ++i) { + XmlNode *node = upgradeNodeList[i]; + Upgrade *newUpgrade = Upgrade::loadGame(node, faction); + upgrades.push_back(newUpgrade); + upgradesLookup[newUpgrade->getType()] = (int)upgrades.size() - 1; + } } -}}// end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/type_instances/upgrade.h b/source/glest_game/type_instances/upgrade.h index ddbd42b62..a95d911af 100644 --- a/source/glest_game/type_instances/upgrade.h +++ b/source/glest_game/type_instances/upgrade.h @@ -3,209 +3,226 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== /** * @file - * Contains the Upgrade and UpgradeManager classes. This is what the factions need to manage - * upgrades (including starting, canceling, and finishing upgrades, figuring out which - * upgrades we have done, etc). + * Contains the Upgrade and UpgradeManager classes. This is what the factions + * need to manage upgrades (including starting, canceling, and finishing + * upgrades, figuring out which upgrades we have done, etc). */ #ifndef _GLEST_GAME_UPGRADE_H_ #define _GLEST_GAME_UPGRADE_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include -#include -#include -#include "xml_parser.h" #include "leak_dumper.h" +#include "xml_parser.h" +#include +#include +#include -using std::vector; -using std::map; using Shared::Xml::XmlNode; +using std::map; +using std::vector; -namespace Glest { namespace Game { +namespace Glest { +namespace Game { class Unit; class UpgradeType; class Faction; /** - * Stores the state of the upgrade (whether or not the upgrading process is complete). + * Stores the state of the upgrade (whether or not the upgrading process is + * complete). */ // TODO: Don't make this global; move it inside Upgrade enum UpgradeState { - usUpgrading, /**< The upgrade is currently in progress. */ - usUpgraded, /**< The upgrade is completed. */ + usUpgrading, /**< The upgrade is currently in progress. */ + usUpgraded, /**< The upgrade is completed. */ - upgradeStateCount // TODO: This should be unnecessary -- there's no need to iterate over this enum + upgradeStateCount // TODO: This should be unnecessary -- there's no need to + // iterate over this enum }; class UpgradeManager; class TotalUpgrade; /** - * An instance of an upgrade. Factions will typically have one upgrade of each type. This object - * groups the type, faction, and upgrade state (ie, has the upgrade been obtained yet?). + * An instance of an upgrade. Factions will typically have one upgrade of each + * type. This object groups the type, faction, and upgrade state (ie, has the + * upgrade been obtained yet?). */ class Upgrade { private: - UpgradeState state; - // TODO: I believe this is unnecessary. As far as I can tell, it's only used for checking - // that the unit we're applying UpgradeManager::computeTotalUpgrade to is in this faction. However, - // I don't see an circumstances when it wouldn't be (since the UpgradeManager already an aggregate - // of a faction and Unit directly gets the UpgradeManager from the faction (so it must have the - // same faction as the upgrades in the UpgradeManager). - int factionIndex; - const UpgradeType *type; - - friend class UpgradeManager; - - Upgrade(); + UpgradeState state; + // TODO: I believe this is unnecessary. As far as I can tell, it's only used + // for checking that the unit we're applying + // UpgradeManager::computeTotalUpgrade to is in this faction. However, I don't + // see an circumstances when it wouldn't be (since the UpgradeManager already + // an aggregate of a faction and Unit directly gets the UpgradeManager from + // the faction (so it must have the same faction as the upgrades in the + // UpgradeManager). + int factionIndex; + const UpgradeType *type; + + friend class UpgradeManager; + + Upgrade(); + public: - /** - * Creates an upgrade. The upgrade state will be set to UpgradeState::usUpgrading. - * @param upgradeType The type of the upgrade that this corresponds to. Upgrade types are - * essentially "classes" for upgrades. - * @param factionIndex The index of the faction that the upgrade belongs to. - */ - Upgrade(const UpgradeType *upgradeType, int factionIndex); + /** + * Creates an upgrade. The upgrade state will be set to + * UpgradeState::usUpgrading. + * @param upgradeType The type of the upgrade that this corresponds to. + * Upgrade types are essentially "classes" for upgrades. + * @param factionIndex The index of the faction that the upgrade belongs to. + */ + Upgrade(const UpgradeType *upgradeType, int factionIndex); private: - UpgradeState getState() const; - int getFactionIndex() const; - const UpgradeType * getType() const; - - void setState(UpgradeState state); - - /** - * Retrieves a string representation of the upgrade (detailing its state, type, and faction). - */ - std::string toString() const; - - /** - * Saves the object state into the given node. - * @param rootNode The UpgradeManager node to save object info to. - */ - void saveGame(XmlNode *rootNode); - - /** - * Loads the object state from the given node. - * @param rootNode The UpgradeManager node to retrieve object info from. - * @param faction The faction that the upgrade belongs to. Used to convert the upgrade type from - * the XML string. - */ - static Upgrade * loadGame(const XmlNode *rootNode,Faction *faction); + UpgradeState getState() const; + int getFactionIndex() const; + const UpgradeType *getType() const; + + void setState(UpgradeState state); + + /** + * Retrieves a string representation of the upgrade (detailing its state, + * type, and faction). + */ + std::string toString() const; + + /** + * Saves the object state into the given node. + * @param rootNode The UpgradeManager node to save object info to. + */ + void saveGame(XmlNode *rootNode); + + /** + * Loads the object state from the given node. + * @param rootNode The UpgradeManager node to retrieve object info from. + * @param faction The faction that the upgrade belongs to. Used to convert the + * upgrade type from the XML string. + */ + static Upgrade *loadGame(const XmlNode *rootNode, Faction *faction); }; /** - * Manages upgrades by starting, stopping, and finishing upgrades. Each faction has their own - * upgrade manager. + * Manages upgrades by starting, stopping, and finishing upgrades. Each faction + * has their own upgrade manager. */ -class UpgradeManager{ +class UpgradeManager { private: - typedef vector Upgrades; - typedef map UgradesLookup; - - /** - * List of upgrades that the upgrade manager is working with (either in progress or finished). - */ - Upgrades upgrades; - - /** - * Maps UpgradeType to the index of the upgrade in UpgradeManager::upgrades. - */ - UgradesLookup upgradesLookup; + typedef vector Upgrades; + typedef map UgradesLookup; + + /** + * List of upgrades that the upgrade manager is working with (either in + * progress or finished). + */ + Upgrades upgrades; + + /** + * Maps UpgradeType to the index of the upgrade in UpgradeManager::upgrades. + */ + UgradesLookup upgradesLookup; + public: - ~UpgradeManager(); - - int getUpgradeCount() const {return (int)upgrades.size();} - - /** - * Starts an upgrade. - * @param upgradeType The type of the upgrade to start. - * @param factionIndex Passed to the constructor of the Upgrade. - */ - void startUpgrade(const UpgradeType *upgradeType, int factionIndex); - - /** - * Cancels an upgrade before it is finished. The upgrade is removed from the UpgradeManager. - * @param upgradeType The type of the upgrade to remove. - * @throws megaglest_runtime_error If there is no upgrade of the desired type in the UpgradeManager. - */ - void cancelUpgrade(const UpgradeType *upgradeType); - - /** - * Sets an Upgrade in the UpgradeManager as finished (ie, the state is UpgradeState::usUpgraded). - * @param upgradeType The type of the upgrade to complete. - * @throws megaglest_runtime_error If there is no upgrade of the desired type in the UpgradeManager. - */ - void finishUpgrade(const UpgradeType *upgradeType); - - /** - * Returns true if an Upgrade of the desired type has state UpgradeState::usUpgraded (ie, is - * finished upgrading). - * @param upgradeType The type of the upgrade in question. - */ - bool isUpgraded(const UpgradeType *upgradeType) const; - - /** - * Returns true if an Upgrade of the desired type has state UpgradeState::usUpgrading (ie, is - * currently in progress). - * @param upgradeType The type of the upgrade in question. - */ - bool isUpgrading(const UpgradeType *upgradeType) const; - - /** - * Returns true if an Upgrade of the desired type exists in the UpgradeManager. - * @param upgradeType The type of the upgrade in question. - */ - bool isUpgradingOrUpgraded(const UpgradeType *upgradeType) const; - - /** - * [Sums up](@ref TotalUpgrade::sum) the effect of all upgrades for this faction as they apply - * to a particular unit. - * @param unit The unit that the TotalUpgrade applies to. This is necessary because some - * upgrades provide percentage boosts. - * @param totalUpgrade The TotalUpgrade object to modify. Note that it is cleared before values - * are calculated. - */ - void computeTotalUpgrade(const Unit *unit, TotalUpgrade *totalUpgrade) const; - - /** - * Retrieves a string representation of the UpgradeManager. Contains the contents of - * Upgrade::toString for all upgrades in the UpgradeManager. - */ - std::string toString() const; - - /** - * Adds a node for the UpgradeManager that contains all the upgrade nodes, saving the object's - * state. - * @param rootNode The faction node to add the UpgradeManager node to. - * @see Upgrade::saveGame - */ - void saveGame(XmlNode *rootNode); - - /** - * Loads all the upgrades from the UpgradeManager node, effectively reloading the object's - * state. - * @param rootNode The faction node to get the UpgradeManager node from. - * @param faction Only passed to Upgrade::loadGame (which does the actual loading of each - * Upgrade object. - */ - void loadGame(const XmlNode *rootNode,Faction *faction); + ~UpgradeManager(); + + int getUpgradeCount() const { return (int)upgrades.size(); } + + /** + * Starts an upgrade. + * @param upgradeType The type of the upgrade to start. + * @param factionIndex Passed to the constructor of the Upgrade. + */ + void startUpgrade(const UpgradeType *upgradeType, int factionIndex); + + /** + * Cancels an upgrade before it is finished. The upgrade is removed from the + * UpgradeManager. + * @param upgradeType The type of the upgrade to remove. + * @throws megaglest_runtime_error If there is no upgrade of the desired type + * in the UpgradeManager. + */ + void cancelUpgrade(const UpgradeType *upgradeType); + + /** + * Sets an Upgrade in the UpgradeManager as finished (ie, the state is + * UpgradeState::usUpgraded). + * @param upgradeType The type of the upgrade to complete. + * @throws megaglest_runtime_error If there is no upgrade of the desired type + * in the UpgradeManager. + */ + void finishUpgrade(const UpgradeType *upgradeType); + + /** + * Returns true if an Upgrade of the desired type has state + * UpgradeState::usUpgraded (ie, is finished upgrading). + * @param upgradeType The type of the upgrade in question. + */ + bool isUpgraded(const UpgradeType *upgradeType) const; + + /** + * Returns true if an Upgrade of the desired type has state + * UpgradeState::usUpgrading (ie, is currently in progress). + * @param upgradeType The type of the upgrade in question. + */ + bool isUpgrading(const UpgradeType *upgradeType) const; + + /** + * Returns true if an Upgrade of the desired type exists in the + * UpgradeManager. + * @param upgradeType The type of the upgrade in question. + */ + bool isUpgradingOrUpgraded(const UpgradeType *upgradeType) const; + + /** + * [Sums up](@ref TotalUpgrade::sum) the effect of all upgrades for this + * faction as they apply to a particular unit. + * @param unit The unit that the TotalUpgrade applies to. This is necessary + * because some upgrades provide percentage boosts. + * @param totalUpgrade The TotalUpgrade object to modify. Note that it is + * cleared before values are calculated. + */ + void computeTotalUpgrade(const Unit *unit, TotalUpgrade *totalUpgrade) const; + + /** + * Retrieves a string representation of the UpgradeManager. Contains the + * contents of Upgrade::toString for all upgrades in the UpgradeManager. + */ + std::string toString() const; + + /** + * Adds a node for the UpgradeManager that contains all the upgrade nodes, + * saving the object's state. + * @param rootNode The faction node to add the UpgradeManager node to. + * @see Upgrade::saveGame + */ + void saveGame(XmlNode *rootNode); + + /** + * Loads all the upgrades from the UpgradeManager node, effectively reloading + * the object's state. + * @param rootNode The faction node to get the UpgradeManager node from. + * @param faction Only passed to Upgrade::loadGame (which does the actual + * loading of each Upgrade object. + */ + void loadGame(const XmlNode *rootNode, Faction *faction); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/types/command_type.cpp b/source/glest_game/types/command_type.cpp index b254a368c..11bc8da0a 100644 --- a/source/glest_game/types/command_type.cpp +++ b/source/glest_game/types/command_type.cpp @@ -14,1007 +14,1247 @@ #include #include -#include "upgrade_type.h" -#include "unit_type.h" -#include "sound.h" -#include "util.h" -#include "leak_dumper.h" -#include "graphics_interface.h" -#include "tech_tree.h" #include "faction_type.h" -#include "unit_updater.h" -#include "renderer.h" +#include "graphics_interface.h" #include "leak_dumper.h" +#include "renderer.h" #include "socket.h" +#include "sound.h" +#include "tech_tree.h" +#include "unit_type.h" +#include "unit_updater.h" +#include "upgrade_type.h" +#include "util.h" using namespace Shared::Util; -namespace Glest{ namespace Game{ - +namespace Glest { +namespace Game { // ===================================================== // class CommandType // ===================================================== -//get -CommandClass CommandType::getClass() const{ - assert(this!=NULL); - return commandTypeClass; -} - -void CommandType::load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList, - string parentLoader) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - this->id= id; - name= n->getChild("name")->getAttribute("value")->getRestrictedValue(); - - //image - const XmlNode *imageNode= n->getChild("image"); - image= Renderer::getInstance().newTexture2D(rsGame); - - string currentPath = dir; - endPathWithSlash(currentPath); - if(image) { - image->load(imageNode->getAttribute("path")->getRestrictedValue(currentPath)); - } - loadedFileList[imageNode->getAttribute("path")->getRestrictedValue(currentPath)].push_back(make_pair(parentLoader,imageNode->getAttribute("path")->getRestrictedValue())); - - //unit requirements - const XmlNode *unitRequirementsNode= n->getChild("unit-requirements"); - for(int i = 0; i < (int)unitRequirementsNode->getChildCount(); ++i) { - const XmlNode *unitNode= unitRequirementsNode->getChild("unit", i); - string name= unitNode->getAttribute("name")->getRestrictedValue(); - unitReqs.push_back(ft->getUnitType(name)); - } - - //upgrade requirements - const XmlNode *upgradeRequirementsNode= n->getChild("upgrade-requirements"); - for(int i = 0; i < (int)upgradeRequirementsNode->getChildCount(); ++i) { - const XmlNode *upgradeReqNode= upgradeRequirementsNode->getChild("upgrade", i); - string name= upgradeReqNode->getAttribute("name")->getRestrictedValue(); - upgradeReqs.push_back(ft->getUpgradeType(name)); - } - - //fog of war - if(n->hasChild("fog-of-war-skill") == true) { - string skillName= n->getChild("fog-of-war-skill")->getAttribute("value")->getRestrictedValue(); - fogOfWarSkillType = static_cast(ut.getSkillType(skillName, scFogOfWar)); - - string skillAttachmentNames = n->getChild("fog-of-war-skill")->getAttribute("skill-attachments")->getValue(); - - std::vector skillList; - Tokenize(skillAttachmentNames,skillList,","); - for(unsigned int i = 0; i < skillList.size(); ++i) { - string skillAttachName = skillList[i]; - fogOfWarSkillAttachments[skillAttachName] = true; - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); +// get +CommandClass CommandType::getClass() const { + assert(this != NULL); + return commandTypeClass; +} + +void CommandType::load( + int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + this->id = id; + name = n->getChild("name")->getAttribute("value")->getRestrictedValue(); + + // image + const XmlNode *imageNode = n->getChild("image"); + image = Renderer::getInstance().newTexture2D(rsGame); + + string currentPath = dir; + endPathWithSlash(currentPath); + if (image) { + image->load( + imageNode->getAttribute("path")->getRestrictedValue(currentPath)); + } + loadedFileList[imageNode->getAttribute("path")->getRestrictedValue( + currentPath)] + .push_back(make_pair( + parentLoader, imageNode->getAttribute("path")->getRestrictedValue())); + + // unit requirements + const XmlNode *unitRequirementsNode = n->getChild("unit-requirements"); + for (int i = 0; i < (int)unitRequirementsNode->getChildCount(); ++i) { + const XmlNode *unitNode = unitRequirementsNode->getChild("unit", i); + string name = unitNode->getAttribute("name")->getRestrictedValue(); + unitReqs.push_back(ft->getUnitType(name)); + } + + // upgrade requirements + const XmlNode *upgradeRequirementsNode = n->getChild("upgrade-requirements"); + for (int i = 0; i < (int)upgradeRequirementsNode->getChildCount(); ++i) { + const XmlNode *upgradeReqNode = + upgradeRequirementsNode->getChild("upgrade", i); + string name = upgradeReqNode->getAttribute("name")->getRestrictedValue(); + upgradeReqs.push_back(ft->getUpgradeType(name)); + } + + // fog of war + if (n->hasChild("fog-of-war-skill") == true) { + string skillName = n->getChild("fog-of-war-skill") + ->getAttribute("value") + ->getRestrictedValue(); + fogOfWarSkillType = static_cast( + ut.getSkillType(skillName, scFogOfWar)); + + string skillAttachmentNames = n->getChild("fog-of-war-skill") + ->getAttribute("skill-attachments") + ->getValue(); + + std::vector skillList; + Tokenize(skillAttachmentNames, skillList, ","); + for (unsigned int i = 0; i < skillList.size(); ++i) { + string skillAttachName = skillList[i]; + fogOfWarSkillAttachments[skillAttachName] = true; + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); } bool CommandType::hasFogOfWarSkillType(string name) const { - std::map::const_iterator iterFind = fogOfWarSkillAttachments.find(name); - bool result = (iterFind != fogOfWarSkillAttachments.end()); - return result; + std::map::const_iterator iterFind = + fogOfWarSkillAttachments.find(name); + bool result = (iterFind != fogOfWarSkillAttachments.end()); + return result; } // ===================================================== // class StopCommandType // ===================================================== -//varios -StopCommandType::StopCommandType(){ - commandTypeClass= ccStop; - clicks= cOne; - stopSkillType=NULL; -} - -void StopCommandType::update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const { - unitUpdater->updateStop(unit, frameIndex); -} - -string StopCommandType::getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const{ - string str; - Lang &lang= Lang::getInstance(); - - str= getName(translatedValue)+"\n"; - str+= lang.getString("ReactionSpeed",(translatedValue == true ? "" : "english")) + ": " + intToStr(stopSkillType->getSpeed())+"\n"; - if(stopSkillType->getEpCost() != 0) - str += lang.getString("EpCost",(translatedValue == true ? "" : "english")) + ": " + intToStr(stopSkillType->getEpCost())+"\n"; - if(stopSkillType->getHpCost() != 0) - str+= lang.getString("HpCost",(translatedValue == true ? "" : "english")) + ": " + intToStr(stopSkillType->getHpCost())+"\n"; - str+=stopSkillType->getBoostDesc(translatedValue); - return str; -} - -string StopCommandType::toString(bool translatedValue) const{ - if(translatedValue == false) { - return "Stop"; - } - Lang &lang= Lang::getInstance(); - return lang.getString("Stop"); -} - -void StopCommandType::load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList,string parentLoader) { - CommandType::load(id, n, dir, tt, ft, ut, loadedFileList,parentLoader); - - //stop - string skillName= n->getChild("stop-skill")->getAttribute("value")->getRestrictedValue(); - stopSkillType= static_cast(ut.getSkillType(skillName, scStop)); +// varios +StopCommandType::StopCommandType() { + commandTypeClass = ccStop; + clicks = cOne; + stopSkillType = NULL; +} + +void StopCommandType::update(UnitUpdater *unitUpdater, Unit *unit, + int frameIndex) const { + unitUpdater->updateStop(unit, frameIndex); +} + +string StopCommandType::getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const { + string str; + Lang &lang = Lang::getInstance(); + + str = getName(translatedValue) + "\n"; + str += lang.getString("ReactionSpeed", + (translatedValue == true ? "" : "english")) + + ": " + intToStr(stopSkillType->getSpeed()) + "\n"; + if (stopSkillType->getEpCost() != 0) + str += + lang.getString("EpCost", (translatedValue == true ? "" : "english")) + + ": " + intToStr(stopSkillType->getEpCost()) + "\n"; + if (stopSkillType->getHpCost() != 0) + str += + lang.getString("HpCost", (translatedValue == true ? "" : "english")) + + ": " + intToStr(stopSkillType->getHpCost()) + "\n"; + str += stopSkillType->getBoostDesc(translatedValue); + return str; +} + +string StopCommandType::toString(bool translatedValue) const { + if (translatedValue == false) { + return "Stop"; + } + Lang &lang = Lang::getInstance(); + return lang.getString("Stop"); +} + +void StopCommandType::load( + int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader) { + CommandType::load(id, n, dir, tt, ft, ut, loadedFileList, parentLoader); + + // stop + string skillName = + n->getChild("stop-skill")->getAttribute("value")->getRestrictedValue(); + stopSkillType = + static_cast(ut.getSkillType(skillName, scStop)); } - // ===================================================== // class MoveCommandType // ===================================================== -//varios -MoveCommandType::MoveCommandType(){ - commandTypeClass= ccMove; - clicks= cTwo; - moveSkillType=NULL; -} - -void MoveCommandType::update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const { - unitUpdater->updateMove(unit, frameIndex); -} - -void MoveCommandType::load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList, - string parentLoader) { - CommandType::load(id, n, dir, tt, ft, ut, loadedFileList,parentLoader); - - //move - string skillName= n->getChild("move-skill")->getAttribute("value")->getRestrictedValue(); - moveSkillType= static_cast(ut.getSkillType(skillName, scMove)); -} - -string MoveCommandType::getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const{ - string str; - Lang &lang= Lang::getInstance(); - - str=getName(translatedValue)+"\n"; - str+= lang.getString("WalkSpeed",(translatedValue == true ? "" : "english"))+": "+ intToStr(moveSkillType->getSpeed()); - if(totalUpgrade->getMoveSpeed(moveSkillType) != 0) { - str+= "+" + intToStr(totalUpgrade->getMoveSpeed(moveSkillType)); - } - str+="\n"; - if(moveSkillType->getEpCost()!=0){ - str+= lang.getString("EpCost",(translatedValue == true ? "" : "english"))+": "+intToStr(moveSkillType->getEpCost())+"\n"; - } - if(moveSkillType->getHpCost()!=0) { - str+= lang.getString("HpCost",(translatedValue == true ? "" : "english"))+": "+intToStr(moveSkillType->getHpCost())+"\n"; - } - str+=moveSkillType->getBoostDesc(translatedValue); - return str; -} - -string MoveCommandType::toString(bool translatedValue) const{ - if(translatedValue == false) { - return "Move"; - } - Lang &lang= Lang::getInstance(); - return lang.getString("Move"); +// varios +MoveCommandType::MoveCommandType() { + commandTypeClass = ccMove; + clicks = cTwo; + moveSkillType = NULL; +} + +void MoveCommandType::update(UnitUpdater *unitUpdater, Unit *unit, + int frameIndex) const { + unitUpdater->updateMove(unit, frameIndex); +} + +void MoveCommandType::load( + int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader) { + CommandType::load(id, n, dir, tt, ft, ut, loadedFileList, parentLoader); + + // move + string skillName = + n->getChild("move-skill")->getAttribute("value")->getRestrictedValue(); + moveSkillType = + static_cast(ut.getSkillType(skillName, scMove)); +} + +string MoveCommandType::getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const { + string str; + Lang &lang = Lang::getInstance(); + + str = getName(translatedValue) + "\n"; + str += + lang.getString("WalkSpeed", (translatedValue == true ? "" : "english")) + + ": " + intToStr(moveSkillType->getSpeed()); + if (totalUpgrade->getMoveSpeed(moveSkillType) != 0) { + str += "+" + intToStr(totalUpgrade->getMoveSpeed(moveSkillType)); + } + str += "\n"; + if (moveSkillType->getEpCost() != 0) { + str += + lang.getString("EpCost", (translatedValue == true ? "" : "english")) + + ": " + intToStr(moveSkillType->getEpCost()) + "\n"; + } + if (moveSkillType->getHpCost() != 0) { + str += + lang.getString("HpCost", (translatedValue == true ? "" : "english")) + + ": " + intToStr(moveSkillType->getHpCost()) + "\n"; + } + str += moveSkillType->getBoostDesc(translatedValue); + return str; +} + +string MoveCommandType::toString(bool translatedValue) const { + if (translatedValue == false) { + return "Move"; + } + Lang &lang = Lang::getInstance(); + return lang.getString("Move"); } // ===================================================== // class AttackCommandType // ===================================================== -//varios -AttackCommandType::AttackCommandType(){ - commandTypeClass= ccAttack; - clicks= cTwo; - moveSkillType=NULL; - attackSkillType=NULL; -} - -void AttackCommandType::update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const { - unitUpdater->updateAttack(unit, frameIndex); -} - -void AttackCommandType::load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList, - string parentLoader) { - CommandType::load(id, n, dir, tt, ft, ut, loadedFileList,parentLoader); - - //move - string skillName= n->getChild("move-skill")->getAttribute("value")->getRestrictedValue(); - moveSkillType= static_cast(ut.getSkillType(skillName, scMove)); - - //attack - skillName= n->getChild("attack-skill")->getAttribute("value")->getRestrictedValue(); - attackSkillType= static_cast(ut.getSkillType(skillName, scAttack)); -} - -string AttackCommandType::getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const{ - string str; - Lang &lang= Lang::getInstance(); - - str=getName(translatedValue)+"\n"; - if(attackSkillType->getEpCost()!=0){ - str+= lang.getString("EpCost",(translatedValue == true ? "" : "english")) + ": " + intToStr(attackSkillType->getEpCost()) + "\n"; - } - if(attackSkillType->getHpCost()!=0){ - str+= lang.getString("HpCost",(translatedValue == true ? "" : "english")) + ": " + intToStr(attackSkillType->getHpCost()) + "\n"; - } - - //attack strength - str+= lang.getString("AttackStrenght",(translatedValue == true ? "" : "english"))+": "; - str+= intToStr(attackSkillType->getAttackStrength()-attackSkillType->getAttackVar()); - str+= "..."; - str+= intToStr(attackSkillType->getAttackStrength()+attackSkillType->getAttackVar()); - if(totalUpgrade->getAttackStrength(attackSkillType) != 0) { - str+= "+"+intToStr(totalUpgrade->getAttackStrength(attackSkillType)); - } - str+= " ("+ attackSkillType->getAttackType()->getName(translatedValue) +")"; - str+= "\n"; - - //splash radius - if(attackSkillType->getSplashRadius()!=0){ - str+= lang.getString("SplashRadius",(translatedValue == true ? "" : "english"))+": "+intToStr(attackSkillType->getSplashRadius())+"\n"; - } - - //attack distance - str+= lang.getString("AttackDistance",(translatedValue == true ? "" : "english"))+": "+intToStr(attackSkillType->getAttackRange()); - if(totalUpgrade->getAttackRange(attackSkillType) != 0) { - str+= "+"+intToStr(totalUpgrade->getAttackRange(attackSkillType)); - } - str+="\n"; - - //attack fields - str+= lang.getString("Fields") + ": "; - for(int i= 0; i < fieldCount; i++){ - Field field = static_cast(i); - if( attackSkillType->getAttackField(field) ) - { - str+= SkillType::fieldToStr(field) + " "; - } - } - str+="\n"; - - //movement speed - str+= lang.getString("WalkSpeed",(translatedValue == true ? "" : "english"))+": "+ intToStr(moveSkillType->getSpeed()) ; - if(totalUpgrade->getMoveSpeed(moveSkillType) != 0) { - str+= "+"+intToStr(totalUpgrade->getMoveSpeed(moveSkillType)); - } - str+="\n"; - - //attack speed - str+= lang.getString("AttackSpeed",(translatedValue == true ? "" : "english"))+": "+ intToStr(attackSkillType->getSpeed()) +"\n"; - if(totalUpgrade->getAttackSpeed(attackSkillType) != 0) { - str+= "+"+intToStr(totalUpgrade->getAttackSpeed(attackSkillType)); - } - str+="\n"; - - str+=attackSkillType->getBoostDesc(translatedValue); - return str; -} - -string AttackCommandType::toString(bool translatedValue) const{ - if(translatedValue == false) { - return "Attack"; - } - Lang &lang= Lang::getInstance(); - return lang.getString("Attack"); +// varios +AttackCommandType::AttackCommandType() { + commandTypeClass = ccAttack; + clicks = cTwo; + moveSkillType = NULL; + attackSkillType = NULL; +} + +void AttackCommandType::update(UnitUpdater *unitUpdater, Unit *unit, + int frameIndex) const { + unitUpdater->updateAttack(unit, frameIndex); +} + +void AttackCommandType::load( + int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader) { + CommandType::load(id, n, dir, tt, ft, ut, loadedFileList, parentLoader); + + // move + string skillName = + n->getChild("move-skill")->getAttribute("value")->getRestrictedValue(); + moveSkillType = + static_cast(ut.getSkillType(skillName, scMove)); + + // attack + skillName = + n->getChild("attack-skill")->getAttribute("value")->getRestrictedValue(); + attackSkillType = static_cast( + ut.getSkillType(skillName, scAttack)); +} + +string AttackCommandType::getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const { + string str; + Lang &lang = Lang::getInstance(); + + str = getName(translatedValue) + "\n"; + if (attackSkillType->getEpCost() != 0) { + str += + lang.getString("EpCost", (translatedValue == true ? "" : "english")) + + ": " + intToStr(attackSkillType->getEpCost()) + "\n"; + } + if (attackSkillType->getHpCost() != 0) { + str += + lang.getString("HpCost", (translatedValue == true ? "" : "english")) + + ": " + intToStr(attackSkillType->getHpCost()) + "\n"; + } + + // attack strength + str += lang.getString("AttackStrenght", + (translatedValue == true ? "" : "english")) + + ": "; + str += intToStr(attackSkillType->getAttackStrength() - + attackSkillType->getAttackVar()); + str += "..."; + str += intToStr(attackSkillType->getAttackStrength() + + attackSkillType->getAttackVar()); + if (totalUpgrade->getAttackStrength(attackSkillType) != 0) { + str += "+" + intToStr(totalUpgrade->getAttackStrength(attackSkillType)); + } + str += + " (" + attackSkillType->getAttackType()->getName(translatedValue) + ")"; + str += "\n"; + + // splash radius + if (attackSkillType->getSplashRadius() != 0) { + str += lang.getString("SplashRadius", + (translatedValue == true ? "" : "english")) + + ": " + intToStr(attackSkillType->getSplashRadius()) + "\n"; + } + + // attack distance + str += lang.getString("AttackDistance", + (translatedValue == true ? "" : "english")) + + ": " + intToStr(attackSkillType->getAttackRange()); + if (totalUpgrade->getAttackRange(attackSkillType) != 0) { + str += "+" + intToStr(totalUpgrade->getAttackRange(attackSkillType)); + } + str += "\n"; + + // attack fields + str += lang.getString("Fields") + ": "; + for (int i = 0; i < fieldCount; i++) { + Field field = static_cast(i); + if (attackSkillType->getAttackField(field)) { + str += SkillType::fieldToStr(field) + " "; + } + } + str += "\n"; + + // movement speed + str += + lang.getString("WalkSpeed", (translatedValue == true ? "" : "english")) + + ": " + intToStr(moveSkillType->getSpeed()); + if (totalUpgrade->getMoveSpeed(moveSkillType) != 0) { + str += "+" + intToStr(totalUpgrade->getMoveSpeed(moveSkillType)); + } + str += "\n"; + + // attack speed + str += lang.getString("AttackSpeed", + (translatedValue == true ? "" : "english")) + + ": " + intToStr(attackSkillType->getSpeed()) + "\n"; + if (totalUpgrade->getAttackSpeed(attackSkillType) != 0) { + str += "+" + intToStr(totalUpgrade->getAttackSpeed(attackSkillType)); + } + str += "\n"; + + str += attackSkillType->getBoostDesc(translatedValue); + return str; +} + +string AttackCommandType::toString(bool translatedValue) const { + if (translatedValue == false) { + return "Attack"; + } + Lang &lang = Lang::getInstance(); + return lang.getString("Attack"); } - // ===================================================== // class AttackStoppedCommandType // ===================================================== -//varios -AttackStoppedCommandType::AttackStoppedCommandType(){ - commandTypeClass= ccAttackStopped; - clicks= cOne; - stopSkillType=NULL; - attackSkillType=NULL; -} - -void AttackStoppedCommandType::update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const { - unitUpdater->updateAttackStopped(unit, frameIndex); -} - -void AttackStoppedCommandType::load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList,string parentLoader) { - CommandType::load(id, n, dir, tt, ft, ut, loadedFileList,parentLoader); - - //stop - string skillName= n->getChild("stop-skill")->getAttribute("value")->getRestrictedValue(); - stopSkillType= static_cast(ut.getSkillType(skillName, scStop)); - - //attack - skillName= n->getChild("attack-skill")->getAttribute("value")->getRestrictedValue(); - attackSkillType= static_cast(ut.getSkillType(skillName, scAttack)); -} - -string AttackStoppedCommandType::getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const{ - Lang &lang= Lang::getInstance(); - string str; - - str=getName(translatedValue)+"\n"; - if(attackSkillType->getEpCost()!=0){ - str+= lang.getString("EpCost",(translatedValue == true ? "" : "english"))+": "+intToStr(attackSkillType->getEpCost())+"\n"; - } - if(attackSkillType->getHpCost()!=0){ - str+= lang.getString("HpCost",(translatedValue == true ? "" : "english"))+": "+intToStr(attackSkillType->getHpCost())+"\n"; - } - - //attack strength - str+= lang.getString("AttackStrenght",(translatedValue == true ? "" : "english"))+": "; - str+= intToStr(attackSkillType->getAttackStrength()-attackSkillType->getAttackVar()); - str+="..."; - str+= intToStr(attackSkillType->getAttackStrength()+attackSkillType->getAttackVar()); - if(totalUpgrade->getAttackStrength(attackSkillType) != 0) - str+= "+"+intToStr(totalUpgrade->getAttackStrength(attackSkillType)); - str+= " ("+ attackSkillType->getAttackType()->getName(translatedValue) +")"; - str+="\n"; - - //splash radius - if(attackSkillType->getSplashRadius()!=0){ - str+= lang.getString("SplashRadius",(translatedValue == true ? "" : "english"))+": "+intToStr(attackSkillType->getSplashRadius())+"\n"; - } - - //attack distance - str+= lang.getString("AttackDistance",(translatedValue == true ? "" : "english"))+": "+intToStr(attackSkillType->getAttackRange()); - if(totalUpgrade->getAttackRange(attackSkillType) != 0) { - str+= "+"+intToStr(totalUpgrade->getAttackRange(attackSkillType) != 0); - } - str+="\n"; - - //attack fields - str+= lang.getString("Fields",(translatedValue == true ? "" : "english")) + ": "; - for(int i= 0; i < fieldCount; i++){ - Field field = static_cast(i); - if( attackSkillType->getAttackField(field) ) - { - str+= SkillType::fieldToStr(field) + " "; - } - } - str+="\n"; - str+=attackSkillType->getBoostDesc(translatedValue); - return str; +// varios +AttackStoppedCommandType::AttackStoppedCommandType() { + commandTypeClass = ccAttackStopped; + clicks = cOne; + stopSkillType = NULL; + attackSkillType = NULL; +} + +void AttackStoppedCommandType::update(UnitUpdater *unitUpdater, Unit *unit, + int frameIndex) const { + unitUpdater->updateAttackStopped(unit, frameIndex); +} + +void AttackStoppedCommandType::load( + int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader) { + CommandType::load(id, n, dir, tt, ft, ut, loadedFileList, parentLoader); + + // stop + string skillName = + n->getChild("stop-skill")->getAttribute("value")->getRestrictedValue(); + stopSkillType = + static_cast(ut.getSkillType(skillName, scStop)); + + // attack + skillName = + n->getChild("attack-skill")->getAttribute("value")->getRestrictedValue(); + attackSkillType = static_cast( + ut.getSkillType(skillName, scAttack)); +} + +string AttackStoppedCommandType::getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const { + Lang &lang = Lang::getInstance(); + string str; + + str = getName(translatedValue) + "\n"; + if (attackSkillType->getEpCost() != 0) { + str += + lang.getString("EpCost", (translatedValue == true ? "" : "english")) + + ": " + intToStr(attackSkillType->getEpCost()) + "\n"; + } + if (attackSkillType->getHpCost() != 0) { + str += + lang.getString("HpCost", (translatedValue == true ? "" : "english")) + + ": " + intToStr(attackSkillType->getHpCost()) + "\n"; + } + + // attack strength + str += lang.getString("AttackStrenght", + (translatedValue == true ? "" : "english")) + + ": "; + str += intToStr(attackSkillType->getAttackStrength() - + attackSkillType->getAttackVar()); + str += "..."; + str += intToStr(attackSkillType->getAttackStrength() + + attackSkillType->getAttackVar()); + if (totalUpgrade->getAttackStrength(attackSkillType) != 0) + str += "+" + intToStr(totalUpgrade->getAttackStrength(attackSkillType)); + str += + " (" + attackSkillType->getAttackType()->getName(translatedValue) + ")"; + str += "\n"; + + // splash radius + if (attackSkillType->getSplashRadius() != 0) { + str += lang.getString("SplashRadius", + (translatedValue == true ? "" : "english")) + + ": " + intToStr(attackSkillType->getSplashRadius()) + "\n"; + } + + // attack distance + str += lang.getString("AttackDistance", + (translatedValue == true ? "" : "english")) + + ": " + intToStr(attackSkillType->getAttackRange()); + if (totalUpgrade->getAttackRange(attackSkillType) != 0) { + str += "+" + intToStr(totalUpgrade->getAttackRange(attackSkillType) != 0); + } + str += "\n"; + + // attack fields + str += lang.getString("Fields", (translatedValue == true ? "" : "english")) + + ": "; + for (int i = 0; i < fieldCount; i++) { + Field field = static_cast(i); + if (attackSkillType->getAttackField(field)) { + str += SkillType::fieldToStr(field) + " "; + } + } + str += "\n"; + str += attackSkillType->getBoostDesc(translatedValue); + return str; } string AttackStoppedCommandType::toString(bool translatedValue) const { - if(translatedValue == false) { - return "AttackStopped"; - } - Lang &lang= Lang::getInstance(); - return lang.getString("AttackStopped"); + if (translatedValue == false) { + return "AttackStopped"; + } + Lang &lang = Lang::getInstance(); + return lang.getString("AttackStopped"); } - // ===================================================== // class BuildCommandType // ===================================================== -//varios +// varios BuildCommandType::BuildCommandType() { - commandTypeClass= ccBuild; - clicks= cTwo; - moveSkillType=NULL; - buildSkillType=NULL; + commandTypeClass = ccBuild; + clicks = cTwo; + moveSkillType = NULL; + buildSkillType = NULL; } BuildCommandType::~BuildCommandType() { - deleteValues(builtSounds.getSounds().begin(), builtSounds.getSounds().end()); - deleteValues(startSounds.getSounds().begin(), startSounds.getSounds().end()); -} - -void BuildCommandType::update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const { - unitUpdater->updateBuild(unit, frameIndex); -} - -void BuildCommandType::load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList, string parentLoader) { - CommandType::load(id, n, dir, tt, ft, ut, loadedFileList, parentLoader); - - //move - string skillName= n->getChild("move-skill")->getAttribute("value")->getRestrictedValue(); - moveSkillType= static_cast(ut.getSkillType(skillName, scMove)); - - //build - skillName= n->getChild("build-skill")->getAttribute("value")->getRestrictedValue(); - buildSkillType= static_cast(ut.getSkillType(skillName, scBuild)); - - //buildings built - const XmlNode *buildingsNode= n->getChild("buildings"); - for(int i=0; i < (int)buildingsNode->getChildCount(); ++i){ - const XmlNode *buildingNode= buildingsNode->getChild("building", i); - string name= buildingNode->getAttribute("name")->getRestrictedValue(); - buildings.push_back(ft->getUnitType(name)); - } - - //start sound - const XmlNode *startSoundNode= n->getChild("start-sound"); - if(startSoundNode->getAttribute("enabled")->getBoolValue()){ - startSounds.resize((int)startSoundNode->getChildCount()); - for(int i=0; i < (int)startSoundNode->getChildCount(); ++i){ - const XmlNode *soundFileNode= startSoundNode->getChild("sound-file", i); - string currentPath = dir; - endPathWithSlash(currentPath); - string path= soundFileNode->getAttribute("path")->getRestrictedValue(currentPath,true); - - StaticSound *sound= new StaticSound(); - - sound->load(path); - loadedFileList[path].push_back(make_pair(parentLoader,soundFileNode->getAttribute("path")->getRestrictedValue())); - startSounds[i]= sound; - } - } - - //built sound - const XmlNode *builtSoundNode= n->getChild("built-sound"); - if(builtSoundNode->getAttribute("enabled")->getBoolValue()){ - builtSounds.resize((int)builtSoundNode->getChildCount()); - for(int i=0; i < (int)builtSoundNode->getChildCount(); ++i){ - const XmlNode *soundFileNode= builtSoundNode->getChild("sound-file", i); - string currentPath = dir; - endPathWithSlash(currentPath); - string path= soundFileNode->getAttribute("path")->getRestrictedValue(currentPath,true); - - StaticSound *sound= new StaticSound(); - - sound->load(path); - loadedFileList[path].push_back(make_pair(parentLoader,soundFileNode->getAttribute("path")->getRestrictedValue())); - builtSounds[i]= sound; - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); -} - -string BuildCommandType::getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const{ - string str; - Lang &lang= Lang::getInstance(); - - str=getName(translatedValue)+"\n"; - str+= lang.getString("BuildSpeed",(translatedValue == true ? "" : "english"))+": "+ intToStr(buildSkillType->getSpeed())+"\n"; - if(buildSkillType->getEpCost()!=0){ - str+= lang.getString("EpCost",(translatedValue == true ? "" : "english"))+": "+intToStr(buildSkillType->getEpCost())+"\n"; - } - if(buildSkillType->getHpCost()!=0){ - str+= lang.getString("HpCost",(translatedValue == true ? "" : "english"))+": "+intToStr(buildSkillType->getHpCost())+"\n"; - } - str+=buildSkillType->getBoostDesc(translatedValue); - return str; -} - -string BuildCommandType::toString(bool translatedValue) const{ - if(translatedValue == false) { - return "Build"; - } - Lang &lang= Lang::getInstance(); - return lang.getString("Build"); + deleteValues(builtSounds.getSounds().begin(), builtSounds.getSounds().end()); + deleteValues(startSounds.getSounds().begin(), startSounds.getSounds().end()); +} + +void BuildCommandType::update(UnitUpdater *unitUpdater, Unit *unit, + int frameIndex) const { + unitUpdater->updateBuild(unit, frameIndex); +} + +void BuildCommandType::load( + int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader) { + CommandType::load(id, n, dir, tt, ft, ut, loadedFileList, parentLoader); + + // move + string skillName = + n->getChild("move-skill")->getAttribute("value")->getRestrictedValue(); + moveSkillType = + static_cast(ut.getSkillType(skillName, scMove)); + + // build + skillName = + n->getChild("build-skill")->getAttribute("value")->getRestrictedValue(); + buildSkillType = + static_cast(ut.getSkillType(skillName, scBuild)); + + // buildings built + const XmlNode *buildingsNode = n->getChild("buildings"); + for (int i = 0; i < (int)buildingsNode->getChildCount(); ++i) { + const XmlNode *buildingNode = buildingsNode->getChild("building", i); + string name = buildingNode->getAttribute("name")->getRestrictedValue(); + buildings.push_back(ft->getUnitType(name)); + } + + // start sound + const XmlNode *startSoundNode = n->getChild("start-sound"); + if (startSoundNode->getAttribute("enabled")->getBoolValue()) { + startSounds.resize((int)startSoundNode->getChildCount()); + for (int i = 0; i < (int)startSoundNode->getChildCount(); ++i) { + const XmlNode *soundFileNode = startSoundNode->getChild("sound-file", i); + string currentPath = dir; + endPathWithSlash(currentPath); + string path = soundFileNode->getAttribute("path")->getRestrictedValue( + currentPath, true); + + StaticSound *sound = new StaticSound(); + + sound->load(path); + loadedFileList[path].push_back( + make_pair(parentLoader, + soundFileNode->getAttribute("path")->getRestrictedValue())); + startSounds[i] = sound; + } + } + + // built sound + const XmlNode *builtSoundNode = n->getChild("built-sound"); + if (builtSoundNode->getAttribute("enabled")->getBoolValue()) { + builtSounds.resize((int)builtSoundNode->getChildCount()); + for (int i = 0; i < (int)builtSoundNode->getChildCount(); ++i) { + const XmlNode *soundFileNode = builtSoundNode->getChild("sound-file", i); + string currentPath = dir; + endPathWithSlash(currentPath); + string path = soundFileNode->getAttribute("path")->getRestrictedValue( + currentPath, true); + + StaticSound *sound = new StaticSound(); + + sound->load(path); + loadedFileList[path].push_back( + make_pair(parentLoader, + soundFileNode->getAttribute("path")->getRestrictedValue())); + builtSounds[i] = sound; + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); +} + +string BuildCommandType::getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const { + string str; + Lang &lang = Lang::getInstance(); + + str = getName(translatedValue) + "\n"; + str += + lang.getString("BuildSpeed", (translatedValue == true ? "" : "english")) + + ": " + intToStr(buildSkillType->getSpeed()) + "\n"; + if (buildSkillType->getEpCost() != 0) { + str += + lang.getString("EpCost", (translatedValue == true ? "" : "english")) + + ": " + intToStr(buildSkillType->getEpCost()) + "\n"; + } + if (buildSkillType->getHpCost() != 0) { + str += + lang.getString("HpCost", (translatedValue == true ? "" : "english")) + + ": " + intToStr(buildSkillType->getHpCost()) + "\n"; + } + str += buildSkillType->getBoostDesc(translatedValue); + return str; +} + +string BuildCommandType::toString(bool translatedValue) const { + if (translatedValue == false) { + return "Build"; + } + Lang &lang = Lang::getInstance(); + return lang.getString("Build"); } // ===================================================== // class HarvestCommandType // ===================================================== -//varios -HarvestCommandType::HarvestCommandType(){ - commandTypeClass= ccHarvest; - clicks= cTwo; - moveSkillType=NULL; - moveLoadedSkillType=NULL; - harvestSkillType=NULL; - stopLoadedSkillType=NULL; - maxLoad=0; - hitsPerUnit=0; -} - -void HarvestCommandType::update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const { - unitUpdater->updateHarvest(unit, frameIndex); -} - -void HarvestCommandType::load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList, string parentLoader) { - CommandType::load(id, n, dir, tt, ft, ut, loadedFileList, parentLoader); - - //move - string skillName= n->getChild("move-skill")->getAttribute("value")->getRestrictedValue(); - moveSkillType= static_cast(ut.getSkillType(skillName, scMove)); - - //harvest - skillName= n->getChild("harvest-skill")->getAttribute("value")->getRestrictedValue(); - harvestSkillType= static_cast(ut.getSkillType(skillName, scHarvest)); - - //stop loaded - skillName= n->getChild("stop-loaded-skill")->getAttribute("value")->getRestrictedValue(); - stopLoadedSkillType= static_cast(ut.getSkillType(skillName, scStop)); - - //move loaded - skillName= n->getChild("move-loaded-skill")->getAttribute("value")->getRestrictedValue(); - moveLoadedSkillType= static_cast(ut.getSkillType(skillName, scMove)); - - //resources can harvest - const XmlNode *resourcesNode= n->getChild("harvested-resources"); - for(int i=0; i < (int)resourcesNode->getChildCount(); ++i){ - const XmlNode *resourceNode= resourcesNode->getChild("resource", i); - harvestedResources.push_back(tt->getResourceType(resourceNode->getAttribute("name")->getRestrictedValue())); - } - - maxLoad= n->getChild("max-load")->getAttribute("value")->getIntValue(); - hitsPerUnit= n->getChild("hits-per-unit")->getAttribute("value")->getIntValue(); -} - -string HarvestCommandType::getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const{ - - Lang &lang= Lang::getInstance(); - string str; - - str=getName(translatedValue)+"\n"; - str+= lang.getString("HarvestSpeed",(translatedValue == true ? "" : "english"))+": "+ intToStr(harvestSkillType->getSpeed()/hitsPerUnit)+"\n"; - str+= lang.getString("MaxLoad",(translatedValue == true ? "" : "english"))+": "+ intToStr(maxLoad)+"\n"; - str+= lang.getString("LoadedSpeed",(translatedValue == true ? "" : "english"))+": "+ intToStr(moveLoadedSkillType->getSpeed())+"\n"; - if(harvestSkillType->getEpCost()!=0){ - str+= lang.getString("EpCost",(translatedValue == true ? "" : "english"))+": "+intToStr(harvestSkillType->getEpCost())+"\n"; - } - if(harvestSkillType->getHpCost()!=0){ - str+= lang.getString("HpCost",(translatedValue == true ? "" : "english"))+": "+intToStr(harvestSkillType->getHpCost())+"\n"; - } - str+=lang.getString("Resources",(translatedValue == true ? "" : "english"))+":\n"; - for(int i=0; igetName(translatedValue)+"\n"; - } - str+=harvestSkillType->getBoostDesc(translatedValue); - return str; -} - -string HarvestCommandType::toString(bool translatedValue) const{ - if(translatedValue == false) { - return "Harvest"; - } - Lang &lang= Lang::getInstance(); - return lang.getString("Harvest"); -} - -bool HarvestCommandType::canHarvest(const ResourceType *resourceType) const{ - return find(harvestedResources.begin(), harvestedResources.end(), resourceType) != harvestedResources.end(); +// varios +HarvestCommandType::HarvestCommandType() { + commandTypeClass = ccHarvest; + clicks = cTwo; + moveSkillType = NULL; + moveLoadedSkillType = NULL; + harvestSkillType = NULL; + stopLoadedSkillType = NULL; + maxLoad = 0; + hitsPerUnit = 0; +} + +void HarvestCommandType::update(UnitUpdater *unitUpdater, Unit *unit, + int frameIndex) const { + unitUpdater->updateHarvest(unit, frameIndex); +} + +void HarvestCommandType::load( + int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader) { + CommandType::load(id, n, dir, tt, ft, ut, loadedFileList, parentLoader); + + // move + string skillName = + n->getChild("move-skill")->getAttribute("value")->getRestrictedValue(); + moveSkillType = + static_cast(ut.getSkillType(skillName, scMove)); + + // harvest + skillName = + n->getChild("harvest-skill")->getAttribute("value")->getRestrictedValue(); + harvestSkillType = static_cast( + ut.getSkillType(skillName, scHarvest)); + + // stop loaded + skillName = n->getChild("stop-loaded-skill") + ->getAttribute("value") + ->getRestrictedValue(); + stopLoadedSkillType = + static_cast(ut.getSkillType(skillName, scStop)); + + // move loaded + skillName = n->getChild("move-loaded-skill") + ->getAttribute("value") + ->getRestrictedValue(); + moveLoadedSkillType = + static_cast(ut.getSkillType(skillName, scMove)); + + // resources can harvest + const XmlNode *resourcesNode = n->getChild("harvested-resources"); + for (int i = 0; i < (int)resourcesNode->getChildCount(); ++i) { + const XmlNode *resourceNode = resourcesNode->getChild("resource", i); + harvestedResources.push_back(tt->getResourceType( + resourceNode->getAttribute("name")->getRestrictedValue())); + } + + maxLoad = n->getChild("max-load")->getAttribute("value")->getIntValue(); + hitsPerUnit = + n->getChild("hits-per-unit")->getAttribute("value")->getIntValue(); +} + +string HarvestCommandType::getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const { + + Lang &lang = Lang::getInstance(); + string str; + + str = getName(translatedValue) + "\n"; + str += lang.getString("HarvestSpeed", + (translatedValue == true ? "" : "english")) + + ": " + intToStr(harvestSkillType->getSpeed() / hitsPerUnit) + "\n"; + str += lang.getString("MaxLoad", (translatedValue == true ? "" : "english")) + + ": " + intToStr(maxLoad) + "\n"; + str += lang.getString("LoadedSpeed", + (translatedValue == true ? "" : "english")) + + ": " + intToStr(moveLoadedSkillType->getSpeed()) + "\n"; + if (harvestSkillType->getEpCost() != 0) { + str += + lang.getString("EpCost", (translatedValue == true ? "" : "english")) + + ": " + intToStr(harvestSkillType->getEpCost()) + "\n"; + } + if (harvestSkillType->getHpCost() != 0) { + str += + lang.getString("HpCost", (translatedValue == true ? "" : "english")) + + ": " + intToStr(harvestSkillType->getHpCost()) + "\n"; + } + str += + lang.getString("Resources", (translatedValue == true ? "" : "english")) + + ":\n"; + for (int i = 0; i < getHarvestedResourceCount(); ++i) { + str += getHarvestedResource(i)->getName(translatedValue) + "\n"; + } + str += harvestSkillType->getBoostDesc(translatedValue); + return str; +} + +string HarvestCommandType::toString(bool translatedValue) const { + if (translatedValue == false) { + return "Harvest"; + } + Lang &lang = Lang::getInstance(); + return lang.getString("Harvest"); +} + +bool HarvestCommandType::canHarvest(const ResourceType *resourceType) const { + return find(harvestedResources.begin(), harvestedResources.end(), + resourceType) != harvestedResources.end(); } - // ===================================================== // class HarvestCommandType // ===================================================== -//varios -HarvestEmergencyReturnCommandType::HarvestEmergencyReturnCommandType(){ - commandTypeClass= ccHarvestEmergencyReturn; - clicks= cTwo; +// varios +HarvestEmergencyReturnCommandType::HarvestEmergencyReturnCommandType() { + commandTypeClass = ccHarvestEmergencyReturn; + clicks = cTwo; - this->id= -10; + this->id = -10; } -void HarvestEmergencyReturnCommandType::update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const { - unitUpdater->updateHarvestEmergencyReturn(unit, frameIndex); +void HarvestEmergencyReturnCommandType::update(UnitUpdater *unitUpdater, + Unit *unit, + int frameIndex) const { + unitUpdater->updateHarvestEmergencyReturn(unit, frameIndex); } -void HarvestEmergencyReturnCommandType::load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList, string parentLoader) { -// CommandType::load(id, n, dir, tt, ft, ut, loadedFileList, parentLoader); +void HarvestEmergencyReturnCommandType::load( + int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader) { + // CommandType::load(id, n, dir, tt, ft, ut, loadedFileList, parentLoader); } -string HarvestEmergencyReturnCommandType::getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const{ - string str=getName(translatedValue)+"\n"; - return str; +string +HarvestEmergencyReturnCommandType::getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const { + string str = getName(translatedValue) + "\n"; + return str; } -string HarvestEmergencyReturnCommandType::toString(bool translatedValue) const{ - if(translatedValue == false) { - return "HarvestEmergencyReturn"; - } - Lang &lang= Lang::getInstance(); - return lang.getString("Harvest"); +string HarvestEmergencyReturnCommandType::toString(bool translatedValue) const { + if (translatedValue == false) { + return "HarvestEmergencyReturn"; + } + Lang &lang = Lang::getInstance(); + return lang.getString("Harvest"); } // ===================================================== // class RepairCommandType // ===================================================== -//varios -RepairCommandType::RepairCommandType(){ - commandTypeClass= ccRepair; - clicks= cTwo; - moveSkillType=NULL; - repairSkillType=NULL; -} - -RepairCommandType::~RepairCommandType(){ -} - -void RepairCommandType::update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const { - unitUpdater->updateRepair(unit, frameIndex); -} - -void RepairCommandType::load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList, string parentLoader) { - CommandType::load(id, n, dir, tt, ft, ut, loadedFileList, parentLoader); - - // move skill (no longer required by means unit must already be beside unit to repair) - // for example a hospital - if(n->hasChild("move-skill") == true) { - string skillName= n->getChild("move-skill")->getAttribute("value")->getRestrictedValue(); - moveSkillType= static_cast(ut.getSkillType(skillName, scMove)); - } - - //repair - string skillName= n->getChild("repair-skill")->getAttribute("value")->getRestrictedValue(); - repairSkillType= static_cast(ut.getSkillType(skillName, scRepair)); - - //repaired units - const XmlNode *unitsNode= n->getChild("repaired-units"); - for(int i=0; i < (int)unitsNode->getChildCount(); ++i){ - const XmlNode *unitNode= unitsNode->getChild("unit", i); - repairableUnits.push_back(ft->getUnitType(unitNode->getAttribute("name")->getRestrictedValue())); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); -} - -string RepairCommandType::getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const{ - Lang &lang= Lang::getInstance(); - string str; - - str=getName(translatedValue)+"\n"; - str+= lang.getString("RepairSpeed",(translatedValue == true ? "" : "english"))+": "+ intToStr(repairSkillType->getSpeed())+"\n"; - if(repairSkillType->getEpCost()!=0){ - str+= lang.getString("EpCost",(translatedValue == true ? "" : "english"))+": "+intToStr(repairSkillType->getEpCost())+"\n"; - } - if(repairSkillType->getHpCost()!=0){ - str+= lang.getString("HpCost",(translatedValue == true ? "" : "english"))+": "+intToStr(repairSkillType->getHpCost())+"\n"; - } - str+="\n"+lang.getString("CanRepair",(translatedValue == true ? "" : "english"))+":\n"; - for(int i=0; i < (int)repairableUnits.size(); ++i){ - str+= (static_cast(repairableUnits[i]))->getName(translatedValue)+"\n"; - } - str+=repairSkillType->getBoostDesc(translatedValue); - return str; -} - -string RepairCommandType::toString(bool translatedValue) const{ - if(translatedValue == false) { - return "Repair"; - } - Lang &lang= Lang::getInstance(); - return lang.getString("Repair"); -} - -//get +// varios +RepairCommandType::RepairCommandType() { + commandTypeClass = ccRepair; + clicks = cTwo; + moveSkillType = NULL; + repairSkillType = NULL; +} + +RepairCommandType::~RepairCommandType() {} + +void RepairCommandType::update(UnitUpdater *unitUpdater, Unit *unit, + int frameIndex) const { + unitUpdater->updateRepair(unit, frameIndex); +} + +void RepairCommandType::load( + int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader) { + CommandType::load(id, n, dir, tt, ft, ut, loadedFileList, parentLoader); + + // move skill (no longer required by means unit must already be beside unit to + // repair) for example a hospital + if (n->hasChild("move-skill") == true) { + string skillName = + n->getChild("move-skill")->getAttribute("value")->getRestrictedValue(); + moveSkillType = + static_cast(ut.getSkillType(skillName, scMove)); + } + + // repair + string skillName = + n->getChild("repair-skill")->getAttribute("value")->getRestrictedValue(); + repairSkillType = static_cast( + ut.getSkillType(skillName, scRepair)); + + // repaired units + const XmlNode *unitsNode = n->getChild("repaired-units"); + for (int i = 0; i < (int)unitsNode->getChildCount(); ++i) { + const XmlNode *unitNode = unitsNode->getChild("unit", i); + repairableUnits.push_back( + ft->getUnitType(unitNode->getAttribute("name")->getRestrictedValue())); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); +} + +string RepairCommandType::getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const { + Lang &lang = Lang::getInstance(); + string str; + + str = getName(translatedValue) + "\n"; + str += lang.getString("RepairSpeed", + (translatedValue == true ? "" : "english")) + + ": " + intToStr(repairSkillType->getSpeed()) + "\n"; + if (repairSkillType->getEpCost() != 0) { + str += + lang.getString("EpCost", (translatedValue == true ? "" : "english")) + + ": " + intToStr(repairSkillType->getEpCost()) + "\n"; + } + if (repairSkillType->getHpCost() != 0) { + str += + lang.getString("HpCost", (translatedValue == true ? "" : "english")) + + ": " + intToStr(repairSkillType->getHpCost()) + "\n"; + } + str += + "\n" + + lang.getString("CanRepair", (translatedValue == true ? "" : "english")) + + ":\n"; + for (int i = 0; i < (int)repairableUnits.size(); ++i) { + str += (static_cast(repairableUnits[i])) + ->getName(translatedValue) + + "\n"; + } + str += repairSkillType->getBoostDesc(translatedValue); + return str; +} + +string RepairCommandType::toString(bool translatedValue) const { + if (translatedValue == false) { + return "Repair"; + } + Lang &lang = Lang::getInstance(); + return lang.getString("Repair"); +} + +// get bool RepairCommandType::isRepairableUnitType(const UnitType *unitType) const { - for(int i = 0; i < (int)repairableUnits.size(); ++i) { - const UnitType *curUnitType = static_cast(repairableUnits[i]); - //printf("Lookup index = %d Can repair unittype [%s][%p] looking for [%s][%p] lookup found result = %d\n",i,curUnitType->getName().c_str(),curUnitType,unitType->getName().c_str(),unitType,(curUnitType == unitType)); - if(curUnitType == unitType) { - return true; - } - } - return false; + for (int i = 0; i < (int)repairableUnits.size(); ++i) { + const UnitType *curUnitType = + static_cast(repairableUnits[i]); + // printf("Lookup index = %d Can repair unittype [%s][%p] looking for + // [%s][%p] lookup found result = + // %d\n",i,curUnitType->getName().c_str(),curUnitType,unitType->getName().c_str(),unitType,(curUnitType + // == unitType)); + if (curUnitType == unitType) { + return true; + } + } + return false; } // ===================================================== // class ProduceCommandType // ===================================================== -//varios -ProduceCommandType::ProduceCommandType(){ - commandTypeClass= ccProduce; - clicks= cOne; - produceSkillType=NULL; - producedUnit=NULL; -} - -void ProduceCommandType::update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const { - unitUpdater->updateProduce(unit, frameIndex); -} - -void ProduceCommandType::load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList, string parentLoader) { - CommandType::load(id, n, dir, tt, ft, ut, loadedFileList, parentLoader); - - //produce - string skillName= n->getChild("produce-skill")->getAttribute("value")->getRestrictedValue(); - produceSkillType= static_cast(ut.getSkillType(skillName, scProduce)); - - string producedUnitName= n->getChild("produced-unit")->getAttribute("name")->getRestrictedValue(); - producedUnit= ft->getUnitType(producedUnitName); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); -} - -string ProduceCommandType::getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const{ - string str=getName(translatedValue)+"\n"; - Lang &lang= Lang::getInstance(); - - //prod speed - str+= lang.getString("ProductionSpeed",(translatedValue == true ? "" : "english"))+": "+ intToStr(produceSkillType->getSpeed()); - if(totalUpgrade->getProdSpeed(produceSkillType)!=0){ - str+="+" + intToStr(totalUpgrade->getProdSpeed(produceSkillType)); - } - str+="\n"; - str+=""+Lang::getInstance().getString("TimeSteps",(translatedValue == true ? "" : "english"))+": "+intToStr(getProducedUnit()->getProductionTime())+"\n"; - int64 speed=produceSkillType->getSpeed()+totalUpgrade->getProdSpeed(produceSkillType); - int64 time=getProducedUnit()->getProductionTime(); - int64 seconds=time*100/speed; - str+=""+Lang::getInstance().getString("Time",(translatedValue == true ? "" : "english"))+": "+intToStr(seconds); - str+="\n"; - - //mpcost - if(produceSkillType->getEpCost()!=0){ - str+= lang.getString("EpCost",(translatedValue == true ? "" : "english"))+": "+intToStr(produceSkillType->getEpCost())+"\n"; - } - if(produceSkillType->getHpCost()!=0){ - str+= lang.getString("hpCost",(translatedValue == true ? "" : "english"))+": "+intToStr(produceSkillType->getHpCost())+"\n"; - } - str+= "\n" + getProducedUnit()->getReqDesc(translatedValue); - str+=produceSkillType->getBoostDesc(translatedValue); - return str; -} - -string ProduceCommandType::toString(bool translatedValue) const{ - if(translatedValue == false) { - return "Produce"; - } - Lang &lang= Lang::getInstance(); - return lang.getString("Produce"); -} - -string ProduceCommandType::getReqDesc(bool translatedValue) const{ - return RequirableType::getReqDesc(translatedValue)+"\n"+getProducedUnit()->getReqDesc(translatedValue); -} - -const ProducibleType *ProduceCommandType::getProduced() const{ - return producedUnit; +// varios +ProduceCommandType::ProduceCommandType() { + commandTypeClass = ccProduce; + clicks = cOne; + produceSkillType = NULL; + producedUnit = NULL; +} + +void ProduceCommandType::update(UnitUpdater *unitUpdater, Unit *unit, + int frameIndex) const { + unitUpdater->updateProduce(unit, frameIndex); +} + +void ProduceCommandType::load( + int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader) { + CommandType::load(id, n, dir, tt, ft, ut, loadedFileList, parentLoader); + + // produce + string skillName = + n->getChild("produce-skill")->getAttribute("value")->getRestrictedValue(); + produceSkillType = static_cast( + ut.getSkillType(skillName, scProduce)); + + string producedUnitName = + n->getChild("produced-unit")->getAttribute("name")->getRestrictedValue(); + producedUnit = ft->getUnitType(producedUnitName); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); +} + +string ProduceCommandType::getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const { + string str = getName(translatedValue) + "\n"; + Lang &lang = Lang::getInstance(); + + // prod speed + str += lang.getString("ProductionSpeed", + (translatedValue == true ? "" : "english")) + + ": " + intToStr(produceSkillType->getSpeed()); + if (totalUpgrade->getProdSpeed(produceSkillType) != 0) { + str += "+" + intToStr(totalUpgrade->getProdSpeed(produceSkillType)); + } + str += "\n"; + str += "" + + Lang::getInstance().getString( + "TimeSteps", (translatedValue == true ? "" : "english")) + + ": " + intToStr(getProducedUnit()->getProductionTime()) + "\n"; + int64 speed = produceSkillType->getSpeed() + + totalUpgrade->getProdSpeed(produceSkillType); + int64 time = getProducedUnit()->getProductionTime(); + int64 seconds = time * 100 / speed; + str += "" + + Lang::getInstance().getString( + "Time", (translatedValue == true ? "" : "english")) + + ": " + intToStr(seconds); + str += "\n"; + + // mpcost + if (produceSkillType->getEpCost() != 0) { + str += + lang.getString("EpCost", (translatedValue == true ? "" : "english")) + + ": " + intToStr(produceSkillType->getEpCost()) + "\n"; + } + if (produceSkillType->getHpCost() != 0) { + str += + lang.getString("hpCost", (translatedValue == true ? "" : "english")) + + ": " + intToStr(produceSkillType->getHpCost()) + "\n"; + } + str += "\n" + getProducedUnit()->getReqDesc(translatedValue); + str += produceSkillType->getBoostDesc(translatedValue); + return str; +} + +string ProduceCommandType::toString(bool translatedValue) const { + if (translatedValue == false) { + return "Produce"; + } + Lang &lang = Lang::getInstance(); + return lang.getString("Produce"); +} + +string ProduceCommandType::getReqDesc(bool translatedValue) const { + return RequirableType::getReqDesc(translatedValue) + "\n" + + getProducedUnit()->getReqDesc(translatedValue); +} + +const ProducibleType *ProduceCommandType::getProduced() const { + return producedUnit; } // ===================================================== // class UpgradeCommandType // ===================================================== -//varios -UpgradeCommandType::UpgradeCommandType(){ - commandTypeClass= ccUpgrade; - clicks= cOne; - upgradeSkillType=NULL; - producedUpgrade=NULL; -} - -void UpgradeCommandType::update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const { - unitUpdater->updateUpgrade(unit, frameIndex); -} - -void UpgradeCommandType::load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList, string parentLoader) { - - CommandType::load(id, n, dir, tt, ft, ut, loadedFileList, parentLoader); - - //upgrade - string skillName= n->getChild("upgrade-skill")->getAttribute("value")->getRestrictedValue(); - upgradeSkillType= static_cast(ut.getSkillType(skillName, scUpgrade)); - - string producedUpgradeName= n->getChild("produced-upgrade")->getAttribute("name")->getRestrictedValue(); - producedUpgrade= ft->getUpgradeType(producedUpgradeName); - -} - -string UpgradeCommandType::getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const{ - string str; - Lang &lang= Lang::getInstance(); - - str=getName(translatedValue)+"\n"; - str+= lang.getString("UpgradeSpeed",(translatedValue == true ? "" : "english"))+": "+ intToStr(upgradeSkillType->getSpeed()); - if(totalUpgrade->getProdSpeed(upgradeSkillType) != 0) { - str+= "+" + intToStr(totalUpgrade->getProdSpeed(upgradeSkillType)); - } - str+="\n"; - str+=""+Lang::getInstance().getString("TimeSteps",(translatedValue == true ? "" : "english"))+": "+intToStr(getProducedUpgrade()->getProductionTime())+"\n"; - int64 speed=upgradeSkillType->getSpeed()+totalUpgrade->getProdSpeed(upgradeSkillType); - int64 time=getProducedUpgrade()->getProductionTime(); - int64 seconds=time*100/speed; - str+=""+Lang::getInstance().getString("Time",(translatedValue == true ? "" : "english"))+": "+intToStr(seconds); - str+="\n"; - - if(upgradeSkillType->getEpCost()!=0) - str+= lang.getString("EpCost",(translatedValue == true ? "" : "english"))+": "+intToStr(upgradeSkillType->getEpCost())+"\n"; - if(upgradeSkillType->getHpCost()!=0) - str+= lang.getString("HpCost",(translatedValue == true ? "" : "english"))+": "+intToStr(upgradeSkillType->getHpCost())+"\n"; - str+= "\n"+getProducedUpgrade()->getReqDesc(translatedValue); - str+=upgradeSkillType->getBoostDesc(translatedValue); - return str; -} - -string UpgradeCommandType::toString(bool translatedValue) const{ - if(translatedValue == false) { - return "Upgrade"; - } - Lang &lang= Lang::getInstance(); - return lang.getString("Upgrade"); -} - -string UpgradeCommandType::getReqDesc(bool translatedValue) const{ - return RequirableType::getReqDesc(translatedValue)+"\n"+getProducedUpgrade()->getReqDesc(translatedValue); -} - -const ProducibleType *UpgradeCommandType::getProduced() const{ - return producedUpgrade; +// varios +UpgradeCommandType::UpgradeCommandType() { + commandTypeClass = ccUpgrade; + clicks = cOne; + upgradeSkillType = NULL; + producedUpgrade = NULL; +} + +void UpgradeCommandType::update(UnitUpdater *unitUpdater, Unit *unit, + int frameIndex) const { + unitUpdater->updateUpgrade(unit, frameIndex); +} + +void UpgradeCommandType::load( + int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader) { + + CommandType::load(id, n, dir, tt, ft, ut, loadedFileList, parentLoader); + + // upgrade + string skillName = + n->getChild("upgrade-skill")->getAttribute("value")->getRestrictedValue(); + upgradeSkillType = static_cast( + ut.getSkillType(skillName, scUpgrade)); + + string producedUpgradeName = n->getChild("produced-upgrade") + ->getAttribute("name") + ->getRestrictedValue(); + producedUpgrade = ft->getUpgradeType(producedUpgradeName); +} + +string UpgradeCommandType::getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const { + string str; + Lang &lang = Lang::getInstance(); + + str = getName(translatedValue) + "\n"; + str += lang.getString("UpgradeSpeed", + (translatedValue == true ? "" : "english")) + + ": " + intToStr(upgradeSkillType->getSpeed()); + if (totalUpgrade->getProdSpeed(upgradeSkillType) != 0) { + str += "+" + intToStr(totalUpgrade->getProdSpeed(upgradeSkillType)); + } + str += "\n"; + str += "" + + Lang::getInstance().getString( + "TimeSteps", (translatedValue == true ? "" : "english")) + + ": " + intToStr(getProducedUpgrade()->getProductionTime()) + "\n"; + int64 speed = upgradeSkillType->getSpeed() + + totalUpgrade->getProdSpeed(upgradeSkillType); + int64 time = getProducedUpgrade()->getProductionTime(); + int64 seconds = time * 100 / speed; + str += "" + + Lang::getInstance().getString( + "Time", (translatedValue == true ? "" : "english")) + + ": " + intToStr(seconds); + str += "\n"; + + if (upgradeSkillType->getEpCost() != 0) + str += + lang.getString("EpCost", (translatedValue == true ? "" : "english")) + + ": " + intToStr(upgradeSkillType->getEpCost()) + "\n"; + if (upgradeSkillType->getHpCost() != 0) + str += + lang.getString("HpCost", (translatedValue == true ? "" : "english")) + + ": " + intToStr(upgradeSkillType->getHpCost()) + "\n"; + str += "\n" + getProducedUpgrade()->getReqDesc(translatedValue); + str += upgradeSkillType->getBoostDesc(translatedValue); + return str; +} + +string UpgradeCommandType::toString(bool translatedValue) const { + if (translatedValue == false) { + return "Upgrade"; + } + Lang &lang = Lang::getInstance(); + return lang.getString("Upgrade"); +} + +string UpgradeCommandType::getReqDesc(bool translatedValue) const { + return RequirableType::getReqDesc(translatedValue) + "\n" + + getProducedUpgrade()->getReqDesc(translatedValue); +} + +const ProducibleType *UpgradeCommandType::getProduced() const { + return producedUpgrade; } // ===================================================== // class MorphCommandType // ===================================================== -//varios -MorphCommandType::MorphCommandType(){ - commandTypeClass= ccMorph; - clicks= cOne; - morphSkillType=NULL; - morphUnit=NULL; - discount=0; - ignoreResourceRequirements = false; -} - -void MorphCommandType::update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const { - unitUpdater->updateMorph(unit, frameIndex); -} - -void MorphCommandType::load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList, string parentLoader) { - CommandType::load(id, n, dir, tt, ft, ut, loadedFileList, parentLoader); - - //morph skill - string skillName= n->getChild("morph-skill")->getAttribute("value")->getRestrictedValue(); - morphSkillType= static_cast(ut.getSkillType(skillName, scMorph)); - - //morph unit - string morphUnitName= n->getChild("morph-unit")->getAttribute("name")->getRestrictedValue(); - morphUnit= ft->getUnitType(morphUnitName); - - //discount - discount= n->getChild("discount")->getAttribute("value")->getIntValue(); - - ignoreResourceRequirements = false; - if(n->hasChild("ignore-resource-requirements") == true) { - ignoreResourceRequirements= n->getChild("ignore-resource-requirements")->getAttribute("value")->getBoolValue(); - - //printf("ignoreResourceRequirements = %d\n",ignoreResourceRequirements); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); -} - -string MorphCommandType::getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const{ - string str=getName(translatedValue)+"\n"; - Lang &lang= Lang::getInstance(); - - //prod speed - str+= lang.getString("MorphSpeed",(translatedValue == true ? "" : "english"))+": "+ intToStr(morphSkillType->getSpeed()); - if(totalUpgrade->getProdSpeed(morphSkillType)!=0){ - str+="+" + intToStr(totalUpgrade->getProdSpeed(morphSkillType)); - } - str+="\n"; - str+=""+Lang::getInstance().getString("TimeSteps",(translatedValue == true ? "" : "english"))+": "+intToStr(getMorphUnit()->getProductionTime())+"\n"; - int64 speed=morphSkillType->getSpeed()+totalUpgrade->getProdSpeed(morphSkillType); - int64 time=getMorphUnit()->getProductionTime(); - int64 seconds=time*100/speed; - str+=""+Lang::getInstance().getString("Time",(translatedValue == true ? "" : "english"))+": "+intToStr(seconds); - str+="\n"; - - //mpcost - if(morphSkillType->getEpCost()!=0){ - str+= lang.getString("EpCost",(translatedValue == true ? "" : "english"))+": "+intToStr(morphSkillType->getEpCost())+"\n"; - } - if(morphSkillType->getHpCost()!=0){ - str+= lang.getString("HpCost",(translatedValue == true ? "" : "english"))+": "+intToStr(morphSkillType->getHpCost())+"\n"; - } - - //discount - if(discount!=0){ - str+= lang.getString("Discount",(translatedValue == true ? "" : "english"))+": "+intToStr(discount)+"%\n"; - } - - str+= "\n"+getProduced()->getReqDesc(ignoreResourceRequirements,translatedValue); - - str+=morphSkillType->getBoostDesc(translatedValue); - - return str; -} - -string MorphCommandType::toString(bool translatedValue) const{ - if(translatedValue == false) { - return "Morph"; - } - Lang &lang= Lang::getInstance(); - return lang.getString("Morph"); -} - -string MorphCommandType::getReqDesc(bool translatedValue) const{ - return RequirableType::getReqDesc(translatedValue) + "\n" + getProduced()->getReqDesc(translatedValue); -} - -const ProducibleType *MorphCommandType::getProduced() const{ - return morphUnit; +// varios +MorphCommandType::MorphCommandType() { + commandTypeClass = ccMorph; + clicks = cOne; + morphSkillType = NULL; + morphUnit = NULL; + discount = 0; + ignoreResourceRequirements = false; +} + +void MorphCommandType::update(UnitUpdater *unitUpdater, Unit *unit, + int frameIndex) const { + unitUpdater->updateMorph(unit, frameIndex); +} + +void MorphCommandType::load( + int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader) { + CommandType::load(id, n, dir, tt, ft, ut, loadedFileList, parentLoader); + + // morph skill + string skillName = + n->getChild("morph-skill")->getAttribute("value")->getRestrictedValue(); + morphSkillType = + static_cast(ut.getSkillType(skillName, scMorph)); + + // morph unit + string morphUnitName = + n->getChild("morph-unit")->getAttribute("name")->getRestrictedValue(); + morphUnit = ft->getUnitType(morphUnitName); + + // discount + discount = n->getChild("discount")->getAttribute("value")->getIntValue(); + + ignoreResourceRequirements = false; + if (n->hasChild("ignore-resource-requirements") == true) { + ignoreResourceRequirements = n->getChild("ignore-resource-requirements") + ->getAttribute("value") + ->getBoolValue(); + + // printf("ignoreResourceRequirements = %d\n",ignoreResourceRequirements); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); +} + +string MorphCommandType::getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const { + string str = getName(translatedValue) + "\n"; + Lang &lang = Lang::getInstance(); + + // prod speed + str += + lang.getString("MorphSpeed", (translatedValue == true ? "" : "english")) + + ": " + intToStr(morphSkillType->getSpeed()); + if (totalUpgrade->getProdSpeed(morphSkillType) != 0) { + str += "+" + intToStr(totalUpgrade->getProdSpeed(morphSkillType)); + } + str += "\n"; + str += "" + + Lang::getInstance().getString( + "TimeSteps", (translatedValue == true ? "" : "english")) + + ": " + intToStr(getMorphUnit()->getProductionTime()) + "\n"; + int64 speed = + morphSkillType->getSpeed() + totalUpgrade->getProdSpeed(morphSkillType); + int64 time = getMorphUnit()->getProductionTime(); + int64 seconds = time * 100 / speed; + str += "" + + Lang::getInstance().getString( + "Time", (translatedValue == true ? "" : "english")) + + ": " + intToStr(seconds); + str += "\n"; + + // mpcost + if (morphSkillType->getEpCost() != 0) { + str += + lang.getString("EpCost", (translatedValue == true ? "" : "english")) + + ": " + intToStr(morphSkillType->getEpCost()) + "\n"; + } + if (morphSkillType->getHpCost() != 0) { + str += + lang.getString("HpCost", (translatedValue == true ? "" : "english")) + + ": " + intToStr(morphSkillType->getHpCost()) + "\n"; + } + + // discount + if (discount != 0) { + str += + lang.getString("Discount", (translatedValue == true ? "" : "english")) + + ": " + intToStr(discount) + "%\n"; + } + + str += "\n" + + getProduced()->getReqDesc(ignoreResourceRequirements, translatedValue); + + str += morphSkillType->getBoostDesc(translatedValue); + + return str; +} + +string MorphCommandType::toString(bool translatedValue) const { + if (translatedValue == false) { + return "Morph"; + } + Lang &lang = Lang::getInstance(); + return lang.getString("Morph"); +} + +string MorphCommandType::getReqDesc(bool translatedValue) const { + return RequirableType::getReqDesc(translatedValue) + "\n" + + getProduced()->getReqDesc(translatedValue); +} + +const ProducibleType *MorphCommandType::getProduced() const { + return morphUnit; } // ===================================================== // class SwitchTeamCommandType // ===================================================== -//varios -SwitchTeamCommandType::SwitchTeamCommandType(){ - commandTypeClass= ccSwitchTeam; - clicks= cOne; +// varios +SwitchTeamCommandType::SwitchTeamCommandType() { + commandTypeClass = ccSwitchTeam; + clicks = cOne; } -void SwitchTeamCommandType::update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const { - unitUpdater->updateSwitchTeam(unit, frameIndex); +void SwitchTeamCommandType::update(UnitUpdater *unitUpdater, Unit *unit, + int frameIndex) const { + unitUpdater->updateSwitchTeam(unit, frameIndex); } -void SwitchTeamCommandType::load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList, string parentLoader) { - CommandType::load(id, n, dir, tt, ft, ut, loadedFileList, parentLoader); +void SwitchTeamCommandType::load( + int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader) { + CommandType::load(id, n, dir, tt, ft, ut, loadedFileList, parentLoader); - //morph skill - //string skillName= n->getChild("morph-skill")->getAttribute("value")->getRestrictedValue(); - //morphSkillType= static_cast(ut.getSkillType(skillName, scMorph)); + // morph skill + // string skillName= + // n->getChild("morph-skill")->getAttribute("value")->getRestrictedValue(); + // morphSkillType= static_cast(ut.getSkillType(skillName, scMorph)); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); } -string SwitchTeamCommandType::getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const{ - string str= getName(translatedValue)+"\n"; - return str; +string SwitchTeamCommandType::getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const { + string str = getName(translatedValue) + "\n"; + return str; } -string SwitchTeamCommandType::toString(bool translatedValue) const{ - if(translatedValue == false) { - return "SwitchTeam"; - } - Lang &lang= Lang::getInstance(); - return lang.getString("SwitchTeam"); +string SwitchTeamCommandType::toString(bool translatedValue) const { + if (translatedValue == false) { + return "SwitchTeam"; + } + Lang &lang = Lang::getInstance(); + return lang.getString("SwitchTeam"); } // ===================================================== // class CommandFactory // ===================================================== -CommandTypeFactory::CommandTypeFactory(){ - registerClass("stop"); - registerClass("move"); - registerClass("attack"); - registerClass("attack_stopped"); - registerClass("build"); - registerClass("harvest"); - registerClass("repair"); - registerClass("produce"); - registerClass("upgrade"); - registerClass("morph"); - registerClass("switch_team"); - registerClass("harvest_return"); +CommandTypeFactory::CommandTypeFactory() { + registerClass("stop"); + registerClass("move"); + registerClass("attack"); + registerClass("attack_stopped"); + registerClass("build"); + registerClass("harvest"); + registerClass("repair"); + registerClass("produce"); + registerClass("upgrade"); + registerClass("morph"); + registerClass("switch_team"); + registerClass("harvest_return"); } -CommandTypeFactory &CommandTypeFactory::getInstance(){ - static CommandTypeFactory ctf; - return ctf; +CommandTypeFactory &CommandTypeFactory::getInstance() { + static CommandTypeFactory ctf; + return ctf; } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/types/command_type.h b/source/glest_game/types/command_type.h index 913272c53..c7b29a517 100644 --- a/source/glest_game/types/command_type.h +++ b/source/glest_game/types/command_type.h @@ -13,20 +13,21 @@ #define _GLEST_GAME_COMMANDTYPE_H_ #ifdef WIN32 - #include - #include +#include +#include #endif #include "element_type.h" -#include "resource_type.h" +#include "factory.h" #include "lang.h" +#include "leak_dumper.h" +#include "resource_type.h" #include "skill_type.h" -#include "factory.h" -#include "xml_parser.h" #include "sound_container.h" -#include "leak_dumper.h" +#include "xml_parser.h" -namespace Glest { namespace Game { +namespace Glest { +namespace Game { using Shared::Util::MultiFactory; @@ -37,34 +38,26 @@ class TechTree; class FactionType; enum CommandClass { - ccStop, - ccMove, - ccAttack, - ccAttackStopped, - ccBuild, - ccHarvest, - ccRepair, - ccProduce, - ccUpgrade, - ccMorph, - ccSwitchTeam, - ccHarvestEmergencyReturn, - - ccCount, - ccNull + ccStop, + ccMove, + ccAttack, + ccAttackStopped, + ccBuild, + ccHarvest, + ccRepair, + ccProduce, + ccUpgrade, + ccMorph, + ccSwitchTeam, + ccHarvestEmergencyReturn, + + ccCount, + ccNull }; -enum Clicks { - cOne, - cTwo -}; +enum Clicks { cOne, cTwo }; -enum Queueability { - qNever, - qOnRequest, - qOnlyLast, - qAlways -}; +enum Queueability { qNever, qOnRequest, qOnlyLast, qAlways }; // ===================================================== // class CommandType @@ -72,406 +65,469 @@ enum Queueability { /// A complex action performed by a unit, composed by skills // ===================================================== -class CommandType: public RequirableType { +class CommandType : public RequirableType { protected: - Clicks clicks; - int id; + Clicks clicks; + int id; - std::map fogOfWarSkillAttachments; - const FogOfWarSkillType* fogOfWarSkillType; + std::map fogOfWarSkillAttachments; + const FogOfWarSkillType *fogOfWarSkillType; public: - static const int invalidId= -1; - CommandClass commandTypeClass; + static const int invalidId = -1; + CommandClass commandTypeClass; public: - CommandType() { - commandTypeClass = ccNull; - clicks = cOne; - id = -1; - fogOfWarSkillType = NULL; - fogOfWarSkillAttachments.clear(); - } - virtual void update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const= 0; - virtual void load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList, string parentLoader); - virtual string getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const= 0; - virtual string toString(bool translatedValue) const= 0; - virtual const ProducibleType *getProduced() const {return NULL;} - virtual Queueability isQueuable() const {return qOnRequest;} - bool isQueuable(bool tryQueue) const { - Queueability q = isQueuable(); - return (q == qAlways) || ((q == qOnRequest || q == qOnlyLast) && tryQueue); - } - bool isQueueAppendable() const { - Queueability q = isQueuable(); - return (q != qNever) && (q != qOnlyLast); - } - //Priority: commands of higher priority will cancel commands of lower priority - virtual int getTypePriority() const {return 10;} - virtual bool usesPathfinder() const= 0; - - //get - CommandClass getClass() const; - Clicks getClicks() const {return clicks;} - int getId() const {return id;} - - const FogOfWarSkillType *getFogOfWarSkillType() const {return fogOfWarSkillType;}; - - bool hasFogOfWarSkillType(string name) const; + CommandType() { + commandTypeClass = ccNull; + clicks = cOne; + id = -1; + fogOfWarSkillType = NULL; + fogOfWarSkillAttachments.clear(); + } + virtual void update(UnitUpdater *unitUpdater, Unit *unit, + int frameIndex) const = 0; + virtual void + load(int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader); + virtual string getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const = 0; + virtual string toString(bool translatedValue) const = 0; + virtual const ProducibleType *getProduced() const { return NULL; } + virtual Queueability isQueuable() const { return qOnRequest; } + bool isQueuable(bool tryQueue) const { + Queueability q = isQueuable(); + return (q == qAlways) || ((q == qOnRequest || q == qOnlyLast) && tryQueue); + } + bool isQueueAppendable() const { + Queueability q = isQueuable(); + return (q != qNever) && (q != qOnlyLast); + } + // Priority: commands of higher priority will cancel commands of lower + // priority + virtual int getTypePriority() const { return 10; } + virtual bool usesPathfinder() const = 0; + + // get + CommandClass getClass() const; + Clicks getClicks() const { return clicks; } + int getId() const { return id; } + + const FogOfWarSkillType *getFogOfWarSkillType() const { + return fogOfWarSkillType; + }; + + bool hasFogOfWarSkillType(string name) const; }; // =============================== // class StopCommandType // =============================== -class StopCommandType: public CommandType { +class StopCommandType : public CommandType { private: - const StopSkillType* stopSkillType; + const StopSkillType *stopSkillType; public: - StopCommandType(); - virtual void update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const; - virtual void load(int id, const XmlNode *n, const string &dir, const TechTree *tt, - const FactionType *ft, const UnitType &ut, std::map > > &loadedFileList, - string parentLoader); - virtual string getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const; - virtual string toString(bool translatedValue) const; - virtual Queueability isQueuable() const {return qNever;} - virtual int getTypePriority() const {return 100000;} - //get - const StopSkillType *getStopSkillType() const {return stopSkillType;}; - - virtual bool usesPathfinder() const { return false; } + StopCommandType(); + virtual void update(UnitUpdater *unitUpdater, Unit *unit, + int frameIndex) const; + virtual void + load(int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader); + virtual string getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const; + virtual string toString(bool translatedValue) const; + virtual Queueability isQueuable() const { return qNever; } + virtual int getTypePriority() const { return 100000; } + // get + const StopSkillType *getStopSkillType() const { return stopSkillType; }; + + virtual bool usesPathfinder() const { return false; } }; - // =============================== // class MoveCommandType // =============================== -class MoveCommandType: public CommandType { +class MoveCommandType : public CommandType { private: - const MoveSkillType *moveSkillType; + const MoveSkillType *moveSkillType; public: - MoveCommandType(); - virtual void update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const; - virtual void load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList, string parentLoader); - virtual string getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const; - virtual string toString(bool translatedValue) const; - - //get - const MoveSkillType *getMoveSkillType() const {return moveSkillType;}; - - virtual bool usesPathfinder() const { return true; } + MoveCommandType(); + virtual void update(UnitUpdater *unitUpdater, Unit *unit, + int frameIndex) const; + virtual void + load(int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader); + virtual string getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const; + virtual string toString(bool translatedValue) const; + + // get + const MoveSkillType *getMoveSkillType() const { return moveSkillType; }; + + virtual bool usesPathfinder() const { return true; } }; - // =============================== // class AttackCommandType // =============================== -class AttackCommandType: public CommandType { +class AttackCommandType : public CommandType { private: - const MoveSkillType* moveSkillType; - const AttackSkillType* attackSkillType; + const MoveSkillType *moveSkillType; + const AttackSkillType *attackSkillType; public: - AttackCommandType(); - virtual void update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const; - virtual void load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList, string parentLoader); - virtual string getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const; - virtual string toString(bool translatedValue) const; - - - //get - const MoveSkillType * getMoveSkillType() const {return moveSkillType;} - const AttackSkillType * getAttackSkillType() const {return attackSkillType;} - - virtual bool usesPathfinder() const { return true; } + AttackCommandType(); + virtual void update(UnitUpdater *unitUpdater, Unit *unit, + int frameIndex) const; + virtual void + load(int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader); + virtual string getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const; + virtual string toString(bool translatedValue) const; + + // get + const MoveSkillType *getMoveSkillType() const { return moveSkillType; } + const AttackSkillType *getAttackSkillType() const { return attackSkillType; } + + virtual bool usesPathfinder() const { return true; } }; // ======================================= // class AttackStoppedCommandType // ======================================= -class AttackStoppedCommandType: public CommandType { +class AttackStoppedCommandType : public CommandType { private: - const StopSkillType* stopSkillType; - const AttackSkillType* attackSkillType; + const StopSkillType *stopSkillType; + const AttackSkillType *attackSkillType; public: - AttackStoppedCommandType(); - virtual void update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const; - virtual void load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList, string parentLoader); - virtual string getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const; - virtual string toString(bool translatedValue) const; - - //get - const StopSkillType * getStopSkillType() const {return stopSkillType;} - const AttackSkillType * getAttackSkillType() const {return attackSkillType;} - - virtual bool usesPathfinder() const { return false; } + AttackStoppedCommandType(); + virtual void update(UnitUpdater *unitUpdater, Unit *unit, + int frameIndex) const; + virtual void + load(int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader); + virtual string getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const; + virtual string toString(bool translatedValue) const; + + // get + const StopSkillType *getStopSkillType() const { return stopSkillType; } + const AttackSkillType *getAttackSkillType() const { return attackSkillType; } + + virtual bool usesPathfinder() const { return false; } }; - // =============================== // class BuildCommandType // =============================== -class BuildCommandType: public CommandType { +class BuildCommandType : public CommandType { private: - const MoveSkillType* moveSkillType; - const BuildSkillType* buildSkillType; - vector buildings; - SoundContainer startSounds; - SoundContainer builtSounds; + const MoveSkillType *moveSkillType; + const BuildSkillType *buildSkillType; + vector buildings; + SoundContainer startSounds; + SoundContainer builtSounds; public: - BuildCommandType(); - ~BuildCommandType(); - virtual void update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const; - virtual void load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList, string parentLoader); - virtual string getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const; - virtual string toString(bool translatedValue) const; - - //get - const MoveSkillType *getMoveSkillType() const {return moveSkillType;} - const BuildSkillType *getBuildSkillType() const {return buildSkillType;} - int getBuildingCount() const {return (int)buildings.size();} - const UnitType * getBuilding(int i) const {return buildings[i];} - StaticSound *getStartSound() const {return startSounds.getRandSound();} - StaticSound *getBuiltSound() const {return builtSounds.getRandSound();} - - virtual bool usesPathfinder() const { return true; } + BuildCommandType(); + ~BuildCommandType(); + virtual void update(UnitUpdater *unitUpdater, Unit *unit, + int frameIndex) const; + virtual void + load(int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader); + virtual string getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const; + virtual string toString(bool translatedValue) const; + + // get + const MoveSkillType *getMoveSkillType() const { return moveSkillType; } + const BuildSkillType *getBuildSkillType() const { return buildSkillType; } + int getBuildingCount() const { return (int)buildings.size(); } + const UnitType *getBuilding(int i) const { return buildings[i]; } + StaticSound *getStartSound() const { return startSounds.getRandSound(); } + StaticSound *getBuiltSound() const { return builtSounds.getRandSound(); } + + virtual bool usesPathfinder() const { return true; } }; - // =============================== // class HarvestCommandType // =============================== -class HarvestCommandType: public CommandType { +class HarvestCommandType : public CommandType { private: - const MoveSkillType *moveSkillType; - const MoveSkillType *moveLoadedSkillType; - const HarvestSkillType *harvestSkillType; - const StopSkillType *stopLoadedSkillType; - vector harvestedResources; - int maxLoad; - int hitsPerUnit; + const MoveSkillType *moveSkillType; + const MoveSkillType *moveLoadedSkillType; + const HarvestSkillType *harvestSkillType; + const StopSkillType *stopLoadedSkillType; + vector harvestedResources; + int maxLoad; + int hitsPerUnit; public: - HarvestCommandType(); - virtual void update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const; - virtual void load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList, string parentLoader); - virtual string getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const; - virtual string toString(bool translatedValue) const; - virtual Queueability isQueuable() const {return qOnRequest;} - - //get - const MoveSkillType *getMoveSkillType() const {return moveSkillType;} - const MoveSkillType *getMoveLoadedSkillType() const {return moveLoadedSkillType;} - const HarvestSkillType *getHarvestSkillType() const {return harvestSkillType;} - const StopSkillType *getStopLoadedSkillType() const {return stopLoadedSkillType;} - int getMaxLoad() const {return maxLoad;} - int getHitsPerUnit() const {return hitsPerUnit;} - int getHarvestedResourceCount() const {return (int)harvestedResources.size();} - const ResourceType* getHarvestedResource(int i) const {return harvestedResources[i];} - bool canHarvest(const ResourceType *resourceType) const; - - virtual bool usesPathfinder() const { return true; } + HarvestCommandType(); + virtual void update(UnitUpdater *unitUpdater, Unit *unit, + int frameIndex) const; + virtual void + load(int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader); + virtual string getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const; + virtual string toString(bool translatedValue) const; + virtual Queueability isQueuable() const { return qOnRequest; } + + // get + const MoveSkillType *getMoveSkillType() const { return moveSkillType; } + const MoveSkillType *getMoveLoadedSkillType() const { + return moveLoadedSkillType; + } + const HarvestSkillType *getHarvestSkillType() const { + return harvestSkillType; + } + const StopSkillType *getStopLoadedSkillType() const { + return stopLoadedSkillType; + } + int getMaxLoad() const { return maxLoad; } + int getHitsPerUnit() const { return hitsPerUnit; } + int getHarvestedResourceCount() const { + return (int)harvestedResources.size(); + } + const ResourceType *getHarvestedResource(int i) const { + return harvestedResources[i]; + } + bool canHarvest(const ResourceType *resourceType) const; + + virtual bool usesPathfinder() const { return true; } }; // =============================== // class HarvestEmergencyReturnCommandType // =============================== -class HarvestEmergencyReturnCommandType: public CommandType { +class HarvestEmergencyReturnCommandType : public CommandType { private: - public: - HarvestEmergencyReturnCommandType(); - virtual void update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const; - virtual void load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList, string parentLoader); - virtual string getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const; - virtual string toString(bool translatedValue) const; - virtual Queueability isQueuable() const {return qOnRequest;} - - //get - virtual bool usesPathfinder() const { return true; } + HarvestEmergencyReturnCommandType(); + virtual void update(UnitUpdater *unitUpdater, Unit *unit, + int frameIndex) const; + virtual void + load(int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader); + virtual string getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const; + virtual string toString(bool translatedValue) const; + virtual Queueability isQueuable() const { return qOnRequest; } + + // get + virtual bool usesPathfinder() const { return true; } }; - // =============================== // class RepairCommandType // =============================== -class RepairCommandType: public CommandType { +class RepairCommandType : public CommandType { private: - const MoveSkillType* moveSkillType; - const RepairSkillType* repairSkillType; - vector repairableUnits; + const MoveSkillType *moveSkillType; + const RepairSkillType *repairSkillType; + vector repairableUnits; public: - RepairCommandType(); - ~RepairCommandType(); - virtual void update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const; - virtual void load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList, string parentLoader); - virtual string getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const; - virtual string toString(bool translatedValue) const; - - //get - const MoveSkillType *getMoveSkillType() const {return moveSkillType;}; - const RepairSkillType *getRepairSkillType() const {return repairSkillType;}; - bool isRepairableUnitType(const UnitType *unitType) const; - - int getRepairCount() const {return (int)repairableUnits.size();} - const UnitType * getRepair(int i) const {return repairableUnits[i];} - - virtual bool usesPathfinder() const { return true; } + RepairCommandType(); + ~RepairCommandType(); + virtual void update(UnitUpdater *unitUpdater, Unit *unit, + int frameIndex) const; + virtual void + load(int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader); + virtual string getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const; + virtual string toString(bool translatedValue) const; + + // get + const MoveSkillType *getMoveSkillType() const { return moveSkillType; }; + const RepairSkillType *getRepairSkillType() const { return repairSkillType; }; + bool isRepairableUnitType(const UnitType *unitType) const; + + int getRepairCount() const { return (int)repairableUnits.size(); } + const UnitType *getRepair(int i) const { return repairableUnits[i]; } + + virtual bool usesPathfinder() const { return true; } }; - // =============================== // class ProduceCommandType // =============================== -class ProduceCommandType: public CommandType { +class ProduceCommandType : public CommandType { private: - const ProduceSkillType* produceSkillType; - const UnitType *producedUnit; + const ProduceSkillType *produceSkillType; + const UnitType *producedUnit; public: - ProduceCommandType(); - virtual void update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const; - virtual void load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList, string parentLoader); - virtual string getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const; - virtual string getReqDesc(bool translatedValue) const; - virtual string toString(bool translatedValue) const; - virtual const ProducibleType *getProduced() const; - virtual Queueability isQueuable() const {return qAlways;} - virtual int getTypePriority() const {return 15;} - - //get - const ProduceSkillType *getProduceSkillType() const {return produceSkillType;} - const UnitType *getProducedUnit() const {return producedUnit;} - - virtual bool usesPathfinder() const { return false; } + ProduceCommandType(); + virtual void update(UnitUpdater *unitUpdater, Unit *unit, + int frameIndex) const; + virtual void + load(int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader); + virtual string getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const; + virtual string getReqDesc(bool translatedValue) const; + virtual string toString(bool translatedValue) const; + virtual const ProducibleType *getProduced() const; + virtual Queueability isQueuable() const { return qAlways; } + virtual int getTypePriority() const { return 15; } + + // get + const ProduceSkillType *getProduceSkillType() const { + return produceSkillType; + } + const UnitType *getProducedUnit() const { return producedUnit; } + + virtual bool usesPathfinder() const { return false; } }; - // =============================== // class UpgradeCommandType // =============================== -class UpgradeCommandType: public CommandType { +class UpgradeCommandType : public CommandType { private: - const UpgradeSkillType* upgradeSkillType; - const UpgradeType* producedUpgrade; + const UpgradeSkillType *upgradeSkillType; + const UpgradeType *producedUpgrade; public: - UpgradeCommandType(); - virtual void update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const; - virtual void load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList, string parentLoader); - virtual string getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const; - virtual string toString(bool translatedValue) const; - virtual string getReqDesc(bool translatedValue) const; - virtual const ProducibleType *getProduced() const; - virtual Queueability isQueuable() const {return qAlways;} - virtual int getTypePriority() const {return 15;} - - //get - const UpgradeSkillType *getUpgradeSkillType() const {return upgradeSkillType;} - const UpgradeType *getProducedUpgrade() const {return producedUpgrade;} - - virtual bool usesPathfinder() const { return false; } + UpgradeCommandType(); + virtual void update(UnitUpdater *unitUpdater, Unit *unit, + int frameIndex) const; + virtual void + load(int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader); + virtual string getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const; + virtual string toString(bool translatedValue) const; + virtual string getReqDesc(bool translatedValue) const; + virtual const ProducibleType *getProduced() const; + virtual Queueability isQueuable() const { return qAlways; } + virtual int getTypePriority() const { return 15; } + + // get + const UpgradeSkillType *getUpgradeSkillType() const { + return upgradeSkillType; + } + const UpgradeType *getProducedUpgrade() const { return producedUpgrade; } + + virtual bool usesPathfinder() const { return false; } }; // =============================== // class MorphCommandType // =============================== -class MorphCommandType: public CommandType { +class MorphCommandType : public CommandType { private: - const MorphSkillType* morphSkillType; - const UnitType* morphUnit; - int discount; - bool ignoreResourceRequirements; + const MorphSkillType *morphSkillType; + const UnitType *morphUnit; + int discount; + bool ignoreResourceRequirements; public: - MorphCommandType(); - virtual void update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const; - virtual void load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList, string parentLoader); - virtual string getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const; - virtual string toString(bool translatedValue) const; - virtual string getReqDesc(bool translatedValue) const; - virtual const ProducibleType *getProduced() const; - Queueability isQueuable() const {return qOnlyLast;} //After morph anything can happen - - //get - const MorphSkillType *getMorphSkillType() const {return morphSkillType;} - const UnitType *getMorphUnit() const {return morphUnit;} - int getDiscount() const {return discount;} - bool getIgnoreResourceRequirements() const {return ignoreResourceRequirements;} - - virtual bool usesPathfinder() const { return false; } + MorphCommandType(); + virtual void update(UnitUpdater *unitUpdater, Unit *unit, + int frameIndex) const; + virtual void + load(int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader); + virtual string getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const; + virtual string toString(bool translatedValue) const; + virtual string getReqDesc(bool translatedValue) const; + virtual const ProducibleType *getProduced() const; + Queueability isQueuable() const { + return qOnlyLast; + } // After morph anything can happen + + // get + const MorphSkillType *getMorphSkillType() const { return morphSkillType; } + const UnitType *getMorphUnit() const { return morphUnit; } + int getDiscount() const { return discount; } + bool getIgnoreResourceRequirements() const { + return ignoreResourceRequirements; + } + + virtual bool usesPathfinder() const { return false; } }; // =============================== // class SwitchTeamCommandType // =============================== -class SwitchTeamCommandType: public CommandType { +class SwitchTeamCommandType : public CommandType { private: - - public: - SwitchTeamCommandType(); - virtual void update(UnitUpdater *unitUpdater, Unit *unit, int frameIndex) const; - virtual void load(int id, const XmlNode *n, const string &dir, - const TechTree *tt, const FactionType *ft, const UnitType &ut, - std::map > > &loadedFileList, string parentLoader); - virtual string getDesc(const TotalUpgrade *totalUpgrade, bool translatedValue) const; - virtual string toString(bool translatedValue) const; - - virtual bool usesPathfinder() const { return false; } + SwitchTeamCommandType(); + virtual void update(UnitUpdater *unitUpdater, Unit *unit, + int frameIndex) const; + virtual void + load(int id, const XmlNode *n, const string &dir, const TechTree *tt, + const FactionType *ft, const UnitType &ut, + std::map>> &loadedFileList, + string parentLoader); + virtual string getDesc(const TotalUpgrade *totalUpgrade, + bool translatedValue) const; + virtual string toString(bool translatedValue) const; + + virtual bool usesPathfinder() const { return false; } }; // =============================== // class CommandFactory // =============================== -class CommandTypeFactory: public MultiFactory{ +class CommandTypeFactory : public MultiFactory { private: - CommandTypeFactory(); + CommandTypeFactory(); public: - static CommandTypeFactory &getInstance(); + static CommandTypeFactory &getInstance(); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/types/damage_multiplier.cpp b/source/glest_game/types/damage_multiplier.cpp index 192b4e073..eec8ed890 100644 --- a/source/glest_game/types/damage_multiplier.cpp +++ b/source/glest_game/types/damage_multiplier.cpp @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -16,90 +16,101 @@ using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { void AttackType::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *attackTypeNode = rootNode->addChild("AttackType"); + std::map mapTagReplacements; + XmlNode *attackTypeNode = rootNode->addChild("AttackType"); -// string name; - attackTypeNode->addAttribute("name",name, mapTagReplacements); -// int id; - attackTypeNode->addAttribute("id",intToStr(id), mapTagReplacements); + // string name; + attackTypeNode->addAttribute("name", name, mapTagReplacements); + // int id; + attackTypeNode->addAttribute("id", intToStr(id), mapTagReplacements); } -string AttackType::getName(bool translatedValue) const { - if(translatedValue == false) return name; +string AttackType::getName(bool translatedValue) const { + if (translatedValue == false) + return name; - Lang &lang = Lang::getInstance(); - return lang.getTechTreeString("AttackTypeName_" + name,name.c_str()); + Lang &lang = Lang::getInstance(); + return lang.getTechTreeString("AttackTypeName_" + name, name.c_str()); } void ArmorType::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *armorTypeNode = rootNode->addChild("ArmorType"); + std::map mapTagReplacements; + XmlNode *armorTypeNode = rootNode->addChild("ArmorType"); -// string name; - armorTypeNode->addAttribute("name",name, mapTagReplacements); -// int id; - armorTypeNode->addAttribute("id",intToStr(id), mapTagReplacements); + // string name; + armorTypeNode->addAttribute("name", name, mapTagReplacements); + // int id; + armorTypeNode->addAttribute("id", intToStr(id), mapTagReplacements); } -string ArmorType::getName(bool translatedValue) const { - if(translatedValue == false) return name; +string ArmorType::getName(bool translatedValue) const { + if (translatedValue == false) + return name; - Lang &lang = Lang::getInstance(); - return lang.getTechTreeString("ArmorTypeName_" + name,name.c_str()); + Lang &lang = Lang::getInstance(); + return lang.getTechTreeString("ArmorTypeName_" + name, name.c_str()); } // ===================================================== // class DamageMultiplierTable // ===================================================== -DamageMultiplierTable::DamageMultiplierTable(){ - values= NULL; - attackTypeCount=0; - armorTypeCount=0; +DamageMultiplierTable::DamageMultiplierTable() { + values = NULL; + attackTypeCount = 0; + armorTypeCount = 0; } -DamageMultiplierTable::~DamageMultiplierTable(){ - delete [] values; - values=NULL; +DamageMultiplierTable::~DamageMultiplierTable() { + delete[] values; + values = NULL; } -void DamageMultiplierTable::init(int attackTypeCount, int armorTypeCount){ - this->attackTypeCount= attackTypeCount; - this->armorTypeCount= armorTypeCount; - - int valueCount= attackTypeCount * armorTypeCount; - values= new double[valueCount]; - for(int i=0; iattackTypeCount = attackTypeCount; + this->armorTypeCount = armorTypeCount; + + int valueCount = attackTypeCount * armorTypeCount; + values = new double[valueCount]; + for (int i = 0; i < valueCount; ++i) { + values[i] = 1.f; + } } -double DamageMultiplierTable::getDamageMultiplier(const AttackType *att, const ArmorType *art) const { - return values[attackTypeCount * art->getId() + att->getId()]; +double DamageMultiplierTable::getDamageMultiplier(const AttackType *att, + const ArmorType *art) const { + return values[attackTypeCount * art->getId() + att->getId()]; } -void DamageMultiplierTable::setDamageMultiplier(const AttackType *att, const ArmorType *art, double value) { - values[attackTypeCount * art->getId() + att->getId()] = value; +void DamageMultiplierTable::setDamageMultiplier(const AttackType *att, + const ArmorType *art, + double value) { + values[attackTypeCount * art->getId() + att->getId()] = value; } void DamageMultiplierTable::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *damageMultiplierTableNode = rootNode->addChild("DamageMultiplierTable"); - -// float *values; -// int attackTypeCount; -// int armorTypeCount; - damageMultiplierTableNode->addAttribute("attackTypeCount",intToStr(attackTypeCount), mapTagReplacements); - damageMultiplierTableNode->addAttribute("armorTypeCount",intToStr(armorTypeCount), mapTagReplacements); - - int valueCount= attackTypeCount * armorTypeCount; - for(int i=0; i < valueCount; ++i) { - XmlNode *valuesNode = damageMultiplierTableNode->addChild("values"); - valuesNode->addAttribute("value",doubleToStr(values[i]), mapTagReplacements); - } + std::map mapTagReplacements; + XmlNode *damageMultiplierTableNode = + rootNode->addChild("DamageMultiplierTable"); + + // float *values; + // int attackTypeCount; + // int armorTypeCount; + damageMultiplierTableNode->addAttribute( + "attackTypeCount", intToStr(attackTypeCount), mapTagReplacements); + damageMultiplierTableNode->addAttribute( + "armorTypeCount", intToStr(armorTypeCount), mapTagReplacements); + + int valueCount = attackTypeCount * armorTypeCount; + for (int i = 0; i < valueCount; ++i) { + XmlNode *valuesNode = damageMultiplierTableNode->addChild("values"); + valuesNode->addAttribute("value", doubleToStr(values[i]), + mapTagReplacements); + } } -}}//end namespaces +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/types/damage_multiplier.h b/source/glest_game/types/damage_multiplier.h index edc451a51..34916047c 100644 --- a/source/glest_game/types/damage_multiplier.h +++ b/source/glest_game/types/damage_multiplier.h @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,87 +13,86 @@ #define _GLEST_GAME_DAMAGEMULTIPLIER_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include -#include "xml_parser.h" #include "leak_dumper.h" +#include "xml_parser.h" +#include -using std::string; using Shared::Xml::XmlNode; +using std::string; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // =============================== -// class AttackType +// class AttackType // =============================== class AttackType { private: - string name; - int id; + string name; + int id; public: - AttackType() { - id = -1; - } - int getId() const {return id;} - string getName(bool translatedValue=false) const; + AttackType() { id = -1; } + int getId() const { return id; } + string getName(bool translatedValue = false) const; - void setName(const string &name) {this->name= name;} - void setId(int id) {this->id= id;} + void setName(const string &name) { this->name = name; } + void setId(int id) { this->id = id; } - void saveGame(XmlNode *rootNode); + void saveGame(XmlNode *rootNode); }; // =============================== -// class ArmorType +// class ArmorType // =============================== class ArmorType { private: - string name; - int id; + string name; + int id; public: - ArmorType() { - id = -1; - } - int getId() const {return id;} - string getName(bool translatedValue=false) const; + ArmorType() { id = -1; } + int getId() const { return id; } + string getName(bool translatedValue = false) const; - void setName(const string &name) {this->name= name;} - void setId(int id) {this->id= id;} + void setName(const string &name) { this->name = name; } + void setId(int id) { this->id = id; } - void saveGame(XmlNode *rootNode); + void saveGame(XmlNode *rootNode); }; // ===================================================== -// class DamageMultiplierTable +// class DamageMultiplierTable // -/// Some attack types have bonuses against some +/// Some attack types have bonuses against some /// armor types and vice-versa // ===================================================== class DamageMultiplierTable { private: - double *values; - int attackTypeCount; - int armorTypeCount; + double *values; + int attackTypeCount; + int armorTypeCount; public: - DamageMultiplierTable(); - ~DamageMultiplierTable(); + DamageMultiplierTable(); + ~DamageMultiplierTable(); - void init(int attackTypeCount, int armorTypeCount); - double getDamageMultiplier(const AttackType *att, const ArmorType *art) const; - void setDamageMultiplier(const AttackType *att, const ArmorType *art, double value); + void init(int attackTypeCount, int armorTypeCount); + double getDamageMultiplier(const AttackType *att, const ArmorType *art) const; + void setDamageMultiplier(const AttackType *att, const ArmorType *art, + double value); - void saveGame(XmlNode *rootNode); + void saveGame(XmlNode *rootNode); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/types/element_type.cpp b/source/glest_game/types/element_type.cpp index b1c7b15f3..bef94401a 100644 --- a/source/glest_game/types/element_type.cpp +++ b/source/glest_game/types/element_type.cpp @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,79 +13,81 @@ #include -#include "resource_type.h" -#include "upgrade_type.h" -#include "unit_type.h" -#include "resource.h" -#include "tech_tree.h" -#include "logger.h" #include "lang.h" -#include "renderer.h" #include "leak_dumper.h" +#include "logger.h" +#include "renderer.h" +#include "resource.h" +#include "resource_type.h" +#include "tech_tree.h" +#include "unit_type.h" +#include "upgrade_type.h" using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class DisplayableType // ===================================================== -DisplayableType::DisplayableType(){ - image= NULL; -} +DisplayableType::DisplayableType() { image = NULL; } string DisplayableType::getName(bool translatedValue) const { - if(translatedValue == false) return name; + if (translatedValue == false) + return name; - Lang &lang = Lang::getInstance(); - return lang.getTechTreeString("CommandName_" + name,name.c_str()); + Lang &lang = Lang::getInstance(); + return lang.getTechTreeString("CommandName_" + name, name.c_str()); } -//void DisplayableType::saveGame(XmlNode *rootNode) const { +// void DisplayableType::saveGame(XmlNode *rootNode) const { // std::map mapTagReplacements; // XmlNode *displayableTypeNode = rootNode->addChild("DisplayableType"); // // displayableTypeNode->addAttribute("name",name, mapTagReplacements); -//} +// } // ===================================================== // class RequirableType // ===================================================== -string RequirableType::getReqDesc(bool translatedValue) const{ - bool anyReqs= false; - - string reqString=""; - for(int i=0; igetName(translatedValue); - reqString+= "\n"; - anyReqs= true; - } - - for(int i=0; igetName(translatedValue); - reqString+= "\n"; - anyReqs= true; + string reqString = ""; + for (int i = 0; i < getUnitReqCount(); ++i) { + if (getUnitReq(i) == NULL) { + throw megaglest_runtime_error("getUnitReq(i) == NULL"); + } + reqString += getUnitReq(i)->getName(translatedValue); + reqString += "\n"; + anyReqs = true; + } + + for (int i = 0; i < getUpgradeReqCount(); ++i) { + if (getUpgradeReq(i) == NULL) { + throw megaglest_runtime_error("getUpgradeReq(i) == NULL"); } - string str= getName(translatedValue); - if(anyReqs){ - return str + " " + Lang::getInstance().getString("Reqs",(translatedValue == true ? "" : "english")) + ":\n" + reqString; - } - else{ - return str; - } -} + reqString += getUpgradeReq(i)->getName(translatedValue); + reqString += "\n"; + anyReqs = true; + } + + string str = getName(translatedValue); + if (anyReqs) { + return str + " " + + Lang::getInstance().getString( + "Reqs", (translatedValue == true ? "" : "english")) + + ":\n" + reqString; + } else { + return str; + } +} -//void RequirableType::saveGame(XmlNode *rootNode) const { +// void RequirableType::saveGame(XmlNode *rootNode) const { // DisplayableType::saveGame(rootNode); // // std::map mapTagReplacements; @@ -95,8 +97,10 @@ string RequirableType::getReqDesc(bool translatedValue) const{ // for(unsigned int i = 0; i < unitReqs.size(); ++i) { // const UnitType *ut = unitReqs[i]; // -// XmlNode *unitReqsNode = requirableTypeNode->addChild("unitReqs"); -// unitReqsNode->addAttribute("name",ut->getName(), mapTagReplacements); +// XmlNode *unitReqsNode = +// requirableTypeNode->addChild("unitReqs"); +// unitReqsNode->addAttribute("name",ut->getName(), +// mapTagReplacements); // } //// UpgradeReqs upgradeReqs; //needed upgrades // for(unsigned int i = 0; i < upgradeReqs.size(); ++i) { @@ -111,81 +115,83 @@ string RequirableType::getReqDesc(bool translatedValue) const{ // class ProducibleType // ===================================================== -ProducibleType::ProducibleType(){ - cancelImage= NULL; - productionTime=0; +ProducibleType::ProducibleType() { + cancelImage = NULL; + productionTime = 0; } -ProducibleType::~ProducibleType(){ -} +ProducibleType::~ProducibleType() {} -const Resource *ProducibleType::getCost(const ResourceType *rt) const{ - for(int i=0; i < (int)costs.size(); ++i){ - if(costs[i].getType()==rt){ - return &costs[i]; - } - } - return NULL; +const Resource *ProducibleType::getCost(const ResourceType *rt) const { + for (int i = 0; i < (int)costs.size(); ++i) { + if (costs[i].getType() == rt) { + return &costs[i]; + } + } + return NULL; } string ProducibleType::getReqDesc(bool translatedValue) const { - return getReqDesc(false,translatedValue); + return getReqDesc(false, translatedValue); } -string ProducibleType::getResourceReqDesc(bool lineBreaks, bool translatedValue) const { - string str= ""; - for(int i=0; igetAmount()!=0){ - str+= getCost(i)->getType()->getName(translatedValue); - str+= ": "+ intToStr(getCost(i)->getAmount()); - if(lineBreaks == true) { - str+= "\n"; - } - else { - str+= " "; - } - } - } +string ProducibleType::getResourceReqDesc(bool lineBreaks, + bool translatedValue) const { + string str = ""; + for (int i = 0; i < getCostCount(); ++i) { + if (getCost(i)->getAmount() != 0) { + str += getCost(i)->getType()->getName(translatedValue); + str += ": " + intToStr(getCost(i)->getAmount()); + if (lineBreaks == true) { + str += "\n"; + } else { + str += " "; + } + } + } - return str; + return str; } -string ProducibleType::getUnitAndUpgradeReqDesc(bool lineBreaks, bool translatedValue) const { - string str= ""; - for(int i=0; igetName(translatedValue); - if(lineBreaks == true) { - str+= "\n"; - } - else { - str+= " "; - } +string ProducibleType::getUnitAndUpgradeReqDesc(bool lineBreaks, + bool translatedValue) const { + string str = ""; + for (int i = 0; i < getUnitReqCount(); ++i) { + str += getUnitReq(i)->getName(translatedValue); + if (lineBreaks == true) { + str += "\n"; + } else { + str += " "; } - - for(int i=0; igetName(translatedValue); - if(lineBreaks == true) { - str+= "\n"; - } - else { - str+= " "; - } + } + + for (int i = 0; i < getUpgradeReqCount(); ++i) { + str += getUpgradeReq(i)->getName(translatedValue); + if (lineBreaks == true) { + str += "\n"; + } else { + str += " "; } + } - return str; -} - -string ProducibleType::getReqDesc(bool ignoreResourceRequirements, bool translatedValue) const { - string str= getName(translatedValue) + " " + Lang::getInstance().getString("Reqs",(translatedValue == true ? "" : "english")) + ":\n"; - if(ignoreResourceRequirements == false) { - str+= getResourceReqDesc(true,translatedValue); - } + return str; +} - str+= getUnitAndUpgradeReqDesc(true,translatedValue); - return str; +string ProducibleType::getReqDesc(bool ignoreResourceRequirements, + bool translatedValue) const { + string str = getName(translatedValue) + " " + + Lang::getInstance().getString( + "Reqs", (translatedValue == true ? "" : "english")) + + ":\n"; + if (ignoreResourceRequirements == false) { + str += getResourceReqDesc(true, translatedValue); + } + + str += getUnitAndUpgradeReqDesc(true, translatedValue); + return str; } -//void ProducibleType::saveGame(XmlNode *rootNode) const { +// void ProducibleType::saveGame(XmlNode *rootNode) const { // RequirableType::saveGame(rootNode); // // std::map mapTagReplacements; @@ -198,13 +204,16 @@ string ProducibleType::getReqDesc(bool ignoreResourceRequirements, bool translat // } //// Texture2D *cancelImage; //// int productionTime; -// producibleTypeNode->addAttribute("productionTime",intToStr(productionTime), mapTagReplacements); +// producibleTypeNode->addAttribute("productionTime",intToStr(productionTime), +// mapTagReplacements); //} -//void ProducibleType::loadGame(const XmlNode *rootNode) { -// const XmlNode *producibleTypeNode = rootNode->getChild("ProducibleType"); +// void ProducibleType::loadGame(const XmlNode *rootNode) { +// const XmlNode *producibleTypeNode = +// rootNode->getChild("ProducibleType"); // // //int newUnitId = producibleTypeNode->getAttribute("id")->getIntValue(); -//} +// } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/types/element_type.h b/source/glest_game/types/element_type.h index bc13bcfad..38e65b816 100644 --- a/source/glest_game/types/element_type.h +++ b/source/glest_game/types/element_type.h @@ -3,32 +3,33 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== -#ifndef _GLEST_GAME_ELEMENTTYPE_H_ +#ifndef _GLEST_GAME_ELEMENTTYPE_H_ #define _GLEST_GAME_ELEMENTTYPE_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include -#include -#include "texture.h" -#include "resource.h" #include "leak_dumper.h" +#include "resource.h" +#include "texture.h" +#include +#include -using std::vector; using std::string; +using std::vector; using Shared::Graphics::Texture2D; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { class UpgradeType; class TechTree; @@ -45,88 +46,88 @@ class ResourceType; class DisplayableType { protected: - string name; //name - Texture2D *image; //portrait + string name; // name + Texture2D *image; // portrait public: - DisplayableType(); - virtual ~DisplayableType(){}; + DisplayableType(); + virtual ~DisplayableType(){}; - //get - virtual string getName(bool translatedValue=false) const; - virtual const Texture2D *getImage() const { return image; } + // get + virtual string getName(bool translatedValue = false) const; + virtual const Texture2D *getImage() const { return image; } - //virtual void saveGame(XmlNode *rootNode) const; + // virtual void saveGame(XmlNode *rootNode) const; }; - // ===================================================== -// class RequirableType +// class RequirableType // /// Base class for anything that has requirements // ===================================================== -class RequirableType: public DisplayableType{ +class RequirableType : public DisplayableType { private: - typedef vector UnitReqs; - typedef vector UpgradeReqs; + typedef vector UnitReqs; + typedef vector UpgradeReqs; protected: - UnitReqs unitReqs; //needed units - UpgradeReqs upgradeReqs; //needed upgrades + UnitReqs unitReqs; // needed units + UpgradeReqs upgradeReqs; // needed upgrades public: - //get - int getUpgradeReqCount() const {return (int)upgradeReqs.size();} - int getUnitReqCount() const {return (int)unitReqs.size();} - const UpgradeType *getUpgradeReq(int i) const {return upgradeReqs[i];} - const UnitType *getUnitReq(int i) const {return unitReqs[i];} - - //other - virtual string getReqDesc(bool translatedValue) const; - - //virtual void saveGame(XmlNode *rootNode) const; -}; + // get + int getUpgradeReqCount() const { return (int)upgradeReqs.size(); } + int getUnitReqCount() const { return (int)unitReqs.size(); } + const UpgradeType *getUpgradeReq(int i) const { return upgradeReqs[i]; } + const UnitType *getUnitReq(int i) const { return unitReqs[i]; } + + // other + virtual string getReqDesc(bool translatedValue) const; + // virtual void saveGame(XmlNode *rootNode) const; +}; // ===================================================== -// class ProducibleType +// class ProducibleType // /// Base class for anything that can be produced // ===================================================== -class ProducibleType: public RequirableType { +class ProducibleType : public RequirableType { private: - typedef vector Costs; + typedef vector Costs; protected: - Costs costs; - Texture2D *cancelImage; - int productionTime; + Costs costs; + Texture2D *cancelImage; + int productionTime; public: - ProducibleType(); - virtual ~ProducibleType(); - - //get - int getCostCount() const {return (int)costs.size();} - const Resource *getCost(int i) const {return &costs[i];} - const Resource *getCost(const ResourceType *rt) const; - int getProductionTime() const {return productionTime;} - const Texture2D *getCancelImage() const {return cancelImage;} - - //varios - void checkCostStrings(TechTree *techTree); - - virtual string getReqDesc(bool translatedValue) const; - string getResourceReqDesc(bool lineBreaks,bool translatedValue) const; - string getUnitAndUpgradeReqDesc(bool lineBreaks, bool translatedValue) const; - string getReqDesc(bool ignoreResourceRequirements, bool translatedValue) const; - -// virtual void saveGame(XmlNode *rootNode) const; -// void loadGame(const XmlNode *rootNode); + ProducibleType(); + virtual ~ProducibleType(); + + // get + int getCostCount() const { return (int)costs.size(); } + const Resource *getCost(int i) const { return &costs[i]; } + const Resource *getCost(const ResourceType *rt) const; + int getProductionTime() const { return productionTime; } + const Texture2D *getCancelImage() const { return cancelImage; } + + // varios + void checkCostStrings(TechTree *techTree); + + virtual string getReqDesc(bool translatedValue) const; + string getResourceReqDesc(bool lineBreaks, bool translatedValue) const; + string getUnitAndUpgradeReqDesc(bool lineBreaks, bool translatedValue) const; + string getReqDesc(bool ignoreResourceRequirements, + bool translatedValue) const; + + // virtual void saveGame(XmlNode *rootNode) const; + // void loadGame(const XmlNode *rootNode); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/types/faction_type.cpp b/source/glest_game/types/faction_type.cpp index 329a9f43c..b6f2ccf59 100644 --- a/source/glest_game/types/faction_type.cpp +++ b/source/glest_game/types/faction_type.cpp @@ -11,1029 +11,1308 @@ #include "faction_type.h" +#include "conversion.h" +#include "game_util.h" +#include "leak_dumper.h" #include "logger.h" +#include "platform_util.h" +#include "renderer.h" +#include "resource.h" +#include "tech_tree.h" #include "util.h" #include "xml_parser.h" -#include "tech_tree.h" -#include "resource.h" -#include "renderer.h" -#include "platform_util.h" -#include "game_util.h" -#include "conversion.h" -#include "leak_dumper.h" using namespace Shared::Util; using namespace Shared::Xml; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ====================================================== // Class FactionType // ====================================================== FactionType::FactionType() { - music = NULL; - personalityType = fpt_Normal; - isLinked = false; - healthbarheight= -100.0f; - healthbarthickness= 0.11f; - healthbarVisible=hbvUndefined; - healthbarBorderTextureEnabled=false; - healthbarBackgroundTextureEnabled=false; - healthbarLineBorder=true; - healthbarTexture=NULL; - healthbarBackgroundTexture=NULL; - flatParticlePositions=false; + music = NULL; + personalityType = fpt_Normal; + isLinked = false; + healthbarheight = -100.0f; + healthbarthickness = 0.11f; + healthbarVisible = hbvUndefined; + healthbarBorderTextureEnabled = false; + healthbarBackgroundTextureEnabled = false; + healthbarLineBorder = true; + healthbarTexture = NULL; + healthbarBackgroundTexture = NULL; + flatParticlePositions = false; } -//load a faction, given a directory -void FactionType::load(const string &factionName, const TechTree *techTree, Checksum* checksum, - Checksum *techtreeChecksum, - std::map > > &loadedFileList, - bool validationMode) { - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - string techTreePath = techTree->getPath(); - string techTreeName=techTree->getNameUntranslated(); - string currentPath = ""; - - //open xml file - string path=""; - XmlTree xmlTree; - const XmlNode *factionNode; - - //printf("\n>>> factionname=%s\n",factionName.c_str()); - for(bool realFactionPathFound=false;realFactionPathFound == false;) { - currentPath = techTreePath + "factions/" + factionName; - endPathWithSlash(currentPath); - - name= lastDir(currentPath); - - // Add special Observer Faction - //Lang &lang= Lang::getInstance(); - if(name == formatString(GameConstants::OBSERVER_SLOTNAME)) { - personalityType = fpt_Observer; - } - - if(personalityType == fpt_Normal) { - string tmppath= currentPath + factionName +".xml"; - std::map mapExtraTagReplacementValues; - // mapExtraTagReplacementValues["$COMMONDATAPATH"] = techTreePath + "/commondata/"; - //printf("current $COMMONDATAPATH = %s\n",mapExtraTagReplacementValues["$COMMONDATAPATH"].c_str()); - XmlTree xmlTree; - xmlTree.load(tmppath, Properties::getTagReplacementValues(&mapExtraTagReplacementValues)); - - - const XmlNode *rootNode= xmlTree.getRootNode(); - - if(rootNode->getName()=="link") { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"Faction [%s] is a linked faction\n",name.c_str()); - - isLinked = true; - const XmlNode *techTreeNode= rootNode->getChild("techtree"); - const string linkedTechTreeName=techTreeNode->getAttribute("name")->getRestrictedValue(); - // const XmlNode *factionLinkNode= rootNode->getChild("faction"); - // string linkedFactionName=factionLinkNode->getAttribute("name")->getRestrictedValue(); - string linkedTechTreePath=techTree->findPath(linkedTechTreeName); - techTreePath=linkedTechTreePath; - endPathWithSlash(techTreePath); - techTreeName=linkedTechTreeName; - - string linkedCurrentPath = techTreePath + "factions/" + factionName; - endPathWithSlash(linkedCurrentPath); - string linkedTmppath= linkedCurrentPath + factionName +".xml"; - - //printf("linkedTmppath [%s] linkedCurrentPath [%s]\n",linkedTmppath.c_str(),linkedCurrentPath.c_str()); - - loadedFileList[linkedTmppath].push_back(make_pair(linkedCurrentPath,linkedCurrentPath)); - loadedFileList[tmppath].push_back(make_pair(currentPath,currentPath)); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"techTreePath [%s] techTreeName [%s]\n",techTreePath.c_str(),techTreeName.c_str()); - } - else { - // stop looking for new path, no more links ... - //xmlTree.load(tmppath, Properties::getTagReplacementValues(&mapExtraTagReplacementValues)); - - loadedFileList[tmppath].push_back(make_pair(currentPath,currentPath)); - - realFactionPathFound=true; - //printf("techPath found! %s\n",tmppath.c_str()); - - path=tmppath; - } - } - else { - break; - } - } - - char szBuf[8096]=""; - snprintf(szBuf,8096,Lang::getInstance().getString("LogScreenGameLoadingFactionType","",true).c_str(),formatString(this->getName()).c_str()); - Logger::getInstance().add(szBuf, true); - - if(personalityType == fpt_Normal) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"Loading faction [%s] currentPath [%s]\n",path.c_str(),currentPath.c_str()); - - checksum->addFile(path); - techtreeChecksum->addFile(path); - - // a1) preload units - //string unitsPath= currentPath + "units/*."; - string unitsPath= currentPath + "units/"; - vector unitFilenames; - //findAll(unitsPath, unitFilenames); - findDirs(unitsPath, unitFilenames,false,false); - - unitTypes.resize(unitFilenames.size()); - - for(int i = 0; i < (int)unitTypes.size(); ++i) { - string str= currentPath + "units/" + unitFilenames[i]; - unitTypes[i].preLoad(str); - - SDL_PumpEvents(); - } - - // a2) preload upgrades - //string upgradesPath= currentPath + "upgrades/*."; - string upgradesPath= currentPath + "upgrades/"; - vector upgradeFilenames; - //findAll(upgradesPath, upgradeFilenames, false, false); - findDirs(upgradesPath, upgradeFilenames,false,false); - - upgradeTypes.resize(upgradeFilenames.size()); - for(int i = 0; i < (int)upgradeTypes.size(); ++i) { - string str= currentPath + "upgrades/" + upgradeFilenames[i]; - upgradeTypes[i].preLoad(str); - - SDL_PumpEvents(); - } - - // b1) load units - try { - Logger &logger= Logger::getInstance(); - int progressBaseValue=logger.getProgress(); - for(int i = 0; i < (int)unitTypes.size(); ++i) { - string str= currentPath + "units/" + unitTypes[i].getName(); - - try { - unitTypes[i].loaddd(i, str, techTree,techTreePath, this, checksum,techtreeChecksum, - loadedFileList,validationMode); - logger.setProgress(progressBaseValue+(int)((((double)i + 1.0) / (double)unitTypes.size()) * 100.0/techTree->getTypeCount())); - SDL_PumpEvents(); - } - catch(megaglest_runtime_error& ex) { - if(validationMode == false) { - throw; - } - else { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - } - } - } - } - catch(megaglest_runtime_error& ex) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - throw megaglest_runtime_error("Error loading units: "+ currentPath + "\nMessage: " + ex.what(),!ex.wantStackTrace()); - } - catch(const exception &e) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what()); - throw megaglest_runtime_error("Error loading units: "+ currentPath + "\nMessage: " + e.what()); - } - - // b2) load upgrades - try{ - for(int i = 0; i < (int)upgradeTypes.size(); ++i) { - string str= currentPath + "upgrades/" + upgradeTypes[i].getName(); - - try { - upgradeTypes[i].load(str, techTree, this, checksum, - techtreeChecksum,loadedFileList,validationMode); - } - catch(megaglest_runtime_error& ex) { - if(validationMode == false) { - throw; - } - else { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - } - } - - SDL_PumpEvents(); - } - } - catch(const exception &e){ - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what()); - throw megaglest_runtime_error("Error loading upgrades: "+ currentPath + "\n" + e.what()); - } - - string tmppath= currentPath + factionName +".xml"; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"Loading faction xml [%s]\n",tmppath.c_str()); - - std::map mapExtraTagReplacementValues; - mapExtraTagReplacementValues["$COMMONDATAPATH"] = techTreePath + "/commondata/"; - //printf("current $COMMONDATAPATH = %s\n",mapExtraTagReplacementValues["$COMMONDATAPATH"].c_str()); - xmlTree.load(tmppath, Properties::getTagReplacementValues(&mapExtraTagReplacementValues)); - - - factionNode=xmlTree.getRootNode(); - //read starting resources - //printf("factionNode->getName()=%s",factionNode->getName().c_str()); - const XmlNode *startingResourcesNode= factionNode->getChild("starting-resources"); - - startingResources.resize(startingResourcesNode->getChildCount()); - for(int i = 0; i < (int)startingResources.size(); ++i) { - const XmlNode *resourceNode= startingResourcesNode->getChild("resource", i); - string name= resourceNode->getAttribute("name")->getRestrictedValue(); - int amount= resourceNode->getAttribute("amount")->getIntValue(); - - try { - startingResources[i].init(techTree->getResourceType(name), amount); - } - catch(megaglest_runtime_error& ex) { - if(validationMode == false) { - throw; - } - else { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\nFor FactionType: %s for StartResource: %s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what(),this->name.c_str(),name.c_str()); - } - } - - SDL_PumpEvents(); - } - - //read starting units - const XmlNode *startingUnitsNode= factionNode->getChild("starting-units"); - for(int i = 0; i < (int)startingUnitsNode->getChildCount(); ++i) { - const XmlNode *unitNode= startingUnitsNode->getChild("unit", i); - string name= unitNode->getAttribute("name")->getRestrictedValue(); - int amount= unitNode->getAttribute("amount")->getIntValue(); - startingUnits.push_back(PairPUnitTypeInt(getUnitType(name), amount)); - - SDL_PumpEvents(); - } - - //read music - const XmlNode *musicNode= factionNode->getChild("music"); - bool value= musicNode->getAttribute("value")->getBoolValue(); - if(value) { - music= new StrSound(); - music->open(musicNode->getAttribute("path")->getRestrictedValue(currentPath)); - loadedFileList[musicNode->getAttribute("path")->getRestrictedValue(currentPath)].push_back(make_pair(path,musicNode->getAttribute("path")->getRestrictedValue())); - } - - if(factionNode->hasChild("flat-particle-positions")) { - const XmlNode *node= factionNode->getChild("flat-particle-positions"); - flatParticlePositions = node->getAttribute("value")->getBoolValue(); - } - - //healthbar - if(factionNode->hasChild("healthbar")) { - const XmlNode *healthbarNode= factionNode->getChild("healthbar"); - if(healthbarNode->hasChild("height")) { - healthbarheight= healthbarNode->getChild("height")->getAttribute("value")->getFloatValue(); - } - if(healthbarNode->hasChild("thickness")) { - healthbarthickness= healthbarNode->getChild("thickness")->getAttribute("value")->getFloatValue(0.f, 1.f); - } - if(healthbarNode->hasChild("visible")) { - string healthbarVisibleString=healthbarNode->getChild("visible")->getAttribute("value")->getValue(); - vector v=split(healthbarVisibleString,"|"); - for (int i = 0; i < (int)v.size(); ++i) { - string current=trim(v[i]); - if(current=="always") { - healthbarVisible=healthbarVisible|hbvAlways; - } else if(current=="selected") { - healthbarVisible=healthbarVisible|hbvSelected; - } else if(current=="ifNeeded") { - healthbarVisible=healthbarVisible|hbvIfNeeded; - } else if(current=="off") { - healthbarVisible=healthbarVisible|hbvOff; - } else { - throw megaglest_runtime_error("Unknown Healthbar Visible Option: " + current, true); - } - } - } - if(healthbarNode->hasChild("borderTexture")) { - healthbarBorderTextureEnabled=healthbarNode->getChild("borderTexture")->getAttribute("enabled")->getBoolValue(); - if(healthbarBorderTextureEnabled && healthbarNode->getChild("borderTexture")->hasAttribute("path")) { - healthbarTexture= Renderer::getInstance().newTexture2D(rsGame); - if(healthbarTexture) { - healthbarTexture->load(healthbarNode->getChild("borderTexture")->getAttribute("path")->getRestrictedValue(currentPath)); - } - loadedFileList[healthbarNode->getChild("borderTexture")->getAttribute("path")->getRestrictedValue(currentPath)].push_back(make_pair(path,healthbarNode->getChild("borderTexture")->getAttribute("path")->getRestrictedValue())); - } - } - if(healthbarNode->hasChild("backgroundTexture")) { - healthbarBackgroundTextureEnabled=healthbarNode->getChild("backgroundTexture")->getAttribute("enabled")->getBoolValue(); - if(healthbarBackgroundTextureEnabled && healthbarNode->getChild("backgroundTexture")->hasAttribute("path")) { - healthbarBackgroundTexture= Renderer::getInstance().newTexture2D(rsGame); - if(healthbarBackgroundTexture) { - healthbarBackgroundTexture->load(healthbarNode->getChild("backgroundTexture")->getAttribute("path")->getRestrictedValue(currentPath)); - } - loadedFileList[healthbarNode->getChild("backgroundTexture")->getAttribute("path")->getRestrictedValue(currentPath)].push_back(make_pair(path,healthbarNode->getChild("backgroundTexture")->getAttribute("path")->getRestrictedValue())); - } - } - if(healthbarNode->hasChild("lineBorder")) { - healthbarLineBorder= healthbarNode->getChild("lineBorder")->getAttribute("enabled")->getBoolValue(); - } - - } - - //read ai behavior - if(factionNode->hasChild("ai-behavior") == true) { - const XmlNode *aiNode= factionNode->getChild("ai-behavior"); - if(aiNode->hasAttribute("min-static-resource-count") == true) { - mapAIBehaviorStaticOverrideValues[aibsvcMinStaticResourceCount] = aiNode->getAttribute("min-static-resource-count")->getIntValue(); - } - - if(aiNode->hasChild("static-values") == true) { - const XmlNode *aiNodeUnits= aiNode->getChild("static-values"); - for(int i = 0; i < (int)aiNodeUnits->getChildCount(); ++i) { - const XmlNode *unitNode= aiNodeUnits->getChild("static", i); - AIBehaviorStaticValueCategory type = aibsvcMaxBuildRadius; - if(unitNode->hasAttribute("type") == true) { - type = static_cast( - unitNode->getAttribute("type")->getIntValue()); - } - else { - type = EnumParser::getEnum( - unitNode->getAttribute("type-name")->getValue()); - //printf("Discovered overriden static value for AI, type = %d, value = %d\n",type,value); - } - - int value = unitNode->getAttribute("value")->getIntValue(); - mapAIBehaviorStaticOverrideValues[type]=value; - //printf("Discovered overriden static value for AI, type = %d, value = %d\n",type,value); - } - } - - if(aiNode->hasChild("worker-units") == true) { - const XmlNode *aiNodeUnits= aiNode->getChild("worker-units"); - for(int i = 0; i < (int)aiNodeUnits->getChildCount(); ++i) { - const XmlNode *unitNode= aiNodeUnits->getChild("unit", i); - string name= unitNode->getAttribute("name")->getRestrictedValue(); - int minimum= unitNode->getAttribute("minimum")->getIntValue(); - - mapAIBehaviorUnitCategories[aibcWorkerUnits].push_back(PairPUnitTypeInt(getUnitType(name), minimum)); - } - } - if(aiNode->hasChild("warrior-units") == true) { - const XmlNode *aiNodeUnits= aiNode->getChild("warrior-units"); - for(int i = 0; i < (int)aiNodeUnits->getChildCount(); ++i) { - const XmlNode *unitNode= aiNodeUnits->getChild("unit", i); - string name= unitNode->getAttribute("name")->getRestrictedValue(); - int minimum= unitNode->getAttribute("minimum")->getIntValue(); - - mapAIBehaviorUnitCategories[aibcWarriorUnits].push_back(PairPUnitTypeInt(getUnitType(name), minimum)); - } - } - if(aiNode->hasChild("resource-producer-units") == true) { - const XmlNode *aiNodeUnits= aiNode->getChild("resource-producer-units"); - for(int i = 0; i < (int)aiNodeUnits->getChildCount(); ++i) { - const XmlNode *unitNode= aiNodeUnits->getChild("unit", i); - string name= unitNode->getAttribute("name")->getRestrictedValue(); - int minimum= unitNode->getAttribute("minimum")->getIntValue(); - - mapAIBehaviorUnitCategories[aibcResourceProducerUnits].push_back(PairPUnitTypeInt(getUnitType(name), minimum)); - } - } - if(aiNode->hasChild("building-units") == true) { - const XmlNode *aiNodeUnits= aiNode->getChild("building-units"); - for(int i = 0; i < (int)aiNodeUnits->getChildCount(); ++i) { - const XmlNode *unitNode= aiNodeUnits->getChild("unit", i); - string name= unitNode->getAttribute("name")->getRestrictedValue(); - int minimum= unitNode->getAttribute("minimum")->getIntValue(); - - mapAIBehaviorUnitCategories[aibcBuildingUnits].push_back(PairPUnitTypeInt(getUnitType(name), minimum)); - } - } - - if(aiNode->hasChild("upgrades") == true) { - const XmlNode *aiNodeUpgrades= aiNode->getChild("upgrades"); - for(int i = 0; i < (int)aiNodeUpgrades->getChildCount(); ++i) { - const XmlNode *upgradeNode= aiNodeUpgrades->getChild("upgrade", i); - string name= upgradeNode->getAttribute("name")->getRestrictedValue(); - - vctAIBehaviorUpgrades.push_back(getUpgradeType(name)); - } - } - } - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); +// load a faction, given a directory +void FactionType::load( + const string &factionName, const TechTree *techTree, Checksum *checksum, + Checksum *techtreeChecksum, + std::map>> &loadedFileList, + bool validationMode) { + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + string techTreePath = techTree->getPath(); + string techTreeName = techTree->getNameUntranslated(); + string currentPath = ""; + + // open xml file + string path = ""; + XmlTree xmlTree; + const XmlNode *factionNode; + + // printf("\n>>> factionname=%s\n",factionName.c_str()); + for (bool realFactionPathFound = false; realFactionPathFound == false;) { + currentPath = techTreePath + "factions/" + factionName; + endPathWithSlash(currentPath); + + name = lastDir(currentPath); + + // Add special Observer Faction + // Lang &lang= Lang::getInstance(); + if (name == formatString(GameConstants::OBSERVER_SLOTNAME)) { + personalityType = fpt_Observer; + } + + if (personalityType == fpt_Normal) { + string tmppath = currentPath + factionName + ".xml"; + std::map mapExtraTagReplacementValues; + // mapExtraTagReplacementValues["$COMMONDATAPATH"] = + // techTreePath + "/commondata/"; printf("current $COMMONDATAPATH = + // %s\n",mapExtraTagReplacementValues["$COMMONDATAPATH"].c_str()); + XmlTree xmlTree; + xmlTree.load(tmppath, Properties::getTagReplacementValues( + &mapExtraTagReplacementValues)); + + const XmlNode *rootNode = xmlTree.getRootNode(); + + if (rootNode->getName() == "link") { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "Faction [%s] is a linked faction\n", + name.c_str()); + + isLinked = true; + const XmlNode *techTreeNode = rootNode->getChild("techtree"); + const string linkedTechTreeName = + techTreeNode->getAttribute("name")->getRestrictedValue(); + // const XmlNode *factionLinkNode= + // rootNode->getChild("faction"); string + // linkedFactionName=factionLinkNode->getAttribute("name")->getRestrictedValue(); + string linkedTechTreePath = techTree->findPath(linkedTechTreeName); + techTreePath = linkedTechTreePath; + endPathWithSlash(techTreePath); + techTreeName = linkedTechTreeName; + + string linkedCurrentPath = techTreePath + "factions/" + factionName; + endPathWithSlash(linkedCurrentPath); + string linkedTmppath = linkedCurrentPath + factionName + ".xml"; + + // printf("linkedTmppath [%s] linkedCurrentPath + // [%s]\n",linkedTmppath.c_str(),linkedCurrentPath.c_str()); + + loadedFileList[linkedTmppath].push_back( + make_pair(linkedCurrentPath, linkedCurrentPath)); + loadedFileList[tmppath].push_back(make_pair(currentPath, currentPath)); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "techTreePath [%s] techTreeName [%s]\n", + techTreePath.c_str(), techTreeName.c_str()); + } else { + // stop looking for new path, no more links ... + // xmlTree.load(tmppath, + // Properties::getTagReplacementValues(&mapExtraTagReplacementValues)); + + loadedFileList[tmppath].push_back(make_pair(currentPath, currentPath)); + + realFactionPathFound = true; + // printf("techPath found! %s\n",tmppath.c_str()); + + path = tmppath; + } + } else { + break; + } + } + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + Lang::getInstance() + .getString("LogScreenGameLoadingFactionType", "", true) + .c_str(), + formatString(this->getName()).c_str()); + Logger::getInstance().add(szBuf, true); + + if (personalityType == fpt_Normal) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "Loading faction [%s] currentPath [%s]\n", + path.c_str(), currentPath.c_str()); + + checksum->addFile(path); + techtreeChecksum->addFile(path); + + // a1) preload units + // string unitsPath= currentPath + "units/*."; + string unitsPath = currentPath + "units/"; + vector unitFilenames; + // findAll(unitsPath, unitFilenames); + findDirs(unitsPath, unitFilenames, false, false); + + unitTypes.resize(unitFilenames.size()); + + for (int i = 0; i < (int)unitTypes.size(); ++i) { + string str = currentPath + "units/" + unitFilenames[i]; + unitTypes[i].preLoad(str); + + SDL_PumpEvents(); + } + + // a2) preload upgrades + // string upgradesPath= currentPath + "upgrades/*."; + string upgradesPath = currentPath + "upgrades/"; + vector upgradeFilenames; + // findAll(upgradesPath, upgradeFilenames, false, false); + findDirs(upgradesPath, upgradeFilenames, false, false); + + upgradeTypes.resize(upgradeFilenames.size()); + for (int i = 0; i < (int)upgradeTypes.size(); ++i) { + string str = currentPath + "upgrades/" + upgradeFilenames[i]; + upgradeTypes[i].preLoad(str); + + SDL_PumpEvents(); + } + + // b1) load units + try { + Logger &logger = Logger::getInstance(); + int progressBaseValue = logger.getProgress(); + for (int i = 0; i < (int)unitTypes.size(); ++i) { + string str = currentPath + "units/" + unitTypes[i].getName(); + + try { + unitTypes[i].loaddd(i, str, techTree, techTreePath, this, checksum, + techtreeChecksum, loadedFileList, validationMode); + logger.setProgress( + progressBaseValue + + (int)((((double)i + 1.0) / (double)unitTypes.size()) * 100.0 / + techTree->getTypeCount())); + SDL_PumpEvents(); + } catch (megaglest_runtime_error &ex) { + if (validationMode == false) { + throw; + } else { + SystemFlags::OutputDebug( + SystemFlags::debugError, "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + } + } + } + } catch (megaglest_runtime_error &ex) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + throw megaglest_runtime_error("Error loading units: " + currentPath + + "\nMessage: " + ex.what(), + !ex.wantStackTrace()); + } catch (const exception &e) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, e.what()); + throw megaglest_runtime_error("Error loading units: " + currentPath + + "\nMessage: " + e.what()); + } + + // b2) load upgrades + try { + for (int i = 0; i < (int)upgradeTypes.size(); ++i) { + string str = currentPath + "upgrades/" + upgradeTypes[i].getName(); + + try { + upgradeTypes[i].load(str, techTree, this, checksum, techtreeChecksum, + loadedFileList, validationMode); + } catch (megaglest_runtime_error &ex) { + if (validationMode == false) { + throw; + } else { + SystemFlags::OutputDebug( + SystemFlags::debugError, "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what()); + } + } + + SDL_PumpEvents(); + } + } catch (const exception &e) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, e.what()); + throw megaglest_runtime_error("Error loading upgrades: " + currentPath + + "\n" + e.what()); + } + + string tmppath = currentPath + factionName + ".xml"; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "Loading faction xml [%s]\n", tmppath.c_str()); + + std::map mapExtraTagReplacementValues; + mapExtraTagReplacementValues["$COMMONDATAPATH"] = + techTreePath + "/commondata/"; + // printf("current $COMMONDATAPATH = + // %s\n",mapExtraTagReplacementValues["$COMMONDATAPATH"].c_str()); + xmlTree.load(tmppath, Properties::getTagReplacementValues( + &mapExtraTagReplacementValues)); + + factionNode = xmlTree.getRootNode(); + // read starting resources + // printf("factionNode->getName()=%s",factionNode->getName().c_str()); + const XmlNode *startingResourcesNode = + factionNode->getChild("starting-resources"); + + startingResources.resize(startingResourcesNode->getChildCount()); + for (int i = 0; i < (int)startingResources.size(); ++i) { + const XmlNode *resourceNode = + startingResourcesNode->getChild("resource", i); + string name = resourceNode->getAttribute("name")->getRestrictedValue(); + int amount = resourceNode->getAttribute("amount")->getIntValue(); + + try { + startingResources[i].init(techTree->getResourceType(name), amount); + } catch (megaglest_runtime_error &ex) { + if (validationMode == false) { + throw; + } else { + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\nFor FactionType: %s for " + "StartResource: %s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what(), this->name.c_str(), name.c_str()); + } + } + + SDL_PumpEvents(); + } + + // read starting units + const XmlNode *startingUnitsNode = factionNode->getChild("starting-units"); + for (int i = 0; i < (int)startingUnitsNode->getChildCount(); ++i) { + const XmlNode *unitNode = startingUnitsNode->getChild("unit", i); + string name = unitNode->getAttribute("name")->getRestrictedValue(); + int amount = unitNode->getAttribute("amount")->getIntValue(); + startingUnits.push_back(PairPUnitTypeInt(getUnitType(name), amount)); + + SDL_PumpEvents(); + } + + // read music + const XmlNode *musicNode = factionNode->getChild("music"); + bool value = musicNode->getAttribute("value")->getBoolValue(); + if (value) { + music = new StrSound(); + music->open( + musicNode->getAttribute("path")->getRestrictedValue(currentPath)); + loadedFileList[musicNode->getAttribute("path")->getRestrictedValue( + currentPath)] + .push_back(make_pair( + path, musicNode->getAttribute("path")->getRestrictedValue())); + } + + if (factionNode->hasChild("flat-particle-positions")) { + const XmlNode *node = factionNode->getChild("flat-particle-positions"); + flatParticlePositions = node->getAttribute("value")->getBoolValue(); + } + + // healthbar + if (factionNode->hasChild("healthbar")) { + const XmlNode *healthbarNode = factionNode->getChild("healthbar"); + if (healthbarNode->hasChild("height")) { + healthbarheight = healthbarNode->getChild("height") + ->getAttribute("value") + ->getFloatValue(); + } + if (healthbarNode->hasChild("thickness")) { + healthbarthickness = healthbarNode->getChild("thickness") + ->getAttribute("value") + ->getFloatValue(0.f, 1.f); + } + if (healthbarNode->hasChild("visible")) { + string healthbarVisibleString = healthbarNode->getChild("visible") + ->getAttribute("value") + ->getValue(); + vector v = split(healthbarVisibleString, "|"); + for (int i = 0; i < (int)v.size(); ++i) { + string current = trim(v[i]); + if (current == "always") { + healthbarVisible = healthbarVisible | hbvAlways; + } else if (current == "selected") { + healthbarVisible = healthbarVisible | hbvSelected; + } else if (current == "ifNeeded") { + healthbarVisible = healthbarVisible | hbvIfNeeded; + } else if (current == "off") { + healthbarVisible = healthbarVisible | hbvOff; + } else { + throw megaglest_runtime_error( + "Unknown Healthbar Visible Option: " + current, true); + } + } + } + if (healthbarNode->hasChild("borderTexture")) { + healthbarBorderTextureEnabled = healthbarNode->getChild("borderTexture") + ->getAttribute("enabled") + ->getBoolValue(); + if (healthbarBorderTextureEnabled && + healthbarNode->getChild("borderTexture")->hasAttribute("path")) { + healthbarTexture = Renderer::getInstance().newTexture2D(rsGame); + if (healthbarTexture) { + healthbarTexture->load(healthbarNode->getChild("borderTexture") + ->getAttribute("path") + ->getRestrictedValue(currentPath)); + } + loadedFileList[healthbarNode->getChild("borderTexture") + ->getAttribute("path") + ->getRestrictedValue(currentPath)] + .push_back( + make_pair(path, healthbarNode->getChild("borderTexture") + ->getAttribute("path") + ->getRestrictedValue())); + } + } + if (healthbarNode->hasChild("backgroundTexture")) { + healthbarBackgroundTextureEnabled = + healthbarNode->getChild("backgroundTexture") + ->getAttribute("enabled") + ->getBoolValue(); + if (healthbarBackgroundTextureEnabled && + healthbarNode->getChild("backgroundTexture") + ->hasAttribute("path")) { + healthbarBackgroundTexture = + Renderer::getInstance().newTexture2D(rsGame); + if (healthbarBackgroundTexture) { + healthbarBackgroundTexture->load( + healthbarNode->getChild("backgroundTexture") + ->getAttribute("path") + ->getRestrictedValue(currentPath)); + } + loadedFileList[healthbarNode->getChild("backgroundTexture") + ->getAttribute("path") + ->getRestrictedValue(currentPath)] + .push_back( + make_pair(path, healthbarNode->getChild("backgroundTexture") + ->getAttribute("path") + ->getRestrictedValue())); + } + } + if (healthbarNode->hasChild("lineBorder")) { + healthbarLineBorder = healthbarNode->getChild("lineBorder") + ->getAttribute("enabled") + ->getBoolValue(); + } + } + + // read ai behavior + if (factionNode->hasChild("ai-behavior") == true) { + const XmlNode *aiNode = factionNode->getChild("ai-behavior"); + if (aiNode->hasAttribute("min-static-resource-count") == true) { + mapAIBehaviorStaticOverrideValues[aibsvcMinStaticResourceCount] = + aiNode->getAttribute("min-static-resource-count")->getIntValue(); + } + + if (aiNode->hasChild("static-values") == true) { + const XmlNode *aiNodeUnits = aiNode->getChild("static-values"); + for (int i = 0; i < (int)aiNodeUnits->getChildCount(); ++i) { + const XmlNode *unitNode = aiNodeUnits->getChild("static", i); + AIBehaviorStaticValueCategory type = aibsvcMaxBuildRadius; + if (unitNode->hasAttribute("type") == true) { + type = static_cast( + unitNode->getAttribute("type")->getIntValue()); + } else { + type = EnumParser::getEnum( + unitNode->getAttribute("type-name")->getValue()); + // printf("Discovered overriden static value for AI, type = %d, + // value = %d\n",type,value); + } + + int value = unitNode->getAttribute("value")->getIntValue(); + mapAIBehaviorStaticOverrideValues[type] = value; + // printf("Discovered overriden static value for AI, type = %d, value + // = %d\n",type,value); + } + } + + if (aiNode->hasChild("worker-units") == true) { + const XmlNode *aiNodeUnits = aiNode->getChild("worker-units"); + for (int i = 0; i < (int)aiNodeUnits->getChildCount(); ++i) { + const XmlNode *unitNode = aiNodeUnits->getChild("unit", i); + string name = unitNode->getAttribute("name")->getRestrictedValue(); + int minimum = unitNode->getAttribute("minimum")->getIntValue(); + + mapAIBehaviorUnitCategories[aibcWorkerUnits].push_back( + PairPUnitTypeInt(getUnitType(name), minimum)); + } + } + if (aiNode->hasChild("warrior-units") == true) { + const XmlNode *aiNodeUnits = aiNode->getChild("warrior-units"); + for (int i = 0; i < (int)aiNodeUnits->getChildCount(); ++i) { + const XmlNode *unitNode = aiNodeUnits->getChild("unit", i); + string name = unitNode->getAttribute("name")->getRestrictedValue(); + int minimum = unitNode->getAttribute("minimum")->getIntValue(); + + mapAIBehaviorUnitCategories[aibcWarriorUnits].push_back( + PairPUnitTypeInt(getUnitType(name), minimum)); + } + } + if (aiNode->hasChild("resource-producer-units") == true) { + const XmlNode *aiNodeUnits = + aiNode->getChild("resource-producer-units"); + for (int i = 0; i < (int)aiNodeUnits->getChildCount(); ++i) { + const XmlNode *unitNode = aiNodeUnits->getChild("unit", i); + string name = unitNode->getAttribute("name")->getRestrictedValue(); + int minimum = unitNode->getAttribute("minimum")->getIntValue(); + + mapAIBehaviorUnitCategories[aibcResourceProducerUnits].push_back( + PairPUnitTypeInt(getUnitType(name), minimum)); + } + } + if (aiNode->hasChild("building-units") == true) { + const XmlNode *aiNodeUnits = aiNode->getChild("building-units"); + for (int i = 0; i < (int)aiNodeUnits->getChildCount(); ++i) { + const XmlNode *unitNode = aiNodeUnits->getChild("unit", i); + string name = unitNode->getAttribute("name")->getRestrictedValue(); + int minimum = unitNode->getAttribute("minimum")->getIntValue(); + + mapAIBehaviorUnitCategories[aibcBuildingUnits].push_back( + PairPUnitTypeInt(getUnitType(name), minimum)); + } + } + + if (aiNode->hasChild("upgrades") == true) { + const XmlNode *aiNodeUpgrades = aiNode->getChild("upgrades"); + for (int i = 0; i < (int)aiNodeUpgrades->getChildCount(); ++i) { + const XmlNode *upgradeNode = aiNodeUpgrades->getChild("upgrade", i); + string name = upgradeNode->getAttribute("name")->getRestrictedValue(); + + vctAIBehaviorUpgrades.push_back(getUpgradeType(name)); + } + } + } + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); } -int FactionType::getAIBehaviorStaticOverideValue(AIBehaviorStaticValueCategory type) const { - int result = INT_MAX; - std::map::const_iterator iterFind = - mapAIBehaviorStaticOverrideValues.find(type); - if(iterFind != mapAIBehaviorStaticOverrideValues.end()) { - result = iterFind->second; - } - return result; +int FactionType::getAIBehaviorStaticOverideValue( + AIBehaviorStaticValueCategory type) const { + int result = INT_MAX; + std::map::const_iterator iterFind = + mapAIBehaviorStaticOverrideValues.find(type); + if (iterFind != mapAIBehaviorStaticOverrideValues.end()) { + result = iterFind->second; + } + return result; } -const std::vector FactionType::getAIBehaviorUnits(AIBehaviorUnitCategory category) const { - std::map >::const_iterator iterFind = mapAIBehaviorUnitCategories.find(category); - if(iterFind != mapAIBehaviorUnitCategories.end()) { - return iterFind->second; - } - return std::vector(); +const std::vector +FactionType::getAIBehaviorUnits(AIBehaviorUnitCategory category) const { + std::map>::const_iterator iterFind = + mapAIBehaviorUnitCategories.find(category); + if (iterFind != mapAIBehaviorUnitCategories.end()) { + return iterFind->second; + } + return std::vector(); } -FactionType::~FactionType(){ - delete music; - music = NULL; +FactionType::~FactionType() { + delete music; + music = NULL; } std::vector FactionType::validateFactionType() { - std::vector results; - - const uint32 MAX_BITRATE_WARNING = 200000; - StrSound *factionMusic = getMusic(); - if(factionMusic != NULL && factionMusic->getInfo()->getBitRate() > MAX_BITRATE_WARNING) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"The Faction [%s] has the music [%s]\nwhich has a bitrate of [%u] which may cause some sound drivers to crash, please use a bitrate of %d or less!",this->getName().c_str(),factionMusic->getFileName().c_str(),factionMusic->getInfo()->getBitRate(),MAX_BITRATE_WARNING); - results.push_back(szBuf); - } - - for(int i=0; i < (int)unitTypes.size(); ++i){ - UnitType &unitType = unitTypes[i]; - - for(int i = 0; i < (int)unitType.getSelectionSounds().getSounds().size(); ++i) { - StaticSound *sound = unitType.getSelectionSounds().getSounds()[i]; - if(sound != NULL && sound->getInfo()->getBitRate() > MAX_BITRATE_WARNING) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"The Unit [%s] in Faction [%s] has the sound [%s]\nwhich has a bitrate of [%u] which may cause some sound drivers to crash, please use a bitrate of %d or less!",unitType.getName().c_str(),this->getName().c_str(),sound->getFileName().c_str(),sound->getInfo()->getBitRate(),MAX_BITRATE_WARNING); - results.push_back(szBuf); - } - } - for(int i = 0; i < (int)unitType.getCommandSounds().getSounds().size(); ++i) { - StaticSound *sound = unitType.getCommandSounds().getSounds()[i]; - if(sound != NULL && sound->getInfo()->getBitRate() > MAX_BITRATE_WARNING) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"The Unit [%s] in Faction [%s] has the sound [%s]\nwhich has a bitrate of [%u] which may cause some sound drivers to crash, please use a bitrate of %d or less!",unitType.getName().c_str(),this->getName().c_str(),sound->getFileName().c_str(),sound->getInfo()->getBitRate(),MAX_BITRATE_WARNING); - results.push_back(szBuf); - } - } - - int morphCommandCount = 0; - for(int j = 0; j < (int)unitType.getCommandTypeCount(); ++j) { - const CommandType *cmdType = unitType.getCommandType(j); - if(cmdType != NULL) { - // Check every unit's commands to validate that for every upgrade-requirements - // upgrade we have a unit that can do the upgrade in the faction. - for(int k = 0; k < cmdType->getUpgradeReqCount(); ++k) { - const UpgradeType *upgradeType = cmdType->getUpgradeReq(k); - - if(upgradeType != NULL) { - // Now lets find a unit that can produced-upgrade this upgrade - bool foundUpgraderUnit = false; - for(int l=0; l < (int)unitTypes.size() && foundUpgraderUnit == false; ++l){ - UnitType &unitType2 = unitTypes[l]; - for(int m = 0; m < unitType2.getCommandTypeCount() && foundUpgraderUnit == false; ++m) { - const CommandType *cmdType2 = unitType2.getCommandType(m); - if(cmdType2 != NULL && dynamic_cast(cmdType2) != NULL) { - const UpgradeCommandType *uct = dynamic_cast(cmdType2); - if(uct != NULL) { - const UpgradeType *upgradeType2 = uct->getProducedUpgrade(); - if(upgradeType2 != NULL && upgradeType2->getName() == upgradeType->getName()) { - foundUpgraderUnit = true; - break; - } - } - } - } - } - - if(foundUpgraderUnit == false) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"The Unit [%s] in Faction [%s] has the command [%s]\nwhich has upgrade requirement [%s] but there are no units able to perform the upgrade!",unitType.getName().c_str(),this->getName().c_str(),cmdType->getName().c_str(),upgradeType->getName().c_str()); - results.push_back(szBuf); - } - } - } - - // Ensure for each build type command that the build units - // exist in this faction - if(cmdType->getClass() == ccBuild) { - const BuildCommandType *build = dynamic_cast(cmdType); - if(build == NULL) { - throw megaglest_runtime_error("build == NULL"); - } - for(int k = 0; k < build->getBuildingCount(); ++k) { - const UnitType *buildUnit = build->getBuilding(k); - - // Now lets find the unit that we should be able to build - bool foundUnit = false; - for(int l=0; l < (int)unitTypes.size() && foundUnit == false; ++l){ - UnitType &unitType2 = unitTypes[l]; - if(unitType2.getName() == buildUnit->getName()) { - foundUnit = true; - - // Now also validate the the unit to be built - // has a be_built_skill - if(buildUnit->hasSkillClass(scBeBuilt) == false) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"The Unit [%s] in Faction [%s] has the command [%s]\nwhich can build the Unit [%s] but the Unit to be built\ndoes not have the skill class [be_built_skill] in this faction!",unitType.getName().c_str(),this->getName().c_str(),cmdType->getName().c_str(),buildUnit->getName().c_str()); - results.push_back(szBuf); - } - - break; - } - } - - if(foundUnit == false) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"The Unit [%s] in Faction [%s] has the command [%s]\nwhich can build the Unit [%s] but the Unit to be built does not exist in this faction!",unitType.getName().c_str(),this->getName().c_str(),cmdType->getName().c_str(),buildUnit->getName().c_str()); - results.push_back(szBuf); - } - } - } - // Ensure for each repair type command that the repair units - // exist in this faction - if(cmdType->getClass() == ccRepair) { - const RepairCommandType *repair = dynamic_cast(cmdType); - if(repair == NULL) { - throw megaglest_runtime_error("repair == NULL"); - } - for(int k = 0; k < repair->getRepairCount(); ++k) { - const UnitType *repairUnit = repair->getRepair(k); - - // Now lets find the unit that we should be able to repair - bool foundUnit = false; - for(int l=0; l < (int)unitTypes.size() && foundUnit == false; ++l){ - UnitType &unitType2 = unitTypes[l]; - if(unitType2.getName() == repairUnit->getName()) { - foundUnit = true; - break; - } - } - - if(foundUnit == false) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"The Unit [%s] in Faction [%s] has the command [%s]\nwhich can repair the Unit [%s] but the Unit to be repaired does not exist in this faction!",unitType.getName().c_str(),this->getName().c_str(),cmdType->getName().c_str(),repairUnit->getName().c_str()); - results.push_back(szBuf); - } - } - } - // Ensure for each morph type command that the morph units - // exist in this faction - if(cmdType->getClass() == ccMorph) { - const MorphCommandType *morph = dynamic_cast(cmdType); - if(morph != NULL) { - morphCommandCount++; - const UnitType *morphUnit = morph->getMorphUnit(); - - // Now lets find the unit that we should be able to morph - // to - bool foundUnit = false; - for(int l=0; l < (int)unitTypes.size() && foundUnit == false; ++l){ - UnitType &unitType2 = unitTypes[l]; - if(unitType2.getName() == morphUnit->getName()) { - foundUnit = true; - break; - } - } - - if(foundUnit == false) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"The Unit [%s] in Faction [%s] has the command [%s]\nwhich can morph into the Unit [%s] but the Unit to be morphed to does not exist in this faction!",unitType.getName().c_str(),this->getName().c_str(),cmdType->getName().c_str(),morphUnit->getName().c_str()); - results.push_back(szBuf); - } - } - } - } - } - - const int maxMorphsAllowed = 6; - if(morphCommandCount > maxMorphsAllowed) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"The Unit [%s] in Faction [%s] has more than %d morph commands which is too many to display in the UI!",unitType.getName().c_str(),this->getName().c_str(),maxMorphsAllowed); - results.push_back(szBuf); - } - - // Check every unit's unit requirements to validate that for every unit-requirements - // we have the units required in the faction. - for(int j = 0; j < unitType.getUnitReqCount(); ++j) { - const UnitType *unitType2 = unitType.getUnitReq(j); - if(unitType2 != NULL) { - // Now lets find the required unit - bool foundUnit = false; - for(int l=0; l < (int)unitTypes.size() && foundUnit == false; ++l){ - UnitType &unitType3 = unitTypes[l]; - - if(unitType2->getName() == unitType3.getName()) { - foundUnit = true; - break; - } - } - - if(foundUnit == false) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"The Unit [%s] in Faction [%s] has the required Unit [%s]\nbut the required unit does not exist in this faction!",unitType.getName().c_str(),this->getName().c_str(),unitType2->getName().c_str()); - results.push_back(szBuf); - } - } - } - - // Now check that at least 1 other unit can produce, build or morph this unit - bool foundUnit = false; - for(int l=0; l < (int)unitTypes.size() && foundUnit == false; ++l){ - UnitType &unitType2 = unitTypes[l]; - - for(int j = 0; j < unitType2.getCommandTypeCount() && foundUnit == false; ++j) { - const CommandType *cmdType = unitType2.getCommandType(j); - if(cmdType != NULL) { - // Check if this is a produce command - if(cmdType->getClass() == ccProduce) { - const ProduceCommandType *produce = dynamic_cast(cmdType); - if(produce != NULL) { - const UnitType *produceUnit = produce->getProducedUnit(); - - if( produceUnit != NULL && - unitType.getId() != unitType2.getId() && - unitType.getName() == produceUnit->getName()) { - foundUnit = true; - break; - } - } - } - // Check if this is a build command - if(cmdType->getClass() == ccBuild) { - const BuildCommandType *build = dynamic_cast(cmdType); - if(build == NULL) { - throw megaglest_runtime_error("build == NULL"); - } - for(int k = 0; k < build->getBuildingCount() && foundUnit == false; ++k) { - const UnitType *buildUnit = build->getBuilding(k); - - if( buildUnit != NULL && - unitType.getId() != unitType2.getId() && - unitType.getName() == buildUnit->getName()) { - foundUnit = true; - break; - } - } - if(foundUnit == true) { - break; - } - } - // Check if this is a morph command - if(cmdType->getClass() == ccMorph) { - const MorphCommandType *morph = dynamic_cast(cmdType); - if(morph == NULL) { - throw megaglest_runtime_error("morph == NULL"); - } - const UnitType *morphUnit = morph->getMorphUnit(); - - if( morphUnit != NULL && - unitType.getId() != unitType2.getId() && - unitType.getName() == morphUnit->getName()) { - foundUnit = true; - break; - } - } - - // Check if this is an attack command with spawned units on attack - if(cmdType->getClass() == ccAttack) { - const AttackCommandType *act= dynamic_cast(cmdType); - if( act != NULL && act->getAttackSkillType() != NULL && - act->getAttackSkillType()->getSpawnUnit() != "" && act->getAttackSkillType()->getSpawnUnitCount() > 0) { - - if( unitType.getId() != unitType2.getId() && - unitType.getName() == act->getAttackSkillType()->getSpawnUnit()) { - foundUnit = true; - break; - } - } - } - } - } - } - - if(foundUnit == false) { - //printf("Problem for unit [%s] unitTypes.size() = " MG_SIZE_T_SPECIFIER "\n",unitType.getName().c_str(),unitTypes.size()); - - char szBuf[8096]=""; - snprintf(szBuf,8096,"The Unit [%s] in Faction [%s] has no other units that can produce, build or morph into it in this faction!",unitType.getName().c_str(),this->getName().c_str()); - results.push_back(szBuf); - } - - // Ensure that all attack skill types have valid values - if(unitType.hasSkillClass(scAttack) == true) { - for(int j = 0; j < unitType.getSkillTypeCount(); ++j) { - const SkillType *st = unitType.getSkillType(j); - if(st != NULL && dynamic_cast(st) != NULL) { - const AttackSkillType *ast = dynamic_cast(st); - if(ast != NULL && ast->getAttackVar() < 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"The Unit [%s] in Faction [%s] has the skill [%s] with an INVALID attack var value which is < 0 [%d]!",unitType.getName().c_str(),this->getName().c_str(),ast->getName().c_str(),ast->getAttackVar()); - results.push_back(szBuf); + std::vector results; + + const uint32 MAX_BITRATE_WARNING = 200000; + StrSound *factionMusic = getMusic(); + if (factionMusic != NULL && + factionMusic->getInfo()->getBitRate() > MAX_BITRATE_WARNING) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "The Faction [%s] has the music [%s]\nwhich has a bitrate of [%u] " + "which may cause some sound drivers to crash, please use a " + "bitrate of %d or less!", + this->getName().c_str(), factionMusic->getFileName().c_str(), + factionMusic->getInfo()->getBitRate(), MAX_BITRATE_WARNING); + results.push_back(szBuf); + } + + for (int i = 0; i < (int)unitTypes.size(); ++i) { + UnitType &unitType = unitTypes[i]; + + for (int i = 0; i < (int)unitType.getSelectionSounds().getSounds().size(); + ++i) { + StaticSound *sound = unitType.getSelectionSounds().getSounds()[i]; + if (sound != NULL && + sound->getInfo()->getBitRate() > MAX_BITRATE_WARNING) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "The Unit [%s] in Faction [%s] has the sound [%s]\nwhich has " + "a bitrate of [%u] which may cause some sound drivers to " + "crash, please use a bitrate of %d or less!", + unitType.getName().c_str(), this->getName().c_str(), + sound->getFileName().c_str(), sound->getInfo()->getBitRate(), + MAX_BITRATE_WARNING); + results.push_back(szBuf); + } + } + for (int i = 0; i < (int)unitType.getCommandSounds().getSounds().size(); + ++i) { + StaticSound *sound = unitType.getCommandSounds().getSounds()[i]; + if (sound != NULL && + sound->getInfo()->getBitRate() > MAX_BITRATE_WARNING) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "The Unit [%s] in Faction [%s] has the sound [%s]\nwhich has " + "a bitrate of [%u] which may cause some sound drivers to " + "crash, please use a bitrate of %d or less!", + unitType.getName().c_str(), this->getName().c_str(), + sound->getFileName().c_str(), sound->getInfo()->getBitRate(), + MAX_BITRATE_WARNING); + results.push_back(szBuf); + } + } + + int morphCommandCount = 0; + for (int j = 0; j < (int)unitType.getCommandTypeCount(); ++j) { + const CommandType *cmdType = unitType.getCommandType(j); + if (cmdType != NULL) { + // Check every unit's commands to validate that for every + // upgrade-requirements upgrade we have a unit that can do the upgrade + // in the faction. + for (int k = 0; k < cmdType->getUpgradeReqCount(); ++k) { + const UpgradeType *upgradeType = cmdType->getUpgradeReq(k); + + if (upgradeType != NULL) { + // Now lets find a unit that can produced-upgrade this upgrade + bool foundUpgraderUnit = false; + for (int l = 0; + l < (int)unitTypes.size() && foundUpgraderUnit == false; ++l) { + UnitType &unitType2 = unitTypes[l]; + for (int m = 0; m < unitType2.getCommandTypeCount() && + foundUpgraderUnit == false; + ++m) { + const CommandType *cmdType2 = unitType2.getCommandType(m); + if (cmdType2 != NULL && + dynamic_cast(cmdType2) != + NULL) { + const UpgradeCommandType *uct = + dynamic_cast(cmdType2); + if (uct != NULL) { + const UpgradeType *upgradeType2 = uct->getProducedUpgrade(); + if (upgradeType2 != NULL && + upgradeType2->getName() == upgradeType->getName()) { + foundUpgraderUnit = true; + break; } + } } + } + } + + if (foundUpgraderUnit == false) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "The Unit [%s] in Faction [%s] has the command " + "[%s]\nwhich has upgrade requirement [%s] but there are " + "no units able to perform the upgrade!", + unitType.getName().c_str(), this->getName().c_str(), + cmdType->getName().c_str(), + upgradeType->getName().c_str()); + results.push_back(szBuf); } + } } - // end - - // Check if the unit has both be_built and harvest skills, this may cause issues - // with the AI - if(unitType.hasSkillClass(scBeBuilt) == true && unitType.hasSkillClass(scHarvest) == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"The Unit [%s] in Faction [%s] has both a bebuilt and harvest skill which will cause AI problems for CPU players!",unitType.getName().c_str(),this->getName().c_str()); - results.push_back(szBuf); + + // Ensure for each build type command that the build units + // exist in this faction + if (cmdType->getClass() == ccBuild) { + const BuildCommandType *build = + dynamic_cast(cmdType); + if (build == NULL) { + throw megaglest_runtime_error("build == NULL"); + } + for (int k = 0; k < build->getBuildingCount(); ++k) { + const UnitType *buildUnit = build->getBuilding(k); + + // Now lets find the unit that we should be able to build + bool foundUnit = false; + for (int l = 0; l < (int)unitTypes.size() && foundUnit == false; + ++l) { + UnitType &unitType2 = unitTypes[l]; + if (unitType2.getName() == buildUnit->getName()) { + foundUnit = true; + + // Now also validate the the unit to be built + // has a be_built_skill + if (buildUnit->hasSkillClass(scBeBuilt) == false) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "The Unit [%s] in Faction [%s] has the command " + "[%s]\nwhich can build the Unit [%s] but the Unit " + "to be built\ndoes not have the skill class " + "[be_built_skill] in this faction!", + unitType.getName().c_str(), this->getName().c_str(), + cmdType->getName().c_str(), + buildUnit->getName().c_str()); + results.push_back(szBuf); + } + + break; + } + } + + if (foundUnit == false) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "The Unit [%s] in Faction [%s] has the command " + "[%s]\nwhich can build the Unit [%s] but the Unit to be " + "built does not exist in this faction!", + unitType.getName().c_str(), this->getName().c_str(), + cmdType->getName().c_str(), + buildUnit->getName().c_str()); + results.push_back(szBuf); + } + } } - // end - - // Check if the unit has harvest skills but not move, meaning they cannot - // harvest the resource - if(unitType.hasSkillClass(scHarvest) == true && unitType.hasSkillClass(scMove) == false) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"The Unit [%s] in Faction [%s] has a harvest skill but no move skill so it cannot harvest!",unitType.getName().c_str(),this->getName().c_str()); - results.push_back(szBuf); + // Ensure for each repair type command that the repair units + // exist in this faction + if (cmdType->getClass() == ccRepair) { + const RepairCommandType *repair = + dynamic_cast(cmdType); + if (repair == NULL) { + throw megaglest_runtime_error("repair == NULL"); + } + for (int k = 0; k < repair->getRepairCount(); ++k) { + const UnitType *repairUnit = repair->getRepair(k); + + // Now lets find the unit that we should be able to repair + bool foundUnit = false; + for (int l = 0; l < (int)unitTypes.size() && foundUnit == false; + ++l) { + UnitType &unitType2 = unitTypes[l]; + if (unitType2.getName() == repairUnit->getName()) { + foundUnit = true; + break; + } + } + + if (foundUnit == false) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "The Unit [%s] in Faction [%s] has the command " + "[%s]\nwhich can repair the Unit [%s] but the Unit to " + "be repaired does not exist in this faction!", + unitType.getName().c_str(), this->getName().c_str(), + cmdType->getName().c_str(), + repairUnit->getName().c_str()); + results.push_back(szBuf); + } + } } - // end + // Ensure for each morph type command that the morph units + // exist in this faction + if (cmdType->getClass() == ccMorph) { + const MorphCommandType *morph = + dynamic_cast(cmdType); + if (morph != NULL) { + morphCommandCount++; + const UnitType *morphUnit = morph->getMorphUnit(); + + // Now lets find the unit that we should be able to morph + // to + bool foundUnit = false; + for (int l = 0; l < (int)unitTypes.size() && foundUnit == false; + ++l) { + UnitType &unitType2 = unitTypes[l]; + if (unitType2.getName() == morphUnit->getName()) { + foundUnit = true; + break; + } + } + if (foundUnit == false) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "The Unit [%s] in Faction [%s] has the command " + "[%s]\nwhich can morph into the Unit [%s] but the Unit " + "to be morphed to does not exist in this faction!", + unitType.getName().c_str(), this->getName().c_str(), + cmdType->getName().c_str(), + morphUnit->getName().c_str()); + results.push_back(szBuf); + } + } + } + } } - return results; -} - -std::vector FactionType::validateFactionTypeResourceTypes(vector &resourceTypes) { - std::vector results; - - for(int i=0; i < (int)unitTypes.size(); ++i) { - UnitType &unitType = unitTypes[i]; - - // Check every unit's required resources to validate that for every resource-requirements - // we have a resource in the faction. - for(int j = 0; j < unitType.getCostCount() ; ++j) { - const Resource *r = unitType.getCost(j); - if(r != NULL && r->getType() != NULL) { - bool foundResourceType = false; - // Now lets find a matching faction resource type for the unit - for(int k=0; k < (int)resourceTypes.size(); ++k){ - ResourceType &rt = resourceTypes[k]; - - if(r->getType()->getName() == rt.getName()) { - foundResourceType = true; - break; - } - } - - if(foundResourceType == false) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"The Unit [%s] in Faction [%s] has the resource req [%s]\nbut there are no such resources in this tech!",unitType.getName().c_str(),this->getName().c_str(),r->getType()->getName().c_str()); - results.push_back(szBuf); - } - } - } - - // Check every unit's stored resources to validate that for every resources-stored - // we have a resource in the faction. - for(int j = 0; j < unitType.getStoredResourceCount() ; ++j) { - const Resource *r = unitType.getStoredResource(j); - if(r != NULL && r->getType() != NULL) { - bool foundResourceType = false; - // Now lets find a matching faction resource type for the unit - for(int k=0; k < (int)resourceTypes.size(); ++k){ - ResourceType &rt = resourceTypes[k]; - - if(r->getType()->getName() == rt.getName()) { - foundResourceType = true; - break; - } - } - - if(foundResourceType == false) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"The Unit [%s] in Faction [%s] has the stored resource [%s]\nbut there are no such resources in this tech!",unitType.getName().c_str(),this->getName().c_str(),r->getType()->getName().c_str()); - results.push_back(szBuf); - } - } - } - - for(int j = 0; j < unitType.getCommandTypeCount(); ++j) { - const CommandType *cmdType = unitType.getCommandType(j); - if(cmdType != NULL) { - // Ensure for each harvest type command that the resource - // exist in this faction - if(cmdType->getClass() == ccHarvest) { - const HarvestCommandType *harvest = dynamic_cast(cmdType); - if(harvest == NULL) { - throw megaglest_runtime_error("harvest == NULL"); - } - for(int k = 0; k < harvest->getHarvestedResourceCount(); ++k) { - const ResourceType *harvestResource = harvest->getHarvestedResource(k); - - bool foundResourceType = false; - // Now lets find a matching faction resource type for the unit - for(int k=0; k < (int)resourceTypes.size(); ++k){ - ResourceType &rt = resourceTypes[k]; - - if(harvestResource->getName() == rt.getName()) { - foundResourceType = true; - break; - } - } - - if(foundResourceType == false) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"The Unit [%s] in Faction [%s] has the command [%s] which can harvest the resource [%s]\nbut there are no such resources in this tech!",unitType.getName().c_str(),this->getName().c_str(),cmdType->getName().c_str(),harvestResource->getName().c_str()); - results.push_back(szBuf); - } - } - } - } - } + const int maxMorphsAllowed = 6; + if (morphCommandCount > maxMorphsAllowed) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "The Unit [%s] in Faction [%s] has more than %d morph commands " + "which is too many to display in the UI!", + unitType.getName().c_str(), this->getName().c_str(), + maxMorphsAllowed); + results.push_back(szBuf); } - return results; -} + // Check every unit's unit requirements to validate that for every + // unit-requirements we have the units required in the faction. + for (int j = 0; j < unitType.getUnitReqCount(); ++j) { + const UnitType *unitType2 = unitType.getUnitReq(j); + if (unitType2 != NULL) { + // Now lets find the required unit + bool foundUnit = false; + for (int l = 0; l < (int)unitTypes.size() && foundUnit == false; ++l) { + UnitType &unitType3 = unitTypes[l]; + + if (unitType2->getName() == unitType3.getName()) { + foundUnit = true; + break; + } + } -std::vector FactionType::validateFactionTypeUpgradeTypes() { - std::vector results; - - // For each upgrade type make sure there is at least 1 unit that can produce - // the upgrade - for(int i = 0; i < (int)upgradeTypes.size(); ++i) { - const UpgradeType &upgradeType = upgradeTypes[i]; - - // First find a unit with a command type to upgrade to this Upgrade type - bool foundUnit = false; - for(int j=0; j < (int)unitTypes.size() && foundUnit == false; ++j){ - UnitType &unitType = unitTypes[j]; - for(int k = 0; k < unitType.getCommandTypeCount() && foundUnit == false; ++k) { - const CommandType *cmdType = unitType.getCommandType(k); - if(cmdType != NULL) { - // Ensure for each build type command that the build units - // exist in this faction - if(cmdType->getClass() == ccUpgrade) { - const UpgradeCommandType *upgrade = dynamic_cast(cmdType); - if(upgrade != NULL) { - const UpgradeType *upgradeType2 = upgrade->getProducedUpgrade(); - - if(upgradeType2 != NULL && upgradeType.getName() == upgradeType2->getName()) { - foundUnit = true; - break; - } - } - } - } - } - } - - if(foundUnit == false) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"The Upgrade Type [%s] in Faction [%s] has no Unit able to produce this upgrade in this faction!",upgradeType.getName().c_str(),this->getName().c_str()); - results.push_back(szBuf); - } - } - - return results; -} + if (foundUnit == false) { + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "The Unit [%s] in Faction [%s] has the required Unit [%s]\nbut " + "the required unit does not exist in this faction!", + unitType.getName().c_str(), this->getName().c_str(), + unitType2->getName().c_str()); + results.push_back(szBuf); + } + } + } -// ==================== get ==================== + // Now check that at least 1 other unit can produce, build or morph this + // unit + bool foundUnit = false; + for (int l = 0; l < (int)unitTypes.size() && foundUnit == false; ++l) { + UnitType &unitType2 = unitTypes[l]; + + for (int j = 0; j < unitType2.getCommandTypeCount() && foundUnit == false; + ++j) { + const CommandType *cmdType = unitType2.getCommandType(j); + if (cmdType != NULL) { + // Check if this is a produce command + if (cmdType->getClass() == ccProduce) { + const ProduceCommandType *produce = + dynamic_cast(cmdType); + if (produce != NULL) { + const UnitType *produceUnit = produce->getProducedUnit(); + + if (produceUnit != NULL && + unitType.getId() != unitType2.getId() && + unitType.getName() == produceUnit->getName()) { + foundUnit = true; + break; + } + } + } + // Check if this is a build command + if (cmdType->getClass() == ccBuild) { + const BuildCommandType *build = + dynamic_cast(cmdType); + if (build == NULL) { + throw megaglest_runtime_error("build == NULL"); + } + for (int k = 0; k < build->getBuildingCount() && foundUnit == false; + ++k) { + const UnitType *buildUnit = build->getBuilding(k); + + if (buildUnit != NULL && unitType.getId() != unitType2.getId() && + unitType.getName() == buildUnit->getName()) { + foundUnit = true; + break; + } + } + if (foundUnit == true) { + break; + } + } + // Check if this is a morph command + if (cmdType->getClass() == ccMorph) { + const MorphCommandType *morph = + dynamic_cast(cmdType); + if (morph == NULL) { + throw megaglest_runtime_error("morph == NULL"); + } + const UnitType *morphUnit = morph->getMorphUnit(); -const UnitType *FactionType::getUnitType(const string &name) const{ - for(int i=0; i < (int)unitTypes.size();i++){ - if(unitTypes[i].getName(false)==name){ - return &unitTypes[i]; - } + if (morphUnit != NULL && unitType.getId() != unitType2.getId() && + unitType.getName() == morphUnit->getName()) { + foundUnit = true; + break; + } + } + + // Check if this is an attack command with spawned units on attack + if (cmdType->getClass() == ccAttack) { + const AttackCommandType *act = + dynamic_cast(cmdType); + if (act != NULL && act->getAttackSkillType() != NULL && + act->getAttackSkillType()->getSpawnUnit() != "" && + act->getAttackSkillType()->getSpawnUnitCount() > 0) { + + if (unitType.getId() != unitType2.getId() && + unitType.getName() == + act->getAttackSkillType()->getSpawnUnit()) { + foundUnit = true; + break; + } + } + } + } + } } - printf("In [%s::%s Line: %d] scanning [%s] size = " MG_SIZE_T_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,name.c_str(),unitTypes.size()); - for(int i=0; i < (int)unitTypes.size();i++){ - printf("In [%s::%s Line: %d] scanning [%s] idx = %d [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,name.c_str(),i,unitTypes[i].getName(false).c_str()); + if (foundUnit == false) { + // printf("Problem for unit [%s] unitTypes.size() = " MG_SIZE_T_SPECIFIER + // "\n",unitType.getName().c_str(),unitTypes.size()); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "The Unit [%s] in Faction [%s] has no other units that can " + "produce, build or morph into it in this faction!", + unitType.getName().c_str(), this->getName().c_str()); + results.push_back(szBuf); } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] scanning [%s] size = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,name.c_str(),unitTypes.size()); - for(int i=0; i < (int)unitTypes.size();i++){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] scanning [%s] idx = %d [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,name.c_str(),i,unitTypes[i].getName(false).c_str()); + // Ensure that all attack skill types have valid values + if (unitType.hasSkillClass(scAttack) == true) { + for (int j = 0; j < unitType.getSkillTypeCount(); ++j) { + const SkillType *st = unitType.getSkillType(j); + if (st != NULL && dynamic_cast(st) != NULL) { + const AttackSkillType *ast = + dynamic_cast(st); + if (ast != NULL && ast->getAttackVar() < 0) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "The Unit [%s] in Faction [%s] has the skill [%s] with an " + "INVALID attack var value which is < 0 [%d]!", + unitType.getName().c_str(), this->getName().c_str(), + ast->getName().c_str(), ast->getAttackVar()); + results.push_back(szBuf); + } + } + } + } + // end + + // Check if the unit has both be_built and harvest skills, this may cause + // issues with the AI + if (unitType.hasSkillClass(scBeBuilt) == true && + unitType.hasSkillClass(scHarvest) == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "The Unit [%s] in Faction [%s] has both a bebuilt and harvest " + "skill which will cause AI problems for CPU players!", + unitType.getName().c_str(), this->getName().c_str()); + results.push_back(szBuf); } + // end + + // Check if the unit has harvest skills but not move, meaning they cannot + // harvest the resource + if (unitType.hasSkillClass(scHarvest) == true && + unitType.hasSkillClass(scMove) == false) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "The Unit [%s] in Faction [%s] has a harvest skill but no move " + "skill so it cannot harvest!", + unitType.getName().c_str(), this->getName().c_str()); + results.push_back(szBuf); + } + // end + } - throw megaglest_runtime_error("Unit type not found: [" + name + "] in faction type [" + this->name + "]",true); + return results; } -//const UnitType *FactionType::getUnitTypeById(int id) const{ -// for(int i=0; i < (int)unitTypes.size();i++){ -// if(unitTypes[i].getId() == id) { -// return &unitTypes[i]; -// } -// } -// -// printf("In [%s::%s Line: %d] scanning [%d] size = " MG_SIZE_T_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,id,unitTypes.size()); -// for(int i=0; i < (int)unitTypes.size();i++){ -// printf("In [%s::%s Line: %d] scanning [%s] idx = %d [%s][%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,name.c_str(),i,unitTypes[i].getName(false).c_str(),unitTypes[i].getId()); -// } -// -// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] scanning [%s] size = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,name.c_str(),unitTypes.size()); -// for(int i=0; i < (int)unitTypes.size();i++){ -// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] scanning [%s] idx = %d [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,name.c_str(),i,unitTypes[i].getName(false).c_str()); -// } -// -// throw megaglest_runtime_error("Unit type not found: [" + intToStr(id) + "] in faction type [" + this->name + "]",true); -//} - -const UpgradeType *FactionType::getUpgradeType(const string &name) const{ - for(int i=0; i < (int)upgradeTypes.size();i++){ - if(upgradeTypes[i].getName()==name){ - return &upgradeTypes[i]; - } +std::vector FactionType::validateFactionTypeResourceTypes( + vector &resourceTypes) { + std::vector results; + + for (int i = 0; i < (int)unitTypes.size(); ++i) { + UnitType &unitType = unitTypes[i]; + + // Check every unit's required resources to validate that for every + // resource-requirements we have a resource in the faction. + for (int j = 0; j < unitType.getCostCount(); ++j) { + const Resource *r = unitType.getCost(j); + if (r != NULL && r->getType() != NULL) { + bool foundResourceType = false; + // Now lets find a matching faction resource type for the unit + for (int k = 0; k < (int)resourceTypes.size(); ++k) { + ResourceType &rt = resourceTypes[k]; + + if (r->getType()->getName() == rt.getName()) { + foundResourceType = true; + break; + } + } + + if (foundResourceType == false) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "The Unit [%s] in Faction [%s] has the resource req " + "[%s]\nbut there are no such resources in this tech!", + unitType.getName().c_str(), this->getName().c_str(), + r->getType()->getName().c_str()); + results.push_back(szBuf); + } + } } - printf("In [%s::%s Line: %d] scanning [%s] size = " MG_SIZE_T_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,name.c_str(),unitTypes.size()); - for(int i=0; i < (int)upgradeTypes.size();i++){ - printf("In [%s::%s Line: %d] scanning [%s] idx = %d [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,name.c_str(),i,upgradeTypes[i].getName().c_str()); + // Check every unit's stored resources to validate that for every + // resources-stored we have a resource in the faction. + for (int j = 0; j < unitType.getStoredResourceCount(); ++j) { + const Resource *r = unitType.getStoredResource(j); + if (r != NULL && r->getType() != NULL) { + bool foundResourceType = false; + // Now lets find a matching faction resource type for the unit + for (int k = 0; k < (int)resourceTypes.size(); ++k) { + ResourceType &rt = resourceTypes[k]; + + if (r->getType()->getName() == rt.getName()) { + foundResourceType = true; + break; + } + } + + if (foundResourceType == false) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "The Unit [%s] in Faction [%s] has the stored resource " + "[%s]\nbut there are no such resources in this tech!", + unitType.getName().c_str(), this->getName().c_str(), + r->getType()->getName().c_str()); + results.push_back(szBuf); + } + } } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] scanning [%s] size = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,name.c_str(),unitTypes.size()); - for(int i=0; i < (int)upgradeTypes.size();i++){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] scanning [%s] idx = %d [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,name.c_str(),i,upgradeTypes[i].getName().c_str()); + for (int j = 0; j < unitType.getCommandTypeCount(); ++j) { + const CommandType *cmdType = unitType.getCommandType(j); + if (cmdType != NULL) { + // Ensure for each harvest type command that the resource + // exist in this faction + if (cmdType->getClass() == ccHarvest) { + const HarvestCommandType *harvest = + dynamic_cast(cmdType); + if (harvest == NULL) { + throw megaglest_runtime_error("harvest == NULL"); + } + for (int k = 0; k < harvest->getHarvestedResourceCount(); ++k) { + const ResourceType *harvestResource = + harvest->getHarvestedResource(k); + + bool foundResourceType = false; + // Now lets find a matching faction resource type for the unit + for (int k = 0; k < (int)resourceTypes.size(); ++k) { + ResourceType &rt = resourceTypes[k]; + + if (harvestResource->getName() == rt.getName()) { + foundResourceType = true; + break; + } + } + + if (foundResourceType == false) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "The Unit [%s] in Faction [%s] has the command [%s] " + "which can harvest the resource [%s]\nbut there are no " + "such resources in this tech!", + unitType.getName().c_str(), this->getName().c_str(), + cmdType->getName().c_str(), + harvestResource->getName().c_str()); + results.push_back(szBuf); + } + } + } + } } + } - throw megaglest_runtime_error("Upgrade type not found: [" + name + "] in faction type [" + this->name + "]",true); + return results; } -int FactionType::getStartingResourceAmount(const ResourceType *resourceType) const{ - for(int i=0; i < (int)startingResources.size(); ++i){ - if(startingResources[i].getType()==resourceType){ - return startingResources[i].getAmount(); - } - } - return 0; +std::vector FactionType::validateFactionTypeUpgradeTypes() { + std::vector results; + + // For each upgrade type make sure there is at least 1 unit that can produce + // the upgrade + for (int i = 0; i < (int)upgradeTypes.size(); ++i) { + const UpgradeType &upgradeType = upgradeTypes[i]; + + // First find a unit with a command type to upgrade to this Upgrade type + bool foundUnit = false; + for (int j = 0; j < (int)unitTypes.size() && foundUnit == false; ++j) { + UnitType &unitType = unitTypes[j]; + for (int k = 0; k < unitType.getCommandTypeCount() && foundUnit == false; + ++k) { + const CommandType *cmdType = unitType.getCommandType(k); + if (cmdType != NULL) { + // Ensure for each build type command that the build units + // exist in this faction + if (cmdType->getClass() == ccUpgrade) { + const UpgradeCommandType *upgrade = + dynamic_cast(cmdType); + if (upgrade != NULL) { + const UpgradeType *upgradeType2 = upgrade->getProducedUpgrade(); + + if (upgradeType2 != NULL && + upgradeType.getName() == upgradeType2->getName()) { + foundUnit = true; + break; + } + } + } + } + } + } + + if (foundUnit == false) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "The Upgrade Type [%s] in Faction [%s] has no Unit able to " + "produce this upgrade in this faction!", + upgradeType.getName().c_str(), this->getName().c_str()); + results.push_back(szBuf); + } + } + + return results; } -void FactionType::deletePixels() { - for(int i = 0; i < (int)unitTypes.size(); ++i) { - UnitType &unitType = unitTypes[i]; - Texture2D *texture = unitType.getMeetingPointImage(); - if(texture != NULL) { - texture->deletePixels(); - } - } +// ==================== get ==================== + +const UnitType *FactionType::getUnitType(const string &name) const { + for (int i = 0; i < (int)unitTypes.size(); i++) { + if (unitTypes[i].getName(false) == name) { + return &unitTypes[i]; + } + } + + printf("In [%s::%s Line: %d] scanning [%s] size = " MG_SIZE_T_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + name.c_str(), unitTypes.size()); + for (int i = 0; i < (int)unitTypes.size(); i++) { + printf("In [%s::%s Line: %d] scanning [%s] idx = %d [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, name.c_str(), i, unitTypes[i].getName(false).c_str()); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] scanning [%s] size = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, name.c_str(), + unitTypes.size()); + for (int i = 0; i < (int)unitTypes.size(); i++) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] scanning [%s] idx = %d [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, name.c_str(), i, unitTypes[i].getName(false).c_str()); + } + + throw megaglest_runtime_error("Unit type not found: [" + name + + "] in faction type [" + this->name + "]", + true); } -bool FactionType::factionUsesResourceType(const ResourceType *rt) const { - bool factionUsesResourceType = false; - if(rt != NULL) { - for(unsigned int j = 0; factionUsesResourceType == false && j < (unsigned int)this->getUnitTypeCount(); ++j) { - const UnitType *ut= this->getUnitType(j); - for(int k = 0; factionUsesResourceType == false && k < ut->getCostCount(); ++k) { - const Resource *costResource = ut->getCost(k); - //printf("#1 factionUsesResourceType, unit [%s] resource [%s] cost [%s]\n",ut->getName().c_str(),rt->getName().c_str(),costResource->getType()->getName().c_str()); - - if(costResource != NULL && costResource->getType() != NULL && - costResource->getType()->getName() == rt->getName()) { - factionUsesResourceType = true; - break; - } - } - if(factionUsesResourceType == false) { - for(unsigned int k = 0; factionUsesResourceType == false && k < (unsigned int)ut->getCommandTypeCount(); ++k) { - const CommandType *commandType = ut->getCommandType(k); - if(commandType != NULL && commandType->getClass() == ccHarvest) { - const HarvestCommandType *hct = dynamic_cast(commandType); - if(hct != NULL && hct->getHarvestedResourceCount() > 0) { - for(unsigned int l = 0; factionUsesResourceType == false && l < (unsigned int)hct->getHarvestedResourceCount(); ++l) { - //printf("#2 factionUsesResourceType, unit [%s] resource [%s] harvest [%s]\n",ut->getName().c_str(),rt->getName().c_str(),hct->getHarvestedResource(l)->getName().c_str()); - - if(hct->getHarvestedResource(l)->getName() == rt->getName()) { - factionUsesResourceType = true; - break; - } - } - } - } - } - } - } - } - return factionUsesResourceType; +// const UnitType *FactionType::getUnitTypeById(int id) const{ +// for(int i=0; i < (int)unitTypes.size();i++){ +// if(unitTypes[i].getId() == id) { +// return &unitTypes[i]; +// } +// } +// +// printf("In [%s::%s Line: %d] scanning [%d] size = " MG_SIZE_T_SPECIFIER +// "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,id,unitTypes.size()); +// for(int i=0; i < (int)unitTypes.size();i++){ +// printf("In [%s::%s Line: %d] scanning [%s] idx = %d +// [%s][%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,name.c_str(),i,unitTypes[i].getName(false).c_str(),unitTypes[i].getId()); +// } +// +// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) +// SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] +// scanning [%s] size = +// %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,name.c_str(),unitTypes.size()); +// for(int i=0; i < (int)unitTypes.size();i++){ +// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) +// SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] +// scanning [%s] idx = %d +// [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,name.c_str(),i,unitTypes[i].getName(false).c_str()); +// } +// +// throw megaglest_runtime_error("Unit type not found: [" + intToStr(id) + +//"] in faction type [" + this->name + "]",true); +// } + +const UpgradeType *FactionType::getUpgradeType(const string &name) const { + for (int i = 0; i < (int)upgradeTypes.size(); i++) { + if (upgradeTypes[i].getName() == name) { + return &upgradeTypes[i]; + } + } + + printf("In [%s::%s Line: %d] scanning [%s] size = " MG_SIZE_T_SPECIFIER "\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, + name.c_str(), unitTypes.size()); + for (int i = 0; i < (int)upgradeTypes.size(); i++) { + printf("In [%s::%s Line: %d] scanning [%s] idx = %d [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, name.c_str(), i, upgradeTypes[i].getName().c_str()); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] scanning [%s] size = %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, name.c_str(), + unitTypes.size()); + for (int i = 0; i < (int)upgradeTypes.size(); i++) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug( + SystemFlags::debugSystem, + "In [%s::%s Line: %d] scanning [%s] idx = %d [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, name.c_str(), i, upgradeTypes[i].getName().c_str()); + } + + throw megaglest_runtime_error("Upgrade type not found: [" + name + + "] in faction type [" + this->name + "]", + true); } -std::string FactionType::toString() const { - std::string result = "Faction Name: " + name + "\n"; +int FactionType::getStartingResourceAmount( + const ResourceType *resourceType) const { + for (int i = 0; i < (int)startingResources.size(); ++i) { + if (startingResources[i].getType() == resourceType) { + return startingResources[i].getAmount(); + } + } + return 0; +} - result += "Unit Type List count = " + intToStr(this->getUnitTypeCount()) + "\n"; - for(int i=0; i < (int)unitTypes.size();i++) { - result += unitTypes[i].toString() + "\n"; +void FactionType::deletePixels() { + for (int i = 0; i < (int)unitTypes.size(); ++i) { + UnitType &unitType = unitTypes[i]; + Texture2D *texture = unitType.getMeetingPointImage(); + if (texture != NULL) { + texture->deletePixels(); } + } +} - result += "Upgrade Type List count = " + intToStr(this->getUpgradeTypeCount()) + "\n"; - for(int i=0; i < (int)upgradeTypes.size();i++) { - result += "index: " + intToStr(i) + " " + upgradeTypes[i].getReqDesc(false) + "\n"; +bool FactionType::factionUsesResourceType(const ResourceType *rt) const { + bool factionUsesResourceType = false; + if (rt != NULL) { + for (unsigned int j = 0; factionUsesResourceType == false && + j < (unsigned int)this->getUnitTypeCount(); + ++j) { + const UnitType *ut = this->getUnitType(j); + for (int k = 0; + factionUsesResourceType == false && k < ut->getCostCount(); ++k) { + const Resource *costResource = ut->getCost(k); + // printf("#1 factionUsesResourceType, unit [%s] resource [%s] cost + // [%s]\n",ut->getName().c_str(),rt->getName().c_str(),costResource->getType()->getName().c_str()); + + if (costResource != NULL && costResource->getType() != NULL && + costResource->getType()->getName() == rt->getName()) { + factionUsesResourceType = true; + break; + } + } + if (factionUsesResourceType == false) { + for (unsigned int k = 0; factionUsesResourceType == false && + k < (unsigned int)ut->getCommandTypeCount(); + ++k) { + const CommandType *commandType = ut->getCommandType(k); + if (commandType != NULL && commandType->getClass() == ccHarvest) { + const HarvestCommandType *hct = + dynamic_cast(commandType); + if (hct != NULL && hct->getHarvestedResourceCount() > 0) { + for (unsigned int l = 0; + factionUsesResourceType == false && + l < (unsigned int)hct->getHarvestedResourceCount(); + ++l) { + // printf("#2 factionUsesResourceType, unit [%s] resource [%s] + // harvest + // [%s]\n",ut->getName().c_str(),rt->getName().c_str(),hct->getHarvestedResource(l)->getName().c_str()); + + if (hct->getHarvestedResource(l)->getName() == rt->getName()) { + factionUsesResourceType = true; + break; + } + } + } + } + } + } } + } + return factionUsesResourceType; +} - return result; +std::string FactionType::toString() const { + std::string result = "Faction Name: " + name + "\n"; + + result += + "Unit Type List count = " + intToStr(this->getUnitTypeCount()) + "\n"; + for (int i = 0; i < (int)unitTypes.size(); i++) { + result += unitTypes[i].toString() + "\n"; + } + + result += + "Upgrade Type List count = " + intToStr(this->getUpgradeTypeCount()) + + "\n"; + for (int i = 0; i < (int)upgradeTypes.size(); i++) { + result += "index: " + intToStr(i) + " " + + upgradeTypes[i].getReqDesc(false) + "\n"; + } + + return result; } string FactionType::getName(bool translatedValue) const { - if(translatedValue == false) return name; + if (translatedValue == false) + return name; - Lang &lang = Lang::getInstance(); - return lang.getTechTreeString("FactionName_" + name,name.c_str()); + Lang &lang = Lang::getInstance(); + return lang.getTechTreeString("FactionName_" + name, name.c_str()); } - -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/types/faction_type.h b/source/glest_game/types/faction_type.h index 8cf3863cc..4666e1de3 100644 --- a/source/glest_game/types/faction_type.h +++ b/source/glest_game/types/faction_type.h @@ -13,21 +13,22 @@ #define _GLEST_GAME_FACTIONTYPE_H_ #ifdef WIN32 - #include - #include +#include +#include #endif +#include "leak_dumper.h" +#include "sound.h" #include "unit_type.h" #include "upgrade_type.h" -#include "sound.h" +#include "util.h" #include #include -#include "util.h" -#include "leak_dumper.h" using Shared::Sound::StrSound; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class FactionType // @@ -35,130 +36,145 @@ namespace Glest{ namespace Game{ // ===================================================== enum AIBehaviorUnitCategory { - aibcWorkerUnits, - aibcWarriorUnits, - aibcResourceProducerUnits, - aibcBuildingUnits + aibcWorkerUnits, + aibcWarriorUnits, + aibcResourceProducerUnits, + aibcBuildingUnits }; enum AIBehaviorStaticValueCategory { - aibsvcMaxBuildRadius, - aibsvcMinMinWarriors, - aibsvcMinMinWarriorsExpandCpuEasy, - aibsvcMinMinWarriorsExpandCpuMega, - aibsvcMinMinWarriorsExpandCpuUltra, - aibsvcMinMinWarriorsExpandCpuNormal, - aibsvcMaxMinWarriors, - aibsvcMaxExpansions, - aibsvcVillageRadius, - aibsvcMinStaticResourceCount, - aibsvcScoutResourceRange, - aibsvcMinWorkerAttackersHarvesting, - aibsvcMinBuildSpacing + aibsvcMaxBuildRadius, + aibsvcMinMinWarriors, + aibsvcMinMinWarriorsExpandCpuEasy, + aibsvcMinMinWarriorsExpandCpuMega, + aibsvcMinMinWarriorsExpandCpuUltra, + aibsvcMinMinWarriorsExpandCpuNormal, + aibsvcMaxMinWarriors, + aibsvcMaxExpansions, + aibsvcVillageRadius, + aibsvcMinStaticResourceCount, + aibsvcScoutResourceRange, + aibsvcMinWorkerAttackersHarvesting, + aibsvcMinBuildSpacing }; -template <> -inline EnumParser::EnumParser() { - enumMap["MaxBuildRadius"] = aibsvcMaxBuildRadius; - enumMap["MinMinWarriors"] = aibsvcMinMinWarriors; - enumMap["MinMinWarriorsExpandCpuEasy"] = aibsvcMinMinWarriorsExpandCpuEasy; - enumMap["MinMinWarriorsExpandCpuMega"] = aibsvcMinMinWarriorsExpandCpuMega; - enumMap["MinMinWarriorsExpandCpuUltra"] = aibsvcMinMinWarriorsExpandCpuUltra; - enumMap["MinMinWarriorsExpandCpuNormal"]= aibsvcMinMinWarriorsExpandCpuNormal; - enumMap["MaxMinWarriors"] = aibsvcMaxMinWarriors; - enumMap["MaxExpansions"] = aibsvcMaxExpansions; - enumMap["VillageRadius"] = aibsvcVillageRadius; - enumMap["MinStaticResourceCount"] = aibsvcMinStaticResourceCount; - enumMap["ScoutResourceRange"] = aibsvcScoutResourceRange; - enumMap["MinWorkerAttackersHarvesting"] = aibsvcMinWorkerAttackersHarvesting; - enumMap["MinBuildSpacing"] = aibsvcMinBuildSpacing; +template <> inline EnumParser::EnumParser() { + enumMap["MaxBuildRadius"] = aibsvcMaxBuildRadius; + enumMap["MinMinWarriors"] = aibsvcMinMinWarriors; + enumMap["MinMinWarriorsExpandCpuEasy"] = aibsvcMinMinWarriorsExpandCpuEasy; + enumMap["MinMinWarriorsExpandCpuMega"] = aibsvcMinMinWarriorsExpandCpuMega; + enumMap["MinMinWarriorsExpandCpuUltra"] = aibsvcMinMinWarriorsExpandCpuUltra; + enumMap["MinMinWarriorsExpandCpuNormal"] = + aibsvcMinMinWarriorsExpandCpuNormal; + enumMap["MaxMinWarriors"] = aibsvcMaxMinWarriors; + enumMap["MaxExpansions"] = aibsvcMaxExpansions; + enumMap["VillageRadius"] = aibsvcVillageRadius; + enumMap["MinStaticResourceCount"] = aibsvcMinStaticResourceCount; + enumMap["ScoutResourceRange"] = aibsvcScoutResourceRange; + enumMap["MinWorkerAttackersHarvesting"] = aibsvcMinWorkerAttackersHarvesting; + enumMap["MinBuildSpacing"] = aibsvcMinBuildSpacing; } class FactionType { public: - typedef pair PairPUnitTypeInt; - typedef vector UnitTypes; - typedef vector UpgradeTypes; - typedef vector StartingUnits; - typedef vector Resources; + typedef pair PairPUnitTypeInt; + typedef vector UnitTypes; + typedef vector UpgradeTypes; + typedef vector StartingUnits; + typedef vector Resources; private: - string name; - UnitTypes unitTypes; - UpgradeTypes upgradeTypes; - StartingUnits startingUnits; - Resources startingResources; - StrSound *music; - FactionPersonalityType personalityType; - - std::map > mapAIBehaviorUnitCategories; - std::vector vctAIBehaviorUpgrades; - std::map mapAIBehaviorStaticOverrideValues; - - bool isLinked; - - float healthbarheight; - float healthbarthickness; - int healthbarVisible; - bool healthbarBorderTextureEnabled; - bool healthbarBackgroundTextureEnabled; - bool healthbarLineBorder; - Texture2D *healthbarTexture; - Texture2D *healthbarBackgroundTexture; - bool flatParticlePositions; + string name; + UnitTypes unitTypes; + UpgradeTypes upgradeTypes; + StartingUnits startingUnits; + Resources startingResources; + StrSound *music; + FactionPersonalityType personalityType; + + std::map> + mapAIBehaviorUnitCategories; + std::vector vctAIBehaviorUpgrades; + std::map + mapAIBehaviorStaticOverrideValues; + + bool isLinked; + + float healthbarheight; + float healthbarthickness; + int healthbarVisible; + bool healthbarBorderTextureEnabled; + bool healthbarBackgroundTextureEnabled; + bool healthbarLineBorder; + Texture2D *healthbarTexture; + Texture2D *healthbarBackgroundTexture; + bool flatParticlePositions; public: - //init - FactionType(); - void load(const string &factionName, const TechTree *techTree, Checksum* checksum, - Checksum *techtreeChecksum, - std::map > > &loadedFileList, - bool validationMode=false); - virtual ~FactionType(); - - const std::vector getAIBehaviorUnits(AIBehaviorUnitCategory category) const; - const std::vector getAIBehaviorUpgrades() const { return vctAIBehaviorUpgrades; }; - int getAIBehaviorStaticOverideValue(AIBehaviorStaticValueCategory type) const; - - //get - bool getIsLinked() const { return isLinked; } - int getUnitTypeCount() const {return (int)unitTypes.size();} - int getUpgradeTypeCount() const {return (int)upgradeTypes.size();} - virtual string getName(bool translatedValue=false) const; - const UnitType *getUnitType(int i) const {return &unitTypes[i];} - const UpgradeType *getUpgradeType(int i) const {return &upgradeTypes[i];} - StrSound *getMusic() const {return music;} - int getStartingUnitCount() const {return (int)startingUnits.size();} - const UnitType *getStartingUnit(int i) const {return startingUnits[i].first;} - int getStartingUnitAmount(int i) const {return startingUnits[i].second;} - inline float getHealthbarHeight() const {return healthbarheight;} - inline float getHealthbarThickness() const {return healthbarthickness;} - inline int getHealthbarVisible() const {return healthbarVisible;} - inline bool isHealthbarBorderTextureEnabled() const {return healthbarBorderTextureEnabled;} - inline bool isHealthbarBackgroundTextureEnabled() const {return healthbarBackgroundTextureEnabled;} - inline bool isHealthbarLineBorder() const {return healthbarLineBorder;} - Texture2D *getHealthbarTexture() const {return healthbarTexture;} - Texture2D *getHealthbarBackgroundTexture() const {return healthbarBackgroundTexture;} - bool isFlatParticlePositions() const {return flatParticlePositions;} - - - const UnitType *getUnitType(const string &name) const; - //const UnitType *getUnitTypeById(int id) const; - const UpgradeType *getUpgradeType(const string &name) const; - int getStartingResourceAmount(const ResourceType *resourceType) const; - - FactionPersonalityType getPersonalityType() const { return personalityType;} - void setPersonalityType(FactionPersonalityType value) { personalityType = value;} - - std::string toString() const; - std::vector validateFactionType(); - std::vector validateFactionTypeResourceTypes(vector &resourceTypes); - std::vector validateFactionTypeUpgradeTypes(); - - void deletePixels(); - bool factionUsesResourceType(const ResourceType *rt) const; - + // init + FactionType(); + void load(const string &factionName, const TechTree *techTree, + Checksum *checksum, Checksum *techtreeChecksum, + std::map>> &loadedFileList, + bool validationMode = false); + virtual ~FactionType(); + + const std::vector + getAIBehaviorUnits(AIBehaviorUnitCategory category) const; + const std::vector getAIBehaviorUpgrades() const { + return vctAIBehaviorUpgrades; + }; + int getAIBehaviorStaticOverideValue(AIBehaviorStaticValueCategory type) const; + + // get + bool getIsLinked() const { return isLinked; } + int getUnitTypeCount() const { return (int)unitTypes.size(); } + int getUpgradeTypeCount() const { return (int)upgradeTypes.size(); } + virtual string getName(bool translatedValue = false) const; + const UnitType *getUnitType(int i) const { return &unitTypes[i]; } + const UpgradeType *getUpgradeType(int i) const { return &upgradeTypes[i]; } + StrSound *getMusic() const { return music; } + int getStartingUnitCount() const { return (int)startingUnits.size(); } + const UnitType *getStartingUnit(int i) const { + return startingUnits[i].first; + } + int getStartingUnitAmount(int i) const { return startingUnits[i].second; } + inline float getHealthbarHeight() const { return healthbarheight; } + inline float getHealthbarThickness() const { return healthbarthickness; } + inline int getHealthbarVisible() const { return healthbarVisible; } + inline bool isHealthbarBorderTextureEnabled() const { + return healthbarBorderTextureEnabled; + } + inline bool isHealthbarBackgroundTextureEnabled() const { + return healthbarBackgroundTextureEnabled; + } + inline bool isHealthbarLineBorder() const { return healthbarLineBorder; } + Texture2D *getHealthbarTexture() const { return healthbarTexture; } + Texture2D *getHealthbarBackgroundTexture() const { + return healthbarBackgroundTexture; + } + bool isFlatParticlePositions() const { return flatParticlePositions; } + + const UnitType *getUnitType(const string &name) const; + // const UnitType *getUnitTypeById(int id) const; + const UpgradeType *getUpgradeType(const string &name) const; + int getStartingResourceAmount(const ResourceType *resourceType) const; + + FactionPersonalityType getPersonalityType() const { return personalityType; } + void setPersonalityType(FactionPersonalityType value) { + personalityType = value; + } + + std::string toString() const; + std::vector validateFactionType(); + std::vector + validateFactionTypeResourceTypes(vector &resourceTypes); + std::vector validateFactionTypeUpgradeTypes(); + + void deletePixels(); + bool factionUsesResourceType(const ResourceType *rt) const; }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/types/object_type.cpp b/source/glest_game/types/object_type.cpp index 43f4e3483..e3641a549 100644 --- a/source/glest_game/types/object_type.cpp +++ b/source/glest_game/types/object_type.cpp @@ -3,59 +3,66 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== #include "object_type.h" -#include "renderer.h" #include "leak_dumper.h" +#include "renderer.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class ObjectType // ===================================================== -void ObjectType::init(int modelCount, int objectClass, bool walkable, int height) { -// modeltypes.reserve(modelCount); - this->objectClass= objectClass; - this->walkable= walkable; - this->height = height; +void ObjectType::init(int modelCount, int objectClass, bool walkable, + int height) { + // modeltypes.reserve(modelCount); + this->objectClass = objectClass; + this->walkable = walkable; + this->height = height; } -ObjectType::~ObjectType(){ - while(!(modeltypes.empty())){ - delete modeltypes.back(); - modeltypes.pop_back(); - //Logger::getInstance().add("ObjectType", true); - } +ObjectType::~ObjectType() { + while (!(modeltypes.empty())) { + delete modeltypes.back(); + modeltypes.pop_back(); + // Logger::getInstance().add("ObjectType", true); + } } -TilesetModelType* ObjectType::loadModel(const string &path, std::map > > *loadedFileList, - string parentLoader) { - Model *model= Renderer::getInstance().newModel(rsGame, path, false, loadedFileList, &parentLoader); - color= Vec3f(0.f); - if(model && model->getMeshCount()>0 && model->getMesh(0)->getTexture(0) != NULL) { - const Pixmap2D *p= model->getMesh(0)->getTexture(0)->getPixmapConst(); - color= p->getPixel3f(p->getW()/2, p->getH()/2); - } - TilesetModelType *modelType=new TilesetModelType(); - modelType->setModel(model); - modeltypes.push_back(modelType); - return modelType; +TilesetModelType *ObjectType::loadModel( + const string &path, + std::map>> *loadedFileList, + string parentLoader) { + Model *model = Renderer::getInstance().newModel( + rsGame, path, false, loadedFileList, &parentLoader); + color = Vec3f(0.f); + if (model && model->getMeshCount() > 0 && + model->getMesh(0)->getTexture(0) != NULL) { + const Pixmap2D *p = model->getMesh(0)->getTexture(0)->getPixmapConst(); + color = p->getPixel3f(p->getW() / 2, p->getH() / 2); + } + TilesetModelType *modelType = new TilesetModelType(); + modelType->setModel(model); + modeltypes.push_back(modelType); + return modelType; } void ObjectType::deletePixels() { - for(int i = 0; i < (int)modeltypes.size(); ++i) { - TilesetModelType *model = modeltypes[i]; - if(model->getModel() != NULL) { - model->getModel()->deletePixels(); - } - } + for (int i = 0; i < (int)modeltypes.size(); ++i) { + TilesetModelType *model = modeltypes[i]; + if (model->getModel() != NULL) { + model->getModel()->deletePixels(); + } + } } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/types/object_type.h b/source/glest_game/types/object_type.h index 355dffe90..68575e189 100644 --- a/source/glest_game/types/object_type.h +++ b/source/glest_game/types/object_type.h @@ -3,79 +3,86 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== #ifndef _GLEST_GAME_OBJECTTYPE_H_ #define _GLEST_GAME_OBJECTTYPE_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include -#include "model.h" -#include "vec.h" #include "leak_dumper.h" -#include "unit_particle_type.h" +#include "model.h" #include "tileset_model_type.h" +#include "unit_particle_type.h" +#include "vec.h" +#include using std::vector; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { using Shared::Graphics::Model; using Shared::Graphics::Vec3f; // ===================================================== -// class ObjectType +// class ObjectType // /// Each of the possible objects of the map: trees, stones ... // ===================================================== -typedef vector ObjectParticleSystemTypes; +typedef vector ObjectParticleSystemTypes; typedef vector ObjectParticleVector; class ObjectType { private: - typedef vector ModelTypes; + typedef vector ModelTypes; + private: - static const int tree1= 0; - static const int tree2= 1; - static const int choppedTree= 2; + static const int tree1 = 0; + static const int tree2 = 1; + static const int choppedTree = 2; private: - ModelTypes modeltypes; - Vec3f color; - int objectClass; - bool walkable; - int height; + ModelTypes modeltypes; + Vec3f color; + int objectClass; + bool walkable; + int height; public: - ObjectType() { - objectClass = -1; - walkable = false; - height = 0; - } - ~ObjectType(); - void init(int modelCount, int objectClass, bool walkable, int height); + ObjectType() { + objectClass = -1; + walkable = false; + height = 0; + } + ~ObjectType(); + void init(int modelCount, int objectClass, bool walkable, int height); - TilesetModelType* loadModel(const string &path, std::map > > *loadedFileList=NULL, - string parentLoader=""); + TilesetModelType *loadModel( + const string &path, + std::map>> *loadedFileList = NULL, + string parentLoader = ""); - inline TilesetModelType *getTilesetModelType(int i) {return modeltypes[i];} - inline int getModelCount() const {return (int)modeltypes.size();} - inline const Vec3f &getColor() const {return color;} - inline int getClass() const {return objectClass;} - inline bool getWalkable() const {return walkable;} - inline int getHeight() const {return height;} - inline bool isATree() const {return objectClass==tree1 || objectClass==tree2;} - void deletePixels(); + inline TilesetModelType *getTilesetModelType(int i) { return modeltypes[i]; } + inline int getModelCount() const { return (int)modeltypes.size(); } + inline const Vec3f &getColor() const { return color; } + inline int getClass() const { return objectClass; } + inline bool getWalkable() const { return walkable; } + inline int getHeight() const { return height; } + inline bool isATree() const { + return objectClass == tree1 || objectClass == tree2; + } + void deletePixels(); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/types/projectile_type.cpp b/source/glest_game/types/projectile_type.cpp index 672c2dc28..debf9c4b2 100644 --- a/source/glest_game/types/projectile_type.cpp +++ b/source/glest_game/types/projectile_type.cpp @@ -3,124 +3,140 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== -#include -#include "logger.h" #include "lang.h" -#include "renderer.h" #include "leak_dumper.h" +#include "logger.h" +#include "renderer.h" +#include using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { ProjectileType::ProjectileType() { - projectileParticleSystemType=NULL; - attackStartTime=0.0f; + projectileParticleSystemType = NULL; + attackStartTime = 0.0f; - spawnUnit=""; - spawnUnitcount=0; - spawnUnitAtTarget=false; + spawnUnit = ""; + spawnUnitcount = 0; + spawnUnitAtTarget = false; - shake=false; - shakeIntensity=0; - shakeDuration=0; + shake = false; + shakeIntensity = 0; + shakeDuration = 0; - shakeVisible=true; - shakeInCameraView=true; - shakeCameraDistanceAffected=false; - damagePercentage=100; + shakeVisible = true; + shakeInCameraView = true; + shakeCameraDistanceAffected = false; + damagePercentage = 100; } ProjectileType::~ProjectileType() { - deleteValues(hitSounds.getSounds().begin(), hitSounds.getSounds().end()); - if(projectileParticleSystemType!=NULL){ - delete projectileParticleSystemType; - projectileParticleSystemType = NULL; - } + deleteValues(hitSounds.getSounds().begin(), hitSounds.getSounds().end()); + if (projectileParticleSystemType != NULL) { + delete projectileParticleSystemType; + projectileParticleSystemType = NULL; + } } -void ProjectileType::load(const XmlNode *projectileNode, const string &dir, const string &techtreepath, std::map > > &loadedFileList, - string parentLoader){ - - string currentPath = dir; - endPathWithSlash(currentPath); - - if(projectileNode->hasAttribute("attack-start-time")){ - attackStartTime =projectileNode->getAttribute("attack-start-time")->getFloatValue(); - } - else - { - attackStartTime=0.0f; - } - - // damage percentage MUST be set! - damagePercentage =projectileNode->getAttribute("damage-percentage")->getIntValue(); - - - // projectiles MUST have a particle system. - const XmlNode *particleNode= projectileNode->getChild("particle"); - string path= particleNode->getAttribute("path")->getRestrictedValue(); - ParticleSystemTypeProjectile* projectileParticleSystemType= new ParticleSystemTypeProjectile(); - projectileParticleSystemType->load(particleNode, dir, currentPath + path, - &Renderer::getInstance(), loadedFileList, parentLoader, - techtreepath); - loadedFileList[currentPath + path].push_back(make_pair(parentLoader,particleNode->getAttribute("path")->getRestrictedValue())); - setProjectileParticleSystemType(projectileParticleSystemType); - - //spawnattack - if (projectileNode->hasChild("unit")) { - spawnUnit = projectileNode->getChild("unit")->getAttribute("value")->getValue(); - spawnUnitcount = projectileNode->getChild("unit")->getAttribute("amount")->getIntValue(); - if(projectileNode->getChild("unit")->hasAttribute("spawnAtTarget")) { - spawnUnitAtTarget = projectileNode->getChild("unit")->getAttribute("spawnAtTarget")->getBoolValue(); - } else { - spawnUnitAtTarget = false; - } - } else { - spawnUnit = ""; - spawnUnitcount = 0; - spawnUnitAtTarget = false; - } - - - if(projectileNode->hasChild("hitshake")){ - const XmlNode *hitShakeNode= projectileNode->getChild("hitshake"); - shake=hitShakeNode->getAttribute("enabled")->getBoolValue(); - if(shake){ - shakeIntensity=hitShakeNode->getAttribute("intensity")->getIntValue(); - shakeDuration=hitShakeNode->getAttribute("duration")->getIntValue(); - - shakeVisible=hitShakeNode->getAttribute("visible")->getBoolValue(); - shakeInCameraView=hitShakeNode->getAttribute("in-camera-view")->getBoolValue(); - shakeCameraDistanceAffected=hitShakeNode->getAttribute("camera-distance-affected")->getBoolValue(); - } - } - - if(projectileNode->hasChild("hitsound")){ - const XmlNode *soundNode= projectileNode->getChild("hitsound"); - if(soundNode->getAttribute("enabled")->getBoolValue()){ - - hitSounds.resize((int)soundNode->getChildCount()); - for(int i=0; i < (int)soundNode->getChildCount(); ++i){ - const XmlNode *soundFileNode= soundNode->getChild("sound-file", i); - string path= soundFileNode->getAttribute("path")->getRestrictedValue(currentPath, true); - //printf("\n\n\n\n!@#$ ---> parentLoader [%s] path [%s] nodeValue [%s] i = %d",parentLoader.c_str(),path.c_str(),soundFileNode->getAttribute("path")->getRestrictedValue().c_str(),i); - - StaticSound *sound= new StaticSound(); - sound->load(path); - loadedFileList[path].push_back(make_pair(parentLoader,soundFileNode->getAttribute("path")->getRestrictedValue())); - hitSounds[i]= sound; - } - } - } +void ProjectileType::load( + const XmlNode *projectileNode, const string &dir, + const string &techtreepath, + std::map>> &loadedFileList, + string parentLoader) { + + string currentPath = dir; + endPathWithSlash(currentPath); + + if (projectileNode->hasAttribute("attack-start-time")) { + attackStartTime = + projectileNode->getAttribute("attack-start-time")->getFloatValue(); + } else { + attackStartTime = 0.0f; + } + + // damage percentage MUST be set! + damagePercentage = + projectileNode->getAttribute("damage-percentage")->getIntValue(); + + // projectiles MUST have a particle system. + const XmlNode *particleNode = projectileNode->getChild("particle"); + string path = particleNode->getAttribute("path")->getRestrictedValue(); + ParticleSystemTypeProjectile *projectileParticleSystemType = + new ParticleSystemTypeProjectile(); + projectileParticleSystemType->load(particleNode, dir, currentPath + path, + &Renderer::getInstance(), loadedFileList, + parentLoader, techtreepath); + loadedFileList[currentPath + path].push_back(make_pair( + parentLoader, particleNode->getAttribute("path")->getRestrictedValue())); + setProjectileParticleSystemType(projectileParticleSystemType); + + // spawnattack + if (projectileNode->hasChild("unit")) { + spawnUnit = + projectileNode->getChild("unit")->getAttribute("value")->getValue(); + spawnUnitcount = + projectileNode->getChild("unit")->getAttribute("amount")->getIntValue(); + if (projectileNode->getChild("unit")->hasAttribute("spawnAtTarget")) { + spawnUnitAtTarget = projectileNode->getChild("unit") + ->getAttribute("spawnAtTarget") + ->getBoolValue(); + } else { + spawnUnitAtTarget = false; + } + } else { + spawnUnit = ""; + spawnUnitcount = 0; + spawnUnitAtTarget = false; + } + + if (projectileNode->hasChild("hitshake")) { + const XmlNode *hitShakeNode = projectileNode->getChild("hitshake"); + shake = hitShakeNode->getAttribute("enabled")->getBoolValue(); + if (shake) { + shakeIntensity = hitShakeNode->getAttribute("intensity")->getIntValue(); + shakeDuration = hitShakeNode->getAttribute("duration")->getIntValue(); + + shakeVisible = hitShakeNode->getAttribute("visible")->getBoolValue(); + shakeInCameraView = + hitShakeNode->getAttribute("in-camera-view")->getBoolValue(); + shakeCameraDistanceAffected = + hitShakeNode->getAttribute("camera-distance-affected") + ->getBoolValue(); + } + } + + if (projectileNode->hasChild("hitsound")) { + const XmlNode *soundNode = projectileNode->getChild("hitsound"); + if (soundNode->getAttribute("enabled")->getBoolValue()) { + + hitSounds.resize((int)soundNode->getChildCount()); + for (int i = 0; i < (int)soundNode->getChildCount(); ++i) { + const XmlNode *soundFileNode = soundNode->getChild("sound-file", i); + string path = soundFileNode->getAttribute("path")->getRestrictedValue( + currentPath, true); + // printf("\n\n\n\n!@#$ ---> parentLoader [%s] path [%s] nodeValue [%s] + // i = + // %d",parentLoader.c_str(),path.c_str(),soundFileNode->getAttribute("path")->getRestrictedValue().c_str(),i); + + StaticSound *sound = new StaticSound(); + sound->load(path); + loadedFileList[path].push_back(make_pair( + parentLoader, + soundFileNode->getAttribute("path")->getRestrictedValue())); + hitSounds[i] = sound; + } + } + } } - -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/types/projectile_type.h b/source/glest_game/types/projectile_type.h index d3871ef1d..7d1aba973 100644 --- a/source/glest_game/types/projectile_type.h +++ b/source/glest_game/types/projectile_type.h @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,78 +13,89 @@ #define _GLEST_GAME_PROJEKTILETYPE_H_ #ifdef WIN32 - #include - #include +#include +#include #endif #include "sound.h" #include "vec.h" -//#include "xml_parser.h" +// #include "xml_parser.h" #include "util.h" -//#include "element_type.h" +// #include "element_type.h" #include "factory.h" -#include "sound_container.h" -#include "particle_type.h" #include "leak_dumper.h" +#include "particle_type.h" +#include "sound_container.h" -using std::vector; using std::string; +using std::vector; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class ProjectileType // ===================================================== class ProjectileType { protected: - ParticleSystemTypeProjectile* projectileParticleSystemType; - SoundContainer hitSounds; - float attackStartTime; + ParticleSystemTypeProjectile *projectileParticleSystemType; + SoundContainer hitSounds; + float attackStartTime; - string spawnUnit; - int spawnUnitcount; - bool spawnUnitAtTarget; + string spawnUnit; + int spawnUnitcount; + bool spawnUnitAtTarget; - bool shake; - int shakeIntensity; - int shakeDuration; + bool shake; + int shakeIntensity; + int shakeDuration; - bool shakeVisible; - bool shakeInCameraView; - bool shakeCameraDistanceAffected; - int damagePercentage; + bool shakeVisible; + bool shakeInCameraView; + bool shakeCameraDistanceAffected; + int damagePercentage; public: - ProjectileType(); - virtual ~ProjectileType(); - - - void load(const XmlNode *projectileNode, const string &dir, const string &techtreepath, std::map > > &loadedFileList, - string parentLoader); - - //get/set - inline StaticSound *getHitSound() const {return hitSounds.getRandSound();} - ParticleSystemTypeProjectile* getProjectileParticleSystemType() const { return projectileParticleSystemType;} - float getAttackStartTime() const {return attackStartTime;} - void setAttackStartTime(float value) {attackStartTime=value;} - - string getSpawnUnit() const{return spawnUnit;} - int getSpawnUnitcount() const{return spawnUnitcount;} - bool getSpawnUnitAtTarget() const{return spawnUnitAtTarget;} - - bool isShake() const{return shake;} - bool isShakeCameraDistanceAffected() const{return shakeCameraDistanceAffected;} - int getShakeDuration() const{return shakeDuration;} - bool isShakeInCameraView() const{return shakeInCameraView;} - int getShakeIntensity() const{return shakeIntensity;} - bool isShakeVisible() const{return shakeVisible;} - int getDamagePercentage() const {return damagePercentage;} - void setDamagePercentage(int value) {damagePercentage=value;} - - void setProjectileParticleSystemType(ParticleSystemTypeProjectile *pointer) {projectileParticleSystemType=pointer;} - ParticleSystemTypeProjectile* getProjectileParticleSystemType() {return projectileParticleSystemType;} + ProjectileType(); + virtual ~ProjectileType(); + + void load(const XmlNode *projectileNode, const string &dir, + const string &techtreepath, + std::map>> &loadedFileList, + string parentLoader); + + // get/set + inline StaticSound *getHitSound() const { return hitSounds.getRandSound(); } + ParticleSystemTypeProjectile *getProjectileParticleSystemType() const { + return projectileParticleSystemType; + } + float getAttackStartTime() const { return attackStartTime; } + void setAttackStartTime(float value) { attackStartTime = value; } + + string getSpawnUnit() const { return spawnUnit; } + int getSpawnUnitcount() const { return spawnUnitcount; } + bool getSpawnUnitAtTarget() const { return spawnUnitAtTarget; } + + bool isShake() const { return shake; } + bool isShakeCameraDistanceAffected() const { + return shakeCameraDistanceAffected; + } + int getShakeDuration() const { return shakeDuration; } + bool isShakeInCameraView() const { return shakeInCameraView; } + int getShakeIntensity() const { return shakeIntensity; } + bool isShakeVisible() const { return shakeVisible; } + int getDamagePercentage() const { return damagePercentage; } + void setDamagePercentage(int value) { damagePercentage = value; } + + void setProjectileParticleSystemType(ParticleSystemTypeProjectile *pointer) { + projectileParticleSystemType = pointer; + } + ParticleSystemTypeProjectile *getProjectileParticleSystemType() { + return projectileParticleSystemType; + } }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/types/resource_type.cpp b/source/glest_game/types/resource_type.cpp index a3b3b9bd2..8b017d67a 100644 --- a/source/glest_game/types/resource_type.cpp +++ b/source/glest_game/types/resource_type.cpp @@ -11,244 +11,277 @@ #include "resource_type.h" -#include "util.h" #include "element_type.h" -#include "logger.h" -#include "renderer.h" -#include "xml_parser.h" #include "game_util.h" -#include "properties.h" #include "lang.h" #include "leak_dumper.h" +#include "logger.h" +#include "properties.h" +#include "renderer.h" +#include "util.h" +#include "xml_parser.h" using namespace Shared::Util; using namespace Shared::Xml; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class ResourceType // ===================================================== ResourceType::ResourceType() { - resourceClass=rcTech; - tilesetObject=0; - resourceNumber=0; - interval=0; - defResPerPatch=0; - recoup_cost = false; - model = NULL; - displayInHud = false; - cleanupMemory = true; + resourceClass = rcTech; + tilesetObject = 0; + resourceNumber = 0; + interval = 0; + defResPerPatch = 0; + recoup_cost = false; + model = NULL; + displayInHud = false; + cleanupMemory = true; } ResourceType::~ResourceType() { - if(cleanupMemory == true) { - while(particleTypes.empty() == false) { - delete particleTypes.back(); - particleTypes.pop_back(); - } - } + if (cleanupMemory == true) { + while (particleTypes.empty() == false) { + delete particleTypes.back(); + particleTypes.pop_back(); + } + } } string ResourceType::getName(bool translatedValue) const { - if(translatedValue == false) return name; + if (translatedValue == false) + return name; - Lang &lang = Lang::getInstance(); - return lang.getTechTreeString("ResourceTypeName_" + name,name.c_str()); + Lang &lang = Lang::getInstance(); + return lang.getTechTreeString("ResourceTypeName_" + name, name.c_str()); } -void ResourceType::load(const string &dir, Checksum* checksum, Checksum *techtreeChecksum, - std::map > > &loadedFileList, string techtreePath) { - - string path, str; - Renderer &renderer= Renderer::getInstance(); - - try - { - recoup_cost = true; - - name= lastDir(dir); - - char szBuf[8096]=""; - snprintf(szBuf,8096,Lang::getInstance().getString("LogScreenGameLoadingResourceType","",true).c_str(),formatString(getName(true)).c_str()); - Logger::getInstance().add(szBuf, true); - - string currentPath = dir; - endPathWithSlash(currentPath); - path= currentPath + name + ".xml"; - string sourceXMLFile = path; - checksum->addFile(path); - techtreeChecksum->addFile(path); - - //tree - XmlTree xmlTree; - std::map mapExtraTagReplacementValues; - mapExtraTagReplacementValues["$COMMONDATAPATH"] = techtreePath + "/commondata/"; - xmlTree.load(path, Properties::getTagReplacementValues(&mapExtraTagReplacementValues)); - loadedFileList[path].push_back(make_pair(currentPath,currentPath)); - - const XmlNode *resourceNode= xmlTree.getRootNode(); - - //image - const XmlNode *imageNode= resourceNode->getChild("image"); - image= renderer.newTexture2D(rsGame); - if(image) { - image->load(imageNode->getAttribute("path")->getRestrictedValue(currentPath)); - } - loadedFileList[imageNode->getAttribute("path")->getRestrictedValue(currentPath)].push_back(make_pair(sourceXMLFile,imageNode->getAttribute("path")->getRestrictedValue())); - - //type - const XmlNode *typeNode= resourceNode->getChild("type"); - resourceClass = strToRc(typeNode->getAttribute("value")->getRestrictedValue()); - - switch(resourceClass) - { - case rcTech: - { - //model - const XmlNode *modelNode= typeNode->getChild("model"); - string modelPath= modelNode->getAttribute("path")->getRestrictedValue(currentPath); - - model= renderer.newModel(rsGame, modelPath, false, &loadedFileList, &sourceXMLFile); - loadedFileList[modelPath].push_back(make_pair(sourceXMLFile,modelNode->getAttribute("path")->getRestrictedValue())); - - if(modelNode->hasChild("particles")){ - const XmlNode *particleNode= modelNode->getChild("particles"); - bool particleEnabled= particleNode->getAttribute("value")->getBoolValue(); - if(particleEnabled == true) { - for(int k= 0; k < (int)particleNode->getChildCount(); ++k) { - const XmlNode *particleFileNode= particleNode->getChild("particle-file", k); - string particlePath= particleFileNode->getAttribute("path")->getRestrictedValue(); - - ObjectParticleSystemType *objectParticleSystemType= new ObjectParticleSystemType(); - objectParticleSystemType->load(particleFileNode, dir, currentPath + particlePath, - &Renderer::getInstance(), loadedFileList, sourceXMLFile, techtreePath); - loadedFileList[currentPath + particlePath].push_back(make_pair(sourceXMLFile,particleFileNode->getAttribute("path")->getRestrictedValue())); - - particleTypes.push_back(objectParticleSystemType); - } - } - } - - //default resources - const XmlNode *defaultAmountNode= typeNode->getChild("default-amount"); - defResPerPatch= defaultAmountNode->getAttribute("value")->getIntValue(); - - //resource number - const XmlNode *resourceNumberNode= typeNode->getChild("resource-number"); - resourceNumber= resourceNumberNode->getAttribute("value")->getIntValue(); - } - break; - - case rcTileset: - { - //resource number - const XmlNode *defaultAmountNode= typeNode->getChild("default-amount"); - defResPerPatch= defaultAmountNode->getAttribute("value")->getIntValue(); - - //resource number - const XmlNode *tilesetObjectNode= typeNode->getChild("tileset-object"); - tilesetObject= tilesetObjectNode->getAttribute("value")->getIntValue(); - } - break; - - case rcConsumable: - { - //interval - const XmlNode *intervalNode= typeNode->getChild("interval"); - interval= intervalNode->getAttribute("value")->getIntValue(); - } - break; - - case rcStatic: - { - //recoup_cost - if(typeNode->hasChild("recoup_cost") == true) { - const XmlNode *recoup_costNode= typeNode->getChild("recoup_cost"); - if(recoup_costNode != NULL) { - recoup_cost= recoup_costNode->getAttribute("value")->getBoolValue(); - } - } - } - break; - - default: - break; - } - - //displayInHud - if(resourceNode->hasChild("display") == true) { - const XmlNode *displayNode= resourceNode->getChild("display"); - displayInHud= displayNode->getAttribute("value")->getBoolValue(); - } - else { - displayInHud=true; - } - } - catch(megaglest_runtime_error& ex) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - throw megaglest_runtime_error("Error loading resource type: "+ path + "\nMessage: " + ex.what(),!ex.wantStackTrace()); +void ResourceType::load( + const string &dir, Checksum *checksum, Checksum *techtreeChecksum, + std::map>> &loadedFileList, + string techtreePath) { + + string path, str; + Renderer &renderer = Renderer::getInstance(); + + try { + recoup_cost = true; + + name = lastDir(dir); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + Lang::getInstance() + .getString("LogScreenGameLoadingResourceType", "", true) + .c_str(), + formatString(getName(true)).c_str()); + Logger::getInstance().add(szBuf, true); + + string currentPath = dir; + endPathWithSlash(currentPath); + path = currentPath + name + ".xml"; + string sourceXMLFile = path; + checksum->addFile(path); + techtreeChecksum->addFile(path); + + // tree + XmlTree xmlTree; + std::map mapExtraTagReplacementValues; + mapExtraTagReplacementValues["$COMMONDATAPATH"] = + techtreePath + "/commondata/"; + xmlTree.load(path, Properties::getTagReplacementValues( + &mapExtraTagReplacementValues)); + loadedFileList[path].push_back(make_pair(currentPath, currentPath)); + + const XmlNode *resourceNode = xmlTree.getRootNode(); + + // image + const XmlNode *imageNode = resourceNode->getChild("image"); + image = renderer.newTexture2D(rsGame); + if (image) { + image->load( + imageNode->getAttribute("path")->getRestrictedValue(currentPath)); + } + loadedFileList[imageNode->getAttribute("path")->getRestrictedValue( + currentPath)] + .push_back( + make_pair(sourceXMLFile, + imageNode->getAttribute("path")->getRestrictedValue())); + + // type + const XmlNode *typeNode = resourceNode->getChild("type"); + resourceClass = + strToRc(typeNode->getAttribute("value")->getRestrictedValue()); + + switch (resourceClass) { + case rcTech: { + // model + const XmlNode *modelNode = typeNode->getChild("model"); + string modelPath = + modelNode->getAttribute("path")->getRestrictedValue(currentPath); + + model = renderer.newModel(rsGame, modelPath, false, &loadedFileList, + &sourceXMLFile); + loadedFileList[modelPath].push_back( + make_pair(sourceXMLFile, + modelNode->getAttribute("path")->getRestrictedValue())); + + if (modelNode->hasChild("particles")) { + const XmlNode *particleNode = modelNode->getChild("particles"); + bool particleEnabled = + particleNode->getAttribute("value")->getBoolValue(); + if (particleEnabled == true) { + for (int k = 0; k < (int)particleNode->getChildCount(); ++k) { + const XmlNode *particleFileNode = + particleNode->getChild("particle-file", k); + string particlePath = + particleFileNode->getAttribute("path")->getRestrictedValue(); + + ObjectParticleSystemType *objectParticleSystemType = + new ObjectParticleSystemType(); + objectParticleSystemType->load( + particleFileNode, dir, currentPath + particlePath, + &Renderer::getInstance(), loadedFileList, sourceXMLFile, + techtreePath); + loadedFileList[currentPath + particlePath].push_back(make_pair( + sourceXMLFile, + particleFileNode->getAttribute("path")->getRestrictedValue())); + + particleTypes.push_back(objectParticleSystemType); + } + } + } + + // default resources + const XmlNode *defaultAmountNode = typeNode->getChild("default-amount"); + defResPerPatch = defaultAmountNode->getAttribute("value")->getIntValue(); + + // resource number + const XmlNode *resourceNumberNode = typeNode->getChild("resource-number"); + resourceNumber = resourceNumberNode->getAttribute("value")->getIntValue(); + } break; + + case rcTileset: { + // resource number + const XmlNode *defaultAmountNode = typeNode->getChild("default-amount"); + defResPerPatch = defaultAmountNode->getAttribute("value")->getIntValue(); + + // resource number + const XmlNode *tilesetObjectNode = typeNode->getChild("tileset-object"); + tilesetObject = tilesetObjectNode->getAttribute("value")->getIntValue(); + } break; + + case rcConsumable: { + // interval + const XmlNode *intervalNode = typeNode->getChild("interval"); + interval = intervalNode->getAttribute("value")->getIntValue(); + } break; + + case rcStatic: { + // recoup_cost + if (typeNode->hasChild("recoup_cost") == true) { + const XmlNode *recoup_costNode = typeNode->getChild("recoup_cost"); + if (recoup_costNode != NULL) { + recoup_cost = recoup_costNode->getAttribute("value")->getBoolValue(); + } + } + } break; + + default: + break; } - catch(const exception &e){ - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,e.what()); - throw megaglest_runtime_error("Error loading resource type: " + path + "\n" + e.what()); - } + + // displayInHud + if (resourceNode->hasChild("display") == true) { + const XmlNode *displayNode = resourceNode->getChild("display"); + displayInHud = displayNode->getAttribute("value")->getBoolValue(); + } else { + displayInHud = true; + } + } catch (megaglest_runtime_error &ex) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + throw megaglest_runtime_error("Error loading resource type: " + path + + "\nMessage: " + ex.what(), + !ex.wantStackTrace()); + } catch (const exception &e) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", __FILE__, + __FUNCTION__, __LINE__, e.what()); + throw megaglest_runtime_error("Error loading resource type: " + path + + "\n" + e.what()); + } } // ==================== misc ==================== -ResourceClass ResourceType::strToRc(const string &s){ - if(s=="tech"){ - return rcTech; - } - if(s=="tileset"){ - return rcTileset; - } - if(s=="static"){ - return rcStatic; - } - if(s=="consumable"){ - return rcConsumable; - } - throw megaglest_runtime_error("Error converting from string ro resourceClass, found: " + s); +ResourceClass ResourceType::strToRc(const string &s) { + if (s == "tech") { + return rcTech; + } + if (s == "tileset") { + return rcTileset; + } + if (s == "static") { + return rcStatic; + } + if (s == "consumable") { + return rcConsumable; + } + throw megaglest_runtime_error( + "Error converting from string ro resourceClass, found: " + s); } void ResourceType::deletePixels() { - if(model != NULL) { - model->deletePixels(); - } + if (model != NULL) { + model->deletePixels(); + } } void ResourceType::saveGame(XmlNode *rootNode) { - //DisplayableType::saveGame(rootNode); - - std::map mapTagReplacements; - XmlNode *resourceTypeNode = rootNode->addChild("ResourceType"); - - resourceTypeNode->addAttribute("name",this->getName(), mapTagReplacements); -// ResourceClass resourceClass; - resourceTypeNode->addAttribute("resourceClass",intToStr(resourceClass), mapTagReplacements); -// int tilesetObject; //used only if class==rcTileset - resourceTypeNode->addAttribute("tilesetObject",intToStr(tilesetObject), mapTagReplacements); -// int resourceNumber; //used only if class==rcTech, resource number in the map - resourceTypeNode->addAttribute("resourceNumber",intToStr(resourceNumber), mapTagReplacements); -// int interval; //used only if class==rcConsumable - resourceTypeNode->addAttribute("interval",intToStr(interval), mapTagReplacements); -// int defResPerPatch; //used only if class==rcTileset || class==rcTech - resourceTypeNode->addAttribute("defResPerPatch",intToStr(defResPerPatch), mapTagReplacements); -// bool recoup_cost; - resourceTypeNode->addAttribute("recoup_cost",intToStr(recoup_cost), mapTagReplacements); -// -// Model *model; - if(model != NULL) { - resourceTypeNode->addAttribute("model",model->getFileName(), mapTagReplacements); - } -// ObjectParticleSystemTypes particleTypes; - for(unsigned int i = 0; i < particleTypes.size(); ++i) { - ObjectParticleSystemType *opst = particleTypes[i]; - opst->saveGame(resourceTypeNode); - } + // DisplayableType::saveGame(rootNode); + + std::map mapTagReplacements; + XmlNode *resourceTypeNode = rootNode->addChild("ResourceType"); + + resourceTypeNode->addAttribute("name", this->getName(), mapTagReplacements); + // ResourceClass resourceClass; + resourceTypeNode->addAttribute("resourceClass", intToStr(resourceClass), + mapTagReplacements); + // int tilesetObject; //used only if class==rcTileset + resourceTypeNode->addAttribute("tilesetObject", intToStr(tilesetObject), + mapTagReplacements); + // int resourceNumber; //used only if class==rcTech, resource number in + // the map + resourceTypeNode->addAttribute("resourceNumber", intToStr(resourceNumber), + mapTagReplacements); + // int interval; //used only if class==rcConsumable + resourceTypeNode->addAttribute("interval", intToStr(interval), + mapTagReplacements); + // int defResPerPatch; //used only if class==rcTileset || class==rcTech + resourceTypeNode->addAttribute("defResPerPatch", intToStr(defResPerPatch), + mapTagReplacements); + // bool recoup_cost; + resourceTypeNode->addAttribute("recoup_cost", intToStr(recoup_cost), + mapTagReplacements); + // + // Model *model; + if (model != NULL) { + resourceTypeNode->addAttribute("model", model->getFileName(), + mapTagReplacements); + } + // ObjectParticleSystemTypes particleTypes; + for (unsigned int i = 0; i < particleTypes.size(); ++i) { + ObjectParticleSystemType *opst = particleTypes[i]; + opst->saveGame(resourceTypeNode); + } } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/types/resource_type.h b/source/glest_game/types/resource_type.h index 8ffbe4805..6b8ff8302 100644 --- a/source/glest_game/types/resource_type.h +++ b/source/glest_game/types/resource_type.h @@ -13,28 +13,24 @@ #define _GLEST_GAME_RESOURCETYPE_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include "element_type.h" -#include "model.h" #include "checksum.h" +#include "element_type.h" #include "leak_dumper.h" -#include "unit_particle_type.h" +#include "model.h" #include "object_type.h" +#include "unit_particle_type.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { using Shared::Graphics::Model; using Shared::Util::Checksum; -enum ResourceClass{ - rcTech, - rcTileset, - rcStatic, - rcConsumable -}; +enum ResourceClass { rcTech, rcTileset, rcStatic, rcConsumable }; // ===================================================== // class ResourceType @@ -42,50 +38,52 @@ enum ResourceClass{ /// A type of resource that can be harvested or not // ===================================================== - -class ResourceType: public DisplayableType{ +class ResourceType : public DisplayableType { private: - ResourceClass resourceClass; - int tilesetObject; //used only if class==rcTileset - int resourceNumber; //used only if class==rcTech, resource number in the map - int interval; //used only if class==rcConsumable - int defResPerPatch; //used only if class==rcTileset || class==rcTech - bool recoup_cost; - bool displayInHud; - - Model *model; - ObjectParticleSystemTypes particleTypes; - bool cleanupMemory; + ResourceClass resourceClass; + int tilesetObject; // used only if class==rcTileset + int resourceNumber; // used only if class==rcTech, resource number in the map + int interval; // used only if class==rcConsumable + int defResPerPatch; // used only if class==rcTileset || class==rcTech + bool recoup_cost; + bool displayInHud; + + Model *model; + ObjectParticleSystemTypes particleTypes; + bool cleanupMemory; public: - ResourceType(); - ~ResourceType(); - void load(const string &dir, Checksum* checksum,Checksum *techtreeChecksum, - std::map > > &loadedFileList, - string techtreePath); - - virtual string getName(bool translatedValue=false) const; - //get - int getClass() const {return resourceClass;} - int getTilesetObject() const {return tilesetObject;} - int getResourceNumber() const {return resourceNumber;} - int getInterval() const {return interval;} - int getDefResPerPatch() const {return defResPerPatch;} - Model *getModel() const {return model;} - bool getRecoup_cost() const { return recoup_cost;} - bool getDisplayInHud() const { return displayInHud;} - - bool hasParticles() const {return !particleTypes.empty();} - const ObjectParticleSystemTypes *getObjectParticleSystemTypes() const {return &particleTypes;} - - void setCleanupMemory(bool value) { cleanupMemory = value; } - - static ResourceClass strToRc(const string &s); - void deletePixels(); - - void saveGame(XmlNode *rootNode); + ResourceType(); + ~ResourceType(); + void load(const string &dir, Checksum *checksum, Checksum *techtreeChecksum, + std::map>> &loadedFileList, + string techtreePath); + + virtual string getName(bool translatedValue = false) const; + // get + int getClass() const { return resourceClass; } + int getTilesetObject() const { return tilesetObject; } + int getResourceNumber() const { return resourceNumber; } + int getInterval() const { return interval; } + int getDefResPerPatch() const { return defResPerPatch; } + Model *getModel() const { return model; } + bool getRecoup_cost() const { return recoup_cost; } + bool getDisplayInHud() const { return displayInHud; } + + bool hasParticles() const { return !particleTypes.empty(); } + const ObjectParticleSystemTypes *getObjectParticleSystemTypes() const { + return &particleTypes; + } + + void setCleanupMemory(bool value) { cleanupMemory = value; } + + static ResourceClass strToRc(const string &s); + void deletePixels(); + + void saveGame(XmlNode *rootNode); }; -}} //end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/types/skill_type.cpp b/source/glest_game/types/skill_type.cpp index 803dd61a5..0e4228789 100644 --- a/source/glest_game/types/skill_type.cpp +++ b/source/glest_game/types/skill_type.cpp @@ -14,1465 +14,1663 @@ #include #include -#include "sound.h" -#include "util.h" +#include "faction_type.h" #include "lang.h" -#include "renderer.h" +#include "leak_dumper.h" #include "particle_type.h" -#include "unit_particle_type.h" #include "projectile_type.h" +#include "renderer.h" +#include "sound.h" #include "tech_tree.h" -#include "faction_type.h" -#include "leak_dumper.h" +#include "unit_particle_type.h" +#include "util.h" using namespace Shared::Util; using namespace Shared::Graphics; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { int SkillType::nextAttackBoostId = 0; AttackBoost::AttackBoost() : boostUpgrade() { - enabled = false; - allowMultipleBoosts = false; - radius = 0; - targetType = abtFaction; - unitParticleSystemTypeForSourceUnit = NULL; - unitParticleSystemTypeForAffectedUnit = NULL; - includeSelf = false; + enabled = false; + allowMultipleBoosts = false; + radius = 0; + targetType = abtFaction; + unitParticleSystemTypeForSourceUnit = NULL; + unitParticleSystemTypeForAffectedUnit = NULL; + includeSelf = false; } AttackBoost::~AttackBoost() { - delete unitParticleSystemTypeForSourceUnit; - unitParticleSystemTypeForSourceUnit = NULL; + delete unitParticleSystemTypeForSourceUnit; + unitParticleSystemTypeForSourceUnit = NULL; - delete unitParticleSystemTypeForAffectedUnit; - unitParticleSystemTypeForAffectedUnit = NULL; + delete unitParticleSystemTypeForAffectedUnit; + unitParticleSystemTypeForAffectedUnit = NULL; } bool AttackBoost::isAffected(const Unit *source, const Unit *dest) const { - bool result = false; - if(enabled == true && - source != NULL && dest != NULL && - (includeSelf == true || source != dest)) { - bool destUnitMightApply = false; - if(source == dest && includeSelf == true) { - destUnitMightApply = true; - } - else { - // All units are affected (including enemies) - if(targetType == abtAll) { - destUnitMightApply = (boostUnitList.empty() && tags.empty()) || isInUnitListOrTags(dest->getType());; - } - // Only same faction units are affected - else if(targetType == abtFaction) { - if(source->getFactionIndex() == dest->getFactionIndex()) { - destUnitMightApply = (boostUnitList.empty() && tags.empty()) || isInUnitListOrTags(dest->getType()); - } - } - // Only ally units are affected - else if(targetType == abtAlly) { - if(source->isAlly(dest) == true) { - destUnitMightApply = (boostUnitList.empty() && tags.empty()) || isInUnitListOrTags(dest->getType()); - } - } - // Only foe units are affected - else if(targetType == abtFoe) { - if(source->isAlly(dest) == false) { - destUnitMightApply = (boostUnitList.empty() && tags.empty()) || isInUnitListOrTags(dest->getType()); - } - } - else if(targetType == abtUnitTypes) { - destUnitMightApply = isInUnitListOrTags(dest->getType()); - } - } - - if(destUnitMightApply == true) { - float distance = source->getCenteredPos().dist(dest->getCenteredPos()); - if(distance <= radius) { - result = true; - } - } - } - - return result; + bool result = false; + if (enabled == true && source != NULL && dest != NULL && + (includeSelf == true || source != dest)) { + bool destUnitMightApply = false; + if (source == dest && includeSelf == true) { + destUnitMightApply = true; + } else { + // All units are affected (including enemies) + if (targetType == abtAll) { + destUnitMightApply = (boostUnitList.empty() && tags.empty()) || + isInUnitListOrTags(dest->getType()); + ; + } + // Only same faction units are affected + else if (targetType == abtFaction) { + if (source->getFactionIndex() == dest->getFactionIndex()) { + destUnitMightApply = (boostUnitList.empty() && tags.empty()) || + isInUnitListOrTags(dest->getType()); + } + } + // Only ally units are affected + else if (targetType == abtAlly) { + if (source->isAlly(dest) == true) { + destUnitMightApply = (boostUnitList.empty() && tags.empty()) || + isInUnitListOrTags(dest->getType()); + } + } + // Only foe units are affected + else if (targetType == abtFoe) { + if (source->isAlly(dest) == false) { + destUnitMightApply = (boostUnitList.empty() && tags.empty()) || + isInUnitListOrTags(dest->getType()); + } + } else if (targetType == abtUnitTypes) { + destUnitMightApply = isInUnitListOrTags(dest->getType()); + } + } + + if (destUnitMightApply == true) { + float distance = source->getCenteredPos().dist(dest->getCenteredPos()); + if (distance <= radius) { + result = true; + } + } + } + + return result; } bool AttackBoost::isInUnitListOrTags(const UnitType *unitType) const { - // Specify which units are affected - std::set::iterator it; - for (it = boostUnitList.begin(); it != boostUnitList.end(); ++it) { - const UnitType *boostUnit = *it; - if(unitType->getId() == boostUnit->getId()) { - return true; - } - } - set unitTags = unitType->getTags(); - set intersect; - set_intersection(tags.begin(),tags.end(),unitTags.begin(),unitTags.end(), - std::inserter(intersect,intersect.begin())); - if(!intersect.empty()) return true; - - // Otherwise no match - return false; + // Specify which units are affected + std::set::iterator it; + for (it = boostUnitList.begin(); it != boostUnitList.end(); ++it) { + const UnitType *boostUnit = *it; + if (unitType->getId() == boostUnit->getId()) { + return true; + } + } + set unitTags = unitType->getTags(); + set intersect; + set_intersection(tags.begin(), tags.end(), unitTags.begin(), unitTags.end(), + std::inserter(intersect, intersect.begin())); + if (!intersect.empty()) + return true; + + // Otherwise no match + return false; } string AttackBoost::getTagName(string tag, bool translatedValue) const { - if(translatedValue == false) return tag; - - Lang &lang = Lang::getInstance(); - return lang.getTechTreeString("TagName_" + tag, tag.c_str()); -} - -string AttackBoost::getDesc(bool translatedValue) const{ - Lang &lang= Lang::getInstance(); - string str= ""; - string indent=" "; - if(enabled) { - if(boostUnitList.empty() == false) { - str+= "\n"+ lang.getString("Effects")+":\n"; - } - - str += indent+lang.getString("effectRadius") + ": " + intToStr(radius) +"\n"; - if(allowMultipleBoosts==false) { - string allowIt=lang.getString("No"); - if(allowMultipleBoosts==true) - allowIt=lang.getString("False"); - str += indent+lang.getString("allowMultiBoost") + ": " + allowIt +"\n"; - } - str+=boostUpgrade.getDesc(translatedValue); - - if(targetType==abtAlly) - { - str+= lang.getString("AffectedUnitsFromTeam") +":\n"; - } - else if(targetType==abtFoe) - { - str+= lang.getString("AffectedUnitsFromFoe") +":\n"; - } - else if(targetType==abtFaction) - { - str+= lang.getString("AffectedUnitsFromYourFaction") +":\n"; - } - else if(targetType==abtUnitTypes) - { - str+= lang.getString("AffectedUnitsFromAll") +":\n"; - } - else if(targetType==abtAll) - { - str+= lang.getString("AffectedUnitsFromAll") +":\n"; - } - - if(boostUnitList.empty() && tags.empty()) { - str+= lang.getString("All")+"\n"; - } - else - { - // We want the output to be sorted, so convert the set to a vector and sort that - std::vector outputUnits(boostUnitList.begin(), boostUnitList.end()); - std::sort(outputUnits.begin(), outputUnits.end(), UnitTypeSorter()); - - vector::iterator unitIter; - for (unitIter = outputUnits.begin(); unitIter != outputUnits.end(); ++unitIter) { - const UnitType *unit = *unitIter; - str+= indent+unit->getName(translatedValue)+"\n"; - } - - // Do the same for tags - std::vector outputTags(tags.begin(), tags.end()); - std::sort(outputTags.begin(), outputTags.end()); - - vector::iterator tagIter; - for (tagIter = outputTags.begin(); tagIter != outputTags.end(); ++tagIter) { - string tag = *tagIter; - str+= indent + lang.getString("TagDesc", (translatedValue == true ? "" : "english")) + - " " + getTagName(tag,translatedValue) + "\n"; - } - } - - return str; + if (translatedValue == false) + return tag; + + Lang &lang = Lang::getInstance(); + return lang.getTechTreeString("TagName_" + tag, tag.c_str()); +} + +string AttackBoost::getDesc(bool translatedValue) const { + Lang &lang = Lang::getInstance(); + string str = ""; + string indent = " "; + if (enabled) { + if (boostUnitList.empty() == false) { + str += "\n" + lang.getString("Effects") + ":\n"; + } + + str += indent + lang.getString("effectRadius") + ": " + intToStr(radius) + + "\n"; + if (allowMultipleBoosts == false) { + string allowIt = lang.getString("No"); + if (allowMultipleBoosts == true) + allowIt = lang.getString("False"); + str += indent + lang.getString("allowMultiBoost") + ": " + allowIt + "\n"; } - else - return ""; -} - -void AttackBoost::loadGame(const XmlNode *rootNode, Faction *faction, const SkillType *skillType) { - const XmlNode *attackBoostNode = rootNode->getChild("AttackBoost"); - - enabled = (attackBoostNode->getAttribute("enabled")->getIntValue() != 0); - allowMultipleBoosts = (attackBoostNode->getAttribute("allowMultipleBoosts")->getIntValue() != 0); - radius = attackBoostNode->getAttribute("radius")->getIntValue(); - targetType = static_cast(attackBoostNode->getAttribute("targetType")->getIntValue()); - - if(attackBoostNode->hasChild("UnitType") == true) { - vector attackBoostNodeList = attackBoostNode->getChildList("UnitType"); - for(unsigned int i = 0; i < attackBoostNodeList.size(); ++i) { - XmlNode *node = attackBoostNodeList[i]; - - string unitTypeName = node->getAttribute("name")->getValue(); - const UnitType *unitType = faction->getType()->getUnitType(unitTypeName); - if(unitType != NULL) { - boostUnitList.insert(unitType); - } - } - } - if(attackBoostNode->hasChild("tag")) { - vector tagNodeList = attackBoostNode->getChildList("tag"); - for(unsigned int i = 0; i < tagNodeList.size(); ++i) { - XmlNode *node = tagNodeList[i]; - string tagName = node->getAttribute("name")->getValue(); - tags.insert(tagName); - } - } - //boostUpgrade.loadGame(attackBoostNode,faction); - boostUpgrade = skillType->getAttackBoost()->boostUpgrade; - - unitParticleSystemTypeForSourceUnit = new UnitParticleSystemType(); - unitParticleSystemTypeForSourceUnit->loadGame(attackBoostNode); - - unitParticleSystemTypeForAffectedUnit = new UnitParticleSystemType(); - unitParticleSystemTypeForAffectedUnit->loadGame(attackBoostNode); - - includeSelf = (attackBoostNode->getAttribute("includeSelf")->getIntValue() != 0); - name = attackBoostNode->getAttribute("name")->getValue(); + str += boostUpgrade.getDesc(translatedValue); + + if (targetType == abtAlly) { + str += lang.getString("AffectedUnitsFromTeam") + ":\n"; + } else if (targetType == abtFoe) { + str += lang.getString("AffectedUnitsFromFoe") + ":\n"; + } else if (targetType == abtFaction) { + str += lang.getString("AffectedUnitsFromYourFaction") + ":\n"; + } else if (targetType == abtUnitTypes) { + str += lang.getString("AffectedUnitsFromAll") + ":\n"; + } else if (targetType == abtAll) { + str += lang.getString("AffectedUnitsFromAll") + ":\n"; + } + + if (boostUnitList.empty() && tags.empty()) { + str += lang.getString("All") + "\n"; + } else { + // We want the output to be sorted, so convert the set to a vector and + // sort that + std::vector outputUnits(boostUnitList.begin(), + boostUnitList.end()); + std::sort(outputUnits.begin(), outputUnits.end(), UnitTypeSorter()); + + vector::iterator unitIter; + for (unitIter = outputUnits.begin(); unitIter != outputUnits.end(); + ++unitIter) { + const UnitType *unit = *unitIter; + str += indent + unit->getName(translatedValue) + "\n"; + } + + // Do the same for tags + std::vector outputTags(tags.begin(), tags.end()); + std::sort(outputTags.begin(), outputTags.end()); + + vector::iterator tagIter; + for (tagIter = outputTags.begin(); tagIter != outputTags.end(); + ++tagIter) { + string tag = *tagIter; + str += indent + + lang.getString("TagDesc", + (translatedValue == true ? "" : "english")) + + " " + getTagName(tag, translatedValue) + "\n"; + } + } + + return str; + } else + return ""; +} + +void AttackBoost::loadGame(const XmlNode *rootNode, Faction *faction, + const SkillType *skillType) { + const XmlNode *attackBoostNode = rootNode->getChild("AttackBoost"); + + enabled = (attackBoostNode->getAttribute("enabled")->getIntValue() != 0); + allowMultipleBoosts = + (attackBoostNode->getAttribute("allowMultipleBoosts")->getIntValue() != + 0); + radius = attackBoostNode->getAttribute("radius")->getIntValue(); + targetType = static_cast( + attackBoostNode->getAttribute("targetType")->getIntValue()); + + if (attackBoostNode->hasChild("UnitType") == true) { + vector attackBoostNodeList = + attackBoostNode->getChildList("UnitType"); + for (unsigned int i = 0; i < attackBoostNodeList.size(); ++i) { + XmlNode *node = attackBoostNodeList[i]; + + string unitTypeName = node->getAttribute("name")->getValue(); + const UnitType *unitType = faction->getType()->getUnitType(unitTypeName); + if (unitType != NULL) { + boostUnitList.insert(unitType); + } + } + } + if (attackBoostNode->hasChild("tag")) { + vector tagNodeList = attackBoostNode->getChildList("tag"); + for (unsigned int i = 0; i < tagNodeList.size(); ++i) { + XmlNode *node = tagNodeList[i]; + string tagName = node->getAttribute("name")->getValue(); + tags.insert(tagName); + } + } + // boostUpgrade.loadGame(attackBoostNode,faction); + boostUpgrade = skillType->getAttackBoost()->boostUpgrade; + + unitParticleSystemTypeForSourceUnit = new UnitParticleSystemType(); + unitParticleSystemTypeForSourceUnit->loadGame(attackBoostNode); + + unitParticleSystemTypeForAffectedUnit = new UnitParticleSystemType(); + unitParticleSystemTypeForAffectedUnit->loadGame(attackBoostNode); + + includeSelf = + (attackBoostNode->getAttribute("includeSelf")->getIntValue() != 0); + name = attackBoostNode->getAttribute("name")->getValue(); } void AttackBoost::saveGame(XmlNode *rootNode) const { - std::map mapTagReplacements; - XmlNode *attackBoostNode = rootNode->addChild("AttackBoost"); - -// bool enabled; - attackBoostNode->addAttribute("enabled",intToStr(enabled), mapTagReplacements); -// bool allowMultipleBoosts; - attackBoostNode->addAttribute("allowMultipleBoosts",intToStr(allowMultipleBoosts), mapTagReplacements); -// int radius; - attackBoostNode->addAttribute("radius",intToStr(radius), mapTagReplacements); -// AttackBoostTargetType targetType; - attackBoostNode->addAttribute("targetType",intToStr(targetType), mapTagReplacements); -// vector boostUnitList; - std::set::iterator unitIter; - for (unitIter = boostUnitList.begin(); unitIter != boostUnitList.end(); ++unitIter) { - const UnitType *unit = *unitIter; - XmlNode *unitTypeNode = attackBoostNode->addChild("UnitType"); - unitTypeNode->addAttribute("name",unit->getName(false), mapTagReplacements); - } - std::set::iterator tagIter; - for (tagIter = tags.begin(); tagIter != tags.end(); ++tagIter) { - string tag = *tagIter; - XmlNode *unitTypeNode = attackBoostNode->addChild("tag"); - unitTypeNode->addAttribute("name", tag, mapTagReplacements); - } -// UpgradeTypeBase boostUpgrade; - boostUpgrade.saveGame(attackBoostNode); -// UnitParticleSystemType *unitParticleSystemTypeForSourceUnit; - if(unitParticleSystemTypeForSourceUnit != NULL) { - unitParticleSystemTypeForSourceUnit->saveGame(attackBoostNode); - } -// UnitParticleSystemType *unitParticleSystemTypeForAffectedUnit; - if(unitParticleSystemTypeForAffectedUnit != NULL) { - unitParticleSystemTypeForAffectedUnit->saveGame(attackBoostNode); - } - -// bool includeSelf; - attackBoostNode->addAttribute("includeSelf",intToStr(includeSelf), mapTagReplacements); -// string name; - attackBoostNode->addAttribute("name",name, mapTagReplacements); + std::map mapTagReplacements; + XmlNode *attackBoostNode = rootNode->addChild("AttackBoost"); + + // bool enabled; + attackBoostNode->addAttribute("enabled", intToStr(enabled), + mapTagReplacements); + // bool allowMultipleBoosts; + attackBoostNode->addAttribute( + "allowMultipleBoosts", intToStr(allowMultipleBoosts), mapTagReplacements); + // int radius; + attackBoostNode->addAttribute("radius", intToStr(radius), mapTagReplacements); + // AttackBoostTargetType targetType; + attackBoostNode->addAttribute("targetType", intToStr(targetType), + mapTagReplacements); + // vector boostUnitList; + std::set::iterator unitIter; + for (unitIter = boostUnitList.begin(); unitIter != boostUnitList.end(); + ++unitIter) { + const UnitType *unit = *unitIter; + XmlNode *unitTypeNode = attackBoostNode->addChild("UnitType"); + unitTypeNode->addAttribute("name", unit->getName(false), + mapTagReplacements); + } + std::set::iterator tagIter; + for (tagIter = tags.begin(); tagIter != tags.end(); ++tagIter) { + string tag = *tagIter; + XmlNode *unitTypeNode = attackBoostNode->addChild("tag"); + unitTypeNode->addAttribute("name", tag, mapTagReplacements); + } + // UpgradeTypeBase boostUpgrade; + boostUpgrade.saveGame(attackBoostNode); + // UnitParticleSystemType *unitParticleSystemTypeForSourceUnit; + if (unitParticleSystemTypeForSourceUnit != NULL) { + unitParticleSystemTypeForSourceUnit->saveGame(attackBoostNode); + } + // UnitParticleSystemType *unitParticleSystemTypeForAffectedUnit; + if (unitParticleSystemTypeForAffectedUnit != NULL) { + unitParticleSystemTypeForAffectedUnit->saveGame(attackBoostNode); + } + + // bool includeSelf; + attackBoostNode->addAttribute("includeSelf", intToStr(includeSelf), + mapTagReplacements); + // string name; + attackBoostNode->addAttribute("name", name, mapTagReplacements); } // ===================================================== // class SkillSound // ===================================================== -SkillSound::SkillSound(){ - startTime=0.0f; -} -SkillSound::~SkillSound() -{ - deleteValues(soundContainer.getSounds().begin(), soundContainer.getSounds().end()); - startTime=0.0f; - //soundContainer +SkillSound::SkillSound() { startTime = 0.0f; } +SkillSound::~SkillSound() { + deleteValues(soundContainer.getSounds().begin(), + soundContainer.getSounds().end()); + startTime = 0.0f; + // soundContainer } // ===================================================== // class SkillType // ===================================================== SkillType::~SkillType() { - while(!skillSoundList.empty()) { - delete skillSoundList.back(); - skillSoundList.pop_back(); - } - //remove unitParticleSystemTypes - while(!unitParticleSystemTypes.empty()) { - delete unitParticleSystemTypes.back(); - unitParticleSystemTypes.pop_back(); - } -} - -const XmlNode * SkillType::findAttackBoostDetails(string attackBoostName, - const XmlNode *attackBoostsNode,const XmlNode *attackBoostNode) { - const XmlNode *result = attackBoostNode; - - if(attackBoostsNode != NULL && attackBoostName != "") { - for(int i = 0; i < (int)attackBoostsNode->getChildCount(); ++i) { - const XmlNode *abn= attackBoostsNode->getChild("attack-boost", i); - - string sharedName = abn->getAttribute("name")->getRestrictedValue(); - if(sharedName == attackBoostName) { - result = abn; - break; - } - } - - } + while (!skillSoundList.empty()) { + delete skillSoundList.back(); + skillSoundList.pop_back(); + } + // remove unitParticleSystemTypes + while (!unitParticleSystemTypes.empty()) { + delete unitParticleSystemTypes.back(); + unitParticleSystemTypes.pop_back(); + } +} + +const XmlNode * +SkillType::findAttackBoostDetails(string attackBoostName, + const XmlNode *attackBoostsNode, + const XmlNode *attackBoostNode) { + const XmlNode *result = attackBoostNode; + + if (attackBoostsNode != NULL && attackBoostName != "") { + for (int i = 0; i < (int)attackBoostsNode->getChildCount(); ++i) { + const XmlNode *abn = attackBoostsNode->getChild("attack-boost", i); + + string sharedName = abn->getAttribute("name")->getRestrictedValue(); + if (sharedName == attackBoostName) { + result = abn; + break; + } + } + } + + return result; +} + +void SkillType::loadAttackBoost( + const XmlNode *attackBoostsNode, const XmlNode *attackBoostNode, + const FactionType *ft, string parentLoader, const string &dir, + string currentPath, + std::map>> &loadedFileList, + const TechTree *tt) { + + attackBoost.enabled = true; + if (attackBoostNode->hasAttribute("name") == true) { + attackBoost.name = + attackBoostNode->getAttribute("name")->getRestrictedValue(); + + attackBoostNode = findAttackBoostDetails(attackBoost.name, attackBoostsNode, + attackBoostNode); + } else { + attackBoost.name = + "attack-boost-autoname-" + intToStr(getNextAttackBoostId()); + } + string targetType = + attackBoostNode->getChild("target")->getAttribute("value")->getValue(); + + attackBoost.allowMultipleBoosts = false; + if (attackBoostNode->hasChild("allow-multiple-boosts") == true) { + attackBoost.allowMultipleBoosts = + attackBoostNode->getChild("allow-multiple-boosts") + ->getAttribute("value") + ->getBoolValue(); + } + + attackBoost.radius = + attackBoostNode->getChild("radius")->getAttribute("value")->getIntValue(); + + attackBoost.includeSelf = false; + if (attackBoostNode->getChild("target")->hasAttribute("include-self") == + true) { + attackBoost.includeSelf = attackBoostNode->getChild("target") + ->getAttribute("include-self") + ->getBoolValue(); + } + + if (targetType == "ally") { + attackBoost.targetType = abtAlly; + } else if (targetType == "foe") { + attackBoost.targetType = abtFoe; + } else if (targetType == "faction") { + attackBoost.targetType = abtFaction; + } else if (targetType == "unit-types") { + attackBoost.targetType = abtUnitTypes; + } else if (targetType == "all") { + attackBoost.targetType = abtAll; + } else { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "Unsupported target [%s] specified for attack boost for skill " + "[%s] in [%s]", + targetType.c_str(), name.c_str(), parentLoader.c_str()); + throw megaglest_runtime_error(szBuf, true); + } + + // Load the regular targets + const XmlNode *targetNode = attackBoostNode->getChild("target"); + vector targetNodes = targetNode->getChildList("unit-type"); + for (size_t i = 0; i < targetNodes.size(); ++i) { + string unitName = + targetNodes.at(i)->getAttribute("name")->getRestrictedValue(); + attackBoost.boostUnitList.insert(ft->getUnitType(unitName)); + } + + // Load tags + vector tagNodes = targetNode->getChildList("tag"); + for (size_t i = 0; i < tagNodes.size(); ++i) { + string unitName = + tagNodes.at(i)->getAttribute("name")->getRestrictedValue(); + attackBoost.tags.insert(unitName); + } + + attackBoost.boostUpgrade.load(attackBoostNode, attackBoost.name); + if (attackBoostNode->hasChild("particles") == true) { + const XmlNode *particleNode = attackBoostNode->getChild("particles"); + bool particleEnabled = particleNode->getAttribute("value")->getBoolValue(); + if (particleEnabled == true) { + if (particleNode->hasChild("originator-particle-file") == true) { + const XmlNode *particleFileNode = + particleNode->getChild("originator-particle-file"); + string path = + particleFileNode->getAttribute("path")->getRestrictedValue(); + attackBoost.unitParticleSystemTypeForSourceUnit = + new UnitParticleSystemType(); + attackBoost.unitParticleSystemTypeForSourceUnit->load( + particleFileNode, dir, currentPath + path, &Renderer::getInstance(), + loadedFileList, parentLoader, tt->getPath()); + loadedFileList[currentPath + path].push_back(make_pair( + parentLoader, + particleFileNode->getAttribute("path")->getRestrictedValue())); + } + if (particleNode->hasChild("affected-particle-file") == true) { + const XmlNode *particleFileNode = + particleNode->getChild("affected-particle-file"); + string path = + particleFileNode->getAttribute("path")->getRestrictedValue(); + attackBoost.unitParticleSystemTypeForAffectedUnit = + new UnitParticleSystemType(); + attackBoost.unitParticleSystemTypeForAffectedUnit->load( + particleFileNode, dir, currentPath + path, &Renderer::getInstance(), + loadedFileList, parentLoader, tt->getPath()); + loadedFileList[currentPath + path].push_back(make_pair( + parentLoader, + particleFileNode->getAttribute("path")->getRestrictedValue())); + } + } + } +} + +void SkillType::load( + const XmlNode *sn, const XmlNode *attackBoostsNode, const string &dir, + const TechTree *tt, const FactionType *ft, + std::map>> &loadedFileList, + string parentLoader) { + // name + name = sn->getChild("name")->getAttribute("value")->getRestrictedValue(); + + // ep cost + if (sn->hasChild("ep-cost") == true) { + mpCost = sn->getChild("ep-cost")->getAttribute("value")->getIntValue(); + } else { + mpCost = 0; + } + + if (sn->hasChild("hp-cost") == true) { + hpCost = sn->getChild("hp-cost")->getAttribute("value")->getIntValue(); + } else { + hpCost = 0; + } + + // speed + if (sn->hasChild("speed") == true) { + speed = sn->getChild("speed")->getAttribute("value")->getIntValue(); + } else { + speed = 0; + } + + // anim speed + if (sn->hasChild("anim-speed") == true) { + animSpeed = + sn->getChild("anim-speed")->getAttribute("value")->getIntValue(); + } else { + animSpeed = 0; + } + + // model + string currentPath = dir; + endPathWithSlash(currentPath); + + animationRandomCycleMaxcount = -1; + if (sn->hasChild("animation-random-cycle-maxcount") == true) { + const XmlNode *randomCycleCountNode = + sn->getChild("animation-random-cycle-maxcount"); + animationRandomCycleMaxcount = + randomCycleCountNode->getAttribute("value")->getIntValue(); + } + + if (sn->hasChild("animation") == true) { + // string path= + // sn->getChild("animation")->getAttribute("path")->getRestrictedValue(currentPath); + vector animationList = sn->getChildList("animation"); + for (unsigned int i = 0; i < animationList.size(); ++i) { + string path = animationList[i]->getAttribute("path")->getRestrictedValue( + currentPath); + if (fileExists(path) == true) { + Model *animation = Renderer::getInstance().newModel( + rsGame, path, false, &loadedFileList, &parentLoader); + loadedFileList[path].push_back(make_pair( + parentLoader, + animationList[i]->getAttribute("path")->getRestrictedValue())); + + animations.push_back(animation); + // printf("**FOUND ANIMATION [%s]\n",path.c_str()); + + AnimationAttributes animationAttributeList; + if (animationList[i]->getAttribute("minHp", false) != NULL && + animationList[i]->getAttribute("maxHp", false) != NULL) { + animationAttributeList.fromHp = + animationList[i]->getAttribute("minHp")->getIntValue(); + animationAttributeList.toHp = + animationList[i]->getAttribute("maxHp")->getIntValue(); + } + animationAttributes.push_back(animationAttributeList); + } else { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line %d] ERROR CANNOT LOAD MODEL " + "[%s] for parentLoader [%s]\n", + __FILE__, __FUNCTION__, __LINE__, path.c_str(), + parentLoader.c_str()); + throw megaglest_runtime_error("Error: cannot load model [" + path + + "] for skill [" + name + "] ", + true); + } + } + if (animations.empty() == true) { + throw megaglest_runtime_error("Error no animations found for skill [" + + name + "] for parentLoader [" + + parentLoader + "]", + true); + } + } + + // particles + if (sn->hasChild("particles")) { + const XmlNode *particleNode = sn->getChild("particles"); + bool particleEnabled = particleNode->getAttribute("value")->getBoolValue(); + if (particleEnabled) { + for (int i = 0; i < (int)particleNode->getChildCount(); ++i) { + const XmlNode *particleFileNode = + particleNode->getChild("particle-file", i); + string path = + particleFileNode->getAttribute("path")->getRestrictedValue(); + UnitParticleSystemType *unitParticleSystemType = + new UnitParticleSystemType(); + unitParticleSystemType->load(particleFileNode, dir, currentPath + path, + &Renderer::getInstance(), loadedFileList, + parentLoader, tt->getPath()); + + if (particleNode->getChild(i)->hasAttribute("start-time")) { + // printf("*NOTE particle system type has start-time + // [%f]\n",particleNode->getAttribute("start-time")->getFloatValue()); + unitParticleSystemType->setStartTime(particleNode->getChild(i) + ->getAttribute("start-time") + ->getFloatValue()); + } else if (particleNode->hasAttribute("start-time")) { + // printf("*NOTE particle system type has start-time + // [%f]\n",particleNode->getAttribute("start-time")->getFloatValue()); + unitParticleSystemType->setStartTime( + particleNode->getAttribute("start-time")->getFloatValue()); + } - return result; -} + if (particleNode->getChild(i)->hasAttribute("end-time")) { + // printf("*NOTE particle system type has start-time + // [%f]\n",particleNode->getAttribute("start-time")->getFloatValue()); + unitParticleSystemType->setEndTime(particleNode->getChild(i) + ->getAttribute("end-time") + ->getFloatValue()); + } else if (particleNode->hasAttribute("end-time")) { + // printf("*NOTE particle system type has end-time + // [%f]\n",particleNode->getAttribute("end-time")->getFloatValue()); + unitParticleSystemType->setEndTime( + particleNode->getAttribute("end-time")->getFloatValue()); + } -void SkillType::loadAttackBoost(const XmlNode *attackBoostsNode, const XmlNode *attackBoostNode, - const FactionType *ft, string parentLoader, const string & dir, - string currentPath, std::map > > & loadedFileList, - const TechTree *tt) { + if (particleNode->getChild(i)->hasAttribute("minHp") && + particleNode->getChild(i)->hasAttribute("maxHp")) { + unitParticleSystemType->setMinmaxEnabled(true); + unitParticleSystemType->setMinHp( + particleNode->getChild(i)->getAttribute("minHp")->getIntValue()); + unitParticleSystemType->setMaxHp( + particleNode->getChild(i)->getAttribute("maxHp")->getIntValue()); + + if (particleNode->getChild(i)->hasAttribute("ispercentbased")) { + unitParticleSystemType->setMinmaxIsPercent( + particleNode->getChild(i) + ->getAttribute("ispercentbased") + ->getBoolValue()); + } + } - attackBoost.enabled = true; - if(attackBoostNode->hasAttribute("name") == true) { - attackBoost.name = attackBoostNode->getAttribute("name")->getRestrictedValue(); + loadedFileList[currentPath + path].push_back(make_pair( + parentLoader, + particleFileNode->getAttribute("path")->getRestrictedValue())); + unitParticleSystemTypes.push_back(unitParticleSystemType); + } - attackBoostNode = findAttackBoostDetails(attackBoost.name,attackBoostsNode,attackBoostNode); + // printf("Load skill particles line: %d size: + // %d\n",__LINE__,(int)unitParticleSystemTypes.size()); } - else { - attackBoost.name = "attack-boost-autoname-" + intToStr(getNextAttackBoostId()); + } + + // sound + vector soundNodeList = sn->getChildList("sound"); + for (unsigned int i = 0; i < soundNodeList.size(); ++i) { + const XmlNode *soundNode = soundNodeList[i]; + if (soundNode->getAttribute("enabled")->getBoolValue()) { + float soundStartTime = + soundNode->getAttribute("start-time")->getFloatValue(); + SkillSound *skillSound = new SkillSound(); + skillSound->setStartTime(soundStartTime); + + skillSound->getSoundContainer()->resize((int)soundNode->getChildCount()); + skillSoundList.push_back(skillSound); + for (int i = 0; i < (int)soundNode->getChildCount(); ++i) { + const XmlNode *soundFileNode = soundNode->getChild("sound-file", i); + string path = soundFileNode->getAttribute("path")->getRestrictedValue( + currentPath, true); + + StaticSound *sound = new StaticSound(); + sound->load(path); + loadedFileList[path].push_back(make_pair( + parentLoader, + soundFileNode->getAttribute("path")->getRestrictedValue())); + (*skillSound->getSoundContainer())[i] = sound; + } } - string targetType = attackBoostNode->getChild("target")->getAttribute("value")->getValue(); - - attackBoost.allowMultipleBoosts = false; - if(attackBoostNode->hasChild("allow-multiple-boosts") == true) { - attackBoost.allowMultipleBoosts = attackBoostNode->getChild("allow-multiple-boosts")->getAttribute("value")->getBoolValue(); + } + + // attack-boost + if (sn->hasChild("attack-boost") == true) { + // printf("$$FOUND ATTACK BOOST FOR [%s]\n",parentLoader.c_str()); + const XmlNode *attackBoostNode = sn->getChild("attack-boost"); + loadAttackBoost(attackBoostsNode, attackBoostNode, ft, parentLoader, dir, + currentPath, loadedFileList, tt); + } + + shake = false; + shakeIntensity = 50; + shakeDuration = 300; + shakeStartTime = 0.0f; + shakeSelfEnabled = false; + shakeSelfVisible = true; + shakeSelfInCameraView = false; + shakeSelfCameraAffected = false; + shakeTeamEnabled = false; + shakeTeamVisible = true; + shakeTeamInCameraView = false; + shakeTeamCameraAffected = false; + shakeEnemyEnabled = false; + shakeEnemyVisible = true; + shakeEnemyInCameraView = false; + shakeEnemyCameraAffected = false; + + if (sn->hasChild("shake")) { + XmlNode *shakeNode = sn->getChild("shake"); + shake = shakeNode->getAttribute("enabled")->getBoolValue(); + shakeIntensity = shakeNode->getAttribute("intensity")->getIntValue(); + shakeDuration = shakeNode->getAttribute("duration")->getIntValue(); + if (shakeNode->hasAttribute("start-time")) { + shakeStartTime = shakeNode->getAttribute("start-time")->getFloatValue(); } - - attackBoost.radius = attackBoostNode->getChild("radius")->getAttribute("value")->getIntValue(); - - attackBoost.includeSelf = false; - if(attackBoostNode->getChild("target")->hasAttribute("include-self") == true) { - attackBoost.includeSelf = attackBoostNode->getChild("target")->getAttribute("include-self")->getBoolValue(); + if (shakeNode->hasChild("self")) { + shakeSelfEnabled = + shakeNode->getChild("enemy")->getAttribute("enabled")->getBoolValue(); + shakeSelfVisible = + shakeNode->getChild("self")->getAttribute("visible")->getBoolValue(); + shakeSelfInCameraView = shakeNode->getChild("self") + ->getAttribute("in-camera-view") + ->getBoolValue(); + shakeSelfCameraAffected = shakeNode->getChild("self") + ->getAttribute("camera-distance-affected") + ->getBoolValue(); } - - if(targetType == "ally") { - attackBoost.targetType = abtAlly; + if (shakeNode->hasChild("team")) { + shakeTeamEnabled = + shakeNode->getChild("enemy")->getAttribute("enabled")->getBoolValue(); + shakeTeamVisible = + shakeNode->getChild("team")->getAttribute("visible")->getBoolValue(); + shakeTeamInCameraView = shakeNode->getChild("team") + ->getAttribute("in-camera-view") + ->getBoolValue(); + shakeTeamCameraAffected = shakeNode->getChild("team") + ->getAttribute("camera-distance-affected") + ->getBoolValue(); } - else if(targetType == "foe") { - attackBoost.targetType = abtFoe; - } - else if(targetType == "faction") { - attackBoost.targetType = abtFaction; - } - else if(targetType == "unit-types") { - attackBoost.targetType = abtUnitTypes; - } - else if(targetType == "all") { - attackBoost.targetType = abtAll; - } - else { - char szBuf[8096] = ""; - snprintf(szBuf, 8096,"Unsupported target [%s] specified for attack boost for skill [%s] in [%s]", targetType.c_str(), name.c_str(), parentLoader.c_str()); - throw megaglest_runtime_error(szBuf,true); - } - - // Load the regular targets - const XmlNode *targetNode = attackBoostNode->getChild("target"); - vector targetNodes = targetNode->getChildList("unit-type"); - for(size_t i = 0;i < targetNodes.size(); ++i) { - string unitName = targetNodes.at(i)->getAttribute("name")->getRestrictedValue(); - attackBoost.boostUnitList.insert(ft->getUnitType(unitName)); - } - - // Load tags - vector tagNodes = targetNode->getChildList("tag"); - for(size_t i = 0;i < tagNodes.size(); ++i) { - string unitName = tagNodes.at(i)->getAttribute("name")->getRestrictedValue(); - attackBoost.tags.insert(unitName); - } - - attackBoost.boostUpgrade.load(attackBoostNode,attackBoost.name); - if(attackBoostNode->hasChild("particles") == true) { - const XmlNode *particleNode = attackBoostNode->getChild("particles"); - bool particleEnabled = particleNode->getAttribute("value")->getBoolValue(); - if(particleEnabled == true) { - if(particleNode->hasChild("originator-particle-file") == true){ - const XmlNode *particleFileNode = particleNode->getChild("originator-particle-file"); - string path = particleFileNode->getAttribute("path")->getRestrictedValue(); - attackBoost.unitParticleSystemTypeForSourceUnit = new UnitParticleSystemType(); - attackBoost.unitParticleSystemTypeForSourceUnit->load(particleFileNode, dir, currentPath + path, &Renderer::getInstance(), loadedFileList, parentLoader, tt->getPath()); - loadedFileList[currentPath + path].push_back(make_pair(parentLoader, particleFileNode->getAttribute("path")->getRestrictedValue())); - } - if(particleNode->hasChild("affected-particle-file") == true) { - const XmlNode *particleFileNode = particleNode->getChild("affected-particle-file"); - string path = particleFileNode->getAttribute("path")->getRestrictedValue(); - attackBoost.unitParticleSystemTypeForAffectedUnit = new UnitParticleSystemType(); - attackBoost.unitParticleSystemTypeForAffectedUnit->load(particleFileNode, dir, currentPath + path, &Renderer::getInstance(), loadedFileList, parentLoader, tt->getPath()); - loadedFileList[currentPath + path].push_back(make_pair(parentLoader, particleFileNode->getAttribute("path")->getRestrictedValue())); - } - } + if (shakeNode->hasChild("enemy")) { + shakeEnemyEnabled = + shakeNode->getChild("enemy")->getAttribute("enabled")->getBoolValue(); + shakeEnemyVisible = + shakeNode->getChild("enemy")->getAttribute("visible")->getBoolValue(); + shakeEnemyInCameraView = shakeNode->getChild("enemy") + ->getAttribute("in-camera-view") + ->getBoolValue(); + shakeEnemyCameraAffected = shakeNode->getChild("enemy") + ->getAttribute("camera-distance-affected") + ->getBoolValue(); } + + // visible-for (team, self,all, team-and-visible, self-and-visible, + // all-and-visible ) + } } -void SkillType::load(const XmlNode *sn, const XmlNode *attackBoostsNode, - const string &dir, const TechTree *tt, const FactionType *ft, - std::map > > &loadedFileList, - string parentLoader) { - //name - name= sn->getChild("name")->getAttribute("value")->getRestrictedValue(); - - //ep cost - if(sn->hasChild("ep-cost") == true) { - mpCost = sn->getChild("ep-cost")->getAttribute("value")->getIntValue(); - } - else { - mpCost = 0; - } - - if (sn->hasChild("hp-cost") == true) { - hpCost = sn->getChild("hp-cost")->getAttribute("value")->getIntValue(); - } - else { - hpCost = 0; - } - - //speed - if(sn->hasChild("speed") == true) { - speed = sn->getChild("speed")->getAttribute("value")->getIntValue(); - } - else { - speed = 0; - } - - //anim speed - if(sn->hasChild("anim-speed") == true) { - animSpeed = sn->getChild("anim-speed")->getAttribute("value")->getIntValue(); - } - else { - animSpeed = 0; - } - - //model - string currentPath = dir; - endPathWithSlash(currentPath); - - animationRandomCycleMaxcount = -1; - if(sn->hasChild("animation-random-cycle-maxcount") == true) { - const XmlNode *randomCycleCountNode = sn->getChild("animation-random-cycle-maxcount"); - animationRandomCycleMaxcount = randomCycleCountNode->getAttribute("value")->getIntValue(); - } - - if(sn->hasChild("animation") == true) { - //string path= sn->getChild("animation")->getAttribute("path")->getRestrictedValue(currentPath); - vector animationList = sn->getChildList("animation"); - for(unsigned int i = 0; i < animationList.size(); ++i) { - string path= animationList[i]->getAttribute("path")->getRestrictedValue(currentPath); - if(fileExists(path) == true) { - Model *animation= Renderer::getInstance().newModel(rsGame, path, false, &loadedFileList, &parentLoader); - loadedFileList[path].push_back(make_pair(parentLoader,animationList[i]->getAttribute("path")->getRestrictedValue())); - - animations.push_back(animation); - //printf("**FOUND ANIMATION [%s]\n",path.c_str()); - - AnimationAttributes animationAttributeList; - if(animationList[i]->getAttribute("minHp",false) != NULL && animationList[i]->getAttribute("maxHp",false) != NULL) { - animationAttributeList.fromHp = animationList[i]->getAttribute("minHp")->getIntValue(); - animationAttributeList.toHp = animationList[i]->getAttribute("maxHp")->getIntValue(); - } - animationAttributes.push_back(animationAttributeList); - } - else { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line %d] ERROR CANNOT LOAD MODEL [%s] for parentLoader [%s]\n",__FILE__,__FUNCTION__,__LINE__,path.c_str(),parentLoader.c_str()); - throw megaglest_runtime_error("Error: cannot load model ["+path+"] for skill ["+name+"] ",true); - } - } - if(animations.empty() == true) { - throw megaglest_runtime_error("Error no animations found for skill ["+name+"] for parentLoader ["+parentLoader+"]",true); - } - } - - //particles - if(sn->hasChild("particles")) { - const XmlNode *particleNode= sn->getChild("particles"); - bool particleEnabled= particleNode->getAttribute("value")->getBoolValue(); - if(particleEnabled) { - for(int i = 0; i < (int)particleNode->getChildCount(); ++i) { - const XmlNode *particleFileNode= particleNode->getChild("particle-file", i); - string path= particleFileNode->getAttribute("path")->getRestrictedValue(); - UnitParticleSystemType *unitParticleSystemType= new UnitParticleSystemType(); - unitParticleSystemType->load(particleFileNode, dir, currentPath + path, &Renderer::getInstance(), - loadedFileList,parentLoader,tt->getPath()); - - if (particleNode->getChild(i)->hasAttribute("start-time")) { - //printf("*NOTE particle system type has start-time [%f]\n",particleNode->getAttribute("start-time")->getFloatValue()); - unitParticleSystemType->setStartTime(particleNode->getChild(i)->getAttribute("start-time")->getFloatValue()); - } else if (particleNode->hasAttribute("start-time")) { - //printf("*NOTE particle system type has start-time [%f]\n",particleNode->getAttribute("start-time")->getFloatValue()); - unitParticleSystemType->setStartTime(particleNode->getAttribute("start-time")->getFloatValue()); - } - - if (particleNode->getChild(i)->hasAttribute("end-time")) { - //printf("*NOTE particle system type has start-time [%f]\n",particleNode->getAttribute("start-time")->getFloatValue()); - unitParticleSystemType->setEndTime(particleNode->getChild(i)->getAttribute("end-time")->getFloatValue()); - } else if (particleNode->hasAttribute("end-time")) { - //printf("*NOTE particle system type has end-time [%f]\n",particleNode->getAttribute("end-time")->getFloatValue()); - unitParticleSystemType->setEndTime(particleNode->getAttribute("end-time")->getFloatValue()); - } - - if(particleNode->getChild(i)->hasAttribute("minHp") && particleNode->getChild(i)->hasAttribute("maxHp")) { - unitParticleSystemType->setMinmaxEnabled(true); - unitParticleSystemType->setMinHp(particleNode->getChild(i)->getAttribute("minHp")->getIntValue()); - unitParticleSystemType->setMaxHp(particleNode->getChild(i)->getAttribute("maxHp")->getIntValue()); - - if(particleNode->getChild(i)->hasAttribute("ispercentbased")) { - unitParticleSystemType->setMinmaxIsPercent(particleNode->getChild(i)->getAttribute("ispercentbased")->getBoolValue()); - } - } - - loadedFileList[currentPath + path].push_back(make_pair(parentLoader,particleFileNode->getAttribute("path")->getRestrictedValue())); - unitParticleSystemTypes.push_back(unitParticleSystemType); - } - - //printf("Load skill particles line: %d size: %d\n",__LINE__,(int)unitParticleSystemTypes.size()); - } - } - - //sound - vector soundNodeList = sn->getChildList("sound"); - for(unsigned int i = 0; i < soundNodeList.size(); ++i) { - const XmlNode *soundNode= soundNodeList[i]; - if(soundNode->getAttribute("enabled")->getBoolValue()) { - float soundStartTime= soundNode->getAttribute("start-time")->getFloatValue(); - SkillSound *skillSound = new SkillSound(); - skillSound->setStartTime(soundStartTime); - - skillSound->getSoundContainer()->resize((int)soundNode->getChildCount()); - skillSoundList.push_back(skillSound); - for(int i = 0; i < (int)soundNode->getChildCount(); ++i) { - const XmlNode *soundFileNode= soundNode->getChild("sound-file", i); - string path= soundFileNode->getAttribute("path")->getRestrictedValue(currentPath, true); - - StaticSound *sound= new StaticSound(); - sound->load(path); - loadedFileList[path].push_back(make_pair(parentLoader,soundFileNode->getAttribute("path")->getRestrictedValue())); - (*skillSound->getSoundContainer())[i]= sound; - } - } - } - - - // attack-boost - if(sn->hasChild("attack-boost") == true) { - //printf("$$FOUND ATTACK BOOST FOR [%s]\n",parentLoader.c_str()); - const XmlNode *attackBoostNode = sn->getChild("attack-boost"); - loadAttackBoost(attackBoostsNode, attackBoostNode, ft, parentLoader, dir, currentPath, loadedFileList, tt); - } - - shake=false; - shakeIntensity=50; - shakeDuration=300; - shakeStartTime=0.0f; - shakeSelfEnabled=false; - shakeSelfVisible=true; - shakeSelfInCameraView=false; - shakeSelfCameraAffected=false; - shakeTeamEnabled=false; - shakeTeamVisible=true; - shakeTeamInCameraView=false; - shakeTeamCameraAffected=false; - shakeEnemyEnabled=false; - shakeEnemyVisible=true; - shakeEnemyInCameraView=false; - shakeEnemyCameraAffected=false; - - if (sn->hasChild("shake")) { - XmlNode *shakeNode=sn->getChild("shake"); - shake= shakeNode->getAttribute("enabled")->getBoolValue(); - shakeIntensity= shakeNode->getAttribute("intensity")->getIntValue(); - shakeDuration= shakeNode->getAttribute("duration")->getIntValue(); - if (shakeNode->hasAttribute("start-time")) { - shakeStartTime= shakeNode->getAttribute("start-time")->getFloatValue(); - } - if (shakeNode->hasChild("self")) { - shakeSelfEnabled= shakeNode->getChild("enemy")->getAttribute("enabled")->getBoolValue(); - shakeSelfVisible= shakeNode->getChild("self")->getAttribute("visible")->getBoolValue(); - shakeSelfInCameraView= shakeNode->getChild("self")->getAttribute("in-camera-view")->getBoolValue(); - shakeSelfCameraAffected= shakeNode->getChild("self")->getAttribute("camera-distance-affected")->getBoolValue(); - } - if (shakeNode->hasChild("team")) { - shakeTeamEnabled= shakeNode->getChild("enemy")->getAttribute("enabled")->getBoolValue(); - shakeTeamVisible= shakeNode->getChild("team")->getAttribute("visible")->getBoolValue(); - shakeTeamInCameraView= shakeNode->getChild("team")->getAttribute("in-camera-view")->getBoolValue(); - shakeTeamCameraAffected= shakeNode->getChild("team")->getAttribute("camera-distance-affected")->getBoolValue(); - } - if (shakeNode->hasChild("enemy")) { - shakeEnemyEnabled= shakeNode->getChild("enemy")->getAttribute("enabled")->getBoolValue(); - shakeEnemyVisible= shakeNode->getChild("enemy")->getAttribute("visible")->getBoolValue(); - shakeEnemyInCameraView= shakeNode->getChild("enemy")->getAttribute("in-camera-view")->getBoolValue(); - shakeEnemyCameraAffected= shakeNode->getChild("enemy")->getAttribute("camera-distance-affected")->getBoolValue(); - } - - //visible-for (team, self,all, team-and-visible, self-and-visible, all-and-visible ) - - } -} - -bool SkillType::CanCycleNextRandomAnimation(const int *animationRandomCycleCount) const { - bool result = true; - if(animations.size() > 1) { - if( animationRandomCycleMaxcount >= 0 && - animationRandomCycleCount != NULL && - *animationRandomCycleCount >= animationRandomCycleMaxcount) { - result = false; - } - } - return result; +bool SkillType::CanCycleNextRandomAnimation( + const int *animationRandomCycleCount) const { + bool result = true; + if (animations.size() > 1) { + if (animationRandomCycleMaxcount >= 0 && + animationRandomCycleCount != NULL && + *animationRandomCycleCount >= animationRandomCycleMaxcount) { + result = false; + } + } + return result; } const AnimationAttributes SkillType::getAnimationAttribute(int index) const { - return animationAttributes[index]; + return animationAttributes[index]; } Model *SkillType::getAnimation(float animProgress, const Unit *unit, - int *lastAnimationIndex, int *animationRandomCycleCount) const { - int modelIndex = 0; - //printf("Count [%d] animProgress = [%f] for skill [%s] animationRandomCycleCount = %d\n",animations.size(),animProgress,name.c_str(),*animationRandomCycleCount); - if(animations.size() > 1) { - //printf("animProgress = [%f] for skill [%s] animationRandomCycleCount = %d\n",animProgress,name.c_str(),*animationRandomCycleCount); - - if(lastAnimationIndex) { - modelIndex = *lastAnimationIndex; - } - if(modelIndex < 0 || animProgress > 1.0f) { - bool canCycle = CanCycleNextRandomAnimation(animationRandomCycleCount); - if(canCycle == true) { - vector filteredAnimations; - bool foundSpecificAnimation = false; - if(unit != NULL) { - for(unsigned int i = 0; i < animationAttributes.size(); ++i) { - const AnimationAttributes &attributes = animationAttributes[i]; - if(attributes.fromHp != 0 || attributes.toHp != 0) { - if(unit->getHp() >= attributes.fromHp && unit->getHp() <= attributes.toHp) { - //modelIndex = i; - foundSpecificAnimation = true; - filteredAnimations.push_back(i); - //printf("SELECTING Model index = %d [%s] model attributes [%d to %d] for unit [%s - %d] with HP = %d\n",i,animations[modelIndex]->getFileName().c_str(),attributes.fromHp,attributes.toHp,unit->getType()->getName().c_str(),unit->getId(),unit->getHp()); - //break; - } - } - } - // Need to make sure the filtered list does NOT include any - // models with min/max hp - if(foundSpecificAnimation == false) { - for(unsigned int i = 0; i < animationAttributes.size(); ++i) { - const AnimationAttributes &attributes = animationAttributes[i]; - if(attributes.fromHp == 0 && attributes.toHp == 0) { - //modelIndex = i; - foundSpecificAnimation = true; - filteredAnimations.push_back(i); - //printf("SELECTING Model index = %d [%s] model attributes [%d to %d] for unit [%s - %d] with HP = %d\n",i,animations[modelIndex]->getFileName().c_str(),attributes.fromHp,attributes.toHp,unit->getType()->getName().c_str(),unit->getId(),unit->getHp()); - //break; - } - } - } - } - - if(foundSpecificAnimation == false) { - //int modelIndex = random.randRange(0,animations.size()-1); - Chrono seed(true); - srand((unsigned int)seed.getCurTicks() + (unit != NULL ? unit->getId() : 0)); - - modelIndex = rand() % animations.size(); - - //const AnimationAttributes &attributes = animationAttributes[modelIndex]; - //printf("SELECTING RANDOM Model index = %d [%s] model attributes [%d to %d] for unit [%s - %d] with HP = %d\n",modelIndex,animations[modelIndex]->getFileName().c_str(),attributes.fromHp,attributes.toHp,unit->getType()->getName().c_str(),unit->getId(),unit->getHp()); - } - else { - Chrono seed(true); - srand((unsigned int)seed.getCurTicks() + unit->getId()); - - int filteredModelIndex = rand() % filteredAnimations.size(); - modelIndex = filteredAnimations[filteredModelIndex]; - } - } - } - } - if(lastAnimationIndex) { - if(*lastAnimationIndex != modelIndex) { - //printf("Switching model from [%s] to [%s]\n",(*lastAnimationIndex >= 0 ? animations[*lastAnimationIndex]->getFileName().c_str() : "none"),animations[modelIndex]->getFileName().c_str()); - } - *lastAnimationIndex = modelIndex; - } - - //printf("!!RETURN ANIMATION [%d / %d]\n",modelIndex,animations.size()-1); - return animations[modelIndex]; + int *lastAnimationIndex, + int *animationRandomCycleCount) const { + int modelIndex = 0; + // printf("Count [%d] animProgress = [%f] for skill [%s] + // animationRandomCycleCount = + // %d\n",animations.size(),animProgress,name.c_str(),*animationRandomCycleCount); + if (animations.size() > 1) { + // printf("animProgress = [%f] for skill [%s] animationRandomCycleCount = + // %d\n",animProgress,name.c_str(),*animationRandomCycleCount); + + if (lastAnimationIndex) { + modelIndex = *lastAnimationIndex; + } + if (modelIndex < 0 || animProgress > 1.0f) { + bool canCycle = CanCycleNextRandomAnimation(animationRandomCycleCount); + if (canCycle == true) { + vector filteredAnimations; + bool foundSpecificAnimation = false; + if (unit != NULL) { + for (unsigned int i = 0; i < animationAttributes.size(); ++i) { + const AnimationAttributes &attributes = animationAttributes[i]; + if (attributes.fromHp != 0 || attributes.toHp != 0) { + if (unit->getHp() >= attributes.fromHp && + unit->getHp() <= attributes.toHp) { + // modelIndex = i; + foundSpecificAnimation = true; + filteredAnimations.push_back(i); + // printf("SELECTING Model index = %d [%s] model attributes [%d + // to %d] for unit [%s - %d] with HP = + // %d\n",i,animations[modelIndex]->getFileName().c_str(),attributes.fromHp,attributes.toHp,unit->getType()->getName().c_str(),unit->getId(),unit->getHp()); + // break; + } + } + } + // Need to make sure the filtered list does NOT include any + // models with min/max hp + if (foundSpecificAnimation == false) { + for (unsigned int i = 0; i < animationAttributes.size(); ++i) { + const AnimationAttributes &attributes = animationAttributes[i]; + if (attributes.fromHp == 0 && attributes.toHp == 0) { + // modelIndex = i; + foundSpecificAnimation = true; + filteredAnimations.push_back(i); + // printf("SELECTING Model index = %d [%s] model attributes [%d + // to %d] for unit [%s - %d] with HP = + // %d\n",i,animations[modelIndex]->getFileName().c_str(),attributes.fromHp,attributes.toHp,unit->getType()->getName().c_str(),unit->getId(),unit->getHp()); + // break; + } + } + } + } + + if (foundSpecificAnimation == false) { + // int modelIndex = random.randRange(0,animations.size()-1); + Chrono seed(true); + srand((unsigned int)seed.getCurTicks() + + (unit != NULL ? unit->getId() : 0)); + + modelIndex = rand() % animations.size(); + + // const AnimationAttributes &attributes = + // animationAttributes[modelIndex]; printf("SELECTING RANDOM Model + // index = %d [%s] model attributes [%d to %d] for unit [%s - %d] with + // HP = + // %d\n",modelIndex,animations[modelIndex]->getFileName().c_str(),attributes.fromHp,attributes.toHp,unit->getType()->getName().c_str(),unit->getId(),unit->getHp()); + } else { + Chrono seed(true); + srand((unsigned int)seed.getCurTicks() + unit->getId()); + + int filteredModelIndex = rand() % filteredAnimations.size(); + modelIndex = filteredAnimations[filteredModelIndex]; + } + } + } + } + if (lastAnimationIndex) { + if (*lastAnimationIndex != modelIndex) { + // printf("Switching model from [%s] to [%s]\n",(*lastAnimationIndex >= 0 + // ? animations[*lastAnimationIndex]->getFileName().c_str() : + // "none"),animations[modelIndex]->getFileName().c_str()); + } + *lastAnimationIndex = modelIndex; + } + + // printf("!!RETURN ANIMATION [%d / %d]\n",modelIndex,animations.size()-1); + return animations[modelIndex]; } string SkillType::skillClassToStr(SkillClass skillClass) { - switch(skillClass){ - case scStop: return "Stop"; - case scMove: return "Move"; - case scAttack: return "Attack"; - case scHarvest: return "Harvest"; - case scRepair: return "Repair"; - case scBuild: return "Build"; - case scDie: return "Die"; - case scBeBuilt: return "Be Built"; - case scProduce: return "Produce"; - case scUpgrade: return "Upgrade"; - case scFogOfWar: return "Fog Of War"; - default: - assert(false); - break; - } - return ""; + switch (skillClass) { + case scStop: + return "Stop"; + case scMove: + return "Move"; + case scAttack: + return "Attack"; + case scHarvest: + return "Harvest"; + case scRepair: + return "Repair"; + case scBuild: + return "Build"; + case scDie: + return "Die"; + case scBeBuilt: + return "Be Built"; + case scProduce: + return "Produce"; + case scUpgrade: + return "Upgrade"; + case scFogOfWar: + return "Fog Of War"; + default: + assert(false); + break; + } + return ""; } string SkillType::fieldToStr(Field field) { - Lang &lang= Lang::getInstance(); - string fieldName = ""; - switch(field) { - case fLand: - if(lang.hasString("FieldLand") == true) { - fieldName = lang.getString("FieldLand"); - } - else { - fieldName = "Land"; - } - //return "Land"; - return lang.getTilesetString("FieldLandName",fieldName.c_str()); - - case fAir: - if(lang.hasString("FieldAir") == true) { - fieldName = lang.getString("FieldAir"); - } - else { - fieldName = "Air"; - } - - //return "Air"; - return lang.getTilesetString("FieldAirName",fieldName.c_str()); - default: - assert(false); - break; - } - return ""; + Lang &lang = Lang::getInstance(); + string fieldName = ""; + switch (field) { + case fLand: + if (lang.hasString("FieldLand") == true) { + fieldName = lang.getString("FieldLand"); + } else { + fieldName = "Land"; + } + // return "Land"; + return lang.getTilesetString("FieldLandName", fieldName.c_str()); + + case fAir: + if (lang.hasString("FieldAir") == true) { + fieldName = lang.getString("FieldAir"); + } else { + fieldName = "Air"; + } + + // return "Air"; + return lang.getTilesetString("FieldAirName", fieldName.c_str()); + default: + assert(false); + break; + } + return ""; } void SkillType::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *skillTypeNode = rootNode->addChild("SkillType"); - -// SkillClass skillClass; - skillTypeNode->addAttribute("skillClass",intToStr(skillClass), mapTagReplacements); -// string name; - skillTypeNode->addAttribute("name",name, mapTagReplacements); -// int mpCost; - skillTypeNode->addAttribute("mpCost",intToStr(mpCost), mapTagReplacements); -// int hpCost; - skillTypeNode->addAttribute("hpCost",intToStr(hpCost), mapTagReplacements); -// int speed; - skillTypeNode->addAttribute("speed",intToStr(speed), mapTagReplacements); -// int animSpeed; - skillTypeNode->addAttribute("animSpeed",intToStr(animSpeed), mapTagReplacements); -// int animationRandomCycleMaxcount; - skillTypeNode->addAttribute("animationRandomCycleMaxcount",intToStr(animationRandomCycleMaxcount), mapTagReplacements); -// vector animations; -// vector animationAttributes; -// -// SoundContainer sounds; -// float soundStartTime; -// skillTypeNode->addAttribute("soundStartTime",floatToStr(soundStartTime,6), mapTagReplacements); -// RandomGen random; - skillTypeNode->addAttribute("random",intToStr(random.getLastNumber()), mapTagReplacements); -// AttackBoost attackBoost; - attackBoost.saveGame(skillTypeNode); -// static int nextAttackBoostId; - skillTypeNode->addAttribute("nextAttackBoostId",intToStr(nextAttackBoostId), mapTagReplacements); -// UnitParticleSystemTypes unitParticleSystemTypes; - for(UnitParticleSystemTypes::iterator it = unitParticleSystemTypes.begin(); it != unitParticleSystemTypes.end(); ++it) { - (*it)->saveGame(skillTypeNode); - } + std::map mapTagReplacements; + XmlNode *skillTypeNode = rootNode->addChild("SkillType"); + + // SkillClass skillClass; + skillTypeNode->addAttribute("skillClass", intToStr(skillClass), + mapTagReplacements); + // string name; + skillTypeNode->addAttribute("name", name, mapTagReplacements); + // int mpCost; + skillTypeNode->addAttribute("mpCost", intToStr(mpCost), mapTagReplacements); + // int hpCost; + skillTypeNode->addAttribute("hpCost", intToStr(hpCost), mapTagReplacements); + // int speed; + skillTypeNode->addAttribute("speed", intToStr(speed), mapTagReplacements); + // int animSpeed; + skillTypeNode->addAttribute("animSpeed", intToStr(animSpeed), + mapTagReplacements); + // int animationRandomCycleMaxcount; + skillTypeNode->addAttribute("animationRandomCycleMaxcount", + intToStr(animationRandomCycleMaxcount), + mapTagReplacements); + // vector animations; + // vector animationAttributes; + // + // SoundContainer sounds; + // float soundStartTime; + // skillTypeNode->addAttribute("soundStartTime",floatToStr(soundStartTime,6), + // mapTagReplacements); RandomGen random; + skillTypeNode->addAttribute("random", intToStr(random.getLastNumber()), + mapTagReplacements); + // AttackBoost attackBoost; + attackBoost.saveGame(skillTypeNode); + // static int nextAttackBoostId; + skillTypeNode->addAttribute("nextAttackBoostId", intToStr(nextAttackBoostId), + mapTagReplacements); + // UnitParticleSystemTypes unitParticleSystemTypes; + for (UnitParticleSystemTypes::iterator it = unitParticleSystemTypes.begin(); + it != unitParticleSystemTypes.end(); ++it) { + (*it)->saveGame(skillTypeNode); + } } // ===================================================== // class StopSkillType // ===================================================== -StopSkillType::StopSkillType(){ - skillClass= scStop; -} +StopSkillType::StopSkillType() { skillClass = scStop; } -string StopSkillType::toString(bool translatedValue) const{ - if(translatedValue == false) { - return "Stop"; - } - return Lang::getInstance().getString("Stop"); +string StopSkillType::toString(bool translatedValue) const { + if (translatedValue == false) { + return "Stop"; + } + return Lang::getInstance().getString("Stop"); } // ===================================================== // class MoveSkillType // ===================================================== -MoveSkillType::MoveSkillType(){ - skillClass= scMove; -} +MoveSkillType::MoveSkillType() { skillClass = scMove; } -string MoveSkillType::toString(bool translatedValue) const{ - if(translatedValue == false) { - return "Move"; - } +string MoveSkillType::toString(bool translatedValue) const { + if (translatedValue == false) { + return "Move"; + } - return Lang::getInstance().getString("Move"); + return Lang::getInstance().getString("Move"); } -int MoveSkillType::getTotalSpeed(const TotalUpgrade *totalUpgrade) const{ - int result = speed + totalUpgrade->getMoveSpeed(this); - result = max(0,result); - return result; +int MoveSkillType::getTotalSpeed(const TotalUpgrade *totalUpgrade) const { + int result = speed + totalUpgrade->getMoveSpeed(this); + result = max(0, result); + return result; } // ===================================================== // class AttackSkillType // ===================================================== -//varios +// varios AttackSkillType::AttackSkillType() { - skillClass= scAttack; - attackType= NULL; - projectile= false; - splash= false; - splashRadius= 0; - spawnUnit=""; - spawnUnitcount=0; - spawnUnitAtTarget=false; - splashParticleSystemType= NULL; - - for(int i = 0; i < fieldCount; ++i) { - attackFields[i]= false; - } - - attackStrength=0; - attackVar=0; - attackRange=0; - attackStartTime=0; - splashDamageAll=false; + skillClass = scAttack; + attackType = NULL; + projectile = false; + splash = false; + splashRadius = 0; + spawnUnit = ""; + spawnUnitcount = 0; + spawnUnitAtTarget = false; + splashParticleSystemType = NULL; + + for (int i = 0; i < fieldCount; ++i) { + attackFields[i] = false; + } + + attackStrength = 0; + attackVar = 0; + attackRange = 0; + attackStartTime = 0; + splashDamageAll = false; } AttackSkillType::~AttackSkillType() { - deleteValues(projectileTypes.begin(), projectileTypes.end()); + deleteValues(projectileTypes.begin(), projectileTypes.end()); + + delete splashParticleSystemType; + splashParticleSystemType = NULL; + deleteValues(projSounds.getSounds().begin(), projSounds.getSounds().end()); + projSounds.clearSounds(); +} + +void AttackSkillType::load( + const XmlNode *sn, const XmlNode *attackBoostsNode, const string &dir, + const TechTree *tt, const FactionType *ft, + std::map>> &loadedFileList, + string parentLoader) { + SkillType::load(sn, attackBoostsNode, dir, tt, ft, loadedFileList, + parentLoader); + + string currentPath = dir; + endPathWithSlash(currentPath); + + // misc + std::vector attackStrengthXMLTags; + attackStrengthXMLTags.push_back("attack-strenght"); + attackStrengthXMLTags.push_back("attack-strength"); + attackStrength = sn->getChildWithAliases(attackStrengthXMLTags) + ->getAttribute("value") + ->getIntValue(); + attackVar = sn->getChild("attack-var")->getAttribute("value")->getIntValue(); + + if (attackVar < 0) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "The attack skill has an INVALID attack var value which is < 0 " + "[%d] in file [%s]!", + attackVar, dir.c_str()); + throw megaglest_runtime_error(szBuf, true); + } + + attackRange = + sn->getChild("attack-range")->getAttribute("value")->getIntValue(); + string attackTypeName = + sn->getChild("attack-type")->getAttribute("value")->getRestrictedValue(); + attackType = tt->getAttackType(attackTypeName); + attackStartTime = + sn->getChild("attack-start-time")->getAttribute("value")->getFloatValue(); + + if (sn->hasChild("unit")) { + spawnUnit = sn->getChild("unit")->getAttribute("value")->getValue(); + spawnUnitcount = + sn->getChild("unit")->getAttribute("amount")->getIntValue(); + if (sn->getChild("unit")->hasAttribute("spawnAtTarget")) { + spawnUnitAtTarget = + sn->getChild("unit")->getAttribute("spawnAtTarget")->getBoolValue(); + } else { + spawnUnitAtTarget = false; + } + } else { + spawnUnit = ""; + spawnUnitcount = 0; + spawnUnitAtTarget = false; + } + // attack fields + const XmlNode *attackFieldsNode = sn->getChild("attack-fields"); + for (int i = 0; i < (int)attackFieldsNode->getChildCount(); ++i) { + const XmlNode *fieldNode = attackFieldsNode->getChild("field", i); + string fieldName = fieldNode->getAttribute("value")->getRestrictedValue(); + if (fieldName == "land") { + attackFields[fLand] = true; + } else if (fieldName == "air") { + attackFields[fAir] = true; + } else { + throw megaglest_runtime_error( + "Not a valid field: " + fieldName + ": " + dir, true); + } + } + + if (sn->hasChild("projectile")) { + // projectile -- backward compatible old behaviour with only one projectile + const XmlNode *projectileNode = sn->getChild("projectile"); + projectile = projectileNode->getAttribute("value")->getBoolValue(); + if (projectile) { + // create new projectile + ProjectileType *projectileType = new ProjectileType(); + // only add this projectile if there is an enabled particlesystem + // projectileTypes.push_back(projectileType); + projectileType->setAttackStartTime(attackStartTime); + projectileType->setDamagePercentage(100); + // proj particle + if (projectileNode->hasChild("particle")) { + const XmlNode *particleNode = projectileNode->getChild("particle"); + bool particleEnabled = + particleNode->getAttribute("value")->getBoolValue(); + if (particleEnabled) { + projectileTypes.push_back(projectileType); + string path = + particleNode->getAttribute("path")->getRestrictedValue(); + ParticleSystemTypeProjectile *projectileParticleSystemType = + new ParticleSystemTypeProjectile(); + projectileParticleSystemType->load( + particleNode, dir, currentPath + path, &Renderer::getInstance(), + loadedFileList, parentLoader, tt->getPath()); + loadedFileList[currentPath + path].push_back(make_pair( + parentLoader, + particleNode->getAttribute("path")->getRestrictedValue())); + projectileType->setProjectileParticleSystemType( + projectileParticleSystemType); + } else { + delete projectileType; + } + } else { + delete projectileType; + } + // proj sounds + const XmlNode *soundNode = projectileNode->getChild("sound"); + if (soundNode->getAttribute("enabled")->getBoolValue()) { + + projSounds.resize((int)soundNode->getChildCount()); + for (int i = 0; i < (int)soundNode->getChildCount(); ++i) { + const XmlNode *soundFileNode = soundNode->getChild("sound-file", i); + string path = soundFileNode->getAttribute("path")->getRestrictedValue( + currentPath, true); + // printf("\n\n\n\n!@#$ ---> parentLoader [%s] path [%s] nodeValue + // [%s] i = + // %d",parentLoader.c_str(),path.c_str(),soundFileNode->getAttribute("path")->getRestrictedValue().c_str(),i); + + StaticSound *sound = new StaticSound(); + sound->load(path); + loadedFileList[path].push_back(make_pair( + parentLoader, + soundFileNode->getAttribute("path")->getRestrictedValue())); + projSounds[i] = sound; + } + } + } + } else { + const XmlNode *projectilesNode = sn->getChild("projectiles"); + vector projectilesNodeList = + projectilesNode->getChildList("projectile"); + int totalDamagePercentage = 0; + for (unsigned int i = 0; i < projectilesNodeList.size(); ++i) { + const XmlNode *projectileNode = projectilesNodeList[i]; + ProjectileType *projectileType = new ProjectileType(); + projectileType->load(projectileNode, dir, tt->getPath(), loadedFileList, + parentLoader); + totalDamagePercentage += projectileType->getDamagePercentage(); + projectileTypes.push_back(projectileType); + projectile = true; + } - delete splashParticleSystemType; - splashParticleSystemType = NULL; - deleteValues(projSounds.getSounds().begin(), projSounds.getSounds().end()); - projSounds.clearSounds(); + if (totalDamagePercentage != 100) { + throw megaglest_runtime_error( + "Damages percentages of projectiles don't sum up to 100 %", true); + } + + if (sn->hasChild("hitsound") == true) { + // general hit sounds, individual ones can be set in projectiles + const XmlNode *soundNode = sn->getChild("hitsound"); + if (soundNode->getAttribute("enabled")->getBoolValue()) { + + projSounds.resize((int)soundNode->getChildCount()); + for (int i = 0; i < (int)soundNode->getChildCount(); ++i) { + const XmlNode *soundFileNode = soundNode->getChild("sound-file", i); + string path = soundFileNode->getAttribute("path")->getRestrictedValue( + currentPath, true); + // printf("\n\n\n\n!@#$ ---> parentLoader [%s] path [%s] nodeValue + // [%s] i = + // %d",parentLoader.c_str(),path.c_str(),soundFileNode->getAttribute("path")->getRestrictedValue().c_str(),i); + + StaticSound *sound = new StaticSound(); + sound->load(path); + loadedFileList[path].push_back(make_pair( + parentLoader, + soundFileNode->getAttribute("path")->getRestrictedValue())); + projSounds[i] = sound; + } + } + } + } + + // splash + const XmlNode *splashNode = sn->getChild("splash"); + splash = splashNode->getAttribute("value")->getBoolValue(); + if (splash) { + splashRadius = + splashNode->getChild("radius")->getAttribute("value")->getIntValue(); + splashDamageAll = splashNode->getChild("damage-all") + ->getAttribute("value") + ->getBoolValue(); + + // splash particle + const XmlNode *particleNode = splashNode->getChild("particle"); + bool particleEnabled = particleNode->getAttribute("value")->getBoolValue(); + if (particleEnabled) { + string path = particleNode->getAttribute("path")->getRestrictedValue(); + splashParticleSystemType = new ParticleSystemTypeSplash(); + splashParticleSystemType->load(particleNode, dir, currentPath + path, + &Renderer::getInstance(), loadedFileList, + parentLoader, tt->getPath()); + } + } } -void AttackSkillType::load(const XmlNode *sn, const XmlNode *attackBoostsNode, - const string &dir, const TechTree *tt, - const FactionType *ft, std::map > > &loadedFileList, - string parentLoader) { - SkillType::load(sn, attackBoostsNode,dir, tt, ft, loadedFileList, parentLoader); +int AttackSkillType::getTotalSpeed(const TotalUpgrade *totalUpgrade) const { + int result = speed + totalUpgrade->getAttackSpeed(this); + result = max(0, result); + return result; +} - string currentPath = dir; - endPathWithSlash(currentPath); +// Get the amount to boost the attack animation speed by (based on attack-speed +// upgrades) +int AttackSkillType::getAnimSpeedBoost(const TotalUpgrade *totalUpgrade) const { + // Same calculation as in TotalUpgrade::sum, but bypassing the use of the + // value list (which is for the attack speed, not animation speed) + if (totalUpgrade->getAttackRangeIsMultiplier()) { + return animSpeed * (totalUpgrade->getAttackSpeed(NULL) / (double)100); + } else { + return totalUpgrade->getAttackSpeed(NULL); + } +} - //misc - std::vector attackStrengthXMLTags; - attackStrengthXMLTags.push_back("attack-strenght"); - attackStrengthXMLTags.push_back("attack-strength"); - attackStrength= sn->getChildWithAliases(attackStrengthXMLTags)->getAttribute("value")->getIntValue(); - attackVar= sn->getChild("attack-var")->getAttribute("value")->getIntValue(); +string AttackSkillType::toString(bool translatedValue) const { + if (translatedValue == false) { + return "Attack"; + } - if(attackVar < 0) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"The attack skill has an INVALID attack var value which is < 0 [%d] in file [%s]!",attackVar,dir.c_str()); - throw megaglest_runtime_error(szBuf,true); - } + return Lang::getInstance().getString("Attack"); +} - attackRange= sn->getChild("attack-range")->getAttribute("value")->getIntValue(); - string attackTypeName= sn->getChild("attack-type")->getAttribute("value")->getRestrictedValue(); - attackType= tt->getAttackType(attackTypeName); - attackStartTime= sn->getChild("attack-start-time")->getAttribute("value")->getFloatValue(); - - if (sn->hasChild("unit")) { - spawnUnit = sn->getChild("unit")->getAttribute("value")->getValue(); - spawnUnitcount = sn->getChild("unit")->getAttribute("amount")->getIntValue(); - if(sn->getChild("unit")->hasAttribute("spawnAtTarget")) { - spawnUnitAtTarget = sn->getChild("unit")->getAttribute("spawnAtTarget")->getBoolValue(); - } else { - spawnUnitAtTarget = false; - } - } else { - spawnUnit = ""; - spawnUnitcount = 0; - spawnUnitAtTarget = false; - } - //attack fields - const XmlNode *attackFieldsNode= sn->getChild("attack-fields"); - for(int i=0; i < (int)attackFieldsNode->getChildCount(); ++i){ - const XmlNode *fieldNode= attackFieldsNode->getChild("field", i); - string fieldName= fieldNode->getAttribute("value")->getRestrictedValue(); - if(fieldName=="land"){ - attackFields[fLand]= true; - } - else if(fieldName=="air"){ - attackFields[fAir]= true; - } - else{ - throw megaglest_runtime_error("Not a valid field: "+fieldName+": "+ dir,true); - } - } - - if(sn->hasChild("projectile")){ - //projectile -- backward compatible old behaviour with only one projectile - const XmlNode *projectileNode= sn->getChild("projectile"); - projectile= projectileNode->getAttribute("value")->getBoolValue(); - if(projectile){ - // create new projectile - ProjectileType *projectileType = new ProjectileType(); - //only add this projectile if there is an enabled particlesystem - //projectileTypes.push_back(projectileType); - projectileType->setAttackStartTime(attackStartTime); - projectileType->setDamagePercentage(100); - //proj particle - if(projectileNode->hasChild("particle")){ - const XmlNode *particleNode= projectileNode->getChild("particle"); - bool particleEnabled= particleNode->getAttribute("value")->getBoolValue(); - if(particleEnabled) { - projectileTypes.push_back(projectileType); - string path= particleNode->getAttribute("path")->getRestrictedValue(); - ParticleSystemTypeProjectile* projectileParticleSystemType= new ParticleSystemTypeProjectile(); - projectileParticleSystemType->load(particleNode, dir, currentPath + path, - &Renderer::getInstance(), loadedFileList, parentLoader, - tt->getPath()); - loadedFileList[currentPath + path].push_back(make_pair(parentLoader,particleNode->getAttribute("path")->getRestrictedValue())); - projectileType->setProjectileParticleSystemType(projectileParticleSystemType); - } - else { - delete projectileType; - } - } - else { - delete projectileType; - } - //proj sounds - const XmlNode *soundNode= projectileNode->getChild("sound"); - if(soundNode->getAttribute("enabled")->getBoolValue()){ - - projSounds.resize((int)soundNode->getChildCount()); - for(int i=0; i < (int)soundNode->getChildCount(); ++i){ - const XmlNode *soundFileNode= soundNode->getChild("sound-file", i); - string path= soundFileNode->getAttribute("path")->getRestrictedValue(currentPath, true); - //printf("\n\n\n\n!@#$ ---> parentLoader [%s] path [%s] nodeValue [%s] i = %d",parentLoader.c_str(),path.c_str(),soundFileNode->getAttribute("path")->getRestrictedValue().c_str(),i); - - StaticSound *sound= new StaticSound(); - sound->load(path); - loadedFileList[path].push_back(make_pair(parentLoader,soundFileNode->getAttribute("path")->getRestrictedValue())); - projSounds[i]= sound; - } - } - } - } - else { - const XmlNode *projectilesNode= sn->getChild("projectiles"); - vector projectilesNodeList = projectilesNode->getChildList("projectile"); - int totalDamagePercentage=0; - for(unsigned int i = 0; i < projectilesNodeList.size(); ++i) { - const XmlNode *projectileNode= projectilesNodeList[i]; - ProjectileType *projectileType=new ProjectileType(); - projectileType->load(projectileNode,dir, tt->getPath(), loadedFileList, parentLoader); - totalDamagePercentage += projectileType->getDamagePercentage(); - projectileTypes.push_back(projectileType); - projectile=true; - } - - if(totalDamagePercentage!=100){ - throw megaglest_runtime_error("Damages percentages of projectiles don't sum up to 100 %",true); - } - - if(sn->hasChild("hitsound")==true){ - //general hit sounds, individual ones can be set in projectiles - const XmlNode *soundNode= sn->getChild("hitsound"); - if(soundNode->getAttribute("enabled")->getBoolValue()){ - - projSounds.resize((int)soundNode->getChildCount()); - for(int i=0; i < (int)soundNode->getChildCount(); ++i){ - const XmlNode *soundFileNode= soundNode->getChild("sound-file", i); - string path= soundFileNode->getAttribute("path")->getRestrictedValue(currentPath, true); - //printf("\n\n\n\n!@#$ ---> parentLoader [%s] path [%s] nodeValue [%s] i = %d",parentLoader.c_str(),path.c_str(),soundFileNode->getAttribute("path")->getRestrictedValue().c_str(),i); - - StaticSound *sound= new StaticSound(); - sound->load(path); - loadedFileList[path].push_back(make_pair(parentLoader,soundFileNode->getAttribute("path")->getRestrictedValue())); - projSounds[i]= sound; - } - } - } - } - - //splash - const XmlNode *splashNode= sn->getChild("splash"); - splash= splashNode->getAttribute("value")->getBoolValue(); - if(splash){ - splashRadius= splashNode->getChild("radius")->getAttribute("value")->getIntValue(); - splashDamageAll= splashNode->getChild("damage-all")->getAttribute("value")->getBoolValue(); - - //splash particle - const XmlNode *particleNode= splashNode->getChild("particle"); - bool particleEnabled= particleNode->getAttribute("value")->getBoolValue(); - if(particleEnabled){ - string path= particleNode->getAttribute("path")->getRestrictedValue(); - splashParticleSystemType= new ParticleSystemTypeSplash(); - splashParticleSystemType->load(particleNode, dir, currentPath + path, - &Renderer::getInstance(),loadedFileList, parentLoader, - tt->getPath()); - } - } -} - -int AttackSkillType::getTotalSpeed(const TotalUpgrade *totalUpgrade) const{ - int result = speed + totalUpgrade->getAttackSpeed(this); - result = max(0,result); - return result; -} - -// Get the amount to boost the attack animation speed by (based on attack-speed upgrades) -int AttackSkillType::getAnimSpeedBoost(const TotalUpgrade *totalUpgrade) const{ - // Same calculation as in TotalUpgrade::sum, but bypassing the use of the value - // list (which is for the attack speed, not animation speed) - if(totalUpgrade->getAttackRangeIsMultiplier()) { - return animSpeed * (totalUpgrade->getAttackSpeed(NULL) / (double)100); - } - else { - return totalUpgrade->getAttackSpeed(NULL); - } -} - -string AttackSkillType::toString(bool translatedValue) const{ - if(translatedValue == false) { - return "Attack"; - } - - return Lang::getInstance().getString("Attack"); -} - -//get totals -int AttackSkillType::getTotalAttackStrength(const TotalUpgrade *totalUpgrade) const{ - int result = attackStrength + totalUpgrade->getAttackStrength(this); - result = max(0,result); - return result; -} - -int AttackSkillType::getTotalAttackRange(const TotalUpgrade *totalUpgrade) const{ - int result = attackRange + totalUpgrade->getAttackRange(this); - result = max(0,result); - return result; +// get totals +int AttackSkillType::getTotalAttackStrength( + const TotalUpgrade *totalUpgrade) const { + int result = attackStrength + totalUpgrade->getAttackStrength(this); + result = max(0, result); + return result; +} + +int AttackSkillType::getTotalAttackRange( + const TotalUpgrade *totalUpgrade) const { + int result = attackRange + totalUpgrade->getAttackRange(this); + result = max(0, result); + return result; } void AttackSkillType::saveGame(XmlNode *rootNode) { - SkillType::saveGame(rootNode); - std::map mapTagReplacements; - XmlNode *attackSkillTypeNode = rootNode->addChild("AttackSkillType"); - -// int attackStrength; - attackSkillTypeNode->addAttribute("attackStrength",intToStr(attackStrength), mapTagReplacements); -// int attackVar; - attackSkillTypeNode->addAttribute("attackVar",intToStr(attackVar), mapTagReplacements); -// int attackRange; - attackSkillTypeNode->addAttribute("attackRange",intToStr(attackRange), mapTagReplacements); -// const AttackType *attackType; - if(attackType != NULL) { - attackSkillTypeNode->addAttribute("attackType",attackType->getName(false), mapTagReplacements); - } -// bool attackFields[fieldCount]; - for(unsigned int i = 0; i < fieldCount; ++i) { - XmlNode *attackFieldsNode = attackSkillTypeNode->addChild("attackFields"); - attackFieldsNode->addAttribute("key",intToStr(i), mapTagReplacements); - attackFieldsNode->addAttribute("value",intToStr(attackFields[i]), mapTagReplacements); - } -// float attackStartTime; - attackSkillTypeNode->addAttribute("attackStartTime",floatToStr(attackStartTime,6), mapTagReplacements); -// string spawnUnit; - attackSkillTypeNode->addAttribute("spawnUnit",spawnUnit, mapTagReplacements); -// int spawnUnitcount; - attackSkillTypeNode->addAttribute("spawnUnitcount",intToStr(spawnUnitcount), mapTagReplacements); -// bool spawnUnitAtTarget; - attackSkillTypeNode->addAttribute("spawnUnitAtTarget",intToStr(spawnUnitAtTarget), mapTagReplacements); -// bool projectile; - attackSkillTypeNode->addAttribute("projectile",intToStr(projectile), mapTagReplacements); -// ParticleSystemTypeProjectile* projectileParticleSystemType; -// save a skill_type ???? - // if(projectileParticleSystemType != NULL) { -// projectileParticleSystemType->saveGame(attackSkillTypeNode); -// } -// SoundContainer projSounds; -// -// bool splash; - attackSkillTypeNode->addAttribute("splash",intToStr(splash), mapTagReplacements); -// int splashRadius; - attackSkillTypeNode->addAttribute("splashRadius",intToStr(splashRadius), mapTagReplacements); -// bool splashDamageAll; - attackSkillTypeNode->addAttribute("splashDamageAll",intToStr(splashDamageAll), mapTagReplacements); -// ParticleSystemTypeSplash* splashParticleSystemType; - if(splashParticleSystemType != NULL) { - splashParticleSystemType->saveGame(attackSkillTypeNode); - } + SkillType::saveGame(rootNode); + std::map mapTagReplacements; + XmlNode *attackSkillTypeNode = rootNode->addChild("AttackSkillType"); + + // int attackStrength; + attackSkillTypeNode->addAttribute("attackStrength", intToStr(attackStrength), + mapTagReplacements); + // int attackVar; + attackSkillTypeNode->addAttribute("attackVar", intToStr(attackVar), + mapTagReplacements); + // int attackRange; + attackSkillTypeNode->addAttribute("attackRange", intToStr(attackRange), + mapTagReplacements); + // const AttackType *attackType; + if (attackType != NULL) { + attackSkillTypeNode->addAttribute("attackType", attackType->getName(false), + mapTagReplacements); + } + // bool attackFields[fieldCount]; + for (unsigned int i = 0; i < fieldCount; ++i) { + XmlNode *attackFieldsNode = attackSkillTypeNode->addChild("attackFields"); + attackFieldsNode->addAttribute("key", intToStr(i), mapTagReplacements); + attackFieldsNode->addAttribute("value", intToStr(attackFields[i]), + mapTagReplacements); + } + // float attackStartTime; + attackSkillTypeNode->addAttribute( + "attackStartTime", floatToStr(attackStartTime, 6), mapTagReplacements); + // string spawnUnit; + attackSkillTypeNode->addAttribute("spawnUnit", spawnUnit, mapTagReplacements); + // int spawnUnitcount; + attackSkillTypeNode->addAttribute("spawnUnitcount", intToStr(spawnUnitcount), + mapTagReplacements); + // bool spawnUnitAtTarget; + attackSkillTypeNode->addAttribute( + "spawnUnitAtTarget", intToStr(spawnUnitAtTarget), mapTagReplacements); + // bool projectile; + attackSkillTypeNode->addAttribute("projectile", intToStr(projectile), + mapTagReplacements); + // ParticleSystemTypeProjectile* projectileParticleSystemType; + // save a skill_type ???? + // if(projectileParticleSystemType != NULL) { + // projectileParticleSystemType->saveGame(attackSkillTypeNode); + // } + // SoundContainer projSounds; + // + // bool splash; + attackSkillTypeNode->addAttribute("splash", intToStr(splash), + mapTagReplacements); + // int splashRadius; + attackSkillTypeNode->addAttribute("splashRadius", intToStr(splashRadius), + mapTagReplacements); + // bool splashDamageAll; + attackSkillTypeNode->addAttribute( + "splashDamageAll", intToStr(splashDamageAll), mapTagReplacements); + // ParticleSystemTypeSplash* splashParticleSystemType; + if (splashParticleSystemType != NULL) { + splashParticleSystemType->saveGame(attackSkillTypeNode); + } } // ===================================================== // class BuildSkillType // ===================================================== -BuildSkillType::BuildSkillType(){ - skillClass= scBuild; -} +BuildSkillType::BuildSkillType() { skillClass = scBuild; } -string BuildSkillType::toString(bool translatedValue) const{ - if(translatedValue == false) { - return "Build"; - } +string BuildSkillType::toString(bool translatedValue) const { + if (translatedValue == false) { + return "Build"; + } - return Lang::getInstance().getString("Build"); + return Lang::getInstance().getString("Build"); } // ===================================================== // class HarvestSkillType // ===================================================== -HarvestSkillType::HarvestSkillType(){ - skillClass= scHarvest; -} +HarvestSkillType::HarvestSkillType() { skillClass = scHarvest; } -string HarvestSkillType::toString(bool translatedValue) const{ - if(translatedValue == false) { - return "Harvest"; - } +string HarvestSkillType::toString(bool translatedValue) const { + if (translatedValue == false) { + return "Harvest"; + } - return Lang::getInstance().getString("Harvest"); + return Lang::getInstance().getString("Harvest"); } // ===================================================== // class RepairSkillType // ===================================================== -RepairSkillType::RepairSkillType(){ - skillClass= scRepair; -} +RepairSkillType::RepairSkillType() { skillClass = scRepair; } -string RepairSkillType::toString(bool translatedValue) const{ - if(translatedValue == false) { - return "Repair"; - } +string RepairSkillType::toString(bool translatedValue) const { + if (translatedValue == false) { + return "Repair"; + } - return Lang::getInstance().getString("Repair"); + return Lang::getInstance().getString("Repair"); } // ===================================================== // class ProduceSkillType // ===================================================== -ProduceSkillType::ProduceSkillType(){ - skillClass= scProduce; - animProgressBound=false; +ProduceSkillType::ProduceSkillType() { + skillClass = scProduce; + animProgressBound = false; } -void ProduceSkillType::load(const XmlNode *sn, const XmlNode *attackBoostsNode, - const string &dir, const TechTree *tt, - const FactionType *ft, std::map > > &loadedFileList, - string parentLoader) { - SkillType::load(sn, attackBoostsNode,dir, tt, ft, loadedFileList, parentLoader); +void ProduceSkillType::load( + const XmlNode *sn, const XmlNode *attackBoostsNode, const string &dir, + const TechTree *tt, const FactionType *ft, + std::map>> &loadedFileList, + string parentLoader) { + SkillType::load(sn, attackBoostsNode, dir, tt, ft, loadedFileList, + parentLoader); - if(sn->hasChild("anim-progress-bound")){ - animProgressBound= sn->getChild("anim-progress-bound")->getAttribute("value")->getBoolValue(); - } - else { - animProgressBound=false; - } + if (sn->hasChild("anim-progress-bound")) { + animProgressBound = sn->getChild("anim-progress-bound") + ->getAttribute("value") + ->getBoolValue(); + } else { + animProgressBound = false; + } } +string ProduceSkillType::toString(bool translatedValue) const { + if (translatedValue == false) { + return "Produce"; + } -string ProduceSkillType::toString(bool translatedValue) const{ - if(translatedValue == false) { - return "Produce"; - } - - return Lang::getInstance().getString("Produce"); + return Lang::getInstance().getString("Produce"); } -int ProduceSkillType::getTotalSpeed(const TotalUpgrade *totalUpgrade) const{ - int result = speed + totalUpgrade->getProdSpeed(this); - result = max(0,result); - return result; +int ProduceSkillType::getTotalSpeed(const TotalUpgrade *totalUpgrade) const { + int result = speed + totalUpgrade->getProdSpeed(this); + result = max(0, result); + return result; } void ProduceSkillType::saveGame(XmlNode *rootNode) { - SkillType::saveGame(rootNode); - std::map mapTagReplacements; - XmlNode *produceSkillTypeNode = rootNode->addChild("ProduceSkillType"); + SkillType::saveGame(rootNode); + std::map mapTagReplacements; + XmlNode *produceSkillTypeNode = rootNode->addChild("ProduceSkillType"); - produceSkillTypeNode->addAttribute("animProgressBound",intToStr(animProgressBound), mapTagReplacements); + produceSkillTypeNode->addAttribute( + "animProgressBound", intToStr(animProgressBound), mapTagReplacements); } // ===================================================== // class UpgradeSkillType // ===================================================== -UpgradeSkillType::UpgradeSkillType(){ - skillClass= scUpgrade; - animProgressBound=false; +UpgradeSkillType::UpgradeSkillType() { + skillClass = scUpgrade; + animProgressBound = false; } -void UpgradeSkillType::load(const XmlNode *sn, const XmlNode *attackBoostsNode, - const string &dir, const TechTree *tt, - const FactionType *ft, std::map > > &loadedFileList, - string parentLoader) { - SkillType::load(sn, attackBoostsNode,dir, tt, ft, loadedFileList, parentLoader); +void UpgradeSkillType::load( + const XmlNode *sn, const XmlNode *attackBoostsNode, const string &dir, + const TechTree *tt, const FactionType *ft, + std::map>> &loadedFileList, + string parentLoader) { + SkillType::load(sn, attackBoostsNode, dir, tt, ft, loadedFileList, + parentLoader); - if(sn->hasChild("anim-progress-bound")){ - animProgressBound= sn->getChild("anim-progress-bound")->getAttribute("value")->getBoolValue(); - } - else { - animProgressBound=false; - } + if (sn->hasChild("anim-progress-bound")) { + animProgressBound = sn->getChild("anim-progress-bound") + ->getAttribute("value") + ->getBoolValue(); + } else { + animProgressBound = false; + } } -string UpgradeSkillType::toString(bool translatedValue) const{ - if(translatedValue == false) { - return "Upgrade"; - } +string UpgradeSkillType::toString(bool translatedValue) const { + if (translatedValue == false) { + return "Upgrade"; + } - return Lang::getInstance().getString("Upgrade"); + return Lang::getInstance().getString("Upgrade"); } -int UpgradeSkillType::getTotalSpeed(const TotalUpgrade *totalUpgrade) const{ - int result = speed + totalUpgrade->getProdSpeed(this); - result = max(0,result); - return result; +int UpgradeSkillType::getTotalSpeed(const TotalUpgrade *totalUpgrade) const { + int result = speed + totalUpgrade->getProdSpeed(this); + result = max(0, result); + return result; } void UpgradeSkillType::saveGame(XmlNode *rootNode) { - SkillType::saveGame(rootNode); - std::map mapTagReplacements; - XmlNode *upgradeSkillTypeNode = rootNode->addChild("UpgradeSkillType"); + SkillType::saveGame(rootNode); + std::map mapTagReplacements; + XmlNode *upgradeSkillTypeNode = rootNode->addChild("UpgradeSkillType"); - upgradeSkillTypeNode->addAttribute("animProgressBound",intToStr(animProgressBound), mapTagReplacements); + upgradeSkillTypeNode->addAttribute( + "animProgressBound", intToStr(animProgressBound), mapTagReplacements); } // ===================================================== // class BeBuiltSkillType // ===================================================== -BeBuiltSkillType::BeBuiltSkillType(){ - skillClass= scBeBuilt; - animProgressBound=false; +BeBuiltSkillType::BeBuiltSkillType() { + skillClass = scBeBuilt; + animProgressBound = false; } -void BeBuiltSkillType::load(const XmlNode *sn, const XmlNode *attackBoostsNode, - const string &dir, const TechTree *tt, - const FactionType *ft, std::map > > &loadedFileList, - string parentLoader) { - SkillType::load(sn, attackBoostsNode,dir, tt, ft, loadedFileList, parentLoader); +void BeBuiltSkillType::load( + const XmlNode *sn, const XmlNode *attackBoostsNode, const string &dir, + const TechTree *tt, const FactionType *ft, + std::map>> &loadedFileList, + string parentLoader) { + SkillType::load(sn, attackBoostsNode, dir, tt, ft, loadedFileList, + parentLoader); - if(sn->hasChild("anim-progress-bound")){ - animProgressBound= sn->getChild("anim-progress-bound")->getAttribute("value")->getBoolValue(); - } - else if(sn->hasChild("anim-hp-bound")){ // deprecated!!!! remove it when you see it after 15th July 2011 - animProgressBound= sn->getChild("anim-hp-bound")->getAttribute("value")->getBoolValue(); - } - else { - animProgressBound=false; - } + if (sn->hasChild("anim-progress-bound")) { + animProgressBound = sn->getChild("anim-progress-bound") + ->getAttribute("value") + ->getBoolValue(); + } else if (sn->hasChild("anim-hp-bound")) { // deprecated!!!! remove it when + // you see it after 15th July 2011 + animProgressBound = + sn->getChild("anim-hp-bound")->getAttribute("value")->getBoolValue(); + } else { + animProgressBound = false; + } } +string BeBuiltSkillType::toString(bool translatedValue) const { + if (translatedValue == false) { + return "Be built"; + } -string BeBuiltSkillType::toString(bool translatedValue) const{ - if(translatedValue == false) { - return "Be built"; - } - - return "Be built"; + return "Be built"; } void BeBuiltSkillType::saveGame(XmlNode *rootNode) { - SkillType::saveGame(rootNode); - std::map mapTagReplacements; - XmlNode *beBuiltSkillTypeNode = rootNode->addChild("BeBuiltSkillType"); + SkillType::saveGame(rootNode); + std::map mapTagReplacements; + XmlNode *beBuiltSkillTypeNode = rootNode->addChild("BeBuiltSkillType"); - beBuiltSkillTypeNode->addAttribute("animProgressBound",intToStr(animProgressBound), mapTagReplacements); + beBuiltSkillTypeNode->addAttribute( + "animProgressBound", intToStr(animProgressBound), mapTagReplacements); } // ===================================================== // class MorphSkillType // ===================================================== -MorphSkillType::MorphSkillType(){ - skillClass= scMorph; - animProgressBound=false; +MorphSkillType::MorphSkillType() { + skillClass = scMorph; + animProgressBound = false; } -void MorphSkillType::load(const XmlNode *sn, const XmlNode *attackBoostsNode, - const string &dir, const TechTree *tt, - const FactionType *ft, std::map > > &loadedFileList, - string parentLoader) { - SkillType::load(sn, attackBoostsNode,dir, tt, ft, loadedFileList, parentLoader); +void MorphSkillType::load( + const XmlNode *sn, const XmlNode *attackBoostsNode, const string &dir, + const TechTree *tt, const FactionType *ft, + std::map>> &loadedFileList, + string parentLoader) { + SkillType::load(sn, attackBoostsNode, dir, tt, ft, loadedFileList, + parentLoader); - if(sn->hasChild("anim-progress-bound")){ - animProgressBound= sn->getChild("anim-progress-bound")->getAttribute("value")->getBoolValue(); - } - else { - animProgressBound=false; - } + if (sn->hasChild("anim-progress-bound")) { + animProgressBound = sn->getChild("anim-progress-bound") + ->getAttribute("value") + ->getBoolValue(); + } else { + animProgressBound = false; + } } -string MorphSkillType::toString(bool translatedValue) const{ - if(translatedValue == false) { - return "Morph"; - } +string MorphSkillType::toString(bool translatedValue) const { + if (translatedValue == false) { + return "Morph"; + } - return "Morph"; + return "Morph"; } -int MorphSkillType::getTotalSpeed(const TotalUpgrade *totalUpgrade) const{ - int result = speed + totalUpgrade->getProdSpeed(this); - result = max(0,result); - return result; +int MorphSkillType::getTotalSpeed(const TotalUpgrade *totalUpgrade) const { + int result = speed + totalUpgrade->getProdSpeed(this); + result = max(0, result); + return result; } void MorphSkillType::saveGame(XmlNode *rootNode) { - SkillType::saveGame(rootNode); - std::map mapTagReplacements; - XmlNode *morphSkillTypeNode = rootNode->addChild("MorphSkillType"); + SkillType::saveGame(rootNode); + std::map mapTagReplacements; + XmlNode *morphSkillTypeNode = rootNode->addChild("MorphSkillType"); - morphSkillTypeNode->addAttribute("animProgressBound",intToStr(animProgressBound), mapTagReplacements); + morphSkillTypeNode->addAttribute( + "animProgressBound", intToStr(animProgressBound), mapTagReplacements); } // ===================================================== // class DieSkillType // ===================================================== -DieSkillType::DieSkillType(){ - skillClass= scDie; - fade=false; - spawn=false; - spawnStartTime=0; - spawnUnit=""; - spawnUnitcount=0; - spawnUnitHealthPercentMin=100; - spawnUnitHealthPercentMax=100; - spawnProbability=100; -} - -void DieSkillType::load(const XmlNode *sn, const XmlNode *attackBoostsNode, - const string &dir, const TechTree *tt, - const FactionType *ft, std::map > > &loadedFileList, - string parentLoader) { - SkillType::load(sn, attackBoostsNode,dir, tt, ft, loadedFileList, parentLoader); - - fade= sn->getChild("fade")->getAttribute("value")->getBoolValue(); - if(sn->hasChild("spawn")){ - const XmlNode *spawnNode= sn->getChild("spawn"); - spawn=true; - spawnStartTime=spawnNode->getAttribute("start-time")->getFloatValue(); - spawnUnit = spawnNode->getChild("unit")->getAttribute("value")->getValue(); - spawnUnitcount = spawnNode->hasChild("amount")?spawnNode->getChild("amount")->getAttribute("value")->getIntValue():0; - if(spawnNode->hasChild("health-percent")){ - spawnUnitHealthPercentMin = spawnNode->getChild("health-percent")->getAttribute("min")->getIntValue(); - spawnUnitHealthPercentMax = spawnNode->getChild("health-percent")->getAttribute("max")->getIntValue(); - } - spawnProbability = spawnNode->hasChild("probability")?spawnNode->getChild("probability")->getAttribute("value")->getIntValue():spawnProbability; - } // else keep defaults -} - -string DieSkillType::toString(bool translatedValue) const{ - if(translatedValue == false) { - return "Die"; - } - - return "Die"; +DieSkillType::DieSkillType() { + skillClass = scDie; + fade = false; + spawn = false; + spawnStartTime = 0; + spawnUnit = ""; + spawnUnitcount = 0; + spawnUnitHealthPercentMin = 100; + spawnUnitHealthPercentMax = 100; + spawnProbability = 100; +} + +void DieSkillType::load( + const XmlNode *sn, const XmlNode *attackBoostsNode, const string &dir, + const TechTree *tt, const FactionType *ft, + std::map>> &loadedFileList, + string parentLoader) { + SkillType::load(sn, attackBoostsNode, dir, tt, ft, loadedFileList, + parentLoader); + + fade = sn->getChild("fade")->getAttribute("value")->getBoolValue(); + if (sn->hasChild("spawn")) { + const XmlNode *spawnNode = sn->getChild("spawn"); + spawn = true; + spawnStartTime = spawnNode->getAttribute("start-time")->getFloatValue(); + spawnUnit = spawnNode->getChild("unit")->getAttribute("value")->getValue(); + spawnUnitcount = spawnNode->hasChild("amount") + ? spawnNode->getChild("amount") + ->getAttribute("value") + ->getIntValue() + : 0; + if (spawnNode->hasChild("health-percent")) { + spawnUnitHealthPercentMin = spawnNode->getChild("health-percent") + ->getAttribute("min") + ->getIntValue(); + spawnUnitHealthPercentMax = spawnNode->getChild("health-percent") + ->getAttribute("max") + ->getIntValue(); + } + spawnProbability = spawnNode->hasChild("probability") + ? spawnNode->getChild("probability") + ->getAttribute("value") + ->getIntValue() + : spawnProbability; + } // else keep defaults } -void DieSkillType::saveGame(XmlNode *rootNode) { - SkillType::saveGame(rootNode); - std::map mapTagReplacements; - XmlNode *dieSkillTypeNode = rootNode->addChild("DieSkillType"); +string DieSkillType::toString(bool translatedValue) const { + if (translatedValue == false) { + return "Die"; + } - dieSkillTypeNode->addAttribute("fade",intToStr(fade), mapTagReplacements); - // no need to save spawn attributes + return "Die"; } -StaticSound *DieSkillType::getSound() const{ - if(skillSoundList.size()==0){ - return NULL; - } - else { - return skillSoundList.front()->getSoundContainer()->getRandSound(); - } +void DieSkillType::saveGame(XmlNode *rootNode) { + SkillType::saveGame(rootNode); + std::map mapTagReplacements; + XmlNode *dieSkillTypeNode = rootNode->addChild("DieSkillType"); + + dieSkillTypeNode->addAttribute("fade", intToStr(fade), mapTagReplacements); + // no need to save spawn attributes } +StaticSound *DieSkillType::getSound() const { + if (skillSoundList.size() == 0) { + return NULL; + } else { + return skillSoundList.front()->getSoundContainer()->getRandSound(); + } +} // ===================================================== // class FogOfWarSkillType // ===================================================== -FogOfWarSkillType::FogOfWarSkillType(){ - skillClass= scFogOfWar; +FogOfWarSkillType::FogOfWarSkillType() { + skillClass = scFogOfWar; - fowEnable = false; - applyToTeam = false; - durationTime = 0; + fowEnable = false; + applyToTeam = false; + durationTime = 0; } -void FogOfWarSkillType::load(const XmlNode *sn, const XmlNode *attackBoostsNode, - const string &dir, const TechTree *tt, - const FactionType *ft, std::map > > &loadedFileList, - string parentLoader) { - SkillType::load(sn, attackBoostsNode,dir, tt, ft, loadedFileList, parentLoader); +void FogOfWarSkillType::load( + const XmlNode *sn, const XmlNode *attackBoostsNode, const string &dir, + const TechTree *tt, const FactionType *ft, + std::map>> &loadedFileList, + string parentLoader) { + SkillType::load(sn, attackBoostsNode, dir, tt, ft, loadedFileList, + parentLoader); - fowEnable = sn->getChild("enable-fog")->getAttribute("value")->getBoolValue(); - applyToTeam = sn->getChild("apply-team")->getAttribute("value")->getBoolValue(); - durationTime = sn->getChild("duration")->getAttribute("value")->getFloatValue(); + fowEnable = sn->getChild("enable-fog")->getAttribute("value")->getBoolValue(); + applyToTeam = + sn->getChild("apply-team")->getAttribute("value")->getBoolValue(); + durationTime = + sn->getChild("duration")->getAttribute("value")->getFloatValue(); } -string FogOfWarSkillType::toString(bool translatedValue) const{ - if(translatedValue == false) { - return "FogOfWar"; - } +string FogOfWarSkillType::toString(bool translatedValue) const { + if (translatedValue == false) { + return "FogOfWar"; + } - return "FogOfWar"; + return "FogOfWar"; } void FogOfWarSkillType::saveGame(XmlNode *rootNode) { - SkillType::saveGame(rootNode); - std::map mapTagReplacements; - XmlNode *fogSkillTypeNode = rootNode->addChild("FogOfWarSkillType"); + SkillType::saveGame(rootNode); + std::map mapTagReplacements; + XmlNode *fogSkillTypeNode = rootNode->addChild("FogOfWarSkillType"); - fogSkillTypeNode->addAttribute("enable-fog",intToStr(fowEnable), mapTagReplacements); - fogSkillTypeNode->addAttribute("apply-team",intToStr(applyToTeam), mapTagReplacements); - fogSkillTypeNode->addAttribute("duration",floatToStr(durationTime,6), mapTagReplacements); + fogSkillTypeNode->addAttribute("enable-fog", intToStr(fowEnable), + mapTagReplacements); + fogSkillTypeNode->addAttribute("apply-team", intToStr(applyToTeam), + mapTagReplacements); + fogSkillTypeNode->addAttribute("duration", floatToStr(durationTime, 6), + mapTagReplacements); } // ===================================================== // class SkillTypeFactory // ===================================================== -SkillTypeFactory::SkillTypeFactory(){ - registerClass("stop"); - registerClass("move"); - registerClass("attack"); - registerClass("build"); - registerClass("be_built"); - registerClass("harvest"); - registerClass("repair"); - registerClass("produce"); - registerClass("upgrade"); - registerClass("morph"); - registerClass("die"); - registerClass("fog_of_war"); +SkillTypeFactory::SkillTypeFactory() { + registerClass("stop"); + registerClass("move"); + registerClass("attack"); + registerClass("build"); + registerClass("be_built"); + registerClass("harvest"); + registerClass("repair"); + registerClass("produce"); + registerClass("upgrade"); + registerClass("morph"); + registerClass("die"); + registerClass("fog_of_war"); } -SkillTypeFactory &SkillTypeFactory::getInstance(){ - static SkillTypeFactory ctf; - return ctf; +SkillTypeFactory &SkillTypeFactory::getInstance() { + static SkillTypeFactory ctf; + return ctf; } -}} //end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/types/skill_type.h b/source/glest_game/types/skill_type.h index fe05990b9..30f564c11 100644 --- a/source/glest_game/types/skill_type.h +++ b/source/glest_game/types/skill_type.h @@ -3,9 +3,9 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== @@ -13,31 +13,32 @@ #define _GLEST_GAME_SKILLTYPE_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include "sound.h" -#include "vec.h" -#include "model.h" -#include "xml_parser.h" -#include "util.h" #include "damage_multiplier.h" #include "element_type.h" #include "factory.h" -#include "sound_container.h" +#include "leak_dumper.h" +#include "model.h" #include "particle.h" #include "projectile_type.h" +#include "sound.h" +#include "sound_container.h" #include "upgrade_type.h" -#include "leak_dumper.h" +#include "util.h" +#include "vec.h" +#include "xml_parser.h" #include +using Shared::Graphics::Model; +using Shared::Graphics::Vec3f; using Shared::Sound::StaticSound; using Shared::Xml::XmlNode; -using Shared::Graphics::Vec3f; -using Shared::Graphics::Model; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { using Shared::Util::MultiFactory; @@ -50,33 +51,32 @@ class Lang; class TotalUpgrade; class Unit; +enum Field { + fLand, + fAir, -enum Field{ - fLand, - fAir, - - fieldCount + fieldCount }; -enum SkillClass{ - scStop, - scMove, - scAttack, - scBuild, - scHarvest, - scRepair, - scBeBuilt, - scProduce, - scUpgrade, - scMorph, - scDie, - scFogOfWar, - - scCount +enum SkillClass { + scStop, + scMove, + scAttack, + scBuild, + scHarvest, + scRepair, + scBeBuilt, + scProduce, + scUpgrade, + scMorph, + scDie, + scFogOfWar, + + scCount }; -typedef list UnitParticleSystemTypes; -typedef list ProjectileTypes; +typedef list UnitParticleSystemTypes; +typedef list ProjectileTypes; // ===================================================== // class SkillType // @@ -84,58 +84,60 @@ typedef list ProjectileTypes; // ===================================================== enum AttackBoostTargetType { - abtAlly, // Only ally units are affected - abtFoe, // Only foe units are affected - abtFaction, // Only same faction units are affected - abtUnitTypes, // Specify which units are affected ( in general same as abtAll ) - abtAll // All units are affected (including enemies) + abtAlly, // Only ally units are affected + abtFoe, // Only foe units are affected + abtFaction, // Only same faction units are affected + abtUnitTypes, // Specify which units are affected ( in general same as abtAll + // ) + abtAll // All units are affected (including enemies) }; class AttackBoost { public: - AttackBoost(); - virtual ~AttackBoost(); - bool enabled; - bool allowMultipleBoosts; - int radius; - AttackBoostTargetType targetType; - std::set boostUnitList; - std::set tags; - UpgradeTypeBase boostUpgrade; - - UnitParticleSystemType *unitParticleSystemTypeForSourceUnit; - UnitParticleSystemType *unitParticleSystemTypeForAffectedUnit; - - bool includeSelf; - string name; - - bool isAffected(const Unit *source, const Unit *dest) const; - virtual string getDesc(bool translatedValue) const; - string getTagName(string tag, bool translatedValue=false) const; - - virtual void saveGame(XmlNode *rootNode) const; - virtual void loadGame(const XmlNode *rootNode, Faction *faction, const SkillType *skillType); + AttackBoost(); + virtual ~AttackBoost(); + bool enabled; + bool allowMultipleBoosts; + int radius; + AttackBoostTargetType targetType; + std::set boostUnitList; + std::set tags; + UpgradeTypeBase boostUpgrade; + + UnitParticleSystemType *unitParticleSystemTypeForSourceUnit; + UnitParticleSystemType *unitParticleSystemTypeForAffectedUnit; + + bool includeSelf; + string name; + + bool isAffected(const Unit *source, const Unit *dest) const; + virtual string getDesc(bool translatedValue) const; + string getTagName(string tag, bool translatedValue = false) const; + + virtual void saveGame(XmlNode *rootNode) const; + virtual void loadGame(const XmlNode *rootNode, Faction *faction, + const SkillType *skillType); private: - /** - * Checks if a unit is affected by the attack boost by checking if either the UnitType is in - * the #boostUnitList or shares a tag with #tags. - * @param unitType The unit type to check. - * @return True if the unit *might* be affected by the attack boost (still have to check if it's - * in range), false otherwise. - */ - bool isInUnitListOrTags(const UnitType *unitType) const; + /** + * Checks if a unit is affected by the attack boost by checking if either the + * UnitType is in the #boostUnitList or shares a tag with #tags. + * @param unitType The unit type to check. + * @return True if the unit *might* be affected by the attack boost (still + * have to check if it's in range), false otherwise. + */ + bool isInUnitListOrTags(const UnitType *unitType) const; }; class AnimationAttributes { public: - AnimationAttributes() { - fromHp = 0; - toHp = 0; - } + AnimationAttributes() { + fromHp = 0; + toHp = 0; + } - int fromHp; - int toHp; + int fromHp; + int toHp; }; // ===================================================== @@ -143,403 +145,433 @@ class AnimationAttributes { // holds the start time and a SoundContainer // ===================================================== -class SkillSound{ +class SkillSound { private: - SoundContainer soundContainer; - float startTime; + SoundContainer soundContainer; + float startTime; public: - SkillSound(); - ~SkillSound(); + SkillSound(); + ~SkillSound(); - SoundContainer *getSoundContainer() {return &soundContainer;} - float getStartTime() const {return startTime;} - void setStartTime(float value) {startTime=value;} + SoundContainer *getSoundContainer() { return &soundContainer; } + float getStartTime() const { return startTime; } + void setStartTime(float value) { startTime = value; } }; -typedef list SkillSoundList; +typedef list SkillSoundList; class SkillType { protected: - SkillClass skillClass; - string name; - int mpCost; - int hpCost; - int speed; - int animSpeed; - - bool shake; - int shakeIntensity; - int shakeDuration; - float shakeStartTime; - bool shakeSelfEnabled; - bool shakeSelfVisible; - bool shakeSelfInCameraView; - bool shakeSelfCameraAffected; - bool shakeTeamEnabled; - bool shakeTeamVisible; - bool shakeTeamInCameraView; - bool shakeTeamCameraAffected; - bool shakeEnemyEnabled; - bool shakeEnemyVisible; - bool shakeEnemyInCameraView; - bool shakeEnemyCameraAffected; - - - int animationRandomCycleMaxcount; - vector animations; - vector animationAttributes; - - SkillSoundList skillSoundList; - RandomGen random; - AttackBoost attackBoost; - - static int nextAttackBoostId; - static int getNextAttackBoostId() { return ++nextAttackBoostId; } - - const XmlNode * findAttackBoostDetails(string attackBoostName, - const XmlNode *attackBoostsNode,const XmlNode *attackBoostNode); - void loadAttackBoost(const XmlNode *attackBoostsNode, - const XmlNode *attackBoostNode, const FactionType *ft, - string parentLoader, const string & dir, string currentPath, - std::map > > & loadedFileList, const TechTree *tt); + SkillClass skillClass; + string name; + int mpCost; + int hpCost; + int speed; + int animSpeed; + + bool shake; + int shakeIntensity; + int shakeDuration; + float shakeStartTime; + bool shakeSelfEnabled; + bool shakeSelfVisible; + bool shakeSelfInCameraView; + bool shakeSelfCameraAffected; + bool shakeTeamEnabled; + bool shakeTeamVisible; + bool shakeTeamInCameraView; + bool shakeTeamCameraAffected; + bool shakeEnemyEnabled; + bool shakeEnemyVisible; + bool shakeEnemyInCameraView; + bool shakeEnemyCameraAffected; + + int animationRandomCycleMaxcount; + vector animations; + vector animationAttributes; + + SkillSoundList skillSoundList; + RandomGen random; + AttackBoost attackBoost; + + static int nextAttackBoostId; + static int getNextAttackBoostId() { return ++nextAttackBoostId; } + + const XmlNode *findAttackBoostDetails(string attackBoostName, + const XmlNode *attackBoostsNode, + const XmlNode *attackBoostNode); + void loadAttackBoost( + const XmlNode *attackBoostsNode, const XmlNode *attackBoostNode, + const FactionType *ft, string parentLoader, const string &dir, + string currentPath, + std::map>> &loadedFileList, + const TechTree *tt); public: - UnitParticleSystemTypes unitParticleSystemTypes; + UnitParticleSystemTypes unitParticleSystemTypes; public: - //varios - virtual ~SkillType(); - virtual void load(const XmlNode *sn, const XmlNode *attackBoostsNode, const string &dir, const TechTree *tt, - const FactionType *ft, std::map > > &loadedFileList, - string parentLoader); - - bool CanCycleNextRandomAnimation(const int *animationRandomCycleCount) const; - - static void resetNextAttackBoostId() { nextAttackBoostId=0; } - - const AnimationAttributes getAnimationAttribute(int index) const; - int getAnimationCount() const { return (int)animations.size(); } - - //get - const string &getName() const {return name;} - SkillClass getClass() const {return skillClass;} - int getEpCost() const {return mpCost;} - int getHpCost() const {return hpCost;} - int getSpeed() const {return speed;} - int getAnimSpeed() const {return animSpeed;} - Model *getAnimation(float animProgress=0, const Unit *unit=NULL, int *lastAnimationIndex=NULL, int *animationRandomCycleCount=NULL) const; - - float getShakeStartTime() const {return shakeStartTime;} - bool getShake() const {return shake;} - int getShakeIntensity() const {return shakeIntensity;} - int getShakeDuration() const {return shakeDuration;} - - const SkillSoundList * getSkillSoundList() const {return &skillSoundList;} - - bool getShakeSelfEnabled() const {return shakeSelfEnabled;} - bool getShakeSelfVisible() const {return shakeSelfVisible;} - bool getShakeSelfInCameraView() const {return shakeSelfInCameraView;} - bool getShakeSelfCameraAffected() const {return shakeSelfCameraAffected;} - bool getShakeTeamEnabled() const {return shakeTeamEnabled;} - bool getShakeTeamVisible() const {return shakeTeamVisible;} - bool getShakeTeamInCameraView() const {return shakeTeamInCameraView;} - bool getShakeTeamCameraAffected() const {return shakeTeamCameraAffected;} - bool getShakeEnemyEnabled() const {return shakeEnemyEnabled;} - bool getShakeEnemyVisible() const {return shakeEnemyVisible;} - bool getShakeEnemyInCameraView() const {return shakeEnemyInCameraView;} - bool getShakeEnemyCameraAffected() const {return shakeEnemyCameraAffected;} - - - bool isAttackBoostEnabled() const { return attackBoost.enabled; } - const AttackBoost * getAttackBoost() const { return &attackBoost; } - //virtual string getDesc(const TotalUpgrade *totalUpgrade) const= 0; - - //other - virtual string toString(bool translatedValue) const= 0; - virtual int getTotalSpeed(const TotalUpgrade *) const {return speed;} - static string skillClassToStr(SkillClass skillClass); - static string fieldToStr(Field field); - virtual string getBoostDesc(bool translatedValue) const {return attackBoost.getDesc(translatedValue);} - - virtual void saveGame(XmlNode *rootNode); + // varios + virtual ~SkillType(); + virtual void + load(const XmlNode *sn, const XmlNode *attackBoostsNode, const string &dir, + const TechTree *tt, const FactionType *ft, + std::map>> &loadedFileList, + string parentLoader); + + bool CanCycleNextRandomAnimation(const int *animationRandomCycleCount) const; + + static void resetNextAttackBoostId() { nextAttackBoostId = 0; } + + const AnimationAttributes getAnimationAttribute(int index) const; + int getAnimationCount() const { return (int)animations.size(); } + + // get + const string &getName() const { return name; } + SkillClass getClass() const { return skillClass; } + int getEpCost() const { return mpCost; } + int getHpCost() const { return hpCost; } + int getSpeed() const { return speed; } + int getAnimSpeed() const { return animSpeed; } + Model *getAnimation(float animProgress = 0, const Unit *unit = NULL, + int *lastAnimationIndex = NULL, + int *animationRandomCycleCount = NULL) const; + + float getShakeStartTime() const { return shakeStartTime; } + bool getShake() const { return shake; } + int getShakeIntensity() const { return shakeIntensity; } + int getShakeDuration() const { return shakeDuration; } + + const SkillSoundList *getSkillSoundList() const { return &skillSoundList; } + + bool getShakeSelfEnabled() const { return shakeSelfEnabled; } + bool getShakeSelfVisible() const { return shakeSelfVisible; } + bool getShakeSelfInCameraView() const { return shakeSelfInCameraView; } + bool getShakeSelfCameraAffected() const { return shakeSelfCameraAffected; } + bool getShakeTeamEnabled() const { return shakeTeamEnabled; } + bool getShakeTeamVisible() const { return shakeTeamVisible; } + bool getShakeTeamInCameraView() const { return shakeTeamInCameraView; } + bool getShakeTeamCameraAffected() const { return shakeTeamCameraAffected; } + bool getShakeEnemyEnabled() const { return shakeEnemyEnabled; } + bool getShakeEnemyVisible() const { return shakeEnemyVisible; } + bool getShakeEnemyInCameraView() const { return shakeEnemyInCameraView; } + bool getShakeEnemyCameraAffected() const { return shakeEnemyCameraAffected; } + + bool isAttackBoostEnabled() const { return attackBoost.enabled; } + const AttackBoost *getAttackBoost() const { return &attackBoost; } + // virtual string getDesc(const TotalUpgrade *totalUpgrade) const= 0; + + // other + virtual string toString(bool translatedValue) const = 0; + virtual int getTotalSpeed(const TotalUpgrade *) const { return speed; } + static string skillClassToStr(SkillClass skillClass); + static string fieldToStr(Field field); + virtual string getBoostDesc(bool translatedValue) const { + return attackBoost.getDesc(translatedValue); + } + + virtual void saveGame(XmlNode *rootNode); }; // =============================== -// class StopSkillType +// class StopSkillType // =============================== -class StopSkillType: public SkillType{ +class StopSkillType : public SkillType { public: - StopSkillType(); - virtual string toString(bool translatedValue) const; + StopSkillType(); + virtual string toString(bool translatedValue) const; }; // =============================== -// class MoveSkillType +// class MoveSkillType // =============================== -class MoveSkillType: public SkillType{ +class MoveSkillType : public SkillType { public: - MoveSkillType(); - virtual string toString(bool translatedValue) const; + MoveSkillType(); + virtual string toString(bool translatedValue) const; - virtual int getTotalSpeed(const TotalUpgrade *totalUpgrade) const; + virtual int getTotalSpeed(const TotalUpgrade *totalUpgrade) const; }; // =============================== -// class AttackSkillType +// class AttackSkillType // =============================== -class AttackSkillType: public SkillType{ +class AttackSkillType : public SkillType { public: - ProjectileTypes projectileTypes; + ProjectileTypes projectileTypes; + private: - int attackStrength; - int attackVar; - int attackRange; - const AttackType *attackType; - bool attackFields[fieldCount]; - float attackStartTime; - - string spawnUnit; - int spawnUnitcount; - bool spawnUnitAtTarget; - bool projectile; - //ParticleSystemTypeProjectile* projectileParticleSystemType; - SoundContainer projSounds; - - bool splash; - int splashRadius; - bool splashDamageAll; - ParticleSystemTypeSplash* splashParticleSystemType; + int attackStrength; + int attackVar; + int attackRange; + const AttackType *attackType; + bool attackFields[fieldCount]; + float attackStartTime; + + string spawnUnit; + int spawnUnitcount; + bool spawnUnitAtTarget; + bool projectile; + // ParticleSystemTypeProjectile* projectileParticleSystemType; + SoundContainer projSounds; + + bool splash; + int splashRadius; + bool splashDamageAll; + ParticleSystemTypeSplash *splashParticleSystemType; public: - AttackSkillType(); - ~AttackSkillType(); - virtual void load(const XmlNode *sn, const XmlNode *attackBoostsNode, const string &dir, const TechTree *tt, - const FactionType *ft, std::map > > &loadedFileList, - string parentLoader); - virtual string toString(bool translatedValue) const; - - //get - inline int getAttackStrength() const {return attackStrength;} - inline int getAttackVar() const {return attackVar;} - inline int getAttackRange() const {return attackRange;} - inline const AttackType *getAttackType() const {return attackType;} - inline bool getAttackField(Field field) const {return attackFields[field];} - inline float getAttackStartTime() const {return attackStartTime;} - inline string getSpawnUnit() const {return spawnUnit;} - inline int getSpawnUnitCount() const {return spawnUnitcount;} - inline bool getSpawnUnitAtTarget() const {return spawnUnitAtTarget;} - - //get proj - inline bool getProjectile() const {return projectile;} - inline StaticSound *getProjSound() const {return projSounds.getRandSound();} - - //get splash - inline bool getSplash() const {return splash;} - inline int getSplashRadius() const {return splashRadius;} - inline bool getSplashDamageAll() const {return splashDamageAll;} - inline ParticleSystemTypeSplash * getSplashParticleType() const {return splashParticleSystemType;} - - //misc - int getTotalAttackStrength(const TotalUpgrade *totalUpgrade) const; - int getTotalAttackRange(const TotalUpgrade *totalUpgrade) const; - virtual int getTotalSpeed(const TotalUpgrade *totalUpgrade) const; - virtual int getAnimSpeedBoost(const TotalUpgrade *totalUpgrade) const; - - virtual void saveGame(XmlNode *rootNode); + AttackSkillType(); + ~AttackSkillType(); + virtual void + load(const XmlNode *sn, const XmlNode *attackBoostsNode, const string &dir, + const TechTree *tt, const FactionType *ft, + std::map>> &loadedFileList, + string parentLoader); + virtual string toString(bool translatedValue) const; + + // get + inline int getAttackStrength() const { return attackStrength; } + inline int getAttackVar() const { return attackVar; } + inline int getAttackRange() const { return attackRange; } + inline const AttackType *getAttackType() const { return attackType; } + inline bool getAttackField(Field field) const { return attackFields[field]; } + inline float getAttackStartTime() const { return attackStartTime; } + inline string getSpawnUnit() const { return spawnUnit; } + inline int getSpawnUnitCount() const { return spawnUnitcount; } + inline bool getSpawnUnitAtTarget() const { return spawnUnitAtTarget; } + + // get proj + inline bool getProjectile() const { return projectile; } + inline StaticSound *getProjSound() const { return projSounds.getRandSound(); } + + // get splash + inline bool getSplash() const { return splash; } + inline int getSplashRadius() const { return splashRadius; } + inline bool getSplashDamageAll() const { return splashDamageAll; } + inline ParticleSystemTypeSplash *getSplashParticleType() const { + return splashParticleSystemType; + } + + // misc + int getTotalAttackStrength(const TotalUpgrade *totalUpgrade) const; + int getTotalAttackRange(const TotalUpgrade *totalUpgrade) const; + virtual int getTotalSpeed(const TotalUpgrade *totalUpgrade) const; + virtual int getAnimSpeedBoost(const TotalUpgrade *totalUpgrade) const; + + virtual void saveGame(XmlNode *rootNode); }; - // =============================== -// class BuildSkillType +// class BuildSkillType // =============================== -class BuildSkillType: public SkillType{ +class BuildSkillType : public SkillType { public: - BuildSkillType(); - virtual string toString(bool translatedValue) const; + BuildSkillType(); + virtual string toString(bool translatedValue) const; }; // =============================== -// class HarvestSkillType +// class HarvestSkillType // =============================== -class HarvestSkillType: public SkillType{ +class HarvestSkillType : public SkillType { public: - HarvestSkillType(); - virtual string toString(bool translatedValue) const; + HarvestSkillType(); + virtual string toString(bool translatedValue) const; }; // =============================== -// class RepairSkillType +// class RepairSkillType // =============================== -class RepairSkillType: public SkillType{ +class RepairSkillType : public SkillType { public: - RepairSkillType(); - virtual string toString(bool translatedValue) const; + RepairSkillType(); + virtual string toString(bool translatedValue) const; }; // =============================== -// class ProduceSkillType +// class ProduceSkillType // =============================== -class ProduceSkillType: public SkillType{ +class ProduceSkillType : public SkillType { private: - bool animProgressBound; + bool animProgressBound; + public: - ProduceSkillType(); - bool getAnimProgressBound() const {return animProgressBound;} - virtual void load(const XmlNode *sn, const XmlNode *attackBoostsNode, const string &dir, const TechTree *tt, - const FactionType *ft, std::map > > &loadedFileList, - string parentLoader); + ProduceSkillType(); + bool getAnimProgressBound() const { return animProgressBound; } + virtual void + load(const XmlNode *sn, const XmlNode *attackBoostsNode, const string &dir, + const TechTree *tt, const FactionType *ft, + std::map>> &loadedFileList, + string parentLoader); - virtual string toString(bool translatedValue) const; + virtual string toString(bool translatedValue) const; - virtual int getTotalSpeed(const TotalUpgrade *totalUpgrade) const; + virtual int getTotalSpeed(const TotalUpgrade *totalUpgrade) const; - virtual void saveGame(XmlNode *rootNode); + virtual void saveGame(XmlNode *rootNode); }; // =============================== -// class UpgradeSkillType +// class UpgradeSkillType // =============================== -class UpgradeSkillType: public SkillType{ +class UpgradeSkillType : public SkillType { private: - bool animProgressBound; + bool animProgressBound; + public: - UpgradeSkillType(); - bool getAnimProgressBound() const {return animProgressBound;} - virtual void load(const XmlNode *sn, const XmlNode *attackBoostsNode, const string &dir, const TechTree *tt, - const FactionType *ft, std::map > > &loadedFileList, - string parentLoader); + UpgradeSkillType(); + bool getAnimProgressBound() const { return animProgressBound; } + virtual void + load(const XmlNode *sn, const XmlNode *attackBoostsNode, const string &dir, + const TechTree *tt, const FactionType *ft, + std::map>> &loadedFileList, + string parentLoader); - virtual string toString(bool translatedValue) const; + virtual string toString(bool translatedValue) const; - virtual int getTotalSpeed(const TotalUpgrade *totalUpgrade) const; + virtual int getTotalSpeed(const TotalUpgrade *totalUpgrade) const; - virtual void saveGame(XmlNode *rootNode); + virtual void saveGame(XmlNode *rootNode); }; - // =============================== -// class BeBuiltSkillType +// class BeBuiltSkillType // =============================== -class BeBuiltSkillType: public SkillType{ +class BeBuiltSkillType : public SkillType { private: - bool animProgressBound; + bool animProgressBound; public: - BeBuiltSkillType(); - bool getAnimProgressBound() const {return animProgressBound;} + BeBuiltSkillType(); + bool getAnimProgressBound() const { return animProgressBound; } - virtual void load(const XmlNode *sn, const XmlNode *attackBoostsNode, const string &dir, const TechTree *tt, - const FactionType *ft, std::map > > &loadedFileList, - string parentLoader); - virtual string toString(bool translatedValue) const; + virtual void + load(const XmlNode *sn, const XmlNode *attackBoostsNode, const string &dir, + const TechTree *tt, const FactionType *ft, + std::map>> &loadedFileList, + string parentLoader); + virtual string toString(bool translatedValue) const; - virtual void saveGame(XmlNode *rootNode); + virtual void saveGame(XmlNode *rootNode); }; // =============================== -// class MorphSkillType +// class MorphSkillType // =============================== -class MorphSkillType: public SkillType{ +class MorphSkillType : public SkillType { private: - bool animProgressBound; + bool animProgressBound; public: - MorphSkillType(); - bool getAnimProgressBound() const {return animProgressBound;} + MorphSkillType(); + bool getAnimProgressBound() const { return animProgressBound; } - virtual void load(const XmlNode *sn, const XmlNode *attackBoostsNode, const string &dir, const TechTree *tt, - const FactionType *ft, std::map > > &loadedFileList, - string parentLoader); + virtual void + load(const XmlNode *sn, const XmlNode *attackBoostsNode, const string &dir, + const TechTree *tt, const FactionType *ft, + std::map>> &loadedFileList, + string parentLoader); - virtual string toString(bool translatedValue) const; - virtual int getTotalSpeed(const TotalUpgrade *totalUpgrade) const; + virtual string toString(bool translatedValue) const; + virtual int getTotalSpeed(const TotalUpgrade *totalUpgrade) const; - virtual void saveGame(XmlNode *rootNode); + virtual void saveGame(XmlNode *rootNode); }; // =============================== -// class DieSkillType +// class DieSkillType // =============================== -class DieSkillType: public SkillType { +class DieSkillType : public SkillType { private: - bool fade; - bool spawn; - float spawnStartTime; - string spawnUnit; - int spawnUnitcount; - int spawnUnitHealthPercentMin; - int spawnUnitHealthPercentMax; - int spawnProbability; + bool fade; + bool spawn; + float spawnStartTime; + string spawnUnit; + int spawnUnitcount; + int spawnUnitHealthPercentMin; + int spawnUnitHealthPercentMax; + int spawnProbability; public: - DieSkillType(); - - virtual void load(const XmlNode *sn, const XmlNode *attackBoostsNode, const string &dir, const TechTree *tt, - const FactionType *ft, std::map > > &loadedFileList, - string parentLoader); - virtual string toString(bool translatedValue) const; - - bool getFade() const {return fade;} - bool getSpawn() const {return spawn;} - inline int getSpawnStartTime() const {return spawnStartTime;} - inline string getSpawnUnit() const {return spawnUnit;} - inline int getSpawnUnitCount() const {return spawnUnitcount;} - inline int getSpawnUnitHealthPercentMin() const {return spawnUnitHealthPercentMin;} - inline int getSpawnUnitHealthPercentMax() const {return spawnUnitHealthPercentMax;} - inline int getSpawnProbability() const {return spawnProbability;} - - virtual void saveGame(XmlNode *rootNode); - StaticSound *getSound() const; + DieSkillType(); + + virtual void + load(const XmlNode *sn, const XmlNode *attackBoostsNode, const string &dir, + const TechTree *tt, const FactionType *ft, + std::map>> &loadedFileList, + string parentLoader); + virtual string toString(bool translatedValue) const; + + bool getFade() const { return fade; } + bool getSpawn() const { return spawn; } + inline int getSpawnStartTime() const { return spawnStartTime; } + inline string getSpawnUnit() const { return spawnUnit; } + inline int getSpawnUnitCount() const { return spawnUnitcount; } + inline int getSpawnUnitHealthPercentMin() const { + return spawnUnitHealthPercentMin; + } + inline int getSpawnUnitHealthPercentMax() const { + return spawnUnitHealthPercentMax; + } + inline int getSpawnProbability() const { return spawnProbability; } + + virtual void saveGame(XmlNode *rootNode); + StaticSound *getSound() const; }; // =============================== // class FogOfWarSkillType // =============================== -class FogOfWarSkillType: public SkillType { +class FogOfWarSkillType : public SkillType { private: - bool fowEnable; - bool applyToTeam; - float durationTime; + bool fowEnable; + bool applyToTeam; + float durationTime; public: - FogOfWarSkillType(); - bool getFowEnable() const {return fowEnable;} - bool getApplyToTeam() const {return applyToTeam;} - float getDurationTime() const {return durationTime;} - - virtual void load(const XmlNode *sn, const XmlNode *attackBoostsNode, const string &dir, const TechTree *tt, - const FactionType *ft, std::map > > &loadedFileList, - string parentLoader); - virtual string toString(bool translatedValue) const; - - virtual void saveGame(XmlNode *rootNode); + FogOfWarSkillType(); + bool getFowEnable() const { return fowEnable; } + bool getApplyToTeam() const { return applyToTeam; } + float getDurationTime() const { return durationTime; } + + virtual void + load(const XmlNode *sn, const XmlNode *attackBoostsNode, const string &dir, + const TechTree *tt, const FactionType *ft, + std::map>> &loadedFileList, + string parentLoader); + virtual string toString(bool translatedValue) const; + + virtual void saveGame(XmlNode *rootNode); }; // =============================== -// class SkillFactory +// class SkillFactory // =============================== -class SkillTypeFactory: public MultiFactory { +class SkillTypeFactory : public MultiFactory { private: - SkillTypeFactory(); + SkillTypeFactory(); + public: - static SkillTypeFactory &getInstance(); + static SkillTypeFactory &getInstance(); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/types/tech_tree.cpp b/source/glest_game/types/tech_tree.cpp index a5dba17b1..e79dc40c2 100644 --- a/source/glest_game/types/tech_tree.cpp +++ b/source/glest_game/types/tech_tree.cpp @@ -13,564 +13,657 @@ #include -#include "util.h" -#include "resource.h" +#include "common_scoped_ptr.h" #include "faction_type.h" +#include "game_util.h" +#include "leak_dumper.h" #include "logger.h" -#include "xml_parser.h" #include "platform_util.h" -#include "game_util.h" +#include "resource.h" +#include "util.h" #include "window.h" -#include "common_scoped_ptr.h" -#include "leak_dumper.h" +#include "xml_parser.h" using namespace Shared::Util; using namespace Shared::Xml; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class TechTree // ===================================================== TechTree::TechTree(const vector pathList) { - SkillType::resetNextAttackBoostId(); - - name=""; - treePath=""; - this->pathList.assign(pathList.begin(), pathList.end()); - - resourceTypes.clear(); - factionTypes.clear(); - armorTypes.clear(); - attackTypes.clear(); - translatedTechNames.clear(); - translatedTechFactionNames.clear(); - languageUsedForCache = ""; - isValidationModeEnabled = false; + SkillType::resetNextAttackBoostId(); + + name = ""; + treePath = ""; + this->pathList.assign(pathList.begin(), pathList.end()); + + resourceTypes.clear(); + factionTypes.clear(); + armorTypes.clear(); + attackTypes.clear(); + translatedTechNames.clear(); + translatedTechFactionNames.clear(); + languageUsedForCache = ""; + isValidationModeEnabled = false; } -string TechTree::getNameUntranslated() const { - return name; -} +string TechTree::getNameUntranslated() const { return name; } string TechTree::getName(bool translatedValue) { - if(translatedValue == false) { - return getNameUntranslated(); - } - - bool foundTranslation = false; - Lang &lang = Lang::getInstance(); - if(lang.getTechNameLoaded() != name || - lang.getLanguage() != languageUsedForCache) { - //printf("Line: %d Tech [%s]\n",__LINE__,name.c_str()); - - foundTranslation = lang.loadTechTreeStrings(name,lang.getLanguage() != languageUsedForCache); - languageUsedForCache = lang.getLanguage(); - translatedTechFactionNames.erase(name); - translatedTechNames.erase(name); - } - - string result = name; - if(foundTranslation == true) { - result = lang.getTechTreeString("TechTreeName",name.c_str()); - } - else { - result = formatString(result); - } - - - //printf("Line: %d Tech [%s] result [%s]\n",__LINE__,name.c_str(),result.c_str()); - return result; + if (translatedValue == false) { + return getNameUntranslated(); + } + + bool foundTranslation = false; + Lang &lang = Lang::getInstance(); + if (lang.getTechNameLoaded() != name || + lang.getLanguage() != languageUsedForCache) { + // printf("Line: %d Tech [%s]\n",__LINE__,name.c_str()); + + foundTranslation = lang.loadTechTreeStrings(name, lang.getLanguage() != + languageUsedForCache); + languageUsedForCache = lang.getLanguage(); + translatedTechFactionNames.erase(name); + translatedTechNames.erase(name); + } + + string result = name; + if (foundTranslation == true) { + result = lang.getTechTreeString("TechTreeName", name.c_str()); + } else { + result = formatString(result); + } + + // printf("Line: %d Tech [%s] result + // [%s]\n",__LINE__,name.c_str(),result.c_str()); + return result; } -string TechTree::getTranslatedName(string techName, bool forceLoad, bool forceTechtreeActiveFile) { - string result = techName; - - //printf("Line: %d Tech [%s] forceLoad = %d forceTechtreeActiveFile = %d\n",__LINE__,techName.c_str(),forceLoad,forceTechtreeActiveFile); - - Lang &lang = Lang::getInstance(); - if(forceTechtreeActiveFile == false && - translatedTechNames.find(techName) != translatedTechNames.end() && - lang.getLanguage() == languageUsedForCache) { - result = translatedTechNames[techName]; - } - else { - name = ""; - string path = findPath(techName); - if(path != "") { - string currentPath = path; - endPathWithSlash(currentPath); - treePath = currentPath; - name= lastDir(currentPath); - - lang.loadTechTreeStrings(name,lang.getLanguage() != languageUsedForCache); - languageUsedForCache = lang.getLanguage(); - - translatedTechFactionNames.erase(techName); - translatedTechNames.erase(techName); - - result = getName(true); - - //printf("techName [%s] name [%s] result [%s]\n",techName.c_str(),name.c_str(),result.c_str()); - translatedTechNames[name] = result; - } - - } - return result; +string TechTree::getTranslatedName(string techName, bool forceLoad, + bool forceTechtreeActiveFile) { + string result = techName; + + // printf("Line: %d Tech [%s] forceLoad = %d forceTechtreeActiveFile = + // %d\n",__LINE__,techName.c_str(),forceLoad,forceTechtreeActiveFile); + + Lang &lang = Lang::getInstance(); + if (forceTechtreeActiveFile == false && + translatedTechNames.find(techName) != translatedTechNames.end() && + lang.getLanguage() == languageUsedForCache) { + result = translatedTechNames[techName]; + } else { + name = ""; + string path = findPath(techName); + if (path != "") { + string currentPath = path; + endPathWithSlash(currentPath); + treePath = currentPath; + name = lastDir(currentPath); + + lang.loadTechTreeStrings(name, + lang.getLanguage() != languageUsedForCache); + languageUsedForCache = lang.getLanguage(); + + translatedTechFactionNames.erase(techName); + translatedTechNames.erase(techName); + + result = getName(true); + + // printf("techName [%s] name [%s] result + // [%s]\n",techName.c_str(),name.c_str(),result.c_str()); + translatedTechNames[name] = result; + } + } + return result; } string TechTree::getTranslatedFactionName(string techName, string factionName) { - //printf("Line: %d Tech [%s] name [%s] factionName [%s]\n",__LINE__,techName.c_str(),name.c_str(),factionName.c_str()); - - Lang &lang = Lang::getInstance(); - if(lang.getTechNameLoaded() != techName || - lang.getLanguage() != languageUsedForCache) { - //printf("Line: %d Tech [%s] name [%s] lang.getTechNameLoaded() [%s] factionName [%s]\n",__LINE__,techName.c_str(),name.c_str(),lang.getTechNameLoaded().c_str(),factionName.c_str()); - - lang.loadTechTreeStrings(techName,lang.getLanguage() != languageUsedForCache); - languageUsedForCache = lang.getLanguage(); + // printf("Line: %d Tech [%s] name [%s] factionName + // [%s]\n",__LINE__,techName.c_str(),name.c_str(),factionName.c_str()); + + Lang &lang = Lang::getInstance(); + if (lang.getTechNameLoaded() != techName || + lang.getLanguage() != languageUsedForCache) { + // printf("Line: %d Tech [%s] name [%s] lang.getTechNameLoaded() [%s] + // factionName + // [%s]\n",__LINE__,techName.c_str(),name.c_str(),lang.getTechNameLoaded().c_str(),factionName.c_str()); + + lang.loadTechTreeStrings(techName, + lang.getLanguage() != languageUsedForCache); + languageUsedForCache = lang.getLanguage(); - translatedTechFactionNames.erase(techName); - } + translatedTechFactionNames.erase(techName); + } - std::map >::iterator iterMap = translatedTechFactionNames.find(techName); - if(iterMap != translatedTechFactionNames.end()) { - if(iterMap->second.find(factionName) != iterMap->second.end()) { - //printf("Line: %d Tech [%s] factionName [%s]\n",__LINE__,techName.c_str(),factionName.c_str()); + std::map>::iterator iterMap = + translatedTechFactionNames.find(techName); + if (iterMap != translatedTechFactionNames.end()) { + if (iterMap->second.find(factionName) != iterMap->second.end()) { + // printf("Line: %d Tech [%s] factionName + // [%s]\n",__LINE__,techName.c_str(),factionName.c_str()); - return iterMap->second.find(factionName)->second; - } - } + return iterMap->second.find(factionName)->second; + } + } - //printf("Line: %d Tech [%s] factionName [%s]\n",__LINE__,techName.c_str(),factionName.c_str()); + // printf("Line: %d Tech [%s] factionName + // [%s]\n",__LINE__,techName.c_str(),factionName.c_str()); - getTranslatedName(techName,false,true); + getTranslatedName(techName, false, true); - string result = lang.getTechTreeString("FactionName_" + factionName,formatString(factionName).c_str()); - //printf(">>result = %s\n",result.c_str()); - translatedTechFactionNames[techName][factionName] = result; + string result = lang.getTechTreeString("FactionName_" + factionName, + formatString(factionName).c_str()); + // printf(">>result = %s\n",result.c_str()); + translatedTechFactionNames[techName][factionName] = result; - //printf("Line: %d Translated faction for Tech [%s] faction [%s] result [%s]\n",__LINE__,techName.c_str(),factionName.c_str(),result.c_str()); + // printf("Line: %d Translated faction for Tech [%s] faction [%s] result + // [%s]\n",__LINE__,techName.c_str(),factionName.c_str(),result.c_str()); - return result; + return result; } -Checksum TechTree::loadTech(const string &techName, - set &factions, Checksum* checksum, - std::map > > &loadedFileList, - bool validationMode) { - name = ""; - isValidationModeEnabled = validationMode; - Checksum techtreeChecksum; - string path=findPath(techName); - if(path!="") { - //printf(">>> path=%s\n",path.c_str()); - load(path, factions, checksum, &techtreeChecksum, loadedFileList, - validationMode); - } - else { - printf(">>> techtree [%s] path not found.\n",techName.c_str()); - } - return techtreeChecksum; +Checksum TechTree::loadTech( + const string &techName, set &factions, Checksum *checksum, + std::map>> &loadedFileList, + bool validationMode) { + name = ""; + isValidationModeEnabled = validationMode; + Checksum techtreeChecksum; + string path = findPath(techName); + if (path != "") { + // printf(">>> path=%s\n",path.c_str()); + load(path, factions, checksum, &techtreeChecksum, loadedFileList, + validationMode); + } else { + printf(">>> techtree [%s] path not found.\n", techName.c_str()); + } + return techtreeChecksum; } -bool TechTree::exists(const string &techName, const vector &pathTechList) { - bool techFound = false; - auto_ptr techTree(new TechTree(pathTechList)); - string path = techTree->findPath(techName); - if(path != "") { - techFound = true; - } - return techFound; +bool TechTree::exists(const string &techName, + const vector &pathTechList) { + bool techFound = false; + auto_ptr techTree(new TechTree(pathTechList)); + string path = techTree->findPath(techName); + if (path != "") { + techFound = true; + } + return techFound; } string TechTree::findPath(const string &techName) const { - return findPath(techName,pathList); + return findPath(techName, pathList); } -string TechTree::findPath(const string &techName, const vector &pathTechList) { - for(unsigned int idx = 0; idx < pathTechList.size(); ++idx) { - string currentPath = (pathTechList)[idx]; - endPathWithSlash(currentPath); - - string path = currentPath + techName; - - //printf(">>> test path=%s\n",path.c_str()); - if(isdir(path.c_str()) == true) { - return path; - //break; - } +string TechTree::findPath(const string &techName, + const vector &pathTechList) { + for (unsigned int idx = 0; idx < pathTechList.size(); ++idx) { + string currentPath = (pathTechList)[idx]; + endPathWithSlash(currentPath); + + string path = currentPath + techName; + + // printf(">>> test path=%s\n",path.c_str()); + if (isdir(path.c_str()) == true) { + return path; + // break; } - //return "no path found for tech: \""+techname+"\""; - return ""; + } + // return "no path found for tech: \""+techname+"\""; + return ""; } - -void TechTree::load(const string &dir, set &factions, Checksum* checksum, - Checksum *techtreeChecksum, - std::map > > &loadedFileList, - bool validationMode) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - string currentPath = dir; - endPathWithSlash(currentPath); - treePath = currentPath; - name= lastDir(currentPath); - - Lang &lang = Lang::getInstance(); - lang.loadTechTreeStrings(name, true); - languageUsedForCache = lang.getLanguage(); - - char szBuf[8096]=""; - snprintf(szBuf,8096,Lang::getInstance().getString("LogScreenGameLoadingTechtree","",true).c_str(),formatString(getName(true)).c_str()); - Logger::getInstance().add(szBuf, true); - - vector filenames; - //load resources - string str= currentPath + "resources/*."; - - try { - findAll(str, filenames); - resourceTypes.resize(filenames.size()); - - for(int i = 0; i < (int)filenames.size(); ++i){ - str= currentPath + "resources/" + filenames[i]; - resourceTypes[i].load(str, checksum, &checksumValue, loadedFileList, - treePath); - Window::handleEvent(); - SDL_PumpEvents(); - } - - // Cleanup pixmap memory - for(int i = 0; i < (int)filenames.size(); ++i) { - resourceTypes[i].deletePixels(); - } - } - catch(megaglest_runtime_error& ex) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - throw megaglest_runtime_error("Error loading Resource Types in: "+ currentPath + "\nMessage: " + ex.what(),!ex.wantStackTrace() || isValidationModeEnabled); - } - catch(const exception &e){ - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what()); - throw megaglest_runtime_error("Error loading Resource Types in: "+ currentPath + "\nMessage: " + e.what(),isValidationModeEnabled); +void TechTree::load( + const string &dir, set &factions, Checksum *checksum, + Checksum *techtreeChecksum, + std::map>> &loadedFileList, + bool validationMode) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + string currentPath = dir; + endPathWithSlash(currentPath); + treePath = currentPath; + name = lastDir(currentPath); + + Lang &lang = Lang::getInstance(); + lang.loadTechTreeStrings(name, true); + languageUsedForCache = lang.getLanguage(); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + Lang::getInstance() + .getString("LogScreenGameLoadingTechtree", "", true) + .c_str(), + formatString(getName(true)).c_str()); + Logger::getInstance().add(szBuf, true); + + vector filenames; + // load resources + string str = currentPath + "resources/*."; + + try { + findAll(str, filenames); + resourceTypes.resize(filenames.size()); + + for (int i = 0; i < (int)filenames.size(); ++i) { + str = currentPath + "resources/" + filenames[i]; + resourceTypes[i].load(str, checksum, &checksumValue, loadedFileList, + treePath); + Window::handleEvent(); + SDL_PumpEvents(); } - // give CPU time to update other things to avoid apperance of hanging - sleep(0); - Window::handleEvent(); - SDL_PumpEvents(); - - //load tech tree xml info - try { - XmlTree xmlTree; - string currentPath = dir; - endPathWithSlash(currentPath); - string path = currentPath + lastDir(dir) + ".xml"; - - checksum->addFile(path); - checksumValue.addFile(path); - - std::map mapExtraTagReplacementValues; - mapExtraTagReplacementValues["$COMMONDATAPATH"] = currentPath + "/commondata/"; - xmlTree.load(path, Properties::getTagReplacementValues(&mapExtraTagReplacementValues)); - loadedFileList[path].push_back(make_pair(currentPath,currentPath)); - - Properties::setTechtreePath(currentPath); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("==> Set techtree path to [%s]\n",currentPath.c_str()); - - const XmlNode *techTreeNode= xmlTree.getRootNode(); - - //attack types - const XmlNode *attackTypesNode= techTreeNode->getChild("attack-types"); - attackTypes.resize(attackTypesNode->getChildCount()); - for(int i = 0; i < (int)attackTypes.size(); ++i) { - const XmlNode *attackTypeNode= attackTypesNode->getChild("attack-type", i); - attackTypes[i].setName(attackTypeNode->getAttribute("name")->getRestrictedValue()); - attackTypes[i].setId(i); - - Window::handleEvent(); - SDL_PumpEvents(); - } - - // give CPU time to update other things to avoid apperance of hanging - sleep(0); - //SDL_PumpEvents(); - - //armor types - const XmlNode *armorTypesNode= techTreeNode->getChild("armor-types"); - armorTypes.resize(armorTypesNode->getChildCount()); - for(int i = 0; i < (int)armorTypes.size(); ++i) { - const XmlNode *armorTypeNode= armorTypesNode->getChild("armor-type", i); - armorTypes[i].setName(armorTypeNode->getAttribute("name")->getRestrictedValue()); - armorTypes[i].setId(i); - - Window::handleEvent(); - SDL_PumpEvents(); - } - - //damage multipliers - damageMultiplierTable.init((int)attackTypes.size(), (int)armorTypes.size()); - const XmlNode *damageMultipliersNode= techTreeNode->getChild("damage-multipliers"); - for(int i = 0; i < (int)damageMultipliersNode->getChildCount(); ++i) { - const XmlNode *damageMultiplierNode= damageMultipliersNode->getChild("damage-multiplier", i); - const AttackType *attackType= getAttackType(damageMultiplierNode->getAttribute("attack")->getRestrictedValue()); - const ArmorType *armorType= getArmorType(damageMultiplierNode->getAttribute("armor")->getRestrictedValue()); - double multiplier= damageMultiplierNode->getAttribute("value")->getFloatValue(); - damageMultiplierTable.setDamageMultiplier(attackType, armorType, multiplier); - - Window::handleEvent(); - SDL_PumpEvents(); - } - } - catch(megaglest_runtime_error& ex) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - throw megaglest_runtime_error("Error loading Tech Tree: "+ currentPath + "\nMessage: " + ex.what(),!ex.wantStackTrace() || isValidationModeEnabled); + // Cleanup pixmap memory + for (int i = 0; i < (int)filenames.size(); ++i) { + resourceTypes[i].deletePixels(); } - catch(const exception &e){ - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what()); - throw megaglest_runtime_error("Error loading Tech Tree: "+ currentPath + "\nMessage: " + e.what(),isValidationModeEnabled); + } catch (megaglest_runtime_error &ex) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + throw megaglest_runtime_error( + "Error loading Resource Types in: " + currentPath + + "\nMessage: " + ex.what(), + !ex.wantStackTrace() || isValidationModeEnabled); + } catch (const exception &e) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, e.what()); + throw megaglest_runtime_error("Error loading Resource Types in: " + + currentPath + "\nMessage: " + e.what(), + isValidationModeEnabled); + } + + // give CPU time to update other things to avoid apperance of hanging + sleep(0); + Window::handleEvent(); + SDL_PumpEvents(); + + // load tech tree xml info + try { + XmlTree xmlTree; + string currentPath = dir; + endPathWithSlash(currentPath); + string path = currentPath + lastDir(dir) + ".xml"; + + checksum->addFile(path); + checksumValue.addFile(path); + + std::map mapExtraTagReplacementValues; + mapExtraTagReplacementValues["$COMMONDATAPATH"] = + currentPath + "/commondata/"; + xmlTree.load(path, Properties::getTagReplacementValues( + &mapExtraTagReplacementValues)); + loadedFileList[path].push_back(make_pair(currentPath, currentPath)); + + Properties::setTechtreePath(currentPath); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("==> Set techtree path to [%s]\n", currentPath.c_str()); + + const XmlNode *techTreeNode = xmlTree.getRootNode(); + + // attack types + const XmlNode *attackTypesNode = techTreeNode->getChild("attack-types"); + attackTypes.resize(attackTypesNode->getChildCount()); + for (int i = 0; i < (int)attackTypes.size(); ++i) { + const XmlNode *attackTypeNode = + attackTypesNode->getChild("attack-type", i); + attackTypes[i].setName( + attackTypeNode->getAttribute("name")->getRestrictedValue()); + attackTypes[i].setId(i); + + Window::handleEvent(); + SDL_PumpEvents(); } // give CPU time to update other things to avoid apperance of hanging sleep(0); - //SDL_PumpEvents(); - - //load factions - try{ - factionTypes.resize(factions.size()); - - int i=0; - for ( set::iterator it = factions.begin(); it != factions.end(); ++it ) { - string factionName = *it; - - char szBuf[8096]=""; - snprintf(szBuf,8096,"%s %s [%d / %d] - %s",Lang::getInstance().getString("Loading").c_str(), - Lang::getInstance().getString("Faction").c_str(), - i+1, - (int)factions.size(), - formatString(this->getTranslatedFactionName(name,factionName)).c_str()); - Logger &logger= Logger::getInstance(); - logger.setState(szBuf); - logger.setProgress((int)((((double)i) / (double)factions.size()) * 100.0)); - - factionTypes[i++].load(factionName, this, checksum,&checksumValue, - loadedFileList,validationMode); - - // give CPU time to update other things to avoid apperance of hanging - sleep(0); - Window::handleEvent(); - SDL_PumpEvents(); - } - } - catch(megaglest_runtime_error& ex) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - throw megaglest_runtime_error("Error loading Faction Types: "+ currentPath + "\nMessage: " + ex.what(),!ex.wantStackTrace() || isValidationModeEnabled); - } - catch(const exception &e){ - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what()); - throw megaglest_runtime_error("Error loading Faction Types: "+ currentPath + "\nMessage: " + e.what(),isValidationModeEnabled); + // SDL_PumpEvents(); + + // armor types + const XmlNode *armorTypesNode = techTreeNode->getChild("armor-types"); + armorTypes.resize(armorTypesNode->getChildCount()); + for (int i = 0; i < (int)armorTypes.size(); ++i) { + const XmlNode *armorTypeNode = armorTypesNode->getChild("armor-type", i); + armorTypes[i].setName( + armorTypeNode->getAttribute("name")->getRestrictedValue()); + armorTypes[i].setId(i); + + Window::handleEvent(); + SDL_PumpEvents(); } - if(techtreeChecksum != NULL) { - *techtreeChecksum = checksumValue; + // damage multipliers + damageMultiplierTable.init((int)attackTypes.size(), (int)armorTypes.size()); + const XmlNode *damageMultipliersNode = + techTreeNode->getChild("damage-multipliers"); + for (int i = 0; i < (int)damageMultipliersNode->getChildCount(); ++i) { + const XmlNode *damageMultiplierNode = + damageMultipliersNode->getChild("damage-multiplier", i); + const AttackType *attackType = getAttackType( + damageMultiplierNode->getAttribute("attack")->getRestrictedValue()); + const ArmorType *armorType = getArmorType( + damageMultiplierNode->getAttribute("armor")->getRestrictedValue()); + double multiplier = + damageMultiplierNode->getAttribute("value")->getFloatValue(); + damageMultiplierTable.setDamageMultiplier(attackType, armorType, + multiplier); + + Window::handleEvent(); + SDL_PumpEvents(); } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + } catch (megaglest_runtime_error &ex) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + throw megaglest_runtime_error( + "Error loading Tech Tree: " + currentPath + "\nMessage: " + ex.what(), + !ex.wantStackTrace() || isValidationModeEnabled); + } catch (const exception &e) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, e.what()); + throw megaglest_runtime_error("Error loading Tech Tree: " + currentPath + + "\nMessage: " + e.what(), + isValidationModeEnabled); + } + + // give CPU time to update other things to avoid apperance of hanging + sleep(0); + // SDL_PumpEvents(); + + // load factions + try { + factionTypes.resize(factions.size()); + + int i = 0; + for (set::iterator it = factions.begin(); it != factions.end(); + ++it) { + string factionName = *it; + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "%s %s [%d / %d] - %s", + Lang::getInstance().getString("Loading").c_str(), + Lang::getInstance().getString("Faction").c_str(), i + 1, + (int)factions.size(), + formatString(this->getTranslatedFactionName(name, factionName)) + .c_str()); + Logger &logger = Logger::getInstance(); + logger.setState(szBuf); + logger.setProgress( + (int)((((double)i) / (double)factions.size()) * 100.0)); + + factionTypes[i++].load(factionName, this, checksum, &checksumValue, + loadedFileList, validationMode); + + // give CPU time to update other things to avoid apperance of hanging + sleep(0); + Window::handleEvent(); + SDL_PumpEvents(); + } + } catch (megaglest_runtime_error &ex) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + throw megaglest_runtime_error( + "Error loading Faction Types: " + currentPath + + "\nMessage: " + ex.what(), + !ex.wantStackTrace() || isValidationModeEnabled); + } catch (const exception &e) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, e.what()); + throw megaglest_runtime_error("Error loading Faction Types: " + + currentPath + "\nMessage: " + e.what(), + isValidationModeEnabled); + } + + if (techtreeChecksum != NULL) { + *techtreeChecksum = checksumValue; + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); } TechTree::~TechTree() { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - Logger::getInstance().add(Lang::getInstance().getString("LogScreenGameUnLoadingTechtree","",true), true); - resourceTypes.clear(); - factionTypes.clear(); - armorTypes.clear(); - attackTypes.clear(); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + Logger::getInstance().add( + Lang::getInstance().getString("LogScreenGameUnLoadingTechtree", "", true), + true); + resourceTypes.clear(); + factionTypes.clear(); + armorTypes.clear(); + attackTypes.clear(); } std::vector TechTree::validateFactionTypes() { - std::vector results; - for (int i = 0; i < (int)factionTypes.size(); ++i) { - std::vector factionResults = factionTypes[i].validateFactionType(); - if(factionResults.empty() == false) { - results.insert(results.end(), factionResults.begin(), factionResults.end()); - } - - factionResults = factionTypes[i].validateFactionTypeUpgradeTypes(); - if(factionResults.empty() == false) { - results.insert(results.end(), factionResults.begin(), factionResults.end()); - } - } - - return results; + std::vector results; + for (int i = 0; i < (int)factionTypes.size(); ++i) { + std::vector factionResults = + factionTypes[i].validateFactionType(); + if (factionResults.empty() == false) { + results.insert(results.end(), factionResults.begin(), + factionResults.end()); + } + + factionResults = factionTypes[i].validateFactionTypeUpgradeTypes(); + if (factionResults.empty() == false) { + results.insert(results.end(), factionResults.begin(), + factionResults.end()); + } + } + + return results; } std::vector TechTree::validateResourceTypes() { - std::vector results; - ResourceTypes resourceTypesNotUsed = resourceTypes; - for (unsigned int i = 0; i < resourceTypesNotUsed.size(); ++i) { - ResourceType &rt = resourceTypesNotUsed[i]; - rt.setCleanupMemory(false); - } - for (unsigned int i = 0; i < factionTypes.size(); ++i) { - //printf("Validating [%d / %d] faction [%s]\n",i,(int)factionTypes.size(),factionTypes[i].getName().c_str()); - - std::vector factionResults = factionTypes[i].validateFactionTypeResourceTypes(resourceTypes); - if(factionResults.empty() == false) { - results.insert(results.end(), factionResults.begin(), factionResults.end()); - } - - // Check if the faction uses the resources in this techtree - // Now lets find a matching faction resource type for the unit - for(int j = (int)resourceTypesNotUsed.size() -1; j >= 0; --j) { - const ResourceType &rt = resourceTypesNotUsed[j]; - //printf("Validating [%d / %d] resourcetype [%s]\n",j,(int)resourceTypesNotUsed.size(),rt.getName().c_str()); - - if(factionTypes[i].factionUsesResourceType(&rt) == true) { - //printf("FOUND FACTION CONSUMER FOR RESOURCE - [%d / %d] faction [%s] resource [%d / %d] resourcetype [%s]\n",i,(int)factionTypes.size(),factionTypes[i].getName().c_str(),j,(int)resourceTypesNotUsed.size(),rt.getName().c_str()); - resourceTypesNotUsed.erase(resourceTypesNotUsed.begin() + j); - } - } - } - - if(resourceTypesNotUsed.empty() == false) { - //printf("FOUND unused resource Types [%d]\n",(int)resourceTypesNotUsed.size()); - - for (unsigned int i = 0; i < resourceTypesNotUsed.size(); ++i) { - const ResourceType &rt = resourceTypesNotUsed[i]; - char szBuf[8096]=""; - snprintf(szBuf,8096,"The Resource type [%s] is not used by any units in this techtree!",rt.getName().c_str()); - results.push_back(szBuf); - } - } - return results; + std::vector results; + ResourceTypes resourceTypesNotUsed = resourceTypes; + for (unsigned int i = 0; i < resourceTypesNotUsed.size(); ++i) { + ResourceType &rt = resourceTypesNotUsed[i]; + rt.setCleanupMemory(false); + } + for (unsigned int i = 0; i < factionTypes.size(); ++i) { + // printf("Validating [%d / %d] faction + // [%s]\n",i,(int)factionTypes.size(),factionTypes[i].getName().c_str()); + + std::vector factionResults = + factionTypes[i].validateFactionTypeResourceTypes(resourceTypes); + if (factionResults.empty() == false) { + results.insert(results.end(), factionResults.begin(), + factionResults.end()); + } + + // Check if the faction uses the resources in this techtree + // Now lets find a matching faction resource type for the unit + for (int j = (int)resourceTypesNotUsed.size() - 1; j >= 0; --j) { + const ResourceType &rt = resourceTypesNotUsed[j]; + // printf("Validating [%d / %d] resourcetype + // [%s]\n",j,(int)resourceTypesNotUsed.size(),rt.getName().c_str()); + + if (factionTypes[i].factionUsesResourceType(&rt) == true) { + // printf("FOUND FACTION CONSUMER FOR RESOURCE - [%d / %d] faction [%s] + // resource [%d / %d] resourcetype + // [%s]\n",i,(int)factionTypes.size(),factionTypes[i].getName().c_str(),j,(int)resourceTypesNotUsed.size(),rt.getName().c_str()); + resourceTypesNotUsed.erase(resourceTypesNotUsed.begin() + j); + } + } + } + + if (resourceTypesNotUsed.empty() == false) { + // printf("FOUND unused resource Types + // [%d]\n",(int)resourceTypesNotUsed.size()); + + for (unsigned int i = 0; i < resourceTypesNotUsed.size(); ++i) { + const ResourceType &rt = resourceTypesNotUsed[i]; + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "The Resource type [%s] is not used by any units in this techtree!", + rt.getName().c_str()); + results.push_back(szBuf); + } + } + return results; } // ==================== get ==================== FactionType *TechTree::getTypeByName(const string &name) { - for(int i=0; i < (int)factionTypes.size(); ++i) { - if(factionTypes[i].getName(false) == name) { - return &factionTypes[i]; - } + for (int i = 0; i < (int)factionTypes.size(); ++i) { + if (factionTypes[i].getName(false) == name) { + return &factionTypes[i]; } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - throw megaglest_runtime_error("Faction not found: " + name,true); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + throw megaglest_runtime_error("Faction not found: " + name, true); } const FactionType *TechTree::getType(const string &name) const { - for(int i=0; i < (int)factionTypes.size(); ++i) { - if(factionTypes[i].getName(false) == name) { - return &factionTypes[i]; - } + for (int i = 0; i < (int)factionTypes.size(); ++i) { + if (factionTypes[i].getName(false) == name) { + return &factionTypes[i]; } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - throw megaglest_runtime_error("Faction not found: " + name,true); + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + throw megaglest_runtime_error("Faction not found: " + name, true); } -const ResourceType *TechTree::getTechResourceType(int i) const{ - for(int j=0; j < getResourceTypeCount(); ++j){ - const ResourceType *rt= getResourceType(j); - assert(rt != NULL); - if(rt == NULL) { - throw megaglest_runtime_error("rt == NULL"); - } - if(rt->getResourceNumber() == i && rt->getClass() == rcTech) - return getResourceType(j); - } - - return getFirstTechResourceType(); +const ResourceType *TechTree::getTechResourceType(int i) const { + for (int j = 0; j < getResourceTypeCount(); ++j) { + const ResourceType *rt = getResourceType(j); + assert(rt != NULL); + if (rt == NULL) { + throw megaglest_runtime_error("rt == NULL"); + } + if (rt->getResourceNumber() == i && rt->getClass() == rcTech) + return getResourceType(j); + } + + return getFirstTechResourceType(); } -const ResourceType *TechTree::getFirstTechResourceType() const{ - for(int i=0; igetResourceNumber()==1 && rt->getClass()==rcTech) - return getResourceType(i); - } - - char szBuf[8096]=""; - snprintf(szBuf,8096,"The referenced tech tree [%s] is either missing or has no resources defined but at least one resource is required.",this->name.c_str()); - throw megaglest_runtime_error(szBuf,true); +const ResourceType *TechTree::getFirstTechResourceType() const { + for (int i = 0; i < getResourceTypeCount(); ++i) { + const ResourceType *rt = getResourceType(i); + assert(rt != NULL); + if (rt->getResourceNumber() == 1 && rt->getClass() == rcTech) + return getResourceType(i); + } + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "The referenced tech tree [%s] is either missing or has no " + "resources defined but at least one resource is required.", + this->name.c_str()); + throw megaglest_runtime_error(szBuf, true); } -const ResourceType *TechTree::getResourceType(const string &name) const{ +const ResourceType *TechTree::getResourceType(const string &name) const { - for(int i=0; i < (int)resourceTypes.size(); ++i){ - if(resourceTypes[i].getName()==name){ - return &resourceTypes[i]; - } - } + for (int i = 0; i < (int)resourceTypes.size(); ++i) { + if (resourceTypes[i].getName() == name) { + return &resourceTypes[i]; + } + } - throw megaglest_runtime_error("Resource Type not found: " + name,true); + throw megaglest_runtime_error("Resource Type not found: " + name, true); } -const ArmorType *TechTree::getArmorType(const string &name) const{ - for(int i=0; i < (int)armorTypes.size(); ++i){ - if(armorTypes[i].getName(false)==name){ - return &armorTypes[i]; - } - } +const ArmorType *TechTree::getArmorType(const string &name) const { + for (int i = 0; i < (int)armorTypes.size(); ++i) { + if (armorTypes[i].getName(false) == name) { + return &armorTypes[i]; + } + } - throw megaglest_runtime_error("Armor Type not found: " + name,true); + throw megaglest_runtime_error("Armor Type not found: " + name, true); } -const AttackType *TechTree::getAttackType(const string &name) const{ - for(int i=0; i < (int)attackTypes.size(); ++i){ - if(attackTypes[i].getName(false)==name){ - return &attackTypes[i]; - } - } +const AttackType *TechTree::getAttackType(const string &name) const { + for (int i = 0; i < (int)attackTypes.size(); ++i) { + if (attackTypes[i].getName(false) == name) { + return &attackTypes[i]; + } + } - throw megaglest_runtime_error("Attack Type not found: " + name,true); + throw megaglest_runtime_error("Attack Type not found: " + name, true); } -double TechTree::getDamageMultiplier(const AttackType *att, const ArmorType *art) const { - return damageMultiplierTable.getDamageMultiplier(att, art); +double TechTree::getDamageMultiplier(const AttackType *att, + const ArmorType *art) const { + return damageMultiplierTable.getDamageMultiplier(att, art); } void TechTree::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *techTreeNode = rootNode->addChild("TechTree"); - -// string name; - techTreeNode->addAttribute("name",name, mapTagReplacements); -// //string desc; -// string treePath; - //techTreeNode->addAttribute("treePath",treePath, mapTagReplacements); -// vector pathList; -// for(unsigned int i = 0; i < pathList.size(); ++i) { -// XmlNode *pathListNode = techTreeNode->addChild("pathList"); -// pathListNode->addAttribute("value",pathList[i], mapTagReplacements); -// } -// ResourceTypes resourceTypes; -// for(unsigned int i = 0; i < resourceTypes.size(); ++i) { -// ResourceType &rt = resourceTypes[i]; -// rt.saveGame(techTreeNode); -// } -// FactionTypes factionTypes; -// for(unsigned int i = 0; i < factionTypes.size(); ++i) { -// FactionType &ft = factionTypes[i]; -// ft.saveGame(techTreeNode); -// } - -// ArmorTypes armorTypes; -// for(unsigned int i = 0; i < armorTypes.size(); ++i) { -// ArmorType &at = armorTypes[i]; -// at.saveGame(techTreeNode); -// } - -// AttackTypes attackTypes; -// for(unsigned int i = 0; i < attackTypes.size(); ++i) { -// AttackType &at = attackTypes[i]; -// at.saveGame(techTreeNode); -// } - -// DamageMultiplierTable damageMultiplierTable; -// damageMultiplierTable.saveGame(techTreeNode); - -// Checksum checksumValue; - techTreeNode->addAttribute("checksumValue",intToStr(checksumValue.getSum()), mapTagReplacements); + std::map mapTagReplacements; + XmlNode *techTreeNode = rootNode->addChild("TechTree"); + + // string name; + techTreeNode->addAttribute("name", name, mapTagReplacements); + // //string desc; + // string treePath; + // techTreeNode->addAttribute("treePath",treePath, mapTagReplacements); + // vector pathList; + // for(unsigned int i = 0; i < pathList.size(); ++i) { + // XmlNode *pathListNode = techTreeNode->addChild("pathList"); + // pathListNode->addAttribute("value",pathList[i], + // mapTagReplacements); + // } + // ResourceTypes resourceTypes; + // for(unsigned int i = 0; i < resourceTypes.size(); ++i) { + // ResourceType &rt = resourceTypes[i]; + // rt.saveGame(techTreeNode); + // } + // FactionTypes factionTypes; + // for(unsigned int i = 0; i < factionTypes.size(); ++i) { + // FactionType &ft = factionTypes[i]; + // ft.saveGame(techTreeNode); + // } + + // ArmorTypes armorTypes; + // for(unsigned int i = 0; i < armorTypes.size(); ++i) { + // ArmorType &at = armorTypes[i]; + // at.saveGame(techTreeNode); + // } + + // AttackTypes attackTypes; + // for(unsigned int i = 0; i < attackTypes.size(); ++i) { + // AttackType &at = attackTypes[i]; + // at.saveGame(techTreeNode); + // } + + // DamageMultiplierTable damageMultiplierTable; + // damageMultiplierTable.saveGame(techTreeNode); + + // Checksum checksumValue; + techTreeNode->addAttribute("checksumValue", intToStr(checksumValue.getSum()), + mapTagReplacements); } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/types/tech_tree.h b/source/glest_game/types/tech_tree.h index d00d2a6c2..fc8a78b01 100644 --- a/source/glest_game/types/tech_tree.h +++ b/source/glest_game/types/tech_tree.h @@ -13,18 +13,19 @@ #define _GLEST_GAME_TECHTREE_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include -#include "util.h" -#include "resource_type.h" -#include "faction_type.h" #include "damage_multiplier.h" +#include "faction_type.h" #include "leak_dumper.h" +#include "resource_type.h" +#include "util.h" +#include -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class TechTree @@ -32,88 +33,95 @@ namespace Glest{ namespace Game{ /// A set of factions and resources // ===================================================== -class TechTree{ +class TechTree { private: - typedef vector ResourceTypes; - typedef vector FactionTypes; - typedef vector ArmorTypes; - typedef vector AttackTypes; + typedef vector ResourceTypes; + typedef vector FactionTypes; + typedef vector ArmorTypes; + typedef vector AttackTypes; private: - - string name; - //string desc; - string treePath; - vector pathList; - - ResourceTypes resourceTypes; - FactionTypes factionTypes; - ArmorTypes armorTypes; - AttackTypes attackTypes; - DamageMultiplierTable damageMultiplierTable; - Checksum checksumValue; - - string languageUsedForCache; - std::map translatedTechNames; - std::map > translatedTechFactionNames; - bool isValidationModeEnabled; + string name; + // string desc; + string treePath; + vector pathList; + + ResourceTypes resourceTypes; + FactionTypes factionTypes; + ArmorTypes armorTypes; + AttackTypes attackTypes; + DamageMultiplierTable damageMultiplierTable; + Checksum checksumValue; + + string languageUsedForCache; + std::map translatedTechNames; + std::map> translatedTechFactionNames; + bool isValidationModeEnabled; public: - Checksum loadTech(const string &techName, - set &factions, Checksum* checksum, - std::map > > &loadedFileList, - bool validationMode=false); - void load(const string &dir, set &factions, Checksum* checksum, - Checksum *techtreeChecksum, - std::map > > &loadedFileList, - bool validationMode=false); - string findPath(const string &techName) const; - - static string findPath(const string &techName, const vector &pathTechList); - static bool exists(const string &techName, const vector &pathTechList); - - explicit TechTree(const vector pathList); - ~TechTree(); - Checksum * getChecksumValue() { return &checksumValue; } - - //get - int getResourceTypeCount() const {return (int)resourceTypes.size();} - int getTypeCount() const {return (int)factionTypes.size();} - const FactionType *getType(int i) const {return &factionTypes[i];} - const ResourceType *getResourceType(int i) const {return &resourceTypes[i];} - string getName(bool translatedValue=false); - string getNameUntranslated() const; - - string getTranslatedName(string techName, bool forceLoad=false, bool forceTechtreeActiveFile=false); - string getTranslatedFactionName(string techName, string factionName); - - vector getPathList() const {return pathList;} - //const string &getDesc() const {return desc;} - - const string getPath() const {return treePath;} - - const FactionType *getType(const string &name) const; - FactionType *getTypeByName(const string &name); - const ResourceType *getResourceType(const string &name) const; - const ResourceType *getTechResourceType(int i) const; - const ResourceType *getFirstTechResourceType() const; - - const ArmorType *getArmorType(const string &name) const; - const AttackType *getAttackType(const string &name) const; - - int getArmorTypeCount() const { return (int)armorTypes.size(); } - const ArmorType * getArmorTypeByIndex(int index) const { return &armorTypes[index]; } - int getAttackTypeCount() const { return (int)attackTypes.size(); } - const AttackType * getAttackTypeByIndex(int index) const { return &attackTypes[index]; } - - double getDamageMultiplier(const AttackType *att, const ArmorType *art) const; - std::vector validateFactionTypes(); - std::vector validateResourceTypes(); - - void saveGame(XmlNode *rootNode); - + Checksum + loadTech(const string &techName, set &factions, Checksum *checksum, + std::map>> &loadedFileList, + bool validationMode = false); + void load(const string &dir, set &factions, Checksum *checksum, + Checksum *techtreeChecksum, + std::map>> &loadedFileList, + bool validationMode = false); + string findPath(const string &techName) const; + + static string findPath(const string &techName, + const vector &pathTechList); + static bool exists(const string &techName, + const vector &pathTechList); + + explicit TechTree(const vector pathList); + ~TechTree(); + Checksum *getChecksumValue() { return &checksumValue; } + + // get + int getResourceTypeCount() const { return (int)resourceTypes.size(); } + int getTypeCount() const { return (int)factionTypes.size(); } + const FactionType *getType(int i) const { return &factionTypes[i]; } + const ResourceType *getResourceType(int i) const { return &resourceTypes[i]; } + string getName(bool translatedValue = false); + string getNameUntranslated() const; + + string getTranslatedName(string techName, bool forceLoad = false, + bool forceTechtreeActiveFile = false); + string getTranslatedFactionName(string techName, string factionName); + + vector getPathList() const { return pathList; } + // const string &getDesc() const + // {return desc;} + + const string getPath() const { return treePath; } + + const FactionType *getType(const string &name) const; + FactionType *getTypeByName(const string &name); + const ResourceType *getResourceType(const string &name) const; + const ResourceType *getTechResourceType(int i) const; + const ResourceType *getFirstTechResourceType() const; + + const ArmorType *getArmorType(const string &name) const; + const AttackType *getAttackType(const string &name) const; + + int getArmorTypeCount() const { return (int)armorTypes.size(); } + const ArmorType *getArmorTypeByIndex(int index) const { + return &armorTypes[index]; + } + int getAttackTypeCount() const { return (int)attackTypes.size(); } + const AttackType *getAttackTypeByIndex(int index) const { + return &attackTypes[index]; + } + + double getDamageMultiplier(const AttackType *att, const ArmorType *art) const; + std::vector validateFactionTypes(); + std::vector validateResourceTypes(); + + void saveGame(XmlNode *rootNode); }; -}} //end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/types/tileset_model_type.cpp b/source/glest_game/types/tileset_model_type.cpp index d897fcc1e..4320b91d9 100644 --- a/source/glest_game/types/tileset_model_type.cpp +++ b/source/glest_game/types/tileset_model_type.cpp @@ -3,43 +3,44 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== #include "tileset_model_type.h" #include "leak_dumper.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class TilesetModelType // ===================================================== TilesetModelType::TilesetModelType() { - model = NULL; - height = 0; - rotationAllowed = false; - smoothTwoFrameAnim = false; - randomPositionEnabled = false; + model = NULL; + height = 0; + rotationAllowed = false; + smoothTwoFrameAnim = false; + randomPositionEnabled = false; - animSpeed = 0; + animSpeed = 0; } -TilesetModelType::~TilesetModelType(){ - while(!(particleTypes.empty())){ - delete particleTypes.back(); - particleTypes.pop_back(); - } - //Logger::getInstance().add("ObjectType", true); +TilesetModelType::~TilesetModelType() { + while (!(particleTypes.empty())) { + delete particleTypes.back(); + particleTypes.pop_back(); + } + // Logger::getInstance().add("ObjectType", true); } - -void TilesetModelType::addParticleSystem(ObjectParticleSystemType *particleSystem){ - particleTypes.push_back(particleSystem); +void TilesetModelType::addParticleSystem( + ObjectParticleSystemType *particleSystem) { + particleTypes.push_back(particleSystem); } - -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/types/tileset_model_type.h b/source/glest_game/types/tileset_model_type.h index bdbc170cd..bd38c1b80 100644 --- a/source/glest_game/types/tileset_model_type.h +++ b/source/glest_game/types/tileset_model_type.h @@ -3,82 +3,90 @@ // // Copyright (C) 2001-2008 Martiño Figueroa // -// You can redistribute this code and/or modify it under -// the terms of the GNU General Public License as published -// by the Free Software Foundation; either version 2 of the +// You can redistribute this code and/or modify it under +// the terms of the GNU General Public License as published +// by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version // ============================================================== #ifndef _GLEST_GAME_TILESET_MODEL_TYPE_H_ #define _GLEST_GAME_TILESET_MODEL_TYPE_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include -#include "model.h" -#include "vec.h" #include "leak_dumper.h" +#include "model.h" #include "unit_particle_type.h" +#include "vec.h" +#include using std::vector; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { using Shared::Graphics::Model; using Shared::Graphics::Vec3f; // ===================================================== -// class ObjectType +// class ObjectType // /// Each of the possible objects of the map: trees, stones ... // ===================================================== -typedef vector ModelParticleSystemTypes; +typedef vector ModelParticleSystemTypes; class TilesetModelType { private: - Model *model; - ModelParticleSystemTypes particleTypes; - int height; - bool rotationAllowed; - bool randomPositionEnabled; - bool smoothTwoFrameAnim; + Model *model; + ModelParticleSystemTypes particleTypes; + int height; + bool rotationAllowed; + bool randomPositionEnabled; + bool smoothTwoFrameAnim; - int animSpeed; + int animSpeed; public: - TilesetModelType(); - ~TilesetModelType(); + TilesetModelType(); + ~TilesetModelType(); - void addParticleSystem(ObjectParticleSystemType *particleSystem); - inline bool hasParticles() const {return particleTypes.empty() == false;} - inline ModelParticleSystemTypes* getParticleTypes() { return &particleTypes ;} + void addParticleSystem(ObjectParticleSystemType *particleSystem); + inline bool hasParticles() const { return particleTypes.empty() == false; } + inline ModelParticleSystemTypes *getParticleTypes() { return &particleTypes; } + inline Model *getModel() const { return model; } + inline void setModel(Model *model) { this->model = model; } - inline Model * getModel() const {return model;} - inline void setModel(Model *model) {this->model=model;} + inline int getHeight() const { return height; } + inline void setHeight(int height) { this->height = height; } - inline int getHeight() const {return height;} - inline void setHeight(int height) {this->height=height;} + inline bool getRotationAllowed() const { return rotationAllowed; } + inline void setRotationAllowed(bool rotationAllowed) { + this->rotationAllowed = rotationAllowed; + } - inline bool getRotationAllowed() const {return rotationAllowed;} - inline void setRotationAllowed(bool rotationAllowed) {this->rotationAllowed=rotationAllowed;} - - inline bool getRandomPositionEnabled() const {return randomPositionEnabled;} - inline void setRandomPositionEnabled(bool randomPositionEnabled) {this->randomPositionEnabled=randomPositionEnabled;} + inline bool getRandomPositionEnabled() const { return randomPositionEnabled; } + inline void setRandomPositionEnabled(bool randomPositionEnabled) { + this->randomPositionEnabled = randomPositionEnabled; + } - inline bool getSmoothTwoFrameAnim() const {return smoothTwoFrameAnim;} - inline void setSmoothTwoFrameAnim(bool smoothTwoFrameAnim) {this->smoothTwoFrameAnim=smoothTwoFrameAnim;} + inline bool getSmoothTwoFrameAnim() const { return smoothTwoFrameAnim; } + inline void setSmoothTwoFrameAnim(bool smoothTwoFrameAnim) { + this->smoothTwoFrameAnim = smoothTwoFrameAnim; + } - inline int getAnimSpeed() const {return animSpeed;} - inline void setAnimSpeed(int value) {animSpeed = value;} + inline int getAnimSpeed() const { return animSpeed; } + inline void setAnimSpeed(int value) { animSpeed = value; } -// inline int getAnimSpeedVariation() const {return animVariation;} -// inline void setAnimSpeedVariation(int value) {animSpeed = valueVariation;} + // inline int getAnimSpeedVariation() const {return + // animVariation;} inline void setAnimSpeedVariation(int value) {animSpeed + // = valueVariation;} }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/types/unit_type.cpp b/source/glest_game/types/unit_type.cpp index ca682ed75..3cd72cd06 100644 --- a/source/glest_game/types/unit_type.cpp +++ b/source/glest_game/types/unit_type.cpp @@ -10,67 +10,70 @@ // ============================================================== #ifdef WIN32 - #include - #include +#include +#include #endif -#include "unit_type.h" -#include -#include "util.h" -#include "upgrade_type.h" +#include "common_scoped_ptr.h" +#include "faction.h" +#include "game_util.h" +#include "leak_dumper.h" +#include "logger.h" +#include "renderer.h" +#include "resource.h" #include "resource_type.h" #include "sound.h" -#include "logger.h" -#include "xml_parser.h" #include "tech_tree.h" -#include "resource.h" -#include "renderer.h" -#include "game_util.h" #include "unit_particle_type.h" -#include "faction.h" -#include "common_scoped_ptr.h" -#include "leak_dumper.h" +#include "unit_type.h" +#include "upgrade_type.h" +#include "util.h" +#include "xml_parser.h" +#include using namespace Shared::Xml; using namespace Shared::Graphics; using namespace Shared::Util; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { -auto_ptr UnitType::ctHarvestEmergencyReturnCommandType(new HarvestEmergencyReturnCommandType()); +auto_ptr UnitType::ctHarvestEmergencyReturnCommandType( + new HarvestEmergencyReturnCommandType()); // =============================== // class Level // =============================== -void Level::init(string name, int kills){ - this->name= name; - this->kills= kills; +void Level::init(string name, int kills) { + this->name = name; + this->kills = kills; } -string Level::getName(bool translatedValue) const { - if(translatedValue == false) return name; +string Level::getName(bool translatedValue) const { + if (translatedValue == false) + return name; - Lang &lang = Lang::getInstance(); - return lang.getTechTreeString("LevelName_" + name,name.c_str()); + Lang &lang = Lang::getInstance(); + return lang.getTechTreeString("LevelName_" + name, name.c_str()); } void Level::saveGame(XmlNode *rootNode) const { - std::map mapTagReplacements; - XmlNode *levelNode = rootNode->addChild("Level"); + std::map mapTagReplacements; + XmlNode *levelNode = rootNode->addChild("Level"); - levelNode->addAttribute("name",name, mapTagReplacements); - levelNode->addAttribute("kills",intToStr(kills), mapTagReplacements); + levelNode->addAttribute("name", name, mapTagReplacements); + levelNode->addAttribute("kills", intToStr(kills), mapTagReplacements); } -const Level * Level::loadGame(const XmlNode *rootNode,const UnitType *ut) { - const Level *result = NULL; - if(rootNode->hasChild("Level") == true) { - const XmlNode *levelNode = rootNode->getChild("Level"); +const Level *Level::loadGame(const XmlNode *rootNode, const UnitType *ut) { + const Level *result = NULL; + if (rootNode->hasChild("Level") == true) { + const XmlNode *levelNode = rootNode->getChild("Level"); - result = ut->getLevel(levelNode->getAttribute("name")->getValue()); - } + result = ut->getLevel(levelNode->getAttribute("name")->getValue()); + } - return result; + return result; } // ===================================================== @@ -79,1288 +82,1495 @@ const Level * Level::loadGame(const XmlNode *rootNode,const UnitType *ut) { // ===================== PUBLIC ======================== -const char *UnitType::propertyNames[]= {"burnable", "rotated_climb"}; +const char *UnitType::propertyNames[] = {"burnable", "rotated_climb"}; // ==================== creation and loading ==================== UnitType::UnitType() : ProducibleType() { - countInVictoryConditions = ucvcNotSet; - meetingPointImage = NULL; - lightColor= Vec3f(0.f); - light= false; - healthbarheight= -100.0f; - healthbarthickness=-1.0f; - healthbarVisible=hbvUndefined; - multiSelect= false; - uniformSelect= false; - commandable= true; - armorType= NULL; - rotatedBuildPos=0; - - field = fLand; - id = 0; - meetingPoint = false; - rotationAllowed = false; - - countUnitDeathInStats=false; - countUnitProductionInStats=false; - countUnitKillInStats=false; - countKillForUnitUpgrade=false; - - - for(int i=0; imaxHp),this->maxHp); - addItemToVault(&(this->hpRegeneration),this->hpRegeneration); - addItemToVault(&(this->maxEp),this->maxEp); - addItemToVault(&(this->epRegeneration),this->epRegeneration); - addItemToVault(&(this->maxUnitCount),this->maxUnitCount); - addItemToVault(&(this->armor),this->armor); - addItemToVault(&(this->sight),this->sight); - addItemToVault(&(this->size),this->size); - addItemToVault(&(this->height),this->height); + countInVictoryConditions = ucvcNotSet; + meetingPointImage = NULL; + lightColor = Vec3f(0.f); + light = false; + healthbarheight = -100.0f; + healthbarthickness = -1.0f; + healthbarVisible = hbvUndefined; + multiSelect = false; + uniformSelect = false; + commandable = true; + armorType = NULL; + rotatedBuildPos = 0; + + field = fLand; + id = 0; + meetingPoint = false; + rotationAllowed = false; + + countUnitDeathInStats = false; + countUnitProductionInStats = false; + countUnitKillInStats = false; + countKillForUnitUpgrade = false; + + for (int i = 0; i < ccCount; ++i) { + firstCommandTypeOfClass[i] = NULL; + } + + for (int i = 0; i < scCount; ++i) { + firstSkillTypeOfClass[i] = NULL; + } + + for (int i = 0; i < pCount; ++i) { + properties[i] = false; + } + + for (int i = 0; i < fieldCount; ++i) { + fields[i] = false; + } + + cellMap = NULL; + allowEmptyCellMap = false; + hpRegeneration = 0; + epRegeneration = 0; + maxUnitCount = 0; + maxHp = 0; + startHpValue = 0; + startHpPercentage = 1.0; + startHpType = stValue; + maxEp = 0; + startEpValue = 0; + startEpPercentage = 0; + startEpType = stValue; + armor = 0; + sight = 0; + size = 0; + aiBuildSize = -1; + renderSize = 0; + height = 0; + burnHeight = 0; + targetHeight = 0; + + addItemToVault(&(this->maxHp), this->maxHp); + addItemToVault(&(this->hpRegeneration), this->hpRegeneration); + addItemToVault(&(this->maxEp), this->maxEp); + addItemToVault(&(this->epRegeneration), this->epRegeneration); + addItemToVault(&(this->maxUnitCount), this->maxUnitCount); + addItemToVault(&(this->armor), this->armor); + addItemToVault(&(this->sight), this->sight); + addItemToVault(&(this->size), this->size); + addItemToVault(&(this->height), this->height); } -UnitType::~UnitType(){ - deleteValues(commandTypes.begin(), commandTypes.end()); - commandTypes.clear(); - deleteValues(skillTypes.begin(), skillTypes.end()); - skillTypes.clear(); - deleteValues(selectionSounds.getSounds().begin(), selectionSounds.getSounds().end()); - selectionSounds.clearSounds(); - deleteValues(commandSounds.getSounds().begin(), commandSounds.getSounds().end()); - commandSounds.clearSounds(); - delete [] cellMap; - cellMap=NULL; - //remove damageParticleSystemTypes - while(!damageParticleSystemTypes.empty()){ - delete damageParticleSystemTypes.back(); - damageParticleSystemTypes.pop_back(); - } +UnitType::~UnitType() { + deleteValues(commandTypes.begin(), commandTypes.end()); + commandTypes.clear(); + deleteValues(skillTypes.begin(), skillTypes.end()); + skillTypes.clear(); + deleteValues(selectionSounds.getSounds().begin(), + selectionSounds.getSounds().end()); + selectionSounds.clearSounds(); + deleteValues(commandSounds.getSounds().begin(), + commandSounds.getSounds().end()); + commandSounds.clearSounds(); + delete[] cellMap; + cellMap = NULL; + // remove damageParticleSystemTypes + while (!damageParticleSystemTypes.empty()) { + delete damageParticleSystemTypes.back(); + damageParticleSystemTypes.pop_back(); + } } -void UnitType::preLoad(const string &dir) { - name= lastDir(dir); -} +void UnitType::preLoad(const string &dir) { name = lastDir(dir); } + +void UnitType::loaddd( + int id, const string &dir, const TechTree *techTree, + const string &techTreePath, const FactionType *factionType, + Checksum *checksum, Checksum *techtreeChecksum, + std::map>> &loadedFileList, + bool validationMode) { + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); + + string currentPath = dir; + endPathWithSlash(currentPath); + string path = currentPath + name + ".xml"; + string sourceXMLFile = path; + + this->id = id; + + try { + // Lang &lang= Lang::getInstance(); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + Lang::getInstance() + .getString("LogScreenGameLoadingUnitType", "", true) + .c_str(), + formatString(this->getName(true)).c_str()); + Logger::getInstance().add(szBuf, true); + + // file load + checksum->addFile(path); + techtreeChecksum->addFile(path); + + XmlTree xmlTree; + std::map mapExtraTagReplacementValues; + mapExtraTagReplacementValues["$COMMONDATAPATH"] = + techTreePath + "/commondata/"; + xmlTree.load(path, Properties::getTagReplacementValues( + &mapExtraTagReplacementValues)); + loadedFileList[path].push_back(make_pair(dir, dir)); + + const XmlNode *unitNode = xmlTree.getRootNode(); + + const XmlNode *parametersNode = unitNode->getChild("parameters"); + + if (parametersNode->hasChild("count-in-victory-conditions") == true) { + bool countUnit = parametersNode->getChild("count-in-victory-conditions") + ->getAttribute("value") + ->getBoolValue(); + if (countUnit == true) { + countInVictoryConditions = ucvcTrue; + } else { + countInVictoryConditions = ucvcFalse; + } + } + + // size + // checkItemInVault(&(this->size),this->size); + size = + parametersNode->getChild("size")->getAttribute("value")->getIntValue(); + addItemToVault(&(this->size), this->size); + renderSize = size; + if (parametersNode->hasChild("render-size")) { + renderSize = parametersNode->getChild("render-size") + ->getAttribute("value") + ->getIntValue(); + } + aiBuildSize = size; + if (parametersNode->hasChild("ai-build-size")) { + aiBuildSize = parametersNode->getChild("ai-build-size") + ->getAttribute("value") + ->getIntValue(); + } + + // height + // checkItemInVault(&(this->height),this->height); + height = parametersNode->getChild("height") + ->getAttribute("value") + ->getIntValue(); + addItemToVault(&(this->height), this->height); + + // targetHeight + if (parametersNode->hasChild("target-height")) { + targetHeight = parametersNode->getChild("target-height") + ->getAttribute("value") + ->getIntValue(); + addItemToVault(&(this->targetHeight), this->targetHeight); + } else { + targetHeight = height; + } + // burnHeight + if (parametersNode->hasChild("target-height")) { + burnHeight = parametersNode->getChild("burn-height") + ->getAttribute("value") + ->getIntValue(); + addItemToVault(&(this->burnHeight), this->burnHeight); + } else { + burnHeight = height; + } + + // maxHp + // checkItemInVault(&(this->maxHp),this->maxHp); + maxHp = parametersNode->getChild("max-hp") + ->getAttribute("value") + ->getIntValue(); + addItemToVault(&(this->maxHp), this->maxHp); + + // hpRegeneration + // checkItemInVault(&(this->hpRegeneration),this->hpRegeneration); + hpRegeneration = parametersNode->getChild("max-hp") + ->getAttribute("regeneration") + ->getIntValue(); + addItemToVault(&(this->hpRegeneration), this->hpRegeneration); + + // maxEp + // checkItemInVault(&(this->maxEp),this->maxEp); + maxEp = parametersNode->getChild("max-ep") + ->getAttribute("value") + ->getIntValue(); + addItemToVault(&(this->maxEp), this->maxEp); + + if (maxEp != 0) { + // epRegeneration + // checkItemInVault(&(this->epRegeneration),this->epRegeneration); + epRegeneration = parametersNode->getChild("max-ep") + ->getAttribute("regeneration") + ->getIntValue(); + } + addItemToVault(&(this->epRegeneration), this->epRegeneration); + + // Check that we don't use both start-value and start-percentage, as they + // are mutually exclusive + if (parametersNode->getChild("max-hp")->hasAttribute("start-value") && + parametersNode->getChild("max-hp")->hasAttribute("start-percentage")) { + throw megaglest_runtime_error( + "Unit " + name + " has both start-value and start-percentage for HP", + true); + } + + // startHpValue -- the *absolute* value to use for starting HP + if (parametersNode->getChild("max-hp")->hasAttribute("start-value")) { + // checkItemInVault(&(this->startEp),this->startEp); + startHpValue = parametersNode->getChild("max-hp") + ->getAttribute("start-value") + ->getIntValue(); + startHpType = stValue; + } + addItemToVault(&(this->startHpValue), this->startHpValue); + + // startHpPercentage -- the *relative* value to use for starting HP + if (parametersNode->getChild("max-hp")->hasAttribute("start-percentage")) { + startHpPercentage = parametersNode->getChild("max-hp") + ->getAttribute("start-percentage") + ->getIntValue(); + startHpType = stPercentage; + } + + // No start value is set; use 100% of the current Max + if (!parametersNode->getChild("max-hp")->hasAttribute("start-value") && + !parametersNode->getChild("max-hp")->hasAttribute("start-percentage")) { + startHpPercentage = 100; + startHpType = stPercentage; + } + addItemToVault(&(this->startHpPercentage), this->startHpPercentage); + + // Check that we don't use both start-value and start-percentage, as they + // are mutually exclusive + if (parametersNode->getChild("max-ep")->hasAttribute("start-value") && + parametersNode->getChild("max-ep")->hasAttribute("start-percentage")) { + throw megaglest_runtime_error( + "Unit " + name + " has both start-value and start-percentage for EP", + true); + } + + // startEpValue -- the *absolute* value to use for starting EP + if (parametersNode->getChild("max-ep")->hasAttribute("start-value")) { + // checkItemInVault(&(this->startEp),this->startEp); + startEpValue = parametersNode->getChild("max-ep") + ->getAttribute("start-value") + ->getIntValue(); + startEpType = stValue; + } + addItemToVault(&(this->startEpValue), this->startEpValue); + + // startEpPercentage -- the *relative* value to use for starting EP + if (parametersNode->getChild("max-ep")->hasAttribute("start-percentage")) { + startEpPercentage = parametersNode->getChild("max-ep") + ->getAttribute("start-percentage") + ->getIntValue(); + startEpType = stPercentage; + } + addItemToVault(&(this->startEpPercentage), this->startEpPercentage); + + // maxUnitCount + if (parametersNode->hasChild("max-unit-count")) { + // checkItemInVault(&(this->maxUnitCount),this->maxUnitCount); + maxUnitCount = parametersNode->getChild("max-unit-count") + ->getAttribute("value") + ->getIntValue(); + } + addItemToVault(&(this->maxUnitCount), this->maxUnitCount); + + // armor + // checkItemInVault(&(this->armor),this->armor); + armor = + parametersNode->getChild("armor")->getAttribute("value")->getIntValue(); + addItemToVault(&(this->armor), this->armor); + + // armor type string + string armorTypeName = parametersNode->getChild("armor-type") + ->getAttribute("value") + ->getRestrictedValue(); + armorType = techTree->getArmorType(armorTypeName); + + // sight + // checkItemInVault(&(this->sight),this->sight); + sight = + parametersNode->getChild("sight")->getAttribute("value")->getIntValue(); + addItemToVault(&(this->sight), this->sight); + + // prod time + productionTime = + parametersNode->getChild("time")->getAttribute("value")->getIntValue(); + + // multi selection + multiSelect = parametersNode->getChild("multi-selection") + ->getAttribute("value") + ->getBoolValue(); + + // uniform selection + if (parametersNode->hasChild("uniform-selection")) { + uniformSelect = parametersNode->getChild("uniform-selection") + ->getAttribute("value") + ->getBoolValue(); + } + + // commandable + if (parametersNode->hasChild("commandable")) { + commandable = parametersNode->getChild("commandable") + ->getAttribute("value") + ->getBoolValue(); + } + // cellmap + allowEmptyCellMap = false; + const XmlNode *cellMapNode = parametersNode->getChild("cellmap"); + bool hasCellMap = cellMapNode->getAttribute("value")->getBoolValue(); + if (hasCellMap == true) { + if (cellMapNode->getAttribute("allowEmpty", false) != NULL) { + allowEmptyCellMap = + cellMapNode->getAttribute("allowEmpty")->getBoolValue(); + } + + cellMap = new bool[size * size]; + for (int i = 0; i < size; ++i) { + const XmlNode *rowNode = cellMapNode->getChild("row", i); + string row = rowNode->getAttribute("value")->getRestrictedValue(); + if ((int)row.size() != size) { + throw megaglest_runtime_error( + "Cellmap row has not the same length as unit size", true); + } + for (int j = 0; j < (int)row.size(); ++j) { + cellMap[i * size + j] = row[j] == '0' ? false : true; + } + } + } + + // levels + const XmlNode *levelsNode = parametersNode->getChild("levels"); + levels.resize(levelsNode->getChildCount()); + for (int i = 0; i < (int)levels.size(); ++i) { + const XmlNode *levelNode = levelsNode->getChild("level", i); + + levels[i].init(levelNode->getAttribute("name")->getRestrictedValue(), + levelNode->getAttribute("kills")->getIntValue()); + } + + // fields + const XmlNode *fieldsNode = parametersNode->getChild("fields"); + for (int i = 0; i < (int)fieldsNode->getChildCount(); ++i) { + const XmlNode *fieldNode = fieldsNode->getChild("field", i); + string fieldName = fieldNode->getAttribute("value")->getRestrictedValue(); + if (fieldName == "land") { + fields[fLand] = true; + } else if (fieldName == "air") { + fields[fAir] = true; + } else { + throw megaglest_runtime_error( + "Not a valid field: " + fieldName + ": " + path, true); + } + } + + if (fields[fLand]) { + field = fLand; + } else if (fields[fAir]) { + field = fAir; + } else { + throw megaglest_runtime_error("Unit has no field: " + path, true); + } + + // properties + const XmlNode *propertiesNode = parametersNode->getChild("properties"); + for (int i = 0; i < (int)propertiesNode->getChildCount(); ++i) { + const XmlNode *propertyNode = propertiesNode->getChild("property", i); + string propertyName = + propertyNode->getAttribute("value")->getRestrictedValue(); + bool found = false; + for (int i = 0; i < pCount; ++i) { + if (propertyName == propertyNames[i]) { + properties[i] = true; + found = true; + break; + } + } + if (!found) { + throw megaglest_runtime_error("Unknown property: " + propertyName, + true); + } + } + // damage-particles + if (parametersNode->hasChild("damage-particles")) { + const XmlNode *particleNode = + parametersNode->getChild("damage-particles"); + bool particleEnabled = + particleNode->getAttribute("value")->getBoolValue(); + + if (particleEnabled) { + for (int i = 0; i < (int)particleNode->getChildCount(); ++i) { + const XmlNode *particleFileNode = + particleNode->getChild("particle-file", i); + string path = + particleFileNode->getAttribute("path")->getRestrictedValue(); + UnitParticleSystemType *unitParticleSystemType = + new UnitParticleSystemType(); + + unitParticleSystemType->load(particleFileNode, dir, + currentPath + path, + &Renderer::getInstance(), loadedFileList, + sourceXMLFile, techTree->getPath()); + loadedFileList[currentPath + path].push_back(make_pair( + sourceXMLFile, + particleFileNode->getAttribute("path")->getRestrictedValue())); + + if (particleFileNode->getAttribute("minHp", false) != NULL && + particleFileNode->getAttribute("maxHp", false) != NULL) { + unitParticleSystemType->setMinmaxEnabled(true); + unitParticleSystemType->setMinHp( + particleFileNode->getAttribute("minHp")->getIntValue()); + unitParticleSystemType->setMaxHp( + particleFileNode->getAttribute("maxHp")->getIntValue()); + + if (particleFileNode->getAttribute("ispercentbased", false) != + NULL) { + unitParticleSystemType->setMinmaxIsPercent( + particleFileNode->getAttribute("ispercentbased") + ->getBoolValue()); + } + } + + damageParticleSystemTypes.push_back(unitParticleSystemType); + } + } + } + + // healthbar + if (parametersNode->hasChild("healthbar")) { + const XmlNode *healthbarNode = parametersNode->getChild("healthbar"); + if (healthbarNode->hasChild("height")) { + healthbarheight = healthbarNode->getChild("height") + ->getAttribute("value") + ->getFloatValue(); + } + if (healthbarNode->hasChild("thickness")) { + healthbarthickness = healthbarNode->getChild("thickness") + ->getAttribute("value") + ->getFloatValue(0.f, 1.f); + } + if (healthbarNode->hasChild("visible")) { + string healthbarVisibleString = healthbarNode->getChild("visible") + ->getAttribute("value") + ->getValue(); + vector v = split(healthbarVisibleString, "|"); + for (int i = 0; i < (int)v.size(); ++i) { + string current = trim(v[i]); + if (current == "always") { + healthbarVisible = healthbarVisible | hbvAlways; + } else if (current == "selected") { + healthbarVisible = healthbarVisible | hbvSelected; + } else if (current == "ifNeeded") { + healthbarVisible = healthbarVisible | hbvIfNeeded; + } else if (current == "off") { + healthbarVisible = healthbarVisible | hbvOff; + } else { + throw megaglest_runtime_error( + "Unknown Healthbar Visible Option: " + current, true); + } + } + } + } + + // light + const XmlNode *lightNode = parametersNode->getChild("light"); + light = lightNode->getAttribute("enabled")->getBoolValue(); + if (light) { + lightColor.x = lightNode->getAttribute("red")->getFloatValue(0.f, 1.f); + lightColor.y = lightNode->getAttribute("green")->getFloatValue(0.f, 1.f); + lightColor.z = lightNode->getAttribute("blue")->getFloatValue(0.f, 1.f); + } + + // rotationAllowed + if (parametersNode->hasChild("rotationAllowed")) { + const XmlNode *rotationAllowedNode = + parametersNode->getChild("rotationAllowed"); + rotationAllowed = + rotationAllowedNode->getAttribute("value")->getBoolValue(); + } else { + rotationAllowed = true; + } + + std::map sortedItems; + + // unit requirements + bool hasDup = false; + const XmlNode *unitRequirementsNode = + parametersNode->getChild("unit-requirements"); + for (int i = 0; i < (int)unitRequirementsNode->getChildCount(); ++i) { + const XmlNode *unitNode = unitRequirementsNode->getChild("unit", i); + string name = unitNode->getAttribute("name")->getRestrictedValue(); + + if (sortedItems.find(name) != sortedItems.end()) { + hasDup = true; + } + + sortedItems[name] = 0; + } + if (hasDup) { + printf("WARNING, unit type [%s] has one or more duplicate unit " + "requirements\n", + this->getName(false).c_str()); + } + + for (std::map::iterator iterMap = sortedItems.begin(); + iterMap != sortedItems.end(); ++iterMap) { + unitReqs.push_back(factionType->getUnitType(iterMap->first)); + } + sortedItems.clear(); + hasDup = false; + + // upgrade requirements + const XmlNode *upgradeRequirementsNode = + parametersNode->getChild("upgrade-requirements"); + for (int i = 0; i < (int)upgradeRequirementsNode->getChildCount(); ++i) { + const XmlNode *upgradeReqNode = + upgradeRequirementsNode->getChild("upgrade", i); + string name = upgradeReqNode->getAttribute("name")->getRestrictedValue(); + + if (sortedItems.find(name) != sortedItems.end()) { + hasDup = true; + } + + sortedItems[name] = 0; + } + + if (hasDup) { + printf("WARNING, unit type [%s] has one or more duplicate upgrade " + "requirements\n", + this->getName(false).c_str()); + } + + for (std::map::iterator iterMap = sortedItems.begin(); + iterMap != sortedItems.end(); ++iterMap) { + upgradeReqs.push_back(factionType->getUpgradeType(iterMap->first)); + } + sortedItems.clear(); + hasDup = false; + + // resource requirements + const XmlNode *resourceRequirementsNode = + parametersNode->getChild("resource-requirements"); + costs.resize(resourceRequirementsNode->getChildCount()); + for (int i = 0; i < (int)costs.size(); ++i) { + const XmlNode *resourceNode = + resourceRequirementsNode->getChild("resource", i); + string name = resourceNode->getAttribute("name")->getRestrictedValue(); + int amount = resourceNode->getAttribute("amount")->getIntValue(); + + if (sortedItems.find(name) != sortedItems.end()) { + hasDup = true; + } + sortedItems[name] = amount; + } + // if(hasDup || sortedItems.size() != costs.size()) printf("Found duplicate + // resource requirement, costs.size() = %d sortedItems.size() = + // %d\n",costs.size(),sortedItems.size()); + + if (hasDup) { + printf("WARNING, unit type [%s] has one or more duplicate resource " + "requirements\n", + this->getName(false).c_str()); + } + + if (sortedItems.size() < costs.size()) { + costs.resize(sortedItems.size()); + } + int index = 0; + for (std::map::iterator iterMap = sortedItems.begin(); + iterMap != sortedItems.end(); ++iterMap) { + try { + costs[index].init(techTree->getResourceType(iterMap->first), + iterMap->second); + index++; + } catch (megaglest_runtime_error &ex) { + if (validationMode == false) { + throw; + } else { + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\nFor UnitType: %s Cost: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what(), name.c_str(), iterMap->second); + } + } + } + sortedItems.clear(); + hasDup = false; + + // resources stored + const XmlNode *resourcesStoredNode = + parametersNode->getChild("resources-stored"); + storedResources.resize(resourcesStoredNode->getChildCount()); + for (int i = 0; i < (int)storedResources.size(); ++i) { + const XmlNode *resourceNode = + resourcesStoredNode->getChild("resource", i); + string name = resourceNode->getAttribute("name")->getRestrictedValue(); + int amount = resourceNode->getAttribute("amount")->getIntValue(); + + if (sortedItems.find(name) != sortedItems.end()) { + hasDup = true; + } + + sortedItems[name] = amount; + } + + if (hasDup) { + printf("WARNING, unit type [%s] has one or more duplicate stored " + "resources\n", + this->getName(false).c_str()); + } -void UnitType::loaddd(int id,const string &dir, const TechTree *techTree, - const string &techTreePath, const FactionType *factionType, - Checksum* checksum, Checksum* techtreeChecksum, - std::map > > &loadedFileList, - bool validationMode) { - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - - string currentPath = dir; - endPathWithSlash(currentPath); - string path = currentPath + name + ".xml"; - string sourceXMLFile = path; - - this->id= id; - - try { - //Lang &lang= Lang::getInstance(); - - char szBuf[8096]=""; - snprintf(szBuf,8096,Lang::getInstance().getString("LogScreenGameLoadingUnitType","",true).c_str(),formatString(this->getName(true)).c_str()); - Logger::getInstance().add(szBuf, true); - - //file load - checksum->addFile(path); - techtreeChecksum->addFile(path); - - XmlTree xmlTree; - std::map mapExtraTagReplacementValues; - mapExtraTagReplacementValues["$COMMONDATAPATH"] = techTreePath + "/commondata/"; - xmlTree.load(path, Properties::getTagReplacementValues(&mapExtraTagReplacementValues)); - loadedFileList[path].push_back(make_pair(dir,dir)); - - const XmlNode *unitNode= xmlTree.getRootNode(); - - const XmlNode *parametersNode= unitNode->getChild("parameters"); - - if(parametersNode->hasChild("count-in-victory-conditions") == true) { - bool countUnit = parametersNode->getChild("count-in-victory-conditions")->getAttribute("value")->getBoolValue(); - if(countUnit == true) { - countInVictoryConditions = ucvcTrue; - } - else { - countInVictoryConditions = ucvcFalse; - } - } - - //size - //checkItemInVault(&(this->size),this->size); - size= parametersNode->getChild("size")->getAttribute("value")->getIntValue(); - addItemToVault(&(this->size),this->size); - renderSize=size; - if(parametersNode->hasChild("render-size")){ - renderSize=parametersNode->getChild("render-size")->getAttribute("value")->getIntValue(); - } - aiBuildSize=size; - if(parametersNode->hasChild("ai-build-size")){ - aiBuildSize= parametersNode->getChild("ai-build-size")->getAttribute("value")->getIntValue(); - } - - //height - //checkItemInVault(&(this->height),this->height); - height= parametersNode->getChild("height")->getAttribute("value")->getIntValue(); - addItemToVault(&(this->height),this->height); - - //targetHeight - if(parametersNode->hasChild("target-height")){ - targetHeight= parametersNode->getChild("target-height")->getAttribute("value")->getIntValue(); - addItemToVault(&(this->targetHeight),this->targetHeight); - } else { - targetHeight=height; - } - //burnHeight - if(parametersNode->hasChild("target-height")){ - burnHeight= parametersNode->getChild("burn-height")->getAttribute("value")->getIntValue(); - addItemToVault(&(this->burnHeight),this->burnHeight); - } else { - burnHeight=height; - } - - - //maxHp - //checkItemInVault(&(this->maxHp),this->maxHp); - maxHp = parametersNode->getChild("max-hp")->getAttribute("value")->getIntValue(); - addItemToVault(&(this->maxHp),this->maxHp); - - //hpRegeneration - //checkItemInVault(&(this->hpRegeneration),this->hpRegeneration); - hpRegeneration= parametersNode->getChild("max-hp")->getAttribute("regeneration")->getIntValue(); - addItemToVault(&(this->hpRegeneration),this->hpRegeneration); - - //maxEp - //checkItemInVault(&(this->maxEp),this->maxEp); - maxEp= parametersNode->getChild("max-ep")->getAttribute("value")->getIntValue(); - addItemToVault(&(this->maxEp),this->maxEp); - - if(maxEp != 0) { - //epRegeneration - //checkItemInVault(&(this->epRegeneration),this->epRegeneration); - epRegeneration= parametersNode->getChild("max-ep")->getAttribute("regeneration")->getIntValue(); - } - addItemToVault(&(this->epRegeneration),this->epRegeneration); - - // Check that we don't use both start-value and start-percentage, as they are mutually - // exclusive - if(parametersNode->getChild("max-hp")->hasAttribute("start-value") && - parametersNode->getChild("max-hp")->hasAttribute("start-percentage")) { - throw megaglest_runtime_error("Unit " + name + - " has both start-value and start-percentage for HP", true); - } - - //startHpValue -- the *absolute* value to use for starting HP - if(parametersNode->getChild("max-hp")->hasAttribute("start-value")) { - //checkItemInVault(&(this->startEp),this->startEp); - startHpValue= parametersNode->getChild("max-hp")->getAttribute("start-value")->getIntValue(); - startHpType= stValue; - } - addItemToVault(&(this->startHpValue),this->startHpValue); - - //startHpPercentage -- the *relative* value to use for starting HP - if(parametersNode->getChild("max-hp")->hasAttribute("start-percentage")) { - startHpPercentage= parametersNode->getChild("max-hp")->getAttribute("start-percentage")->getIntValue(); - startHpType= stPercentage; - } - - // No start value is set; use 100% of the current Max - if(!parametersNode->getChild("max-hp")->hasAttribute("start-value") && - !parametersNode->getChild("max-hp")->hasAttribute("start-percentage")) { - startHpPercentage=100; - startHpType= stPercentage; - } - addItemToVault(&(this->startHpPercentage),this->startHpPercentage); - - // Check that we don't use both start-value and start-percentage, as they are mutually - // exclusive - if(parametersNode->getChild("max-ep")->hasAttribute("start-value") && - parametersNode->getChild("max-ep")->hasAttribute("start-percentage")) { - throw megaglest_runtime_error("Unit " + name + - " has both start-value and start-percentage for EP", true); - } - - //startEpValue -- the *absolute* value to use for starting EP - if(parametersNode->getChild("max-ep")->hasAttribute("start-value")) { - //checkItemInVault(&(this->startEp),this->startEp); - startEpValue= parametersNode->getChild("max-ep")->getAttribute("start-value")->getIntValue(); - startEpType= stValue; - } - addItemToVault(&(this->startEpValue),this->startEpValue); - - //startEpPercentage -- the *relative* value to use for starting EP - if(parametersNode->getChild("max-ep")->hasAttribute("start-percentage")) { - startEpPercentage= parametersNode->getChild("max-ep")->getAttribute("start-percentage")->getIntValue(); - startEpType= stPercentage; - } - addItemToVault(&(this->startEpPercentage),this->startEpPercentage); - - //maxUnitCount - if(parametersNode->hasChild("max-unit-count")) { - //checkItemInVault(&(this->maxUnitCount),this->maxUnitCount); - maxUnitCount= parametersNode->getChild("max-unit-count")->getAttribute("value")->getIntValue(); - } - addItemToVault(&(this->maxUnitCount),this->maxUnitCount); - - //armor - //checkItemInVault(&(this->armor),this->armor); - armor= parametersNode->getChild("armor")->getAttribute("value")->getIntValue(); - addItemToVault(&(this->armor),this->armor); - - //armor type string - string armorTypeName= parametersNode->getChild("armor-type")->getAttribute("value")->getRestrictedValue(); - armorType= techTree->getArmorType(armorTypeName); - - //sight - //checkItemInVault(&(this->sight),this->sight); - sight= parametersNode->getChild("sight")->getAttribute("value")->getIntValue(); - addItemToVault(&(this->sight),this->sight); - - //prod time - productionTime= parametersNode->getChild("time")->getAttribute("value")->getIntValue(); - - //multi selection - multiSelect= parametersNode->getChild("multi-selection")->getAttribute("value")->getBoolValue(); - - //uniform selection - if(parametersNode->hasChild("uniform-selection")) { - uniformSelect= parametersNode->getChild("uniform-selection")->getAttribute("value")->getBoolValue(); - } - - //commandable - if(parametersNode->hasChild("commandable")){ - commandable= parametersNode->getChild("commandable")->getAttribute("value")->getBoolValue(); - } - //cellmap - allowEmptyCellMap = false; - const XmlNode *cellMapNode= parametersNode->getChild("cellmap"); - bool hasCellMap= cellMapNode->getAttribute("value")->getBoolValue(); - if(hasCellMap == true) { - if(cellMapNode->getAttribute("allowEmpty",false) != NULL) { - allowEmptyCellMap = cellMapNode->getAttribute("allowEmpty")->getBoolValue(); - } - - cellMap= new bool[size*size]; - for(int i=0; igetChild("row", i); - string row= rowNode->getAttribute("value")->getRestrictedValue(); - if((int)row.size() != size){ - throw megaglest_runtime_error("Cellmap row has not the same length as unit size",true); - } - for(int j=0; j < (int)row.size(); ++j){ - cellMap[i*size+j]= row[j]=='0'? false: true; - } - } - } - - //levels - const XmlNode *levelsNode= parametersNode->getChild("levels"); - levels.resize(levelsNode->getChildCount()); - for(int i=0; i < (int)levels.size(); ++i){ - const XmlNode *levelNode= levelsNode->getChild("level", i); - - levels[i].init( - levelNode->getAttribute("name")->getRestrictedValue(), - levelNode->getAttribute("kills")->getIntValue()); - } - - //fields - const XmlNode *fieldsNode= parametersNode->getChild("fields"); - for(int i=0; i < (int)fieldsNode->getChildCount(); ++i){ - const XmlNode *fieldNode= fieldsNode->getChild("field", i); - string fieldName= fieldNode->getAttribute("value")->getRestrictedValue(); - if(fieldName=="land"){ - fields[fLand]= true; - } - else if(fieldName=="air"){ - fields[fAir]= true; - } - else{ - throw megaglest_runtime_error("Not a valid field: "+fieldName+": "+ path, true); - } - } - - if (fields[fLand]) { - field = fLand; - } - else if (fields[fAir]) { - field = fAir; - } - else { - throw megaglest_runtime_error("Unit has no field: " + path, true); - } - - //properties - const XmlNode *propertiesNode= parametersNode->getChild("properties"); - for(int i = 0; i < (int)propertiesNode->getChildCount(); ++i) { - const XmlNode *propertyNode= propertiesNode->getChild("property", i); - string propertyName= propertyNode->getAttribute("value")->getRestrictedValue(); - bool found= false; - for(int i = 0; i < pCount; ++i) { - if(propertyName == propertyNames[i]) { - properties[i]= true; - found= true; - break; - } - } - if(!found) { - throw megaglest_runtime_error("Unknown property: " + propertyName, true); - } - } - //damage-particles - if(parametersNode->hasChild("damage-particles")) { - const XmlNode *particleNode= parametersNode->getChild("damage-particles"); - bool particleEnabled= particleNode->getAttribute("value")->getBoolValue(); - - if(particleEnabled) { - for(int i = 0; i < (int)particleNode->getChildCount(); ++i) { - const XmlNode *particleFileNode= particleNode->getChild("particle-file", i); - string path= particleFileNode->getAttribute("path")->getRestrictedValue(); - UnitParticleSystemType *unitParticleSystemType= new UnitParticleSystemType(); - - unitParticleSystemType->load(particleFileNode, dir, currentPath + path, - &Renderer::getInstance(),loadedFileList, sourceXMLFile, - techTree->getPath()); - loadedFileList[currentPath + path].push_back(make_pair(sourceXMLFile,particleFileNode->getAttribute("path")->getRestrictedValue())); - - if(particleFileNode->getAttribute("minHp",false) != NULL && particleFileNode->getAttribute("maxHp",false) != NULL) { - unitParticleSystemType->setMinmaxEnabled(true); - unitParticleSystemType->setMinHp(particleFileNode->getAttribute("minHp")->getIntValue()); - unitParticleSystemType->setMaxHp(particleFileNode->getAttribute("maxHp")->getIntValue()); - - if(particleFileNode->getAttribute("ispercentbased",false) != NULL) { - unitParticleSystemType->setMinmaxIsPercent(particleFileNode->getAttribute("ispercentbased")->getBoolValue()); - } - - } - - damageParticleSystemTypes.push_back(unitParticleSystemType); - } - } - } - - //healthbar - if(parametersNode->hasChild("healthbar")) { - const XmlNode *healthbarNode= parametersNode->getChild("healthbar"); - if(healthbarNode->hasChild("height")) { - healthbarheight= healthbarNode->getChild("height")->getAttribute("value")->getFloatValue(); - } - if(healthbarNode->hasChild("thickness")) { - healthbarthickness= healthbarNode->getChild("thickness")->getAttribute("value")->getFloatValue(0.f, 1.f); - } - if(healthbarNode->hasChild("visible")) { - string healthbarVisibleString=healthbarNode->getChild("visible")->getAttribute("value")->getValue(); - vector v=split(healthbarVisibleString,"|"); - for (int i = 0; i < (int)v.size(); ++i) { - string current=trim(v[i]); - if(current=="always") { - healthbarVisible=healthbarVisible|hbvAlways; - } else if(current=="selected") { - healthbarVisible=healthbarVisible|hbvSelected; - } else if(current=="ifNeeded") { - healthbarVisible=healthbarVisible|hbvIfNeeded; - } else if(current=="off") { - healthbarVisible=healthbarVisible|hbvOff; - } else { - throw megaglest_runtime_error("Unknown Healthbar Visible Option: " + current, true); - } - } - } - } - - //light - const XmlNode *lightNode= parametersNode->getChild("light"); - light= lightNode->getAttribute("enabled")->getBoolValue(); - if(light){ - lightColor.x= lightNode->getAttribute("red")->getFloatValue(0.f, 1.f); - lightColor.y= lightNode->getAttribute("green")->getFloatValue(0.f, 1.f); - lightColor.z= lightNode->getAttribute("blue")->getFloatValue(0.f, 1.f); - } - - //rotationAllowed - if(parametersNode->hasChild("rotationAllowed")) { - const XmlNode *rotationAllowedNode= parametersNode->getChild("rotationAllowed"); - rotationAllowed= rotationAllowedNode->getAttribute("value")->getBoolValue(); - } - else - { - rotationAllowed=true; - } - - std::map sortedItems; - - //unit requirements - bool hasDup = false; - const XmlNode *unitRequirementsNode= parametersNode->getChild("unit-requirements"); - for(int i=0; i < (int)unitRequirementsNode->getChildCount(); ++i){ - const XmlNode *unitNode= unitRequirementsNode->getChild("unit", i); - string name= unitNode->getAttribute("name")->getRestrictedValue(); - - if(sortedItems.find(name) != sortedItems.end()) { - hasDup = true; - } - - sortedItems[name] = 0; - } - if(hasDup) { - printf("WARNING, unit type [%s] has one or more duplicate unit requirements\n",this->getName(false).c_str()); - } - - for(std::map::iterator iterMap = sortedItems.begin(); - iterMap != sortedItems.end(); ++iterMap) { - unitReqs.push_back(factionType->getUnitType(iterMap->first)); - } - sortedItems.clear(); - hasDup = false; - - //upgrade requirements - const XmlNode *upgradeRequirementsNode= parametersNode->getChild("upgrade-requirements"); - for(int i=0; i < (int)upgradeRequirementsNode->getChildCount(); ++i){ - const XmlNode *upgradeReqNode= upgradeRequirementsNode->getChild("upgrade", i); - string name= upgradeReqNode->getAttribute("name")->getRestrictedValue(); - - if(sortedItems.find(name) != sortedItems.end()) { - hasDup = true; - } - - sortedItems[name] = 0; - } - - if(hasDup) { - printf("WARNING, unit type [%s] has one or more duplicate upgrade requirements\n",this->getName(false).c_str()); - } - - for(std::map::iterator iterMap = sortedItems.begin(); - iterMap != sortedItems.end(); ++iterMap) { - upgradeReqs.push_back(factionType->getUpgradeType(iterMap->first)); - } - sortedItems.clear(); - hasDup = false; - - //resource requirements - const XmlNode *resourceRequirementsNode= parametersNode->getChild("resource-requirements"); - costs.resize(resourceRequirementsNode->getChildCount()); - for(int i = 0; i < (int)costs.size(); ++i) { - const XmlNode *resourceNode= resourceRequirementsNode->getChild("resource", i); - string name= resourceNode->getAttribute("name")->getRestrictedValue(); - int amount= resourceNode->getAttribute("amount")->getIntValue(); - - if(sortedItems.find(name) != sortedItems.end()) { - hasDup = true; - } - sortedItems[name] = amount; - } - //if(hasDup || sortedItems.size() != costs.size()) printf("Found duplicate resource requirement, costs.size() = %d sortedItems.size() = %d\n",costs.size(),sortedItems.size()); - - if(hasDup) { - printf("WARNING, unit type [%s] has one or more duplicate resource requirements\n",this->getName(false).c_str()); - } - - if(sortedItems.size() < costs.size()) { - costs.resize(sortedItems.size()); - } - int index = 0; - for(std::map::iterator iterMap = sortedItems.begin(); - iterMap != sortedItems.end(); ++iterMap) { - try { - costs[index].init(techTree->getResourceType(iterMap->first), iterMap->second); - index++; - } - catch(megaglest_runtime_error& ex) { - if(validationMode == false) { - throw; - } - else { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\nFor UnitType: %s Cost: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what(),name.c_str(),iterMap->second); - } - } - } - sortedItems.clear(); - hasDup = false; - - //resources stored - const XmlNode *resourcesStoredNode= parametersNode->getChild("resources-stored"); - storedResources.resize(resourcesStoredNode->getChildCount()); - for(int i=0; i < (int)storedResources.size(); ++i){ - const XmlNode *resourceNode= resourcesStoredNode->getChild("resource", i); - string name= resourceNode->getAttribute("name")->getRestrictedValue(); - int amount= resourceNode->getAttribute("amount")->getIntValue(); - - if(sortedItems.find(name) != sortedItems.end()) { - hasDup = true; - } - - sortedItems[name] = amount; - } - - if(hasDup) { - printf("WARNING, unit type [%s] has one or more duplicate stored resources\n",this->getName(false).c_str()); - } - - if(sortedItems.size() < storedResources.size()) { - storedResources.resize(sortedItems.size()); - } - - index = 0; - for(std::map::iterator iterMap = sortedItems.begin(); - iterMap != sortedItems.end(); ++iterMap) { - try { - storedResources[index].init(techTree->getResourceType(iterMap->first), iterMap->second); - index++; - } - catch(megaglest_runtime_error& ex) { - if(validationMode == false) { - throw; - } - else { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\nFor UnitType: %s Store: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what(),name.c_str(),iterMap->second); - } - } - } - sortedItems.clear(); - //hasDup = false; - - // Lootable resources (resources given/lost on death) - if(parametersNode->hasChild("resources-death")) { - const XmlNode *deathResourcesNode= parametersNode->getChild("resources-death"); - - for(unsigned int i = 0; i < deathResourcesNode->getChildCount(); ++i){ - const XmlNode *resourceNode= deathResourcesNode->getChild("resource", i); - string name= resourceNode->getAttribute("name")->getRestrictedValue(); - - LootableResource resource; - resource.setResourceType(techTree->getResourceType(name)); - - // All attributes are optional, although nothing happens if they aren't used. They can - // be combined freely. Percentages will take affect before absolute values. - if(resourceNode->hasAttribute("amount-value")) { - resource.setAmountValue(resourceNode->getAttribute("amount-value")->getIntValue()); - } - else { - resource.setAmountValue(0); - } - - if(resourceNode->hasAttribute("amount-faction-percent")) { - resource.setAmountFactionPercent(resourceNode->getAttribute("amount-faction-percent")->getIntValue()); - } - else { - resource.setAmountFactionPercent(0); - } - - if(resourceNode->hasAttribute("loss-value")) { - resource.setLossValue(resourceNode->getAttribute("loss-value")->getIntValue()); - } - else { - resource.setLossValue(0); - } - - if(resourceNode->hasAttribute("loss-faction-percent")) { - resource.setLossFactionPercent(resourceNode->getAttribute("loss-faction-percent")->getIntValue()); - } - else { - resource.setLossFactionPercent(0); - } - - if(resourceNode->hasAttribute("allow-negative")) { - resource.setNegativeAllowed(resourceNode->getAttribute("allow-negative")->getBoolValue()); - } - else { - resource.setNegativeAllowed(false); - } - - // Figure out if there are duplicate resources. The value stored in the map is arbitrary, - // and exists solely because - if(std::find(lootableResources.begin(), lootableResources.end(), resource) != lootableResources.end()) { - printf("WARNING, unit type [%s] has one or more duplicate lootable resources\n", this->getName(false).c_str()); - } - - lootableResources.push_back(resource); - } - } - - // Tags - if(parametersNode->hasChild("tags")) { - const XmlNode *tagsNode= parametersNode->getChild("tags"); - - for(unsigned int i = 0; i < tagsNode->getChildCount(); ++i){ - const XmlNode *resourceNode= tagsNode->getChild("tag", i); - string tag= resourceNode->getAttribute("value")->getRestrictedValue(); - tags.insert(tag); - } - } - - //image - const XmlNode *imageNode= parametersNode->getChild("image"); - image= Renderer::getInstance().newTexture2D(rsGame); - if(image) { - image->load(imageNode->getAttribute("path")->getRestrictedValue(currentPath)); - } - loadedFileList[imageNode->getAttribute("path")->getRestrictedValue(currentPath)].push_back(make_pair(sourceXMLFile,imageNode->getAttribute("path")->getRestrictedValue())); - - //image cancel - const XmlNode *imageCancelNode= parametersNode->getChild("image-cancel"); - cancelImage= Renderer::getInstance().newTexture2D(rsGame); - if(cancelImage) { - cancelImage->load(imageCancelNode->getAttribute("path")->getRestrictedValue(currentPath)); - } - loadedFileList[imageCancelNode->getAttribute("path")->getRestrictedValue(currentPath)].push_back(make_pair(sourceXMLFile,imageCancelNode->getAttribute("path")->getRestrictedValue())); - - //meeting point - const XmlNode *meetingPointNode= parametersNode->getChild("meeting-point"); - meetingPoint= meetingPointNode->getAttribute("value")->getBoolValue(); - if(meetingPoint) { - meetingPointImage= Renderer::getInstance().newTexture2D(rsGame); - if(meetingPointImage) { - meetingPointImage->load(meetingPointNode->getAttribute("image-path")->getRestrictedValue(currentPath)); - } - loadedFileList[meetingPointNode->getAttribute("image-path")->getRestrictedValue(currentPath)].push_back(make_pair(sourceXMLFile,meetingPointNode->getAttribute("image-path")->getRestrictedValue())); - } - - //countUnitDeathInStats - if(parametersNode->hasChild("count-unit-death-in-stats")){ - const XmlNode *countUnitDeathInStatsNode= parametersNode->getChild("count-unit-death-in-stats"); - countUnitDeathInStats= countUnitDeathInStatsNode->getAttribute("value")->getBoolValue(); - } - else { - countUnitDeathInStats=true; - } - //countUnitProductionInStats - if(parametersNode->hasChild("count-unit-production-in-stats")){ - const XmlNode *countUnitProductionInStatsNode= parametersNode->getChild("count-unit-production-in-stats"); - countUnitProductionInStats= countUnitProductionInStatsNode->getAttribute("value")->getBoolValue(); - } - else { - countUnitProductionInStats=true; - } - //countUnitKillInStats - if(parametersNode->hasChild("count-unit-kill-in-stats")){ - const XmlNode *countUnitKillInStatsNode= parametersNode->getChild("count-unit-kill-in-stats"); - countUnitKillInStats= countUnitKillInStatsNode->getAttribute("value")->getBoolValue(); - } - else { - countUnitKillInStats=true; - } - - //countKillForUnitUpgrade - if(parametersNode->hasChild("count-kill-for-unit-upgrade")){ - const XmlNode *countKillForUnitUpgradeNode= parametersNode->getChild("count-kill-for-unit-upgrade"); - countKillForUnitUpgrade= countKillForUnitUpgradeNode->getAttribute("value")->getBoolValue(); - } else { - countKillForUnitUpgrade=true; - } - - if(countKillForUnitUpgrade == false){ - // it makes no sense if we count it in stats but not for upgrades - countUnitKillInStats=false; - } - - //selection sounds - const XmlNode *selectionSoundNode= parametersNode->getChild("selection-sounds"); - if(selectionSoundNode->getAttribute("enabled")->getBoolValue()){ - selectionSounds.resize((int)selectionSoundNode->getChildCount()); - for(int i = 0; i < (int)selectionSounds.getSounds().size(); ++i) { - const XmlNode *soundNode= selectionSoundNode->getChild("sound", i); - string path= soundNode->getAttribute("path")->getRestrictedValue(currentPath); - StaticSound *sound= new StaticSound(); - sound->load(path); - loadedFileList[path].push_back(make_pair(sourceXMLFile,soundNode->getAttribute("path")->getRestrictedValue())); - selectionSounds[i]= sound; - } - } - - //command sounds - const XmlNode *commandSoundNode= parametersNode->getChild("command-sounds"); - if(commandSoundNode->getAttribute("enabled")->getBoolValue()) { - commandSounds.resize((int)commandSoundNode->getChildCount()); - for(int i = 0; i < (int)commandSoundNode->getChildCount(); ++i) { - const XmlNode *soundNode= commandSoundNode->getChild("sound", i); - string path= soundNode->getAttribute("path")->getRestrictedValue(currentPath); - StaticSound *sound= new StaticSound(); - sound->load(path); - loadedFileList[path].push_back(make_pair(sourceXMLFile,soundNode->getAttribute("path")->getRestrictedValue())); - commandSounds[i]= sound; - } - } - - //skills - - const XmlNode *attackBoostsNode= NULL; - if(unitNode->hasChild("attack-boosts") == true) { - attackBoostsNode=unitNode->getChild("attack-boosts"); - } - - const XmlNode *skillsNode= unitNode->getChild("skills"); - skillTypes.resize(skillsNode->getChildCount()); - - snprintf(szBuf,8096,Lang::getInstance().getString("LogScreenGameLoadingUnitTypeSkills","",true).c_str(),formatString(this->getName(true)).c_str(),skillTypes.size()); - Logger::getInstance().add(szBuf, true); - - for(int i = 0; i < (int)skillTypes.size(); ++i) { - const XmlNode *sn= skillsNode->getChild("skill", i); - const XmlNode *typeNode= sn->getChild("type"); - string classId= typeNode->getAttribute("value")->getRestrictedValue(); - SkillType *skillType= SkillTypeFactory::getInstance().newInstance(classId); - - skillTypes[i]=NULL; - try { - skillType->load(sn, attackBoostsNode, dir, techTree, factionType, loadedFileList,sourceXMLFile); - skillTypes[i]= skillType; - } - catch(megaglest_runtime_error& ex) { - if(validationMode == false) { - throw; - } - else { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\nFor UnitType: %s SkillType: %s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what(),name.c_str(),classId.c_str()); - } - } - } - - //commands - const XmlNode *commandsNode= unitNode->getChild("commands"); - commandTypes.resize(commandsNode->getChildCount()); - for(int i = 0; i < (int)commandTypes.size(); ++i) { - const XmlNode *commandNode= commandsNode->getChild("command", i); - const XmlNode *typeNode= commandNode->getChild("type"); - string classId= typeNode->getAttribute("value")->getRestrictedValue(); - CommandType *commandType= CommandTypeFactory::getInstance().newInstance(classId); - - commandTypes[i]=NULL; - try { - commandType->load(i, commandNode, dir, techTree, factionType, *this, - loadedFileList,sourceXMLFile); - commandTypes[i]= commandType; - } - catch(megaglest_runtime_error& ex) { - if(validationMode == false) { - throw; - } - else { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\nFor UnitType: %s CommandType:%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what(),name.c_str(),classId.c_str()); - } - } - } - - computeFirstStOfClass(); - computeFirstCtOfClass(); - - if(getFirstStOfClass(scStop)==NULL){ - throw megaglest_runtime_error("Every unit must have at least one stop skill: "+ path,true); - } - if(getFirstStOfClass(scDie)==NULL){ - throw megaglest_runtime_error("Every unit must have at least one die skill: "+ path,true); - } - - } - //Exception handling (conversions and so on); - catch(megaglest_runtime_error& ex) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - throw megaglest_runtime_error("Error loading UnitType: " + path + "\nMessage: " + ex.what(),!ex.wantStackTrace()); - } - catch(const exception &e){ - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what()); - throw megaglest_runtime_error("Error loading UnitType: " + path + "\nMessage: " + e.what()); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + if (sortedItems.size() < storedResources.size()) { + storedResources.resize(sortedItems.size()); + } + + index = 0; + for (std::map::iterator iterMap = sortedItems.begin(); + iterMap != sortedItems.end(); ++iterMap) { + try { + storedResources[index].init(techTree->getResourceType(iterMap->first), + iterMap->second); + index++; + } catch (megaglest_runtime_error &ex) { + if (validationMode == false) { + throw; + } else { + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\nFor UnitType: %s Store: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what(), name.c_str(), iterMap->second); + } + } + } + sortedItems.clear(); + // hasDup = false; + + // Lootable resources (resources given/lost on death) + if (parametersNode->hasChild("resources-death")) { + const XmlNode *deathResourcesNode = + parametersNode->getChild("resources-death"); + + for (unsigned int i = 0; i < deathResourcesNode->getChildCount(); ++i) { + const XmlNode *resourceNode = + deathResourcesNode->getChild("resource", i); + string name = resourceNode->getAttribute("name")->getRestrictedValue(); + + LootableResource resource; + resource.setResourceType(techTree->getResourceType(name)); + + // All attributes are optional, although nothing happens if they aren't + // used. They can be combined freely. Percentages will take affect + // before absolute values. + if (resourceNode->hasAttribute("amount-value")) { + resource.setAmountValue( + resourceNode->getAttribute("amount-value")->getIntValue()); + } else { + resource.setAmountValue(0); + } + + if (resourceNode->hasAttribute("amount-faction-percent")) { + resource.setAmountFactionPercent( + resourceNode->getAttribute("amount-faction-percent") + ->getIntValue()); + } else { + resource.setAmountFactionPercent(0); + } + + if (resourceNode->hasAttribute("loss-value")) { + resource.setLossValue( + resourceNode->getAttribute("loss-value")->getIntValue()); + } else { + resource.setLossValue(0); + } + + if (resourceNode->hasAttribute("loss-faction-percent")) { + resource.setLossFactionPercent( + resourceNode->getAttribute("loss-faction-percent") + ->getIntValue()); + } else { + resource.setLossFactionPercent(0); + } + + if (resourceNode->hasAttribute("allow-negative")) { + resource.setNegativeAllowed( + resourceNode->getAttribute("allow-negative")->getBoolValue()); + } else { + resource.setNegativeAllowed(false); + } + + // Figure out if there are duplicate resources. The value stored in the + // map is arbitrary, and exists solely because + if (std::find(lootableResources.begin(), lootableResources.end(), + resource) != lootableResources.end()) { + printf("WARNING, unit type [%s] has one or more duplicate lootable " + "resources\n", + this->getName(false).c_str()); + } + + lootableResources.push_back(resource); + } + } + + // Tags + if (parametersNode->hasChild("tags")) { + const XmlNode *tagsNode = parametersNode->getChild("tags"); + + for (unsigned int i = 0; i < tagsNode->getChildCount(); ++i) { + const XmlNode *resourceNode = tagsNode->getChild("tag", i); + string tag = resourceNode->getAttribute("value")->getRestrictedValue(); + tags.insert(tag); + } + } + + // image + const XmlNode *imageNode = parametersNode->getChild("image"); + image = Renderer::getInstance().newTexture2D(rsGame); + if (image) { + image->load( + imageNode->getAttribute("path")->getRestrictedValue(currentPath)); + } + loadedFileList[imageNode->getAttribute("path")->getRestrictedValue( + currentPath)] + .push_back( + make_pair(sourceXMLFile, + imageNode->getAttribute("path")->getRestrictedValue())); + + // image cancel + const XmlNode *imageCancelNode = parametersNode->getChild("image-cancel"); + cancelImage = Renderer::getInstance().newTexture2D(rsGame); + if (cancelImage) { + cancelImage->load( + imageCancelNode->getAttribute("path")->getRestrictedValue( + currentPath)); + } + loadedFileList[imageCancelNode->getAttribute("path")->getRestrictedValue( + currentPath)] + .push_back(make_pair( + sourceXMLFile, + imageCancelNode->getAttribute("path")->getRestrictedValue())); + + // meeting point + const XmlNode *meetingPointNode = parametersNode->getChild("meeting-point"); + meetingPoint = meetingPointNode->getAttribute("value")->getBoolValue(); + if (meetingPoint) { + meetingPointImage = Renderer::getInstance().newTexture2D(rsGame); + if (meetingPointImage) { + meetingPointImage->load(meetingPointNode->getAttribute("image-path") + ->getRestrictedValue(currentPath)); + } + loadedFileList[meetingPointNode->getAttribute("image-path") + ->getRestrictedValue(currentPath)] + .push_back(make_pair(sourceXMLFile, + meetingPointNode->getAttribute("image-path") + ->getRestrictedValue())); + } + + // countUnitDeathInStats + if (parametersNode->hasChild("count-unit-death-in-stats")) { + const XmlNode *countUnitDeathInStatsNode = + parametersNode->getChild("count-unit-death-in-stats"); + countUnitDeathInStats = + countUnitDeathInStatsNode->getAttribute("value")->getBoolValue(); + } else { + countUnitDeathInStats = true; + } + // countUnitProductionInStats + if (parametersNode->hasChild("count-unit-production-in-stats")) { + const XmlNode *countUnitProductionInStatsNode = + parametersNode->getChild("count-unit-production-in-stats"); + countUnitProductionInStats = + countUnitProductionInStatsNode->getAttribute("value")->getBoolValue(); + } else { + countUnitProductionInStats = true; + } + // countUnitKillInStats + if (parametersNode->hasChild("count-unit-kill-in-stats")) { + const XmlNode *countUnitKillInStatsNode = + parametersNode->getChild("count-unit-kill-in-stats"); + countUnitKillInStats = + countUnitKillInStatsNode->getAttribute("value")->getBoolValue(); + } else { + countUnitKillInStats = true; + } + + // countKillForUnitUpgrade + if (parametersNode->hasChild("count-kill-for-unit-upgrade")) { + const XmlNode *countKillForUnitUpgradeNode = + parametersNode->getChild("count-kill-for-unit-upgrade"); + countKillForUnitUpgrade = + countKillForUnitUpgradeNode->getAttribute("value")->getBoolValue(); + } else { + countKillForUnitUpgrade = true; + } + + if (countKillForUnitUpgrade == false) { + // it makes no sense if we count it in stats but not for upgrades + countUnitKillInStats = false; + } + + // selection sounds + const XmlNode *selectionSoundNode = + parametersNode->getChild("selection-sounds"); + if (selectionSoundNode->getAttribute("enabled")->getBoolValue()) { + selectionSounds.resize((int)selectionSoundNode->getChildCount()); + for (int i = 0; i < (int)selectionSounds.getSounds().size(); ++i) { + const XmlNode *soundNode = selectionSoundNode->getChild("sound", i); + string path = + soundNode->getAttribute("path")->getRestrictedValue(currentPath); + StaticSound *sound = new StaticSound(); + sound->load(path); + loadedFileList[path].push_back( + make_pair(sourceXMLFile, + soundNode->getAttribute("path")->getRestrictedValue())); + selectionSounds[i] = sound; + } + } + + // command sounds + const XmlNode *commandSoundNode = + parametersNode->getChild("command-sounds"); + if (commandSoundNode->getAttribute("enabled")->getBoolValue()) { + commandSounds.resize((int)commandSoundNode->getChildCount()); + for (int i = 0; i < (int)commandSoundNode->getChildCount(); ++i) { + const XmlNode *soundNode = commandSoundNode->getChild("sound", i); + string path = + soundNode->getAttribute("path")->getRestrictedValue(currentPath); + StaticSound *sound = new StaticSound(); + sound->load(path); + loadedFileList[path].push_back( + make_pair(sourceXMLFile, + soundNode->getAttribute("path")->getRestrictedValue())); + commandSounds[i] = sound; + } + } + + // skills + + const XmlNode *attackBoostsNode = NULL; + if (unitNode->hasChild("attack-boosts") == true) { + attackBoostsNode = unitNode->getChild("attack-boosts"); + } + + const XmlNode *skillsNode = unitNode->getChild("skills"); + skillTypes.resize(skillsNode->getChildCount()); + + snprintf(szBuf, 8096, + Lang::getInstance() + .getString("LogScreenGameLoadingUnitTypeSkills", "", true) + .c_str(), + formatString(this->getName(true)).c_str(), skillTypes.size()); + Logger::getInstance().add(szBuf, true); + + for (int i = 0; i < (int)skillTypes.size(); ++i) { + const XmlNode *sn = skillsNode->getChild("skill", i); + const XmlNode *typeNode = sn->getChild("type"); + string classId = typeNode->getAttribute("value")->getRestrictedValue(); + SkillType *skillType = + SkillTypeFactory::getInstance().newInstance(classId); + + skillTypes[i] = NULL; + try { + skillType->load(sn, attackBoostsNode, dir, techTree, factionType, + loadedFileList, sourceXMLFile); + skillTypes[i] = skillType; + } catch (megaglest_runtime_error &ex) { + if (validationMode == false) { + throw; + } else { + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\nFor UnitType: %s SkillType: " + "%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what(), name.c_str(), classId.c_str()); + } + } + } + + // commands + const XmlNode *commandsNode = unitNode->getChild("commands"); + commandTypes.resize(commandsNode->getChildCount()); + for (int i = 0; i < (int)commandTypes.size(); ++i) { + const XmlNode *commandNode = commandsNode->getChild("command", i); + const XmlNode *typeNode = commandNode->getChild("type"); + string classId = typeNode->getAttribute("value")->getRestrictedValue(); + CommandType *commandType = + CommandTypeFactory::getInstance().newInstance(classId); + + commandTypes[i] = NULL; + try { + commandType->load(i, commandNode, dir, techTree, factionType, *this, + loadedFileList, sourceXMLFile); + commandTypes[i] = commandType; + } catch (megaglest_runtime_error &ex) { + if (validationMode == false) { + throw; + } else { + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\nFor UnitType: %s " + "CommandType:%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what(), name.c_str(), classId.c_str()); + } + } + } + + computeFirstStOfClass(); + computeFirstCtOfClass(); + + if (getFirstStOfClass(scStop) == NULL) { + throw megaglest_runtime_error( + "Every unit must have at least one stop skill: " + path, true); + } + if (getFirstStOfClass(scDie) == NULL) { + throw megaglest_runtime_error( + "Every unit must have at least one die skill: " + path, true); + } + + } + // Exception handling (conversions and so on); + catch (megaglest_runtime_error &ex) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + throw megaglest_runtime_error("Error loading UnitType: " + path + + "\nMessage: " + ex.what(), + !ex.wantStackTrace()); + } catch (const exception &e) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, e.what()); + throw megaglest_runtime_error("Error loading UnitType: " + path + + "\nMessage: " + e.what()); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__); } // ==================== get ==================== const Level *UnitType::getLevel(string name) const { - const Level *result = NULL; - for(unsigned int i = 0; i < levels.size(); ++i) { - const Level &level = levels[i]; - if(level.getName() == name) { - result = &level; - break; - } - } - - return result; + const Level *result = NULL; + for (unsigned int i = 0; i < levels.size(); ++i) { + const Level &level = levels[i]; + if (level.getName() == name) { + result = &level; + break; + } + } + + return result; } -const CommandType *UnitType::getFirstCtOfClass(CommandClass commandClass) const{ - if(firstCommandTypeOfClass[commandClass] == NULL) { - return NULL; - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] commandClass = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,commandClass); - - /* - for(int j=0; jgetClass()== CommandClass(j)){ - return commandTypes[i]; - } - } - } - */ - - //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - return firstCommandTypeOfClass[commandClass]; +const CommandType * +UnitType::getFirstCtOfClass(CommandClass commandClass) const { + if (firstCommandTypeOfClass[commandClass] == NULL) { + return NULL; + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] + // commandClass = + // %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,commandClass); + + /* +for(int j=0; jgetClass()== CommandClass(j)){ + return commandTypes[i]; + } + } } +*/ -const SkillType *UnitType::getFirstStOfClass(SkillClass skillClass) const{ - if(firstSkillTypeOfClass[skillClass] == NULL) { - /* - for(int j= 0; jgetClass()== SkillClass(j)){ - return skillTypes[i]; - } - } - } - */ - //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - } - return firstSkillTypeOfClass[skillClass]; + // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + } + return firstCommandTypeOfClass[commandClass]; } -const HarvestCommandType *UnitType::getFirstHarvestCommand(const ResourceType *resourceType, const Faction *faction) const { - for(int i = 0; i < (int)commandTypes.size(); ++i) { - if(commandTypes[i]->getClass() == ccHarvest) { - const HarvestCommandType *hct = static_cast(commandTypes[i]); - - if (faction->reqsOk(hct) == false) { - continue; - } - - if(hct->canHarvest(resourceType)) { - return hct; - } - } - } - return NULL; +const SkillType *UnitType::getFirstStOfClass(SkillClass skillClass) const { + if (firstSkillTypeOfClass[skillClass] == NULL) { + /* + for(int j= 0; jgetClass()== SkillClass(j)){ + return skillTypes[i]; + } + } +} +*/ + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + } + return firstSkillTypeOfClass[skillClass]; } -const HarvestEmergencyReturnCommandType *UnitType::getFirstHarvestEmergencyReturnCommand() const { - const HarvestEmergencyReturnCommandType *result = dynamic_cast(ctHarvestEmergencyReturnCommandType.get()); - return result; +const HarvestCommandType * +UnitType::getFirstHarvestCommand(const ResourceType *resourceType, + const Faction *faction) const { + for (int i = 0; i < (int)commandTypes.size(); ++i) { + if (commandTypes[i]->getClass() == ccHarvest) { + const HarvestCommandType *hct = + static_cast(commandTypes[i]); + + if (faction->reqsOk(hct) == false) { + continue; + } + + if (hct->canHarvest(resourceType)) { + return hct; + } + } + } + return NULL; } -const AttackCommandType *UnitType::getFirstAttackCommand(Field field) const{ - //printf("$$$ Unit [%s] commandTypes.size() = %d\n",this->getName().c_str(),(int)commandTypes.size()); - - for(int i = 0; i < (int)commandTypes.size(); ++i){ - if(commandTypes[i] == NULL) { - throw megaglest_runtime_error("commandTypes[i] == NULL"); - } - - //printf("$$$ Unit [%s] i = %d, commandTypes[i] [%s]\n",this->getName().c_str(),(int)i, commandTypes[i]->toString().c_str()); - if(commandTypes[i]->getClass()== ccAttack){ - const AttackCommandType *act= dynamic_cast(commandTypes[i]); - if(act != NULL && act->getAttackSkillType()->getAttackField(field)) { - //printf("## Unit [%s] i = %d, is found\n",this->getName().c_str(),(int)i); - return act; - } - } - } - - return NULL; +const HarvestEmergencyReturnCommandType * +UnitType::getFirstHarvestEmergencyReturnCommand() const { + const HarvestEmergencyReturnCommandType *result = + dynamic_cast( + ctHarvestEmergencyReturnCommandType.get()); + return result; } -const AttackStoppedCommandType *UnitType::getFirstAttackStoppedCommand(Field field) const{ - //printf("$$$ Unit [%s] commandTypes.size() = %d\n",this->getName().c_str(),(int)commandTypes.size()); - - for(int i = 0; i < (int)commandTypes.size(); ++i){ - if(commandTypes[i] == NULL) { - throw megaglest_runtime_error("commandTypes[i] == NULL"); - } - - //printf("$$$ Unit [%s] i = %d, commandTypes[i] [%s]\n",this->getName().c_str(),(int)i, commandTypes[i]->toString().c_str()); - if(commandTypes[i]->getClass()== ccAttackStopped){ - const AttackStoppedCommandType *act= dynamic_cast(commandTypes[i]); - if(act != NULL && act->getAttackSkillType()->getAttackField(field)) { - //printf("## Unit [%s] i = %d, is found\n",this->getName().c_str(),(int)i); - return act; - } - } - } - - return NULL; +const AttackCommandType *UnitType::getFirstAttackCommand(Field field) const { + // printf("$$$ Unit [%s] commandTypes.size() = + // %d\n",this->getName().c_str(),(int)commandTypes.size()); + + for (int i = 0; i < (int)commandTypes.size(); ++i) { + if (commandTypes[i] == NULL) { + throw megaglest_runtime_error("commandTypes[i] == NULL"); + } + + // printf("$$$ Unit [%s] i = %d, commandTypes[i] + // [%s]\n",this->getName().c_str(),(int)i, + // commandTypes[i]->toString().c_str()); + if (commandTypes[i]->getClass() == ccAttack) { + const AttackCommandType *act = + dynamic_cast(commandTypes[i]); + if (act != NULL && act->getAttackSkillType()->getAttackField(field)) { + // printf("## Unit [%s] i = %d, is + // found\n",this->getName().c_str(),(int)i); + return act; + } + } + } + + return NULL; +} + +const AttackStoppedCommandType * +UnitType::getFirstAttackStoppedCommand(Field field) const { + // printf("$$$ Unit [%s] commandTypes.size() = + // %d\n",this->getName().c_str(),(int)commandTypes.size()); + + for (int i = 0; i < (int)commandTypes.size(); ++i) { + if (commandTypes[i] == NULL) { + throw megaglest_runtime_error("commandTypes[i] == NULL"); + } + + // printf("$$$ Unit [%s] i = %d, commandTypes[i] + // [%s]\n",this->getName().c_str(),(int)i, + // commandTypes[i]->toString().c_str()); + if (commandTypes[i]->getClass() == ccAttackStopped) { + const AttackStoppedCommandType *act = + dynamic_cast(commandTypes[i]); + if (act != NULL && act->getAttackSkillType()->getAttackField(field)) { + // printf("## Unit [%s] i = %d, is + // found\n",this->getName().c_str(),(int)i); + return act; + } + } + } + + return NULL; } -const RepairCommandType *UnitType::getFirstRepairCommand(const UnitType *repaired) const{ - for(int i=0; i < (int)commandTypes.size(); ++i){ - if(commandTypes[i]->getClass()== ccRepair){ - const RepairCommandType *rct= static_cast(commandTypes[i]); - if(rct->isRepairableUnitType(repaired)){ - return rct; - } - } - } - return NULL; +const RepairCommandType * +UnitType::getFirstRepairCommand(const UnitType *repaired) const { + for (int i = 0; i < (int)commandTypes.size(); ++i) { + if (commandTypes[i]->getClass() == ccRepair) { + const RepairCommandType *rct = + static_cast(commandTypes[i]); + if (rct->isRepairableUnitType(repaired)) { + return rct; + } + } + } + return NULL; } bool UnitType::hasEmptyCellMap() const { - //checkItemInVault(&(this->size),this->size); - bool result = (size > 0); - for(int i = 0; result == true && i < size; ++i) { - for(int j = 0; j < size; ++j){ - if(cellMap[i*size+j] == true) { - result = false; - break; - } - } - } - - return result; + // checkItemInVault(&(this->size),this->size); + bool result = (size > 0); + for (int i = 0; result == true && i < size; ++i) { + for (int j = 0; j < size; ++j) { + if (cellMap[i * size + j] == true) { + result = false; + break; + } + } + } + + return result; } Vec2i UnitType::getFirstOccupiedCellInCellMap(Vec2i currentPos) const { - Vec2i cell = currentPos; - //printf("\n\n\n\n^^^^^^^^^^ currentPos [%s] size [%d]\n",currentPos.getString().c_str(),size); - - //checkItemInVault(&(this->size),this->size); - if(hasCellMap() == true) { - for(int i = 0; i < size; ++i) { - for(int j = 0; j < size; ++j){ - if(cellMap[i*size+j] == true) { - cell.x += i; - cell.y += j; - //printf("\n^^^^^^^^^^ cell [%s] i [%d] j [%d]\n",cell.getString().c_str(),i,j); - return cell; - } - } - } - } - return cell; + Vec2i cell = currentPos; + // printf("\n\n\n\n^^^^^^^^^^ currentPos [%s] size + // [%d]\n",currentPos.getString().c_str(),size); + + // checkItemInVault(&(this->size),this->size); + if (hasCellMap() == true) { + for (int i = 0; i < size; ++i) { + for (int j = 0; j < size; ++j) { + if (cellMap[i * size + j] == true) { + cell.x += i; + cell.y += j; + // printf("\n^^^^^^^^^^ cell [%s] i [%d] j + // [%d]\n",cell.getString().c_str(),i,j); + return cell; + } + } + } + } + return cell; } bool UnitType::getCellMapCell(int x, int y, CardinalDir facing) const { - assert(cellMap); - if(cellMap == NULL) { - throw megaglest_runtime_error("cellMap == NULL"); - } - - //checkItemInVault(&(this->size),this->size); - int tmp=0; - switch (facing) { - case CardinalDir::EAST: - tmp = y; - y = x; - x = size - tmp - 1; - break; - case CardinalDir::SOUTH: - x = size - x - 1; - y = size - y - 1; - break; - case CardinalDir::WEST: - tmp = x; - x = y; - y = size - tmp - 1; - break; - default: - break; - } - return cellMap[y * size + x]; + assert(cellMap); + if (cellMap == NULL) { + throw megaglest_runtime_error("cellMap == NULL"); + } + + // checkItemInVault(&(this->size),this->size); + int tmp = 0; + switch (facing) { + case CardinalDir::EAST: + tmp = y; + y = x; + x = size - tmp - 1; + break; + case CardinalDir::SOUTH: + x = size - x - 1; + y = size - y - 1; + break; + case CardinalDir::WEST: + tmp = x; + x = y; + y = size - tmp - 1; + break; + default: + break; + } + return cellMap[y * size + x]; } -int UnitType::getStore(const ResourceType *rt) const{ - for(int i=0; i < (int)storedResources.size(); ++i){ - if(storedResources[i].getType()==rt){ - return storedResources[i].getAmount(); - } +int UnitType::getStore(const ResourceType *rt) const { + for (int i = 0; i < (int)storedResources.size(); ++i) { + if (storedResources[i].getType() == rt) { + return storedResources[i].getAmount(); } - return 0; + } + return 0; } -const SkillType *UnitType::getSkillType(const string &skillName, SkillClass skillClass) const{ - for(int i=0; i < (int)skillTypes.size(); ++i){ - if(skillTypes[i]->getName()==skillName){ - if(skillTypes[i]->getClass()==skillClass){ - return skillTypes[i]; - } - else{ - throw megaglest_runtime_error("Skill \""+skillName+"\" is not of class \""+SkillType::skillClassToStr(skillClass)); - } - } - } - throw megaglest_runtime_error("No skill named \""+skillName+"\""); +const SkillType *UnitType::getSkillType(const string &skillName, + SkillClass skillClass) const { + for (int i = 0; i < (int)skillTypes.size(); ++i) { + if (skillTypes[i]->getName() == skillName) { + if (skillTypes[i]->getClass() == skillClass) { + return skillTypes[i]; + } else { + throw megaglest_runtime_error("Skill \"" + skillName + + "\" is not of class \"" + + SkillType::skillClassToStr(skillClass)); + } + } + } + throw megaglest_runtime_error("No skill named \"" + skillName + "\""); } // ==================== totals ==================== int UnitType::getTotalMaxHp(const TotalUpgrade *totalUpgrade) const { - checkItemInVault(&(this->maxHp),this->maxHp); - int result = maxHp + totalUpgrade->getMaxHp(); - result = max(0,result); - return result; + checkItemInVault(&(this->maxHp), this->maxHp); + int result = maxHp + totalUpgrade->getMaxHp(); + result = max(0, result); + return result; } -int UnitType::getTotalMaxHpRegeneration(const TotalUpgrade *totalUpgrade) const { - checkItemInVault(&(this->hpRegeneration),this->hpRegeneration); - int result = hpRegeneration + totalUpgrade->getMaxHpRegeneration(); - //result = max(0,result); - return result; +int UnitType::getTotalMaxHpRegeneration( + const TotalUpgrade *totalUpgrade) const { + checkItemInVault(&(this->hpRegeneration), this->hpRegeneration); + int result = hpRegeneration + totalUpgrade->getMaxHpRegeneration(); + // result = max(0,result); + return result; } int UnitType::getTotalMaxEp(const TotalUpgrade *totalUpgrade) const { - checkItemInVault(&(this->maxEp),this->maxEp); - int result = maxEp + totalUpgrade->getMaxEp(); - result = max(0,result); - return result; + checkItemInVault(&(this->maxEp), this->maxEp); + int result = maxEp + totalUpgrade->getMaxEp(); + result = max(0, result); + return result; } -int UnitType::getTotalMaxEpRegeneration(const TotalUpgrade *totalUpgrade) const { - checkItemInVault(&(this->epRegeneration),this->epRegeneration); - int result = epRegeneration + totalUpgrade->getMaxEpRegeneration(); - //result = max(0,result); - return result; +int UnitType::getTotalMaxEpRegeneration( + const TotalUpgrade *totalUpgrade) const { + checkItemInVault(&(this->epRegeneration), this->epRegeneration); + int result = epRegeneration + totalUpgrade->getMaxEpRegeneration(); + // result = max(0,result); + return result; } int UnitType::getTotalArmor(const TotalUpgrade *totalUpgrade) const { - checkItemInVault(&(this->armor),this->armor); - int result = armor + totalUpgrade->getArmor(); - result = max(0,result); - return result; + checkItemInVault(&(this->armor), this->armor); + int result = armor + totalUpgrade->getArmor(); + result = max(0, result); + return result; } int UnitType::getTotalSight(const TotalUpgrade *totalUpgrade) const { - checkItemInVault(&(this->sight),this->sight); - int result = sight + totalUpgrade->getSight(); - result = max(0,result); - return result; + checkItemInVault(&(this->sight), this->sight); + int result = sight + totalUpgrade->getSight(); + result = max(0, result); + return result; } // ==================== has ==================== bool UnitType::hasSkillClass(SkillClass skillClass) const { - return firstSkillTypeOfClass[skillClass]!=NULL; + return firstSkillTypeOfClass[skillClass] != NULL; } bool UnitType::hasCommandType(const CommandType *commandType) const { - assert(commandType!=NULL); - - const HarvestEmergencyReturnCommandType *result = dynamic_cast(ctHarvestEmergencyReturnCommandType.get()); - if(commandType == result) { - return true; - } - - for(int i=0; i < (int)commandTypes.size(); ++i) { - if(commandTypes[i]==commandType) { - return true; - } + assert(commandType != NULL); + + const HarvestEmergencyReturnCommandType *result = + dynamic_cast( + ctHarvestEmergencyReturnCommandType.get()); + if (commandType == result) { + return true; + } + + for (int i = 0; i < (int)commandTypes.size(); ++i) { + if (commandTypes[i] == commandType) { + return true; } - return false; + } + return false; } -//bool UnitType::hasSkillType(const SkillType *skillType) const { -// assert(skillType!=NULL); -// for(int i=0; i < (int)skillTypes.size(); ++i) { -// if(skillTypes[i]==skillType) { -// return true; -// } -// } -// return false; -//} - -bool UnitType::isOfClass(UnitClass uc) const{ - switch(uc){ - case ucWarrior: - return hasSkillClass(scAttack) && !hasSkillClass(scHarvest); - case ucWorker: - return hasSkillClass(scBuild) || hasSkillClass(scRepair)|| hasSkillClass(scHarvest); - case ucBuilding: - return hasSkillClass(scBeBuilt); - default: - assert(false); - break; - } - return false; +// bool UnitType::hasSkillType(const SkillType *skillType) const { +// assert(skillType!=NULL); +// for(int i=0; i < (int)skillTypes.size(); ++i) { +// if(skillTypes[i]==skillType) { +// return true; +// } +// } +// return false; +// } + +bool UnitType::isOfClass(UnitClass uc) const { + switch (uc) { + case ucWarrior: + return hasSkillClass(scAttack) && !hasSkillClass(scHarvest); + case ucWorker: + return hasSkillClass(scBuild) || hasSkillClass(scRepair) || + hasSkillClass(scHarvest); + case ucBuilding: + return hasSkillClass(scBeBuilt); + default: + assert(false); + break; + } + return false; } // ==================== PRIVATE ==================== void UnitType::computeFirstStOfClass() { - for(int j= 0; j < scCount; ++j) { - firstSkillTypeOfClass[j]= NULL; - for(int i= 0; i < (int)skillTypes.size(); ++i) { - if(skillTypes[i] != NULL && skillTypes[i]->getClass()== SkillClass(j)) { - firstSkillTypeOfClass[j]= skillTypes[i]; - break; - } - } + for (int j = 0; j < scCount; ++j) { + firstSkillTypeOfClass[j] = NULL; + for (int i = 0; i < (int)skillTypes.size(); ++i) { + if (skillTypes[i] != NULL && skillTypes[i]->getClass() == SkillClass(j)) { + firstSkillTypeOfClass[j] = skillTypes[i]; + break; + } } + } } void UnitType::computeFirstCtOfClass() { - for(int j = 0; j < ccCount; ++j) { - firstCommandTypeOfClass[j]= NULL; - for(int i = 0; i < (int)commandTypes.size(); ++i) { - if(commandTypes[i] != NULL && commandTypes[i]->getClass() == CommandClass(j)) { - firstCommandTypeOfClass[j] = commandTypes[i]; - break; - } - } + for (int j = 0; j < ccCount; ++j) { + firstCommandTypeOfClass[j] = NULL; + for (int i = 0; i < (int)commandTypes.size(); ++i) { + if (commandTypes[i] != NULL && + commandTypes[i]->getClass() == CommandClass(j)) { + firstCommandTypeOfClass[j] = commandTypes[i]; + break; + } } + } } -const CommandType* UnitType::findCommandTypeById(int id) const{ - const HarvestEmergencyReturnCommandType *result = dynamic_cast(ctHarvestEmergencyReturnCommandType.get()); - if(result != NULL && id == result->getId()) { - return result; - } - - for(int i=0; i < getCommandTypeCount(); ++i) { - const CommandType *commandType= getCommandType(i); - if(commandType->getId() == id){ - return commandType; - } - } - return NULL; +const CommandType *UnitType::findCommandTypeById(int id) const { + const HarvestEmergencyReturnCommandType *result = + dynamic_cast( + ctHarvestEmergencyReturnCommandType.get()); + if (result != NULL && id == result->getId()) { + return result; + } + + for (int i = 0; i < getCommandTypeCount(); ++i) { + const CommandType *commandType = getCommandType(i); + if (commandType->getId() == id) { + return commandType; + } + } + return NULL; } const CommandType *UnitType::getCommandType(int i) const { - if(i >= (int)commandTypes.size()) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s Line: %d] i >= commandTypes.size(), i = %d, commandTypes.size() = " MG_SIZE_T_SPECIFIER "",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,commandTypes.size()); - throw megaglest_runtime_error(szBuf); - } - return commandTypes[i]; + if (i >= (int)commandTypes.size()) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In [%s::%s Line: %d] i >= commandTypes.size(), i = %d, " + "commandTypes.size() = " MG_SIZE_T_SPECIFIER "", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, i, commandTypes.size()); + throw megaglest_runtime_error(szBuf); + } + return commandTypes[i]; } string UnitType::getCommandTypeListDesc() const { - string desc = "Commands: "; - for(int i=0; igetId()); + " toString: " + commandType->toString(false); - } - return desc; - + string desc = "Commands: "; + for (int i = 0; i < getCommandTypeCount(); ++i) { + const CommandType *commandType = getCommandType(i); + desc += " id = " + intToStr(commandType->getId()); + +" toString: " + commandType->toString(false); + } + return desc; } -string UnitType::getReqDesc(bool translatedValue) const{ - Lang &lang= Lang::getInstance(); - //string desc = "Limits: "; - string resultTxt=""; - - checkItemInVault(&(this->maxUnitCount),this->maxUnitCount); - if(getMaxUnitCount() > 0) { - resultTxt += "\n" + lang.getString("MaxUnitCount") + " " + intToStr(getMaxUnitCount()); - } - if(resultTxt == "") - return ProducibleType::getReqDesc(translatedValue); - else - return ProducibleType::getReqDesc(translatedValue)+"\n" + lang.getString("Limits") + " " + resultTxt; +string UnitType::getReqDesc(bool translatedValue) const { + Lang &lang = Lang::getInstance(); + // string desc = "Limits: "; + string resultTxt = ""; + + checkItemInVault(&(this->maxUnitCount), this->maxUnitCount); + if (getMaxUnitCount() > 0) { + resultTxt += "\n" + lang.getString("MaxUnitCount") + " " + + intToStr(getMaxUnitCount()); + } + if (resultTxt == "") + return ProducibleType::getReqDesc(translatedValue); + else + return ProducibleType::getReqDesc(translatedValue) + "\n" + + lang.getString("Limits") + " " + resultTxt; } string UnitType::getName(bool translatedValue) const { - if(translatedValue == false) return name; + if (translatedValue == false) + return name; - Lang &lang = Lang::getInstance(); - return lang.getTechTreeString("UnitTypeName_" + name,name.c_str()); + Lang &lang = Lang::getInstance(); + return lang.getTechTreeString("UnitTypeName_" + name, name.c_str()); } std::string UnitType::toString() const { - std::string result = "Unit Name: [" + name + "] id = " + intToStr(id); - result += " maxHp = " + intToStr(maxHp); - result += " hpRegeneration = " + intToStr(hpRegeneration); - result += " maxEp = " + intToStr(maxEp); - result += " startEpValue = " + intToStr(startEpValue); - result += " startEpPercentage = " + intToStr(startEpPercentage); - result += " epRegeneration = " + intToStr(epRegeneration); - result += " maxUnitCount = " + intToStr(getMaxUnitCount()); - - - for(int i = 0; i < fieldCount; i++) { - result += " fields index = " + intToStr(i) + " value = " + intToStr(fields[i]); - } - for(int i = 0; i < pCount; i++) { - result += " properties index = " + intToStr(i) + " value = " + intToStr(properties[i]); - } - - result += " armor = " + intToStr(armor); - - if(armorType != NULL) { - result += " armorType Name: [" + armorType->getName(false) + " id = " + intToStr(armorType->getId()); - } - - result += " light = " + intToStr(light); - result += " lightColor = " + lightColor.getString(); - result += " multiSelect = " + intToStr(multiSelect); - result += " uniformSelect = " + intToStr(uniformSelect); - result += " commandable = " + intToStr(commandable); - result += " sight = " + intToStr(sight); - result += " size = " + intToStr(size); - result += " height = " + intToStr(height); - result += " rotatedBuildPos = " + floatToStr(rotatedBuildPos,6); - result += " rotationAllowed = " + intToStr(rotationAllowed); - - if(cellMap != NULL) { - result += " cellMap: [" + intToStr(size) + "]"; - for(int i = 0; i < size; ++i) { - for(int j = 0; j < size; ++j){ - result += " i = " + intToStr(i) + " j = " + intToStr(j) + " value = " + intToStr(cellMap[i*size+j]); - } - } - } - - result += " skillTypes: [" + intToStr(skillTypes.size()) + "]"; - for(int i = 0; i < (int)skillTypes.size(); ++i) { - result += " i = " + intToStr(i) + " " + skillTypes[i]->toString(false); - } - - result += " commandTypes: [" + intToStr(commandTypes.size()) + "]"; - for(int i = 0; i < (int)commandTypes.size(); ++i) { - result += " i = " + intToStr(i) + " " + commandTypes[i]->toString(false); - } - - result += " storedResources: [" + intToStr(storedResources.size()) + "]"; - for(int i = 0; i < (int)storedResources.size(); ++i) { - result += " i = " + intToStr(i) + " " + storedResources[i].getDescription(false); - } - - result += " levels: [" + intToStr(levels.size()) + "]"; - for(int i = 0; i < (int)levels.size(); ++i) { - result += " i = " + intToStr(i) + " " + levels[i].getName(); - } - - result += " meetingPoint = " + intToStr(meetingPoint); - - result += " countInVictoryConditions = " + intToStr(countInVictoryConditions); - - return result; + std::string result = "Unit Name: [" + name + "] id = " + intToStr(id); + result += " maxHp = " + intToStr(maxHp); + result += " hpRegeneration = " + intToStr(hpRegeneration); + result += " maxEp = " + intToStr(maxEp); + result += " startEpValue = " + intToStr(startEpValue); + result += " startEpPercentage = " + intToStr(startEpPercentage); + result += " epRegeneration = " + intToStr(epRegeneration); + result += " maxUnitCount = " + intToStr(getMaxUnitCount()); + + for (int i = 0; i < fieldCount; i++) { + result += + " fields index = " + intToStr(i) + " value = " + intToStr(fields[i]); + } + for (int i = 0; i < pCount; i++) { + result += " properties index = " + intToStr(i) + + " value = " + intToStr(properties[i]); + } + + result += " armor = " + intToStr(armor); + + if (armorType != NULL) { + result += " armorType Name: [" + armorType->getName(false) + + " id = " + intToStr(armorType->getId()); + } + + result += " light = " + intToStr(light); + result += " lightColor = " + lightColor.getString(); + result += " multiSelect = " + intToStr(multiSelect); + result += " uniformSelect = " + intToStr(uniformSelect); + result += " commandable = " + intToStr(commandable); + result += " sight = " + intToStr(sight); + result += " size = " + intToStr(size); + result += " height = " + intToStr(height); + result += " rotatedBuildPos = " + floatToStr(rotatedBuildPos, 6); + result += " rotationAllowed = " + intToStr(rotationAllowed); + + if (cellMap != NULL) { + result += " cellMap: [" + intToStr(size) + "]"; + for (int i = 0; i < size; ++i) { + for (int j = 0; j < size; ++j) { + result += " i = " + intToStr(i) + " j = " + intToStr(j) + + " value = " + intToStr(cellMap[i * size + j]); + } + } + } + + result += " skillTypes: [" + intToStr(skillTypes.size()) + "]"; + for (int i = 0; i < (int)skillTypes.size(); ++i) { + result += " i = " + intToStr(i) + " " + skillTypes[i]->toString(false); + } + + result += " commandTypes: [" + intToStr(commandTypes.size()) + "]"; + for (int i = 0; i < (int)commandTypes.size(); ++i) { + result += " i = " + intToStr(i) + " " + commandTypes[i]->toString(false); + } + + result += " storedResources: [" + intToStr(storedResources.size()) + "]"; + for (int i = 0; i < (int)storedResources.size(); ++i) { + result += + " i = " + intToStr(i) + " " + storedResources[i].getDescription(false); + } + + result += " levels: [" + intToStr(levels.size()) + "]"; + for (int i = 0; i < (int)levels.size(); ++i) { + result += " i = " + intToStr(i) + " " + levels[i].getName(); + } + + result += " meetingPoint = " + intToStr(meetingPoint); + + result += " countInVictoryConditions = " + intToStr(countInVictoryConditions); + + return result; } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/types/unit_type.h b/source/glest_game/types/unit_type.h index 0b3a75c32..4482db6e8 100644 --- a/source/glest_game/types/unit_type.h +++ b/source/glest_game/types/unit_type.h @@ -13,25 +13,26 @@ #define _GLEST_GAME_UNITTYPE_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include "element_type.h" +#include "checksum.h" #include "command_type.h" +#include "common_scoped_ptr.h" #include "damage_multiplier.h" -#include "sound_container.h" -#include "checksum.h" +#include "element_type.h" #include "game_constants.h" -#include "platform_common.h" -#include "common_scoped_ptr.h" #include "leak_dumper.h" +#include "platform_common.h" +#include "sound_container.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { +using Shared::PlatformCommon::ValueCheckerVault; using Shared::Sound::StaticSound; using Shared::Util::Checksum; -using Shared::PlatformCommon::ValueCheckerVault; class UpgradeType; class UnitType; @@ -41,75 +42,79 @@ class TechTree; class FactionType; class Faction; - // =============================== // class Level // =============================== class Level { private: - string name; - int kills; + string name; + int kills; public: - Level() { - kills = 0; - } - void init(string name, int kills); + Level() { kills = 0; } + void init(string name, int kills); - string getName(bool translatedValue=false) const; - int getKills() const {return kills;} + string getName(bool translatedValue = false) const; + int getKills() const { return kills; } - void saveGame(XmlNode *rootNode) const ; - static const Level * loadGame(const XmlNode *rootNode, const UnitType *ut); + void saveGame(XmlNode *rootNode) const; + static const Level *loadGame(const XmlNode *rootNode, const UnitType *ut); }; // =============================== // class LootResource // -/// Stores information about a lootable resource. Lootable resources are stolen by the attacker on death. +/// Stores information about a lootable resource. Lootable resources are +/// stolen by the attacker on death. // =============================== class LootableResource { private: - const ResourceType *type; - int amountValue; - int amountFactionPercent; - int lossValue; - int lossFactionPercent; - bool negativeAllowed; + const ResourceType *type; + int amountValue; + int amountFactionPercent; + int lossValue; + int lossFactionPercent; + bool negativeAllowed; public: - LootableResource() { - type=NULL; - amountValue=0; - amountFactionPercent=0; - lossValue=0; - lossFactionPercent=0; - negativeAllowed=false; - } - - const ResourceType* getResourceType() const {return type;} - void setResourceType(const ResourceType *type) {this->type=type;} - - int getAmountValue() const {return amountValue;} - void setAmountValue(int amountValue) {this->amountValue=amountValue;} - - int getAmountFactionPercent() const {return amountFactionPercent;} - void setAmountFactionPercent(int amountPercentage) {this->amountFactionPercent=amountPercentage;} - - int getLossValue() const {return lossValue;} - void setLossValue(int lossValue) {this->lossValue=lossValue;} - - int getLossFactionPercent() const {return lossFactionPercent;} - void setLossFactionPercent(int lossPercentage) {this->lossFactionPercent=lossPercentage;} - - bool isNegativeAllowed() const {return negativeAllowed;} - void setNegativeAllowed(bool negativeAllowed) {this->negativeAllowed=negativeAllowed;} - - bool operator==(const LootableResource& other) { - return type == other.getResourceType(); - } + LootableResource() { + type = NULL; + amountValue = 0; + amountFactionPercent = 0; + lossValue = 0; + lossFactionPercent = 0; + negativeAllowed = false; + } + + const ResourceType *getResourceType() const { return type; } + void setResourceType(const ResourceType *type) { this->type = type; } + + int getAmountValue() const { return amountValue; } + void setAmountValue(int amountValue) { this->amountValue = amountValue; } + + int getAmountFactionPercent() const { return amountFactionPercent; } + void setAmountFactionPercent(int amountPercentage) { + this->amountFactionPercent = amountPercentage; + } + + int getLossValue() const { return lossValue; } + void setLossValue(int lossValue) { this->lossValue = lossValue; } + + int getLossFactionPercent() const { return lossFactionPercent; } + void setLossFactionPercent(int lossPercentage) { + this->lossFactionPercent = lossPercentage; + } + + bool isNegativeAllowed() const { return negativeAllowed; } + void setNegativeAllowed(bool negativeAllowed) { + this->negativeAllowed = negativeAllowed; + } + + bool operator==(const LootableResource &other) { + return type == other.getResourceType(); + } }; // =============================== @@ -118,263 +123,278 @@ class LootableResource { /// A unit or building type // =============================== -enum UnitClass { - ucWarrior, - ucWorker, - ucBuilding -}; +enum UnitClass { ucWarrior, ucWorker, ucBuilding }; -typedef vector DamageParticleSystemTypes; +typedef vector DamageParticleSystemTypes; enum HealthbarVisible { - hbvUndefined=0, - hbvOff=1, - hbvAlways=2, - hbvIfNeeded=4, - hbvSelected=8 + hbvUndefined = 0, + hbvOff = 1, + hbvAlways = 2, + hbvIfNeeded = 4, + hbvSelected = 8 }; -enum UnitCountsInVictoryConditions { - ucvcNotSet, - ucvcTrue, - ucvcFalse -}; +enum UnitCountsInVictoryConditions { ucvcNotSet, ucvcTrue, ucvcFalse }; -class UnitType: public ProducibleType, public ValueCheckerVault { +class UnitType : public ProducibleType, public ValueCheckerVault { public: - enum Property { - pBurnable, - pRotatedClimb, + enum Property { + pBurnable, + pRotatedClimb, + + pCount + }; - pCount - }; + enum StartType { stValue, stPercentage }; - enum StartType { - stValue, - stPercentage - }; + static const char *propertyNames[]; + DamageParticleSystemTypes damageParticleSystemTypes; - static const char *propertyNames[]; - DamageParticleSystemTypes damageParticleSystemTypes; private: - typedef vector SkillTypes; - typedef vector CommandTypes; - typedef vector StoredResources; - typedef vector Levels; - typedef vector LootableResources; + typedef vector SkillTypes; + typedef vector CommandTypes; + typedef vector StoredResources; + typedef vector Levels; + typedef vector LootableResources; private: - //basic - int id; - int maxHp; - int startHpValue; - int startHpPercentage; - StartType startHpType; - int hpRegeneration; - int maxEp; - int startEpValue; - int startEpPercentage; - StartType startEpType; - int epRegeneration; - int maxUnitCount; - - - // remove fields, multiple fields are not supported by the engine - bool fields[fieldCount]; //fields: land, sea or air - Field field; - - bool properties[pCount]; //properties - int armor; //armor - const ArmorType *armorType; - bool light; - Vec3f lightColor; - float healthbarheight; - float healthbarthickness; - int healthbarVisible; - bool multiSelect; - bool uniformSelect; - bool commandable; - int sight; - int size; //size in cells - int aiBuildSize; - int renderSize; //size to render in cells - int height; - int burnHeight; - int targetHeight; - float rotatedBuildPos; - bool rotationAllowed; - - //cellmap - bool *cellMap; - bool allowEmptyCellMap; - - //sounds - SoundContainer selectionSounds; - SoundContainer commandSounds; - - //info - SkillTypes skillTypes; - CommandTypes commandTypes; - StoredResources storedResources; - Levels levels; - LootableResources lootableResources; - std::set tags; - - //meeting point - bool meetingPoint; - Texture2D *meetingPointImage; - - // for dummy units and units used as shots and so on .... - bool countUnitDeathInStats; - bool countUnitProductionInStats; - bool countUnitKillInStats; - bool countKillForUnitUpgrade; - - //OPTIMIZATION: store first command type and skill type of each class - const CommandType *firstCommandTypeOfClass[ccCount]; - const SkillType *firstSkillTypeOfClass[scCount]; - - UnitCountsInVictoryConditions countInVictoryConditions; - - static auto_ptr ctHarvestEmergencyReturnCommandType; + // basic + int id; + int maxHp; + int startHpValue; + int startHpPercentage; + StartType startHpType; + int hpRegeneration; + int maxEp; + int startEpValue; + int startEpPercentage; + StartType startEpType; + int epRegeneration; + int maxUnitCount; + + // remove fields, multiple fields are not supported by the engine + bool fields[fieldCount]; // fields: land, sea or air + Field field; + + bool properties[pCount]; // properties + int armor; // armor + const ArmorType *armorType; + bool light; + Vec3f lightColor; + float healthbarheight; + float healthbarthickness; + int healthbarVisible; + bool multiSelect; + bool uniformSelect; + bool commandable; + int sight; + int size; // size in cells + int aiBuildSize; + int renderSize; // size to render in cells + int height; + int burnHeight; + int targetHeight; + float rotatedBuildPos; + bool rotationAllowed; + + // cellmap + bool *cellMap; + bool allowEmptyCellMap; + + // sounds + SoundContainer selectionSounds; + SoundContainer commandSounds; + + // info + SkillTypes skillTypes; + CommandTypes commandTypes; + StoredResources storedResources; + Levels levels; + LootableResources lootableResources; + std::set tags; + + // meeting point + bool meetingPoint; + Texture2D *meetingPointImage; + + // for dummy units and units used as shots and so on .... + bool countUnitDeathInStats; + bool countUnitProductionInStats; + bool countUnitKillInStats; + bool countKillForUnitUpgrade; + + // OPTIMIZATION: store first command type and skill type of each class + const CommandType *firstCommandTypeOfClass[ccCount]; + const SkillType *firstSkillTypeOfClass[scCount]; + + UnitCountsInVictoryConditions countInVictoryConditions; + + static auto_ptr ctHarvestEmergencyReturnCommandType; public: - //creation and loading - UnitType(); - virtual ~UnitType(); - void preLoad(const string &dir); - void loaddd(int id, const string &dir, const TechTree *techTree, - const string &techTreePath, - const FactionType *factionType, Checksum* checksum, - Checksum* techtreeChecksum, - std::map > > &loadedFileList, - bool validationMode=false); - - virtual string getName(bool translatedValue=false) const; - - UnitCountsInVictoryConditions getCountInVictoryConditions() const { return countInVictoryConditions; } - //get - inline int getId() const {return id;} - inline int getMaxHp() const {return maxHp;} - inline int getHpRegeneration() const {return hpRegeneration;} - inline int getStartHpValue() const {return startHpValue;} - inline int getStartHpPercentage() const {return startHpPercentage;} - inline StartType getStartHpType() const {return startHpType;} - inline int getMaxEp() const {return maxEp;} - inline int getEpRegeneration() const {return epRegeneration;} - inline int getStartEpValue() const {return startEpValue;} - inline int getStartEpPercentage() const {return startEpPercentage;} - inline StartType getStartEpType() const {return startEpType;} - inline int getMaxUnitCount() const {return maxUnitCount;} - inline bool getField(Field field) const {return fields[field];} - inline Field getField() const {return field;} - inline bool getProperty(Property property) const {return properties[property];} - inline int getArmor() const {return armor;} - inline const ArmorType *getArmorType() const {return armorType;} - inline const SkillType *getSkillType(int i) const {return skillTypes[i];} - const CommandType *getCommandType(int i) const; - inline const Level *getLevel(int i) const {return &levels[i];} - const Level *getLevel(string name) const; - inline int getSkillTypeCount() const {return (int)skillTypes.size();} - inline int getCommandTypeCount() const {return (int)commandTypes.size();} - inline int getLevelCount() const {return (int)levels.size();} - inline bool getLight() const {return light;} - inline bool getRotationAllowed() const {return rotationAllowed;} - inline Vec3f getLightColor() const {return lightColor;} - inline float getHealthbarHeight() const {return healthbarheight;} - inline float getHealthbarThickness() const {return healthbarthickness;} - inline int getHealthbarVisible() const {return healthbarVisible;} - inline bool getMultiSelect() const {return multiSelect;} - inline bool getUniformSelect() const {return uniformSelect;} - inline bool isCommandable() const {return commandable;} - inline int getSight() const {return sight;} - inline int getSize() const {return size;} - inline int getAiBuildSize() const {return aiBuildSize;} - inline int getRenderSize() const {return renderSize;} - int getHeight() const {return height;} - int getBurnHeight() const {return burnHeight;} - int getTargetHeight() const {return targetHeight;} - int getStoredResourceCount() const {return (int)storedResources.size();} - inline const Resource *getStoredResource(int i) const {return &storedResources[i];} - int getLootableResourceCount() const {return (int)lootableResources.size();} - inline const LootableResource getLootableResource(int i) const {return lootableResources.at(i);} - const set &getTags() const {return tags;} - bool getCellMapCell(int x, int y, CardinalDir facing) const; - inline bool getMeetingPoint() const {return meetingPoint;} - inline bool getCountUnitDeathInStats() const {return countUnitDeathInStats;} - inline bool getCountUnitProductionInStats() const {return countUnitProductionInStats;} - inline bool getCountUnitKillInStats() const {return countUnitKillInStats;} - inline bool getCountKillForUnitUpgrade() const {return countKillForUnitUpgrade;} - inline bool isMobile() const {return (firstSkillTypeOfClass[scMove] != NULL);} - inline Texture2D *getMeetingPointImage() const {return meetingPointImage;} - inline StaticSound *getSelectionSound() const {return selectionSounds.getRandSound();} - inline StaticSound *getCommandSound() const {return commandSounds.getRandSound();} - - inline const SoundContainer & getSelectionSounds() const { return selectionSounds; } - inline const SoundContainer & getCommandSounds() const { return commandSounds; } - - int getStore(const ResourceType *rt) const; - const SkillType *getSkillType(const string &skillName, SkillClass skillClass) const; - const SkillType *getFirstStOfClass(SkillClass skillClass) const; - const CommandType *getFirstCtOfClass(CommandClass commandClass) const; - const HarvestCommandType *getFirstHarvestCommand(const ResourceType *resourceType,const Faction *faction) const; - const HarvestEmergencyReturnCommandType *getFirstHarvestEmergencyReturnCommand() const; - const AttackCommandType *getFirstAttackCommand(Field field) const; - const AttackStoppedCommandType *getFirstAttackStoppedCommand(Field field) const; - const RepairCommandType *getFirstRepairCommand(const UnitType *repaired) const; - - //get totals - int getTotalMaxHp(const TotalUpgrade *totalUpgrade) const; - int getTotalMaxHpRegeneration(const TotalUpgrade *totalUpgrade) const; - int getTotalMaxEp(const TotalUpgrade *totalUpgrade) const; - int getTotalMaxEpRegeneration(const TotalUpgrade *totalUpgrade) const; - int getTotalArmor(const TotalUpgrade *totalUpgrade) const; - int getTotalSight(const TotalUpgrade *totalUpgrade) const; - - //has - bool hasCommandType(const CommandType *commandType) const; - inline bool hasCommandClass(CommandClass commandClass) const { - return firstCommandTypeOfClass[commandClass]!=NULL; - } - //bool hasSkillType(const SkillType *skillType) const; - bool hasSkillClass(SkillClass skillClass) const; - inline bool hasCellMap() const {return cellMap!=NULL;} - inline bool getAllowEmptyCellMap() const {return allowEmptyCellMap;} - bool hasEmptyCellMap() const; - Vec2i getFirstOccupiedCellInCellMap(Vec2i currentPos) const; - - //is - bool isOfClass(UnitClass uc) const; - - //find - const CommandType* findCommandTypeById(int id) const; - string getCommandTypeListDesc() const; - - inline float getRotatedBuildPos() { return rotatedBuildPos; } - inline void setRotatedBuildPos(float value) { rotatedBuildPos = value; } - - //other - virtual string getReqDesc(bool translatedValue) const; - - std::string toString() const; + // creation and loading + UnitType(); + virtual ~UnitType(); + void preLoad(const string &dir); + void loaddd(int id, const string &dir, const TechTree *techTree, + const string &techTreePath, const FactionType *factionType, + Checksum *checksum, Checksum *techtreeChecksum, + std::map>> &loadedFileList, + bool validationMode = false); + + virtual string getName(bool translatedValue = false) const; + + UnitCountsInVictoryConditions getCountInVictoryConditions() const { + return countInVictoryConditions; + } + // get + inline int getId() const { return id; } + inline int getMaxHp() const { return maxHp; } + inline int getHpRegeneration() const { return hpRegeneration; } + inline int getStartHpValue() const { return startHpValue; } + inline int getStartHpPercentage() const { return startHpPercentage; } + inline StartType getStartHpType() const { return startHpType; } + inline int getMaxEp() const { return maxEp; } + inline int getEpRegeneration() const { return epRegeneration; } + inline int getStartEpValue() const { return startEpValue; } + inline int getStartEpPercentage() const { return startEpPercentage; } + inline StartType getStartEpType() const { return startEpType; } + inline int getMaxUnitCount() const { return maxUnitCount; } + inline bool getField(Field field) const { return fields[field]; } + inline Field getField() const { return field; } + inline bool getProperty(Property property) const { + return properties[property]; + } + inline int getArmor() const { return armor; } + inline const ArmorType *getArmorType() const { return armorType; } + inline const SkillType *getSkillType(int i) const { return skillTypes[i]; } + const CommandType *getCommandType(int i) const; + inline const Level *getLevel(int i) const { return &levels[i]; } + const Level *getLevel(string name) const; + inline int getSkillTypeCount() const { return (int)skillTypes.size(); } + inline int getCommandTypeCount() const { return (int)commandTypes.size(); } + inline int getLevelCount() const { return (int)levels.size(); } + inline bool getLight() const { return light; } + inline bool getRotationAllowed() const { return rotationAllowed; } + inline Vec3f getLightColor() const { return lightColor; } + inline float getHealthbarHeight() const { return healthbarheight; } + inline float getHealthbarThickness() const { return healthbarthickness; } + inline int getHealthbarVisible() const { return healthbarVisible; } + inline bool getMultiSelect() const { return multiSelect; } + inline bool getUniformSelect() const { return uniformSelect; } + inline bool isCommandable() const { return commandable; } + inline int getSight() const { return sight; } + inline int getSize() const { return size; } + inline int getAiBuildSize() const { return aiBuildSize; } + inline int getRenderSize() const { return renderSize; } + int getHeight() const { return height; } + int getBurnHeight() const { return burnHeight; } + int getTargetHeight() const { return targetHeight; } + int getStoredResourceCount() const { return (int)storedResources.size(); } + inline const Resource *getStoredResource(int i) const { + return &storedResources[i]; + } + int getLootableResourceCount() const { return (int)lootableResources.size(); } + inline const LootableResource getLootableResource(int i) const { + return lootableResources.at(i); + } + const set &getTags() const { return tags; } + bool getCellMapCell(int x, int y, CardinalDir facing) const; + inline bool getMeetingPoint() const { return meetingPoint; } + inline bool getCountUnitDeathInStats() const { return countUnitDeathInStats; } + inline bool getCountUnitProductionInStats() const { + return countUnitProductionInStats; + } + inline bool getCountUnitKillInStats() const { return countUnitKillInStats; } + inline bool getCountKillForUnitUpgrade() const { + return countKillForUnitUpgrade; + } + inline bool isMobile() const { + return (firstSkillTypeOfClass[scMove] != NULL); + } + inline Texture2D *getMeetingPointImage() const { return meetingPointImage; } + inline StaticSound *getSelectionSound() const { + return selectionSounds.getRandSound(); + } + inline StaticSound *getCommandSound() const { + return commandSounds.getRandSound(); + } + + inline const SoundContainer &getSelectionSounds() const { + return selectionSounds; + } + inline const SoundContainer &getCommandSounds() const { + return commandSounds; + } + + int getStore(const ResourceType *rt) const; + const SkillType *getSkillType(const string &skillName, + SkillClass skillClass) const; + const SkillType *getFirstStOfClass(SkillClass skillClass) const; + const CommandType *getFirstCtOfClass(CommandClass commandClass) const; + const HarvestCommandType * + getFirstHarvestCommand(const ResourceType *resourceType, + const Faction *faction) const; + const HarvestEmergencyReturnCommandType * + getFirstHarvestEmergencyReturnCommand() const; + const AttackCommandType *getFirstAttackCommand(Field field) const; + const AttackStoppedCommandType * + getFirstAttackStoppedCommand(Field field) const; + const RepairCommandType * + getFirstRepairCommand(const UnitType *repaired) const; + + // get totals + int getTotalMaxHp(const TotalUpgrade *totalUpgrade) const; + int getTotalMaxHpRegeneration(const TotalUpgrade *totalUpgrade) const; + int getTotalMaxEp(const TotalUpgrade *totalUpgrade) const; + int getTotalMaxEpRegeneration(const TotalUpgrade *totalUpgrade) const; + int getTotalArmor(const TotalUpgrade *totalUpgrade) const; + int getTotalSight(const TotalUpgrade *totalUpgrade) const; + + // has + bool hasCommandType(const CommandType *commandType) const; + inline bool hasCommandClass(CommandClass commandClass) const { + return firstCommandTypeOfClass[commandClass] != NULL; + } + // bool hasSkillType(const SkillType *skillType) const; + bool hasSkillClass(SkillClass skillClass) const; + inline bool hasCellMap() const { return cellMap != NULL; } + inline bool getAllowEmptyCellMap() const { return allowEmptyCellMap; } + bool hasEmptyCellMap() const; + Vec2i getFirstOccupiedCellInCellMap(Vec2i currentPos) const; + + // is + bool isOfClass(UnitClass uc) const; + + // find + const CommandType *findCommandTypeById(int id) const; + string getCommandTypeListDesc() const; + + inline float getRotatedBuildPos() { return rotatedBuildPos; } + inline void setRotatedBuildPos(float value) { rotatedBuildPos = value; } + + // other + virtual string getReqDesc(bool translatedValue) const; + + std::string toString() const; private: - void computeFirstStOfClass(); - void computeFirstCtOfClass(); + void computeFirstStOfClass(); + void computeFirstCtOfClass(); }; /** - * Used to sort UnitType. Sorts by *translated* unit name. Sorting is case sensitive and done in - * lexical order. + * Used to sort UnitType. Sorts by *translated* unit name. Sorting is case + * sensitive and done in lexical order. */ -struct UnitTypeSorter -{ - bool operator()( const UnitType *left, const UnitType *right ) const { - return left->getName(true) < right->getName(true); - } +struct UnitTypeSorter { + bool operator()(const UnitType *left, const UnitType *right) const { + return left->getName(true) < right->getName(true); + } }; -}}//end namespace - +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/types/upgrade_type.cpp b/source/glest_game/types/upgrade_type.cpp index b87577a34..332937b1b 100644 --- a/source/glest_game/types/upgrade_type.cpp +++ b/source/glest_game/types/upgrade_type.cpp @@ -15,23 +15,24 @@ #include #include -#include "unit_type.h" -#include "util.h" -#include "logger.h" -#include "lang.h" -#include "xml_parser.h" -#include "tech_tree.h" +#include "faction.h" #include "faction_type.h" -#include "resource.h" -#include "renderer.h" #include "game_util.h" -#include "faction.h" +#include "lang.h" #include "leak_dumper.h" +#include "logger.h" +#include "renderer.h" +#include "resource.h" +#include "tech_tree.h" +#include "unit_type.h" +#include "util.h" +#include "xml_parser.h" using namespace Shared::Util; using namespace Shared::Xml; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class UpgradeType @@ -43,1062 +44,1332 @@ const string VALUE_PERCENT_MULTIPLIER_KEY_NAME = "value-percent-multiplier"; const string VALUE_REGEN_KEY_NAME = "regeneration"; void UpgradeTypeBase::copyDataFrom(UpgradeTypeBase *source) { - upgradename = source->upgradename; - maxHp = source->maxHp; - maxHpIsMultiplier = source->maxHpIsMultiplier; - maxHpRegeneration = source->maxHpRegeneration; - sight = source->sight; - sightIsMultiplier = source->sightIsMultiplier; - maxEp = source->maxEp; - maxEpIsMultiplier = source->maxEpIsMultiplier; - maxEpRegeneration = source->maxEpRegeneration; - armor = source->armor; - armorIsMultiplier = source->armorIsMultiplier; - attackStrength = source->attackStrength; - attackStrengthIsMultiplier = source->attackStrengthIsMultiplier; - attackStrengthMultiplierValueList = source->attackStrengthMultiplierValueList; - attackRange = source->attackRange; - attackRangeIsMultiplier = source->attackRangeIsMultiplier; - attackRangeMultiplierValueList = source->attackRangeMultiplierValueList; - moveSpeed = source->moveSpeed; - moveSpeedIsMultiplier = source->moveSpeedIsMultiplier; - moveSpeedIsMultiplierValueList = source->moveSpeedIsMultiplierValueList; - prodSpeed = source->prodSpeed; - prodSpeedIsMultiplier = source->prodSpeedIsMultiplier; - prodSpeedProduceIsMultiplierValueList = source->prodSpeedProduceIsMultiplierValueList; - prodSpeedUpgradeIsMultiplierValueList = source->prodSpeedUpgradeIsMultiplierValueList; - prodSpeedMorphIsMultiplierValueList = source->prodSpeedMorphIsMultiplierValueList; - attackSpeed = source->attackSpeed; - attackSpeedIsMultiplier = source->attackSpeedIsMultiplier; - attackSpeedIsMultiplierValueList = source->attackSpeedIsMultiplierValueList; + upgradename = source->upgradename; + maxHp = source->maxHp; + maxHpIsMultiplier = source->maxHpIsMultiplier; + maxHpRegeneration = source->maxHpRegeneration; + sight = source->sight; + sightIsMultiplier = source->sightIsMultiplier; + maxEp = source->maxEp; + maxEpIsMultiplier = source->maxEpIsMultiplier; + maxEpRegeneration = source->maxEpRegeneration; + armor = source->armor; + armorIsMultiplier = source->armorIsMultiplier; + attackStrength = source->attackStrength; + attackStrengthIsMultiplier = source->attackStrengthIsMultiplier; + attackStrengthMultiplierValueList = source->attackStrengthMultiplierValueList; + attackRange = source->attackRange; + attackRangeIsMultiplier = source->attackRangeIsMultiplier; + attackRangeMultiplierValueList = source->attackRangeMultiplierValueList; + moveSpeed = source->moveSpeed; + moveSpeedIsMultiplier = source->moveSpeedIsMultiplier; + moveSpeedIsMultiplierValueList = source->moveSpeedIsMultiplierValueList; + prodSpeed = source->prodSpeed; + prodSpeedIsMultiplier = source->prodSpeedIsMultiplier; + prodSpeedProduceIsMultiplierValueList = + source->prodSpeedProduceIsMultiplierValueList; + prodSpeedUpgradeIsMultiplierValueList = + source->prodSpeedUpgradeIsMultiplierValueList; + prodSpeedMorphIsMultiplierValueList = + source->prodSpeedMorphIsMultiplierValueList; + attackSpeed = source->attackSpeed; + attackSpeedIsMultiplier = source->attackSpeedIsMultiplier; + attackSpeedIsMultiplierValueList = source->attackSpeedIsMultiplierValueList; } void UpgradeTypeBase::load(const XmlNode *upgradeNode, string upgradename) { - this->upgradename = upgradename; - //values - maxHpIsMultiplier = false; - if(upgradeNode->hasChild("max-hp") == true) { - maxHp = upgradeNode->getChild("max-hp")->getAttribute("value")->getIntValue(); - if(upgradeNode->getChild("max-hp")->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME,false) != NULL) { - maxHpIsMultiplier = upgradeNode->getChild("max-hp")->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME)->getBoolValue(); - - //printf("Found maxHpIsMultiplier = %d\n",maxHpIsMultiplier); - } - } - else { - maxHp = 0; - } - maxHpRegeneration = 0; - //maxHpRegenerationIsMultiplier = false; - if(upgradeNode->hasChild("max-hp") == true) { - if(upgradeNode->getChild("max-hp")->getAttribute(VALUE_REGEN_KEY_NAME,false) != NULL) { - maxHpRegeneration = upgradeNode->getChild("max-hp")->getAttribute(VALUE_REGEN_KEY_NAME)->getIntValue(); - - //printf("Found maxHpIsMultiplier = %d\n",maxHpIsMultiplier); - } - } - - maxEpIsMultiplier = false; - if(upgradeNode->hasChild("max-ep") == true) { - maxEp = upgradeNode->getChild("max-ep")->getAttribute("value")->getIntValue(); - if(upgradeNode->getChild("max-ep")->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME,false) != NULL) { - maxEpIsMultiplier = upgradeNode->getChild("max-ep")->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME)->getBoolValue(); - - //printf("Found maxEpIsMultiplier = %d\n",maxEpIsMultiplier); - } - } - else { - maxEp = 0; - } - maxEpRegeneration = 0; - //maxEpRegenerationIsMultiplier = false; - if(upgradeNode->hasChild("max-ep") == true) { - if(upgradeNode->getChild("max-ep")->getAttribute(VALUE_REGEN_KEY_NAME,false) != NULL) { - maxEpRegeneration = upgradeNode->getChild("max-ep")->getAttribute(VALUE_REGEN_KEY_NAME)->getIntValue(); - - //printf("Found maxHpIsMultiplier = %d\n",maxHpIsMultiplier); - } - } - - sightIsMultiplier = false; - if(upgradeNode->hasChild("sight") == true) { - sight= upgradeNode->getChild("sight")->getAttribute("value")->getIntValue(); - if(upgradeNode->getChild("sight")->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME,false) != NULL) { - sightIsMultiplier = upgradeNode->getChild("sight")->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME)->getBoolValue(); - - //printf("Found sightIsMultiplier = %d\n",sightIsMultiplier); - } - } - else { - sight = 0; - } - - attackStrengthIsMultiplier = false; - - std::vector attackStrengthXMLTags; - attackStrengthXMLTags.push_back("attack-strenght"); - attackStrengthXMLTags.push_back("attack-strength"); - if(upgradeNode->hasChildWithAliases(attackStrengthXMLTags) == true) { - attackStrength= upgradeNode->getChildWithAliases(attackStrengthXMLTags)->getAttribute("value")->getIntValue(); - if(upgradeNode->getChildWithAliases(attackStrengthXMLTags)->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME,false) != NULL) { - attackStrengthIsMultiplier = upgradeNode->getChildWithAliases(attackStrengthXMLTags)->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME)->getBoolValue(); - - //printf("Found attackStrengthIsMultiplier = %d\n",attackStrengthIsMultiplier); - } - } - else { - attackStrength = 0; - } - - attackRangeIsMultiplier = false; - if(upgradeNode->hasChild("attack-range") == true) { - attackRange= upgradeNode->getChild("attack-range")->getAttribute("value")->getIntValue(); - if(upgradeNode->getChild("attack-range")->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME,false) != NULL) { - attackRangeIsMultiplier = upgradeNode->getChild("attack-range")->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME)->getBoolValue(); - - //printf("Found attackRangeIsMultiplier = %d\n",attackRangeIsMultiplier); - } - } - else { - attackRange = 0; - } - - armorIsMultiplier = false; - if(upgradeNode->hasChild("armor") == true) { - armor= upgradeNode->getChild("armor")->getAttribute("value")->getIntValue(); - if(upgradeNode->getChild("armor")->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME,false) != NULL) { - armorIsMultiplier = upgradeNode->getChild("armor")->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME)->getBoolValue(); - - //printf("Found armorIsMultiplier = %d\n",armorIsMultiplier); - } - } - else { - armor = 0; - } - - moveSpeedIsMultiplier = false; - if(upgradeNode->hasChild("move-speed") == true) { - moveSpeed= upgradeNode->getChild("move-speed")->getAttribute("value")->getIntValue(); - if(upgradeNode->getChild("move-speed")->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME,false) != NULL) { - moveSpeedIsMultiplier = upgradeNode->getChild("move-speed")->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME)->getBoolValue(); - - //printf("Found moveSpeedIsMultiplier = %d\n",moveSpeedIsMultiplier); - } - } - else { - moveSpeed= 0; - } - - prodSpeedIsMultiplier = false; - if(upgradeNode->hasChild("production-speed") == true) { - prodSpeed= upgradeNode->getChild("production-speed")->getAttribute("value")->getIntValue(); - if(upgradeNode->getChild("production-speed")->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME,false) != NULL) { - prodSpeedIsMultiplier = upgradeNode->getChild("production-speed")->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME)->getBoolValue(); - - //printf("Found prodSpeedIsMultiplier = %d\n",prodSpeedIsMultiplier); - } - } - else { - prodSpeed = 0; - } - - attackSpeedIsMultiplier = false; - if(upgradeNode->hasChild("attack-speed") == true) { - attackSpeed= upgradeNode->getChild("attack-speed")->getAttribute("value")->getIntValue(); - if(upgradeNode->getChild("attack-speed")->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME,false) != NULL) { - attackSpeedIsMultiplier = upgradeNode->getChild("attack-speed")->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME)->getBoolValue(); - - //printf("Found prodSpeedIsMultiplier = %d\n",prodSpeedIsMultiplier); - } - } - else { - attackSpeed = 0; - } + this->upgradename = upgradename; + // values + maxHpIsMultiplier = false; + if (upgradeNode->hasChild("max-hp") == true) { + maxHp = + upgradeNode->getChild("max-hp")->getAttribute("value")->getIntValue(); + if (upgradeNode->getChild("max-hp")->getAttribute( + VALUE_PERCENT_MULTIPLIER_KEY_NAME, false) != NULL) { + maxHpIsMultiplier = upgradeNode->getChild("max-hp") + ->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME) + ->getBoolValue(); + + // printf("Found maxHpIsMultiplier = %d\n",maxHpIsMultiplier); + } + } else { + maxHp = 0; + } + maxHpRegeneration = 0; + // maxHpRegenerationIsMultiplier = false; + if (upgradeNode->hasChild("max-hp") == true) { + if (upgradeNode->getChild("max-hp")->getAttribute(VALUE_REGEN_KEY_NAME, + false) != NULL) { + maxHpRegeneration = upgradeNode->getChild("max-hp") + ->getAttribute(VALUE_REGEN_KEY_NAME) + ->getIntValue(); + + // printf("Found maxHpIsMultiplier = %d\n",maxHpIsMultiplier); + } + } + + maxEpIsMultiplier = false; + if (upgradeNode->hasChild("max-ep") == true) { + maxEp = + upgradeNode->getChild("max-ep")->getAttribute("value")->getIntValue(); + if (upgradeNode->getChild("max-ep")->getAttribute( + VALUE_PERCENT_MULTIPLIER_KEY_NAME, false) != NULL) { + maxEpIsMultiplier = upgradeNode->getChild("max-ep") + ->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME) + ->getBoolValue(); + + // printf("Found maxEpIsMultiplier = %d\n",maxEpIsMultiplier); + } + } else { + maxEp = 0; + } + maxEpRegeneration = 0; + // maxEpRegenerationIsMultiplier = false; + if (upgradeNode->hasChild("max-ep") == true) { + if (upgradeNode->getChild("max-ep")->getAttribute(VALUE_REGEN_KEY_NAME, + false) != NULL) { + maxEpRegeneration = upgradeNode->getChild("max-ep") + ->getAttribute(VALUE_REGEN_KEY_NAME) + ->getIntValue(); + + // printf("Found maxHpIsMultiplier = %d\n",maxHpIsMultiplier); + } + } + + sightIsMultiplier = false; + if (upgradeNode->hasChild("sight") == true) { + sight = + upgradeNode->getChild("sight")->getAttribute("value")->getIntValue(); + if (upgradeNode->getChild("sight")->getAttribute( + VALUE_PERCENT_MULTIPLIER_KEY_NAME, false) != NULL) { + sightIsMultiplier = upgradeNode->getChild("sight") + ->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME) + ->getBoolValue(); + + // printf("Found sightIsMultiplier = %d\n",sightIsMultiplier); + } + } else { + sight = 0; + } + + attackStrengthIsMultiplier = false; + + std::vector attackStrengthXMLTags; + attackStrengthXMLTags.push_back("attack-strenght"); + attackStrengthXMLTags.push_back("attack-strength"); + if (upgradeNode->hasChildWithAliases(attackStrengthXMLTags) == true) { + attackStrength = upgradeNode->getChildWithAliases(attackStrengthXMLTags) + ->getAttribute("value") + ->getIntValue(); + if (upgradeNode->getChildWithAliases(attackStrengthXMLTags) + ->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME, false) != NULL) { + attackStrengthIsMultiplier = + upgradeNode->getChildWithAliases(attackStrengthXMLTags) + ->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME) + ->getBoolValue(); + + // printf("Found attackStrengthIsMultiplier = + // %d\n",attackStrengthIsMultiplier); + } + } else { + attackStrength = 0; + } + + attackRangeIsMultiplier = false; + if (upgradeNode->hasChild("attack-range") == true) { + attackRange = upgradeNode->getChild("attack-range") + ->getAttribute("value") + ->getIntValue(); + if (upgradeNode->getChild("attack-range") + ->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME, false) != NULL) { + attackRangeIsMultiplier = + upgradeNode->getChild("attack-range") + ->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME) + ->getBoolValue(); + + // printf("Found attackRangeIsMultiplier = %d\n",attackRangeIsMultiplier); + } + } else { + attackRange = 0; + } + + armorIsMultiplier = false; + if (upgradeNode->hasChild("armor") == true) { + armor = + upgradeNode->getChild("armor")->getAttribute("value")->getIntValue(); + if (upgradeNode->getChild("armor")->getAttribute( + VALUE_PERCENT_MULTIPLIER_KEY_NAME, false) != NULL) { + armorIsMultiplier = upgradeNode->getChild("armor") + ->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME) + ->getBoolValue(); + + // printf("Found armorIsMultiplier = %d\n",armorIsMultiplier); + } + } else { + armor = 0; + } + + moveSpeedIsMultiplier = false; + if (upgradeNode->hasChild("move-speed") == true) { + moveSpeed = upgradeNode->getChild("move-speed") + ->getAttribute("value") + ->getIntValue(); + if (upgradeNode->getChild("move-speed") + ->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME, false) != NULL) { + moveSpeedIsMultiplier = + upgradeNode->getChild("move-speed") + ->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME) + ->getBoolValue(); + + // printf("Found moveSpeedIsMultiplier = %d\n",moveSpeedIsMultiplier); + } + } else { + moveSpeed = 0; + } + + prodSpeedIsMultiplier = false; + if (upgradeNode->hasChild("production-speed") == true) { + prodSpeed = upgradeNode->getChild("production-speed") + ->getAttribute("value") + ->getIntValue(); + if (upgradeNode->getChild("production-speed") + ->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME, false) != NULL) { + prodSpeedIsMultiplier = + upgradeNode->getChild("production-speed") + ->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME) + ->getBoolValue(); + + // printf("Found prodSpeedIsMultiplier = %d\n",prodSpeedIsMultiplier); + } + } else { + prodSpeed = 0; + } + + attackSpeedIsMultiplier = false; + if (upgradeNode->hasChild("attack-speed") == true) { + attackSpeed = upgradeNode->getChild("attack-speed") + ->getAttribute("value") + ->getIntValue(); + if (upgradeNode->getChild("attack-speed") + ->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME, false) != NULL) { + attackSpeedIsMultiplier = + upgradeNode->getChild("attack-speed") + ->getAttribute(VALUE_PERCENT_MULTIPLIER_KEY_NAME) + ->getBoolValue(); + + // printf("Found prodSpeedIsMultiplier = %d\n",prodSpeedIsMultiplier); + } + } else { + attackSpeed = 0; + } } -int UpgradeTypeBase::getAttackStrength(const AttackSkillType *st) const { - if(st == NULL) { - return attackStrength; - } - else { - int result = 0; - if(attackStrengthMultiplierValueList.find(st->getName()) != attackStrengthMultiplierValueList.end()) { - result = attackStrengthMultiplierValueList.find(st->getName())->second; - } - return result; - } +int UpgradeTypeBase::getAttackStrength(const AttackSkillType *st) const { + if (st == NULL) { + return attackStrength; + } else { + int result = 0; + if (attackStrengthMultiplierValueList.find(st->getName()) != + attackStrengthMultiplierValueList.end()) { + result = attackStrengthMultiplierValueList.find(st->getName())->second; + } + return result; + } } int UpgradeTypeBase::getAttackRange(const AttackSkillType *st) const { - if(st == NULL) { - return attackRange; - } - else { - int result = 0; - if(attackRangeMultiplierValueList.find(st->getName()) != attackRangeMultiplierValueList.end()) { - result = attackRangeMultiplierValueList.find(st->getName())->second; - } - return result; - } + if (st == NULL) { + return attackRange; + } else { + int result = 0; + if (attackRangeMultiplierValueList.find(st->getName()) != + attackRangeMultiplierValueList.end()) { + result = attackRangeMultiplierValueList.find(st->getName())->second; + } + return result; + } } int UpgradeTypeBase::getMoveSpeed(const MoveSkillType *st) const { - if( st == NULL) { - //printf("getMoveSpeed moveSpeedIsMultiplier OFF st [%p]\n",st); - return moveSpeed; - } - else { - int result = 0; - if(moveSpeedIsMultiplierValueList.find(st->getName()) != moveSpeedIsMultiplierValueList.end()) { - result = moveSpeedIsMultiplierValueList.find(st->getName())->second; - } - - //printf("getMoveSpeed moveSpeedIsMultiplier mst->getSpeed() = %d for skill [%s] result = %d\n",st->getSpeed(),st->getName().c_str(),result); - return result; - } + if (st == NULL) { + // printf("getMoveSpeed moveSpeedIsMultiplier OFF st [%p]\n",st); + return moveSpeed; + } else { + int result = 0; + if (moveSpeedIsMultiplierValueList.find(st->getName()) != + moveSpeedIsMultiplierValueList.end()) { + result = moveSpeedIsMultiplierValueList.find(st->getName())->second; + } + + // printf("getMoveSpeed moveSpeedIsMultiplier mst->getSpeed() = %d for skill + // [%s] result = %d\n",st->getSpeed(),st->getName().c_str(),result); + return result; + } } int UpgradeTypeBase::getAttackSpeed(const AttackSkillType *st) const { - if(attackSpeedIsMultiplier == false || st == NULL) { - return attackSpeed; - } - else { - int result = 0; - if(attackSpeedIsMultiplierValueList.find(st->getName()) != attackSpeedIsMultiplierValueList.end()) { - result = attackSpeedIsMultiplierValueList.find(st->getName())->second; - } - - return result; - } + if (attackSpeedIsMultiplier == false || st == NULL) { + return attackSpeed; + } else { + int result = 0; + if (attackSpeedIsMultiplierValueList.find(st->getName()) != + attackSpeedIsMultiplierValueList.end()) { + result = attackSpeedIsMultiplierValueList.find(st->getName())->second; + } + + return result; + } } int UpgradeTypeBase::getProdSpeed(const SkillType *st) const { - if(st == NULL) { - return prodSpeed; - } - else { - int result = 0; - if(dynamic_cast(st) != NULL) { - if(prodSpeedProduceIsMultiplierValueList.find(st->getName()) != prodSpeedProduceIsMultiplierValueList.end()) { - result = prodSpeedProduceIsMultiplierValueList.find(st->getName())->second; - } - } - else if(dynamic_cast(st) != NULL) { - if(prodSpeedUpgradeIsMultiplierValueList.find(st->getName()) != prodSpeedUpgradeIsMultiplierValueList.end()) { - result = prodSpeedUpgradeIsMultiplierValueList.find(st->getName())->second; - } - } - else if(dynamic_cast(st) != NULL) { - if(prodSpeedMorphIsMultiplierValueList.find(st->getName()) != prodSpeedMorphIsMultiplierValueList.end()) { - result = prodSpeedMorphIsMultiplierValueList.find(st->getName())->second; - } - } - else { - throw megaglest_runtime_error("Unsupported skilltype in getProdSpeed!"); - } - - return result; - } + if (st == NULL) { + return prodSpeed; + } else { + int result = 0; + if (dynamic_cast(st) != NULL) { + if (prodSpeedProduceIsMultiplierValueList.find(st->getName()) != + prodSpeedProduceIsMultiplierValueList.end()) { + result = + prodSpeedProduceIsMultiplierValueList.find(st->getName())->second; + } + } else if (dynamic_cast(st) != NULL) { + if (prodSpeedUpgradeIsMultiplierValueList.find(st->getName()) != + prodSpeedUpgradeIsMultiplierValueList.end()) { + result = + prodSpeedUpgradeIsMultiplierValueList.find(st->getName())->second; + } + } else if (dynamic_cast(st) != NULL) { + if (prodSpeedMorphIsMultiplierValueList.find(st->getName()) != + prodSpeedMorphIsMultiplierValueList.end()) { + result = + prodSpeedMorphIsMultiplierValueList.find(st->getName())->second; + } + } else { + throw megaglest_runtime_error("Unsupported skilltype in getProdSpeed!"); + } + + return result; + } } -string UpgradeTypeBase::getDesc(bool translatedValue) const{ - - string str=""; - string indent="->"; - Lang &lang= Lang::getInstance(); - - if(getMaxHp() != 0 || getMaxHpRegeneration() != 0) { - str += indent+lang.getString("Hp",(translatedValue == true ? "" : "english")) + " +" + intToStr(maxHp); - if(maxHpIsMultiplier) { - str += "%"; - } -// if(getMaxHpFromBoosts() != 0) { -// str += " +" + intToStr(getMaxHpFromBoosts()); -// } - if(getMaxHpRegeneration() != 0) { - str += " (" + lang.getString("Regeneration",(translatedValue == true ? "" : "english")) + ": +" + intToStr(maxHpRegeneration); -// if(getMaxHpRegenerationFromBoosts() != 0) { -// str += " +" + intToStr(getMaxHpRegenerationFromBoosts()); -// } - str += ")"; - } - } - - if(getSight() != 0) { - if(str != "") { - str += "\n"; - } - str += indent+lang.getString("Sight",(translatedValue == true ? "" : "english")) + " +" + intToStr(sight); - if(sightIsMultiplier) { - str += "%"; - } -// if(getSightFromBoosts() != 0) { -// str += " +" + intToStr(getSightFromBoosts()); -// } - } - - if(getMaxEp() != 0 || getMaxEpRegeneration() != 0) { - if(str != "") { - str += "\n"; - } - - str += indent+lang.getString("Ep",(translatedValue == true ? "" : "english")) + " +" + intToStr(maxEp); - if(maxEpIsMultiplier) { - str += "%"; - } -// if(getMaxEpFromBoosts() != 0) { -// str += " +" + intToStr(getMaxEpFromBoosts()); -// } - - if(getMaxEpRegeneration() != 0) { - str += " (" + lang.getString("Regeneration",(translatedValue == true ? "" : "english")) + ": +" + intToStr(maxEpRegeneration); -// if(getMaxEpRegenerationFromBoosts() != 0) { -// str += " +" + intToStr(getMaxEpRegenerationFromBoosts()); -// } - str += ")"; - } - } - - if(getAttackStrength() != 0) { - if(str != "") { - str += "\n"; - } - - str += indent+lang.getString("AttackStrenght",(translatedValue == true ? "" : "english")) + " +" + intToStr(attackStrength); - if(attackStrengthIsMultiplier) { - str += "%"; - } -// if(getAttackStrengthFromBoosts(NULL) != 0) { -// str += " +" + intToStr(getAttackStrengthFromBoosts(NULL)); -// } - } - - if(getAttackRange() != 0) { - if(str != "") { - str += "\n"; - } - - str += indent+lang.getString("AttackDistance",(translatedValue == true ? "" : "english")) + " +" + intToStr(attackRange); - if(attackRangeIsMultiplier) { - str += "%"; - } -// if(getAttackRangeFromBoosts(NULL) != 0) { -// str += " +" + intToStr(getAttackRangeFromBoosts(NULL)); -// } - } - - if(getArmor() != 0) { - if(str != "") { - str += "\n"; - } - - str += indent+lang.getString("Armor",(translatedValue == true ? "" : "english")) + " +" + intToStr(armor); - if(armorIsMultiplier) { - str += "%"; - } -// if(getArmorFromBoosts() != 0) { -// str += " +" + intToStr(getArmorFromBoosts()); -// } - } - - if(getMoveSpeed() != 0) { - if(str != "") { - str += "\n"; - } - - str += indent+lang.getString("WalkSpeed",(translatedValue == true ? "" : "english")) + " +" + intToStr(moveSpeed); - if(moveSpeedIsMultiplier) { - str += "%"; - } -// if(getMoveSpeedFromBoosts(NULL) != 0) { -// str += " +" + intToStr(getMoveSpeedFromBoosts(NULL)); -// } - } - - if(getProdSpeed() != 0) { - if(str != "") { - str += "\n"; - } - - str += indent+lang.getString("ProductionSpeed",(translatedValue == true ? "" : "english")) + " +" + intToStr(prodSpeed); - if(prodSpeedIsMultiplier) { - str += "%"; - } -// if(getProdSpeedFromBoosts(NULL) != 0) { -// str += " +" + intToStr(getProdSpeedFromBoosts(NULL)); -// } - } - - if(getAttackSpeed() != 0) { - if(str != "") { - str += "\n"; - } - - str += indent+lang.getString("AttackSpeed",(translatedValue == true ? "" : "english")) + " +" + intToStr(attackSpeed); - if(attackSpeedIsMultiplier) { - str += "%"; - } -// if(getAttackSpeedFromBoosts(NULL) != 0) { -// str += " +" + intToStr(getAttackSpeedFromBoosts(NULL)); -// } - } - if(str != "") { - str += "\n"; - } - - return str; +string UpgradeTypeBase::getDesc(bool translatedValue) const { + + string str = ""; + string indent = "->"; + Lang &lang = Lang::getInstance(); + + if (getMaxHp() != 0 || getMaxHpRegeneration() != 0) { + str += indent + + lang.getString("Hp", (translatedValue == true ? "" : "english")) + + " +" + intToStr(maxHp); + if (maxHpIsMultiplier) { + str += "%"; + } + // if(getMaxHpFromBoosts() != 0) { + // str += " +" + intToStr(getMaxHpFromBoosts()); + // } + if (getMaxHpRegeneration() != 0) { + str += " (" + + lang.getString("Regeneration", + (translatedValue == true ? "" : "english")) + + ": +" + intToStr(maxHpRegeneration); + // if(getMaxHpRegenerationFromBoosts() != 0) { + // str += " +" + + // intToStr(getMaxHpRegenerationFromBoosts()); + // } + str += ")"; + } + } + + if (getSight() != 0) { + if (str != "") { + str += "\n"; + } + str += indent + + lang.getString("Sight", (translatedValue == true ? "" : "english")) + + " +" + intToStr(sight); + if (sightIsMultiplier) { + str += "%"; + } + // if(getSightFromBoosts() != 0) { + // str += " +" + intToStr(getSightFromBoosts()); + // } + } + + if (getMaxEp() != 0 || getMaxEpRegeneration() != 0) { + if (str != "") { + str += "\n"; + } + + str += indent + + lang.getString("Ep", (translatedValue == true ? "" : "english")) + + " +" + intToStr(maxEp); + if (maxEpIsMultiplier) { + str += "%"; + } + // if(getMaxEpFromBoosts() != 0) { + // str += " +" + intToStr(getMaxEpFromBoosts()); + // } + + if (getMaxEpRegeneration() != 0) { + str += " (" + + lang.getString("Regeneration", + (translatedValue == true ? "" : "english")) + + ": +" + intToStr(maxEpRegeneration); + // if(getMaxEpRegenerationFromBoosts() != 0) { + // str += " +" + + // intToStr(getMaxEpRegenerationFromBoosts()); + // } + str += ")"; + } + } + + if (getAttackStrength() != 0) { + if (str != "") { + str += "\n"; + } + + str += indent + + lang.getString("AttackStrenght", + (translatedValue == true ? "" : "english")) + + " +" + intToStr(attackStrength); + if (attackStrengthIsMultiplier) { + str += "%"; + } + // if(getAttackStrengthFromBoosts(NULL) != 0) { + // str += " +" + + // intToStr(getAttackStrengthFromBoosts(NULL)); + // } + } + + if (getAttackRange() != 0) { + if (str != "") { + str += "\n"; + } + + str += indent + + lang.getString("AttackDistance", + (translatedValue == true ? "" : "english")) + + " +" + intToStr(attackRange); + if (attackRangeIsMultiplier) { + str += "%"; + } + // if(getAttackRangeFromBoosts(NULL) != 0) { + // str += " +" + intToStr(getAttackRangeFromBoosts(NULL)); + // } + } + + if (getArmor() != 0) { + if (str != "") { + str += "\n"; + } + + str += indent + + lang.getString("Armor", (translatedValue == true ? "" : "english")) + + " +" + intToStr(armor); + if (armorIsMultiplier) { + str += "%"; + } + // if(getArmorFromBoosts() != 0) { + // str += " +" + intToStr(getArmorFromBoosts()); + // } + } + + if (getMoveSpeed() != 0) { + if (str != "") { + str += "\n"; + } + + str += indent + + lang.getString("WalkSpeed", + (translatedValue == true ? "" : "english")) + + " +" + intToStr(moveSpeed); + if (moveSpeedIsMultiplier) { + str += "%"; + } + // if(getMoveSpeedFromBoosts(NULL) != 0) { + // str += " +" + intToStr(getMoveSpeedFromBoosts(NULL)); + // } + } + + if (getProdSpeed() != 0) { + if (str != "") { + str += "\n"; + } + + str += indent + + lang.getString("ProductionSpeed", + (translatedValue == true ? "" : "english")) + + " +" + intToStr(prodSpeed); + if (prodSpeedIsMultiplier) { + str += "%"; + } + // if(getProdSpeedFromBoosts(NULL) != 0) { + // str += " +" + intToStr(getProdSpeedFromBoosts(NULL)); + // } + } + + if (getAttackSpeed() != 0) { + if (str != "") { + str += "\n"; + } + + str += indent + + lang.getString("AttackSpeed", + (translatedValue == true ? "" : "english")) + + " +" + intToStr(attackSpeed); + if (attackSpeedIsMultiplier) { + str += "%"; + } + // if(getAttackSpeedFromBoosts(NULL) != 0) { + // str += " +" + intToStr(getAttackSpeedFromBoosts(NULL)); + // } + } + if (str != "") { + str += "\n"; + } + + return str; } -//void UpgradeTypeBase::saveGameBoost(XmlNode *rootNode) const { +// void UpgradeTypeBase::saveGameBoost(XmlNode *rootNode) const { // std::map mapTagReplacements; -// XmlNode *upgradeTypeBaseNode = rootNode->addChild("UpgradeTypeBaseBoost"); +// XmlNode *upgradeTypeBaseNode = +// rootNode->addChild("UpgradeTypeBaseBoost"); // -// upgradeTypeBaseNode->addAttribute("upgradename",upgradename, mapTagReplacements); +// upgradeTypeBaseNode->addAttribute("upgradename",upgradename, +// mapTagReplacements); // //// int maxHp; -// upgradeTypeBaseNode->addAttribute("maxHp",intToStr(maxHp), mapTagReplacements); +// upgradeTypeBaseNode->addAttribute("maxHp",intToStr(maxHp), +// mapTagReplacements); //// bool maxHpIsMultiplier; -// upgradeTypeBaseNode->addAttribute("maxHpIsMultiplier",intToStr(maxHpIsMultiplier), mapTagReplacements); +// upgradeTypeBaseNode->addAttribute("maxHpIsMultiplier",intToStr(maxHpIsMultiplier), +// mapTagReplacements); //// int maxHpRegeneration; -// upgradeTypeBaseNode->addAttribute("maxHpRegeneration",intToStr(maxHpRegeneration), mapTagReplacements); +// upgradeTypeBaseNode->addAttribute("maxHpRegeneration",intToStr(maxHpRegeneration), +// mapTagReplacements); //// //bool maxHpRegenerationIsMultiplier; //// //// int sight; -// upgradeTypeBaseNode->addAttribute("sight",intToStr(sight), mapTagReplacements); +// upgradeTypeBaseNode->addAttribute("sight",intToStr(sight), +// mapTagReplacements); //// bool sightIsMultiplier; -// upgradeTypeBaseNode->addAttribute("sightIsMultiplier",intToStr(sightIsMultiplier), mapTagReplacements); +// upgradeTypeBaseNode->addAttribute("sightIsMultiplier",intToStr(sightIsMultiplier), +// mapTagReplacements); //// int maxEp; -// upgradeTypeBaseNode->addAttribute("maxEp",intToStr(maxEp), mapTagReplacements); +// upgradeTypeBaseNode->addAttribute("maxEp",intToStr(maxEp), +// mapTagReplacements); //// bool maxEpIsMultiplier; -// upgradeTypeBaseNode->addAttribute("maxEpIsMultiplier",intToStr(maxEpIsMultiplier), mapTagReplacements); +// upgradeTypeBaseNode->addAttribute("maxEpIsMultiplier",intToStr(maxEpIsMultiplier), +// mapTagReplacements); //// int maxEpRegeneration; -// upgradeTypeBaseNode->addAttribute("maxEpRegeneration",intToStr(maxEpRegeneration), mapTagReplacements); +// upgradeTypeBaseNode->addAttribute("maxEpRegeneration",intToStr(maxEpRegeneration), +// mapTagReplacements); //// //bool maxEpRegenerationIsMultiplier; //// int armor; -// upgradeTypeBaseNode->addAttribute("armor",intToStr(armor), mapTagReplacements); +// upgradeTypeBaseNode->addAttribute("armor",intToStr(armor), +// mapTagReplacements); //// bool armorIsMultiplier; -// upgradeTypeBaseNode->addAttribute("armorIsMultiplier",intToStr(armorIsMultiplier), mapTagReplacements); +// upgradeTypeBaseNode->addAttribute("armorIsMultiplier",intToStr(armorIsMultiplier), +// mapTagReplacements); //// int attackStrength; -// upgradeTypeBaseNode->addAttribute("attackStrength",intToStr(attackStrength), mapTagReplacements); +// upgradeTypeBaseNode->addAttribute("attackStrength",intToStr(attackStrength), +// mapTagReplacements); //// bool attackStrengthIsMultiplier; -// upgradeTypeBaseNode->addAttribute("attackStrengthIsMultiplier",intToStr(attackStrengthIsMultiplier), mapTagReplacements); +// upgradeTypeBaseNode->addAttribute("attackStrengthIsMultiplier",intToStr(attackStrengthIsMultiplier), +// mapTagReplacements); //// std::map attackStrengthMultiplierValueList; -// for(std::map::const_iterator iterMap = attackStrengthMultiplierValueList.begin(); -// iterMap != attackStrengthMultiplierValueList.end(); ++iterMap) { -// XmlNode *attackStrengthMultiplierValueListNode = upgradeTypeBaseNode->addChild("attackStrengthMultiplierValueList"); +// for(std::map::const_iterator iterMap = +// attackStrengthMultiplierValueList.begin(); iterMap != +// attackStrengthMultiplierValueList.end(); ++iterMap) { XmlNode +//*attackStrengthMultiplierValueListNode = +// upgradeTypeBaseNode->addChild("attackStrengthMultiplierValueList"); // -// attackStrengthMultiplierValueListNode->addAttribute("key",iterMap->first, mapTagReplacements); -// attackStrengthMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); +// attackStrengthMultiplierValueListNode->addAttribute("key",iterMap->first, +// mapTagReplacements); +// attackStrengthMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), +// mapTagReplacements); // } //// int attackRange; -// upgradeTypeBaseNode->addAttribute("attackRange",intToStr(attackRange), mapTagReplacements); +// upgradeTypeBaseNode->addAttribute("attackRange",intToStr(attackRange), +// mapTagReplacements); //// bool attackRangeIsMultiplier; -// upgradeTypeBaseNode->addAttribute("attackRangeIsMultiplier",intToStr(attackRangeIsMultiplier), mapTagReplacements); +// upgradeTypeBaseNode->addAttribute("attackRangeIsMultiplier",intToStr(attackRangeIsMultiplier), +// mapTagReplacements); //// std::map attackRangeMultiplierValueList; -// for(std::map::const_iterator iterMap = attackRangeMultiplierValueList.begin(); -// iterMap != attackRangeMultiplierValueList.end(); ++iterMap) { -// XmlNode *attackRangeMultiplierValueListNode = upgradeTypeBaseNode->addChild("attackRangeMultiplierValueList"); +// for(std::map::const_iterator iterMap = +// attackRangeMultiplierValueList.begin(); iterMap != +// attackRangeMultiplierValueList.end(); ++iterMap) { XmlNode +//*attackRangeMultiplierValueListNode = +// upgradeTypeBaseNode->addChild("attackRangeMultiplierValueList"); // -// attackRangeMultiplierValueListNode->addAttribute("key",iterMap->first, mapTagReplacements); -// attackRangeMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); +// attackRangeMultiplierValueListNode->addAttribute("key",iterMap->first, +// mapTagReplacements); +// attackRangeMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), +// mapTagReplacements); // } // //// int moveSpeed; -// upgradeTypeBaseNode->addAttribute("moveSpeed",intToStr(moveSpeed), mapTagReplacements); +// upgradeTypeBaseNode->addAttribute("moveSpeed",intToStr(moveSpeed), +// mapTagReplacements); //// bool moveSpeedIsMultiplier; -// upgradeTypeBaseNode->addAttribute("moveSpeedIsMultiplier",intToStr(moveSpeedIsMultiplier), mapTagReplacements); +// upgradeTypeBaseNode->addAttribute("moveSpeedIsMultiplier",intToStr(moveSpeedIsMultiplier), +// mapTagReplacements); //// std::map moveSpeedIsMultiplierValueList; -// for(std::map::const_iterator iterMap = moveSpeedIsMultiplierValueList.begin(); -// iterMap != moveSpeedIsMultiplierValueList.end(); ++iterMap) { -// XmlNode *moveSpeedIsMultiplierValueListNode = upgradeTypeBaseNode->addChild("moveSpeedIsMultiplierValueList"); +// for(std::map::const_iterator iterMap = +// moveSpeedIsMultiplierValueList.begin(); iterMap != +// moveSpeedIsMultiplierValueList.end(); ++iterMap) { XmlNode +//*moveSpeedIsMultiplierValueListNode = +// upgradeTypeBaseNode->addChild("moveSpeedIsMultiplierValueList"); // -// moveSpeedIsMultiplierValueListNode->addAttribute("key",iterMap->first, mapTagReplacements); -// moveSpeedIsMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); +// moveSpeedIsMultiplierValueListNode->addAttribute("key",iterMap->first, +// mapTagReplacements); +// moveSpeedIsMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), +// mapTagReplacements); // } // //// int prodSpeed; -// upgradeTypeBaseNode->addAttribute("prodSpeed",intToStr(prodSpeed), mapTagReplacements); +// upgradeTypeBaseNode->addAttribute("prodSpeed",intToStr(prodSpeed), +// mapTagReplacements); //// bool prodSpeedIsMultiplier; -// upgradeTypeBaseNode->addAttribute("prodSpeedIsMultiplier",intToStr(prodSpeedIsMultiplier), mapTagReplacements); +// upgradeTypeBaseNode->addAttribute("prodSpeedIsMultiplier",intToStr(prodSpeedIsMultiplier), +// mapTagReplacements); //// std::map prodSpeedProduceIsMultiplierValueList; -// for(std::map::const_iterator iterMap = prodSpeedProduceIsMultiplierValueList.begin(); -// iterMap != prodSpeedProduceIsMultiplierValueList.end(); ++iterMap) { -// XmlNode *prodSpeedProduceIsMultiplierValueListNode = upgradeTypeBaseNode->addChild("prodSpeedProduceIsMultiplierValueList"); +// for(std::map::const_iterator iterMap = +// prodSpeedProduceIsMultiplierValueList.begin(); iterMap +// != prodSpeedProduceIsMultiplierValueList.end(); ++iterMap) { +// XmlNode *prodSpeedProduceIsMultiplierValueListNode = +// upgradeTypeBaseNode->addChild("prodSpeedProduceIsMultiplierValueList"); // -// prodSpeedProduceIsMultiplierValueListNode->addAttribute("key",iterMap->first, mapTagReplacements); -// prodSpeedProduceIsMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); +// prodSpeedProduceIsMultiplierValueListNode->addAttribute("key",iterMap->first, +// mapTagReplacements); +// prodSpeedProduceIsMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), +// mapTagReplacements); // } // //// std::map prodSpeedUpgradeIsMultiplierValueList; -// for(std::map::const_iterator iterMap = prodSpeedUpgradeIsMultiplierValueList.begin(); -// iterMap != prodSpeedUpgradeIsMultiplierValueList.end(); ++iterMap) { -// XmlNode *prodSpeedUpgradeIsMultiplierValueListNode = upgradeTypeBaseNode->addChild("prodSpeedUpgradeIsMultiplierValueList"); +// for(std::map::const_iterator iterMap = +// prodSpeedUpgradeIsMultiplierValueList.begin(); iterMap +// != prodSpeedUpgradeIsMultiplierValueList.end(); ++iterMap) { +// XmlNode *prodSpeedUpgradeIsMultiplierValueListNode = +// upgradeTypeBaseNode->addChild("prodSpeedUpgradeIsMultiplierValueList"); // -// prodSpeedUpgradeIsMultiplierValueListNode->addAttribute("key",iterMap->first, mapTagReplacements); -// prodSpeedUpgradeIsMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); +// prodSpeedUpgradeIsMultiplierValueListNode->addAttribute("key",iterMap->first, +// mapTagReplacements); +// prodSpeedUpgradeIsMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), +// mapTagReplacements); // } // //// std::map prodSpeedMorphIsMultiplierValueList; -// for(std::map::const_iterator iterMap = prodSpeedMorphIsMultiplierValueList.begin(); -// iterMap != prodSpeedMorphIsMultiplierValueList.end(); ++iterMap) { -// XmlNode *prodSpeedMorphIsMultiplierValueListNode = upgradeTypeBaseNode->addChild("prodSpeedMorphIsMultiplierValueList"); +// for(std::map::const_iterator iterMap = +// prodSpeedMorphIsMultiplierValueList.begin(); iterMap +// != prodSpeedMorphIsMultiplierValueList.end(); ++iterMap) { XmlNode +//*prodSpeedMorphIsMultiplierValueListNode = +// upgradeTypeBaseNode->addChild("prodSpeedMorphIsMultiplierValueList"); // -// prodSpeedMorphIsMultiplierValueListNode->addAttribute("key",iterMap->first, mapTagReplacements); -// prodSpeedMorphIsMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); +// prodSpeedMorphIsMultiplierValueListNode->addAttribute("key",iterMap->first, +// mapTagReplacements); +// prodSpeedMorphIsMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), +// mapTagReplacements); // } //} void UpgradeTypeBase::saveGame(XmlNode *rootNode) const { - std::map mapTagReplacements; - XmlNode *upgradeTypeBaseNode = rootNode->addChild("UpgradeTypeBase"); - - upgradeTypeBaseNode->addAttribute("upgradename",upgradename, mapTagReplacements); - -//// int maxHp; -// upgradeTypeBaseNode->addAttribute("maxHp",intToStr(maxHp), mapTagReplacements); -//// bool maxHpIsMultiplier; -// upgradeTypeBaseNode->addAttribute("maxHpIsMultiplier",intToStr(maxHpIsMultiplier), mapTagReplacements); -//// int maxHpRegeneration; -// upgradeTypeBaseNode->addAttribute("maxHpRegeneration",intToStr(maxHpRegeneration), mapTagReplacements); -//// //bool maxHpRegenerationIsMultiplier; -//// -//// int sight; -// upgradeTypeBaseNode->addAttribute("sight",intToStr(sight), mapTagReplacements); -//// bool sightIsMultiplier; -// upgradeTypeBaseNode->addAttribute("sightIsMultiplier",intToStr(sightIsMultiplier), mapTagReplacements); -//// int maxEp; -// upgradeTypeBaseNode->addAttribute("maxEp",intToStr(maxEp), mapTagReplacements); -//// bool maxEpIsMultiplier; -// upgradeTypeBaseNode->addAttribute("maxEpIsMultiplier",intToStr(maxEpIsMultiplier), mapTagReplacements); -//// int maxEpRegeneration; -// upgradeTypeBaseNode->addAttribute("maxEpRegeneration",intToStr(maxEpRegeneration), mapTagReplacements); -//// //bool maxEpRegenerationIsMultiplier; -//// int armor; -// upgradeTypeBaseNode->addAttribute("armor",intToStr(armor), mapTagReplacements); -//// bool armorIsMultiplier; -// upgradeTypeBaseNode->addAttribute("armorIsMultiplier",intToStr(armorIsMultiplier), mapTagReplacements); -//// int attackStrength; -// upgradeTypeBaseNode->addAttribute("attackStrength",intToStr(attackStrength), mapTagReplacements); -//// bool attackStrengthIsMultiplier; -// upgradeTypeBaseNode->addAttribute("attackStrengthIsMultiplier",intToStr(attackStrengthIsMultiplier), mapTagReplacements); -//// std::map attackStrengthMultiplierValueList; -// for(std::map::const_iterator iterMap = attackStrengthMultiplierValueList.begin(); -// iterMap != attackStrengthMultiplierValueList.end(); ++iterMap) { -// XmlNode *attackStrengthMultiplierValueListNode = upgradeTypeBaseNode->addChild("attackStrengthMultiplierValueList"); -// -// attackStrengthMultiplierValueListNode->addAttribute("key",iterMap->first, mapTagReplacements); -// attackStrengthMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); -// } -//// int attackRange; -// upgradeTypeBaseNode->addAttribute("attackRange",intToStr(attackRange), mapTagReplacements); -//// bool attackRangeIsMultiplier; -// upgradeTypeBaseNode->addAttribute("attackRangeIsMultiplier",intToStr(attackRangeIsMultiplier), mapTagReplacements); -//// std::map attackRangeMultiplierValueList; -// for(std::map::const_iterator iterMap = attackRangeMultiplierValueList.begin(); -// iterMap != attackRangeMultiplierValueList.end(); ++iterMap) { -// XmlNode *attackRangeMultiplierValueListNode = upgradeTypeBaseNode->addChild("attackRangeMultiplierValueList"); -// -// attackRangeMultiplierValueListNode->addAttribute("key",iterMap->first, mapTagReplacements); -// attackRangeMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); -// } -// -//// int moveSpeed; -// upgradeTypeBaseNode->addAttribute("moveSpeed",intToStr(moveSpeed), mapTagReplacements); -//// bool moveSpeedIsMultiplier; -// upgradeTypeBaseNode->addAttribute("moveSpeedIsMultiplier",intToStr(moveSpeedIsMultiplier), mapTagReplacements); -//// std::map moveSpeedIsMultiplierValueList; -// for(std::map::const_iterator iterMap = moveSpeedIsMultiplierValueList.begin(); -// iterMap != moveSpeedIsMultiplierValueList.end(); ++iterMap) { -// XmlNode *moveSpeedIsMultiplierValueListNode = upgradeTypeBaseNode->addChild("moveSpeedIsMultiplierValueList"); -// -// moveSpeedIsMultiplierValueListNode->addAttribute("key",iterMap->first, mapTagReplacements); -// moveSpeedIsMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); -// } -// -//// int prodSpeed; -// upgradeTypeBaseNode->addAttribute("prodSpeed",intToStr(prodSpeed), mapTagReplacements); -//// bool prodSpeedIsMultiplier; -// upgradeTypeBaseNode->addAttribute("prodSpeedIsMultiplier",intToStr(prodSpeedIsMultiplier), mapTagReplacements); -//// std::map prodSpeedProduceIsMultiplierValueList; -// for(std::map::const_iterator iterMap = prodSpeedProduceIsMultiplierValueList.begin(); -// iterMap != prodSpeedProduceIsMultiplierValueList.end(); ++iterMap) { -// XmlNode *prodSpeedProduceIsMultiplierValueListNode = upgradeTypeBaseNode->addChild("prodSpeedProduceIsMultiplierValueList"); -// -// prodSpeedProduceIsMultiplierValueListNode->addAttribute("key",iterMap->first, mapTagReplacements); -// prodSpeedProduceIsMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); -// } -// -//// std::map prodSpeedUpgradeIsMultiplierValueList; -// for(std::map::const_iterator iterMap = prodSpeedUpgradeIsMultiplierValueList.begin(); -// iterMap != prodSpeedUpgradeIsMultiplierValueList.end(); ++iterMap) { -// XmlNode *prodSpeedUpgradeIsMultiplierValueListNode = upgradeTypeBaseNode->addChild("prodSpeedUpgradeIsMultiplierValueList"); -// -// prodSpeedUpgradeIsMultiplierValueListNode->addAttribute("key",iterMap->first, mapTagReplacements); -// prodSpeedUpgradeIsMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); -// } -// -//// std::map prodSpeedMorphIsMultiplierValueList; -// for(std::map::const_iterator iterMap = prodSpeedMorphIsMultiplierValueList.begin(); -// iterMap != prodSpeedMorphIsMultiplierValueList.end(); ++iterMap) { -// XmlNode *prodSpeedMorphIsMultiplierValueListNode = upgradeTypeBaseNode->addChild("prodSpeedMorphIsMultiplierValueList"); -// -// prodSpeedMorphIsMultiplierValueListNode->addAttribute("key",iterMap->first, mapTagReplacements); -// prodSpeedMorphIsMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); -// } + std::map mapTagReplacements; + XmlNode *upgradeTypeBaseNode = rootNode->addChild("UpgradeTypeBase"); + + upgradeTypeBaseNode->addAttribute("upgradename", upgradename, + mapTagReplacements); + + //// int maxHp; + // upgradeTypeBaseNode->addAttribute("maxHp",intToStr(maxHp), + // mapTagReplacements); + //// bool maxHpIsMultiplier; + // upgradeTypeBaseNode->addAttribute("maxHpIsMultiplier",intToStr(maxHpIsMultiplier), + // mapTagReplacements); + //// int maxHpRegeneration; + // upgradeTypeBaseNode->addAttribute("maxHpRegeneration",intToStr(maxHpRegeneration), + // mapTagReplacements); + //// //bool maxHpRegenerationIsMultiplier; + //// + //// int sight; + // upgradeTypeBaseNode->addAttribute("sight",intToStr(sight), + // mapTagReplacements); + //// bool sightIsMultiplier; + // upgradeTypeBaseNode->addAttribute("sightIsMultiplier",intToStr(sightIsMultiplier), + // mapTagReplacements); + //// int maxEp; + // upgradeTypeBaseNode->addAttribute("maxEp",intToStr(maxEp), + // mapTagReplacements); + //// bool maxEpIsMultiplier; + // upgradeTypeBaseNode->addAttribute("maxEpIsMultiplier",intToStr(maxEpIsMultiplier), + // mapTagReplacements); + //// int maxEpRegeneration; + // upgradeTypeBaseNode->addAttribute("maxEpRegeneration",intToStr(maxEpRegeneration), + // mapTagReplacements); + //// //bool maxEpRegenerationIsMultiplier; + //// int armor; + // upgradeTypeBaseNode->addAttribute("armor",intToStr(armor), + // mapTagReplacements); + //// bool armorIsMultiplier; + // upgradeTypeBaseNode->addAttribute("armorIsMultiplier",intToStr(armorIsMultiplier), + // mapTagReplacements); + //// int attackStrength; + // upgradeTypeBaseNode->addAttribute("attackStrength",intToStr(attackStrength), + // mapTagReplacements); + //// bool attackStrengthIsMultiplier; + // upgradeTypeBaseNode->addAttribute("attackStrengthIsMultiplier",intToStr(attackStrengthIsMultiplier), + // mapTagReplacements); + //// std::map attackStrengthMultiplierValueList; + // for(std::map::const_iterator iterMap = + // attackStrengthMultiplierValueList.begin(); iterMap + // != attackStrengthMultiplierValueList.end(); ++iterMap) { XmlNode + //*attackStrengthMultiplierValueListNode = + // upgradeTypeBaseNode->addChild("attackStrengthMultiplierValueList"); + // + // attackStrengthMultiplierValueListNode->addAttribute("key",iterMap->first, + // mapTagReplacements); + // attackStrengthMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), + // mapTagReplacements); + // } + //// int attackRange; + // upgradeTypeBaseNode->addAttribute("attackRange",intToStr(attackRange), + // mapTagReplacements); + //// bool attackRangeIsMultiplier; + // upgradeTypeBaseNode->addAttribute("attackRangeIsMultiplier",intToStr(attackRangeIsMultiplier), + // mapTagReplacements); + //// std::map attackRangeMultiplierValueList; + // for(std::map::const_iterator iterMap = + // attackRangeMultiplierValueList.begin(); iterMap != + // attackRangeMultiplierValueList.end(); ++iterMap) { XmlNode + //*attackRangeMultiplierValueListNode = + // upgradeTypeBaseNode->addChild("attackRangeMultiplierValueList"); + // + // attackRangeMultiplierValueListNode->addAttribute("key",iterMap->first, + // mapTagReplacements); + // attackRangeMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), + // mapTagReplacements); + // } + // + //// int moveSpeed; + // upgradeTypeBaseNode->addAttribute("moveSpeed",intToStr(moveSpeed), + // mapTagReplacements); + //// bool moveSpeedIsMultiplier; + // upgradeTypeBaseNode->addAttribute("moveSpeedIsMultiplier",intToStr(moveSpeedIsMultiplier), + // mapTagReplacements); + //// std::map moveSpeedIsMultiplierValueList; + // for(std::map::const_iterator iterMap = + // moveSpeedIsMultiplierValueList.begin(); iterMap != + // moveSpeedIsMultiplierValueList.end(); ++iterMap) { XmlNode + //*moveSpeedIsMultiplierValueListNode = + // upgradeTypeBaseNode->addChild("moveSpeedIsMultiplierValueList"); + // + // moveSpeedIsMultiplierValueListNode->addAttribute("key",iterMap->first, + // mapTagReplacements); + // moveSpeedIsMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), + // mapTagReplacements); + // } + // + //// int prodSpeed; + // upgradeTypeBaseNode->addAttribute("prodSpeed",intToStr(prodSpeed), + // mapTagReplacements); + //// bool prodSpeedIsMultiplier; + // upgradeTypeBaseNode->addAttribute("prodSpeedIsMultiplier",intToStr(prodSpeedIsMultiplier), + // mapTagReplacements); + //// std::map prodSpeedProduceIsMultiplierValueList; + // for(std::map::const_iterator iterMap = + // prodSpeedProduceIsMultiplierValueList.begin(); iterMap + // != prodSpeedProduceIsMultiplierValueList.end(); ++iterMap) { + // XmlNode *prodSpeedProduceIsMultiplierValueListNode = + // upgradeTypeBaseNode->addChild("prodSpeedProduceIsMultiplierValueList"); + // + // prodSpeedProduceIsMultiplierValueListNode->addAttribute("key",iterMap->first, + // mapTagReplacements); + // prodSpeedProduceIsMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), + // mapTagReplacements); + // } + // + //// std::map prodSpeedUpgradeIsMultiplierValueList; + // for(std::map::const_iterator iterMap = + // prodSpeedUpgradeIsMultiplierValueList.begin(); iterMap + // != prodSpeedUpgradeIsMultiplierValueList.end(); ++iterMap) { + // XmlNode *prodSpeedUpgradeIsMultiplierValueListNode = + // upgradeTypeBaseNode->addChild("prodSpeedUpgradeIsMultiplierValueList"); + // + // prodSpeedUpgradeIsMultiplierValueListNode->addAttribute("key",iterMap->first, + // mapTagReplacements); + // prodSpeedUpgradeIsMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), + // mapTagReplacements); + // } + // + //// std::map prodSpeedMorphIsMultiplierValueList; + // for(std::map::const_iterator iterMap = + // prodSpeedMorphIsMultiplierValueList.begin(); iterMap + // != prodSpeedMorphIsMultiplierValueList.end(); ++iterMap) { + // XmlNode *prodSpeedMorphIsMultiplierValueListNode = + // upgradeTypeBaseNode->addChild("prodSpeedMorphIsMultiplierValueList"); + // + // prodSpeedMorphIsMultiplierValueListNode->addAttribute("key",iterMap->first, + // mapTagReplacements); + // prodSpeedMorphIsMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), + // mapTagReplacements); + // } } -//void UpgradeTypeBase::loadGameBoost(const XmlNode *rootNode) { -// const XmlNode *upgradeTypeBaseNode = rootNode->getChild("UpgradeTypeBaseBoost"); +// void UpgradeTypeBase::loadGameBoost(const XmlNode *rootNode) { +// const XmlNode *upgradeTypeBaseNode = +// rootNode->getChild("UpgradeTypeBaseBoost"); // -// //description = upgradeTypeBaseNode->getAttribute("description")->getValue(); +// //description = +// upgradeTypeBaseNode->getAttribute("description")->getValue(); // -// upgradename = upgradeTypeBaseNode->getAttribute("upgradename")->getValue(); +// upgradename = +// upgradeTypeBaseNode->getAttribute("upgradename")->getValue(); // // // int maxHp; // maxHp = upgradeTypeBaseNode->getAttribute("maxHp")->getIntValue(); // // bool maxHpIsMultiplier; -// maxHpIsMultiplier = (upgradeTypeBaseNode->getAttribute("maxHpIsMultiplier")->getIntValue() != 0); -// // int maxHpRegeneration; -// maxHpRegeneration = upgradeTypeBaseNode->getAttribute("maxHpRegeneration")->getIntValue(); -// // //bool maxHpRegenerationIsMultiplier; -// // -// // int sight; -// sight = upgradeTypeBaseNode->getAttribute("sight")->getIntValue(); -// // bool sightIsMultiplier; -// sightIsMultiplier = (upgradeTypeBaseNode->getAttribute("sightIsMultiplier")->getIntValue() != 0); -// // int maxEp; -// maxEp = upgradeTypeBaseNode->getAttribute("maxEp")->getIntValue(); -// // bool maxEpIsMultiplier; -// maxEpIsMultiplier = (upgradeTypeBaseNode->getAttribute("maxEpIsMultiplier")->getIntValue() != 0); -// // int maxEpRegeneration; -// maxEpRegeneration = upgradeTypeBaseNode->getAttribute("maxEpRegeneration")->getIntValue(); -// // //bool maxEpRegenerationIsMultiplier; -// // int armor; -// armor = upgradeTypeBaseNode->getAttribute("armor")->getIntValue(); -// // bool armorIsMultiplier; -// armorIsMultiplier = (upgradeTypeBaseNode->getAttribute("armorIsMultiplier")->getIntValue() != 0); -// // int attackStrength; -// attackStrength = upgradeTypeBaseNode->getAttribute("attackStrength")->getIntValue(); -// // bool attackStrengthIsMultiplier; -// attackStrengthIsMultiplier = (upgradeTypeBaseNode->getAttribute("attackStrengthIsMultiplier")->getIntValue() != 0); -// // std::map attackStrengthMultiplierValueList; -// vector attackStrengthMultiplierValueNodeList = upgradeTypeBaseNode->getChildList("attackStrengthMultiplierValueList"); -// for(unsigned int i = 0; i < attackStrengthMultiplierValueNodeList.size(); ++i) { -// XmlNode *node = attackStrengthMultiplierValueNodeList[i]; -// -// attackStrengthMultiplierValueList[node->getAttribute("key")->getValue()] = -// node->getAttribute("value")->getIntValue(); -// } -// // int attackRange; -// attackRange = upgradeTypeBaseNode->getAttribute("attackRange")->getIntValue(); -// // bool attackRangeIsMultiplier; -// attackRangeIsMultiplier = (upgradeTypeBaseNode->getAttribute("attackRangeIsMultiplier")->getIntValue() != 0); -// // std::map attackRangeMultiplierValueList; -// vector attackRangeMultiplierValueNodeList = upgradeTypeBaseNode->getChildList("attackRangeMultiplierValueList"); -// for(unsigned int i = 0; i < attackRangeMultiplierValueNodeList.size(); ++i) { -// XmlNode *node = attackRangeMultiplierValueNodeList[i]; -// -// attackRangeMultiplierValueList[node->getAttribute("key")->getValue()] = -// node->getAttribute("value")->getIntValue(); -// } -// -// // int moveSpeed; -// moveSpeed = upgradeTypeBaseNode->getAttribute("moveSpeed")->getIntValue(); -// // bool moveSpeedIsMultiplier; -// moveSpeedIsMultiplier = (upgradeTypeBaseNode->getAttribute("moveSpeedIsMultiplier")->getIntValue() != 0); -// // std::map moveSpeedIsMultiplierValueList; -// vector moveSpeedIsMultiplierValueNodeList = upgradeTypeBaseNode->getChildList("moveSpeedIsMultiplierValueList"); -// for(unsigned int i = 0; i < moveSpeedIsMultiplierValueNodeList.size(); ++i) { -// XmlNode *node = moveSpeedIsMultiplierValueNodeList[i]; -// -// moveSpeedIsMultiplierValueList[node->getAttribute("key")->getValue()] = -// node->getAttribute("value")->getIntValue(); -// } -// -// // int prodSpeed; -// prodSpeed = upgradeTypeBaseNode->getAttribute("prodSpeed")->getIntValue(); -// // bool prodSpeedIsMultiplier; -// prodSpeedIsMultiplier = (upgradeTypeBaseNode->getAttribute("prodSpeedIsMultiplier")->getIntValue() != 0); -// // std::map prodSpeedProduceIsMultiplierValueList; -// vector prodSpeedProduceIsMultiplierValueNodeList = upgradeTypeBaseNode->getChildList("prodSpeedProduceIsMultiplierValueList"); -// for(unsigned int i = 0; i < prodSpeedProduceIsMultiplierValueNodeList.size(); ++i) { -// XmlNode *node = prodSpeedProduceIsMultiplierValueNodeList[i]; -// -// prodSpeedProduceIsMultiplierValueList[node->getAttribute("key")->getValue()] = -// node->getAttribute("value")->getIntValue(); -// } -// -// // std::map prodSpeedUpgradeIsMultiplierValueList; -// vector prodSpeedUpgradeIsMultiplierValueNodeList = upgradeTypeBaseNode->getChildList("prodSpeedUpgradeIsMultiplierValueList"); -// for(unsigned int i = 0; i < prodSpeedUpgradeIsMultiplierValueNodeList.size(); ++i) { -// XmlNode *node = prodSpeedUpgradeIsMultiplierValueNodeList[i]; -// -// prodSpeedUpgradeIsMultiplierValueList[node->getAttribute("key")->getValue()] = -// node->getAttribute("value")->getIntValue(); -// } -// -// // std::map prodSpeedMorphIsMultiplierValueList; -// vector prodSpeedMorphIsMultiplierValueNodeList = upgradeTypeBaseNode->getChildList("prodSpeedMorphIsMultiplierValueList"); -// for(unsigned int i = 0; i < prodSpeedMorphIsMultiplierValueNodeList.size(); ++i) { -// XmlNode *node = prodSpeedMorphIsMultiplierValueNodeList[i]; -// -// prodSpeedMorphIsMultiplierValueList[node->getAttribute("key")->getValue()] = -// node->getAttribute("value")->getIntValue(); -// } -//} - -const UpgradeType * UpgradeTypeBase::loadGame(const XmlNode *rootNode, Faction *faction) { - const XmlNode *upgradeTypeBaseNode = rootNode->getChild("UpgradeTypeBase"); - - //description = upgradeTypeBaseNode->getAttribute("description")->getValue(); - - string upgradename = upgradeTypeBaseNode->getAttribute("upgradename")->getValue(); - return faction->getType()->getUpgradeType(upgradename); - // int maxHp; -// maxHp = upgradeTypeBaseNode->getAttribute("maxHp")->getIntValue(); -// // bool maxHpIsMultiplier; -// maxHpIsMultiplier = upgradeTypeBaseNode->getAttribute("maxHpIsMultiplier")->getIntValue(); +// maxHpIsMultiplier = +//(upgradeTypeBaseNode->getAttribute("maxHpIsMultiplier")->getIntValue() != 0); // // int maxHpRegeneration; -// maxHpRegeneration = upgradeTypeBaseNode->getAttribute("maxHpRegeneration")->getIntValue(); +// maxHpRegeneration = +// upgradeTypeBaseNode->getAttribute("maxHpRegeneration")->getIntValue(); // // //bool maxHpRegenerationIsMultiplier; // // // // int sight; // sight = upgradeTypeBaseNode->getAttribute("sight")->getIntValue(); // // bool sightIsMultiplier; -// sightIsMultiplier = upgradeTypeBaseNode->getAttribute("sightIsMultiplier")->getIntValue(); +// sightIsMultiplier = +//(upgradeTypeBaseNode->getAttribute("sightIsMultiplier")->getIntValue() != 0); // // int maxEp; // maxEp = upgradeTypeBaseNode->getAttribute("maxEp")->getIntValue(); // // bool maxEpIsMultiplier; -// maxEpIsMultiplier = upgradeTypeBaseNode->getAttribute("maxEpIsMultiplier")->getIntValue(); +// maxEpIsMultiplier = +//(upgradeTypeBaseNode->getAttribute("maxEpIsMultiplier")->getIntValue() != 0); // // int maxEpRegeneration; -// maxEpRegeneration = upgradeTypeBaseNode->getAttribute("maxEpRegeneration")->getIntValue(); +// maxEpRegeneration = +// upgradeTypeBaseNode->getAttribute("maxEpRegeneration")->getIntValue(); // // //bool maxEpRegenerationIsMultiplier; // // int armor; // armor = upgradeTypeBaseNode->getAttribute("armor")->getIntValue(); // // bool armorIsMultiplier; -// armorIsMultiplier = upgradeTypeBaseNode->getAttribute("armorIsMultiplier")->getIntValue(); +// armorIsMultiplier = +//(upgradeTypeBaseNode->getAttribute("armorIsMultiplier")->getIntValue() != 0); // // int attackStrength; -// attackStrength = upgradeTypeBaseNode->getAttribute("attackStrength")->getIntValue(); +// attackStrength = +// upgradeTypeBaseNode->getAttribute("attackStrength")->getIntValue(); // // bool attackStrengthIsMultiplier; -// attackStrengthIsMultiplier = upgradeTypeBaseNode->getAttribute("attackStrengthIsMultiplier")->getIntValue(); +// attackStrengthIsMultiplier = +//(upgradeTypeBaseNode->getAttribute("attackStrengthIsMultiplier")->getIntValue() +//!= 0); // // std::map attackStrengthMultiplierValueList; -// vector attackStrengthMultiplierValueNodeList = upgradeTypeBaseNode->getChildList("attackStrengthMultiplierValueList"); -// for(unsigned int i = 0; i < attackStrengthMultiplierValueNodeList.size(); ++i) { -// XmlNode *node = attackStrengthMultiplierValueNodeList[i]; +// vector attackStrengthMultiplierValueNodeList = +// upgradeTypeBaseNode->getChildList("attackStrengthMultiplierValueList"); +// for(unsigned int i = 0; i < +// attackStrengthMultiplierValueNodeList.size(); ++i) { XmlNode *node +// = attackStrengthMultiplierValueNodeList[i]; // -// attackStrengthMultiplierValueList[node->getAttribute("key")->getValue()] = -// node->getAttribute("value")->getIntValue(); +// attackStrengthMultiplierValueList[node->getAttribute("key")->getValue()] +//= node->getAttribute("value")->getIntValue(); // } // // int attackRange; -// attackRange = upgradeTypeBaseNode->getAttribute("attackRange")->getIntValue(); +// attackRange = +// upgradeTypeBaseNode->getAttribute("attackRange")->getIntValue(); // // bool attackRangeIsMultiplier; -// attackRangeIsMultiplier = upgradeTypeBaseNode->getAttribute("attackRangeIsMultiplier")->getIntValue(); +// attackRangeIsMultiplier = +//(upgradeTypeBaseNode->getAttribute("attackRangeIsMultiplier")->getIntValue() +//!= 0); // // std::map attackRangeMultiplierValueList; -// vector attackRangeMultiplierValueNodeList = upgradeTypeBaseNode->getChildList("attackRangeMultiplierValueList"); -// for(unsigned int i = 0; i < attackRangeMultiplierValueNodeList.size(); ++i) { -// XmlNode *node = attackRangeMultiplierValueNodeList[i]; +// vector attackRangeMultiplierValueNodeList = +// upgradeTypeBaseNode->getChildList("attackRangeMultiplierValueList"); +// for(unsigned int i = 0; i < attackRangeMultiplierValueNodeList.size(); +//++i) { XmlNode *node = attackRangeMultiplierValueNodeList[i]; // -// attackRangeMultiplierValueList[node->getAttribute("key")->getValue()] = -// node->getAttribute("value")->getIntValue(); +// attackRangeMultiplierValueList[node->getAttribute("key")->getValue()] +//= node->getAttribute("value")->getIntValue(); // } // // // int moveSpeed; -// moveSpeed = upgradeTypeBaseNode->getAttribute("moveSpeed")->getIntValue(); +// moveSpeed = +// upgradeTypeBaseNode->getAttribute("moveSpeed")->getIntValue(); // // bool moveSpeedIsMultiplier; -// moveSpeedIsMultiplier = upgradeTypeBaseNode->getAttribute("moveSpeedIsMultiplier")->getIntValue(); +// moveSpeedIsMultiplier = +//(upgradeTypeBaseNode->getAttribute("moveSpeedIsMultiplier")->getIntValue() != +// 0); // // std::map moveSpeedIsMultiplierValueList; -// vector moveSpeedIsMultiplierValueNodeList = upgradeTypeBaseNode->getChildList("moveSpeedIsMultiplierValueList"); -// for(unsigned int i = 0; i < moveSpeedIsMultiplierValueNodeList.size(); ++i) { -// XmlNode *node = moveSpeedIsMultiplierValueNodeList[i]; +// vector moveSpeedIsMultiplierValueNodeList = +// upgradeTypeBaseNode->getChildList("moveSpeedIsMultiplierValueList"); +// for(unsigned int i = 0; i < moveSpeedIsMultiplierValueNodeList.size(); +//++i) { XmlNode *node = moveSpeedIsMultiplierValueNodeList[i]; // -// moveSpeedIsMultiplierValueList[node->getAttribute("key")->getValue()] = -// node->getAttribute("value")->getIntValue(); +// moveSpeedIsMultiplierValueList[node->getAttribute("key")->getValue()] +//= node->getAttribute("value")->getIntValue(); // } // // // int prodSpeed; -// prodSpeed = upgradeTypeBaseNode->getAttribute("prodSpeed")->getIntValue(); +// prodSpeed = +// upgradeTypeBaseNode->getAttribute("prodSpeed")->getIntValue(); // // bool prodSpeedIsMultiplier; -// prodSpeedIsMultiplier = upgradeTypeBaseNode->getAttribute("prodSpeedIsMultiplier")->getIntValue(); +// prodSpeedIsMultiplier = +//(upgradeTypeBaseNode->getAttribute("prodSpeedIsMultiplier")->getIntValue() != +// 0); // // std::map prodSpeedProduceIsMultiplierValueList; -// vector prodSpeedProduceIsMultiplierValueNodeList = upgradeTypeBaseNode->getChildList("prodSpeedProduceIsMultiplierValueList"); -// for(unsigned int i = 0; i < prodSpeedProduceIsMultiplierValueNodeList.size(); ++i) { -// XmlNode *node = prodSpeedProduceIsMultiplierValueNodeList[i]; +// vector prodSpeedProduceIsMultiplierValueNodeList = +// upgradeTypeBaseNode->getChildList("prodSpeedProduceIsMultiplierValueList"); +// for(unsigned int i = 0; i < +// prodSpeedProduceIsMultiplierValueNodeList.size(); ++i) { XmlNode +// *node = prodSpeedProduceIsMultiplierValueNodeList[i]; // -// prodSpeedProduceIsMultiplierValueList[node->getAttribute("key")->getValue()] = -// node->getAttribute("value")->getIntValue(); +// prodSpeedProduceIsMultiplierValueList[node->getAttribute("key")->getValue()] +//= node->getAttribute("value")->getIntValue(); // } // // // std::map prodSpeedUpgradeIsMultiplierValueList; -// vector prodSpeedUpgradeIsMultiplierValueNodeList = upgradeTypeBaseNode->getChildList("prodSpeedUpgradeIsMultiplierValueList"); -// for(unsigned int i = 0; i < prodSpeedUpgradeIsMultiplierValueNodeList.size(); ++i) { -// XmlNode *node = prodSpeedUpgradeIsMultiplierValueNodeList[i]; +// vector prodSpeedUpgradeIsMultiplierValueNodeList = +// upgradeTypeBaseNode->getChildList("prodSpeedUpgradeIsMultiplierValueList"); +// for(unsigned int i = 0; i < +// prodSpeedUpgradeIsMultiplierValueNodeList.size(); ++i) { XmlNode +// *node = prodSpeedUpgradeIsMultiplierValueNodeList[i]; // -// prodSpeedUpgradeIsMultiplierValueList[node->getAttribute("key")->getValue()] = -// node->getAttribute("value")->getIntValue(); +// prodSpeedUpgradeIsMultiplierValueList[node->getAttribute("key")->getValue()] +//= node->getAttribute("value")->getIntValue(); // } // // // std::map prodSpeedMorphIsMultiplierValueList; -// vector prodSpeedMorphIsMultiplierValueNodeList = upgradeTypeBaseNode->getChildList("prodSpeedMorphIsMultiplierValueList"); -// for(unsigned int i = 0; i < prodSpeedMorphIsMultiplierValueNodeList.size(); ++i) { -// XmlNode *node = prodSpeedMorphIsMultiplierValueNodeList[i]; +// vector prodSpeedMorphIsMultiplierValueNodeList = +// upgradeTypeBaseNode->getChildList("prodSpeedMorphIsMultiplierValueList"); +// for(unsigned int i = 0; i < +// prodSpeedMorphIsMultiplierValueNodeList.size(); ++i) { XmlNode +// *node = prodSpeedMorphIsMultiplierValueNodeList[i]; // -// prodSpeedMorphIsMultiplierValueList[node->getAttribute("key")->getValue()] = -// node->getAttribute("value")->getIntValue(); +// prodSpeedMorphIsMultiplierValueList[node->getAttribute("key")->getValue()] +//= node->getAttribute("value")->getIntValue(); // } +// } + +const UpgradeType *UpgradeTypeBase::loadGame(const XmlNode *rootNode, + Faction *faction) { + const XmlNode *upgradeTypeBaseNode = rootNode->getChild("UpgradeTypeBase"); + + // description = upgradeTypeBaseNode->getAttribute("description")->getValue(); + + string upgradename = + upgradeTypeBaseNode->getAttribute("upgradename")->getValue(); + return faction->getType()->getUpgradeType(upgradename); + // int maxHp; + // maxHp = upgradeTypeBaseNode->getAttribute("maxHp")->getIntValue(); + // // bool maxHpIsMultiplier; + // maxHpIsMultiplier = + // upgradeTypeBaseNode->getAttribute("maxHpIsMultiplier")->getIntValue(); + // // int maxHpRegeneration; + // maxHpRegeneration = + // upgradeTypeBaseNode->getAttribute("maxHpRegeneration")->getIntValue(); + // // //bool maxHpRegenerationIsMultiplier; + // // + // // int sight; + // sight = upgradeTypeBaseNode->getAttribute("sight")->getIntValue(); + // // bool sightIsMultiplier; + // sightIsMultiplier = + // upgradeTypeBaseNode->getAttribute("sightIsMultiplier")->getIntValue(); + // // int maxEp; + // maxEp = upgradeTypeBaseNode->getAttribute("maxEp")->getIntValue(); + // // bool maxEpIsMultiplier; + // maxEpIsMultiplier = + // upgradeTypeBaseNode->getAttribute("maxEpIsMultiplier")->getIntValue(); + // // int maxEpRegeneration; + // maxEpRegeneration = + // upgradeTypeBaseNode->getAttribute("maxEpRegeneration")->getIntValue(); + // // //bool maxEpRegenerationIsMultiplier; + // // int armor; + // armor = upgradeTypeBaseNode->getAttribute("armor")->getIntValue(); + // // bool armorIsMultiplier; + // armorIsMultiplier = + // upgradeTypeBaseNode->getAttribute("armorIsMultiplier")->getIntValue(); + // // int attackStrength; + // attackStrength = + // upgradeTypeBaseNode->getAttribute("attackStrength")->getIntValue(); + // // bool attackStrengthIsMultiplier; + // attackStrengthIsMultiplier = + // upgradeTypeBaseNode->getAttribute("attackStrengthIsMultiplier")->getIntValue(); + // // std::map attackStrengthMultiplierValueList; + // vector attackStrengthMultiplierValueNodeList = + // upgradeTypeBaseNode->getChildList("attackStrengthMultiplierValueList"); + // for(unsigned int i = 0; i < + // attackStrengthMultiplierValueNodeList.size(); ++i) { XmlNode *node + // = attackStrengthMultiplierValueNodeList[i]; + // + // attackStrengthMultiplierValueList[node->getAttribute("key")->getValue()] + //= node->getAttribute("value")->getIntValue(); + // } + // // int attackRange; + // attackRange = + // upgradeTypeBaseNode->getAttribute("attackRange")->getIntValue(); + // // bool attackRangeIsMultiplier; + // attackRangeIsMultiplier = + // upgradeTypeBaseNode->getAttribute("attackRangeIsMultiplier")->getIntValue(); + // // std::map attackRangeMultiplierValueList; + // vector attackRangeMultiplierValueNodeList = + // upgradeTypeBaseNode->getChildList("attackRangeMultiplierValueList"); + // for(unsigned int i = 0; i < attackRangeMultiplierValueNodeList.size(); + //++i) { XmlNode *node = attackRangeMultiplierValueNodeList[i]; + // + // attackRangeMultiplierValueList[node->getAttribute("key")->getValue()] + //= node->getAttribute("value")->getIntValue(); + // } + // + // // int moveSpeed; + // moveSpeed = + // upgradeTypeBaseNode->getAttribute("moveSpeed")->getIntValue(); + // // bool moveSpeedIsMultiplier; + // moveSpeedIsMultiplier = + // upgradeTypeBaseNode->getAttribute("moveSpeedIsMultiplier")->getIntValue(); + // // std::map moveSpeedIsMultiplierValueList; + // vector moveSpeedIsMultiplierValueNodeList = + // upgradeTypeBaseNode->getChildList("moveSpeedIsMultiplierValueList"); + // for(unsigned int i = 0; i < moveSpeedIsMultiplierValueNodeList.size(); + //++i) { XmlNode *node = moveSpeedIsMultiplierValueNodeList[i]; + // + // moveSpeedIsMultiplierValueList[node->getAttribute("key")->getValue()] + //= node->getAttribute("value")->getIntValue(); + // } + // + // // int prodSpeed; + // prodSpeed = + // upgradeTypeBaseNode->getAttribute("prodSpeed")->getIntValue(); + // // bool prodSpeedIsMultiplier; + // prodSpeedIsMultiplier = + // upgradeTypeBaseNode->getAttribute("prodSpeedIsMultiplier")->getIntValue(); + // // std::map prodSpeedProduceIsMultiplierValueList; + // vector prodSpeedProduceIsMultiplierValueNodeList = + // upgradeTypeBaseNode->getChildList("prodSpeedProduceIsMultiplierValueList"); + // for(unsigned int i = 0; i < + // prodSpeedProduceIsMultiplierValueNodeList.size(); ++i) { XmlNode + // *node = prodSpeedProduceIsMultiplierValueNodeList[i]; + // + // prodSpeedProduceIsMultiplierValueList[node->getAttribute("key")->getValue()] + //= node->getAttribute("value")->getIntValue(); + // } + // + // // std::map prodSpeedUpgradeIsMultiplierValueList; + // vector prodSpeedUpgradeIsMultiplierValueNodeList = + // upgradeTypeBaseNode->getChildList("prodSpeedUpgradeIsMultiplierValueList"); + // for(unsigned int i = 0; i < + // prodSpeedUpgradeIsMultiplierValueNodeList.size(); ++i) { XmlNode + // *node = prodSpeedUpgradeIsMultiplierValueNodeList[i]; + // + // prodSpeedUpgradeIsMultiplierValueList[node->getAttribute("key")->getValue()] + //= node->getAttribute("value")->getIntValue(); + // } + // + // // std::map prodSpeedMorphIsMultiplierValueList; + // vector prodSpeedMorphIsMultiplierValueNodeList = + // upgradeTypeBaseNode->getChildList("prodSpeedMorphIsMultiplierValueList"); + // for(unsigned int i = 0; i < + // prodSpeedMorphIsMultiplierValueNodeList.size(); ++i) { XmlNode *node + // = prodSpeedMorphIsMultiplierValueNodeList[i]; + // + // prodSpeedMorphIsMultiplierValueList[node->getAttribute("key")->getValue()] + //= node->getAttribute("value")->getIntValue(); + // } } // ==================== misc ==================== string UpgradeType::getName(bool translatedValue) const { - if(translatedValue == false) return name; + if (translatedValue == false) + return name; - Lang &lang = Lang::getInstance(); - return lang.getTechTreeString("UpgradeTypeName_" + name,name.c_str()); + Lang &lang = Lang::getInstance(); + return lang.getTechTreeString("UpgradeTypeName_" + name, name.c_str()); } string UpgradeType::getTagName(string tag, bool translatedValue) const { - if(translatedValue == false) return tag; + if (translatedValue == false) + return tag; - Lang &lang = Lang::getInstance(); - return lang.getTechTreeString("TagName_" + tag, tag.c_str()); + Lang &lang = Lang::getInstance(); + return lang.getTechTreeString("TagName_" + tag, tag.c_str()); } -string UpgradeType::getReqDesc(bool translatedValue) const{ - Lang &lang= Lang::getInstance(); - string str= ProducibleType::getReqDesc(translatedValue); - string indent=" "; - if(!effects.empty() || !tags.empty()){ - str+= "\n"+ lang.getString("Upgrades",(translatedValue == true ? "" : "english"))+"\n"; - } - str+=UpgradeTypeBase::getDesc(translatedValue); - if(!effects.empty() || !tags.empty()){ - str+= lang.getString("AffectedUnits",(translatedValue == true ? "" : "english"))+"\n"; - - // We want the output to be sorted, so convert the set to a vector and sort that - std::vector outputUnits(effects.begin(), effects.end()); - std::sort(outputUnits.begin(), outputUnits.end(), UnitTypeSorter()); - - vector::iterator unitIter; - for (unitIter = outputUnits.begin(); unitIter != outputUnits.end(); ++unitIter) { - const UnitType *unit = *unitIter; - str+= indent+unit->getName(translatedValue)+"\n"; - } - - // Do the same for tags - std::vector outputTags(tags.begin(), tags.end()); - std::sort(outputTags.begin(), outputTags.end()); - - vector::iterator tagIter; - for (tagIter = outputTags.begin(); tagIter != outputTags.end(); ++tagIter) { - string tag = *tagIter; - str+= indent + lang.getString("TagDesc", (translatedValue == true ? "" : "english")) + - " " + getTagName(tag,translatedValue) + "\n"; - } - } - return str; -} +string UpgradeType::getReqDesc(bool translatedValue) const { + Lang &lang = Lang::getInstance(); + string str = ProducibleType::getReqDesc(translatedValue); + string indent = " "; + if (!effects.empty() || !tags.empty()) { + str += + "\n" + + lang.getString("Upgrades", (translatedValue == true ? "" : "english")) + + "\n"; + } + str += UpgradeTypeBase::getDesc(translatedValue); + if (!effects.empty() || !tags.empty()) { + str += lang.getString("AffectedUnits", + (translatedValue == true ? "" : "english")) + + "\n"; + + // We want the output to be sorted, so convert the set to a vector and sort + // that + std::vector outputUnits(effects.begin(), effects.end()); + std::sort(outputUnits.begin(), outputUnits.end(), UnitTypeSorter()); + + vector::iterator unitIter; + for (unitIter = outputUnits.begin(); unitIter != outputUnits.end(); + ++unitIter) { + const UnitType *unit = *unitIter; + str += indent + unit->getName(translatedValue) + "\n"; + } -void UpgradeType::preLoad(const string &dir){ - name=lastDir(dir); + // Do the same for tags + std::vector outputTags(tags.begin(), tags.end()); + std::sort(outputTags.begin(), outputTags.end()); + + vector::iterator tagIter; + for (tagIter = outputTags.begin(); tagIter != outputTags.end(); ++tagIter) { + string tag = *tagIter; + str += indent + + lang.getString("TagDesc", + (translatedValue == true ? "" : "english")) + + " " + getTagName(tag, translatedValue) + "\n"; + } + } + return str; } -void UpgradeType::load(const string &dir, const TechTree *techTree, - const FactionType *factionType, Checksum* checksum, - Checksum* techtreeChecksum, std::map > > &loadedFileList, - bool validationMode) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - char szBuf[8096]=""; - snprintf(szBuf,8096,Lang::getInstance().getString("LogScreenGameLoadingUpgradeType","",true).c_str(),formatString(this->getName(true)).c_str()); - Logger::getInstance().add(szBuf, true); - - string currentPath = dir; - endPathWithSlash(currentPath); - string path = currentPath + name + ".xml"; - string sourceXMLFile = path; - - try { - checksum->addFile(path); - techtreeChecksum->addFile(path); - - XmlTree xmlTree; - std::map mapExtraTagReplacementValues; - mapExtraTagReplacementValues["$COMMONDATAPATH"] = techTree->getPath() + "/commondata/"; - xmlTree.load(path, Properties::getTagReplacementValues(&mapExtraTagReplacementValues)); - loadedFileList[path].push_back(make_pair(currentPath,currentPath)); - const XmlNode *upgradeNode= xmlTree.getRootNode(); - - //image - image = NULL; // Not used for upgrade types - - //image cancel - cancelImage = NULL; // Not used for upgrade types - - //upgrade time - const XmlNode *upgradeTimeNode= upgradeNode->getChild("time"); - productionTime= upgradeTimeNode->getAttribute("value")->getIntValue(); - - std::map sortedItems; - - //unit requirements - bool hasDup = false; - const XmlNode *unitRequirementsNode= upgradeNode->getChild("unit-requirements"); - for(int i = 0; i < (int)unitRequirementsNode->getChildCount(); ++i) { - const XmlNode *unitNode= unitRequirementsNode->getChild("unit", i); - string name= unitNode->getAttribute("name")->getRestrictedValue(); - - if(sortedItems.find(name) != sortedItems.end()) { - hasDup = true; - } - - sortedItems[name] = 0; - } - - if(hasDup) { - printf("WARNING, upgrade type [%s] has one or more duplicate unit requirements\n",this->getName().c_str()); - } - - for(std::map::iterator iterMap = sortedItems.begin(); - iterMap != sortedItems.end(); ++iterMap) { - unitReqs.push_back(factionType->getUnitType(iterMap->first)); - } - sortedItems.clear(); - hasDup = false; - - //upgrade requirements - const XmlNode *upgradeRequirementsNode= upgradeNode->getChild("upgrade-requirements"); - for(int i = 0; i < (int)upgradeRequirementsNode->getChildCount(); ++i) { - const XmlNode *upgradeReqNode= upgradeRequirementsNode->getChild("upgrade", i); - string name= upgradeReqNode->getAttribute("name")->getRestrictedValue(); - - if(sortedItems.find(name) != sortedItems.end()) { - hasDup = true; - } - - sortedItems[name] = 0; - } - - if(hasDup) { - printf("WARNING, upgrade type [%s] has one or more duplicate upgrade requirements\n",this->getName().c_str()); - } - - for(std::map::iterator iterMap = sortedItems.begin(); - iterMap != sortedItems.end(); ++iterMap) { - upgradeReqs.push_back(factionType->getUpgradeType(iterMap->first)); - } - sortedItems.clear(); - hasDup = false; - - //resource requirements - int index = 0; - const XmlNode *resourceRequirementsNode= upgradeNode->getChild("resource-requirements"); - - costs.resize(resourceRequirementsNode->getChildCount()); - for(int i = 0; i < (int)costs.size(); ++i) { - const XmlNode *resourceNode= resourceRequirementsNode->getChild("resource", i); - string name= resourceNode->getAttribute("name")->getRestrictedValue(); - int amount= resourceNode->getAttribute("amount")->getIntValue(); - - if(sortedItems.find(name) != sortedItems.end()) { - hasDup = true; - } - - sortedItems[name] = amount; - } - - //if(hasDup || sortedItems.size() != costs.size()) printf("Found duplicate resource requirement, costs.size() = %d sortedItems.size() = %d\n",costs.size(),sortedItems.size()); - - if(hasDup) { - printf("WARNING, upgrade type [%s] has one or more duplicate resource requirements\n",this->getName().c_str()); - } - - if(sortedItems.size() < costs.size()) { - costs.resize(sortedItems.size()); - } - - index = 0; - for(std::map::iterator iterMap = sortedItems.begin(); - iterMap != sortedItems.end(); ++iterMap) { - try { - costs[index].init(techTree->getResourceType(iterMap->first), iterMap->second); - index++; - } - catch(megaglest_runtime_error& ex) { - if(validationMode == false) { - throw; - } - else { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\nFor UpgradeType: %s Cost: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what(),name.c_str(),iterMap->second); - } - } - - } - sortedItems.clear(); - //hasDup = false; - - //effects -- get list of affected units - const XmlNode *effectsNode= upgradeNode->getChild("effects"); - vector unitNodes= effectsNode->getChildList("unit"); - for(size_t i = 0; i < unitNodes.size(); ++i) { - const XmlNode *unitNode= unitNodes.at(i); - string name= unitNode->getAttribute("name")->getRestrictedValue(); - - effects.insert(factionType->getUnitType(name)); - } - - //effects -- convert tags into units - vector tagNodes= effectsNode->getChildList("tag"); - for(size_t i = 0; i < tagNodes.size(); ++i) { - const XmlNode *tagNode= tagNodes.at(i); - string name= tagNode->getAttribute("name")->getRestrictedValue(); - tags.insert(name); - } - - //values - UpgradeTypeBase::load(upgradeNode,name); - } - catch(megaglest_runtime_error& ex) { - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); - throw megaglest_runtime_error("Error loading UpgradeType: "+ currentPath + "\nMessage: " + ex.what(),!ex.wantStackTrace() ); - } - catch(const exception &e){ - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,e.what()); - throw megaglest_runtime_error("Error loading UpgradeType: "+ currentPath + "\n" +e.what()); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); +void UpgradeType::preLoad(const string &dir) { name = lastDir(dir); } + +void UpgradeType::load( + const string &dir, const TechTree *techTree, const FactionType *factionType, + Checksum *checksum, Checksum *techtreeChecksum, + std::map>> &loadedFileList, + bool validationMode) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + Lang::getInstance() + .getString("LogScreenGameLoadingUpgradeType", "", true) + .c_str(), + formatString(this->getName(true)).c_str()); + Logger::getInstance().add(szBuf, true); + + string currentPath = dir; + endPathWithSlash(currentPath); + string path = currentPath + name + ".xml"; + string sourceXMLFile = path; + + try { + checksum->addFile(path); + techtreeChecksum->addFile(path); + + XmlTree xmlTree; + std::map mapExtraTagReplacementValues; + mapExtraTagReplacementValues["$COMMONDATAPATH"] = + techTree->getPath() + "/commondata/"; + xmlTree.load(path, Properties::getTagReplacementValues( + &mapExtraTagReplacementValues)); + loadedFileList[path].push_back(make_pair(currentPath, currentPath)); + const XmlNode *upgradeNode = xmlTree.getRootNode(); + + // image + image = NULL; // Not used for upgrade types + + // image cancel + cancelImage = NULL; // Not used for upgrade types + + // upgrade time + const XmlNode *upgradeTimeNode = upgradeNode->getChild("time"); + productionTime = upgradeTimeNode->getAttribute("value")->getIntValue(); + + std::map sortedItems; + + // unit requirements + bool hasDup = false; + const XmlNode *unitRequirementsNode = + upgradeNode->getChild("unit-requirements"); + for (int i = 0; i < (int)unitRequirementsNode->getChildCount(); ++i) { + const XmlNode *unitNode = unitRequirementsNode->getChild("unit", i); + string name = unitNode->getAttribute("name")->getRestrictedValue(); + + if (sortedItems.find(name) != sortedItems.end()) { + hasDup = true; + } + + sortedItems[name] = 0; + } + + if (hasDup) { + printf("WARNING, upgrade type [%s] has one or more duplicate unit " + "requirements\n", + this->getName().c_str()); + } + + for (std::map::iterator iterMap = sortedItems.begin(); + iterMap != sortedItems.end(); ++iterMap) { + unitReqs.push_back(factionType->getUnitType(iterMap->first)); + } + sortedItems.clear(); + hasDup = false; + + // upgrade requirements + const XmlNode *upgradeRequirementsNode = + upgradeNode->getChild("upgrade-requirements"); + for (int i = 0; i < (int)upgradeRequirementsNode->getChildCount(); ++i) { + const XmlNode *upgradeReqNode = + upgradeRequirementsNode->getChild("upgrade", i); + string name = upgradeReqNode->getAttribute("name")->getRestrictedValue(); + + if (sortedItems.find(name) != sortedItems.end()) { + hasDup = true; + } + + sortedItems[name] = 0; + } + + if (hasDup) { + printf("WARNING, upgrade type [%s] has one or more duplicate upgrade " + "requirements\n", + this->getName().c_str()); + } + + for (std::map::iterator iterMap = sortedItems.begin(); + iterMap != sortedItems.end(); ++iterMap) { + upgradeReqs.push_back(factionType->getUpgradeType(iterMap->first)); + } + sortedItems.clear(); + hasDup = false; + + // resource requirements + int index = 0; + const XmlNode *resourceRequirementsNode = + upgradeNode->getChild("resource-requirements"); + + costs.resize(resourceRequirementsNode->getChildCount()); + for (int i = 0; i < (int)costs.size(); ++i) { + const XmlNode *resourceNode = + resourceRequirementsNode->getChild("resource", i); + string name = resourceNode->getAttribute("name")->getRestrictedValue(); + int amount = resourceNode->getAttribute("amount")->getIntValue(); + + if (sortedItems.find(name) != sortedItems.end()) { + hasDup = true; + } + + sortedItems[name] = amount; + } + + // if(hasDup || sortedItems.size() != costs.size()) printf("Found duplicate + // resource requirement, costs.size() = %d sortedItems.size() = + // %d\n",costs.size(),sortedItems.size()); + + if (hasDup) { + printf("WARNING, upgrade type [%s] has one or more duplicate resource " + "requirements\n", + this->getName().c_str()); + } + + if (sortedItems.size() < costs.size()) { + costs.resize(sortedItems.size()); + } + + index = 0; + for (std::map::iterator iterMap = sortedItems.begin(); + iterMap != sortedItems.end(); ++iterMap) { + try { + costs[index].init(techTree->getResourceType(iterMap->first), + iterMap->second); + index++; + } catch (megaglest_runtime_error &ex) { + if (validationMode == false) { + throw; + } else { + SystemFlags::OutputDebug( + SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\nFor UpgradeType: %s Cost: %d\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, ex.what(), name.c_str(), iterMap->second); + } + } + } + sortedItems.clear(); + // hasDup = false; + + // effects -- get list of affected units + const XmlNode *effectsNode = upgradeNode->getChild("effects"); + vector unitNodes = effectsNode->getChildList("unit"); + for (size_t i = 0; i < unitNodes.size(); ++i) { + const XmlNode *unitNode = unitNodes.at(i); + string name = unitNode->getAttribute("name")->getRestrictedValue(); + + effects.insert(factionType->getUnitType(name)); + } + + // effects -- convert tags into units + vector tagNodes = effectsNode->getChildList("tag"); + for (size_t i = 0; i < tagNodes.size(); ++i) { + const XmlNode *tagNode = tagNodes.at(i); + string name = tagNode->getAttribute("name")->getRestrictedValue(); + tags.insert(name); + } + + // values + UpgradeTypeBase::load(upgradeNode, name); + } catch (megaglest_runtime_error &ex) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), + __FUNCTION__, __LINE__, ex.what()); + throw megaglest_runtime_error("Error loading UpgradeType: " + currentPath + + "\nMessage: " + ex.what(), + !ex.wantStackTrace()); + } catch (const exception &e) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", __FILE__, + __FUNCTION__, __LINE__, e.what()); + throw megaglest_runtime_error("Error loading UpgradeType: " + currentPath + + "\n" + e.what()); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); } -bool UpgradeType::isAffected(const UnitType *unitType) const{ - if(std::find(effects.begin(), effects.end(), unitType)!=effects.end()) return true; +bool UpgradeType::isAffected(const UnitType *unitType) const { + if (std::find(effects.begin(), effects.end(), unitType) != effects.end()) + return true; - const set unitTags = unitType->getTags(); - set intersect; - set_intersection(tags.begin(),tags.end(),unitTags.begin(),unitTags.end(), - std::inserter(intersect,intersect.begin())); - if(!intersect.empty()) return true; + const set unitTags = unitType->getTags(); + set intersect; + set_intersection(tags.begin(), tags.end(), unitTags.begin(), unitTags.end(), + std::inserter(intersect, intersect.begin())); + if (!intersect.empty()) + return true; - return false; + return false; } -//void UpgradeType::saveGame(XmlNode *rootNode) const { +// void UpgradeType::saveGame(XmlNode *rootNode) const { // UpgradeTypeBase::saveGame(rootNode); // ProducibleType::saveGame(rootNode); // // std::map mapTagReplacements; // XmlNode *upgradeTypeNode = rootNode->addChild("UpgradeType"); // -// //upgradeTypeNode->addAttribute("maxHp",intToStr(maxHp), mapTagReplacements); +// //upgradeTypeNode->addAttribute("maxHp",intToStr(maxHp), +// mapTagReplacements); // //vector effects; // for(unsigned int i = 0; i < effects.size(); ++i) { // XmlNode *unitTypeNode = rootNode->addChild("UnitType"); // // const UnitType *ut = effects[i]; -// unitTypeNode->addAttribute("name",ut->getName(), mapTagReplacements); +// unitTypeNode->addAttribute("name",ut->getName(), +// mapTagReplacements); // } -//} +// } // -//void UpgradeType::loadGame(const XmlNode *rootNode, Faction *faction) { +// void UpgradeType::loadGame(const XmlNode *rootNode, Faction *faction) { // //UpgradeTypeBase::loadGame(rootNode); // //ProducibleType::loadGame(rootNode); // @@ -1106,741 +1377,837 @@ bool UpgradeType::isAffected(const UnitType *unitType) const{ // // //maxHp = upgradeTypeNode->getAttribute("maxHp")->getIntValue(); // -//// vector unitTypeNodeList = upgradeTypeNode->getChildList("UnitType"); -//// for(unsigned int i = 0; i < unitTypeNodeList.size(); ++i) { -//// XmlNode *node = unitTypeNodeList[i]; -//// } +//// vector unitTypeNodeList = +/// upgradeTypeNode->getChildList("UnitType"); / for(unsigned int i = 0; i +/// < unitTypeNodeList.size(); ++i) { / XmlNode *node = +/// unitTypeNodeList[i]; / } //} // =============================== // class TotalUpgrade // =============================== -TotalUpgrade::TotalUpgrade() { - reset(); -} +TotalUpgrade::TotalUpgrade() { reset(); } void TotalUpgrade::reset() { - maxHp= 0; - maxHpIsMultiplier=false; - maxHpRegeneration = 0; + maxHp = 0; + maxHpIsMultiplier = false; + maxHpRegeneration = 0; - maxEp= 0; - maxEpIsMultiplier = false; - maxEpRegeneration = 0; + maxEp = 0; + maxEpIsMultiplier = false; + maxEpRegeneration = 0; - sight=0; - sightIsMultiplier=false; + sight = 0; + sightIsMultiplier = false; - armor= 0; - armorIsMultiplier=false; + armor = 0; + armorIsMultiplier = false; - attackStrength= 0; - attackStrengthIsMultiplier=false; + attackStrength = 0; + attackStrengthIsMultiplier = false; - attackRange= 0; - attackRangeIsMultiplier=false; + attackRange = 0; + attackRangeIsMultiplier = false; - moveSpeed= 0; - moveSpeedIsMultiplier=false; + moveSpeed = 0; + moveSpeedIsMultiplier = false; - prodSpeed=0; - prodSpeedIsMultiplier=false; + prodSpeed = 0; + prodSpeedIsMultiplier = false; - attackSpeed=0; - attackSpeedIsMultiplier=false; + attackSpeed = 0; + attackSpeedIsMultiplier = false; - boostUpgradeBase = NULL; - boostUpgradeSourceUnit = -1; - boostUpgradeDestUnit = -1; + boostUpgradeBase = NULL; + boostUpgradeSourceUnit = -1; + boostUpgradeDestUnit = -1; - attackStrengthMultiplierValueList.clear(); - moveSpeedIsMultiplierValueList.clear(); - prodSpeedProduceIsMultiplierValueList.clear(); - prodSpeedUpgradeIsMultiplierValueList.clear(); - prodSpeedMorphIsMultiplierValueList.clear(); - attackSpeedIsMultiplierValueList.clear(); + attackStrengthMultiplierValueList.clear(); + moveSpeedIsMultiplierValueList.clear(); + prodSpeedProduceIsMultiplierValueList.clear(); + prodSpeedUpgradeIsMultiplierValueList.clear(); + prodSpeedMorphIsMultiplierValueList.clear(); + attackSpeedIsMultiplierValueList.clear(); } -void TotalUpgrade::sum(const UpgradeTypeBase *ut, const Unit *unit, bool boostMode) { - maxHpIsMultiplier = ut->getMaxHpIsMultiplier(); - sightIsMultiplier = ut->getSightIsMultiplier(); - maxEpIsMultiplier = ut->getMaxEpIsMultiplier(); - armorIsMultiplier = ut->getArmorIsMultiplier(); - attackStrengthIsMultiplier = ut->getAttackStrengthIsMultiplier(); - attackRangeIsMultiplier = ut->getAttackRangeIsMultiplier(); - moveSpeedIsMultiplier = ut->getMoveSpeedIsMultiplier(); - prodSpeedIsMultiplier = ut->getProdSpeedIsMultiplier(); - attackSpeedIsMultiplier = ut->getAttackSpeedIsMultiplier(); - - - { - int upgradeValue; - if (ut->getMaxHpIsMultiplier() == true) { - upgradeValue = ((double) unit->getType()->getMaxHp() * ((double) ut->getMaxHp() / (double) 100)); - } else { - upgradeValue = ut->getMaxHp(); - } - if (boostMode) { - //no boost for MaxHP. This makes no sense. Just upgrades allowed. - maxHp=0; - } else { - maxHp += upgradeValue; - } - } - - { - int upgradeValue; - if (ut->getMaxEpIsMultiplier() == true) { - upgradeValue = ((double) unit->getType()->getHpRegeneration() * ((double) ut->getMaxHpRegeneration() / (double) 100)); - } else { - upgradeValue = ut->getMaxHpRegeneration(); - } - if (boostMode) { - //ignore! no boost for MaxEP. This makes no sense. Just upgrades allowed - maxHpRegeneration=upgradeValue; - } else { - maxHpRegeneration += upgradeValue; - } - } - - { - int upgradeValue; - if (ut->getMaxEpIsMultiplier() == true) { - upgradeValue = ((double) unit->getType()->getMaxEp() * ((double) ut->getMaxEp() / (double) 100)); - } else { - upgradeValue = ut->getMaxEp(); - } - if (boostMode) { - //ignore! no boost for MaxEP. This makes no sense. Just upgrades allowed - maxEp=0; - } else { - maxEp += upgradeValue; - } - } - - { - int upgradeValue; - if (ut->getMaxEpIsMultiplier() == true) { - upgradeValue = ((double) unit->getType()->getEpRegeneration() * ((double) ut->getMaxEpRegeneration() / (double) 100)); - } else { - upgradeValue = ut->getMaxEpRegeneration(); - } - if (boostMode) { - //ignore! no boost for MaxEP. This makes no sense. Just upgrades allowed - maxEpRegeneration=upgradeValue; - } else { - maxEpRegeneration += upgradeValue; - } - } - - { - int upgradeValue; - if (ut->getSightIsMultiplier() == true) { - upgradeValue = ((double) unit->getType()->getSight() * ((double) ut->getSight() / (double) 100)); - } else { - upgradeValue = ut->getSight(); - } - if (boostMode) { - sight = upgradeValue; - } else { - sight += upgradeValue; - } - } - - { - int upgradeValue; - if (ut->getArmorIsMultiplier() == true) { - upgradeValue = ((double) unit->getType()->getArmor() * ((double) ut->getArmor() / (double) 100)); - } else { - upgradeValue = ut->getArmor(); - } - if (boostMode) { - armor = upgradeValue; - } else { - armor += upgradeValue; - } - } - - for(unsigned int i = 0; i < (unsigned int)unit->getType()->getSkillTypeCount(); ++i) { - const SkillType *skillType = unit->getType()->getSkillType(i); - const AttackSkillType *ast = dynamic_cast(skillType); - if(ast != NULL) { - int newValue; - if(ut->getAttackStrengthIsMultiplier() == true){ - newValue = ((double)ast->getAttackStrength() * ((double)ut->getAttackStrength(NULL) / (double)100)); - } - else { - newValue = ut->getAttackStrength(NULL); - } - if(boostMode) { - attackStrengthMultiplierValueList[ast->getName()] = newValue; - } - else { - attackStrengthMultiplierValueList[ast->getName()] += newValue; - } - } - } - - - for(unsigned int i = 0; i < (unsigned int)unit->getType()->getSkillTypeCount(); ++i) { - const SkillType *skillType = unit->getType()->getSkillType(i); - const AttackSkillType *ast = dynamic_cast(skillType); - if (ast != NULL) { - int newValue; - if (ut->getAttackRangeIsMultiplier() == true) { - newValue = ((double) ast->getAttackRange() * ((double) ut->getAttackRange(NULL) / (double) 100)); - } else { - newValue = ut->getAttackRange(NULL); - } - if (boostMode) { - attackRangeMultiplierValueList[ast->getName()] = newValue; - } else { - attackRangeMultiplierValueList[ast->getName()] += newValue; - } - } - } - - - for(unsigned int i = 0; i < (unsigned int)unit->getType()->getSkillTypeCount(); ++i) { - const SkillType *skillType = unit->getType()->getSkillType(i); - const MoveSkillType *mst = dynamic_cast(skillType); - if(mst != NULL) { - int newValue; - if(ut->getMoveSpeedIsMultiplier() == true) { - newValue = ((double)mst->getSpeed() * ((double)ut->getMoveSpeed(NULL) / (double)100)); - } - else { - newValue = ut->getMoveSpeed(NULL); - } - if(boostMode) { - moveSpeedIsMultiplierValueList[mst->getName()] = newValue; - } - else { - moveSpeedIsMultiplierValueList[mst->getName()] += newValue; - } - } - } - - - - - for(unsigned int i = 0; i < (unsigned int)unit->getType()->getSkillTypeCount(); ++i) { - const SkillType *skillType = unit->getType()->getSkillType(i); - const ProduceSkillType *pst = dynamic_cast(skillType); - if(pst != NULL) { - int newValue; - if(ut->getProdSpeedIsMultiplier() == true) { - newValue = ((double)pst->getSpeed() * ((double)ut->getProdSpeed(NULL) / (double)100)); - } - else { - newValue = ut->getProdSpeed(NULL); - } - if(boostMode) { - prodSpeedProduceIsMultiplierValueList[pst->getName()] = newValue; - } - else { - prodSpeedProduceIsMultiplierValueList[pst->getName()] += newValue; - } - } - const UpgradeSkillType *ust = dynamic_cast(skillType); - if(ust != NULL) { - int newValue; - if(ut->getProdSpeedIsMultiplier() == true) { - newValue = ((double)ust->getSpeed() * ((double)ut->getProdSpeed(NULL) / (double)100)); - } - else { - newValue = ut->getProdSpeed(NULL); - } if(boostMode) { - prodSpeedUpgradeIsMultiplierValueList[ust->getName()] = newValue; - } - else { - prodSpeedUpgradeIsMultiplierValueList[ust->getName()] += newValue; - } - } - const MorphSkillType *mst = dynamic_cast(skillType); - if(mst != NULL) { - int newValue; - if(ut->getProdSpeedIsMultiplier() == true) { - newValue = ((double)mst->getSpeed() * ((double)ut->getProdSpeed(NULL) / (double)100)); - } - else { - newValue = ut->getProdSpeed(NULL); - } - if(boostMode) { - prodSpeedMorphIsMultiplierValueList[mst->getName()] = newValue; - } - else { - prodSpeedMorphIsMultiplierValueList[mst->getName()] += newValue; - } - } - } - - if(ut->getAttackSpeedIsMultiplier() == true) { - for(unsigned int i = 0; i < (unsigned int)unit->getType()->getSkillTypeCount(); ++i) { - const SkillType *skillType = unit->getType()->getSkillType(i); - const AttackSkillType *ast = dynamic_cast(skillType); - if(ast != NULL) { - int newValue = ((double)ast->getSpeed() * ((double)ut->getAttackSpeed(NULL) / (double)100)); - if(boostMode) { - attackSpeedIsMultiplierValueList[ast->getName()] = newValue; - } - else { - attackSpeedIsMultiplierValueList[ast->getName()] += newValue; - } - } - } - } - else { - int newValue = ut->getAttackSpeed(NULL); - if(boostMode) { - attackSpeed = newValue; - } - else { - attackSpeed += newValue; - } - } +void TotalUpgrade::sum(const UpgradeTypeBase *ut, const Unit *unit, + bool boostMode) { + maxHpIsMultiplier = ut->getMaxHpIsMultiplier(); + sightIsMultiplier = ut->getSightIsMultiplier(); + maxEpIsMultiplier = ut->getMaxEpIsMultiplier(); + armorIsMultiplier = ut->getArmorIsMultiplier(); + attackStrengthIsMultiplier = ut->getAttackStrengthIsMultiplier(); + attackRangeIsMultiplier = ut->getAttackRangeIsMultiplier(); + moveSpeedIsMultiplier = ut->getMoveSpeedIsMultiplier(); + prodSpeedIsMultiplier = ut->getProdSpeedIsMultiplier(); + attackSpeedIsMultiplier = ut->getAttackSpeedIsMultiplier(); + + { + int upgradeValue; + if (ut->getMaxHpIsMultiplier() == true) { + upgradeValue = ((double)unit->getType()->getMaxHp() * + ((double)ut->getMaxHp() / (double)100)); + } else { + upgradeValue = ut->getMaxHp(); + } + if (boostMode) { + // no boost for MaxHP. This makes no sense. Just upgrades allowed. + maxHp = 0; + } else { + maxHp += upgradeValue; + } + } + + { + int upgradeValue; + if (ut->getMaxEpIsMultiplier() == true) { + upgradeValue = ((double)unit->getType()->getHpRegeneration() * + ((double)ut->getMaxHpRegeneration() / (double)100)); + } else { + upgradeValue = ut->getMaxHpRegeneration(); + } + if (boostMode) { + // ignore! no boost for MaxEP. This makes no sense. Just upgrades allowed + maxHpRegeneration = upgradeValue; + } else { + maxHpRegeneration += upgradeValue; + } + } + + { + int upgradeValue; + if (ut->getMaxEpIsMultiplier() == true) { + upgradeValue = ((double)unit->getType()->getMaxEp() * + ((double)ut->getMaxEp() / (double)100)); + } else { + upgradeValue = ut->getMaxEp(); + } + if (boostMode) { + // ignore! no boost for MaxEP. This makes no sense. Just upgrades allowed + maxEp = 0; + } else { + maxEp += upgradeValue; + } + } + + { + int upgradeValue; + if (ut->getMaxEpIsMultiplier() == true) { + upgradeValue = ((double)unit->getType()->getEpRegeneration() * + ((double)ut->getMaxEpRegeneration() / (double)100)); + } else { + upgradeValue = ut->getMaxEpRegeneration(); + } + if (boostMode) { + // ignore! no boost for MaxEP. This makes no sense. Just upgrades allowed + maxEpRegeneration = upgradeValue; + } else { + maxEpRegeneration += upgradeValue; + } + } + + { + int upgradeValue; + if (ut->getSightIsMultiplier() == true) { + upgradeValue = ((double)unit->getType()->getSight() * + ((double)ut->getSight() / (double)100)); + } else { + upgradeValue = ut->getSight(); + } + if (boostMode) { + sight = upgradeValue; + } else { + sight += upgradeValue; + } + } + + { + int upgradeValue; + if (ut->getArmorIsMultiplier() == true) { + upgradeValue = ((double)unit->getType()->getArmor() * + ((double)ut->getArmor() / (double)100)); + } else { + upgradeValue = ut->getArmor(); + } + if (boostMode) { + armor = upgradeValue; + } else { + armor += upgradeValue; + } + } + + for (unsigned int i = 0; + i < (unsigned int)unit->getType()->getSkillTypeCount(); ++i) { + const SkillType *skillType = unit->getType()->getSkillType(i); + const AttackSkillType *ast = + dynamic_cast(skillType); + if (ast != NULL) { + int newValue; + if (ut->getAttackStrengthIsMultiplier() == true) { + newValue = ((double)ast->getAttackStrength() * + ((double)ut->getAttackStrength(NULL) / (double)100)); + } else { + newValue = ut->getAttackStrength(NULL); + } + if (boostMode) { + attackStrengthMultiplierValueList[ast->getName()] = newValue; + } else { + attackStrengthMultiplierValueList[ast->getName()] += newValue; + } + } + } + + for (unsigned int i = 0; + i < (unsigned int)unit->getType()->getSkillTypeCount(); ++i) { + const SkillType *skillType = unit->getType()->getSkillType(i); + const AttackSkillType *ast = + dynamic_cast(skillType); + if (ast != NULL) { + int newValue; + if (ut->getAttackRangeIsMultiplier() == true) { + newValue = ((double)ast->getAttackRange() * + ((double)ut->getAttackRange(NULL) / (double)100)); + } else { + newValue = ut->getAttackRange(NULL); + } + if (boostMode) { + attackRangeMultiplierValueList[ast->getName()] = newValue; + } else { + attackRangeMultiplierValueList[ast->getName()] += newValue; + } + } + } + + for (unsigned int i = 0; + i < (unsigned int)unit->getType()->getSkillTypeCount(); ++i) { + const SkillType *skillType = unit->getType()->getSkillType(i); + const MoveSkillType *mst = dynamic_cast(skillType); + if (mst != NULL) { + int newValue; + if (ut->getMoveSpeedIsMultiplier() == true) { + newValue = ((double)mst->getSpeed() * + ((double)ut->getMoveSpeed(NULL) / (double)100)); + } else { + newValue = ut->getMoveSpeed(NULL); + } + if (boostMode) { + moveSpeedIsMultiplierValueList[mst->getName()] = newValue; + } else { + moveSpeedIsMultiplierValueList[mst->getName()] += newValue; + } + } + } + + for (unsigned int i = 0; + i < (unsigned int)unit->getType()->getSkillTypeCount(); ++i) { + const SkillType *skillType = unit->getType()->getSkillType(i); + const ProduceSkillType *pst = + dynamic_cast(skillType); + if (pst != NULL) { + int newValue; + if (ut->getProdSpeedIsMultiplier() == true) { + newValue = ((double)pst->getSpeed() * + ((double)ut->getProdSpeed(NULL) / (double)100)); + } else { + newValue = ut->getProdSpeed(NULL); + } + if (boostMode) { + prodSpeedProduceIsMultiplierValueList[pst->getName()] = newValue; + } else { + prodSpeedProduceIsMultiplierValueList[pst->getName()] += newValue; + } + } + const UpgradeSkillType *ust = + dynamic_cast(skillType); + if (ust != NULL) { + int newValue; + if (ut->getProdSpeedIsMultiplier() == true) { + newValue = ((double)ust->getSpeed() * + ((double)ut->getProdSpeed(NULL) / (double)100)); + } else { + newValue = ut->getProdSpeed(NULL); + } + if (boostMode) { + prodSpeedUpgradeIsMultiplierValueList[ust->getName()] = newValue; + } else { + prodSpeedUpgradeIsMultiplierValueList[ust->getName()] += newValue; + } + } + const MorphSkillType *mst = dynamic_cast(skillType); + if (mst != NULL) { + int newValue; + if (ut->getProdSpeedIsMultiplier() == true) { + newValue = ((double)mst->getSpeed() * + ((double)ut->getProdSpeed(NULL) / (double)100)); + } else { + newValue = ut->getProdSpeed(NULL); + } + if (boostMode) { + prodSpeedMorphIsMultiplierValueList[mst->getName()] = newValue; + } else { + prodSpeedMorphIsMultiplierValueList[mst->getName()] += newValue; + } + } + } + + if (ut->getAttackSpeedIsMultiplier() == true) { + for (unsigned int i = 0; + i < (unsigned int)unit->getType()->getSkillTypeCount(); ++i) { + const SkillType *skillType = unit->getType()->getSkillType(i); + const AttackSkillType *ast = + dynamic_cast(skillType); + if (ast != NULL) { + int newValue = ((double)ast->getSpeed() * + ((double)ut->getAttackSpeed(NULL) / (double)100)); + if (boostMode) { + attackSpeedIsMultiplierValueList[ast->getName()] = newValue; + } else { + attackSpeedIsMultiplierValueList[ast->getName()] += newValue; + } + } + } + } else { + int newValue = ut->getAttackSpeed(NULL); + if (boostMode) { + attackSpeed = newValue; + } else { + attackSpeed += newValue; + } + } } -void TotalUpgrade::apply(int sourceUnitId, const UpgradeTypeBase *ut, const Unit *unit) { - //sum(ut, unit); +void TotalUpgrade::apply(int sourceUnitId, const UpgradeTypeBase *ut, + const Unit *unit) { + // sum(ut, unit); - //printf("====> About to apply boost: %s\nTo unit: %d\n\n",ut->toString().c_str(),unit->getId()); - TotalUpgrade *boostUpgrade = new TotalUpgrade(); - boostUpgrade->copyDataFrom(this); - boostUpgrade->boostUpgradeBase = ut; - boostUpgrade->boostUpgradeSourceUnit = sourceUnitId; - boostUpgrade->boostUpgradeDestUnit = unit->getId(); + // printf("====> About to apply boost: %s\nTo unit: + // %d\n\n",ut->toString().c_str(),unit->getId()); + TotalUpgrade *boostUpgrade = new TotalUpgrade(); + boostUpgrade->copyDataFrom(this); + boostUpgrade->boostUpgradeBase = ut; + boostUpgrade->boostUpgradeSourceUnit = sourceUnitId; + boostUpgrade->boostUpgradeDestUnit = unit->getId(); - boostUpgrade->sum(ut,unit, true); - boostUpgrades.push_back(boostUpgrade); + boostUpgrade->sum(ut, unit, true); + boostUpgrades.push_back(boostUpgrade); } -void TotalUpgrade::deapply(int sourceUnitId, const UpgradeTypeBase *ut,int destUnitId) { - //printf("<****** About to de-apply boost: %s\nTo unit: %d\n\n",ut->toString().c_str(),destUnitId); - - bool removedBoost = false; - for(unsigned int index = 0; index < boostUpgrades.size(); ++index) { - TotalUpgrade *boost = boostUpgrades[index]; - if(boost->boostUpgradeSourceUnit == sourceUnitId && - boost->boostUpgradeBase->getUpgradeName() == ut->getUpgradeName() && - boost->boostUpgradeDestUnit == destUnitId) { - - boostUpgrades.erase(boostUpgrades.begin() + index); - delete boost; - removedBoost = true; - - //printf("de-apply boost FOUND!\n"); - break; - } - } - if(removedBoost == false) { - printf("\n\n!!!!!! de-apply boost NOT FOUND for sourceUnitId = %d, destUnitId = %d\n%s\n\nCurrent Boosts:\n", - sourceUnitId,destUnitId,ut->toString().c_str()); - for(unsigned int index = 0; index < boostUpgrades.size(); ++index) { - TotalUpgrade *boost = boostUpgrades[index]; - printf("\nBoost #%u\n%s\n",index,boost->toString().c_str()); - } - } -} +void TotalUpgrade::deapply(int sourceUnitId, const UpgradeTypeBase *ut, + int destUnitId) { + // printf("<****** About to de-apply boost: %s\nTo unit: + // %d\n\n",ut->toString().c_str(),destUnitId); + + bool removedBoost = false; + for (unsigned int index = 0; index < boostUpgrades.size(); ++index) { + TotalUpgrade *boost = boostUpgrades[index]; + if (boost->boostUpgradeSourceUnit == sourceUnitId && + boost->boostUpgradeBase->getUpgradeName() == ut->getUpgradeName() && + boost->boostUpgradeDestUnit == destUnitId) { -int TotalUpgrade::getMaxHp() const { - return maxHp + getMaxHpFromBoosts(); + boostUpgrades.erase(boostUpgrades.begin() + index); + delete boost; + removedBoost = true; + + // printf("de-apply boost FOUND!\n"); + break; + } + } + if (removedBoost == false) { + printf("\n\n!!!!!! de-apply boost NOT FOUND for sourceUnitId = %d, " + "destUnitId = %d\n%s\n\nCurrent Boosts:\n", + sourceUnitId, destUnitId, ut->toString().c_str()); + for (unsigned int index = 0; index < boostUpgrades.size(); ++index) { + TotalUpgrade *boost = boostUpgrades[index]; + printf("\nBoost #%u\n%s\n", index, boost->toString().c_str()); + } + } } + +int TotalUpgrade::getMaxHp() const { return maxHp + getMaxHpFromBoosts(); } int TotalUpgrade::getMaxHpFromBoosts() const { - int result = 0; - for(unsigned int index = 0; index < boostUpgrades.size(); ++index) { - TotalUpgrade *boost = boostUpgrades[index]; - result += boost->getMaxHp(); - } - return result; + int result = 0; + for (unsigned int index = 0; index < boostUpgrades.size(); ++index) { + TotalUpgrade *boost = boostUpgrades[index]; + result += boost->getMaxHp(); + } + return result; } int TotalUpgrade::getMaxHpRegeneration() const { - return maxHpRegeneration + getMaxHpRegenerationFromBoosts(); + return maxHpRegeneration + getMaxHpRegenerationFromBoosts(); } int TotalUpgrade::getMaxHpRegenerationFromBoosts() const { - int result = 0; - for(unsigned int index = 0; index < boostUpgrades.size(); ++index) { - TotalUpgrade *boost = boostUpgrades[index]; - result += boost->getMaxHpRegeneration(); - } - return result; -} -int TotalUpgrade::getSight() const { - return sight + getSightFromBoosts(); + int result = 0; + for (unsigned int index = 0; index < boostUpgrades.size(); ++index) { + TotalUpgrade *boost = boostUpgrades[index]; + result += boost->getMaxHpRegeneration(); + } + return result; } +int TotalUpgrade::getSight() const { return sight + getSightFromBoosts(); } int TotalUpgrade::getSightFromBoosts() const { - int result = 0; - for(unsigned int index = 0; index < boostUpgrades.size(); ++index) { - TotalUpgrade *boost = boostUpgrades[index]; - result += boost->getSight(); - } - return result; -} -int TotalUpgrade::getMaxEp() const { - return maxEp + getMaxEpFromBoosts(); + int result = 0; + for (unsigned int index = 0; index < boostUpgrades.size(); ++index) { + TotalUpgrade *boost = boostUpgrades[index]; + result += boost->getSight(); + } + return result; } +int TotalUpgrade::getMaxEp() const { return maxEp + getMaxEpFromBoosts(); } int TotalUpgrade::getMaxEpFromBoosts() const { - int result = 0; - for(unsigned int index = 0; index < boostUpgrades.size(); ++index) { - TotalUpgrade *boost = boostUpgrades[index]; - result += boost->getMaxEp(); - } - return result; + int result = 0; + for (unsigned int index = 0; index < boostUpgrades.size(); ++index) { + TotalUpgrade *boost = boostUpgrades[index]; + result += boost->getMaxEp(); + } + return result; } int TotalUpgrade::getMaxEpRegeneration() const { - return maxEpRegeneration + getMaxEpRegenerationFromBoosts(); + return maxEpRegeneration + getMaxEpRegenerationFromBoosts(); } int TotalUpgrade::getMaxEpRegenerationFromBoosts() const { - int result = 0; - for(unsigned int index = 0; index < boostUpgrades.size(); ++index) { - TotalUpgrade *boost = boostUpgrades[index]; - result += boost->getMaxEpRegeneration(); - } - return result; + int result = 0; + for (unsigned int index = 0; index < boostUpgrades.size(); ++index) { + TotalUpgrade *boost = boostUpgrades[index]; + result += boost->getMaxEpRegeneration(); + } + return result; } -int TotalUpgrade::getArmor() const { - return armor + getArmorFromBoosts(); -} +int TotalUpgrade::getArmor() const { return armor + getArmorFromBoosts(); } int TotalUpgrade::getArmorFromBoosts() const { - int result = 0; - for(unsigned int index = 0; index < boostUpgrades.size(); ++index) { - TotalUpgrade *boost = boostUpgrades[index]; - result += boost->getArmor(); - } - return result; + int result = 0; + for (unsigned int index = 0; index < boostUpgrades.size(); ++index) { + TotalUpgrade *boost = boostUpgrades[index]; + result += boost->getArmor(); + } + return result; } int TotalUpgrade::getAttackStrength(const AttackSkillType *st) const { - return UpgradeTypeBase::getAttackStrength(st) + getAttackStrengthFromBoosts(st); + return UpgradeTypeBase::getAttackStrength(st) + + getAttackStrengthFromBoosts(st); } int TotalUpgrade::getAttackStrengthFromBoosts(const AttackSkillType *st) const { - int result = 0; - for(unsigned int index = 0; index < boostUpgrades.size(); ++index) { - TotalUpgrade *boost = boostUpgrades[index]; - result += boost->getAttackStrength(st); - } - return result; + int result = 0; + for (unsigned int index = 0; index < boostUpgrades.size(); ++index) { + TotalUpgrade *boost = boostUpgrades[index]; + result += boost->getAttackStrength(st); + } + return result; } int TotalUpgrade::getAttackRange(const AttackSkillType *st) const { - return UpgradeTypeBase::getAttackRange(st) + getAttackRangeFromBoosts(st); + return UpgradeTypeBase::getAttackRange(st) + getAttackRangeFromBoosts(st); } int TotalUpgrade::getAttackRangeFromBoosts(const AttackSkillType *st) const { - int result = 0; - for(unsigned int index = 0; index < boostUpgrades.size(); ++index) { - TotalUpgrade *boost = boostUpgrades[index]; - result += boost->getAttackRange(st); - } - return result; + int result = 0; + for (unsigned int index = 0; index < boostUpgrades.size(); ++index) { + TotalUpgrade *boost = boostUpgrades[index]; + result += boost->getAttackRange(st); + } + return result; } int TotalUpgrade::getMoveSpeed(const MoveSkillType *st) const { - return UpgradeTypeBase::getMoveSpeed(st) + getMoveSpeedFromBoosts(st); + return UpgradeTypeBase::getMoveSpeed(st) + getMoveSpeedFromBoosts(st); } int TotalUpgrade::getMoveSpeedFromBoosts(const MoveSkillType *st) const { - int result = 0; - for(unsigned int index = 0; index < boostUpgrades.size(); ++index) { - TotalUpgrade *boost = boostUpgrades[index]; - result += boost->getMoveSpeed(st); - } - return result; + int result = 0; + for (unsigned int index = 0; index < boostUpgrades.size(); ++index) { + TotalUpgrade *boost = boostUpgrades[index]; + result += boost->getMoveSpeed(st); + } + return result; } int TotalUpgrade::getProdSpeed(const SkillType *st) const { - return UpgradeTypeBase::getProdSpeed(st) + getProdSpeedFromBoosts(st); + return UpgradeTypeBase::getProdSpeed(st) + getProdSpeedFromBoosts(st); } int TotalUpgrade::getProdSpeedFromBoosts(const SkillType *st) const { - int result = 0; - for(unsigned int index = 0; index < boostUpgrades.size(); ++index) { - TotalUpgrade *boost = boostUpgrades[index]; - result += boost->getProdSpeed(st); - } - return result; + int result = 0; + for (unsigned int index = 0; index < boostUpgrades.size(); ++index) { + TotalUpgrade *boost = boostUpgrades[index]; + result += boost->getProdSpeed(st); + } + return result; } int TotalUpgrade::getAttackSpeed(const AttackSkillType *st) const { - return UpgradeTypeBase::getAttackSpeed(st) + getAttackSpeedFromBoosts(st); + return UpgradeTypeBase::getAttackSpeed(st) + getAttackSpeedFromBoosts(st); } int TotalUpgrade::getAttackSpeedFromBoosts(const AttackSkillType *st) const { - int result = 0; - for(unsigned int index = 0; index < boostUpgrades.size(); ++index) { - TotalUpgrade *boost = boostUpgrades[index]; - result += boost->getAttackSpeed(st); - } - return result; + int result = 0; + for (unsigned int index = 0; index < boostUpgrades.size(); ++index) { + TotalUpgrade *boost = boostUpgrades[index]; + result += boost->getAttackSpeed(st); + } + return result; } void TotalUpgrade::incLevel(const UnitType *ut) { - maxHp += ut->getMaxHp()*50/100; - maxEp += ut->getMaxEp()*50/100; - sight += ut->getSight()*20/100; - armor += ut->getArmor()*50/100; + maxHp += ut->getMaxHp() * 50 / 100; + maxEp += ut->getMaxEp() * 50 / 100; + sight += ut->getSight() * 20 / 100; + armor += ut->getArmor() * 50 / 100; } void TotalUpgrade::saveGame(XmlNode *rootNode) const { - std::map mapTagReplacements; - XmlNode *upgradeTypeBaseNode = rootNode->addChild("TotalUpgrade"); - -// int maxHp; - upgradeTypeBaseNode->addAttribute("maxHp",intToStr(maxHp), mapTagReplacements); -// bool maxHpIsMultiplier; - upgradeTypeBaseNode->addAttribute("maxHpIsMultiplier",intToStr(maxHpIsMultiplier), mapTagReplacements); -// int maxHpRegeneration; - upgradeTypeBaseNode->addAttribute("maxHpRegeneration",intToStr(maxHpRegeneration), mapTagReplacements); -// //bool maxHpRegenerationIsMultiplier; -// -// int sight; - upgradeTypeBaseNode->addAttribute("sight",intToStr(sight), mapTagReplacements); -// bool sightIsMultiplier; - upgradeTypeBaseNode->addAttribute("sightIsMultiplier",intToStr(sightIsMultiplier), mapTagReplacements); -// int maxEp; - upgradeTypeBaseNode->addAttribute("maxEp",intToStr(maxEp), mapTagReplacements); -// bool maxEpIsMultiplier; - upgradeTypeBaseNode->addAttribute("maxEpIsMultiplier",intToStr(maxEpIsMultiplier), mapTagReplacements); -// int maxEpRegeneration; - upgradeTypeBaseNode->addAttribute("maxEpRegeneration",intToStr(maxEpRegeneration), mapTagReplacements); -// //bool maxEpRegenerationIsMultiplier; -// int armor; - upgradeTypeBaseNode->addAttribute("armor",intToStr(armor), mapTagReplacements); -// bool armorIsMultiplier; - upgradeTypeBaseNode->addAttribute("armorIsMultiplier",intToStr(armorIsMultiplier), mapTagReplacements); -// int attackStrength; - upgradeTypeBaseNode->addAttribute("attackStrength",intToStr(attackStrength), mapTagReplacements); -// bool attackStrengthIsMultiplier; - upgradeTypeBaseNode->addAttribute("attackStrengthIsMultiplier",intToStr(attackStrengthIsMultiplier), mapTagReplacements); -// std::map attackStrengthMultiplierValueList; - for(std::map::const_iterator iterMap = attackStrengthMultiplierValueList.begin(); - iterMap != attackStrengthMultiplierValueList.end(); ++iterMap) { - XmlNode *attackStrengthMultiplierValueListNode = upgradeTypeBaseNode->addChild("attackStrengthMultiplierValueList"); - - attackStrengthMultiplierValueListNode->addAttribute("key",iterMap->first, mapTagReplacements); - attackStrengthMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); - } -// int attackRange; - upgradeTypeBaseNode->addAttribute("attackRange",intToStr(attackRange), mapTagReplacements); -// bool attackRangeIsMultiplier; - upgradeTypeBaseNode->addAttribute("attackRangeIsMultiplier",intToStr(attackRangeIsMultiplier), mapTagReplacements); -// std::map attackRangeMultiplierValueList; - for(std::map::const_iterator iterMap = attackRangeMultiplierValueList.begin(); - iterMap != attackRangeMultiplierValueList.end(); ++iterMap) { - XmlNode *attackRangeMultiplierValueListNode = upgradeTypeBaseNode->addChild("attackRangeMultiplierValueList"); - - attackRangeMultiplierValueListNode->addAttribute("key",iterMap->first, mapTagReplacements); - attackRangeMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); - } - -// int moveSpeed; - upgradeTypeBaseNode->addAttribute("moveSpeed",intToStr(moveSpeed), mapTagReplacements); -// bool moveSpeedIsMultiplier; - upgradeTypeBaseNode->addAttribute("moveSpeedIsMultiplier",intToStr(moveSpeedIsMultiplier), mapTagReplacements); -// std::map moveSpeedIsMultiplierValueList; - for(std::map::const_iterator iterMap = moveSpeedIsMultiplierValueList.begin(); - iterMap != moveSpeedIsMultiplierValueList.end(); ++iterMap) { - XmlNode *moveSpeedIsMultiplierValueListNode = upgradeTypeBaseNode->addChild("moveSpeedIsMultiplierValueList"); - - moveSpeedIsMultiplierValueListNode->addAttribute("key",iterMap->first, mapTagReplacements); - moveSpeedIsMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); - } - -// int prodSpeed; - upgradeTypeBaseNode->addAttribute("prodSpeed",intToStr(prodSpeed), mapTagReplacements); -// bool prodSpeedIsMultiplier; - upgradeTypeBaseNode->addAttribute("prodSpeedIsMultiplier",intToStr(prodSpeedIsMultiplier), mapTagReplacements); -// std::map prodSpeedProduceIsMultiplierValueList; - for(std::map::const_iterator iterMap = prodSpeedProduceIsMultiplierValueList.begin(); - iterMap != prodSpeedProduceIsMultiplierValueList.end(); ++iterMap) { - XmlNode *prodSpeedProduceIsMultiplierValueListNode = upgradeTypeBaseNode->addChild("prodSpeedProduceIsMultiplierValueList"); - - prodSpeedProduceIsMultiplierValueListNode->addAttribute("key",iterMap->first, mapTagReplacements); - prodSpeedProduceIsMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); - } - -// std::map prodSpeedUpgradeIsMultiplierValueList; - for(std::map::const_iterator iterMap = prodSpeedUpgradeIsMultiplierValueList.begin(); - iterMap != prodSpeedUpgradeIsMultiplierValueList.end(); ++iterMap) { - XmlNode *prodSpeedUpgradeIsMultiplierValueListNode = upgradeTypeBaseNode->addChild("prodSpeedUpgradeIsMultiplierValueList"); - - prodSpeedUpgradeIsMultiplierValueListNode->addAttribute("key",iterMap->first, mapTagReplacements); - prodSpeedUpgradeIsMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); - } - -// std::map prodSpeedMorphIsMultiplierValueList; - for(std::map::const_iterator iterMap = prodSpeedMorphIsMultiplierValueList.begin(); - iterMap != prodSpeedMorphIsMultiplierValueList.end(); ++iterMap) { - XmlNode *prodSpeedMorphIsMultiplierValueListNode = upgradeTypeBaseNode->addChild("prodSpeedMorphIsMultiplierValueList"); - - prodSpeedMorphIsMultiplierValueListNode->addAttribute("key",iterMap->first, mapTagReplacements); - prodSpeedMorphIsMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); - } - - upgradeTypeBaseNode->addAttribute("attackSpeed",intToStr(attackSpeed), mapTagReplacements); - upgradeTypeBaseNode->addAttribute("attackSpeedIsMultiplier",intToStr(attackSpeedIsMultiplier), mapTagReplacements); - for(std::map::const_iterator iterMap = attackSpeedIsMultiplierValueList.begin(); - iterMap != attackSpeedIsMultiplierValueList.end(); ++iterMap) { - XmlNode *attackSpeedIsMultiplierValueListNode = upgradeTypeBaseNode->addChild("attackSpeedIsMultiplierValueList"); - - attackSpeedIsMultiplierValueListNode->addAttribute("key",iterMap->first, mapTagReplacements); - attackSpeedIsMultiplierValueListNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements); - } - -// for(unsigned int index = 0; index < boostUpgrades.size(); ++index) { -// TotalUpgrade *boost = boostUpgrades[index]; -// XmlNode *attackBoostListNode = upgradeTypeBaseNode->addChild("attackBoostList"); -// attackBoostListNode->addAttribute("unitId",intToStr(boost->boostUpgradeUnit->getId()), mapTagReplacements); -// -// std::map mapTagReplacements; -// if(boost != NULL) { -// boost->saveGameBoost(attackBoostListNode); -// boost->boostUpgradeBase->saveGameBoost(attackBoostListNode); -// } -// } + std::map mapTagReplacements; + XmlNode *upgradeTypeBaseNode = rootNode->addChild("TotalUpgrade"); + + // int maxHp; + upgradeTypeBaseNode->addAttribute("maxHp", intToStr(maxHp), + mapTagReplacements); + // bool maxHpIsMultiplier; + upgradeTypeBaseNode->addAttribute( + "maxHpIsMultiplier", intToStr(maxHpIsMultiplier), mapTagReplacements); + // int maxHpRegeneration; + upgradeTypeBaseNode->addAttribute( + "maxHpRegeneration", intToStr(maxHpRegeneration), mapTagReplacements); + // //bool maxHpRegenerationIsMultiplier; + // + // int sight; + upgradeTypeBaseNode->addAttribute("sight", intToStr(sight), + mapTagReplacements); + // bool sightIsMultiplier; + upgradeTypeBaseNode->addAttribute( + "sightIsMultiplier", intToStr(sightIsMultiplier), mapTagReplacements); + // int maxEp; + upgradeTypeBaseNode->addAttribute("maxEp", intToStr(maxEp), + mapTagReplacements); + // bool maxEpIsMultiplier; + upgradeTypeBaseNode->addAttribute( + "maxEpIsMultiplier", intToStr(maxEpIsMultiplier), mapTagReplacements); + // int maxEpRegeneration; + upgradeTypeBaseNode->addAttribute( + "maxEpRegeneration", intToStr(maxEpRegeneration), mapTagReplacements); + // //bool maxEpRegenerationIsMultiplier; + // int armor; + upgradeTypeBaseNode->addAttribute("armor", intToStr(armor), + mapTagReplacements); + // bool armorIsMultiplier; + upgradeTypeBaseNode->addAttribute( + "armorIsMultiplier", intToStr(armorIsMultiplier), mapTagReplacements); + // int attackStrength; + upgradeTypeBaseNode->addAttribute("attackStrength", intToStr(attackStrength), + mapTagReplacements); + // bool attackStrengthIsMultiplier; + upgradeTypeBaseNode->addAttribute("attackStrengthIsMultiplier", + intToStr(attackStrengthIsMultiplier), + mapTagReplacements); + // std::map attackStrengthMultiplierValueList; + for (std::map::const_iterator iterMap = + attackStrengthMultiplierValueList.begin(); + iterMap != attackStrengthMultiplierValueList.end(); ++iterMap) { + XmlNode *attackStrengthMultiplierValueListNode = + upgradeTypeBaseNode->addChild("attackStrengthMultiplierValueList"); + + attackStrengthMultiplierValueListNode->addAttribute("key", iterMap->first, + mapTagReplacements); + attackStrengthMultiplierValueListNode->addAttribute( + "value", intToStr(iterMap->second), mapTagReplacements); + } + // int attackRange; + upgradeTypeBaseNode->addAttribute("attackRange", intToStr(attackRange), + mapTagReplacements); + // bool attackRangeIsMultiplier; + upgradeTypeBaseNode->addAttribute("attackRangeIsMultiplier", + intToStr(attackRangeIsMultiplier), + mapTagReplacements); + // std::map attackRangeMultiplierValueList; + for (std::map::const_iterator iterMap = + attackRangeMultiplierValueList.begin(); + iterMap != attackRangeMultiplierValueList.end(); ++iterMap) { + XmlNode *attackRangeMultiplierValueListNode = + upgradeTypeBaseNode->addChild("attackRangeMultiplierValueList"); + + attackRangeMultiplierValueListNode->addAttribute("key", iterMap->first, + mapTagReplacements); + attackRangeMultiplierValueListNode->addAttribute( + "value", intToStr(iterMap->second), mapTagReplacements); + } + + // int moveSpeed; + upgradeTypeBaseNode->addAttribute("moveSpeed", intToStr(moveSpeed), + mapTagReplacements); + // bool moveSpeedIsMultiplier; + upgradeTypeBaseNode->addAttribute("moveSpeedIsMultiplier", + intToStr(moveSpeedIsMultiplier), + mapTagReplacements); + // std::map moveSpeedIsMultiplierValueList; + for (std::map::const_iterator iterMap = + moveSpeedIsMultiplierValueList.begin(); + iterMap != moveSpeedIsMultiplierValueList.end(); ++iterMap) { + XmlNode *moveSpeedIsMultiplierValueListNode = + upgradeTypeBaseNode->addChild("moveSpeedIsMultiplierValueList"); + + moveSpeedIsMultiplierValueListNode->addAttribute("key", iterMap->first, + mapTagReplacements); + moveSpeedIsMultiplierValueListNode->addAttribute( + "value", intToStr(iterMap->second), mapTagReplacements); + } + + // int prodSpeed; + upgradeTypeBaseNode->addAttribute("prodSpeed", intToStr(prodSpeed), + mapTagReplacements); + // bool prodSpeedIsMultiplier; + upgradeTypeBaseNode->addAttribute("prodSpeedIsMultiplier", + intToStr(prodSpeedIsMultiplier), + mapTagReplacements); + // std::map prodSpeedProduceIsMultiplierValueList; + for (std::map::const_iterator iterMap = + prodSpeedProduceIsMultiplierValueList.begin(); + iterMap != prodSpeedProduceIsMultiplierValueList.end(); ++iterMap) { + XmlNode *prodSpeedProduceIsMultiplierValueListNode = + upgradeTypeBaseNode->addChild("prodSpeedProduceIsMultiplierValueList"); + + prodSpeedProduceIsMultiplierValueListNode->addAttribute( + "key", iterMap->first, mapTagReplacements); + prodSpeedProduceIsMultiplierValueListNode->addAttribute( + "value", intToStr(iterMap->second), mapTagReplacements); + } + + // std::map prodSpeedUpgradeIsMultiplierValueList; + for (std::map::const_iterator iterMap = + prodSpeedUpgradeIsMultiplierValueList.begin(); + iterMap != prodSpeedUpgradeIsMultiplierValueList.end(); ++iterMap) { + XmlNode *prodSpeedUpgradeIsMultiplierValueListNode = + upgradeTypeBaseNode->addChild("prodSpeedUpgradeIsMultiplierValueList"); + + prodSpeedUpgradeIsMultiplierValueListNode->addAttribute( + "key", iterMap->first, mapTagReplacements); + prodSpeedUpgradeIsMultiplierValueListNode->addAttribute( + "value", intToStr(iterMap->second), mapTagReplacements); + } + + // std::map prodSpeedMorphIsMultiplierValueList; + for (std::map::const_iterator iterMap = + prodSpeedMorphIsMultiplierValueList.begin(); + iterMap != prodSpeedMorphIsMultiplierValueList.end(); ++iterMap) { + XmlNode *prodSpeedMorphIsMultiplierValueListNode = + upgradeTypeBaseNode->addChild("prodSpeedMorphIsMultiplierValueList"); + + prodSpeedMorphIsMultiplierValueListNode->addAttribute("key", iterMap->first, + mapTagReplacements); + prodSpeedMorphIsMultiplierValueListNode->addAttribute( + "value", intToStr(iterMap->second), mapTagReplacements); + } + + upgradeTypeBaseNode->addAttribute("attackSpeed", intToStr(attackSpeed), + mapTagReplacements); + upgradeTypeBaseNode->addAttribute("attackSpeedIsMultiplier", + intToStr(attackSpeedIsMultiplier), + mapTagReplacements); + for (std::map::const_iterator iterMap = + attackSpeedIsMultiplierValueList.begin(); + iterMap != attackSpeedIsMultiplierValueList.end(); ++iterMap) { + XmlNode *attackSpeedIsMultiplierValueListNode = + upgradeTypeBaseNode->addChild("attackSpeedIsMultiplierValueList"); + + attackSpeedIsMultiplierValueListNode->addAttribute("key", iterMap->first, + mapTagReplacements); + attackSpeedIsMultiplierValueListNode->addAttribute( + "value", intToStr(iterMap->second), mapTagReplacements); + } + + // for(unsigned int index = 0; index < boostUpgrades.size(); ++index) { + // TotalUpgrade *boost = boostUpgrades[index]; + // XmlNode *attackBoostListNode = + // upgradeTypeBaseNode->addChild("attackBoostList"); + // attackBoostListNode->addAttribute("unitId",intToStr(boost->boostUpgradeUnit->getId()), + // mapTagReplacements); + // + // std::map mapTagReplacements; + // if(boost != NULL) { + // boost->saveGameBoost(attackBoostListNode); + // boost->boostUpgradeBase->saveGameBoost(attackBoostListNode); + // } + // } } void TotalUpgrade::loadGame(const XmlNode *rootNode) { - const XmlNode *upgradeTypeBaseNode = rootNode->getChild("TotalUpgrade"); - - //description = upgradeTypeBaseNode->getAttribute("description")->getValue(); - - // int maxHp; - maxHp = upgradeTypeBaseNode->getAttribute("maxHp")->getIntValue(); - // bool maxHpIsMultiplier; - maxHpIsMultiplier = upgradeTypeBaseNode->getAttribute("maxHpIsMultiplier")->getIntValue() != 0; - // int maxHpRegeneration; - maxHpRegeneration = upgradeTypeBaseNode->getAttribute("maxHpRegeneration")->getIntValue(); - // //bool maxHpRegenerationIsMultiplier; - // - // int sight; - sight = upgradeTypeBaseNode->getAttribute("sight")->getIntValue(); - // bool sightIsMultiplier; - sightIsMultiplier = upgradeTypeBaseNode->getAttribute("sightIsMultiplier")->getIntValue() != 0; - // int maxEp; - maxEp = upgradeTypeBaseNode->getAttribute("maxEp")->getIntValue(); - // bool maxEpIsMultiplier; - maxEpIsMultiplier = upgradeTypeBaseNode->getAttribute("maxEpIsMultiplier")->getIntValue() != 0; - // int maxEpRegeneration; - maxEpRegeneration = upgradeTypeBaseNode->getAttribute("maxEpRegeneration")->getIntValue(); - // //bool maxEpRegenerationIsMultiplier; - // int armor; - armor = upgradeTypeBaseNode->getAttribute("armor")->getIntValue(); - // bool armorIsMultiplier; - armorIsMultiplier = upgradeTypeBaseNode->getAttribute("armorIsMultiplier")->getIntValue() != 0; - // int attackStrength; - attackStrength = upgradeTypeBaseNode->getAttribute("attackStrength")->getIntValue(); - // bool attackStrengthIsMultiplier; - attackStrengthIsMultiplier = upgradeTypeBaseNode->getAttribute("attackStrengthIsMultiplier")->getIntValue() != 0; - // std::map attackStrengthMultiplierValueList; - vector attackStrengthMultiplierValueNodeList = upgradeTypeBaseNode->getChildList("attackStrengthMultiplierValueList"); - for(unsigned int i = 0; i < attackStrengthMultiplierValueNodeList.size(); ++i) { - XmlNode *node = attackStrengthMultiplierValueNodeList[i]; - - attackStrengthMultiplierValueList[node->getAttribute("key")->getValue()] = - node->getAttribute("value")->getIntValue(); - } - // int attackRange; - attackRange = upgradeTypeBaseNode->getAttribute("attackRange")->getIntValue(); - // bool attackRangeIsMultiplier; - attackRangeIsMultiplier = upgradeTypeBaseNode->getAttribute("attackRangeIsMultiplier")->getIntValue() != 0; - // std::map attackRangeMultiplierValueList; - vector attackRangeMultiplierValueNodeList = upgradeTypeBaseNode->getChildList("attackRangeMultiplierValueList"); - for(unsigned int i = 0; i < attackRangeMultiplierValueNodeList.size(); ++i) { - XmlNode *node = attackRangeMultiplierValueNodeList[i]; - - attackRangeMultiplierValueList[node->getAttribute("key")->getValue()] = - node->getAttribute("value")->getIntValue(); - } - - // int moveSpeed; - moveSpeed = upgradeTypeBaseNode->getAttribute("moveSpeed")->getIntValue(); - // bool moveSpeedIsMultiplier; - moveSpeedIsMultiplier = upgradeTypeBaseNode->getAttribute("moveSpeedIsMultiplier")->getIntValue() != 0; - // std::map moveSpeedIsMultiplierValueList; - vector moveSpeedIsMultiplierValueNodeList = upgradeTypeBaseNode->getChildList("moveSpeedIsMultiplierValueList"); - for(unsigned int i = 0; i < moveSpeedIsMultiplierValueNodeList.size(); ++i) { - XmlNode *node = moveSpeedIsMultiplierValueNodeList[i]; - - moveSpeedIsMultiplierValueList[node->getAttribute("key")->getValue()] = - node->getAttribute("value")->getIntValue(); - } - - // int prodSpeed; - prodSpeed = upgradeTypeBaseNode->getAttribute("prodSpeed")->getIntValue(); - // bool prodSpeedIsMultiplier; - prodSpeedIsMultiplier = upgradeTypeBaseNode->getAttribute("prodSpeedIsMultiplier")->getIntValue() != 0; - // std::map prodSpeedProduceIsMultiplierValueList; - vector prodSpeedProduceIsMultiplierValueNodeList = upgradeTypeBaseNode->getChildList("prodSpeedProduceIsMultiplierValueList"); - for(unsigned int i = 0; i < prodSpeedProduceIsMultiplierValueNodeList.size(); ++i) { - XmlNode *node = prodSpeedProduceIsMultiplierValueNodeList[i]; - - prodSpeedProduceIsMultiplierValueList[node->getAttribute("key")->getValue()] = - node->getAttribute("value")->getIntValue(); - } - - // std::map prodSpeedUpgradeIsMultiplierValueList; - vector prodSpeedUpgradeIsMultiplierValueNodeList = upgradeTypeBaseNode->getChildList("prodSpeedUpgradeIsMultiplierValueList"); - for(unsigned int i = 0; i < prodSpeedUpgradeIsMultiplierValueNodeList.size(); ++i) { - XmlNode *node = prodSpeedUpgradeIsMultiplierValueNodeList[i]; - - prodSpeedUpgradeIsMultiplierValueList[node->getAttribute("key")->getValue()] = - node->getAttribute("value")->getIntValue(); - } - - // std::map prodSpeedMorphIsMultiplierValueList; - vector prodSpeedMorphIsMultiplierValueNodeList = upgradeTypeBaseNode->getChildList("prodSpeedMorphIsMultiplierValueList"); - for(unsigned int i = 0; i < prodSpeedMorphIsMultiplierValueNodeList.size(); ++i) { - XmlNode *node = prodSpeedMorphIsMultiplierValueNodeList[i]; - - prodSpeedMorphIsMultiplierValueList[node->getAttribute("key")->getValue()] = - node->getAttribute("value")->getIntValue(); - } - - if(upgradeTypeBaseNode->hasAttribute("attackSpeed")){ - attackSpeed = upgradeTypeBaseNode->getAttribute("attackSpeed")->getIntValue(); - attackSpeedIsMultiplier = upgradeTypeBaseNode->getAttribute("attackSpeedIsMultiplier")->getIntValue() != 0; - vector attackSpeedIsMultiplierValueNodeList = upgradeTypeBaseNode->getChildList("attackSpeedIsMultiplierValueList"); - for(unsigned int i = 0; i < attackSpeedIsMultiplierValueNodeList.size(); ++i) { - XmlNode *node = attackSpeedIsMultiplierValueNodeList[i]; - - attackSpeedIsMultiplierValueList[node->getAttribute("key")->getValue()] = - node->getAttribute("value")->getIntValue(); - } - } - -// vector boostNodeList = upgradeTypeBaseNode->getChildList("attackBoostList"); -// for(unsigned int index = 0; index < boostNodeList.size(); ++index) { -// XmlNode *boostNode = boostNodeList[index]; -// -// //for(unsigned int index = 0; index < boostUpgrades.size(); ++index) { -// // TotalUpgrade *boost = boostUpgrades[index]; -// // XmlNode *attackBoostListNode = upgradeTypeBaseNode->addChild("attackBoostList"); -// -//// std::map mapTagReplacements; -//// if(boost != NULL) { -//// boost->saveGame(attackBoostListNode); -//// } -// int unitId = boostNode->getAttribute("unitId")->getIntValue(); -// const Unit *unit = world->findUnitById(unitId); -// -// TotalUpgrade *boostUpgrade = new TotalUpgrade(); -// //boostUpgrade->copyDataFrom(this); -// boostUpgrade->loadGameBoost(boostNode); -// boostUpgrade->loadGameBoost(boostNode); -// -// boostUpgrade->boostUpgradeBase = ut; -// boostUpgrade->boostUpgradeUnit = unit; -// -// //boostUpgrade->sum(ut,unit); -// boostUpgrades.push_back(boostUpgrade); -// -// //boost->saveGameBoost(attackBoostListNode); -// //boost->boostUpgradeBase->saveGameBoost(attackBoostListNode); -// -// //apply(const UpgradeTypeBase *ut, unit); -// } - + const XmlNode *upgradeTypeBaseNode = rootNode->getChild("TotalUpgrade"); + + // description = upgradeTypeBaseNode->getAttribute("description")->getValue(); + + // int maxHp; + maxHp = upgradeTypeBaseNode->getAttribute("maxHp")->getIntValue(); + // bool maxHpIsMultiplier; + maxHpIsMultiplier = + upgradeTypeBaseNode->getAttribute("maxHpIsMultiplier")->getIntValue() != + 0; + // int maxHpRegeneration; + maxHpRegeneration = + upgradeTypeBaseNode->getAttribute("maxHpRegeneration")->getIntValue(); + // //bool maxHpRegenerationIsMultiplier; + // + // int sight; + sight = upgradeTypeBaseNode->getAttribute("sight")->getIntValue(); + // bool sightIsMultiplier; + sightIsMultiplier = + upgradeTypeBaseNode->getAttribute("sightIsMultiplier")->getIntValue() != + 0; + // int maxEp; + maxEp = upgradeTypeBaseNode->getAttribute("maxEp")->getIntValue(); + // bool maxEpIsMultiplier; + maxEpIsMultiplier = + upgradeTypeBaseNode->getAttribute("maxEpIsMultiplier")->getIntValue() != + 0; + // int maxEpRegeneration; + maxEpRegeneration = + upgradeTypeBaseNode->getAttribute("maxEpRegeneration")->getIntValue(); + // //bool maxEpRegenerationIsMultiplier; + // int armor; + armor = upgradeTypeBaseNode->getAttribute("armor")->getIntValue(); + // bool armorIsMultiplier; + armorIsMultiplier = + upgradeTypeBaseNode->getAttribute("armorIsMultiplier")->getIntValue() != + 0; + // int attackStrength; + attackStrength = + upgradeTypeBaseNode->getAttribute("attackStrength")->getIntValue(); + // bool attackStrengthIsMultiplier; + attackStrengthIsMultiplier = + upgradeTypeBaseNode->getAttribute("attackStrengthIsMultiplier") + ->getIntValue() != 0; + // std::map attackStrengthMultiplierValueList; + vector attackStrengthMultiplierValueNodeList = + upgradeTypeBaseNode->getChildList("attackStrengthMultiplierValueList"); + for (unsigned int i = 0; i < attackStrengthMultiplierValueNodeList.size(); + ++i) { + XmlNode *node = attackStrengthMultiplierValueNodeList[i]; + + attackStrengthMultiplierValueList[node->getAttribute("key")->getValue()] = + node->getAttribute("value")->getIntValue(); + } + // int attackRange; + attackRange = upgradeTypeBaseNode->getAttribute("attackRange")->getIntValue(); + // bool attackRangeIsMultiplier; + attackRangeIsMultiplier = + upgradeTypeBaseNode->getAttribute("attackRangeIsMultiplier") + ->getIntValue() != 0; + // std::map attackRangeMultiplierValueList; + vector attackRangeMultiplierValueNodeList = + upgradeTypeBaseNode->getChildList("attackRangeMultiplierValueList"); + for (unsigned int i = 0; i < attackRangeMultiplierValueNodeList.size(); ++i) { + XmlNode *node = attackRangeMultiplierValueNodeList[i]; + + attackRangeMultiplierValueList[node->getAttribute("key")->getValue()] = + node->getAttribute("value")->getIntValue(); + } + + // int moveSpeed; + moveSpeed = upgradeTypeBaseNode->getAttribute("moveSpeed")->getIntValue(); + // bool moveSpeedIsMultiplier; + moveSpeedIsMultiplier = + upgradeTypeBaseNode->getAttribute("moveSpeedIsMultiplier") + ->getIntValue() != 0; + // std::map moveSpeedIsMultiplierValueList; + vector moveSpeedIsMultiplierValueNodeList = + upgradeTypeBaseNode->getChildList("moveSpeedIsMultiplierValueList"); + for (unsigned int i = 0; i < moveSpeedIsMultiplierValueNodeList.size(); ++i) { + XmlNode *node = moveSpeedIsMultiplierValueNodeList[i]; + + moveSpeedIsMultiplierValueList[node->getAttribute("key")->getValue()] = + node->getAttribute("value")->getIntValue(); + } + + // int prodSpeed; + prodSpeed = upgradeTypeBaseNode->getAttribute("prodSpeed")->getIntValue(); + // bool prodSpeedIsMultiplier; + prodSpeedIsMultiplier = + upgradeTypeBaseNode->getAttribute("prodSpeedIsMultiplier") + ->getIntValue() != 0; + // std::map prodSpeedProduceIsMultiplierValueList; + vector prodSpeedProduceIsMultiplierValueNodeList = + upgradeTypeBaseNode->getChildList( + "prodSpeedProduceIsMultiplierValueList"); + for (unsigned int i = 0; i < prodSpeedProduceIsMultiplierValueNodeList.size(); + ++i) { + XmlNode *node = prodSpeedProduceIsMultiplierValueNodeList[i]; + + prodSpeedProduceIsMultiplierValueList[node->getAttribute("key") + ->getValue()] = + node->getAttribute("value")->getIntValue(); + } + + // std::map prodSpeedUpgradeIsMultiplierValueList; + vector prodSpeedUpgradeIsMultiplierValueNodeList = + upgradeTypeBaseNode->getChildList( + "prodSpeedUpgradeIsMultiplierValueList"); + for (unsigned int i = 0; i < prodSpeedUpgradeIsMultiplierValueNodeList.size(); + ++i) { + XmlNode *node = prodSpeedUpgradeIsMultiplierValueNodeList[i]; + + prodSpeedUpgradeIsMultiplierValueList[node->getAttribute("key") + ->getValue()] = + node->getAttribute("value")->getIntValue(); + } + + // std::map prodSpeedMorphIsMultiplierValueList; + vector prodSpeedMorphIsMultiplierValueNodeList = + upgradeTypeBaseNode->getChildList("prodSpeedMorphIsMultiplierValueList"); + for (unsigned int i = 0; i < prodSpeedMorphIsMultiplierValueNodeList.size(); + ++i) { + XmlNode *node = prodSpeedMorphIsMultiplierValueNodeList[i]; + + prodSpeedMorphIsMultiplierValueList[node->getAttribute("key")->getValue()] = + node->getAttribute("value")->getIntValue(); + } + + if (upgradeTypeBaseNode->hasAttribute("attackSpeed")) { + attackSpeed = + upgradeTypeBaseNode->getAttribute("attackSpeed")->getIntValue(); + attackSpeedIsMultiplier = + upgradeTypeBaseNode->getAttribute("attackSpeedIsMultiplier") + ->getIntValue() != 0; + vector attackSpeedIsMultiplierValueNodeList = + upgradeTypeBaseNode->getChildList("attackSpeedIsMultiplierValueList"); + for (unsigned int i = 0; i < attackSpeedIsMultiplierValueNodeList.size(); + ++i) { + XmlNode *node = attackSpeedIsMultiplierValueNodeList[i]; + + attackSpeedIsMultiplierValueList[node->getAttribute("key")->getValue()] = + node->getAttribute("value")->getIntValue(); + } + } + + // vector boostNodeList = + // upgradeTypeBaseNode->getChildList("attackBoostList"); for(unsigned int + // index = 0; index < boostNodeList.size(); ++index) { XmlNode + //*boostNode = boostNodeList[index]; + // + // //for(unsigned int index = 0; index < boostUpgrades.size(); ++index) { + // // TotalUpgrade *boost = boostUpgrades[index]; + // // XmlNode *attackBoostListNode = + // upgradeTypeBaseNode->addChild("attackBoostList"); + // + //// std::map mapTagReplacements; + //// if(boost != NULL) { + //// boost->saveGame(attackBoostListNode); + //// } + // int unitId = boostNode->getAttribute("unitId")->getIntValue(); + // const Unit *unit = world->findUnitById(unitId); + // + // TotalUpgrade *boostUpgrade = new TotalUpgrade(); + // //boostUpgrade->copyDataFrom(this); + // boostUpgrade->loadGameBoost(boostNode); + // boostUpgrade->loadGameBoost(boostNode); + // + // boostUpgrade->boostUpgradeBase = ut; + // boostUpgrade->boostUpgradeUnit = unit; + // + // //boostUpgrade->sum(ut,unit); + // boostUpgrades.push_back(boostUpgrade); + // + // //boost->saveGameBoost(attackBoostListNode); + // //boost->boostUpgradeBase->saveGameBoost(attackBoostListNode); + // + // //apply(const UpgradeTypeBase *ut, unit); + // } } - -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/types/upgrade_type.h b/source/glest_game/types/upgrade_type.h index 303faf44a..9a6cac4c4 100644 --- a/source/glest_game/types/upgrade_type.h +++ b/source/glest_game/types/upgrade_type.h @@ -11,32 +11,34 @@ /** * @file - * Classified the Upgrade type (which is sort of like a class for upgrades). Each upgrade has a - * type that details the stats that it boosts and the units that it affects. Also has TotalUpgrade, - * which is a sum of all upgrades applied to a particular unit (and is what determines how units - * stats are modified by an upgrade. + * Classified the Upgrade type (which is sort of like a class for upgrades). + * Each upgrade has a type that details the stats that it boosts and the units + * that it affects. Also has TotalUpgrade, which is a sum of all upgrades + * applied to a particular unit (and is what determines how units stats are + * modified by an upgrade. */ #ifndef _GLEST_GAME_UPGRADETYPE_H_ #define _GLEST_GAME_UPGRADETYPE_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include "element_type.h" #include "checksum.h" #include "conversion.h" -#include "xml_parser.h" +#include "element_type.h" #include "leak_dumper.h" +#include "xml_parser.h" #include using Shared::Util::Checksum; using namespace Shared::Util; using namespace Shared::Xml; -namespace Glest { namespace Game { +namespace Glest { +namespace Game { class TechTree; class FactionType; @@ -49,396 +51,446 @@ class ProduceSkillType; class Faction; /** - * Groups all information used for upgrades. Attack boosts also use this class for modifying stats. + * Groups all information used for upgrades. Attack boosts also use this class + * for modifying stats. */ class UpgradeTypeBase { protected: - string upgradename; - int maxHp; - bool maxHpIsMultiplier; - int maxHpRegeneration; - //bool maxHpRegenerationIsMultiplier; - - int sight; - bool sightIsMultiplier; - - int maxEp; - bool maxEpIsMultiplier; - int maxEpRegeneration; - //bool maxEpRegenerationIsMultiplier; - - int armor; - bool armorIsMultiplier; - - int attackStrength; - bool attackStrengthIsMultiplier; - /** - * List of the values (for each skill type) that the stat was boosted by. This is used so - * that we can restore the original values when the upgrade is removed (eg, an attack - * boost wears off). - */ - std::map attackStrengthMultiplierValueList; - - int attackRange; - bool attackRangeIsMultiplier; - std::map attackRangeMultiplierValueList; /**< @see #attackStrengthMultiplierValueList */ - - int moveSpeed; - bool moveSpeedIsMultiplier; - std::map moveSpeedIsMultiplierValueList; /**< @see #attackStrengthMultiplierValueList */ - - int prodSpeed; - bool prodSpeedIsMultiplier; - std::map prodSpeedProduceIsMultiplierValueList; /**< @see #attackStrengthMultiplierValueList */ - std::map prodSpeedUpgradeIsMultiplierValueList; /**< @see #attackStrengthMultiplierValueList */ - std::map prodSpeedMorphIsMultiplierValueList; /**< @see #attackStrengthMultiplierValueList */ - - int attackSpeed; - bool attackSpeedIsMultiplier; - std::map attackSpeedIsMultiplierValueList; + string upgradename; + int maxHp; + bool maxHpIsMultiplier; + int maxHpRegeneration; + // bool maxHpRegenerationIsMultiplier; + + int sight; + bool sightIsMultiplier; + + int maxEp; + bool maxEpIsMultiplier; + int maxEpRegeneration; + // bool maxEpRegenerationIsMultiplier; + + int armor; + bool armorIsMultiplier; + + int attackStrength; + bool attackStrengthIsMultiplier; + /** + * List of the values (for each skill type) that the stat was boosted by. This + * is used so that we can restore the original values when the upgrade is + * removed (eg, an attack boost wears off). + */ + std::map attackStrengthMultiplierValueList; + + int attackRange; + bool attackRangeIsMultiplier; + std::map + attackRangeMultiplierValueList; /**< @see + #attackStrengthMultiplierValueList */ + + int moveSpeed; + bool moveSpeedIsMultiplier; + std::map + moveSpeedIsMultiplierValueList; /**< @see + #attackStrengthMultiplierValueList */ + + int prodSpeed; + bool prodSpeedIsMultiplier; + std::map + prodSpeedProduceIsMultiplierValueList; /**< @see + #attackStrengthMultiplierValueList + */ + std::map + prodSpeedUpgradeIsMultiplierValueList; /**< @see + #attackStrengthMultiplierValueList + */ + std::map + prodSpeedMorphIsMultiplierValueList; /**< @see + #attackStrengthMultiplierValueList + */ + + int attackSpeed; + bool attackSpeedIsMultiplier; + std::map attackSpeedIsMultiplierValueList; protected: - - virtual int getAttackStrength() const { return attackStrength; } - virtual int getAttackRange() const { return attackRange; } - virtual int getMoveSpeed() const { return moveSpeed; } - virtual int getProdSpeed() const { return prodSpeed; } - virtual int getAttackSpeed() const { return attackSpeed; } - - virtual int getMaxHpFromBoosts() const { return 0; } - virtual int getMaxHpRegenerationFromBoosts() const { return 0; } - virtual int getSightFromBoosts() const { return 0; } - virtual int getMaxEpFromBoosts() const { return 0; } - virtual int getMaxEpRegenerationFromBoosts() const { return 0; } - virtual int getArmorFromBoosts() const { return 0; }; - virtual int getAttackStrengthFromBoosts(const AttackSkillType *st) const { return 0; } - virtual int getAttackRangeFromBoosts(const AttackSkillType *st) const { return 0; } - virtual int getMoveSpeedFromBoosts(const MoveSkillType *st) const { return 0; } - virtual int getProdSpeedFromBoosts(const SkillType *st) const { return 0; } - virtual int getAttackSpeedFromBoosts(const AttackSkillType *st) const { return 0; } + virtual int getAttackStrength() const { return attackStrength; } + virtual int getAttackRange() const { return attackRange; } + virtual int getMoveSpeed() const { return moveSpeed; } + virtual int getProdSpeed() const { return prodSpeed; } + virtual int getAttackSpeed() const { return attackSpeed; } + + virtual int getMaxHpFromBoosts() const { return 0; } + virtual int getMaxHpRegenerationFromBoosts() const { return 0; } + virtual int getSightFromBoosts() const { return 0; } + virtual int getMaxEpFromBoosts() const { return 0; } + virtual int getMaxEpRegenerationFromBoosts() const { return 0; } + virtual int getArmorFromBoosts() const { return 0; }; + virtual int getAttackStrengthFromBoosts(const AttackSkillType *st) const { + return 0; + } + virtual int getAttackRangeFromBoosts(const AttackSkillType *st) const { + return 0; + } + virtual int getMoveSpeedFromBoosts(const MoveSkillType *st) const { + return 0; + } + virtual int getProdSpeedFromBoosts(const SkillType *st) const { return 0; } + virtual int getAttackSpeedFromBoosts(const AttackSkillType *st) const { + return 0; + } public: - /** - * Creates an UpgradeTypeBase with values such that there are no stat changes. - */ - UpgradeTypeBase() { - maxHp = 0;; - maxHpIsMultiplier = false; - maxHpRegeneration = 0; - sight = 0; - sightIsMultiplier = false; - maxEp = 0;; - maxEpIsMultiplier = false; - maxEpRegeneration = 0; - armor = 0; - armorIsMultiplier = false; - attackStrength = 0; - attackStrengthIsMultiplier = false; - attackRange = 0; - attackRangeIsMultiplier = false; - moveSpeed = 0; - moveSpeedIsMultiplier = false; - prodSpeed = 0; - prodSpeedIsMultiplier = false; - attackSpeed = 0; - attackSpeedIsMultiplier = false; - } - virtual ~UpgradeTypeBase() {} - - virtual void copyDataFrom(UpgradeTypeBase *source); - - virtual string getUpgradeName() const { return upgradename; } - virtual int getMaxHp() const {return maxHp;} - virtual int getMaxHpRegeneration() const {return maxHpRegeneration;} - virtual int getSight() const {return sight;} - virtual int getMaxEp() const {return maxEp;} - virtual int getMaxEpRegeneration() const {return maxEpRegeneration;} - virtual int getArmor() const {return armor;} - virtual int getAttackStrength(const AttackSkillType *st) const; - virtual int getAttackRange(const AttackSkillType *st) const; - virtual int getMoveSpeed(const MoveSkillType *st) const; - virtual int getProdSpeed(const SkillType *st) const; - virtual int getAttackSpeed(const AttackSkillType *st) const; - - virtual bool getAttackStrengthIsMultiplier() const {return attackStrengthIsMultiplier;} - virtual bool getMaxHpIsMultiplier() const {return maxHpIsMultiplier;} - virtual bool getSightIsMultiplier() const {return sightIsMultiplier;} - virtual bool getMaxEpIsMultiplier() const {return maxEpIsMultiplier;} - virtual bool getArmorIsMultiplier() const {return armorIsMultiplier;} - virtual bool getAttackRangeIsMultiplier() const {return attackRangeIsMultiplier;} - virtual bool getMoveSpeedIsMultiplier() const {return moveSpeedIsMultiplier;} - virtual bool getProdSpeedIsMultiplier() const {return prodSpeedIsMultiplier;} - virtual bool getAttackSpeedIsMultiplier() const {return attackSpeedIsMultiplier;} - - /** - * Loads the upgrade values (stat boosts and whether or not the boosts use a multiplier) from an - * XML node. - * @param upgradeNode Node containing the stat boost elements (`max-hp`, `attack-strength`, etc). - * @param upgradename Unique identifier for the upgrade. - */ - - virtual void load(const XmlNode *upgradeNode, string upgradename); - - /** - * Creates a string representation of the upgrade. All stat boosts are detailed on their own line - * with their corresponding boosts. - * @param translatedValue If true, the description is translated. Otherwise the description uses - * names as they appear in the XMLs. - */ - virtual string getDesc(bool translatedValue) const; - - /** - * Returns a string representation of this object. Lists all the value that the object stores. - * For debugging purposes, only. - */ - virtual std::string toString() const { - std::string result = ""; - - result += "upgradename =" + getUpgradeName(); - result += "maxHp = " + intToStr(getMaxHp()); - result += "maxHpIsMultiplier = " + intToStr(getMaxHpIsMultiplier()); - result += "maxHpRegeneration = " + intToStr(getMaxHpRegeneration()); - //result += "maxHpRegenerationIsMultiplier = " + intToStr(maxHpRegenerationIsMultiplier); - - result += " sight = " + intToStr(getSight()); - result += "sightIsMultiplier = " + intToStr(getSightIsMultiplier()); - - result += " maxEp = " + intToStr(getMaxEp()); - result += " maxEpIsMultiplier = " + intToStr(getMaxEpIsMultiplier()); - result += " maxEpRegeneration = " + intToStr(getMaxEpRegeneration()); - //result += "maxEpRegenerationIsMultiplier = " + intToStr(maxEpRegenerationIsMultiplier); - - result += " armor = " + intToStr(getArmor()); - result += " armorIsMultiplier = " + intToStr(getArmorIsMultiplier()); - result += " attackStrength = " + intToStr(getAttackStrength()); - result += " attackStrengthIsMultiplier = " + intToStr(getAttackStrengthIsMultiplier()); - result += " attackRange = " + intToStr(getAttackRange()); - result += " attackRangeIsMultiplier = " + intToStr(getAttackRangeIsMultiplier()); - result += " moveSpeed = " + intToStr(getMoveSpeed()); - result += " moveSpeedIsMultiplier = " + intToStr(getMoveSpeedIsMultiplier()); - result += " prodSpeed = " + intToStr(getProdSpeed()); - result += " prodSpeedIsMultiplier = " + intToStr(getProdSpeedIsMultiplier()); - - return result; - } - - // TODO: It's not clear if these save game methods are being used, currently. I think - // attack boosts might use the few lines that aren't commented out. - virtual void saveGame(XmlNode *rootNode) const; - //virtual void saveGameBoost(XmlNode *rootNode) const; - static const UpgradeType * loadGame(const XmlNode *rootNode, Faction *faction); - //void loadGameBoost(const XmlNode *rootNode); - - /** - * Generates a checksum value for the upgrade. - */ - virtual Checksum getCRC() { - Checksum crcForUpgradeType; - - crcForUpgradeType.addString(getUpgradeName()); - crcForUpgradeType.addInt(getMaxHp()); - crcForUpgradeType.addInt(getMaxHpIsMultiplier()); - crcForUpgradeType.addInt(getMaxHpRegeneration()); - - crcForUpgradeType.addInt(getSight()); - crcForUpgradeType.addInt(getSightIsMultiplier()); - - crcForUpgradeType.addInt(getMaxEp()); - crcForUpgradeType.addInt(getMaxEpIsMultiplier()); - crcForUpgradeType.addInt(getMaxEpRegeneration()); - - crcForUpgradeType.addInt(getArmor()); - crcForUpgradeType.addInt(getArmorIsMultiplier()); - - crcForUpgradeType.addInt(getAttackStrength()); - crcForUpgradeType.addInt(getAttackStrengthIsMultiplier()); - //std::map attackStrengthMultiplierValueList; - crcForUpgradeType.addInt64((int64)attackStrengthMultiplierValueList.size()); - - crcForUpgradeType.addInt(getAttackRange()); - crcForUpgradeType.addInt(getAttackRangeIsMultiplier()); - //std::map attackRangeMultiplierValueList; - crcForUpgradeType.addInt64((int64)attackRangeMultiplierValueList.size()); - - crcForUpgradeType.addInt(getMoveSpeed()); - crcForUpgradeType.addInt(getMoveSpeedIsMultiplier()); - //std::map moveSpeedIsMultiplierValueList; - crcForUpgradeType.addInt64((int64)moveSpeedIsMultiplierValueList.size()); - - crcForUpgradeType.addInt(getProdSpeed()); - crcForUpgradeType.addInt(getProdSpeedIsMultiplier()); - //std::map prodSpeedProduceIsMultiplierValueList; - crcForUpgradeType.addInt64((int64)prodSpeedProduceIsMultiplierValueList.size()); - //std::map prodSpeedUpgradeIsMultiplierValueList; - crcForUpgradeType.addInt64((int64)prodSpeedUpgradeIsMultiplierValueList.size()); - //std::map prodSpeedMorphIsMultiplierValueList; - crcForUpgradeType.addInt64((int64)prodSpeedMorphIsMultiplierValueList.size()); - - crcForUpgradeType.addInt(getAttackSpeed()); - crcForUpgradeType.addInt(getAttackSpeedIsMultiplier()); - - return crcForUpgradeType; - } + /** + * Creates an UpgradeTypeBase with values such that there are no stat changes. + */ + UpgradeTypeBase() { + maxHp = 0; + ; + maxHpIsMultiplier = false; + maxHpRegeneration = 0; + sight = 0; + sightIsMultiplier = false; + maxEp = 0; + ; + maxEpIsMultiplier = false; + maxEpRegeneration = 0; + armor = 0; + armorIsMultiplier = false; + attackStrength = 0; + attackStrengthIsMultiplier = false; + attackRange = 0; + attackRangeIsMultiplier = false; + moveSpeed = 0; + moveSpeedIsMultiplier = false; + prodSpeed = 0; + prodSpeedIsMultiplier = false; + attackSpeed = 0; + attackSpeedIsMultiplier = false; + } + virtual ~UpgradeTypeBase() {} + + virtual void copyDataFrom(UpgradeTypeBase *source); + + virtual string getUpgradeName() const { return upgradename; } + virtual int getMaxHp() const { return maxHp; } + virtual int getMaxHpRegeneration() const { return maxHpRegeneration; } + virtual int getSight() const { return sight; } + virtual int getMaxEp() const { return maxEp; } + virtual int getMaxEpRegeneration() const { return maxEpRegeneration; } + virtual int getArmor() const { return armor; } + virtual int getAttackStrength(const AttackSkillType *st) const; + virtual int getAttackRange(const AttackSkillType *st) const; + virtual int getMoveSpeed(const MoveSkillType *st) const; + virtual int getProdSpeed(const SkillType *st) const; + virtual int getAttackSpeed(const AttackSkillType *st) const; + + virtual bool getAttackStrengthIsMultiplier() const { + return attackStrengthIsMultiplier; + } + virtual bool getMaxHpIsMultiplier() const { return maxHpIsMultiplier; } + virtual bool getSightIsMultiplier() const { return sightIsMultiplier; } + virtual bool getMaxEpIsMultiplier() const { return maxEpIsMultiplier; } + virtual bool getArmorIsMultiplier() const { return armorIsMultiplier; } + virtual bool getAttackRangeIsMultiplier() const { + return attackRangeIsMultiplier; + } + virtual bool getMoveSpeedIsMultiplier() const { + return moveSpeedIsMultiplier; + } + virtual bool getProdSpeedIsMultiplier() const { + return prodSpeedIsMultiplier; + } + virtual bool getAttackSpeedIsMultiplier() const { + return attackSpeedIsMultiplier; + } + + /** + * Loads the upgrade values (stat boosts and whether or not the boosts use a + * multiplier) from an XML node. + * @param upgradeNode Node containing the stat boost elements (`max-hp`, + * `attack-strength`, etc). + * @param upgradename Unique identifier for the upgrade. + */ + + virtual void load(const XmlNode *upgradeNode, string upgradename); + + /** + * Creates a string representation of the upgrade. All stat boosts are + * detailed on their own line with their corresponding boosts. + * @param translatedValue If true, the description is translated. Otherwise + * the description uses names as they appear in the XMLs. + */ + virtual string getDesc(bool translatedValue) const; + + /** + * Returns a string representation of this object. Lists all the value that + * the object stores. For debugging purposes, only. + */ + virtual std::string toString() const { + std::string result = ""; + + result += "upgradename =" + getUpgradeName(); + result += "maxHp = " + intToStr(getMaxHp()); + result += "maxHpIsMultiplier = " + intToStr(getMaxHpIsMultiplier()); + result += "maxHpRegeneration = " + intToStr(getMaxHpRegeneration()); + // result += "maxHpRegenerationIsMultiplier = " + + // intToStr(maxHpRegenerationIsMultiplier); + + result += " sight = " + intToStr(getSight()); + result += "sightIsMultiplier = " + intToStr(getSightIsMultiplier()); + + result += " maxEp = " + intToStr(getMaxEp()); + result += " maxEpIsMultiplier = " + intToStr(getMaxEpIsMultiplier()); + result += " maxEpRegeneration = " + intToStr(getMaxEpRegeneration()); + // result += "maxEpRegenerationIsMultiplier = " + + // intToStr(maxEpRegenerationIsMultiplier); + + result += " armor = " + intToStr(getArmor()); + result += " armorIsMultiplier = " + intToStr(getArmorIsMultiplier()); + result += " attackStrength = " + intToStr(getAttackStrength()); + result += " attackStrengthIsMultiplier = " + + intToStr(getAttackStrengthIsMultiplier()); + result += " attackRange = " + intToStr(getAttackRange()); + result += + " attackRangeIsMultiplier = " + intToStr(getAttackRangeIsMultiplier()); + result += " moveSpeed = " + intToStr(getMoveSpeed()); + result += + " moveSpeedIsMultiplier = " + intToStr(getMoveSpeedIsMultiplier()); + result += " prodSpeed = " + intToStr(getProdSpeed()); + result += + " prodSpeedIsMultiplier = " + intToStr(getProdSpeedIsMultiplier()); + + return result; + } + + // TODO: It's not clear if these save game methods are being used, currently. + // I think attack boosts might use the few lines that aren't commented out. + virtual void saveGame(XmlNode *rootNode) const; + // virtual void saveGameBoost(XmlNode *rootNode) const; + static const UpgradeType *loadGame(const XmlNode *rootNode, Faction *faction); + // void loadGameBoost(const XmlNode *rootNode); + + /** + * Generates a checksum value for the upgrade. + */ + virtual Checksum getCRC() { + Checksum crcForUpgradeType; + + crcForUpgradeType.addString(getUpgradeName()); + crcForUpgradeType.addInt(getMaxHp()); + crcForUpgradeType.addInt(getMaxHpIsMultiplier()); + crcForUpgradeType.addInt(getMaxHpRegeneration()); + + crcForUpgradeType.addInt(getSight()); + crcForUpgradeType.addInt(getSightIsMultiplier()); + + crcForUpgradeType.addInt(getMaxEp()); + crcForUpgradeType.addInt(getMaxEpIsMultiplier()); + crcForUpgradeType.addInt(getMaxEpRegeneration()); + + crcForUpgradeType.addInt(getArmor()); + crcForUpgradeType.addInt(getArmorIsMultiplier()); + + crcForUpgradeType.addInt(getAttackStrength()); + crcForUpgradeType.addInt(getAttackStrengthIsMultiplier()); + // std::map attackStrengthMultiplierValueList; + crcForUpgradeType.addInt64((int64)attackStrengthMultiplierValueList.size()); + + crcForUpgradeType.addInt(getAttackRange()); + crcForUpgradeType.addInt(getAttackRangeIsMultiplier()); + // std::map attackRangeMultiplierValueList; + crcForUpgradeType.addInt64((int64)attackRangeMultiplierValueList.size()); + + crcForUpgradeType.addInt(getMoveSpeed()); + crcForUpgradeType.addInt(getMoveSpeedIsMultiplier()); + // std::map moveSpeedIsMultiplierValueList; + crcForUpgradeType.addInt64((int64)moveSpeedIsMultiplierValueList.size()); + + crcForUpgradeType.addInt(getProdSpeed()); + crcForUpgradeType.addInt(getProdSpeedIsMultiplier()); + // std::map prodSpeedProduceIsMultiplierValueList; + crcForUpgradeType.addInt64( + (int64)prodSpeedProduceIsMultiplierValueList.size()); + // std::map prodSpeedUpgradeIsMultiplierValueList; + crcForUpgradeType.addInt64( + (int64)prodSpeedUpgradeIsMultiplierValueList.size()); + // std::map prodSpeedMorphIsMultiplierValueList; + crcForUpgradeType.addInt64( + (int64)prodSpeedMorphIsMultiplierValueList.size()); + + crcForUpgradeType.addInt(getAttackSpeed()); + crcForUpgradeType.addInt(getAttackSpeedIsMultiplier()); + + return crcForUpgradeType; + } }; /** - * Represents the type of upgrade. That is, the single upgrade as it appears in the faction's XML - * files. Each upgrade has a single `UpgradeType`. Contains information about what units are - * affected by the upgrade. + * Represents the type of upgrade. That is, the single upgrade as it appears in + * the faction's XML files. Each upgrade has a single `UpgradeType`. Contains + * information about what units are affected by the upgrade. */ -class UpgradeType: public UpgradeTypeBase, public ProducibleType { +class UpgradeType : public UpgradeTypeBase, public ProducibleType { private: - /** - * Set of unit types (the "classes" of units, eg, swordman) that are affected by this upgrade. - */ - std::set effects; - std::set tags; + /** + * Set of unit types (the "classes" of units, eg, swordman) that are affected + * by this upgrade. + */ + std::set effects; + std::set tags; public: - /** - * Sets the upgrade name to the directory name (the base name of `dir`). - * @param dir Path of the upgrade directory. - */ - void preLoad(const string &dir); - - /** - * Loads an upgrade from an XML file. - * @param dir Path of the upgrade directory. The file name is determined from this. - * @param techTree The techtree that this upgrade is in. Used to access the common data - * directory and to access resources. - * @param factionType The faction type (a unique type for each faction) that the upgrade belongs - * to. Used for accessing unit types that are in the unit requirements list. - * @param checksum Will have the checksum of the upgrade path added to it (treated the same way - * as the `techtreeChecksum`). - * @param techtreeChecksum Cumulative checksum for the techtree. The path of loaded upgrades - * is added to this checksum. - */ - void load(const string &dir, const TechTree *techTree, - const FactionType *factionType, Checksum* checksum, - Checksum* techtreeChecksum, - std::map > > &loadedFileList, - bool validationMode=false); - - /** - * Obtains the upgrade name. - * @param translatedValue If true, the name is translated. Otherwise the name is returned as it - * appears in the XMLs. - */ - virtual string getName(bool translatedValue=false) const; - string getTagName(string tag, bool translatedValue=false) const; - - /** - * Determines if a unit is affected by this upgrade. - * @param unitType The UnitType we are checking (to see if they're affected). - * @return True if the unit is affected, false otherwise. - */ - bool isAffected(const UnitType *unitType) const; - - /** - * Creates a description for this upgrade. Lists the affected units. - */ - virtual string getReqDesc(bool translatedValue) const; - - //virtual void saveGame(XmlNode *rootNode) const; - //virtual void loadGame(const XmlNode *rootNode); + /** + * Sets the upgrade name to the directory name (the base name of `dir`). + * @param dir Path of the upgrade directory. + */ + void preLoad(const string &dir); + + /** + * Loads an upgrade from an XML file. + * @param dir Path of the upgrade directory. The file name is determined from + * this. + * @param techTree The techtree that this upgrade is in. Used to access the + * common data directory and to access resources. + * @param factionType The faction type (a unique type for each faction) that + * the upgrade belongs to. Used for accessing unit types that are in the unit + * requirements list. + * @param checksum Will have the checksum of the upgrade path added to it + * (treated the same way as the `techtreeChecksum`). + * @param techtreeChecksum Cumulative checksum for the techtree. The path of + * loaded upgrades is added to this checksum. + */ + void load(const string &dir, const TechTree *techTree, + const FactionType *factionType, Checksum *checksum, + Checksum *techtreeChecksum, + std::map>> &loadedFileList, + bool validationMode = false); + + /** + * Obtains the upgrade name. + * @param translatedValue If true, the name is translated. Otherwise the name + * is returned as it appears in the XMLs. + */ + virtual string getName(bool translatedValue = false) const; + string getTagName(string tag, bool translatedValue = false) const; + + /** + * Determines if a unit is affected by this upgrade. + * @param unitType The UnitType we are checking (to see if they're affected). + * @return True if the unit is affected, false otherwise. + */ + bool isAffected(const UnitType *unitType) const; + + /** + * Creates a description for this upgrade. Lists the affected units. + */ + virtual string getReqDesc(bool translatedValue) const; + + // virtual void saveGame(XmlNode *rootNode) const; + // virtual void loadGame(const XmlNode *rootNode); }; /** - * Keeps track of the cumulative effects of upgrades on units. This allows us to apply multiple - * upgrades to a unit with the effects stacking. + * Keeps track of the cumulative effects of upgrades on units. This allows us to + * apply multiple upgrades to a unit with the effects stacking. */ -class TotalUpgrade: public UpgradeTypeBase { +class TotalUpgrade : public UpgradeTypeBase { private: - - // List of boosts - const UpgradeTypeBase *boostUpgradeBase; - int boostUpgradeSourceUnit; - int boostUpgradeDestUnit; - std::vector boostUpgrades; + // List of boosts + const UpgradeTypeBase *boostUpgradeBase; + int boostUpgradeSourceUnit; + int boostUpgradeDestUnit; + std::vector boostUpgrades; public: - TotalUpgrade(); - virtual ~TotalUpgrade() {} - - /** - * Resets all stat boosts (so there's effectively no upgrade). - */ - void reset(); - - /** - * Adds an upgrade to this one, stacking the effects. Note that multipliers are stacked - * by multiplying by the original, unboosted amount, and then adding that to the TotalUpgrade. - * @param ut The upgrade to apply. - * @param unit The unit this TotalUpgrade is associated with (since when we use a multiplier, - * the stats raise by an amount relative to the unit's base stats). - */ - void sum(const UpgradeTypeBase *ut, const Unit *unit, bool boostMode=false); - - /** - * Increases the level of the unit. Doing so results in their HP, EP, and armour going up by - * 50% while their sight goes up by 20%. - * @param ut The unit type to get the original stats from (so we can determine just how much - * to increase the stats by on level up). - */ - void incLevel(const UnitType *ut); - - /** - * Applies the upgrade. Just a delegate to TotalUpgrade::sum. - */ - void apply(int sourceUnitId, const UpgradeTypeBase *ut, const Unit *unit); - - /** - * Removes the effect of an upgrade to a specific unit. Using this after applying the upgrade - * is an invariant. ie, - * - * totalUpgrade->apply(upgrade, unit); - * totalUpgrade->deapply(upgrade, unit); - * // totalUpgrade is now the same as before the call to apply() - * - * @param ut The upgrade to remove. - * @param unit The unit this TotalUpgrade is associated with (since when we use a multiplier, - * the stats were raise by an amount relative to the unit's base stats). - */ - void deapply(int sourceUnitId, const UpgradeTypeBase *ut,int destUnitId); - - virtual int getMaxHp() const; - virtual int getMaxHpRegeneration() const; - virtual int getSight() const; - virtual int getMaxEp() const; - virtual int getMaxEpRegeneration() const; - virtual int getArmor() const; - virtual int getAttackStrength(const AttackSkillType *st) const; - virtual int getAttackRange(const AttackSkillType *st) const; - virtual int getMoveSpeed(const MoveSkillType *st) const; - virtual int getProdSpeed(const SkillType *st) const; - virtual int getAttackSpeed(const AttackSkillType *st) const; - - virtual int getMaxHpFromBoosts() const; - virtual int getMaxHpRegenerationFromBoosts() const; - virtual int getSightFromBoosts() const; - virtual int getMaxEpFromBoosts() const; - virtual int getMaxEpRegenerationFromBoosts() const; - virtual int getArmorFromBoosts() const; - virtual int getAttackStrengthFromBoosts(const AttackSkillType *st) const; - virtual int getAttackRangeFromBoosts(const AttackSkillType *st) const; - virtual int getMoveSpeedFromBoosts(const MoveSkillType *st) const; - virtual int getProdSpeedFromBoosts(const SkillType *st) const; - virtual int getAttackSpeedFromBoosts(const AttackSkillType *st) const; - - /** - * Creates the XML for the save game file. Essentially just stores everything about its state. - * @rootNode The node of the unit that this TotalUpgrade object belongs to. - */ - void saveGame(XmlNode *rootNode) const; - - /** - * Reloads the object's state from a saved game. - * @rootNode The node of the unit that this TotalUpgrade object belongs to. - */ - void loadGame(const XmlNode *rootNode); + TotalUpgrade(); + virtual ~TotalUpgrade() {} + + /** + * Resets all stat boosts (so there's effectively no upgrade). + */ + void reset(); + + /** + * Adds an upgrade to this one, stacking the effects. Note that multipliers + * are stacked by multiplying by the original, unboosted amount, and then + * adding that to the TotalUpgrade. + * @param ut The upgrade to apply. + * @param unit The unit this TotalUpgrade is associated with (since when we + * use a multiplier, the stats raise by an amount relative to the unit's base + * stats). + */ + void sum(const UpgradeTypeBase *ut, const Unit *unit, bool boostMode = false); + + /** + * Increases the level of the unit. Doing so results in their HP, EP, and + * armour going up by 50% while their sight goes up by 20%. + * @param ut The unit type to get the original stats from (so we can determine + * just how much to increase the stats by on level up). + */ + void incLevel(const UnitType *ut); + + /** + * Applies the upgrade. Just a delegate to TotalUpgrade::sum. + */ + void apply(int sourceUnitId, const UpgradeTypeBase *ut, const Unit *unit); + + /** + * Removes the effect of an upgrade to a specific unit. Using this after + * applying the upgrade is an invariant. ie, + * + * totalUpgrade->apply(upgrade, unit); + * totalUpgrade->deapply(upgrade, unit); + * // totalUpgrade is now the same as before the call to apply() + * + * @param ut The upgrade to remove. + * @param unit The unit this TotalUpgrade is associated with (since when we + * use a multiplier, the stats were raise by an amount relative to the unit's + * base stats). + */ + void deapply(int sourceUnitId, const UpgradeTypeBase *ut, int destUnitId); + + virtual int getMaxHp() const; + virtual int getMaxHpRegeneration() const; + virtual int getSight() const; + virtual int getMaxEp() const; + virtual int getMaxEpRegeneration() const; + virtual int getArmor() const; + virtual int getAttackStrength(const AttackSkillType *st) const; + virtual int getAttackRange(const AttackSkillType *st) const; + virtual int getMoveSpeed(const MoveSkillType *st) const; + virtual int getProdSpeed(const SkillType *st) const; + virtual int getAttackSpeed(const AttackSkillType *st) const; + + virtual int getMaxHpFromBoosts() const; + virtual int getMaxHpRegenerationFromBoosts() const; + virtual int getSightFromBoosts() const; + virtual int getMaxEpFromBoosts() const; + virtual int getMaxEpRegenerationFromBoosts() const; + virtual int getArmorFromBoosts() const; + virtual int getAttackStrengthFromBoosts(const AttackSkillType *st) const; + virtual int getAttackRangeFromBoosts(const AttackSkillType *st) const; + virtual int getMoveSpeedFromBoosts(const MoveSkillType *st) const; + virtual int getProdSpeedFromBoosts(const SkillType *st) const; + virtual int getAttackSpeedFromBoosts(const AttackSkillType *st) const; + + /** + * Creates the XML for the save game file. Essentially just stores everything + * about its state. + * @rootNode The node of the unit that this TotalUpgrade object belongs to. + */ + void saveGame(XmlNode *rootNode) const; + + /** + * Reloads the object's state from a saved game. + * @rootNode The node of the unit that this TotalUpgrade object belongs to. + */ + void loadGame(const XmlNode *rootNode); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/world/map.cpp b/source/glest_game/world/map.cpp index 5f8fe06e4..98ebbc6b4 100644 --- a/source/glest_game/world/map.cpp +++ b/source/glest_game/world/map.cpp @@ -14,109 +14,118 @@ #include -#include "tileset.h" -#include "unit.h" -#include "resource.h" -#include "logger.h" -#include "tech_tree.h" +#include "byte_order.h" +#include "command.h" #include "config.h" -#include "util.h" -#include "game_settings.h" -#include "platform_util.h" #include "faction.h" -#include "command.h" +#include "game_settings.h" +#include "leak_dumper.h" +#include "logger.h" #include "map_preview.h" +#include "platform_util.h" +#include "resource.h" +#include "tech_tree.h" +#include "tileset.h" +#include "unit.h" +#include "util.h" #include "world.h" -#include "byte_order.h" -#include "leak_dumper.h" using namespace Shared::Graphics; using namespace Shared::Util; using namespace Shared::Platform; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class Cell // ===================================================== Cell::Cell() { - //game data - for(int i = 0; i < fieldCount; ++i) { - units[i]= NULL; - unitsWithEmptyCellMap[i]=NULL; - } - height= 0; + // game data + for (int i = 0; i < fieldCount; ++i) { + units[i] = NULL; + unitsWithEmptyCellMap[i] = NULL; + } + height = 0; } // ==================== misc ==================== -//returns if the cell is free +// returns if the cell is free -//returns if the cell is free +// returns if the cell is free void Cell::saveGame(XmlNode *rootNode, int index) const { - bool saveCell = false; - //if(saveCell == false) { - for(unsigned int i = 0; i < fieldCount; ++i) { - if(units[i] != NULL) { - saveCell = true; - break; - } - if(unitsWithEmptyCellMap[i] != NULL) { - saveCell = true; - break; - } - } - //} - - if(saveCell == true) { - std::map mapTagReplacements; - XmlNode *cellNode = rootNode->addChild("Cell" + intToStr(index)); - cellNode->addAttribute("index",intToStr(index), mapTagReplacements); - - // Unit *units[fieldCount]; //units on this cell - for(unsigned int i = 0; i < fieldCount; ++i) { - if(units[i] != NULL) { - XmlNode *unitsNode = cellNode->addChild("units"); - unitsNode->addAttribute("field",intToStr(i), mapTagReplacements); - unitsNode->addAttribute("unitid",intToStr(units[i]->getId()), mapTagReplacements); - } - } - // Unit *unitsWithEmptyCellMap[fieldCount]; //units with an empty cellmap on this cell - for(unsigned int i = 0; i < fieldCount; ++i) { - if(unitsWithEmptyCellMap[i] != NULL) { - XmlNode *unitsWithEmptyCellMapNode = cellNode->addChild("unitsWithEmptyCellMap"); - unitsWithEmptyCellMapNode->addAttribute("field",intToStr(i), mapTagReplacements); - unitsWithEmptyCellMapNode->addAttribute("unitid",intToStr(unitsWithEmptyCellMap[i]->getId()), mapTagReplacements); - } - } - - // float height; - cellNode->addAttribute("height",floatToStr(getHeight(),6), mapTagReplacements); - } + bool saveCell = false; + // if(saveCell == false) { + for (unsigned int i = 0; i < fieldCount; ++i) { + if (units[i] != NULL) { + saveCell = true; + break; + } + if (unitsWithEmptyCellMap[i] != NULL) { + saveCell = true; + break; + } + } + //} + + if (saveCell == true) { + std::map mapTagReplacements; + XmlNode *cellNode = rootNode->addChild("Cell" + intToStr(index)); + cellNode->addAttribute("index", intToStr(index), mapTagReplacements); + + // Unit *units[fieldCount]; //units on this cell + for (unsigned int i = 0; i < fieldCount; ++i) { + if (units[i] != NULL) { + XmlNode *unitsNode = cellNode->addChild("units"); + unitsNode->addAttribute("field", intToStr(i), mapTagReplacements); + unitsNode->addAttribute("unitid", intToStr(units[i]->getId()), + mapTagReplacements); + } + } + // Unit *unitsWithEmptyCellMap[fieldCount]; //units with an empty + // cellmap on this cell + for (unsigned int i = 0; i < fieldCount; ++i) { + if (unitsWithEmptyCellMap[i] != NULL) { + XmlNode *unitsWithEmptyCellMapNode = + cellNode->addChild("unitsWithEmptyCellMap"); + unitsWithEmptyCellMapNode->addAttribute("field", intToStr(i), + mapTagReplacements); + unitsWithEmptyCellMapNode->addAttribute( + "unitid", intToStr(unitsWithEmptyCellMap[i]->getId()), + mapTagReplacements); + } + } + + // float height; + cellNode->addAttribute("height", floatToStr(getHeight(), 6), + mapTagReplacements); + } } void Cell::loadGame(const XmlNode *rootNode, int index, World *world) { - if(rootNode->hasChild("Cell" + intToStr(index)) == true) { - const XmlNode *cellNode = rootNode->getChild("Cell" + intToStr(index)); - - unsigned int unitCount = (unsigned int)cellNode->getChildCount(); - for(unsigned int i = 0; i < unitCount; ++i) { - if(cellNode->hasChildAtIndex("units",i) == true) { - const XmlNode *unitsNode = cellNode->getChild("units",i); - int field = unitsNode->getAttribute("field")->getIntValue(); - int unitId = unitsNode->getAttribute("unitid")->getIntValue(); - units[field] = world->findUnitById(unitId); - } - if(cellNode->hasChildAtIndex("unitsWithEmptyCellMap",i) == true) { - const XmlNode *unitsNode = cellNode->getChild("unitsWithEmptyCellMap",i); - int field = unitsNode->getAttribute("field")->getIntValue(); - int unitId = unitsNode->getAttribute("unitid")->getIntValue(); - unitsWithEmptyCellMap[field] = world->findUnitById(unitId); - } - } - } + if (rootNode->hasChild("Cell" + intToStr(index)) == true) { + const XmlNode *cellNode = rootNode->getChild("Cell" + intToStr(index)); + + unsigned int unitCount = (unsigned int)cellNode->getChildCount(); + for (unsigned int i = 0; i < unitCount; ++i) { + if (cellNode->hasChildAtIndex("units", i) == true) { + const XmlNode *unitsNode = cellNode->getChild("units", i); + int field = unitsNode->getAttribute("field")->getIntValue(); + int unitId = unitsNode->getAttribute("unitid")->getIntValue(); + units[field] = world->findUnitById(unitId); + } + if (cellNode->hasChildAtIndex("unitsWithEmptyCellMap", i) == true) { + const XmlNode *unitsNode = + cellNode->getChild("unitsWithEmptyCellMap", i); + int field = unitsNode->getAttribute("field")->getIntValue(); + int unitId = unitsNode->getAttribute("unitid")->getIntValue(); + unitsWithEmptyCellMap[field] = world->findUnitById(unitId); + } + } + } } // ===================================================== @@ -124,210 +133,240 @@ void Cell::loadGame(const XmlNode *rootNode, int index, World *world) { // ===================================================== SurfaceCell::SurfaceCell() { - object= NULL; - vertex= Vec3f(0.f); - normal= Vec3f(0.f, 1.f, 0.f); - surfaceType= -1; - surfaceTexture= NULL; - nearSubmerged = false; - cellChangedFromOriginalMapLoad = false; - - for(int index = 0; index < GameConstants::maxPlayers + GameConstants::specialFactions; ++index) { - setVisible(index,false); - setExplored(index,false); - } + object = NULL; + vertex = Vec3f(0.f); + normal = Vec3f(0.f, 1.f, 0.f); + surfaceType = -1; + surfaceTexture = NULL; + nearSubmerged = false; + cellChangedFromOriginalMapLoad = false; + + for (int index = 0; + index < GameConstants::maxPlayers + GameConstants::specialFactions; + ++index) { + setVisible(index, false); + setExplored(index, false); + } } SurfaceCell::~SurfaceCell() { - delete object; - object=NULL; + delete object; + object = NULL; } -void SurfaceCell::end(){ - if(object!=NULL){ - object->end(); - } +void SurfaceCell::end() { + if (object != NULL) { + object->end(); + } } void SurfaceCell::deleteResource() { - cellChangedFromOriginalMapLoad = true; + cellChangedFromOriginalMapLoad = true; - delete object; - object= NULL; + delete object; + object = NULL; } -void SurfaceCell::setHeight(float height, bool cellChangedFromOriginalMapLoadValue) { - height = truncateDecimal(height); - vertex.y= height; - if(cellChangedFromOriginalMapLoadValue == true) { - this->cellChangedFromOriginalMapLoad = true; - } +void SurfaceCell::setHeight(float height, + bool cellChangedFromOriginalMapLoadValue) { + height = truncateDecimal(height); + vertex.y = height; + if (cellChangedFromOriginalMapLoadValue == true) { + this->cellChangedFromOriginalMapLoad = true; + } } bool SurfaceCell::decAmount(int value) { - cellChangedFromOriginalMapLoad = true; + cellChangedFromOriginalMapLoad = true; - return object->getResource()->decAmount(value); + return object->getResource()->decAmount(value); } void SurfaceCell::setExplored(int teamIndex, bool explored) { - if(teamIndex < 0 || teamIndex >= GameConstants::maxPlayers + GameConstants::specialFactions) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Invalid value for teamIndex [%d]",teamIndex); - printf("%s\n",szBuf); - throw megaglest_runtime_error(szBuf); - } - - this->explored[teamIndex]= explored; - //printf("Setting explored to %d for teamIndex %d\n",explored,teamIndex); + if (teamIndex < 0 || + teamIndex >= GameConstants::maxPlayers + GameConstants::specialFactions) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "Invalid value for teamIndex [%d]", teamIndex); + printf("%s\n", szBuf); + throw megaglest_runtime_error(szBuf); + } + + this->explored[teamIndex] = explored; + // printf("Setting explored to %d for teamIndex %d\n",explored,teamIndex); } void SurfaceCell::setVisible(int teamIndex, bool visible) { - if(teamIndex < 0 || teamIndex >= GameConstants::maxPlayers + GameConstants::specialFactions) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Invalid value for teamIndex [%d]",teamIndex); - printf("%s\n",szBuf); - throw megaglest_runtime_error(szBuf); - } - - this->visible[teamIndex]= visible; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && - SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax).enabled == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In setVisible() teamIndex %d visible %d",teamIndex,visible); - -// if(frameIndex < 0) { -// unit->logSynchData(__FILE__,__LINE__,szBuf); -// } -// else { -// unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); -// } - - if(Thread::isCurrentThreadMainThread()) { - //unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); - SystemFlags::OutputDebug(SystemFlags::debugWorldSynch,szBuf); - } - else { - //unit->logSynchData(__FILE__,__LINE__,szBuf); - printf("%s",szBuf); - } - - } - + if (teamIndex < 0 || + teamIndex >= GameConstants::maxPlayers + GameConstants::specialFactions) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "Invalid value for teamIndex [%d]", teamIndex); + printf("%s\n", szBuf); + throw megaglest_runtime_error(szBuf); + } + + this->visible[teamIndex] = visible; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == + true && + SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax) + .enabled == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In setVisible() teamIndex %d visible %d", teamIndex, + visible); + + // if(frameIndex < 0) { + // unit->logSynchData(__FILE__,__LINE__,szBuf); + // } + // else { + // unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); + // } + + if (Thread::isCurrentThreadMainThread()) { + // unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); + SystemFlags::OutputDebug(SystemFlags::debugWorldSynch, szBuf); + } else { + // unit->logSynchData(__FILE__,__LINE__,szBuf); + printf("%s", szBuf); + } + } } -string SurfaceCell::isVisibleString() const { - string result = "isVisibleList = "; - for(int index = 0; index < GameConstants::maxPlayers + GameConstants::specialFactions; ++index) { - result += string(visible[index] ? "true" : "false"); - } - return result; +string SurfaceCell::isVisibleString() const { + string result = "isVisibleList = "; + for (int index = 0; + index < GameConstants::maxPlayers + GameConstants::specialFactions; + ++index) { + result += string(visible[index] ? "true" : "false"); + } + return result; } string SurfaceCell::isExploredString() const { - string result = "isExploredList = "; - for(int index = 0; index < GameConstants::maxPlayers + GameConstants::specialFactions; ++index) { - result += string(explored[index] ? "true" : "false"); - } - return result; + string result = "isExploredList = "; + for (int index = 0; + index < GameConstants::maxPlayers + GameConstants::specialFactions; + ++index) { + result += string(explored[index] ? "true" : "false"); + } + return result; } -void SurfaceCell::saveGame(XmlNode *rootNode,int index) const { - bool saveCell = (this->getCellChangedFromOriginalMapLoad() == true); - - if(saveCell == true) { - std::map mapTagReplacements; - XmlNode *surfaceCellNode = rootNode->addChild("SurfaceCell" + intToStr(index)); - surfaceCellNode->addAttribute("index",intToStr(index), mapTagReplacements); - - // //geometry - // Vec3f vertex; - surfaceCellNode->addAttribute("vertex",vertex.getString(), mapTagReplacements); - // Vec3f normal; - //surfaceCellNode->addAttribute("normal",normal.getString(), mapTagReplacements); - // Vec3f color; - //surfaceCellNode->addAttribute("color",color.getString(), mapTagReplacements); - // - // //tex coords - // Vec2f fowTexCoord; //tex coords for TEXTURE1 when multitexturing and fogOfWar - //surfaceCellNode->addAttribute("fowTexCoord",fowTexCoord.getString(), mapTagReplacements); - // Vec2f surfTexCoord; //tex coords for TEXTURE0 - //surfaceCellNode->addAttribute("surfTexCoord",surfTexCoord.getString(), mapTagReplacements); - // //surface - // int surfaceType; - //surfaceCellNode->addAttribute("surfaceType",intToStr(surfaceType), mapTagReplacements); - // const Texture2D *surfaceTexture; - // - // //object & resource - // Object *object; - if(object != NULL) { - object->saveGame(surfaceCellNode); - } - else { - XmlNode *objectNode = surfaceCellNode->addChild("Object"); - objectNode->addAttribute("isDeleted",intToStr(true), mapTagReplacements); - } - // //visibility - // bool visible[GameConstants::maxPlayers + GameConstants::specialFactions]; -// for(unsigned int i = 0; i < GameConstants::maxPlayers; ++i) { -// if(visible[i] == true) { -// XmlNode *visibleNode = surfaceCellNode->addChild("visible"); -// visibleNode->addAttribute("index",intToStr(i), mapTagReplacements); -// visibleNode->addAttribute("value",intToStr(visible[i]), mapTagReplacements); -// } -// } -// // bool explored[GameConstants::maxPlayers + GameConstants::specialFactions]; -// for(unsigned int i = 0; i < GameConstants::maxPlayers; ++i) { -// if(explored[i] == true) { -// XmlNode *exploredNode = surfaceCellNode->addChild("explored"); -// exploredNode->addAttribute("index",intToStr(i), mapTagReplacements); -// exploredNode->addAttribute("value",intToStr(explored[i]), mapTagReplacements); -// } -// } - - // //cache - // bool nearSubmerged; - //surfaceCellNode->addAttribute("nearSubmerged",intToStr(nearSubmerged), mapTagReplacements); - } +void SurfaceCell::saveGame(XmlNode *rootNode, int index) const { + bool saveCell = (this->getCellChangedFromOriginalMapLoad() == true); + + if (saveCell == true) { + std::map mapTagReplacements; + XmlNode *surfaceCellNode = + rootNode->addChild("SurfaceCell" + intToStr(index)); + surfaceCellNode->addAttribute("index", intToStr(index), mapTagReplacements); + + // //geometry + // Vec3f vertex; + surfaceCellNode->addAttribute("vertex", vertex.getString(), + mapTagReplacements); + // Vec3f normal; + // surfaceCellNode->addAttribute("normal",normal.getString(), + // mapTagReplacements); + // Vec3f color; + // surfaceCellNode->addAttribute("color",color.getString(), + // mapTagReplacements); + // + // //tex coords + // Vec2f fowTexCoord; //tex coords for TEXTURE1 when multitexturing + //and fogOfWar + // surfaceCellNode->addAttribute("fowTexCoord",fowTexCoord.getString(), + // mapTagReplacements); + // Vec2f surfTexCoord; //tex coords for TEXTURE0 + // surfaceCellNode->addAttribute("surfTexCoord",surfTexCoord.getString(), + // mapTagReplacements); + // //surface + // int surfaceType; + // surfaceCellNode->addAttribute("surfaceType",intToStr(surfaceType), + // mapTagReplacements); + // const Texture2D *surfaceTexture; + // + // //object & resource + // Object *object; + if (object != NULL) { + object->saveGame(surfaceCellNode); + } else { + XmlNode *objectNode = surfaceCellNode->addChild("Object"); + objectNode->addAttribute("isDeleted", intToStr(true), mapTagReplacements); + } + // //visibility + // bool visible[GameConstants::maxPlayers + + // GameConstants::specialFactions]; + // for(unsigned int i = 0; i < GameConstants::maxPlayers; ++i) { + // if(visible[i] == true) { + // XmlNode *visibleNode = + // surfaceCellNode->addChild("visible"); + // visibleNode->addAttribute("index",intToStr(i), + // mapTagReplacements); + // visibleNode->addAttribute("value",intToStr(visible[i]), + // mapTagReplacements); + // } + // } + // // bool explored[GameConstants::maxPlayers + + // GameConstants::specialFactions]; for(unsigned int i = 0; i + // < GameConstants::maxPlayers; ++i) { if(explored[i] + // == true) { XmlNode *exploredNode = + //surfaceCellNode->addChild("explored"); + // exploredNode->addAttribute("index",intToStr(i), + // mapTagReplacements); + // exploredNode->addAttribute("value",intToStr(explored[i]), + // mapTagReplacements); + // } + // } + + // //cache + // bool nearSubmerged; + // surfaceCellNode->addAttribute("nearSubmerged",intToStr(nearSubmerged), + // mapTagReplacements); + } } void SurfaceCell::loadGame(const XmlNode *rootNode, int index, World *world) { - if(rootNode->hasChild("SurfaceCell" + intToStr(index)) == true) { - const XmlNode *surfaceCellNode = rootNode->getChild("SurfaceCell" + intToStr(index)); - - if(surfaceCellNode->hasAttribute("vertex") == true) { - vertex = Vec3f::strToVec3(surfaceCellNode->getAttribute("vertex")->getValue()); - } - - //int visibleCount = cellNode->getChildCount(); - XmlNode *objectNode = surfaceCellNode->getChild("Object"); - if(objectNode->hasAttribute("isDeleted") == true) { - this->deleteResource(); - } - else { - object->loadGame(surfaceCellNode,world->getTechTree()); - } - - //printf("Loading game, sc index [%d][%d]\n",index,visibleCount); - -// for(unsigned int i = 0; i < visibleCount; ++i) { -// if(cellNode->hasChildAtIndex("visible",i) == true) { -// const XmlNode *visibleNode = cellNode->getChild("visible",i); -// int indexCell = visibleNode->getAttribute("index")->getIntValue(); -// bool value = visibleNode->getAttribute("value")->getIntValue(); -// visible[indexCell] = value; -// -// //printf("Loading game, sc visible index [%d][%d][%d]\n",index,indexCell,value); -// } -// if(cellNode->hasChildAtIndex("explored",i) == true) { -// const XmlNode *exploredNode = cellNode->getChild("explored",i); -// int indexCell = exploredNode->getAttribute("index")->getIntValue(); -// bool value = exploredNode->getAttribute("value")->getIntValue(); -// explored[indexCell] = value; -// -// //printf("Loading game, sc explored cell index [%d] exploredIndex [%d] value [%d]\n",index,indexCell,value); -// } -// } - } + if (rootNode->hasChild("SurfaceCell" + intToStr(index)) == true) { + const XmlNode *surfaceCellNode = + rootNode->getChild("SurfaceCell" + intToStr(index)); + + if (surfaceCellNode->hasAttribute("vertex") == true) { + vertex = + Vec3f::strToVec3(surfaceCellNode->getAttribute("vertex")->getValue()); + } + + // int visibleCount = cellNode->getChildCount(); + XmlNode *objectNode = surfaceCellNode->getChild("Object"); + if (objectNode->hasAttribute("isDeleted") == true) { + this->deleteResource(); + } else { + object->loadGame(surfaceCellNode, world->getTechTree()); + } + + // printf("Loading game, sc index [%d][%d]\n",index,visibleCount); + + // for(unsigned int i = 0; i < visibleCount; ++i) { + // if(cellNode->hasChildAtIndex("visible",i) == true) { + // const XmlNode *visibleNode = + // cellNode->getChild("visible",i); int indexCell + // = visibleNode->getAttribute("index")->getIntValue(); + // bool value = visibleNode->getAttribute("value")->getIntValue(); + // visible[indexCell] = value; + // + // //printf("Loading game, sc visible index + //[%d][%d][%d]\n",index,indexCell,value); + // } + // if(cellNode->hasChildAtIndex("explored",i) == true) { + // const XmlNode *exploredNode = + // cellNode->getChild("explored",i); int indexCell + // = exploredNode->getAttribute("index")->getIntValue(); + // bool value = exploredNode->getAttribute("value")->getIntValue(); + // explored[indexCell] = value; + // + // //printf("Loading game, sc explored cell index [%d] + //exploredIndex + //[%d] value [%d]\n",index,indexCell,value); + // } + // } + } } // ===================================================== // class Map @@ -335,464 +374,529 @@ void SurfaceCell::loadGame(const XmlNode *rootNode, int index, World *world) { // ===================== PUBLIC ======================== -const int Map::cellScale= 2; -const int Map::mapScale= 2; +const int Map::cellScale = 2; +const int Map::mapScale = 2; Map::Map() { - cells= NULL; - surfaceCells= NULL; - startLocations= NULL; - - title=""; - waterLevel=0; - heightFactor=0; - cliffLevel=0; - cameraHeight=0; - w=0; - h=0; - surfaceW=0; - surfaceH=0; - surfaceSize=(surfaceW * surfaceH); - maxPlayers=0; - maxMapHeight=0; + cells = NULL; + surfaceCells = NULL; + startLocations = NULL; + + title = ""; + waterLevel = 0; + heightFactor = 0; + cliffLevel = 0; + cameraHeight = 0; + w = 0; + h = 0; + surfaceW = 0; + surfaceH = 0; + surfaceSize = (surfaceW * surfaceH); + maxPlayers = 0; + maxMapHeight = 0; } Map::~Map() { - Logger::getInstance().add(Lang::getInstance().getString("LogScreenGameUnLoadingMapCells","",true), true); - - delete [] cells; - cells = NULL; - delete [] surfaceCells; - surfaceCells = NULL; - delete [] startLocations; - startLocations = NULL; + Logger::getInstance().add( + Lang::getInstance().getString("LogScreenGameUnLoadingMapCells", "", true), + true); + + delete[] cells; + cells = NULL; + delete[] surfaceCells; + surfaceCells = NULL; + delete[] startLocations; + startLocations = NULL; } -void Map::end(){ - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - Logger::getInstance().add(Lang::getInstance().getString("LogScreenGameUnLoadingMap","",true), true); - //read heightmap - for(int j = 0; j < surfaceH; ++j) { - for(int i = 0; i < surfaceW; ++i) { - getSurfaceCell(i, j)->end(); - } - } - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); +void Map::end() { + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + Logger::getInstance().add( + Lang::getInstance().getString("LogScreenGameUnLoadingMap", "", true), + true); + // read heightmap + for (int j = 0; j < surfaceH; ++j) { + for (int i = 0; i < surfaceW; ++i) { + getSurfaceCell(i, j)->end(); + } + } + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); } Vec2i Map::getStartLocation(int locationIndex) const { - if(locationIndex >= maxPlayers) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"locationIndex >= maxPlayers [%d] [%d]",locationIndex, maxPlayers); - printf("%s\n",szBuf); - throw megaglest_runtime_error(szBuf); - //assert(locationIndex < maxPlayers); - } - else if(startLocations == NULL) { - throw megaglest_runtime_error("startLocations == NULL"); - } - - return startLocations[locationIndex]; + if (locationIndex >= maxPlayers) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "locationIndex >= maxPlayers [%d] [%d]", + locationIndex, maxPlayers); + printf("%s\n", szBuf); + throw megaglest_runtime_error(szBuf); + // assert(locationIndex < maxPlayers); + } else if (startLocations == NULL) { + throw megaglest_runtime_error("startLocations == NULL"); + } + + return startLocations[locationIndex]; } Checksum Map::load(const string &path, TechTree *techTree, Tileset *tileset) { - Checksum mapChecksum; - try{ + Checksum mapChecksum; + try { #ifdef WIN32 - FILE *f= _wfopen(utf8_decode(path).c_str(), L"rb"); + FILE *f = _wfopen(utf8_decode(path).c_str(), L"rb"); #else - FILE *f = fopen(path.c_str(), "rb"); + FILE *f = fopen(path.c_str(), "rb"); #endif - if(f != NULL) { - mapFile = path; - - mapChecksum.addFile(path); - checksumValue.addFile(path); - //read header - MapFileHeader header; - size_t readBytes = fread(&header, sizeof(MapFileHeader), 1, f); - if(readBytes != 1) { - throw megaglest_runtime_error("Invalid map header detected for file: " + path); - } - fromEndianMapFileHeader(header); - - if(next2Power(header.width) != header.width){ - throw megaglest_runtime_error("Map width is not a power of 2"); - } - - if(next2Power(header.height) != header.height){ - throw megaglest_runtime_error("Map height is not a power of 2"); - } - - heightFactor= header.heightFactor; - if(heightFactor>100){ - heightFactor=heightFactor/100; - heightFactor = truncateDecimal(heightFactor,6); - } - waterLevel= static_cast((header.waterLevel-0.01f)/heightFactor); - waterLevel = truncateDecimal(waterLevel,6); - title= header.title; - maxPlayers= header.maxFactions; - - surfaceW= header.width; - surfaceH= header.height; - surfaceSize=(surfaceW * surfaceH); - - w= surfaceW*cellScale; - h= surfaceH*cellScale; - cliffLevel = 0; - cameraHeight = 0; - if(header.version==1){ - //desc = header.description; - } - else if(header.version==2){ - //desc = header.version2.short_desc; - if(header.version2.cliffLevel > 0 && header.version2.cliffLevel < 5000){ - cliffLevel=static_cast((header.version2.cliffLevel-0.01f)/(heightFactor)); - cliffLevel = truncateDecimal(cliffLevel,6); - } - if(header.version2.cameraHeight > 0 && header.version2.cameraHeight < 5000) { - cameraHeight = header.version2.cameraHeight; - } - } - - //start locations - startLocations= new Vec2i[maxPlayers]; - for(int i=0; i < maxPlayers; ++i) { - int x=0, y=0; - readBytes = fread(&x, sizeof(int32), 1, f); - if(readBytes != 1) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " on line: %d.",readBytes,__LINE__); - throw megaglest_runtime_error(szBuf); - } - x = ::Shared::PlatformByteOrder::fromCommonEndian(x); - - readBytes = fread(&y, sizeof(int32), 1, f); - if(readBytes != 1) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " on line: %d.",readBytes,__LINE__); - throw megaglest_runtime_error(szBuf); - } - y = ::Shared::PlatformByteOrder::fromCommonEndian(y); - - startLocations[i]= Vec2i(x, y)*cellScale; - } - - //cells - cells= new Cell[getCellArraySize()]; - surfaceCells= new SurfaceCell[getSurfaceCellArraySize()]; - - //read heightmap - for(int j = 0; j < surfaceH; ++j) { - for(int i = 0; i < surfaceW; ++i) { - float32 alt=0; - readBytes = fread(&alt, sizeof(float32), 1, f); - if(readBytes != 1) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " on line: %d.",readBytes,__LINE__); - throw megaglest_runtime_error(szBuf); - } - alt = ::Shared::PlatformByteOrder::fromCommonEndian(alt); - - SurfaceCell *sc= getSurfaceCell(i, j); - sc->setVertex(Vec3f(i*mapScale, alt / heightFactor, j*mapScale)); - } - } - - //read surfaces - for(int j = 0; j < surfaceH; ++j) { - for(int i = 0; i < surfaceW; ++i) { - int8 surf=0; - readBytes = fread(&surf, sizeof(int8), 1, f); - if(readBytes != 1) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " on line: %d.",readBytes,__LINE__); - throw megaglest_runtime_error(szBuf); - } - surf = ::Shared::PlatformByteOrder::fromCommonEndian(surf); - - getSurfaceCell(i, j)->setSurfaceType(surf-1); - } - } - - //read objects and resources - for(int j = 0; j < h; j += cellScale) { - for(int i = 0; i < w; i += cellScale) { - - int8 objNumber=0; - readBytes = fread(&objNumber, sizeof(int8), 1, f); - if(readBytes != 1) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " on line: %d.",readBytes,__LINE__); - throw megaglest_runtime_error(szBuf); - } - objNumber = ::Shared::PlatformByteOrder::fromCommonEndian(objNumber); - - SurfaceCell *sc= getSurfaceCell(toSurfCoords(Vec2i(i, j))); - if(objNumber <= 0) { - sc->setObject(NULL); - } - else if(objNumber <= Tileset::objCount) { - Object *o= new Object(tileset->getObjectType(objNumber-1), sc->getVertex(),Vec2i(i, j)); - sc->setObject(o); - for(int k = 0; k < techTree->getResourceTypeCount(); ++k) { - const ResourceType *rt= techTree->getResourceType(k); - if(rt->getClass() == rcTileset && rt->getTilesetObject() == objNumber){ - o->setResource(rt, Vec2i(i, j)); - } - } - } - else{ - const ResourceType *rt= techTree->getTechResourceType(objNumber - Tileset::objCount) ; - Object *o= new Object(NULL, sc->getVertex(),Vec2i(i, j)); - o->setResource(rt, Vec2i(i, j)); - sc->setObject(o); - } - } - } - if(f) fclose(f); - } - else { - throw megaglest_runtime_error("Can't open file"); - } - } - catch(const exception &e){ - SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,e.what()); - throw megaglest_runtime_error("Error loading map: "+ path+ "\n"+ e.what()); - } - - return mapChecksum; + if (f != NULL) { + mapFile = path; + + mapChecksum.addFile(path); + checksumValue.addFile(path); + // read header + MapFileHeader header; + size_t readBytes = fread(&header, sizeof(MapFileHeader), 1, f); + if (readBytes != 1) { + throw megaglest_runtime_error("Invalid map header detected for file: " + + path); + } + fromEndianMapFileHeader(header); + + if (next2Power(header.width) != header.width) { + throw megaglest_runtime_error("Map width is not a power of 2"); + } + + if (next2Power(header.height) != header.height) { + throw megaglest_runtime_error("Map height is not a power of 2"); + } + + heightFactor = header.heightFactor; + if (heightFactor > 100) { + heightFactor = heightFactor / 100; + heightFactor = truncateDecimal(heightFactor, 6); + } + waterLevel = + static_cast((header.waterLevel - 0.01f) / heightFactor); + waterLevel = truncateDecimal(waterLevel, 6); + title = header.title; + maxPlayers = header.maxFactions; + + surfaceW = header.width; + surfaceH = header.height; + surfaceSize = (surfaceW * surfaceH); + + w = surfaceW * cellScale; + h = surfaceH * cellScale; + cliffLevel = 0; + cameraHeight = 0; + if (header.version == 1) { + // desc = header.description; + } else if (header.version == 2) { + // desc = header.version2.short_desc; + if (header.version2.cliffLevel > 0 && + header.version2.cliffLevel < 5000) { + cliffLevel = static_cast((header.version2.cliffLevel - 0.01f) / + (heightFactor)); + cliffLevel = truncateDecimal(cliffLevel, 6); + } + if (header.version2.cameraHeight > 0 && + header.version2.cameraHeight < 5000) { + cameraHeight = header.version2.cameraHeight; + } + } + + // start locations + startLocations = new Vec2i[maxPlayers]; + for (int i = 0; i < maxPlayers; ++i) { + int x = 0, y = 0; + readBytes = fread(&x, sizeof(int32), 1, f); + if (readBytes != 1) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "fread returned wrong size = " MG_SIZE_T_SPECIFIER + " on line: %d.", + readBytes, __LINE__); + throw megaglest_runtime_error(szBuf); + } + x = ::Shared::PlatformByteOrder::fromCommonEndian(x); + + readBytes = fread(&y, sizeof(int32), 1, f); + if (readBytes != 1) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "fread returned wrong size = " MG_SIZE_T_SPECIFIER + " on line: %d.", + readBytes, __LINE__); + throw megaglest_runtime_error(szBuf); + } + y = ::Shared::PlatformByteOrder::fromCommonEndian(y); + + startLocations[i] = Vec2i(x, y) * cellScale; + } + + // cells + cells = new Cell[getCellArraySize()]; + surfaceCells = new SurfaceCell[getSurfaceCellArraySize()]; + + // read heightmap + for (int j = 0; j < surfaceH; ++j) { + for (int i = 0; i < surfaceW; ++i) { + float32 alt = 0; + readBytes = fread(&alt, sizeof(float32), 1, f); + if (readBytes != 1) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "fread returned wrong size = " MG_SIZE_T_SPECIFIER + " on line: %d.", + readBytes, __LINE__); + throw megaglest_runtime_error(szBuf); + } + alt = ::Shared::PlatformByteOrder::fromCommonEndian(alt); + + SurfaceCell *sc = getSurfaceCell(i, j); + sc->setVertex(Vec3f(i * mapScale, alt / heightFactor, j * mapScale)); + } + } + + // read surfaces + for (int j = 0; j < surfaceH; ++j) { + for (int i = 0; i < surfaceW; ++i) { + int8 surf = 0; + readBytes = fread(&surf, sizeof(int8), 1, f); + if (readBytes != 1) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "fread returned wrong size = " MG_SIZE_T_SPECIFIER + " on line: %d.", + readBytes, __LINE__); + throw megaglest_runtime_error(szBuf); + } + surf = ::Shared::PlatformByteOrder::fromCommonEndian(surf); + + getSurfaceCell(i, j)->setSurfaceType(surf - 1); + } + } + + // read objects and resources + for (int j = 0; j < h; j += cellScale) { + for (int i = 0; i < w; i += cellScale) { + + int8 objNumber = 0; + readBytes = fread(&objNumber, sizeof(int8), 1, f); + if (readBytes != 1) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "fread returned wrong size = " MG_SIZE_T_SPECIFIER + " on line: %d.", + readBytes, __LINE__); + throw megaglest_runtime_error(szBuf); + } + objNumber = ::Shared::PlatformByteOrder::fromCommonEndian(objNumber); + + SurfaceCell *sc = getSurfaceCell(toSurfCoords(Vec2i(i, j))); + if (objNumber <= 0) { + sc->setObject(NULL); + } else if (objNumber <= Tileset::objCount) { + Object *o = new Object(tileset->getObjectType(objNumber - 1), + sc->getVertex(), Vec2i(i, j)); + sc->setObject(o); + for (int k = 0; k < techTree->getResourceTypeCount(); ++k) { + const ResourceType *rt = techTree->getResourceType(k); + if (rt->getClass() == rcTileset && + rt->getTilesetObject() == objNumber) { + o->setResource(rt, Vec2i(i, j)); + } + } + } else { + const ResourceType *rt = + techTree->getTechResourceType(objNumber - Tileset::objCount); + Object *o = new Object(NULL, sc->getVertex(), Vec2i(i, j)); + o->setResource(rt, Vec2i(i, j)); + sc->setObject(o); + } + } + } + if (f) + fclose(f); + } else { + throw megaglest_runtime_error("Can't open file"); + } + } catch (const exception &e) { + SystemFlags::OutputDebug(SystemFlags::debugError, + "In [%s::%s Line: %d] Error [%s]\n", __FILE__, + __FUNCTION__, __LINE__, e.what()); + throw megaglest_runtime_error("Error loading map: " + path + "\n" + + e.what()); + } + + return mapChecksum; } void Map::init(Tileset *tileset) { - Logger::getInstance().add(Lang::getInstance().getString("LogScreenGameUnLoadingMap","",true), true); - maxMapHeight=0.0f; - smoothSurface(tileset); - computeNormals(); - computeInterpolatedHeights(); - computeNearSubmerged(); - computeCellColors(); + Logger::getInstance().add( + Lang::getInstance().getString("LogScreenGameUnLoadingMap", "", true), + true); + maxMapHeight = 0.0f; + smoothSurface(tileset); + computeNormals(); + computeInterpolatedHeights(); + computeNearSubmerged(); + computeCellColors(); } - // ==================== is ==================== -class FindBestPos { +class FindBestPos { public: - float distanceFromUnitNoAdjustment; - float distanceFromClickNoAdjustment; - Vec2i resourcePosNoAdjustment; + float distanceFromUnitNoAdjustment; + float distanceFromClickNoAdjustment; + Vec2i resourcePosNoAdjustment; }; -//returns if there is a resource next to a unit, in "resourcePos" is stored the relative position of the resource -bool Map::isResourceNear(int frameIndex,const Vec2i &pos, const ResourceType *rt, Vec2i &resourcePos, - int size, Unit *unit, bool fallbackToPeersHarvestingSameResource, - Vec2i *resourceClickPos) const { - - bool resourceNear = false; - float distanceFromUnit=-1; - float distanceFromClick=-1; - - if(resourceClickPos) { - //printf("+++++++++ unit [%s - %d] pos = [%s] resourceClickPos [%s]\n",unit->getFullName().c_str(),unit->getId(),pos.getString().c_str(),resourceClickPos->getString().c_str()); - } - for(int i = -size; i <= size; ++i) { - for(int j = -size; j <= size; ++j) { - Vec2i resPos = Vec2i(pos.x + i, pos.y + j); - if(resourceClickPos) { - resPos = Vec2i(resourceClickPos->x + i, resourceClickPos->y + j); - } - Vec2i surfCoords = toSurfCoords(resPos); - - if(isInside(resPos) && isInsideSurface(surfCoords)) { - Resource *r= getSurfaceCell(surfCoords)->getResource(); - if(r != NULL) { - if(r->getType() == rt) { - if(resourceClickPos) { - //printf("****** unit [%s - %d] resPos = [%s] resourceClickPos->dist(resPos) [%f] distanceFromClick [%f] unit->getCenteredPos().dist(resPos) [%f] distanceFromUnit [%f]\n",unit->getFullName().c_str(),unit->getId(),resPos.getString().c_str(),resourceClickPos->dist(resPos),distanceFromClick,unit->getCenteredPos().dist(resPos),distanceFromUnit); - } - if(resourceClickPos == NULL || - (distanceFromClick < 0 || resourceClickPos->dist(resPos) <= distanceFromClick)) { - if(unit == NULL || - (distanceFromUnit < 0 || unit->getCenteredPos().dist(resPos) <= distanceFromUnit)) { - - bool isResourceNextToUnit = (resourceClickPos == NULL); - for(int i1 = -size; isResourceNextToUnit == false && i1 <= size; ++i1) { - for(int j1 = -size; j1 <= size; ++j1) { - Vec2i resPos1 = Vec2i(pos.x + i1, pos.y + j1); - if(resPos == resPos1) { - isResourceNextToUnit = true; - break; - } - } - } - if(isResourceNextToUnit == true) { - if(resourceClickPos != NULL) { - distanceFromClick = resourceClickPos->dist(resPos); - } - if(unit != NULL) { - distanceFromUnit = unit->getCenteredPos().dist(resPos); - } - - resourcePos= pos + Vec2i(i,j); - - if(unit == NULL || unit->isBadHarvestPos(resourcePos) == false) { - resourceNear = true; - - if(resourceClickPos) { - //printf("@@@@@@@@ unit [%s - %d] resPos = [%s] resourceClickPos->dist(resPos) [%f] distanceFromClick [%f] unit->getCenteredPos().dist(resPos) [%f] distanceFromUnit [%f]\n",unit->getFullName().c_str(),unit->getId(),resPos.getString().c_str(),resourceClickPos->dist(resPos),distanceFromClick,unit->getCenteredPos().dist(resPos),distanceFromUnit); - } - } - } - } - } - } - } - } - } - } - - if(resourceNear == false) { - if(fallbackToPeersHarvestingSameResource == true && unit != NULL) { - // Look for another unit that is currently harvesting the same resource - // type right now - - // Check the faction cache for a known position where we can harvest - // this resource type - Vec2i result = unit->getFaction()->getClosestResourceTypeTargetFromCache(unit, rt,frameIndex); - if(result.x >= 0) { - resourcePos = result; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"[found peer harvest pos] pos [%s] resourcePos [%s] unit->getFaction()->getCacheResourceTargetListSize() [%d]", - pos.getString().c_str(),resourcePos.getString().c_str(),unit->getFaction()->getCacheResourceTargetListSize()); - - if(frameIndex < 0) { - unit->logSynchData(__FILE__,__LINE__,szBuf); - } - else { - unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); - } - } - - if(unit->getPos().dist(resourcePos) <= size) { - resourceNear = true; - - if(resourceClickPos) { - //printf("###### unit [%s - %d]\n",unit->getFullName().c_str(),unit->getId()); - } - } - } - } - } - - if(resourceNear == false && resourceClickPos != NULL) { - std::vector bestPosList; - - //if(resourceClickPos) { - //printf("^^^^^ unit [%s - %d]\n",unit->getFullName().c_str(),unit->getId()); - //} - - for(int i = -1; i <= 1; ++i) { - for(int j = -1; j <= 1; ++j) { - Vec2i resPos = Vec2i(resourceClickPos->x + i, resourceClickPos->y + j); - Vec2i surfCoords = toSurfCoords(resPos); - - if(isInside(resPos) && isInsideSurface(surfCoords)) { - Resource *r= getSurfaceCell(surfCoords)->getResource(); - if(r != NULL) { - if(r->getType() == rt) { - //printf("^^^^^^ unit [%s - %d] resPos = [%s] resourceClickPos->dist(resPos) [%f] distanceFromClick [%f] unit->getCenteredPos().dist(resPos) [%f] distanceFromUnit [%f]\n",unit->getFullName().c_str(),unit->getId(),resPos.getString().c_str(),resourceClickPos->dist(resPos),distanceFromClick,unit->getCenteredPos().dist(resPos),distanceFromUnit); - - if(unit == NULL || - (distanceFromUnit < 0 || unit->getCenteredPos().dist(resPos) <= (distanceFromUnit + 2.0))) { - - if(resourceClickPos->dist(resPos) <= 1.0) { - if(unit != NULL) { - FindBestPos bestPosItem; - - bestPosItem.distanceFromUnitNoAdjustment = unit->getCenteredPos().dist(resPos); - bestPosItem.distanceFromClickNoAdjustment =distanceFromClick = resourceClickPos->dist(resPos); - bestPosItem.resourcePosNoAdjustment = resPos; - - bestPosList.push_back(bestPosItem); - } - } - - //printf("!!!! unit [%s - %d] resPos = [%s] resourceClickPos->dist(resPos) [%f] distanceFromClick [%f] unit->getCenteredPos().dist(resPos) [%f] distanceFromUnit [%f]\n",unit->getFullName().c_str(),unit->getId(),resPos.getString().c_str(),resourceClickPos->dist(resPos),distanceFromClick,unit->getCenteredPos().dist(resPos),distanceFromUnit); - if(distanceFromClick < 0 || resourceClickPos->dist(resPos) <= distanceFromClick) { - //if(resourceClickPos != NULL) { - distanceFromClick = resourceClickPos->dist(resPos); - //} - if(unit != NULL) { - distanceFromUnit = unit->getCenteredPos().dist(resPos); - } - - *resourceClickPos = resPos; - - if(unit == NULL || unit->isBadHarvestPos(*resourceClickPos) == false) { - //resourceNear = true; - - //printf("%%----------- unit [%s - %d] resPos = [%s] resourceClickPos->dist(resPos) [%f] distanceFromClick [%f] unit->getCenteredPos().dist(resPos) [%f] distanceFromUnit [%f]\n",unit->getFullName().c_str(),unit->getId(),resPos.getString().c_str(),resourceClickPos->dist(resPos),distanceFromClick,unit->getCenteredPos().dist(resPos),distanceFromUnit); - } - } - } - } - } - } - } - } - - float bestUnitDist = distanceFromUnit; - for(unsigned int i = 0; i < bestPosList.size(); ++i) { - FindBestPos &bestPosItem = bestPosList[i]; - - if(bestPosItem.distanceFromUnitNoAdjustment < bestUnitDist) { - bestUnitDist = bestPosItem.distanceFromUnitNoAdjustment; - *resourceClickPos = bestPosItem.resourcePosNoAdjustment; - - if(unit == NULL || unit->isBadHarvestPos(*resourceClickPos) == false) { - //printf("%%----------- unit [%s - %d] resourceClickPos [%s] bestUnitDist [%f]\n",unit->getFullName().c_str(),unit->getId(),resourceClickPos->getString().c_str(),bestUnitDist); - } - } - } - } - - return resourceNear; +// returns if there is a resource next to a unit, in "resourcePos" is stored the +// relative position of the resource +bool Map::isResourceNear(int frameIndex, const Vec2i &pos, + const ResourceType *rt, Vec2i &resourcePos, int size, + Unit *unit, bool fallbackToPeersHarvestingSameResource, + Vec2i *resourceClickPos) const { + + bool resourceNear = false; + float distanceFromUnit = -1; + float distanceFromClick = -1; + + if (resourceClickPos) { + // printf("+++++++++ unit [%s - %d] pos = [%s] resourceClickPos + // [%s]\n",unit->getFullName().c_str(),unit->getId(),pos.getString().c_str(),resourceClickPos->getString().c_str()); + } + for (int i = -size; i <= size; ++i) { + for (int j = -size; j <= size; ++j) { + Vec2i resPos = Vec2i(pos.x + i, pos.y + j); + if (resourceClickPos) { + resPos = Vec2i(resourceClickPos->x + i, resourceClickPos->y + j); + } + Vec2i surfCoords = toSurfCoords(resPos); + + if (isInside(resPos) && isInsideSurface(surfCoords)) { + Resource *r = getSurfaceCell(surfCoords)->getResource(); + if (r != NULL) { + if (r->getType() == rt) { + if (resourceClickPos) { + // printf("****** unit [%s - %d] resPos = [%s] + // resourceClickPos->dist(resPos) [%f] distanceFromClick [%f] + // unit->getCenteredPos().dist(resPos) [%f] distanceFromUnit + // [%f]\n",unit->getFullName().c_str(),unit->getId(),resPos.getString().c_str(),resourceClickPos->dist(resPos),distanceFromClick,unit->getCenteredPos().dist(resPos),distanceFromUnit); + } + if (resourceClickPos == NULL || + (distanceFromClick < 0 || + resourceClickPos->dist(resPos) <= distanceFromClick)) { + if (unit == NULL || + (distanceFromUnit < 0 || + unit->getCenteredPos().dist(resPos) <= distanceFromUnit)) { + + bool isResourceNextToUnit = (resourceClickPos == NULL); + for (int i1 = -size; + isResourceNextToUnit == false && i1 <= size; ++i1) { + for (int j1 = -size; j1 <= size; ++j1) { + Vec2i resPos1 = Vec2i(pos.x + i1, pos.y + j1); + if (resPos == resPos1) { + isResourceNextToUnit = true; + break; + } + } + } + if (isResourceNextToUnit == true) { + if (resourceClickPos != NULL) { + distanceFromClick = resourceClickPos->dist(resPos); + } + if (unit != NULL) { + distanceFromUnit = unit->getCenteredPos().dist(resPos); + } + + resourcePos = pos + Vec2i(i, j); + + if (unit == NULL || + unit->isBadHarvestPos(resourcePos) == false) { + resourceNear = true; + + if (resourceClickPos) { + // printf("@@@@@@@@ unit [%s - %d] resPos = [%s] + // resourceClickPos->dist(resPos) [%f] distanceFromClick + // [%f] unit->getCenteredPos().dist(resPos) [%f] + // distanceFromUnit + // [%f]\n",unit->getFullName().c_str(),unit->getId(),resPos.getString().c_str(),resourceClickPos->dist(resPos),distanceFromClick,unit->getCenteredPos().dist(resPos),distanceFromUnit); + } + } + } + } + } + } + } + } + } + } + + if (resourceNear == false) { + if (fallbackToPeersHarvestingSameResource == true && unit != NULL) { + // Look for another unit that is currently harvesting the same resource + // type right now + + // Check the faction cache for a known position where we can harvest + // this resource type + Vec2i result = unit->getFaction()->getClosestResourceTypeTargetFromCache( + unit, rt, frameIndex); + if (result.x >= 0) { + resourcePos = result; + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "[found peer harvest pos] pos [%s] resourcePos [%s] " + "unit->getFaction()->getCacheResourceTargetListSize() [%d]", + pos.getString().c_str(), resourcePos.getString().c_str(), + unit->getFaction()->getCacheResourceTargetListSize()); + + if (frameIndex < 0) { + unit->logSynchData(__FILE__, __LINE__, szBuf); + } else { + unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf); + } + } + + if (unit->getPos().dist(resourcePos) <= size) { + resourceNear = true; + + if (resourceClickPos) { + // printf("###### unit [%s - + // %d]\n",unit->getFullName().c_str(),unit->getId()); + } + } + } + } + } + + if (resourceNear == false && resourceClickPos != NULL) { + std::vector bestPosList; + + // if(resourceClickPos) { + // printf("^^^^^ unit [%s - + // %d]\n",unit->getFullName().c_str(),unit->getId()); + //} + + for (int i = -1; i <= 1; ++i) { + for (int j = -1; j <= 1; ++j) { + Vec2i resPos = Vec2i(resourceClickPos->x + i, resourceClickPos->y + j); + Vec2i surfCoords = toSurfCoords(resPos); + + if (isInside(resPos) && isInsideSurface(surfCoords)) { + Resource *r = getSurfaceCell(surfCoords)->getResource(); + if (r != NULL) { + if (r->getType() == rt) { + // printf("^^^^^^ unit [%s - %d] resPos = [%s] + // resourceClickPos->dist(resPos) [%f] distanceFromClick [%f] + // unit->getCenteredPos().dist(resPos) [%f] distanceFromUnit + // [%f]\n",unit->getFullName().c_str(),unit->getId(),resPos.getString().c_str(),resourceClickPos->dist(resPos),distanceFromClick,unit->getCenteredPos().dist(resPos),distanceFromUnit); + + if (unit == NULL || (distanceFromUnit < 0 || + unit->getCenteredPos().dist(resPos) <= + (distanceFromUnit + 2.0))) { + + if (resourceClickPos->dist(resPos) <= 1.0) { + if (unit != NULL) { + FindBestPos bestPosItem; + + bestPosItem.distanceFromUnitNoAdjustment = + unit->getCenteredPos().dist(resPos); + bestPosItem.distanceFromClickNoAdjustment = + distanceFromClick = resourceClickPos->dist(resPos); + bestPosItem.resourcePosNoAdjustment = resPos; + + bestPosList.push_back(bestPosItem); + } + } + + // printf("!!!! unit [%s - %d] resPos = [%s] + // resourceClickPos->dist(resPos) [%f] distanceFromClick [%f] + // unit->getCenteredPos().dist(resPos) [%f] distanceFromUnit + // [%f]\n",unit->getFullName().c_str(),unit->getId(),resPos.getString().c_str(),resourceClickPos->dist(resPos),distanceFromClick,unit->getCenteredPos().dist(resPos),distanceFromUnit); + if (distanceFromClick < 0 || + resourceClickPos->dist(resPos) <= distanceFromClick) { + // if(resourceClickPos != NULL) { + distanceFromClick = resourceClickPos->dist(resPos); + //} + if (unit != NULL) { + distanceFromUnit = unit->getCenteredPos().dist(resPos); + } + + *resourceClickPos = resPos; + + if (unit == NULL || + unit->isBadHarvestPos(*resourceClickPos) == false) { + // resourceNear = true; + + // printf("%%----------- unit [%s - %d] resPos = [%s] + // resourceClickPos->dist(resPos) [%f] distanceFromClick + // [%f] unit->getCenteredPos().dist(resPos) [%f] + // distanceFromUnit + // [%f]\n",unit->getFullName().c_str(),unit->getId(),resPos.getString().c_str(),resourceClickPos->dist(resPos),distanceFromClick,unit->getCenteredPos().dist(resPos),distanceFromUnit); + } + } + } + } + } + } + } + } + + float bestUnitDist = distanceFromUnit; + for (unsigned int i = 0; i < bestPosList.size(); ++i) { + FindBestPos &bestPosItem = bestPosList[i]; + + if (bestPosItem.distanceFromUnitNoAdjustment < bestUnitDist) { + bestUnitDist = bestPosItem.distanceFromUnitNoAdjustment; + *resourceClickPos = bestPosItem.resourcePosNoAdjustment; + + if (unit == NULL || unit->isBadHarvestPos(*resourceClickPos) == false) { + // printf("%%----------- unit [%s - %d] resourceClickPos [%s] + // bestUnitDist + // [%f]\n",unit->getFullName().c_str(),unit->getId(),resourceClickPos->getString().c_str(),bestUnitDist); + } + } + } + } + + return resourceNear; } // ==================== free cells ==================== bool Map::isFreeCell(const Vec2i &pos, Field field) const { - return - isInside(pos) && - isInsideSurface(toSurfCoords(pos)) && - getCell(pos)->isFree(field) && - (field==fAir || getSurfaceCell(toSurfCoords(pos))->isFree()) && - (field!=fLand || getDeepSubmerged(getCell(pos)) == false); + return isInside(pos) && isInsideSurface(toSurfCoords(pos)) && + getCell(pos)->isFree(field) && + (field == fAir || getSurfaceCell(toSurfCoords(pos))->isFree()) && + (field != fLand || getDeepSubmerged(getCell(pos)) == false); } - -bool Map::isFreeCellOrHasUnit(const Vec2i &pos, Field field, const Unit *unit) const{ - if(isInside(pos)){ - Cell *c= getCell(pos); - if(c->getUnit(field) == unit && unit != NULL) { - return true; - } - else{ - return isFreeCell(pos, field); - } - } - return false; +bool Map::isFreeCellOrHasUnit(const Vec2i &pos, Field field, + const Unit *unit) const { + if (isInside(pos)) { + Cell *c = getCell(pos); + if (c->getUnit(field) == unit && unit != NULL) { + return true; + } else { + return isFreeCell(pos, field); + } + } + return false; } -//TT: this is much more complicated compared with the old one above. I think its no more needed -//bool Map::isFreeCellOrHasUnit(const Vec2i &pos, Field field, const Unit *unit) const { -// if(isInside(pos) && isInsideSurface(toSurfCoords(pos))) { -// if(unit->getCurrField() != field) { -// return isFreeCell(pos, field); +// TT: this is much more complicated compared with the old one above. I think +// its no more needed bool Map::isFreeCellOrHasUnit(const Vec2i &pos, Field +// field, const Unit *unit) const { if(isInside(pos) && +// isInsideSurface(toSurfCoords(pos))) { if(unit->getCurrField() != +// field) { return isFreeCell(pos, field); // } // Cell *c= getCell(pos); // if(c->getUnit(unit->getCurrField()) == unit) { @@ -800,17 +904,17 @@ bool Map::isFreeCellOrHasUnit(const Vec2i &pos, Field field, const Unit *unit) c // if(field == fAir) { // return true; // } -// const SurfaceCell *sc= getSurfaceCell(toSurfCoords(pos)); -// if(sc != NULL) { -// if(getDeepSubmerged(sc) == true) { -// return false; +// const SurfaceCell *sc= +// getSurfaceCell(toSurfCoords(pos)); if(sc != NULL) { +// if(getDeepSubmerged(sc) == +// true) { return false; // } // else if(field == fLand) { // if(sc->isFree() == false) { // return false; // } -// else if(c->getUnit(field) != NULL) { -// return false; +// else if(c->getUnit(field) != +//NULL) { return false; // } // } // } @@ -822,99 +926,98 @@ bool Map::isFreeCellOrHasUnit(const Vec2i &pos, Field field, const Unit *unit) c // } // } // return false; -//} +// } bool Map::isAproxFreeCell(const Vec2i &pos, Field field, int teamIndex) const { - if(isInside(pos) && isInsideSurface(toSurfCoords(pos))) { - const SurfaceCell *sc= getSurfaceCell(toSurfCoords(pos)); - - if(sc->isVisible(teamIndex)) { - return isFreeCell(pos, field); - } - else if(sc->isExplored(teamIndex)) { - return field==fLand? sc->isFree() && !getDeepSubmerged(getCell(pos)): true; - } - else { - return true; - } - } - - //printf("[%s] Line: %d returning false\n",__FUNCTION__,__LINE__); - return false; + if (isInside(pos) && isInsideSurface(toSurfCoords(pos))) { + const SurfaceCell *sc = getSurfaceCell(toSurfCoords(pos)); + + if (sc->isVisible(teamIndex)) { + return isFreeCell(pos, field); + } else if (sc->isExplored(teamIndex)) { + return field == fLand ? sc->isFree() && !getDeepSubmerged(getCell(pos)) + : true; + } else { + return true; + } + } + + // printf("[%s] Line: %d returning false\n",__FUNCTION__,__LINE__); + return false; } -bool Map::isFreeCells(const Vec2i & pos, int size, Field field) const { - for(int i=pos.x; igetField(); - const UnitType *ut=targetUnitType; - CardinalDir facing=currentUnit->getModelFacing(); - - if (ut->hasCellMap() && isInside(pos) && isInsideSurface(toSurfCoords(pos))) { - for (int y=0; y < ut->getSize(); ++y) { - for (int x=0; x < ut->getSize(); ++x) { - Vec2i cellPos = pos + Vec2i(x, y); - if(isInside(cellPos) && isInsideSurface(toSurfCoords(cellPos))) { - if (ut->getCellMapCell(x, y, facing)) { - if (isFreeCellOrHasUnit(cellPos, field, currentUnit) == false) { - return false; - } - } - } - else { - return false; - } - } - } - return true; - } - else { - return isFreeCellsOrHasUnit(pos, ut->getSize(), field,currentUnit); - } +bool Map::canMorph(const Vec2i &pos, const Unit *currentUnit, + const UnitType *targetUnitType) const { + Field field = targetUnitType->getField(); + const UnitType *ut = targetUnitType; + CardinalDir facing = currentUnit->getModelFacing(); + + if (ut->hasCellMap() && isInside(pos) && isInsideSurface(toSurfCoords(pos))) { + for (int y = 0; y < ut->getSize(); ++y) { + for (int x = 0; x < ut->getSize(); ++x) { + Vec2i cellPos = pos + Vec2i(x, y); + if (isInside(cellPos) && isInsideSurface(toSurfCoords(cellPos))) { + if (ut->getCellMapCell(x, y, facing)) { + if (isFreeCellOrHasUnit(cellPos, field, currentUnit) == false) { + return false; + } + } + } else { + return false; + } + } + } + return true; + } else { + return isFreeCellsOrHasUnit(pos, ut->getSize(), field, currentUnit); + } } -//bool Map::canOccupy(const Vec2i &pos, Field field, const UnitType *ut, CardinalDir facing) { -// if (ut->hasCellMap() && isInside(pos) && isInsideSurface(toSurfCoords(pos))) { -// for (int y=0; y < ut->getSize(); ++y) { -// for (int x=0; x < ut->getSize(); ++x) { -// Vec2i cellPos = pos + Vec2i(x, y); -// if(isInside(cellPos) && isInsideSurface(toSurfCoords(cellPos))) { -// if (ut->getCellMapCell(x, y, facing)) { -// if (isFreeCell(cellPos, field) == false) { -// return false; +// bool Map::canOccupy(const Vec2i &pos, Field field, const UnitType *ut, +// CardinalDir facing) { if (ut->hasCellMap() && isInside(pos) && +// isInsideSurface(toSurfCoords(pos))) { for (int y=0; y < +// ut->getSize(); ++y) { for (int x=0; x < ut->getSize(); ++x) { Vec2i cellPos = +//pos + Vec2i(x, y); if(isInside(cellPos) && +// isInsideSurface(toSurfCoords(cellPos))) { if +// (ut->getCellMapCell(x, y, +// facing)) { if (isFreeCell(cellPos, field) == +// false) { return false; // } // } // } @@ -928,279 +1031,309 @@ bool Map::canMorph(const Vec2i &pos,const Unit *currentUnit,const UnitType *targ // else { // return isFreeCells(pos, ut->getSize(), field); // } -//} +// } // ==================== unit placement ==================== -//checks if a unit can move from between 2 cells -bool Map::canMove(const Unit *unit, const Vec2i &pos1, const Vec2i &pos2, std::map > > > *lookupCache) const { - int size= unit->getType()->getSize(); - Field field= unit->getCurrField(); - - if(lookupCache != NULL) { - std::map > > >::const_iterator iterFind1 = lookupCache->find(pos1); - if(iterFind1 != lookupCache->end()) { - std::map > >::const_iterator iterFind2 = iterFind1->second.find(pos2); - if(iterFind2 != iterFind1->second.end()) { - std::map >::const_iterator iterFind3 = iterFind2->second.find(size); - if(iterFind3 != iterFind2->second.end()) { - std::map::const_iterator iterFind4 = iterFind3->second.find(field); - if(iterFind4 != iterFind3->second.end()) { - // Found this result in the cache - return iterFind4->second; - } - } - } - } - } - - for(int i=pos2.x; igetUnit(field) != unit) { - if(isFreeCell(Vec2i(i, j), field) == false) { - if(lookupCache != NULL) { - (*lookupCache)[pos1][pos2][size][field]=false; - } - - return false; - } - } - } - else { - if(lookupCache != NULL) { - (*lookupCache)[pos1][pos2][size][field]=false; - } - - return false; - } - } - } - - bool isBadHarvestPos = false; - //if(unit != NULL) { - Command *command= unit->getCurrCommand(); - if(command != NULL) { - const HarvestCommandType *hct = dynamic_cast(command->getCommandType()); - if(hct != NULL && unit->isBadHarvestPos(pos2) == true) { - isBadHarvestPos = true; - } - } - //} - - if(isBadHarvestPos == true) { - if(lookupCache != NULL) { - (*lookupCache)[pos1][pos2][size][field]=false; - } - - return false; - } - - if(lookupCache != NULL) { - (*lookupCache)[pos1][pos2][size][field]=true; - } +// checks if a unit can move from between 2 cells +bool Map::canMove( + const Unit *unit, const Vec2i &pos1, const Vec2i &pos2, + std::map>>> + *lookupCache) const { + int size = unit->getType()->getSize(); + Field field = unit->getCurrField(); + + if (lookupCache != NULL) { + std::map>>>:: + const_iterator iterFind1 = lookupCache->find(pos1); + if (iterFind1 != lookupCache->end()) { + std::map>>::const_iterator + iterFind2 = iterFind1->second.find(pos2); + if (iterFind2 != iterFind1->second.end()) { + std::map>::const_iterator iterFind3 = + iterFind2->second.find(size); + if (iterFind3 != iterFind2->second.end()) { + std::map::const_iterator iterFind4 = + iterFind3->second.find(field); + if (iterFind4 != iterFind3->second.end()) { + // Found this result in the cache + return iterFind4->second; + } + } + } + } + } + + for (int i = pos2.x; i < pos2.x + size; ++i) { + for (int j = pos2.y; j < pos2.y + size; ++j) { + if (isInside(i, j) && isInsideSurface(toSurfCoords(Vec2i(i, j)))) { + if (getCell(i, j)->getUnit(field) != unit) { + if (isFreeCell(Vec2i(i, j), field) == false) { + if (lookupCache != NULL) { + (*lookupCache)[pos1][pos2][size][field] = false; + } - return true; -} + return false; + } + } + } else { + if (lookupCache != NULL) { + (*lookupCache)[pos1][pos2][size][field] = false; + } + + return false; + } + } + } + + bool isBadHarvestPos = false; + // if(unit != NULL) { + Command *command = unit->getCurrCommand(); + if (command != NULL) { + const HarvestCommandType *hct = + dynamic_cast(command->getCommandType()); + if (hct != NULL && unit->isBadHarvestPos(pos2) == true) { + isBadHarvestPos = true; + } + } + //} + + if (isBadHarvestPos == true) { + if (lookupCache != NULL) { + (*lookupCache)[pos1][pos2][size][field] = false; + } + + return false; + } + + if (lookupCache != NULL) { + (*lookupCache)[pos1][pos2][size][field] = true; + } -//checks if a unit can move from between 2 cells using only visible cells (for pathfinding) -bool Map::aproxCanMove(const Unit *unit, const Vec2i &pos1, const Vec2i &pos2, std::map > > > > *lookupCache) const { - if(isInside(pos1) == false || isInsideSurface(toSurfCoords(pos1)) == false || - isInside(pos2) == false || isInsideSurface(toSurfCoords(pos2)) == false) { - - //printf("[%s] Line: %d returning false\n",__FUNCTION__,__LINE__); - return false; - } - - if(unit == NULL) { - throw megaglest_runtime_error("unit == NULL"); - } - int size= unit->getType()->getSize(); - int teamIndex= unit->getTeam(); - Field field= unit->getCurrField(); - - if(lookupCache != NULL) { - std::map > > > >::const_iterator iterFind1 = lookupCache->find(pos1); - if(iterFind1 != lookupCache->end()) { - std::map > > >::const_iterator iterFind2 = iterFind1->second.find(pos2); - if(iterFind2 != iterFind1->second.end()) { - std::map > >::const_iterator iterFind3 = iterFind2->second.find(teamIndex); - if(iterFind3 != iterFind2->second.end()) { - std::map >::const_iterator iterFind4 = iterFind3->second.find(size); - if(iterFind4 != iterFind3->second.end()) { - std::map::const_iterator iterFind5 = iterFind4->second.find(field); - if(iterFind5 != iterFind4->second.end()) { - // Found this result in the cache - if(iterFind5->second == false) { - //printf("[%s] Line: %d returning false\n",__FUNCTION__,__LINE__); - } - return iterFind5->second; - } - } - } - } - } - } - - //single cell units - if(size == 1) { - if(isAproxFreeCell(pos2, field, teamIndex) == false) { - if(lookupCache != NULL) { - (*lookupCache)[pos1][pos2][teamIndex][size][field]=false; - } - - //printf("[%s] Line: %d returning false\n",__FUNCTION__,__LINE__); - return false; - } - if(pos1.x != pos2.x && pos1.y != pos2.y) { - if(isAproxFreeCell(Vec2i(pos1.x, pos2.y), field, teamIndex) == false) { - if(lookupCache != NULL) { - (*lookupCache)[pos1][pos2][teamIndex][size][field]=false; - } - - //Unit *cellUnit = getCell(Vec2i(pos1.x, pos2.y))->getUnit(field); - //Object * obj = getSurfaceCell(toSurfCoords(Vec2i(pos1.x, pos2.y)))->getObject(); - - //printf("[%s] Line: %d returning false cell [%s] free [%d] cell unitid = %d object class = %d\n",__FUNCTION__,__LINE__,Vec2i(pos1.x, pos2.y).getString().c_str(),this->isFreeCell(Vec2i(pos1.x, pos2.y),field),(cellUnit != NULL ? cellUnit->getId() : -1),(obj != NULL ? obj->getType()->getClass() : -1)); - //printf("[%s] Line: %d returning false\n",__FUNCTION__,__LINE__); - return false; - } - if(isAproxFreeCell(Vec2i(pos2.x, pos1.y), field, teamIndex) == false) { - if(lookupCache != NULL) { - (*lookupCache)[pos1][pos2][teamIndex][size][field]=false; - } - - //printf("[%s] Line: %d returning false\n",__FUNCTION__,__LINE__); - return false; - } - } - - bool isBadHarvestPos = false; - //if(unit != NULL) { - Command *command= unit->getCurrCommand(); - if(command != NULL) { - const HarvestCommandType *hct = dynamic_cast(command->getCommandType()); - if(hct != NULL && unit->isBadHarvestPos(pos2) == true) { - isBadHarvestPos = true; - } - } - //} - - if(unit == NULL || isBadHarvestPos == true) { - if(lookupCache != NULL) { - (*lookupCache)[pos1][pos2][teamIndex][size][field]=false; - } - - //printf("[%s] Line: %d returning false\n",__FUNCTION__,__LINE__); - return false; - } - - if(lookupCache != NULL) { - (*lookupCache)[pos1][pos2][teamIndex][size][field]=true; - } - - return true; - } - //multi cell units - else { - for(int i = pos2.x; i < pos2.x + size; ++i) { - for(int j = pos2.y; j < pos2.y + size; ++j) { - - Vec2i cellPos = Vec2i(i,j); - if(isInside(cellPos) && isInsideSurface(toSurfCoords(cellPos))) { - if(getCell(cellPos)->getUnit(unit->getCurrField()) != unit) { - if(isAproxFreeCell(cellPos, field, teamIndex) == false) { - if(lookupCache != NULL) { - (*lookupCache)[pos1][pos2][teamIndex][size][field]=false; - } - - //printf("[%s] Line: %d returning false\n",__FUNCTION__,__LINE__); - return false; - } - } - } - else { - - if(lookupCache != NULL) { - (*lookupCache)[pos1][pos2][teamIndex][size][field]=false; - } - - //printf("[%s] Line: %d returning false\n",__FUNCTION__,__LINE__); - return false; - } - } - } - - bool isBadHarvestPos = false; - Command *command= unit->getCurrCommand(); - if(command != NULL) { - const HarvestCommandType *hct = dynamic_cast(command->getCommandType()); - if(hct != NULL && unit->isBadHarvestPos(pos2) == true) { - isBadHarvestPos = true; - } - } - - if(isBadHarvestPos == true) { - if(lookupCache != NULL) { - (*lookupCache)[pos1][pos2][teamIndex][size][field]=false; - } - - //printf("[%s] Line: %d returning false\n",__FUNCTION__,__LINE__); - return false; - } - - if(lookupCache != NULL) { - (*lookupCache)[pos1][pos2][teamIndex][size][field]=true; - } - } - return true; + return true; } +// checks if a unit can move from between 2 cells using only visible cells (for +// pathfinding) +bool Map::aproxCanMove( + const Unit *unit, const Vec2i &pos1, const Vec2i &pos2, + std::map< + Vec2i, + std::map>>>> + *lookupCache) const { + if (isInside(pos1) == false || isInsideSurface(toSurfCoords(pos1)) == false || + isInside(pos2) == false || isInsideSurface(toSurfCoords(pos2)) == false) { + + // printf("[%s] Line: %d returning false\n",__FUNCTION__,__LINE__); + return false; + } + + if (unit == NULL) { + throw megaglest_runtime_error("unit == NULL"); + } + int size = unit->getType()->getSize(); + int teamIndex = unit->getTeam(); + Field field = unit->getCurrField(); + + if (lookupCache != NULL) { + std::map< + Vec2i, + std::map>>>>:: + const_iterator iterFind1 = lookupCache->find(pos1); + if (iterFind1 != lookupCache->end()) { + std::map>>>:: + const_iterator iterFind2 = iterFind1->second.find(pos2); + if (iterFind2 != iterFind1->second.end()) { + std::map>>::const_iterator + iterFind3 = iterFind2->second.find(teamIndex); + if (iterFind3 != iterFind2->second.end()) { + std::map>::const_iterator iterFind4 = + iterFind3->second.find(size); + if (iterFind4 != iterFind3->second.end()) { + std::map::const_iterator iterFind5 = + iterFind4->second.find(field); + if (iterFind5 != iterFind4->second.end()) { + // Found this result in the cache + if (iterFind5->second == false) { + // printf("[%s] Line: %d returning + // false\n",__FUNCTION__,__LINE__); + } + return iterFind5->second; + } + } + } + } + } + } -Vec2i Map::computeRefPos(const Selection *selection) const { - Vec2i total= Vec2i(0); + // single cell units + if (size == 1) { + if (isAproxFreeCell(pos2, field, teamIndex) == false) { + if (lookupCache != NULL) { + (*lookupCache)[pos1][pos2][teamIndex][size][field] = false; + } + + // printf("[%s] Line: %d returning false\n",__FUNCTION__,__LINE__); + return false; + } + if (pos1.x != pos2.x && pos1.y != pos2.y) { + if (isAproxFreeCell(Vec2i(pos1.x, pos2.y), field, teamIndex) == false) { + if (lookupCache != NULL) { + (*lookupCache)[pos1][pos2][teamIndex][size][field] = false; + } + + // Unit *cellUnit = getCell(Vec2i(pos1.x, pos2.y))->getUnit(field); + // Object * obj = getSurfaceCell(toSurfCoords(Vec2i(pos1.x, + // pos2.y)))->getObject(); + + // printf("[%s] Line: %d returning false cell [%s] free [%d] cell unitid + // = %d object class = %d\n",__FUNCTION__,__LINE__,Vec2i(pos1.x, + // pos2.y).getString().c_str(),this->isFreeCell(Vec2i(pos1.x, + // pos2.y),field),(cellUnit != NULL ? cellUnit->getId() : -1),(obj != + // NULL ? obj->getType()->getClass() : -1)); printf("[%s] Line: %d + // returning false\n",__FUNCTION__,__LINE__); + return false; + } + if (isAproxFreeCell(Vec2i(pos2.x, pos1.y), field, teamIndex) == false) { + if (lookupCache != NULL) { + (*lookupCache)[pos1][pos2][teamIndex][size][field] = false; + } + + // printf("[%s] Line: %d returning false\n",__FUNCTION__,__LINE__); + return false; + } + } + + bool isBadHarvestPos = false; + // if(unit != NULL) { + Command *command = unit->getCurrCommand(); + if (command != NULL) { + const HarvestCommandType *hct = + dynamic_cast(command->getCommandType()); + if (hct != NULL && unit->isBadHarvestPos(pos2) == true) { + isBadHarvestPos = true; + } + } + //} + + if (unit == NULL || isBadHarvestPos == true) { + if (lookupCache != NULL) { + (*lookupCache)[pos1][pos2][teamIndex][size][field] = false; + } - if(selection == NULL) { - throw megaglest_runtime_error("selection == NULL"); - } + // printf("[%s] Line: %d returning false\n",__FUNCTION__,__LINE__); + return false; + } + + if (lookupCache != NULL) { + (*lookupCache)[pos1][pos2][teamIndex][size][field] = true; + } + + return true; + } + // multi cell units + else { + for (int i = pos2.x; i < pos2.x + size; ++i) { + for (int j = pos2.y; j < pos2.y + size; ++j) { + + Vec2i cellPos = Vec2i(i, j); + if (isInside(cellPos) && isInsideSurface(toSurfCoords(cellPos))) { + if (getCell(cellPos)->getUnit(unit->getCurrField()) != unit) { + if (isAproxFreeCell(cellPos, field, teamIndex) == false) { + if (lookupCache != NULL) { + (*lookupCache)[pos1][pos2][teamIndex][size][field] = false; + } + + // printf("[%s] Line: %d returning + // false\n",__FUNCTION__,__LINE__); + return false; + } + } + } else { - for(int i = 0; i < selection->getCount(); ++i) { - if(selection->getUnit(i) == NULL) { - throw megaglest_runtime_error("selection == NULL || selection->getUnit(i) == NULL"); - } - total = total + selection->getUnit(i)->getPosNotThreadSafe(); + if (lookupCache != NULL) { + (*lookupCache)[pos1][pos2][teamIndex][size][field] = false; + } + + // printf("[%s] Line: %d returning false\n",__FUNCTION__,__LINE__); + return false; + } + } } - return Vec2i(total.x / selection->getCount(), total.y / selection->getCount()); + bool isBadHarvestPos = false; + Command *command = unit->getCurrCommand(); + if (command != NULL) { + const HarvestCommandType *hct = + dynamic_cast(command->getCommandType()); + if (hct != NULL && unit->isBadHarvestPos(pos2) == true) { + isBadHarvestPos = true; + } + } + + if (isBadHarvestPos == true) { + if (lookupCache != NULL) { + (*lookupCache)[pos1][pos2][teamIndex][size][field] = false; + } + + // printf("[%s] Line: %d returning false\n",__FUNCTION__,__LINE__); + return false; + } + + if (lookupCache != NULL) { + (*lookupCache)[pos1][pos2][teamIndex][size][field] = true; + } + } + return true; } -Vec2i Map::computeDestPos( const Vec2i &refUnitPos, const Vec2i &unitPos, - const Vec2i &commandPos) const { - Vec2i pos; -// no more random needed -// Vec2i posDiff = unitPos - refUnitPos; -// -// if(abs(posDiff.x) >= 3){ -// posDiff.x = posDiff.x % 3; -// } -// -// if(abs(posDiff.y) >= 3){ -// posDiff.y = posDiff.y % 3; -// } +Vec2i Map::computeRefPos(const Selection *selection) const { + Vec2i total = Vec2i(0); - pos = commandPos; //+ posDiff; - clampPos(pos); - return pos; + if (selection == NULL) { + throw megaglest_runtime_error("selection == NULL"); + } + + for (int i = 0; i < selection->getCount(); ++i) { + if (selection->getUnit(i) == NULL) { + throw megaglest_runtime_error( + "selection == NULL || selection->getUnit(i) == NULL"); + } + total = total + selection->getUnit(i)->getPosNotThreadSafe(); + } + + return Vec2i(total.x / selection->getCount(), + total.y / selection->getCount()); } -//std::pair Map::getUnitDistanceToPos(const Unit *unit,Vec2i pos,const UnitType *ut) { -// if(unit == NULL) { -// throw megaglest_runtime_error("unit == NULL"); +Vec2i Map::computeDestPos(const Vec2i &refUnitPos, const Vec2i &unitPos, + const Vec2i &commandPos) const { + Vec2i pos; + // no more random needed + // Vec2i posDiff = unitPos - refUnitPos; + // + // if(abs(posDiff.x) >= 3){ + // posDiff.x = posDiff.x % 3; + // } + // + // if(abs(posDiff.y) >= 3){ + // posDiff.y = posDiff.y % 3; + // } + + pos = commandPos; //+ posDiff; + clampPos(pos); + return pos; +} + +// std::pair Map::getUnitDistanceToPos(const Unit *unit,Vec2i +// pos,const UnitType *ut) { if(unit == NULL) { throw +// megaglest_runtime_error("unit == NULL"); // } // // std::pair result(-1,Vec2i(0)); // //int unitId= unit->getId(); -// Vec2i unitPos= computeDestPos(unit->getPosNotThreadSafe(), unit->getPosNotThreadSafe(), pos); +// Vec2i unitPos= computeDestPos(unit->getPosNotThreadSafe(), +// unit->getPosNotThreadSafe(), pos); // // Vec2i start = pos - Vec2i(1); // int unitTypeSize = 0; @@ -1213,848 +1346,933 @@ Vec2i Map::computeDestPos( const Vec2i &refUnitPos, const Vec2i &unitPos, // for(int j = start.y; j <= end.y; ++j){ // Vec2i testPos(i,j); // -// if(ut == NULL || isInUnitTypeCells(ut, pos,testPos) == false) { -// float distance = unitPos.dist(testPos); -// if(result.first < 0 || result.first > distance) { -// result.first = distance; -// result.second = testPos; +// if(ut == NULL || isInUnitTypeCells(ut, pos,testPos) == +// false) { float distance = unitPos.dist(testPos); +// if(result.first < 0 || result.first > distance) { +// result.first = distance; result.second = +// testPos; // } // } // } // } // // return result; -//} - -const Unit * Map::findClosestUnitToPos(const Selection *selection, Vec2i originalBuildPos, - const UnitType *ut) const { - const Unit *closestUnit = NULL; - Vec2i refPos = computeRefPos(selection); - - Vec2i pos = originalBuildPos; - - float bestRange = -1; - - Vec2i start = pos - Vec2i(1); - int unitTypeSize = 0; - if(ut != NULL) { - unitTypeSize = ut->getSize(); - } - Vec2i end = pos + Vec2i(unitTypeSize); - - for(int i = 0; i < selection->getCount(); ++i) { - const Unit *unit = selection->getUnit(i); - //int unitId= unit->getId(); - Vec2i unitBuilderPos= computeDestPos(refPos, unit->getPosNotThreadSafe(), pos); - - for(int i = start.x; i <= end.x; ++i) { - for(int j = start.y; j <= end.y; ++j){ - Vec2i testPos(i,j); - if(isInUnitTypeCells(ut, originalBuildPos,testPos) == false) { - float distance = unitBuilderPos.dist(testPos); - if(bestRange < 0 || bestRange > distance) { - bestRange = distance; - pos = testPos; - closestUnit = unit; - } - } - } - } - } - - return closestUnit; +// } + +const Unit *Map::findClosestUnitToPos(const Selection *selection, + Vec2i originalBuildPos, + const UnitType *ut) const { + const Unit *closestUnit = NULL; + Vec2i refPos = computeRefPos(selection); + + Vec2i pos = originalBuildPos; + + float bestRange = -1; + + Vec2i start = pos - Vec2i(1); + int unitTypeSize = 0; + if (ut != NULL) { + unitTypeSize = ut->getSize(); + } + Vec2i end = pos + Vec2i(unitTypeSize); + + for (int i = 0; i < selection->getCount(); ++i) { + const Unit *unit = selection->getUnit(i); + // int unitId= unit->getId(); + Vec2i unitBuilderPos = + computeDestPos(refPos, unit->getPosNotThreadSafe(), pos); + + for (int i = start.x; i <= end.x; ++i) { + for (int j = start.y; j <= end.y; ++j) { + Vec2i testPos(i, j); + if (isInUnitTypeCells(ut, originalBuildPos, testPos) == false) { + float distance = unitBuilderPos.dist(testPos); + if (bestRange < 0 || bestRange > distance) { + bestRange = distance; + pos = testPos; + closestUnit = unit; + } + } + } + } + } + + return closestUnit; } -Vec2i Map::findBestBuildApproach(const Unit *unit, Vec2i originalBuildPos,const UnitType *ut) const { - if(unit == NULL) { - throw megaglest_runtime_error("unit == NULL"); - } - if(ut == NULL) { - throw megaglest_runtime_error("ut == NULL"); - } - - Vec2i unitBuilderPos = unit->getPosNotThreadSafe(); - Vec2i pos = originalBuildPos; - - float bestRange = -1; - - Vec2i start = pos - Vec2i(unit->getType()->getSize()); - Vec2i end = pos + Vec2i(ut->getSize()); - - for(int i = start.x; i <= end.x; ++i) { - for(int j = start.y; j <= end.y; ++j) { - Vec2i testPos(i,j); - if(isInUnitTypeCells(ut, originalBuildPos,testPos) == false) { - float distance = unitBuilderPos.dist(testPos); - if(bestRange < 0 || bestRange > distance) { - // Check if the cell is occupied by another unit - if(isFreeCellOrHasUnit(testPos, unit->getType()->getField(), unit) == true) { - bestRange = distance; - pos = testPos; - } - } - } - } - } - - return pos; +Vec2i Map::findBestBuildApproach(const Unit *unit, Vec2i originalBuildPos, + const UnitType *ut) const { + if (unit == NULL) { + throw megaglest_runtime_error("unit == NULL"); + } + if (ut == NULL) { + throw megaglest_runtime_error("ut == NULL"); + } + + Vec2i unitBuilderPos = unit->getPosNotThreadSafe(); + Vec2i pos = originalBuildPos; + + float bestRange = -1; + + Vec2i start = pos - Vec2i(unit->getType()->getSize()); + Vec2i end = pos + Vec2i(ut->getSize()); + + for (int i = start.x; i <= end.x; ++i) { + for (int j = start.y; j <= end.y; ++j) { + Vec2i testPos(i, j); + if (isInUnitTypeCells(ut, originalBuildPos, testPos) == false) { + float distance = unitBuilderPos.dist(testPos); + if (bestRange < 0 || bestRange > distance) { + // Check if the cell is occupied by another unit + if (isFreeCellOrHasUnit(testPos, unit->getType()->getField(), unit) == + true) { + bestRange = distance; + pos = testPos; + } + } + } + } + } + + return pos; } bool Map::isNextToUnitTypeCells(const UnitType *ut, const Vec2i &pos, - const Vec2i &testPos) const { - bool isInsideDestUnitCells = isInUnitTypeCells(ut, pos,testPos); - if(isInsideDestUnitCells == false) { - //Cell *testCell = getCell(testPos); - for(int i=-1; i <= ut->getSize(); ++i){ - for(int j = -1; j <= ut->getSize(); ++j) { - Vec2i currPos = pos + Vec2i(i, j); - if(isInside(currPos) == true && isInsideSurface(toSurfCoords(currPos)) == true) { - //Cell *unitCell = getCell(currPos); - //if(unitCell == testCell) { - if(isNextTo(testPos,currPos) == true) { - return true; - } - } - } - } - } - - return false; + const Vec2i &testPos) const { + bool isInsideDestUnitCells = isInUnitTypeCells(ut, pos, testPos); + if (isInsideDestUnitCells == false) { + // Cell *testCell = getCell(testPos); + for (int i = -1; i <= ut->getSize(); ++i) { + for (int j = -1; j <= ut->getSize(); ++j) { + Vec2i currPos = pos + Vec2i(i, j); + if (isInside(currPos) == true && + isInsideSurface(toSurfCoords(currPos)) == true) { + // Cell *unitCell = getCell(currPos); + // if(unitCell == testCell) { + if (isNextTo(testPos, currPos) == true) { + return true; + } + } + } + } + } + + return false; } // is testPos in the cells of unitType where unitType's position is pos bool Map::isInUnitTypeCells(const UnitType *ut, const Vec2i &pos, - const Vec2i &testPos) const { - assert(ut != NULL); - if(ut == NULL) { - throw megaglest_runtime_error("ut == NULL"); - } - - if(isInside(testPos) && isInsideSurface(toSurfCoords(testPos))) { - Cell *testCell = getCell(testPos); - for(int i=0; i < ut->getSize(); ++i){ - for(int j = 0; j < ut->getSize(); ++j) { - Vec2i currPos = pos + Vec2i(i, j); - if(isInside(currPos) && isInsideSurface(toSurfCoords(currPos))) { - Cell *unitCell = getCell(currPos); - if(unitCell == testCell) { - return true; - } - } - } - } - } - return false; + const Vec2i &testPos) const { + assert(ut != NULL); + if (ut == NULL) { + throw megaglest_runtime_error("ut == NULL"); + } + + if (isInside(testPos) && isInsideSurface(toSurfCoords(testPos))) { + Cell *testCell = getCell(testPos); + for (int i = 0; i < ut->getSize(); ++i) { + for (int j = 0; j < ut->getSize(); ++j) { + Vec2i currPos = pos + Vec2i(i, j); + if (isInside(currPos) && isInsideSurface(toSurfCoords(currPos))) { + Cell *unitCell = getCell(currPos); + if (unitCell == testCell) { + return true; + } + } + } + } + } + return false; } -//put a units into the cells -void Map::putUnitCells(Unit *unit, const Vec2i &pos, bool ignoreSkill, bool threaded) { - assert(unit != NULL); - if(unit == NULL) { - throw megaglest_runtime_error("ut == NULL"); - } - putUnitCellsPrivate(unit, pos, unit->getType(), false, threaded); - - // block space for morphing units - if(ignoreSkill==false && - unit->getCurrSkill() != NULL && - unit->getCurrSkill()->getClass() == scMorph) { - Command *command= unit->getCurrCommand(); - if(command != NULL && command->getCommandType()->commandTypeClass == ccMorph){ - const MorphCommandType *mct= static_cast(command->getCommandType()); - putUnitCellsPrivate(unit, pos, mct->getMorphUnit(),true, threaded); - unit->setMorphFieldsBlocked(true); - } - } +// put a units into the cells +void Map::putUnitCells(Unit *unit, const Vec2i &pos, bool ignoreSkill, + bool threaded) { + assert(unit != NULL); + if (unit == NULL) { + throw megaglest_runtime_error("ut == NULL"); + } + putUnitCellsPrivate(unit, pos, unit->getType(), false, threaded); + + // block space for morphing units + if (ignoreSkill == false && unit->getCurrSkill() != NULL && + unit->getCurrSkill()->getClass() == scMorph) { + Command *command = unit->getCurrCommand(); + if (command != NULL && + command->getCommandType()->commandTypeClass == ccMorph) { + const MorphCommandType *mct = + static_cast(command->getCommandType()); + putUnitCellsPrivate(unit, pos, mct->getMorphUnit(), true, threaded); + unit->setMorphFieldsBlocked(true); + } + } } -void Map::putUnitCellsPrivate(Unit *unit, const Vec2i &pos, const UnitType *ut, bool isMorph, bool threaded) { - assert(unit != NULL); - if(unit == NULL) { - throw megaglest_runtime_error("ut == NULL"); - } - - bool canPutInCell = true; - Field field=ut->getField(); - for(int i = 0; i < ut->getSize(); ++i) { - for(int j = 0; j < ut->getSize(); ++j) { - Vec2i currPos= pos + Vec2i(i, j); - assert(isInside(currPos)); - if(isInside(currPos) == false) { - throw megaglest_runtime_error("isInside(currPos) == false"); - } - - if( ut->hasCellMap() == false || ut->getCellMapCell(i, j, unit->getModelFacing())) { - if(getCell(currPos)->getUnit(field) != NULL && - getCell(currPos)->getUnit(field) != unit) { - -// TT: is this ok ? - // If unit tries to move into a cell where another unit resides - // cancel the move command - if(unit->getCurrSkill() != NULL && - unit->getCurrSkill()->getClass() == scMove) { - canPutInCell = false; - //unit->setCurrSkill(scStop); - //unit->finishCommand(); - - //SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] POSSIBLE ERROR [getCell(currPos)->getUnit(unit->getCurrField()) != NULL] currPos [%s] unit [%s] cell unit [%s]\n", - // __FILE__,__FUNCTION__,__LINE__, - // currPos.getString().c_str(), - // unit->toString().c_str(), - // getCell(currPos)->getUnit(unit->getCurrField())->toString().c_str()); - } -//TT: Nonsens? -// else { -// // If the unit trying to move into the cell is not in the moving state -// // it is likely being created or morphed so we will will log the error -// canPutInCell = false; -// // throw megaglest_runtime_error("getCell(currPos)->getUnit(unit->getCurrField()) != NULL"); -// SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] ERROR [getCell(currPos)->getUnit(unit->getCurrField()) != NULL] currPos [%s] unit [%s] cell unit [%s]\n", -// __FILE__,__FUNCTION__,__LINE__, -// currPos.getString().c_str(), -// unit->toString().c_str(), -// getCell(currPos)->getUnit(unit->getCurrField())->toString().c_str()); -// } - } - - - if(getCell(currPos)->getUnit(field) == NULL || - getCell(currPos)->getUnit(field) == unit) { - if(isMorph) { - // unit is beeing morphed to another unit with maybe other field. - getCell(currPos)->setUnit(field, unit); - canPutInCell = false; - } - if(canPutInCell == true) { - getCell(currPos)->setUnit(unit->getCurrField(), unit); - } - } - else if(canPutInCell == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Trying to move unit [%d - %s] into occupied cell [%s] and field = %d, unit already in cell [%d - %s] ",unit->getId(),unit->getType()->getName(false).c_str(),pos.getString().c_str(),field,getCell(currPos)->getUnit(field)->getId(),getCell(currPos)->getUnit(field)->getType()->getName(false).c_str()); - throw megaglest_runtime_error(szBuf); - } - } - else if(ut->hasCellMap() == true && - ut->getAllowEmptyCellMap() == true && - ut->hasEmptyCellMap() == true) { - getCell(currPos)->setUnitWithEmptyCellMap(unit->getCurrField(), unit); - - //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] currPos = %s unit = %s\n", - // __FILE__,__FUNCTION__,__LINE__, - // currPos.getString().c_str(), - // unit->toString().c_str()); - } - } - } - if(canPutInCell == true) { - unit->setPos(pos, false, threaded); - } +void Map::putUnitCellsPrivate(Unit *unit, const Vec2i &pos, const UnitType *ut, + bool isMorph, bool threaded) { + assert(unit != NULL); + if (unit == NULL) { + throw megaglest_runtime_error("ut == NULL"); + } + + bool canPutInCell = true; + Field field = ut->getField(); + for (int i = 0; i < ut->getSize(); ++i) { + for (int j = 0; j < ut->getSize(); ++j) { + Vec2i currPos = pos + Vec2i(i, j); + assert(isInside(currPos)); + if (isInside(currPos) == false) { + throw megaglest_runtime_error("isInside(currPos) == false"); + } + + if (ut->hasCellMap() == false || + ut->getCellMapCell(i, j, unit->getModelFacing())) { + if (getCell(currPos)->getUnit(field) != NULL && + getCell(currPos)->getUnit(field) != unit) { + + // TT: is this ok ? + // If unit tries to move into a cell where another unit resides + // cancel the move command + if (unit->getCurrSkill() != NULL && + unit->getCurrSkill()->getClass() == scMove) { + canPutInCell = false; + // unit->setCurrSkill(scStop); + // unit->finishCommand(); + + // SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s + // Line: %d] POSSIBLE ERROR + // [getCell(currPos)->getUnit(unit->getCurrField()) != NULL] currPos + // [%s] unit [%s] cell unit [%s]\n", + // __FILE__,__FUNCTION__,__LINE__, + // currPos.getString().c_str(), + // unit->toString().c_str(), + // getCell(currPos)->getUnit(unit->getCurrField())->toString().c_str()); + } + // TT: Nonsens? + // else { + // // If the unit trying to move into the cell + // is not in the moving state + // // it is likely being created or morphed so + // we will will log the error canPutInCell = + // false; + // // throw + // megaglest_runtime_error("getCell(currPos)->getUnit(unit->getCurrField()) + //!= NULL"); + // SystemFlags::OutputDebug(SystemFlags::debugError,"In + // [%s::%s Line: %d] ERROR + // [getCell(currPos)->getUnit(unit->getCurrField()) + // != NULL] currPos [%s] unit [%s] cell unit + // [%s]\n", + // __FILE__,__FUNCTION__,__LINE__, + // currPos.getString().c_str(), + // unit->toString().c_str(), + // getCell(currPos)->getUnit(unit->getCurrField())->toString().c_str()); + // } + } + + if (getCell(currPos)->getUnit(field) == NULL || + getCell(currPos)->getUnit(field) == unit) { + if (isMorph) { + // unit is beeing morphed to another unit with maybe other field. + getCell(currPos)->setUnit(field, unit); + canPutInCell = false; + } + if (canPutInCell == true) { + getCell(currPos)->setUnit(unit->getCurrField(), unit); + } + } else if (canPutInCell == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "Trying to move unit [%d - %s] into occupied cell [%s] and " + "field = %d, unit already in cell [%d - %s] ", + unit->getId(), unit->getType()->getName(false).c_str(), + pos.getString().c_str(), field, + getCell(currPos)->getUnit(field)->getId(), + getCell(currPos) + ->getUnit(field) + ->getType() + ->getName(false) + .c_str()); + throw megaglest_runtime_error(szBuf); + } + } else if (ut->hasCellMap() == true && + ut->getAllowEmptyCellMap() == true && + ut->hasEmptyCellMap() == true) { + getCell(currPos)->setUnitWithEmptyCellMap(unit->getCurrField(), unit); + + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d] currPos = %s unit = %s\n", + // __FILE__,__FUNCTION__,__LINE__, + // currPos.getString().c_str(), + // unit->toString().c_str()); + } + } + } + if (canPutInCell == true) { + unit->setPos(pos, false, threaded); + } } -//removes a unit from cells +// removes a unit from cells void Map::clearUnitCells(Unit *unit, const Vec2i &pos, bool ignoreSkill) { - assert(unit != NULL); - if(unit == NULL) { - throw megaglest_runtime_error("unit == NULL"); - } - - const UnitType *ut= unit->getType(); - Field currentField=unit->getCurrField(); - - if(ignoreSkill==false && - unit->getCurrSkill() != NULL && - unit->getCurrSkill()->getClass() == scMorph && - unit->getMorphFieldsBlocked() == true) { - Command *command= unit->getCurrCommand(); - const MorphCommandType *mct= static_cast(command->getCommandType()); - if(unit->getType()->getSize()<=mct->getMorphUnit()->getSize()){ - ut=mct->getMorphUnit(); - currentField=ut->getField(); - unit->setMorphFieldsBlocked(false); - } - } - - - for(int i=0; igetSize(); ++i){ - for(int j=0; jgetSize(); ++j){ - Vec2i currPos= pos + Vec2i(i, j); - assert(isInside(currPos)); - if(isInside(currPos) == false) { - throw megaglest_runtime_error("isInside(currPos) == false"); - } - - if(ut->hasCellMap() == false || ut->getCellMapCell(i, j, unit->getModelFacing())) { - // This seems to be a bad assert since you can clear the cell - // for many reasons including a unit dieing. - - //assert(getCell(currPos)->getUnit(unit->getCurrField()) == unit || getCell(currPos)->getUnit(unit->getCurrField()) == NULL); - //if(getCell(currPos)->getUnit(unit->getCurrField()) != unit && getCell(currPos)->getUnit(unit->getCurrField()) != NULL) { - // throw megaglest_runtime_error("getCell(currPos)->getUnit(unit->getCurrField()) != unit"); - //SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] ERROR [getCell(currPos)->getUnit(unit->getCurrField()) != unit] currPos [%s] unit [%s] cell unit [%s]\n", - // __FILE__,__FUNCTION__,__LINE__, - // currPos.getString().c_str(), - // unit->toString().c_str(), - // (getCell(currPos)->getUnit(unit->getCurrField()) != NULL ? getCell(currPos)->getUnit(unit->getCurrField())->toString().c_str() : "NULL")); - //} - - // Only clear the cell if its the unit we expect to clear out of it - if(getCell(currPos)->getUnit(currentField) == unit) { - getCell(currPos)->setUnit(currentField, NULL); - } - } - else if(ut->hasCellMap() == true && - ut->getAllowEmptyCellMap() == true && - ut->hasEmptyCellMap() == true) { - getCell(currPos)->setUnitWithEmptyCellMap(currentField, NULL); - - //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] currPos = %s unit = %s\n", - // __FILE__,__FUNCTION__,__LINE__, - // currPos.getString().c_str(), - // unit->toString().c_str()); - } - } - } + assert(unit != NULL); + if (unit == NULL) { + throw megaglest_runtime_error("unit == NULL"); + } + + const UnitType *ut = unit->getType(); + Field currentField = unit->getCurrField(); + + if (ignoreSkill == false && unit->getCurrSkill() != NULL && + unit->getCurrSkill()->getClass() == scMorph && + unit->getMorphFieldsBlocked() == true) { + Command *command = unit->getCurrCommand(); + const MorphCommandType *mct = + static_cast(command->getCommandType()); + if (unit->getType()->getSize() <= mct->getMorphUnit()->getSize()) { + ut = mct->getMorphUnit(); + currentField = ut->getField(); + unit->setMorphFieldsBlocked(false); + } + } + + for (int i = 0; i < ut->getSize(); ++i) { + for (int j = 0; j < ut->getSize(); ++j) { + Vec2i currPos = pos + Vec2i(i, j); + assert(isInside(currPos)); + if (isInside(currPos) == false) { + throw megaglest_runtime_error("isInside(currPos) == false"); + } + + if (ut->hasCellMap() == false || + ut->getCellMapCell(i, j, unit->getModelFacing())) { + // This seems to be a bad assert since you can clear the cell + // for many reasons including a unit dieing. + + // assert(getCell(currPos)->getUnit(unit->getCurrField()) == unit || + // getCell(currPos)->getUnit(unit->getCurrField()) == NULL); + // if(getCell(currPos)->getUnit(unit->getCurrField()) != unit && + // getCell(currPos)->getUnit(unit->getCurrField()) != NULL) { throw + // megaglest_runtime_error("getCell(currPos)->getUnit(unit->getCurrField()) + //!= unit"); SystemFlags::OutputDebug(SystemFlags::debugError,"In + // [%s::%s Line: %d] ERROR + // [getCell(currPos)->getUnit(unit->getCurrField()) != unit] currPos + // [%s] unit [%s] cell unit [%s]\n", + // __FILE__,__FUNCTION__,__LINE__, + // currPos.getString().c_str(), + // unit->toString().c_str(), + // (getCell(currPos)->getUnit(unit->getCurrField()) != NULL ? + // getCell(currPos)->getUnit(unit->getCurrField())->toString().c_str() + // : "NULL")); + //} + + // Only clear the cell if its the unit we expect to clear out of it + if (getCell(currPos)->getUnit(currentField) == unit) { + getCell(currPos)->setUnit(currentField, NULL); + } + } else if (ut->hasCellMap() == true && + ut->getAllowEmptyCellMap() == true && + ut->hasEmptyCellMap() == true) { + getCell(currPos)->setUnitWithEmptyCellMap(currentField, NULL); + + // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: + // %d] currPos = %s unit = %s\n", + // __FILE__,__FUNCTION__,__LINE__, + // currPos.getString().c_str(), + // unit->toString().c_str()); + } + } + } } // ==================== misc ==================== -//return if unit is next to pos +// return if unit is next to pos bool Map::isNextTo(const Vec2i &pos, const Unit *unit) const { - for(int i=-1; i<=1; ++i) { - for(int j=-1; j<=1; ++j) { - if(isInside(pos.x+i, pos.y+j) && isInsideSurface(toSurfCoords(Vec2i(pos.x+i, pos.y+j)))) { - if(getCell(pos.x+i, pos.y+j)->getUnit(fLand) == unit) { - return true; - } - else if(getCell(pos.x+i, pos.y+j)->getUnitWithEmptyCellMap(fLand) == unit) { - return true; - } - } - } - } - return false; + for (int i = -1; i <= 1; ++i) { + for (int j = -1; j <= 1; ++j) { + if (isInside(pos.x + i, pos.y + j) && + isInsideSurface(toSurfCoords(Vec2i(pos.x + i, pos.y + j)))) { + if (getCell(pos.x + i, pos.y + j)->getUnit(fLand) == unit) { + return true; + } else if (getCell(pos.x + i, pos.y + j) + ->getUnitWithEmptyCellMap(fLand) == unit) { + return true; + } + } + } + } + return false; } -//return if unit is next to pos +// return if unit is next to pos bool Map::isNextTo(const Unit *unit1, const Unit *unit2) const { - Vec2i pos = unit1->getPosNotThreadSafe(); - const UnitType *ut = unit1->getType(); - for (int y=-1; y < ut->getSize()+1; ++y) { - for (int x=-1; x < ut->getSize()+1; ++x) { - Vec2i cellPos = pos + Vec2i(x, y); - if(isInside(cellPos) && isInsideSurface(toSurfCoords(cellPos))) { - if(getCell(cellPos)->getUnit(fLand) == unit2) { - return true; - } - else if(getCell(cellPos)->getUnitWithEmptyCellMap(fLand) == unit2) { - return true; - } - } - } - } + Vec2i pos = unit1->getPosNotThreadSafe(); + const UnitType *ut = unit1->getType(); + for (int y = -1; y < ut->getSize() + 1; ++y) { + for (int x = -1; x < ut->getSize() + 1; ++x) { + Vec2i cellPos = pos + Vec2i(x, y); + if (isInside(cellPos) && isInsideSurface(toSurfCoords(cellPos))) { + if (getCell(cellPos)->getUnit(fLand) == unit2) { + return true; + } else if (getCell(cellPos)->getUnitWithEmptyCellMap(fLand) == unit2) { + return true; + } + } + } + } - return false; + return false; } -//return if unit is next to pos +// return if unit is next to pos bool Map::isNextTo(const Vec2i &pos, const Vec2i &nextToPos) const { - for(int i=-1; i<=1; ++i) { - for(int j=-1; j<=1; ++j) { - if(isInside(pos.x+i, pos.y+j) && isInsideSurface(toSurfCoords(Vec2i(pos.x+i, pos.y+j)))) { - if(getCell(pos.x+i, pos.y+j) == getCell(nextToPos.x,nextToPos.y)) { - return true; - } - } - } - } - return false; + for (int i = -1; i <= 1; ++i) { + for (int j = -1; j <= 1; ++j) { + if (isInside(pos.x + i, pos.y + j) && + isInsideSurface(toSurfCoords(Vec2i(pos.x + i, pos.y + j)))) { + if (getCell(pos.x + i, pos.y + j) == + getCell(nextToPos.x, nextToPos.y)) { + return true; + } + } + } + } + return false; } -void Map::clampPos(Vec2i &pos) const{ - if(pos.x<0){ - pos.x=0; - } - if(pos.y<0){ - pos.y=0; - } - if(pos.x>=w){ - pos.x=w-1; - } - if(pos.y>=h){ - pos.y=h-1; - } +void Map::clampPos(Vec2i &pos) const { + if (pos.x < 0) { + pos.x = 0; + } + if (pos.y < 0) { + pos.y = 0; + } + if (pos.x >= w) { + pos.x = w - 1; + } + if (pos.y >= h) { + pos.y = h - 1; + } } void Map::prepareTerrain(const Unit *unit) { - Chrono chrono; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); - - flatternTerrain(unit); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis()); - - computeNormals(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis()); - - computeInterpolatedHeights(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis()); + Chrono chrono; + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) + chrono.start(); + + flatternTerrain(unit); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld\n", + __FILE__, __FUNCTION__, __LINE__, + chrono.getMillis()); + + computeNormals(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld\n", + __FILE__, __FUNCTION__, __LINE__, + chrono.getMillis()); + + computeInterpolatedHeights(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance) + .enabled && + chrono.getMillis() > 0) + SystemFlags::OutputDebug(SystemFlags::debugPerformance, + "In [%s::%s Line: %d] took msecs: %lld\n", + __FILE__, __FUNCTION__, __LINE__, + chrono.getMillis()); } // ==================== PRIVATE ==================== // ==================== compute ==================== -void Map::flatternTerrain(const Unit *unit){ - float refHeight= getSurfaceCell(toSurfCoords(unit->getCenteredPos()))->getHeight(); - for(int i=-1; i<=unit->getType()->getSize(); ++i){ - for(int j=-1; j<=unit->getType()->getSize(); ++j){ - Vec2i pos= unit->getPosNotThreadSafe()+Vec2i(i, j); - if(isInside(pos) && isInsideSurface(toSurfCoords(pos))) { - Cell *c= getCell(pos); - SurfaceCell *sc= getSurfaceCell(toSurfCoords(pos)); - //we change height if pos is inside world, if its free or ocupied by the currenty building - if(sc->getObject() == NULL && (c->getUnit(fLand)==NULL || c->getUnit(fLand)==unit)) { - sc->setHeight(refHeight,true); - } - } +void Map::flatternTerrain(const Unit *unit) { + float refHeight = + getSurfaceCell(toSurfCoords(unit->getCenteredPos()))->getHeight(); + for (int i = -1; i <= unit->getType()->getSize(); ++i) { + for (int j = -1; j <= unit->getType()->getSize(); ++j) { + Vec2i pos = unit->getPosNotThreadSafe() + Vec2i(i, j); + if (isInside(pos) && isInsideSurface(toSurfCoords(pos))) { + Cell *c = getCell(pos); + SurfaceCell *sc = getSurfaceCell(toSurfCoords(pos)); + // we change height if pos is inside world, if its free or ocupied by + // the currenty building + if (sc->getObject() == NULL && + (c->getUnit(fLand) == NULL || c->getUnit(fLand) == unit)) { + sc->setHeight(refHeight, true); } + } } + } } -//compute normals -void Map::computeNormals(){ - //compute center normals - for(int i=1; isetNormal( - getSurfaceCell(i, j)->getVertex().normal(getSurfaceCell(i, j-1)->getVertex(), - getSurfaceCell(i+1, j)->getVertex(), - getSurfaceCell(i, j+1)->getVertex(), - getSurfaceCell(i-1, j)->getVertex())); - } +// compute normals +void Map::computeNormals() { + // compute center normals + for (int i = 1; i < surfaceW - 1; ++i) { + for (int j = 1; j < surfaceH - 1; ++j) { + getSurfaceCell(i, j)->setNormal(getSurfaceCell(i, j)->getVertex().normal( + getSurfaceCell(i, j - 1)->getVertex(), + getSurfaceCell(i + 1, j)->getVertex(), + getSurfaceCell(i, j + 1)->getVertex(), + getSurfaceCell(i - 1, j)->getVertex())); } + } } -void Map::computeInterpolatedHeights(){ - - for(int i=0; isetHeight(getSurfaceCell(toSurfCoords(Vec2i(i, j)))->getHeight()); - } - } - - for(int i=1; isetHeight(getSurfaceCell(i, j)->getHeight()); - } - else if(k!=0 && l==0){ - getCell(i*cellScale+k, j*cellScale)->setHeight(( - getSurfaceCell(i, j)->getHeight()+ - getSurfaceCell(i+1, j)->getHeight())/2.f); - } - else if(l!=0 && k==0){ - getCell(i*cellScale, j*cellScale+l)->setHeight(( - getSurfaceCell(i, j)->getHeight()+ - getSurfaceCell(i, j+1)->getHeight())/2.f); - } - else{ - getCell(i*cellScale+k, j*cellScale+l)->setHeight(( - getSurfaceCell(i, j)->getHeight()+ - getSurfaceCell(i, j+1)->getHeight()+ - getSurfaceCell(i+1, j)->getHeight()+ - getSurfaceCell(i+1, j+1)->getHeight())/4.f); - } - } - } - } - } +void Map::computeInterpolatedHeights() { + + for (int i = 0; i < w; ++i) { + for (int j = 0; j < h; ++j) { + getCell(i, j)->setHeight( + getSurfaceCell(toSurfCoords(Vec2i(i, j)))->getHeight()); + } + } + + for (int i = 1; i < surfaceW - 1; ++i) { + for (int j = 1; j < surfaceH - 1; ++j) { + for (int k = 0; k < cellScale; ++k) { + for (int l = 0; l < cellScale; ++l) { + if (k == 0 && l == 0) { + getCell(i * cellScale, j * cellScale) + ->setHeight(getSurfaceCell(i, j)->getHeight()); + } else if (k != 0 && l == 0) { + getCell(i * cellScale + k, j * cellScale) + ->setHeight((getSurfaceCell(i, j)->getHeight() + + getSurfaceCell(i + 1, j)->getHeight()) / + 2.f); + } else if (l != 0 && k == 0) { + getCell(i * cellScale, j * cellScale + l) + ->setHeight((getSurfaceCell(i, j)->getHeight() + + getSurfaceCell(i, j + 1)->getHeight()) / + 2.f); + } else { + getCell(i * cellScale + k, j * cellScale + l) + ->setHeight((getSurfaceCell(i, j)->getHeight() + + getSurfaceCell(i, j + 1)->getHeight() + + getSurfaceCell(i + 1, j)->getHeight() + + getSurfaceCell(i + 1, j + 1)->getHeight()) / + 4.f); + } + } + } + } + } } void Map::smoothSurface(Tileset *tileset) { - float *oldHeights = new float[getSurfaceCellArraySize()]; - //int arraySize=getSurfaceCellArraySize(); - - for (int i = 0; i < getSurfaceCellArraySize(); ++i) { - oldHeights[i] = surfaceCells[i].getHeight(); - } - - for (int i = 1; i < surfaceW - 1; ++i) { - for (int j = 1; j < surfaceH - 1; ++j) { - float height = 0.f; - float numUsedToSmooth = 0.f; - for (int k = -1; k <= 1; ++k) { - for (int l = -1; l <= 1; ++l) { + float *oldHeights = new float[getSurfaceCellArraySize()]; + // int arraySize=getSurfaceCellArraySize(); + + for (int i = 0; i < getSurfaceCellArraySize(); ++i) { + oldHeights[i] = surfaceCells[i].getHeight(); + } + + for (int i = 1; i < surfaceW - 1; ++i) { + for (int j = 1; j < surfaceH - 1; ++j) { + float height = 0.f; + float numUsedToSmooth = 0.f; + for (int k = -1; k <= 1; ++k) { + for (int l = -1; l <= 1; ++l) { #ifdef USE_STREFLOP - if (cliffLevel<=0.1f || cliffLevel > streflop::fabs(static_cast(oldHeights[(j) * surfaceW + (i)] - - oldHeights[(j + k) * surfaceW + (i + l)]))) { + if (cliffLevel <= 0.1f || + cliffLevel > streflop::fabs(static_cast( + oldHeights[(j)*surfaceW + (i)] - + oldHeights[(j + k) * surfaceW + (i + l)]))) { #else - if (cliffLevel<=0.1f || cliffLevel > fabs(oldHeights[(j) * surfaceW + (i)] - - oldHeights[(j + k) * surfaceW + (i + l)])) { + if (cliffLevel <= 0.1f || + cliffLevel > fabs(oldHeights[(j)*surfaceW + (i)] - + oldHeights[(j + k) * surfaceW + (i + l)])) { #endif - height += oldHeights[(j + k) * surfaceW + (i + l)]; - numUsedToSmooth++; - } - else { - // we have something which should not be smoothed! - // This is a cliff and must be textured -> set cliff texture - getSurfaceCell(i, j)->setSurfaceType(5); - //set invisible blocking object and replace resource objects - //and non blocking objects with invisible blocker too - Object *formerObject = - getSurfaceCell(i, j)->getObject(); - if (formerObject != NULL) { - if (formerObject->getWalkable() - || formerObject->getResource() != NULL) { - delete formerObject; - formerObject = NULL; - } - } - if (formerObject == NULL) { - Object *o = new Object(tileset->getObjectType(9), - getSurfaceCell(i, j)->getVertex(), - Vec2i(i,j)); - getSurfaceCell(i, j)->setObject(o); - } - } - } - } - - height /= numUsedToSmooth; - if(maxMapHeightsetHeight(height); - Object *object = getSurfaceCell(i, j)->getObject(); - if (object != NULL) { - object->setHeight(height); - } - } - } - delete[] oldHeights; + height += oldHeights[(j + k) * surfaceW + (i + l)]; + numUsedToSmooth++; + } else { + // we have something which should not be smoothed! + // This is a cliff and must be textured -> set cliff texture + getSurfaceCell(i, j)->setSurfaceType(5); + // set invisible blocking object and replace resource objects + // and non blocking objects with invisible blocker too + Object *formerObject = getSurfaceCell(i, j)->getObject(); + if (formerObject != NULL) { + if (formerObject->getWalkable() || + formerObject->getResource() != NULL) { + delete formerObject; + formerObject = NULL; + } + } + if (formerObject == NULL) { + Object *o = + new Object(tileset->getObjectType(9), + getSurfaceCell(i, j)->getVertex(), Vec2i(i, j)); + getSurfaceCell(i, j)->setObject(o); + } + } + } + } + + height /= numUsedToSmooth; + if (maxMapHeight < height) { + maxMapHeight = height; + } + + getSurfaceCell(i, j)->setHeight(height); + Object *object = getSurfaceCell(i, j)->getObject(); + if (object != NULL) { + object->setHeight(height); + } + } + } + delete[] oldHeights; } -void Map::computeNearSubmerged(){ - - for(int i=0; isetNearSubmerged(anySubmerged); - } - } +void Map::computeNearSubmerged() { + + for (int i = 0; i < surfaceW - 1; ++i) { + for (int j = 0; j < surfaceH - 1; ++j) { + bool anySubmerged = false; + for (int k = -1; k <= 2; ++k) { + for (int l = -1; l <= 2; ++l) { + Vec2i pos = Vec2i(i + k, j + l); + if (isInsideSurface(pos) && isInsideSurface(toSurfCoords(pos))) { + if (getSubmerged(getSurfaceCell(pos))) + anySubmerged = true; + } + } + } + getSurfaceCell(i, j)->setNearSubmerged(anySubmerged); + } + } } -void Map::computeCellColors(){ - for(int i=0; igetHeight()*1.5f, 1.f, 1.5f); - sc->setColor(Vec3f(1.0f, 1.0f, 1.0f)/factor); - } - else{ - sc->setColor(Vec3f(1.0f, 1.0f, 1.0f)); - } - } - } +void Map::computeCellColors() { + for (int i = 0; i < surfaceW; ++i) { + for (int j = 0; j < surfaceH; ++j) { + SurfaceCell *sc = getSurfaceCell(i, j); + if (getDeepSubmerged(sc)) { + float factor = clamp(waterLevel - sc->getHeight() * 1.5f, 1.f, 1.5f); + sc->setColor(Vec3f(1.0f, 1.0f, 1.0f) / factor); + } else { + sc->setColor(Vec3f(1.0f, 1.0f, 1.0f)); + } + } + } } void Map::saveGame(XmlNode *rootNode) const { - std::map mapTagReplacements; - XmlNode *mapNode = rootNode->addChild("Map"); - -// string title; - mapNode->addAttribute("title",title, mapTagReplacements); -// float waterLevel; - mapNode->addAttribute("waterLevel",floatToStr(waterLevel,6), mapTagReplacements); -// float heightFactor; - mapNode->addAttribute("heightFactor",floatToStr(heightFactor,6), mapTagReplacements); -// float cliffLevel; - mapNode->addAttribute("cliffLevel",floatToStr(cliffLevel,6), mapTagReplacements); -// int cameraHeight; - mapNode->addAttribute("cameraHeight",intToStr(cameraHeight), mapTagReplacements); -// int w; - mapNode->addAttribute("w",intToStr(w), mapTagReplacements); -// int h; - mapNode->addAttribute("h",intToStr(h), mapTagReplacements); -// int surfaceW; - mapNode->addAttribute("surfaceW",intToStr(surfaceW), mapTagReplacements); -// int surfaceH; - mapNode->addAttribute("surfaceH",intToStr(surfaceH), mapTagReplacements); -// int maxPlayers; - mapNode->addAttribute("maxPlayers",intToStr(maxPlayers), mapTagReplacements); -// Cell *cells; - //printf("getCellArraySize() = %d\n",getCellArraySize()); -// for(unsigned int i = 0; i < getCellArraySize(); ++i) { -// Cell &cell = cells[i]; -// cell.saveGame(mapNode,i); -// } -// SurfaceCell *surfaceCells; - //printf("getSurfaceCellArraySize() = %d\n",getSurfaceCellArraySize()); - - string exploredList = ""; - string visibleList = ""; - - for(unsigned int i = 0; i < (unsigned int)getSurfaceCellArraySize(); ++i) { - SurfaceCell &surfaceCell = surfaceCells[i]; - - if(exploredList != "") { - exploredList += ","; - } - - for(unsigned int j = 0; j < (unsigned int)GameConstants::maxPlayers; ++j) { - if(j > 0) { - exploredList += "|"; - } - - exploredList += intToStr(surfaceCell.isExplored(j)); - } - - if(visibleList != "") { - visibleList += ","; - } - - for(unsigned int j = 0; j < (unsigned int)GameConstants::maxPlayers; ++j) { - if(j > 0) { - visibleList += "|"; - } - - visibleList += intToStr(surfaceCell.isVisible(j)); - } - - surfaceCell.saveGame(mapNode,i); - - if(i > 0 && i % 100 == 0) { - XmlNode *surfaceCellNode = mapNode->addChild("SurfaceCell"); - surfaceCellNode->addAttribute("batchIndex",intToStr(i), mapTagReplacements); - surfaceCellNode->addAttribute("exploredList",exploredList, mapTagReplacements); - surfaceCellNode->addAttribute("visibleList",visibleList, mapTagReplacements); - - exploredList = ""; - visibleList = ""; - } - } - - if(exploredList != "") { - XmlNode *surfaceCellNode = mapNode->addChild("SurfaceCell"); - surfaceCellNode->addAttribute("batchIndex",intToStr(getSurfaceCellArraySize()), mapTagReplacements); - surfaceCellNode->addAttribute("exploredList",exploredList, mapTagReplacements); - surfaceCellNode->addAttribute("visibleList",visibleList, mapTagReplacements); - } - -// Vec2i *startLocations; - for(unsigned int i = 0; i < (unsigned int)maxPlayers; ++i) { - XmlNode *startLocationsNode = mapNode->addChild("startLocations"); - startLocationsNode->addAttribute("location",startLocations[i].getString(), mapTagReplacements); - } -// Checksum checksumValue; -// mapNode->addAttribute("checksumValue",intToStr(checksumValue.getSum()), mapTagReplacements); -// float maxMapHeight; - mapNode->addAttribute("maxMapHeight",floatToStr(maxMapHeight,6), mapTagReplacements); -// string mapFile; - mapNode->addAttribute("mapFile",mapFile, mapTagReplacements); -} + std::map mapTagReplacements; + XmlNode *mapNode = rootNode->addChild("Map"); + + // string title; + mapNode->addAttribute("title", title, mapTagReplacements); + // float waterLevel; + mapNode->addAttribute("waterLevel", floatToStr(waterLevel, 6), + mapTagReplacements); + // float heightFactor; + mapNode->addAttribute("heightFactor", floatToStr(heightFactor, 6), + mapTagReplacements); + // float cliffLevel; + mapNode->addAttribute("cliffLevel", floatToStr(cliffLevel, 6), + mapTagReplacements); + // int cameraHeight; + mapNode->addAttribute("cameraHeight", intToStr(cameraHeight), + mapTagReplacements); + // int w; + mapNode->addAttribute("w", intToStr(w), mapTagReplacements); + // int h; + mapNode->addAttribute("h", intToStr(h), mapTagReplacements); + // int surfaceW; + mapNode->addAttribute("surfaceW", intToStr(surfaceW), mapTagReplacements); + // int surfaceH; + mapNode->addAttribute("surfaceH", intToStr(surfaceH), mapTagReplacements); + // int maxPlayers; + mapNode->addAttribute("maxPlayers", intToStr(maxPlayers), mapTagReplacements); + // Cell *cells; + // printf("getCellArraySize() = %d\n",getCellArraySize()); + // for(unsigned int i = 0; i < getCellArraySize(); ++i) { + // Cell &cell = cells[i]; + // cell.saveGame(mapNode,i); + // } + // SurfaceCell *surfaceCells; + // printf("getSurfaceCellArraySize() = %d\n",getSurfaceCellArraySize()); + + string exploredList = ""; + string visibleList = ""; + + for (unsigned int i = 0; i < (unsigned int)getSurfaceCellArraySize(); ++i) { + SurfaceCell &surfaceCell = surfaceCells[i]; + + if (exploredList != "") { + exploredList += ","; + } -void Map::loadGame(const XmlNode *rootNode, World *world) { - const XmlNode *mapNode = rootNode->getChild("Map"); + for (unsigned int j = 0; j < (unsigned int)GameConstants::maxPlayers; ++j) { + if (j > 0) { + exploredList += "|"; + } - //description = gameSettingsNode->getAttribute("description")->getValue(); + exploredList += intToStr(surfaceCell.isExplored(j)); + } -// for(unsigned int i = 0; i < getCellArraySize(); ++i) { -// Cell &cell = cells[i]; -// cell.saveGame(mapNode,i); -// } -// for(unsigned int i = 0; i < getSurfaceCellArraySize(); ++i) { -// SurfaceCell &surfaceCell = surfaceCells[i]; -// surfaceCell.saveGame(mapNode,i); -// } + if (visibleList != "") { + visibleList += ","; + } -// printf("getCellArraySize() = %d\n",getCellArraySize()); -// for(unsigned int i = 0; i < getCellArraySize(); ++i) { -// Cell &cell = cells[i]; -// cell.loadGame(mapNode,i,world); -// } + for (unsigned int j = 0; j < (unsigned int)GameConstants::maxPlayers; ++j) { + if (j > 0) { + visibleList += "|"; + } -// printf("getSurfaceCellArraySize() = %d\n",getSurfaceCellArraySize()); - for(unsigned int i = 0; i < (unsigned int)getSurfaceCellArraySize(); ++i) { - SurfaceCell &surfaceCell = surfaceCells[i]; - surfaceCell.loadGame(mapNode,i,world); - } - - int surfaceCellIndexExplored = 0; - int surfaceCellIndexVisible = 0; - vector surfaceCellNodeList = mapNode->getChildList("SurfaceCell"); - for(unsigned int i = 0; i < surfaceCellNodeList.size(); ++i) { - XmlNode *surfaceCellNode = surfaceCellNodeList[i]; - - //XmlNode *surfaceCellNode = mapNode->getChild("SurfaceCell"); - string exploredList = surfaceCellNode->getAttribute("exploredList")->getValue(); - string visibleList = surfaceCellNode->getAttribute("visibleList")->getValue(); - //int batchIndex = surfaceCellNode->getAttribute("batchIndex")->getIntValue(); - - vector tokensExplored; - Tokenize(exploredList,tokensExplored,","); - - //printf("=====================\nNew batchIndex = %d batchsize = %d\n",batchIndex,tokensExplored.size()); - //for(unsigned int j = 0; j < tokensExplored.size(); ++j) { - //string valueList = tokensExplored[j]; - //printf("valueList [%s]\n",valueList.c_str()); - //} - for(unsigned int j = 0; j < tokensExplored.size(); ++j) { - string valueList = tokensExplored[j]; - - //int surfaceCellIndex = (i * tokensExplored.size()) + j; - //printf("Loading sc = %d batchIndex = %d\n",surfaceCellIndexExplored,batchIndex); - SurfaceCell &surfaceCell = surfaceCells[surfaceCellIndexExplored]; - - vector tokensExploredValue; - Tokenize(valueList,tokensExploredValue,"|"); - -// if(tokensExploredValue.size() != GameConstants::maxPlayers) { -// for(unsigned int k = 0; k < tokensExploredValue.size(); ++k) { -// string value = tokensExploredValue[k]; -// printf("k = %d [%s]\n",k,value.c_str()); -// } -// throw megaglest_runtime_error("tokensExploredValue.size() [" + intToStr(tokensExploredValue.size()) + "] != GameConstants::maxPlayers"); -// } - for(unsigned int k = 0; k < tokensExploredValue.size(); ++k) { - string value = tokensExploredValue[k]; + visibleList += intToStr(surfaceCell.isVisible(j)); + } - surfaceCell.setExplored(k,strToInt(value) != 0); + surfaceCell.saveGame(mapNode, i); - //if(surfaceCell.isExplored(k) == true) { - // printf("Setting cell at index: %d for team: %d to: %d [%s]\n",surfaceCellIndexExplored,k,surfaceCell.isExplored(k),value.c_str()); - //} - } - surfaceCellIndexExplored++; - } + if (i > 0 && i % 100 == 0) { + XmlNode *surfaceCellNode = mapNode->addChild("SurfaceCell"); + surfaceCellNode->addAttribute("batchIndex", intToStr(i), + mapTagReplacements); + surfaceCellNode->addAttribute("exploredList", exploredList, + mapTagReplacements); + surfaceCellNode->addAttribute("visibleList", visibleList, + mapTagReplacements); - vector tokensVisible; - Tokenize(visibleList,tokensVisible,","); - for(unsigned int j = 0; j < tokensVisible.size(); ++j) { - string valueList = tokensVisible[j]; + exploredList = ""; + visibleList = ""; + } + } + + if (exploredList != "") { + XmlNode *surfaceCellNode = mapNode->addChild("SurfaceCell"); + surfaceCellNode->addAttribute( + "batchIndex", intToStr(getSurfaceCellArraySize()), mapTagReplacements); + surfaceCellNode->addAttribute("exploredList", exploredList, + mapTagReplacements); + surfaceCellNode->addAttribute("visibleList", visibleList, + mapTagReplacements); + } + + // Vec2i *startLocations; + for (unsigned int i = 0; i < (unsigned int)maxPlayers; ++i) { + XmlNode *startLocationsNode = mapNode->addChild("startLocations"); + startLocationsNode->addAttribute("location", startLocations[i].getString(), + mapTagReplacements); + } + // Checksum checksumValue; + // mapNode->addAttribute("checksumValue",intToStr(checksumValue.getSum()), + // mapTagReplacements); float maxMapHeight; + mapNode->addAttribute("maxMapHeight", floatToStr(maxMapHeight, 6), + mapTagReplacements); + // string mapFile; + mapNode->addAttribute("mapFile", mapFile, mapTagReplacements); +} - //int surfaceCellIndex = (i * tokensVisible.size()) + j; - SurfaceCell &surfaceCell = surfaceCells[surfaceCellIndexVisible]; +void Map::loadGame(const XmlNode *rootNode, World *world) { + const XmlNode *mapNode = rootNode->getChild("Map"); + + // description = gameSettingsNode->getAttribute("description")->getValue(); + + // for(unsigned int i = 0; i < getCellArraySize(); ++i) { + // Cell &cell = cells[i]; + // cell.saveGame(mapNode,i); + // } + // for(unsigned int i = 0; i < getSurfaceCellArraySize(); ++i) { + // SurfaceCell &surfaceCell = surfaceCells[i]; + // surfaceCell.saveGame(mapNode,i); + // } + + // printf("getCellArraySize() = %d\n",getCellArraySize()); + // for(unsigned int i = 0; i < getCellArraySize(); ++i) { + // Cell &cell = cells[i]; + // cell.loadGame(mapNode,i,world); + // } + + // printf("getSurfaceCellArraySize() = %d\n",getSurfaceCellArraySize()); + for (unsigned int i = 0; i < (unsigned int)getSurfaceCellArraySize(); ++i) { + SurfaceCell &surfaceCell = surfaceCells[i]; + surfaceCell.loadGame(mapNode, i, world); + } + + int surfaceCellIndexExplored = 0; + int surfaceCellIndexVisible = 0; + vector surfaceCellNodeList = mapNode->getChildList("SurfaceCell"); + for (unsigned int i = 0; i < surfaceCellNodeList.size(); ++i) { + XmlNode *surfaceCellNode = surfaceCellNodeList[i]; + + // XmlNode *surfaceCellNode = mapNode->getChild("SurfaceCell"); + string exploredList = + surfaceCellNode->getAttribute("exploredList")->getValue(); + string visibleList = + surfaceCellNode->getAttribute("visibleList")->getValue(); + // int batchIndex = + // surfaceCellNode->getAttribute("batchIndex")->getIntValue(); + + vector tokensExplored; + Tokenize(exploredList, tokensExplored, ","); + + // printf("=====================\nNew batchIndex = %d batchsize = + // %d\n",batchIndex,tokensExplored.size()); for(unsigned int j = 0; j < + // tokensExplored.size(); ++j) { string valueList = tokensExplored[j]; + // printf("valueList [%s]\n",valueList.c_str()); + //} + for (unsigned int j = 0; j < tokensExplored.size(); ++j) { + string valueList = tokensExplored[j]; + + // int surfaceCellIndex = (i * tokensExplored.size()) + j; + // printf("Loading sc = %d batchIndex = + // %d\n",surfaceCellIndexExplored,batchIndex); + SurfaceCell &surfaceCell = surfaceCells[surfaceCellIndexExplored]; + + vector tokensExploredValue; + Tokenize(valueList, tokensExploredValue, "|"); + + // if(tokensExploredValue.size() != + // GameConstants::maxPlayers) { for(unsigned int + // k = 0; k < tokensExploredValue.size(); ++k) { + // string value = tokensExploredValue[k]; + // printf("k = %d [%s]\n",k,value.c_str()); + // } + // throw + // megaglest_runtime_error("tokensExploredValue.size() [" + + // intToStr(tokensExploredValue.size()) + "] != + // GameConstants::maxPlayers"); + // } + for (unsigned int k = 0; k < tokensExploredValue.size(); ++k) { + string value = tokensExploredValue[k]; + + surfaceCell.setExplored(k, strToInt(value) != 0); + + // if(surfaceCell.isExplored(k) == true) { + // printf("Setting cell at index: %d for team: %d to: %d + //[%s]\n",surfaceCellIndexExplored,k,surfaceCell.isExplored(k),value.c_str()); + // } + } + surfaceCellIndexExplored++; + } - vector tokensVisibleValue; - Tokenize(valueList,tokensVisibleValue,"|"); + vector tokensVisible; + Tokenize(visibleList, tokensVisible, ","); + for (unsigned int j = 0; j < tokensVisible.size(); ++j) { + string valueList = tokensVisible[j]; -// if(tokensVisibleValue.size() != GameConstants::maxPlayers) { -// throw megaglest_runtime_error("tokensVisibleValue.size() [" + intToStr(tokensVisibleValue.size()) + "] != GameConstants::maxPlayers"); -// } + // int surfaceCellIndex = (i * tokensVisible.size()) + j; + SurfaceCell &surfaceCell = surfaceCells[surfaceCellIndexVisible]; - for(unsigned int k = 0; k < tokensVisibleValue.size(); ++k) { - string value = tokensVisibleValue[k]; + vector tokensVisibleValue; + Tokenize(valueList, tokensVisibleValue, "|"); - surfaceCell.setVisible(k,strToInt(value) != 0); - } - surfaceCellIndexVisible++; - } - } + // if(tokensVisibleValue.size() != + // GameConstants::maxPlayers) { throw + // megaglest_runtime_error("tokensVisibleValue.size() [" + + // intToStr(tokensVisibleValue.size()) + "] != + // GameConstants::maxPlayers"); + // } - computeNormals(); - computeInterpolatedHeights(); + for (unsigned int k = 0; k < tokensVisibleValue.size(); ++k) { + string value = tokensVisibleValue[k]; + + surfaceCell.setVisible(k, strToInt(value) != 0); + } + surfaceCellIndexVisible++; + } + } + + computeNormals(); + computeInterpolatedHeights(); } // ===================================================== // class PosCircularIterator // ===================================================== -PosCircularIterator::PosCircularIterator(const Map *map, const Vec2i ¢er, int radius){ - this->map= map; - this->radius= radius; - this->center= center; - pos= center - Vec2i(radius, radius); - pos.x-= 1; +PosCircularIterator::PosCircularIterator(const Map *map, const Vec2i ¢er, + int radius) { + this->map = map; + this->radius = radius; + this->center = center; + pos = center - Vec2i(radius, radius); + pos.x -= 1; } -bool PosCircularIterator::next(){ - - //iterate while dont find a cell that is inside the world - //and at less or equal distance that the radius - do{ - pos.x++; - if(pos.x > center.x+radius){ - pos.x= center.x-radius; - pos.y++; - } - if(pos.y>center.y+radius) - return false; - } +bool PosCircularIterator::next() { + + // iterate while dont find a cell that is inside the world + // and at less or equal distance that the radius + do { + pos.x++; + if (pos.x > center.x + radius) { + pos.x = center.x - radius; + pos.y++; + } + if (pos.y > center.y + radius) + return false; + } #ifdef USE_STREFLOP - while(streflop::floor(static_cast(pos.dist(center))) >= (radius+1) || !map->isInside(pos) || !map->isInsideSurface(map->toSurfCoords(pos)) ); + while (streflop::floor(static_cast(pos.dist(center))) >= + (radius + 1) || + !map->isInside(pos) || !map->isInsideSurface(map->toSurfCoords(pos))); #else - while(floor(pos.dist(center)) >= (radius+1) || !map->isInside(pos) || !map->isInsideSurface(map->toSurfCoords(pos)) ); + while (floor(pos.dist(center)) >= (radius + 1) || !map->isInside(pos) || + !map->isInsideSurface(map->toSurfCoords(pos))); #endif - return true; -} - -const Vec2i &PosCircularIterator::getPos(){ - return pos; + return true; } +const Vec2i &PosCircularIterator::getPos() { return pos; } // ===================================================== // class PosQuadIterator // ===================================================== -PosQuadIterator::PosQuadIterator(const Map *map,const Quad2i &quad, int step) { - this->map = map; - - this->quad= quad; - this->boundingRect= quad.computeBoundingRect(); - this->step= step; - pos= boundingRect.p[0]; - --pos.x; - pos.x= (pos.x/step)*step; - pos.y= (pos.y/step)*step; - //map->clampPos(pos); +PosQuadIterator::PosQuadIterator(const Map *map, const Quad2i &quad, int step) { + this->map = map; + + this->quad = quad; + this->boundingRect = quad.computeBoundingRect(); + this->step = step; + pos = boundingRect.p[0]; + --pos.x; + pos.x = (pos.x / step) * step; + pos.y = (pos.y / step) * step; + // map->clampPos(pos); } bool PosQuadIterator::next() { - do { - pos.x += step; - if(pos.x > boundingRect.p[1].x) { - pos.x = (boundingRect.p[0].x / step) * step; - pos.y += step; - } - if(pos.y > boundingRect.p[1].y) { - return false; - } - - //printf("pos [%s] boundingRect.p[0] [%s] boundingRect.p[1] [%s]\n",pos.getString().c_str(),boundingRect.p[0].getString().c_str(),boundingRect.p[1].getString().c_str()); - } - while(!quad.isInside(pos)); - - return true; + do { + pos.x += step; + if (pos.x > boundingRect.p[1].x) { + pos.x = (boundingRect.p[0].x / step) * step; + pos.y += step; + } + if (pos.y > boundingRect.p[1].y) { + return false; + } + + // printf("pos [%s] boundingRect.p[0] [%s] boundingRect.p[1] + // [%s]\n",pos.getString().c_str(),boundingRect.p[0].getString().c_str(),boundingRect.p[1].getString().c_str()); + } while (!quad.isInside(pos)); + + return true; } -//void PosQuadIterator::skipX() { +// void PosQuadIterator::skipX() { // pos.x+= step; -//} +// } -const Vec2i &PosQuadIterator::getPos(){ - return pos; -} +const Vec2i &PosQuadIterator::getPos() { return pos; } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/world/map.h b/source/glest_game/world/map.h index ea7103ab9..88f3e4b83 100644 --- a/source/glest_game/world/map.h +++ b/source/glest_game/world/map.h @@ -13,33 +13,32 @@ #define _GLEST_GAME_MAP_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include "vec.h" -#include "math_util.h" +#include "checksum.h" +#include "command.h" #include "command_type.h" +#include "game_constants.h" +#include "leak_dumper.h" #include "logger.h" +#include "math_util.h" #include "object.h" -#include "game_constants.h" #include "selection.h" -#include #include "unit_type.h" -#include "command.h" -#include "checksum.h" -#include "leak_dumper.h" - +#include "vec.h" +#include -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { -using Shared::Graphics::Vec4f; using Shared::Graphics::Quad2i; using Shared::Graphics::Rect2i; -using Shared::Graphics::Vec4f; +using Shared::Graphics::Texture2D; using Shared::Graphics::Vec2f; using Shared::Graphics::Vec2i; -using Shared::Graphics::Texture2D; +using Shared::Graphics::Vec4f; class Tileset; class Unit; @@ -56,54 +55,80 @@ class World; class Cell { private: - Unit *units[fieldCount]; //units on this cell - Unit *unitsWithEmptyCellMap[fieldCount]; //units with an empty cellmap on this cell - float height; + Unit *units[fieldCount]; // units on this cell + Unit *unitsWithEmptyCellMap[fieldCount]; // units with an empty cellmap on + // this cell + float height; private: - Cell(Cell&); - void operator=(Cell&); + Cell(Cell &); + void operator=(Cell &); public: - Cell(); - - //get - inline Unit *getUnit(int field) const { if(field >= fieldCount) { throw megaglest_runtime_error("Invalid field value" + intToStr(field));} return units[field];} - inline Unit *getUnitWithEmptyCellMap(int field) const { if(field >= fieldCount) { throw megaglest_runtime_error("Invalid field value" + intToStr(field));} return unitsWithEmptyCellMap[field];} - inline float getHeight() const {return truncateDecimal(height,6);} - - inline void setUnit(int field, Unit *unit) { if(field >= fieldCount) { throw megaglest_runtime_error("Invalid field value" + intToStr(field));} units[field]= unit;} - inline void setUnitWithEmptyCellMap(int field, Unit *unit) { if(field >= fieldCount) { throw megaglest_runtime_error("Invalid field value" + intToStr(field));} unitsWithEmptyCellMap[field]= unit;} - inline void setHeight(float height) {this->height = truncateDecimal(height,6);} - - inline bool isFree(Field field) const { - Unit *unit = getUnit(field); - bool result = (unit == NULL || unit->isPutrefacting()); - - if(result == false) { - //printf("[%s] Line: %d returning false, unit id = %d [%s]\n",__FUNCTION__,__LINE__,getUnit(field)->getId(),getUnit(field)->getType()->getName().c_str()); - } - - return result; - } - - inline bool isFreeOrMightBeFreeSoon(Vec2i originPos, Vec2i cellPos, Field field) const { - Unit *unit = getUnit(field); - bool result = (unit == NULL || unit->isPutrefacting()); - - if(result == false) { - if(originPos.dist(cellPos) > 5 && unit->getType()->isMobile() == true) { - result = true; - } - - //printf("[%s] Line: %d returning false, unit id = %d [%s]\n",__FUNCTION__,__LINE__,getUnit(field)->getId(),getUnit(field)->getType()->getName().c_str()); - } - - return result; - } - - void saveGame(XmlNode *rootNode,int index) const; - void loadGame(const XmlNode *rootNode, int index, World *world); + Cell(); + + // get + inline Unit *getUnit(int field) const { + if (field >= fieldCount) { + throw megaglest_runtime_error("Invalid field value" + intToStr(field)); + } + return units[field]; + } + inline Unit *getUnitWithEmptyCellMap(int field) const { + if (field >= fieldCount) { + throw megaglest_runtime_error("Invalid field value" + intToStr(field)); + } + return unitsWithEmptyCellMap[field]; + } + inline float getHeight() const { return truncateDecimal(height, 6); } + + inline void setUnit(int field, Unit *unit) { + if (field >= fieldCount) { + throw megaglest_runtime_error("Invalid field value" + intToStr(field)); + } + units[field] = unit; + } + inline void setUnitWithEmptyCellMap(int field, Unit *unit) { + if (field >= fieldCount) { + throw megaglest_runtime_error("Invalid field value" + intToStr(field)); + } + unitsWithEmptyCellMap[field] = unit; + } + inline void setHeight(float height) { + this->height = truncateDecimal(height, 6); + } + + inline bool isFree(Field field) const { + Unit *unit = getUnit(field); + bool result = (unit == NULL || unit->isPutrefacting()); + + if (result == false) { + // printf("[%s] Line: %d returning false, unit id = %d + // [%s]\n",__FUNCTION__,__LINE__,getUnit(field)->getId(),getUnit(field)->getType()->getName().c_str()); + } + + return result; + } + + inline bool isFreeOrMightBeFreeSoon(Vec2i originPos, Vec2i cellPos, + Field field) const { + Unit *unit = getUnit(field); + bool result = (unit == NULL || unit->isPutrefacting()); + + if (result == false) { + if (originPos.dist(cellPos) > 5 && unit->getType()->isMobile() == true) { + result = true; + } + + // printf("[%s] Line: %d returning false, unit id = %d + // [%s]\n",__FUNCTION__,__LINE__,getUnit(field)->getId(),getUnit(field)->getType()->getName().c_str()); + } + + return result; + } + + void saveGame(XmlNode *rootNode, int index) const; + void loadGame(const XmlNode *rootNode, int index, World *world); }; // ===================================================== @@ -114,85 +139,95 @@ class Cell { class SurfaceCell { private: - //geometry - Vec3f vertex; - Vec3f normal; - Vec3f color; + // geometry + Vec3f vertex; + Vec3f normal; + Vec3f color; - //tex coords - Vec2f fowTexCoord; //tex coords for TEXTURE1 when multitexturing and fogOfWar - Vec2f surfTexCoord; //tex coords for TEXTURE0 + // tex coords + Vec2f fowTexCoord; // tex coords for TEXTURE1 when multitexturing and fogOfWar + Vec2f surfTexCoord; // tex coords for TEXTURE0 - //surface - int surfaceType; - const Texture2D *surfaceTexture; + // surface + int surfaceType; + const Texture2D *surfaceTexture; - //object & resource - Object *object; + // object & resource + Object *object; - //visibility - bool visible[GameConstants::maxPlayers + GameConstants::specialFactions]; - bool explored[GameConstants::maxPlayers + GameConstants::specialFactions]; + // visibility + bool visible[GameConstants::maxPlayers + GameConstants::specialFactions]; + bool explored[GameConstants::maxPlayers + GameConstants::specialFactions]; - //cache - bool nearSubmerged; - bool cellChangedFromOriginalMapLoad; + // cache + bool nearSubmerged; + bool cellChangedFromOriginalMapLoad; public: - SurfaceCell(); - ~SurfaceCell(); - - void end(); //to kill particles - //get - inline const Vec3f &getVertex() const {return vertex;} - inline float getHeight() const {return vertex.y;} - inline const Vec3f &getColor() const {return color;} - inline const Vec3f &getNormal() const {return normal;} - inline int getSurfaceType() const {return surfaceType;} - inline const Texture2D *getSurfaceTexture() const {return surfaceTexture;} - inline Object *getObject() const {return object;} - inline Resource *getResource() const {return object==NULL? NULL: object->getResource();} - inline const Vec2f &getFowTexCoord() const {return fowTexCoord;} - inline const Vec2f &getSurfTexCoord() const {return surfTexCoord;} - inline bool getNearSubmerged() const {return nearSubmerged;} - - inline bool isVisible(int teamIndex) const {return visible[teamIndex];} - inline bool isExplored(int teamIndex) const {return explored[teamIndex];} - string isVisibleString() const; - string isExploredString() const; - - //set - inline void setVertex(const Vec3f &vertex) {this->vertex= vertex;} - inline void setHeight(float height, bool cellChangedFromOriginalMapLoadValue=false); - inline void setNormal(const Vec3f &normal) {this->normal= normal;} - inline void setColor(const Vec3f &color) {this->color= color;} - inline void setSurfaceType(int surfaceType) {this->surfaceType= surfaceType;} - inline void setSurfaceTexture(const Texture2D *st) {this->surfaceTexture= st;} - inline void setObject(Object *object) {this->object= object;} - inline void setFowTexCoord(const Vec2f &ftc) {this->fowTexCoord= ftc;} - inline void setSurfTexCoord(const Vec2f &stc) {this->surfTexCoord= stc;} - void setExplored(int teamIndex, bool explored); - void setVisible(int teamIndex, bool visible); - inline void setNearSubmerged(bool nearSubmerged) {this->nearSubmerged= nearSubmerged;} - - //misc - void deleteResource(); - bool decAmount(int value); - inline bool isFree() const { - bool result = (object==NULL || object->getWalkable()); - - if(result == false) { - //printf("[%s] Line: %d returning false\n",__FUNCTION__,__LINE__); - } - return result; - } - bool getCellChangedFromOriginalMapLoad() const { return cellChangedFromOriginalMapLoad; } - - void saveGame(XmlNode *rootNode,int index) const; - void loadGame(const XmlNode *rootNode, int index, World *world); + SurfaceCell(); + ~SurfaceCell(); + + void end(); // to kill particles + // get + inline const Vec3f &getVertex() const { return vertex; } + inline float getHeight() const { return vertex.y; } + inline const Vec3f &getColor() const { return color; } + inline const Vec3f &getNormal() const { return normal; } + inline int getSurfaceType() const { return surfaceType; } + inline const Texture2D *getSurfaceTexture() const { return surfaceTexture; } + inline Object *getObject() const { return object; } + inline Resource *getResource() const { + return object == NULL ? NULL : object->getResource(); + } + inline const Vec2f &getFowTexCoord() const { return fowTexCoord; } + inline const Vec2f &getSurfTexCoord() const { return surfTexCoord; } + inline bool getNearSubmerged() const { return nearSubmerged; } + + inline bool isVisible(int teamIndex) const { return visible[teamIndex]; } + inline bool isExplored(int teamIndex) const { return explored[teamIndex]; } + string isVisibleString() const; + string isExploredString() const; + + // set + inline void setVertex(const Vec3f &vertex) { this->vertex = vertex; } + inline void setHeight(float height, + bool cellChangedFromOriginalMapLoadValue = false); + inline void setNormal(const Vec3f &normal) { this->normal = normal; } + inline void setColor(const Vec3f &color) { this->color = color; } + inline void setSurfaceType(int surfaceType) { + this->surfaceType = surfaceType; + } + inline void setSurfaceTexture(const Texture2D *st) { + this->surfaceTexture = st; + } + inline void setObject(Object *object) { this->object = object; } + inline void setFowTexCoord(const Vec2f &ftc) { this->fowTexCoord = ftc; } + inline void setSurfTexCoord(const Vec2f &stc) { this->surfTexCoord = stc; } + void setExplored(int teamIndex, bool explored); + void setVisible(int teamIndex, bool visible); + inline void setNearSubmerged(bool nearSubmerged) { + this->nearSubmerged = nearSubmerged; + } + + // misc + void deleteResource(); + bool decAmount(int value); + inline bool isFree() const { + bool result = (object == NULL || object->getWalkable()); + + if (result == false) { + // printf("[%s] Line: %d returning false\n",__FUNCTION__,__LINE__); + } + return result; + } + bool getCellChangedFromOriginalMapLoad() const { + return cellChangedFromOriginalMapLoad; + } + + void saveGame(XmlNode *rootNode, int index) const; + void loadGame(const XmlNode *rootNode, int index, World *world); }; - // ===================================================== // class Map // @@ -201,448 +236,530 @@ class SurfaceCell { class FastAINodeCache { public: - explicit FastAINodeCache(Unit *unit) { - this->unit = unit; - } - Unit *unit; - std::map > cachedCanMoveSoonList; + explicit FastAINodeCache(Unit *unit) { this->unit = unit; } + Unit *unit; + std::map> cachedCanMoveSoonList; }; class Map { public: - static const int cellScale; //number of cells per surfaceCell - static const int mapScale; //horizontal scale of surface + static const int cellScale; // number of cells per surfaceCell + static const int mapScale; // horizontal scale of surface private: - string title; - float waterLevel; - float heightFactor; - float cliffLevel; - int cameraHeight; - int w; - int h; - int surfaceW; - int surfaceH; - int surfaceSize; - - int maxPlayers; - Cell *cells; - SurfaceCell *surfaceCells; - Vec2i *startLocations; - Checksum checksumValue; - float maxMapHeight; - string mapFile; + string title; + float waterLevel; + float heightFactor; + float cliffLevel; + int cameraHeight; + int w; + int h; + int surfaceW; + int surfaceH; + int surfaceSize; + + int maxPlayers; + Cell *cells; + SurfaceCell *surfaceCells; + Vec2i *startLocations; + Checksum checksumValue; + float maxMapHeight; + string mapFile; private: - Map(Map&); - void operator=(Map&); + Map(Map &); + void operator=(Map &); public: - Map(); - ~Map(); - void end(); //to kill particles - Checksum * getChecksumValue() { return &checksumValue; } - - void init(Tileset *tileset); - Checksum load(const string &path, TechTree *techTree, Tileset *tileset); - - //get - inline Cell *getCell(int x, int y, bool errorOnInvalid=true) const { - int arrayIndex = y * w + x; - if(arrayIndex < 0 || arrayIndex >= getCellArraySize()) { - if(errorOnInvalid == false) { - return NULL; - } - //abort(); - throw megaglest_runtime_error("arrayIndex >= getCellArraySize(), arrayIndex = " + intToStr(arrayIndex) + " w = " + intToStr(w) + " h = " + intToStr(h)); - } - else if(cells == NULL) { - if(errorOnInvalid == false) { - return NULL; - } - - throw megaglest_runtime_error("cells == NULL"); - } - - return &cells[arrayIndex]; - } - inline Cell *getCell(const Vec2i &pos) const { - return getCell(pos.x, pos.y); - } - - inline int getCellArraySize() const { - return (w * h); - } - inline int getSurfaceCellArraySize() const { - //return (surfaceW * surfaceH); - return surfaceSize; - } - inline SurfaceCell *getSurfaceCell(int sx, int sy) const { - int arrayIndex = sy * surfaceW + sx; - if(arrayIndex < 0 || arrayIndex >= getSurfaceCellArraySize()) { - throw megaglest_runtime_error("arrayIndex >= getSurfaceCellArraySize(), arrayIndex = " + intToStr(arrayIndex) + - " surfaceW = " + intToStr(surfaceW) + " surfaceH = " + intToStr(surfaceH) + - " sx: " + intToStr(sx) + " sy: " + intToStr(sy)); - } - else if(surfaceCells == NULL) { - throw megaglest_runtime_error("surfaceCells == NULL"); - } - return &surfaceCells[arrayIndex]; - } - inline SurfaceCell *getSurfaceCell(const Vec2i &sPos) const { - return getSurfaceCell(sPos.x, sPos.y); - } - - inline int getW() const {return w;} - inline int getH() const {return h;} - inline int getSurfaceW() const {return surfaceW;} - inline int getSurfaceH() const {return surfaceH;} - inline int getMaxPlayers() const {return maxPlayers;} - inline float getHeightFactor() const {return truncateDecimal(heightFactor,6);} - inline float getWaterLevel() const {return truncateDecimal(waterLevel,6);} - inline float getCliffLevel() const {return truncateDecimal(cliffLevel,6);} - inline int getCameraHeight() const {return cameraHeight;} - inline float getMaxMapHeight() const {return truncateDecimal(maxMapHeight,6);} - Vec2i getStartLocation(int locationIndex) const; - inline bool getSubmerged(const SurfaceCell *sc) const {return sc->getHeight()getHeight()getHeight()getHeight()=0 && y>=0 && x=0 && sy>=0 && sx > > > > *lookupCache=NULL) const; - bool canMove(const Unit *unit, const Vec2i &pos1, const Vec2i &pos2,std::map > > > *lookupCache=NULL) const; - void putUnitCells(Unit *unit, const Vec2i &pos,bool ignoreSkill = false, bool threaded = false); - void clearUnitCells(Unit *unit, const Vec2i &pos,bool ignoreSkill = false); - - Vec2i computeRefPos(const Selection *selection) const; - Vec2i computeDestPos( const Vec2i &refUnitPos, const Vec2i &unitPos, - const Vec2i &commandPos) const; - const Unit * findClosestUnitToPos(const Selection *selection, Vec2i originalBuildPos, - const UnitType *ut) const; - bool isInUnitTypeCells(const UnitType *ut, const Vec2i &pos,const Vec2i &testPos) const; - bool isNextToUnitTypeCells(const UnitType *ut, const Vec2i &pos,const Vec2i &testPos) const; - Vec2i findBestBuildApproach(const Unit *unit, Vec2i originalBuildPos,const UnitType *ut) const; - //std::pair getUnitDistanceToPos(const Unit *unit,Vec2i pos,const UnitType *ut); - - //misc - bool isNextTo(const Vec2i &pos, const Unit *unit) const; - bool isNextTo(const Vec2i &pos, const Vec2i &nextToPos) const; - bool isNextTo(const Unit *unit1, const Unit *unit2) const; - void clampPos(Vec2i &pos) const; - - void prepareTerrain(const Unit *unit); - void flatternTerrain(const Unit *unit); - void computeNormals(); - void computeInterpolatedHeights(); - - //static - inline static Vec2i toSurfCoords(const Vec2i &unitPos) {return unitPos / cellScale;} - inline static Vec2i toUnitCoords(const Vec2i &surfPos) {return surfPos * cellScale;} - - inline bool isFreeCellOrMightBeFreeSoon(Vec2i originPos, const Vec2i &pos, Field field) const { - return - isInside(pos) && - isInsideSurface(toSurfCoords(pos)) && - getCell(pos)->isFreeOrMightBeFreeSoon(originPos,pos,field) && - (field==fAir || getSurfaceCell(toSurfCoords(pos))->isFree()) && - (field!=fLand || getDeepSubmerged(getCell(pos)) == false); - } - - inline bool isAproxFreeCellOrMightBeFreeSoon(Vec2i originPos,const Vec2i &pos, Field field, int teamIndex) const { - if(isInside(pos) && isInsideSurface(toSurfCoords(pos))) { - const SurfaceCell *sc= getSurfaceCell(toSurfCoords(pos)); - - if(sc->isVisible(teamIndex)) { - return isFreeCellOrMightBeFreeSoon(originPos, pos, field); - } - else if(sc->isExplored(teamIndex)) { - return field==fLand? sc->isFree() && !getDeepSubmerged(getCell(pos)): true; - } - else { - return true; - } - } - - //printf("[%s] Line: %d returning false\n",__FUNCTION__,__LINE__); - return false; - } - - //checks if a unit can move from between 2 cells using only visible cells (for pathfinding) - inline bool aproxCanMoveSoon(Unit *unit, const Vec2i &pos1, const Vec2i &pos2) const { - if(isInside(pos1) == false || isInsideSurface(toSurfCoords(pos1)) == false || - isInside(pos2) == false || isInsideSurface(toSurfCoords(pos2)) == false) { - - //printf("[%s] Line: %d returning false\n",__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && - SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax).enabled == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In aproxCanMoveSoon() return false"); - if(Thread::isCurrentThreadMainThread() == false) { - unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); - } - else { - unit->logSynchData(__FILE__,__LINE__,szBuf); - } - } - - return false; - } - - if(unit == NULL) { - throw megaglest_runtime_error("unit == NULL"); - } - - int size= unit->getType()->getSize(); - int teamIndex= unit->getTeam(); - Field field= unit->getCurrField(); - - //single cell units - if(size == 1) { - bool tryPosResult = isAproxFreeCellOrMightBeFreeSoon(unit->getPosNotThreadSafe(),pos2, field, teamIndex); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && - SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax).enabled == true) { - string extraInfo = (string("tryPosResult = ") + (tryPosResult ? string("true") : string("false"))); - const SurfaceCell *sc= getSurfaceCell(toSurfCoords(pos2)); - if(sc->isVisible(teamIndex)) { - bool testCond = isFreeCellOrMightBeFreeSoon(unit->getPosNotThreadSafe(), pos2, field); - extraInfo += (string("isFreeCellOrMightBeFreeSoon = ") + (testCond ? string("true") : string("false"))); - } - else if(sc->isExplored(teamIndex)) { - bool testCond = field==fLand? sc->isFree() && !getDeepSubmerged(getCell(pos2)): true; - extraInfo += (string("field==fLand = ") + (testCond ? string("true") : string("false"))); - } - - char szBuf[8096]=""; - snprintf(szBuf,8096,"In aproxCanMoveSoon() pos2 = %s extraInfo = %s %s %s",pos2.getString().c_str(),extraInfo.c_str(),sc->isVisibleString().c_str(),sc->isExploredString().c_str()); - if(Thread::isCurrentThreadMainThread() == false) { - unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); - } - else { - unit->logSynchData(__FILE__,__LINE__,szBuf); - } - } - - if(tryPosResult == false) { - return false; - } - if(pos1.x != pos2.x && pos1.y != pos2.y) { - Vec2i tryPos = Vec2i(pos1.x, pos2.y); - bool tryPosResult = isAproxFreeCellOrMightBeFreeSoon(unit->getPosNotThreadSafe(),tryPos, field, teamIndex); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && - SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax).enabled == true) { - string extraInfo = (string("tryPosResult = ") + (tryPosResult ? string("true") : string("false"))); - const SurfaceCell *sc= getSurfaceCell(toSurfCoords(tryPos)); - if(sc->isVisible(teamIndex)) { - bool testCond = isFreeCellOrMightBeFreeSoon(unit->getPosNotThreadSafe(), tryPos, field); - extraInfo += (string("isFreeCellOrMightBeFreeSoon = ") + (testCond ? string("true") : string("false"))); - } - else if(sc->isExplored(teamIndex)) { - bool testCond = field==fLand? sc->isFree() && !getDeepSubmerged(getCell(tryPos)): true; - extraInfo += (string("field==fLand = ") + (testCond ? string("true") : string("false"))); - } - - char szBuf[8096]=""; - snprintf(szBuf,8096,"In aproxCanMoveSoon() extraInfo = %s",extraInfo.c_str()); - if(Thread::isCurrentThreadMainThread() == false) { - unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); - } - else { - unit->logSynchData(__FILE__,__LINE__,szBuf); - } - } - - if(tryPosResult == false) { - return false; - } - - tryPos = Vec2i(pos2.x, pos1.y); - tryPosResult = isAproxFreeCellOrMightBeFreeSoon(unit->getPosNotThreadSafe(),tryPos, field, teamIndex); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && - SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax).enabled == true) { - string extraInfo = (string("tryPosResult = ") + (tryPosResult ? string("true") : string("false"))); - const SurfaceCell *sc= getSurfaceCell(toSurfCoords(tryPos)); - if(sc->isVisible(teamIndex)) { - bool testCond = isFreeCellOrMightBeFreeSoon(unit->getPosNotThreadSafe(), tryPos, field); - extraInfo += (string("isFreeCellOrMightBeFreeSoon = ") + (testCond ? string("true") : string("false"))); - } - else if(sc->isExplored(teamIndex)) { - bool testCond = field==fLand? sc->isFree() && !getDeepSubmerged(getCell(tryPos)): true; - extraInfo += (string("field==fLand = ") + (testCond ? string("true") : string("false"))); - } - - char szBuf[8096]=""; - snprintf(szBuf,8096,"In aproxCanMoveSoon() extraInfo = %s",extraInfo.c_str()); - if(Thread::isCurrentThreadMainThread() == false) { - unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); - } - else { - unit->logSynchData(__FILE__,__LINE__,szBuf); - } - } - - if(tryPosResult == false) { - - return false; - } - } - - bool isBadHarvestPos = false; - Command *command= unit->getCurrCommand(); - if(command != NULL) { - const HarvestCommandType *hct = dynamic_cast(command->getCommandType()); - if(hct != NULL && unit->isBadHarvestPos(pos2) == true) { - isBadHarvestPos = true; - } - } - - if(unit == NULL || isBadHarvestPos == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && - SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax).enabled == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In aproxCanMoveSoon() return false"); - if(Thread::isCurrentThreadMainThread() == false) { - unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); - } - else { - unit->logSynchData(__FILE__,__LINE__,szBuf); - } - } - - return false; - } - - return true; - } - //multi cell units - else { - for(int i = pos2.x; i < pos2.x + size; ++i) { - for(int j = pos2.y; j < pos2.y + size; ++j) { - - Vec2i cellPos = Vec2i(i,j); - if(isInside(cellPos) && isInsideSurface(toSurfCoords(cellPos))) { - if(getCell(cellPos)->getUnit(unit->getCurrField()) != unit) { - if(isAproxFreeCellOrMightBeFreeSoon(unit->getPosNotThreadSafe(),cellPos, field, teamIndex) == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && - SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax).enabled == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In aproxCanMoveSoon() return false"); - if(Thread::isCurrentThreadMainThread() == false) { - unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); - } - else { - unit->logSynchData(__FILE__,__LINE__,szBuf); - } - } - - return false; - } - } - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && - SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax).enabled == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In aproxCanMoveSoon() return false"); - if(Thread::isCurrentThreadMainThread() == false) { - unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); - } - else { - unit->logSynchData(__FILE__,__LINE__,szBuf); - } - } - - return false; - } - } - } - - bool isBadHarvestPos = false; - Command *command= unit->getCurrCommand(); - if(command != NULL) { - const HarvestCommandType *hct = dynamic_cast(command->getCommandType()); - if(hct != NULL && unit->isBadHarvestPos(pos2) == true) { - isBadHarvestPos = true; - } - } - - if(isBadHarvestPos == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && - SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax).enabled == true) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In aproxCanMoveSoon() return false"); - if(Thread::isCurrentThreadMainThread() == false) { - unit->logSynchDataThreaded(__FILE__,__LINE__,szBuf); - } - else { - unit->logSynchData(__FILE__,__LINE__,szBuf); - } - } - - return false; - } - - } - return true; - } - - string getMapFile() const { return mapFile; } - - void saveGame(XmlNode *rootNode) const; - void loadGame(const XmlNode *rootNode,World *world); + Map(); + ~Map(); + void end(); // to kill particles + Checksum *getChecksumValue() { return &checksumValue; } + + void init(Tileset *tileset); + Checksum load(const string &path, TechTree *techTree, Tileset *tileset); + + // get + inline Cell *getCell(int x, int y, bool errorOnInvalid = true) const { + int arrayIndex = y * w + x; + if (arrayIndex < 0 || arrayIndex >= getCellArraySize()) { + if (errorOnInvalid == false) { + return NULL; + } + // abort(); + throw megaglest_runtime_error( + "arrayIndex >= getCellArraySize(), arrayIndex = " + + intToStr(arrayIndex) + " w = " + intToStr(w) + " h = " + intToStr(h)); + } else if (cells == NULL) { + if (errorOnInvalid == false) { + return NULL; + } + + throw megaglest_runtime_error("cells == NULL"); + } + + return &cells[arrayIndex]; + } + inline Cell *getCell(const Vec2i &pos) const { return getCell(pos.x, pos.y); } + + inline int getCellArraySize() const { return (w * h); } + inline int getSurfaceCellArraySize() const { + // return (surfaceW * surfaceH); + return surfaceSize; + } + inline SurfaceCell *getSurfaceCell(int sx, int sy) const { + int arrayIndex = sy * surfaceW + sx; + if (arrayIndex < 0 || arrayIndex >= getSurfaceCellArraySize()) { + throw megaglest_runtime_error( + "arrayIndex >= getSurfaceCellArraySize(), arrayIndex = " + + intToStr(arrayIndex) + " surfaceW = " + intToStr(surfaceW) + + " surfaceH = " + intToStr(surfaceH) + " sx: " + intToStr(sx) + + " sy: " + intToStr(sy)); + } else if (surfaceCells == NULL) { + throw megaglest_runtime_error("surfaceCells == NULL"); + } + return &surfaceCells[arrayIndex]; + } + inline SurfaceCell *getSurfaceCell(const Vec2i &sPos) const { + return getSurfaceCell(sPos.x, sPos.y); + } + + inline int getW() const { return w; } + inline int getH() const { return h; } + inline int getSurfaceW() const { return surfaceW; } + inline int getSurfaceH() const { return surfaceH; } + inline int getMaxPlayers() const { return maxPlayers; } + inline float getHeightFactor() const { + return truncateDecimal(heightFactor, 6); + } + inline float getWaterLevel() const { + return truncateDecimal(waterLevel, 6); + } + inline float getCliffLevel() const { + return truncateDecimal(cliffLevel, 6); + } + inline int getCameraHeight() const { return cameraHeight; } + inline float getMaxMapHeight() const { + return truncateDecimal(maxMapHeight, 6); + } + Vec2i getStartLocation(int locationIndex) const; + inline bool getSubmerged(const SurfaceCell *sc) const { + return sc->getHeight() < waterLevel; + } + inline bool getSubmerged(const Cell *c) const { + return c->getHeight() < waterLevel; + } + inline bool getDeepSubmerged(const SurfaceCell *sc) const { + return sc->getHeight() < waterLevel - (1.5f / heightFactor); + } + inline bool getDeepSubmerged(const Cell *c) const { + return c->getHeight() < waterLevel - (1.5f / heightFactor); + } + + // is + inline bool isInside(int x, int y) const { + return x >= 0 && y >= 0 && x < w && y < h; + } + inline bool isInside(const Vec2i &pos) const { + return isInside(pos.x, pos.y); + } + inline bool isInsideSurface(int sx, int sy) const { + return sx >= 0 && sy >= 0 && sx < surfaceW && sy < surfaceH; + } + inline bool isInsideSurface(const Vec2i &sPos) const { + return isInsideSurface(sPos.x, sPos.y); + } + bool isResourceNear(int frameIndex, const Vec2i &pos, const ResourceType *rt, + Vec2i &resourcePos, int size, Unit *unit = NULL, + bool fallbackToPeersHarvestingSameResource = false, + Vec2i *resourceClickPos = NULL) const; + + // free cells + bool isFreeCell(const Vec2i &pos, Field field) const; + bool isFreeCellOrHasUnit(const Vec2i &pos, Field field, + const Unit *unit) const; + bool isAproxFreeCell(const Vec2i &pos, Field field, int teamIndex) const; + bool isFreeCells(const Vec2i &pos, int size, Field field) const; + bool isFreeCellsOrHasUnit(const Vec2i &pos, int size, Field field, + const Unit *unit) const; + bool isAproxFreeCells(const Vec2i &pos, int size, Field field, + int teamIndex) const; + bool canMorph(const Vec2i &pos, const Unit *currentUnit, + const UnitType *targetUnitType) const; + // bool canOccupy(const Vec2i &pos, Field field, const UnitType *ut, + // CardinalDir facing); + + // unit placement + bool aproxCanMove( + const Unit *unit, const Vec2i &pos1, const Vec2i &pos2, + std::map< + Vec2i, + std::map>>>> + *lookupCache = NULL) const; + bool + canMove(const Unit *unit, const Vec2i &pos1, const Vec2i &pos2, + std::map>>> + *lookupCache = NULL) const; + void putUnitCells(Unit *unit, const Vec2i &pos, bool ignoreSkill = false, + bool threaded = false); + void clearUnitCells(Unit *unit, const Vec2i &pos, bool ignoreSkill = false); + + Vec2i computeRefPos(const Selection *selection) const; + Vec2i computeDestPos(const Vec2i &refUnitPos, const Vec2i &unitPos, + const Vec2i &commandPos) const; + const Unit *findClosestUnitToPos(const Selection *selection, + Vec2i originalBuildPos, + const UnitType *ut) const; + bool isInUnitTypeCells(const UnitType *ut, const Vec2i &pos, + const Vec2i &testPos) const; + bool isNextToUnitTypeCells(const UnitType *ut, const Vec2i &pos, + const Vec2i &testPos) const; + Vec2i findBestBuildApproach(const Unit *unit, Vec2i originalBuildPos, + const UnitType *ut) const; + // std::pair getUnitDistanceToPos(const Unit *unit,Vec2i + // pos,const UnitType *ut); + + // misc + bool isNextTo(const Vec2i &pos, const Unit *unit) const; + bool isNextTo(const Vec2i &pos, const Vec2i &nextToPos) const; + bool isNextTo(const Unit *unit1, const Unit *unit2) const; + void clampPos(Vec2i &pos) const; + + void prepareTerrain(const Unit *unit); + void flatternTerrain(const Unit *unit); + void computeNormals(); + void computeInterpolatedHeights(); + + // static + inline static Vec2i toSurfCoords(const Vec2i &unitPos) { + return unitPos / cellScale; + } + inline static Vec2i toUnitCoords(const Vec2i &surfPos) { + return surfPos * cellScale; + } + + inline bool isFreeCellOrMightBeFreeSoon(Vec2i originPos, const Vec2i &pos, + Field field) const { + return isInside(pos) && isInsideSurface(toSurfCoords(pos)) && + getCell(pos)->isFreeOrMightBeFreeSoon(originPos, pos, field) && + (field == fAir || getSurfaceCell(toSurfCoords(pos))->isFree()) && + (field != fLand || getDeepSubmerged(getCell(pos)) == false); + } + + inline bool isAproxFreeCellOrMightBeFreeSoon(Vec2i originPos, + const Vec2i &pos, Field field, + int teamIndex) const { + if (isInside(pos) && isInsideSurface(toSurfCoords(pos))) { + const SurfaceCell *sc = getSurfaceCell(toSurfCoords(pos)); + + if (sc->isVisible(teamIndex)) { + return isFreeCellOrMightBeFreeSoon(originPos, pos, field); + } else if (sc->isExplored(teamIndex)) { + return field == fLand ? sc->isFree() && !getDeepSubmerged(getCell(pos)) + : true; + } else { + return true; + } + } + + // printf("[%s] Line: %d returning false\n",__FUNCTION__,__LINE__); + return false; + } + + // checks if a unit can move from between 2 cells using only visible cells + // (for pathfinding) + inline bool aproxCanMoveSoon(Unit *unit, const Vec2i &pos1, + const Vec2i &pos2) const { + if (isInside(pos1) == false || + isInsideSurface(toSurfCoords(pos1)) == false || + isInside(pos2) == false || + isInsideSurface(toSurfCoords(pos2)) == false) { + + // printf("[%s] Line: %d returning false\n",__FUNCTION__,__LINE__); + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax) + .enabled == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In aproxCanMoveSoon() return false"); + if (Thread::isCurrentThreadMainThread() == false) { + unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf); + } else { + unit->logSynchData(__FILE__, __LINE__, szBuf); + } + } + + return false; + } + + if (unit == NULL) { + throw megaglest_runtime_error("unit == NULL"); + } + + int size = unit->getType()->getSize(); + int teamIndex = unit->getTeam(); + Field field = unit->getCurrField(); + + // single cell units + if (size == 1) { + bool tryPosResult = isAproxFreeCellOrMightBeFreeSoon( + unit->getPosNotThreadSafe(), pos2, field, teamIndex); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax) + .enabled == true) { + string extraInfo = (string("tryPosResult = ") + + (tryPosResult ? string("true") : string("false"))); + const SurfaceCell *sc = getSurfaceCell(toSurfCoords(pos2)); + if (sc->isVisible(teamIndex)) { + bool testCond = isFreeCellOrMightBeFreeSoon( + unit->getPosNotThreadSafe(), pos2, field); + extraInfo += (string("isFreeCellOrMightBeFreeSoon = ") + + (testCond ? string("true") : string("false"))); + } else if (sc->isExplored(teamIndex)) { + bool testCond = field == fLand + ? sc->isFree() && !getDeepSubmerged(getCell(pos2)) + : true; + extraInfo += (string("field==fLand = ") + + (testCond ? string("true") : string("false"))); + } + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "In aproxCanMoveSoon() pos2 = %s extraInfo = %s %s %s", + pos2.getString().c_str(), extraInfo.c_str(), + sc->isVisibleString().c_str(), sc->isExploredString().c_str()); + if (Thread::isCurrentThreadMainThread() == false) { + unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf); + } else { + unit->logSynchData(__FILE__, __LINE__, szBuf); + } + } + + if (tryPosResult == false) { + return false; + } + if (pos1.x != pos2.x && pos1.y != pos2.y) { + Vec2i tryPos = Vec2i(pos1.x, pos2.y); + bool tryPosResult = isAproxFreeCellOrMightBeFreeSoon( + unit->getPosNotThreadSafe(), tryPos, field, teamIndex); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax) + .enabled == true) { + string extraInfo = + (string("tryPosResult = ") + + (tryPosResult ? string("true") : string("false"))); + const SurfaceCell *sc = getSurfaceCell(toSurfCoords(tryPos)); + if (sc->isVisible(teamIndex)) { + bool testCond = isFreeCellOrMightBeFreeSoon( + unit->getPosNotThreadSafe(), tryPos, field); + extraInfo += (string("isFreeCellOrMightBeFreeSoon = ") + + (testCond ? string("true") : string("false"))); + } else if (sc->isExplored(teamIndex)) { + bool testCond = + field == fLand + ? sc->isFree() && !getDeepSubmerged(getCell(tryPos)) + : true; + extraInfo += (string("field==fLand = ") + + (testCond ? string("true") : string("false"))); + } + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In aproxCanMoveSoon() extraInfo = %s", + extraInfo.c_str()); + if (Thread::isCurrentThreadMainThread() == false) { + unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf); + } else { + unit->logSynchData(__FILE__, __LINE__, szBuf); + } + } + + if (tryPosResult == false) { + return false; + } + + tryPos = Vec2i(pos2.x, pos1.y); + tryPosResult = isAproxFreeCellOrMightBeFreeSoon( + unit->getPosNotThreadSafe(), tryPos, field, teamIndex); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax) + .enabled == true) { + string extraInfo = + (string("tryPosResult = ") + + (tryPosResult ? string("true") : string("false"))); + const SurfaceCell *sc = getSurfaceCell(toSurfCoords(tryPos)); + if (sc->isVisible(teamIndex)) { + bool testCond = isFreeCellOrMightBeFreeSoon( + unit->getPosNotThreadSafe(), tryPos, field); + extraInfo += (string("isFreeCellOrMightBeFreeSoon = ") + + (testCond ? string("true") : string("false"))); + } else if (sc->isExplored(teamIndex)) { + bool testCond = + field == fLand + ? sc->isFree() && !getDeepSubmerged(getCell(tryPos)) + : true; + extraInfo += (string("field==fLand = ") + + (testCond ? string("true") : string("false"))); + } + + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In aproxCanMoveSoon() extraInfo = %s", + extraInfo.c_str()); + if (Thread::isCurrentThreadMainThread() == false) { + unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf); + } else { + unit->logSynchData(__FILE__, __LINE__, szBuf); + } + } + + if (tryPosResult == false) { + + return false; + } + } + + bool isBadHarvestPos = false; + Command *command = unit->getCurrCommand(); + if (command != NULL) { + const HarvestCommandType *hct = + dynamic_cast(command->getCommandType()); + if (hct != NULL && unit->isBadHarvestPos(pos2) == true) { + isBadHarvestPos = true; + } + } + + if (unit == NULL || isBadHarvestPos == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax) + .enabled == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In aproxCanMoveSoon() return false"); + if (Thread::isCurrentThreadMainThread() == false) { + unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf); + } else { + unit->logSynchData(__FILE__, __LINE__, szBuf); + } + } + + return false; + } + + return true; + } + // multi cell units + else { + for (int i = pos2.x; i < pos2.x + size; ++i) { + for (int j = pos2.y; j < pos2.y + size; ++j) { + + Vec2i cellPos = Vec2i(i, j); + if (isInside(cellPos) && isInsideSurface(toSurfCoords(cellPos))) { + if (getCell(cellPos)->getUnit(unit->getCurrField()) != unit) { + if (isAproxFreeCellOrMightBeFreeSoon(unit->getPosNotThreadSafe(), + cellPos, field, + teamIndex) == false) { + if (SystemFlags::getSystemSettingType( + SystemFlags::debugWorldSynch) + .enabled == true && + SystemFlags::getSystemSettingType( + SystemFlags::debugWorldSynchMax) + .enabled == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In aproxCanMoveSoon() return false"); + if (Thread::isCurrentThreadMainThread() == false) { + unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf); + } else { + unit->logSynchData(__FILE__, __LINE__, szBuf); + } + } + + return false; + } + } + } else { + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + SystemFlags::getSystemSettingType( + SystemFlags::debugWorldSynchMax) + .enabled == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In aproxCanMoveSoon() return false"); + if (Thread::isCurrentThreadMainThread() == false) { + unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf); + } else { + unit->logSynchData(__FILE__, __LINE__, szBuf); + } + } + + return false; + } + } + } + + bool isBadHarvestPos = false; + Command *command = unit->getCurrCommand(); + if (command != NULL) { + const HarvestCommandType *hct = + dynamic_cast(command->getCommandType()); + if (hct != NULL && unit->isBadHarvestPos(pos2) == true) { + isBadHarvestPos = true; + } + } + + if (isBadHarvestPos == true) { + if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch) + .enabled == true && + SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynchMax) + .enabled == true) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In aproxCanMoveSoon() return false"); + if (Thread::isCurrentThreadMainThread() == false) { + unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf); + } else { + unit->logSynchData(__FILE__, __LINE__, szBuf); + } + } + + return false; + } + } + return true; + } + + string getMapFile() const { return mapFile; } + + void saveGame(XmlNode *rootNode) const; + void loadGame(const XmlNode *rootNode, World *world); private: - //compute - void smoothSurface(Tileset *tileset); - void computeNearSubmerged(); - void computeCellColors(); - void putUnitCellsPrivate(Unit *unit, const Vec2i &pos, const UnitType *ut, bool isMorph, bool threaded); + // compute + void smoothSurface(Tileset *tileset); + void computeNearSubmerged(); + void computeCellColors(); + void putUnitCellsPrivate(Unit *unit, const Vec2i &pos, const UnitType *ut, + bool isMorph, bool threaded); }; - // =============================== // class PosCircularIterator // =============================== -class PosCircularIterator{ +class PosCircularIterator { private: - Vec2i center; - int radius; - const Map *map; - Vec2i pos; + Vec2i center; + int radius; + const Map *map; + Vec2i pos; public: - PosCircularIterator(const Map *map, const Vec2i ¢er, int radius); - bool next(); - const Vec2i &getPos(); + PosCircularIterator(const Map *map, const Vec2i ¢er, int radius); + bool next(); + const Vec2i &getPos(); }; // =============================== @@ -651,19 +768,20 @@ class PosCircularIterator{ class PosQuadIterator { private: - Quad2i quad; - Rect2i boundingRect; - Vec2i pos; - int step; - const Map *map; + Quad2i quad; + Rect2i boundingRect; + Vec2i pos; + int step; + const Map *map; public: - PosQuadIterator(const Map *map,const Quad2i &quad, int step=1); - bool next(); - //void skipX(); - const Vec2i &getPos(); + PosQuadIterator(const Map *map, const Quad2i &quad, int step = 1); + bool next(); + // void skipX(); + const Vec2i &getPos(); }; -} } //end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/world/minimap.cpp b/source/glest_game/world/minimap.cpp index 8cc0e1a9d..ada885bb0 100644 --- a/source/glest_game/world/minimap.cpp +++ b/source/glest_game/world/minimap.cpp @@ -13,316 +13,350 @@ #include -#include "world.h" -#include "vec.h" -#include "renderer.h" #include "config.h" -#include "object.h" #include "game_settings.h" #include "leak_dumper.h" +#include "object.h" +#include "renderer.h" +#include "vec.h" +#include "world.h" using namespace Shared::Graphics; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class Minimap // ===================================================== -const float Minimap::exploredAlpha= 0.5f; +const float Minimap::exploredAlpha = 0.5f; Minimap::Minimap() { - fowPixmap0= NULL; - fowPixmap1= NULL; - fowPixmap1_default=NULL; - fowPixmap0Copy = NULL; - fowPixmap1Copy = NULL; - fowPixmap1Copy_default = NULL; - fogOfWar= true; - gameSettings= NULL; - tex=NULL; - fowTex=NULL; + fowPixmap0 = NULL; + fowPixmap1 = NULL; + fowPixmap1_default = NULL; + fowPixmap0Copy = NULL; + fowPixmap1Copy = NULL; + fowPixmap1Copy_default = NULL; + fogOfWar = true; + gameSettings = NULL; + tex = NULL; + fowTex = NULL; } void Minimap::init(int w, int h, const World *world, bool fogOfWar) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - int scaledW= w/Map::cellScale; - int scaledH= h/Map::cellScale; - int potW = next2Power(scaledW); - int potH = next2Power(scaledH); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] scaledW = %d, scaledH = %d, potW = %d, potH = %d\n",__FILE__,__FUNCTION__,__LINE__,scaledW,scaledH,potW,potH); - - this->fogOfWar = fogOfWar; - this->gameSettings = world->getGameSettings(); - Renderer &renderer= Renderer::getInstance(); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - //fow pixmaps - float f= 0.f; - - if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { - fowPixmap0 = new Pixmap2D(potW, potH, 1); - fowPixmap0Copy = new Pixmap2D(potW, potH, 1); - fowPixmap1 = new Pixmap2D(potW, potH, 1); - fowPixmap1_default = new Pixmap2D(potW, potH, 1); - fowPixmap1Copy = new Pixmap2D(potW, potH, 1); - fowPixmap1Copy_default = new Pixmap2D(potW, potH, 1); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - fowPixmap0->setPixels(&f,1); - if((this->gameSettings->getFlagTypes1() & ft1_show_map_resources) == ft1_show_map_resources) { - f = 0.f; - fowPixmap1->setPixels(&f,1); - f = 0.5f; - for (int y=1; y < scaledH - 1; ++y) { - for (int x=1; x < scaledW - 1; ++x) { - fowPixmap1->setPixel(x, y, &f,1); - } - } - } - else { - fowPixmap1->setPixels(&f,1); - } - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - //fow tex - fowTex= renderer.newTexture2D(rsGame); - if(fowTex) { - fowTex->setMipmap(false); - fowTex->setPixmapInit(false); - fowTex->setFormat(Texture::fAlpha); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] scaledW = %d, scaledH = %d, potW = %d, potH = %d\n",__FILE__,__FUNCTION__,__LINE__,scaledW,scaledH,potW,potH); - - fowTex->getPixmap()->init(potW, potH, 1); - fowTex->getPixmap()->setPixels(&f,1); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - //tex - tex= renderer.newTexture2D(rsGame); - if(tex) { - tex->getPixmap()->init(scaledW, scaledH, 3); - tex->setMipmap(false); - } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - - computeTexture(world); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + int scaledW = w / Map::cellScale; + int scaledH = h / Map::cellScale; + int potW = next2Power(scaledW); + int potH = next2Power(scaledH); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] scaledW = %d, scaledH = %d, " + "potW = %d, potH = %d\n", + __FILE__, __FUNCTION__, __LINE__, scaledW, scaledH, + potW, potH); + + this->fogOfWar = fogOfWar; + this->gameSettings = world->getGameSettings(); + Renderer &renderer = Renderer::getInstance(); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + // fow pixmaps + float f = 0.f; + + if (GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) { + fowPixmap0 = new Pixmap2D(potW, potH, 1); + fowPixmap0Copy = new Pixmap2D(potW, potH, 1); + fowPixmap1 = new Pixmap2D(potW, potH, 1); + fowPixmap1_default = new Pixmap2D(potW, potH, 1); + fowPixmap1Copy = new Pixmap2D(potW, potH, 1); + fowPixmap1Copy_default = new Pixmap2D(potW, potH, 1); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d]\n", __FILE__, __FUNCTION__, + __LINE__); + + fowPixmap0->setPixels(&f, 1); + if ((this->gameSettings->getFlagTypes1() & ft1_show_map_resources) == + ft1_show_map_resources) { + f = 0.f; + fowPixmap1->setPixels(&f, 1); + f = 0.5f; + for (int y = 1; y < scaledH - 1; ++y) { + for (int x = 1; x < scaledW - 1; ++x) { + fowPixmap1->setPixel(x, y, &f, 1); + } + } + } else { + fowPixmap1->setPixels(&f, 1); + } + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + // fow tex + fowTex = renderer.newTexture2D(rsGame); + if (fowTex) { + fowTex->setMipmap(false); + fowTex->setPixmapInit(false); + fowTex->setFormat(Texture::fAlpha); + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, + "In [%s::%s Line: %d] scaledW = %d, scaledH = " + "%d, potW = %d, potH = %d\n", + __FILE__, __FUNCTION__, __LINE__, scaledW, + scaledH, potW, potH); + + fowTex->getPixmap()->init(potW, potH, 1); + fowTex->getPixmap()->setPixels(&f, 1); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + // tex + tex = renderer.newTexture2D(rsGame); + if (tex) { + tex->getPixmap()->init(scaledW, scaledH, 3); + tex->setMipmap(false); + } + + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "In [%s::%s Line: %d]\n", + __FILE__, __FUNCTION__, __LINE__); + + computeTexture(world); } Minimap::~Minimap() { - Logger::getInstance().add(Lang::getInstance().getString("LogScreenGameUnLoadingMiniMap","",true), true); - delete fowPixmap0; - fowPixmap0=NULL; - delete fowPixmap0Copy; - fowPixmap0Copy = NULL; - delete fowPixmap1; - fowPixmap1=NULL; - delete fowPixmap1_default; - fowPixmap1_default = NULL; - delete fowPixmap1Copy; - fowPixmap1Copy=NULL; - delete fowPixmap1Copy_default; - fowPixmap1Copy_default = NULL; + Logger::getInstance().add( + Lang::getInstance().getString("LogScreenGameUnLoadingMiniMap", "", true), + true); + delete fowPixmap0; + fowPixmap0 = NULL; + delete fowPixmap0Copy; + fowPixmap0Copy = NULL; + delete fowPixmap1; + fowPixmap1 = NULL; + delete fowPixmap1_default; + fowPixmap1_default = NULL; + delete fowPixmap1Copy; + fowPixmap1Copy = NULL; + delete fowPixmap1Copy_default; + fowPixmap1Copy_default = NULL; } // ==================== set ==================== void Minimap::incFowTextureAlphaSurface(const Vec2i sPos, float alpha, - bool isIncrementalUpdate) { - if(fowPixmap1) { - assert(sPos.x < fowPixmap1->getW() && sPos.y < fowPixmap1->getH()); - - if(fowPixmap1->getPixelf(sPos.x, sPos.y) < alpha){ - fowPixmap1->setPixel(sPos.x, sPos.y, alpha); - } - - if(fowPixmap1Copy != NULL && isIncrementalUpdate == true) { - if(fowPixmap1Copy->getPixelf(sPos.x, sPos.y) < alpha){ - fowPixmap1Copy->setPixel(sPos.x, sPos.y, alpha); - } - } - } + bool isIncrementalUpdate) { + if (fowPixmap1) { + assert(sPos.x < fowPixmap1->getW() && sPos.y < fowPixmap1->getH()); + + if (fowPixmap1->getPixelf(sPos.x, sPos.y) < alpha) { + fowPixmap1->setPixel(sPos.x, sPos.y, alpha); + } + + if (fowPixmap1Copy != NULL && isIncrementalUpdate == true) { + if (fowPixmap1Copy->getPixelf(sPos.x, sPos.y) < alpha) { + fowPixmap1Copy->setPixel(sPos.x, sPos.y, alpha); + } + } + } } void Minimap::copyFowTexAlphaSurface() { - if(fowPixmap1_default != NULL && fowPixmap1 != NULL) { - fowPixmap1_default->copy(fowPixmap1); - } - if(fowPixmap1Copy_default != NULL && fowPixmap1Copy != NULL) { - fowPixmap1Copy_default->copy(fowPixmap1Copy); - } + if (fowPixmap1_default != NULL && fowPixmap1 != NULL) { + fowPixmap1_default->copy(fowPixmap1); + } + if (fowPixmap1Copy_default != NULL && fowPixmap1Copy != NULL) { + fowPixmap1Copy_default->copy(fowPixmap1Copy); + } } void Minimap::restoreFowTexAlphaSurface() { - if(fowPixmap1 != NULL && fowPixmap1_default != NULL) { - fowPixmap1->copy(fowPixmap1_default); - } - if(fowPixmap1Copy != NULL && fowPixmap1Copy_default != NULL) { - fowPixmap1Copy->copy(fowPixmap1Copy_default); - } + if (fowPixmap1 != NULL && fowPixmap1_default != NULL) { + fowPixmap1->copy(fowPixmap1_default); + } + if (fowPixmap1Copy != NULL && fowPixmap1Copy_default != NULL) { + fowPixmap1Copy->copy(fowPixmap1Copy_default); + } } void Minimap::setFogOfWar(bool value) { - fogOfWar = value; - resetFowTex(); + fogOfWar = value; + resetFowTex(); } void Minimap::copyFowTex() { - if(fowPixmap0Copy != NULL && fowPixmap0 != NULL) { - fowPixmap0Copy->copy(fowPixmap0); - } - if(fowPixmap1Copy != NULL && fowPixmap1 != NULL) { - fowPixmap1Copy->copy(fowPixmap1); - } + if (fowPixmap0Copy != NULL && fowPixmap0 != NULL) { + fowPixmap0Copy->copy(fowPixmap0); + } + if (fowPixmap1Copy != NULL && fowPixmap1 != NULL) { + fowPixmap1Copy->copy(fowPixmap1); + } } void Minimap::restoreFowTex() { - if(fowPixmap0 != NULL && fowPixmap0Copy != NULL) { - fowPixmap0->copy(fowPixmap0Copy); - } - if(fowPixmap1 != NULL && fowPixmap1Copy != NULL) { - fowPixmap1->copy(fowPixmap1Copy); - } + if (fowPixmap0 != NULL && fowPixmap0Copy != NULL) { + fowPixmap0->copy(fowPixmap0Copy); + } + if (fowPixmap1 != NULL && fowPixmap1Copy != NULL) { + fowPixmap1->copy(fowPixmap1Copy); + } } void Minimap::resetFowTex() { - if(fowTex && fowPixmap0 && fowPixmap1) { - Pixmap2D *tmpPixmap= fowPixmap0; - fowPixmap0= fowPixmap1; - fowPixmap1= tmpPixmap; - - // Could turn off ONLY fog of war by setting below to false - bool overridefogOfWarValue = fogOfWar; - - for(int indexPixelWidth = 0; - indexPixelWidth < fowTex->getPixmap()->getW(); - ++indexPixelWidth){ - for(int indexPixelHeight = 0; - indexPixelHeight < fowTex->getPixmap()->getH(); - ++indexPixelHeight){ - if ((fogOfWar == false && overridefogOfWarValue == false)) { - //(gameSettings->getFlagTypes1() & ft1_show_map_resources) != ft1_show_map_resources) { - //printf("Line: %d\n",__LINE__); - - float p0 = fowPixmap0->getPixelf(indexPixelWidth, indexPixelHeight); - float p1 = fowPixmap1->getPixelf(indexPixelWidth, indexPixelHeight); - if (p0 > p1) { - fowPixmap1->setPixel(indexPixelWidth, indexPixelHeight, p0); - } - else { - fowPixmap1->setPixel(indexPixelWidth, indexPixelHeight, p1); - } - } - else if((fogOfWar && overridefogOfWarValue) || - (gameSettings->getFlagTypes1() & ft1_show_map_resources) == ft1_show_map_resources) { - //printf("Line: %d\n",__LINE__); - - float p0= fowPixmap0->getPixelf(indexPixelWidth, indexPixelHeight); - float p1= fowPixmap1->getPixelf(indexPixelWidth, indexPixelHeight); - - if(p1 > exploredAlpha) { - fowPixmap1->setPixel(indexPixelWidth, indexPixelHeight, exploredAlpha); - } - if(p0 > p1) { - fowPixmap1->setPixel(indexPixelWidth, indexPixelHeight, p0); - } - } - else { - //printf("Line: %d\n",__LINE__); - fowPixmap1->setPixel(indexPixelWidth, indexPixelHeight, 1.f); - } - } - } - } + if (fowTex && fowPixmap0 && fowPixmap1) { + Pixmap2D *tmpPixmap = fowPixmap0; + fowPixmap0 = fowPixmap1; + fowPixmap1 = tmpPixmap; + + // Could turn off ONLY fog of war by setting below to false + bool overridefogOfWarValue = fogOfWar; + + for (int indexPixelWidth = 0; indexPixelWidth < fowTex->getPixmap()->getW(); + ++indexPixelWidth) { + for (int indexPixelHeight = 0; + indexPixelHeight < fowTex->getPixmap()->getH(); ++indexPixelHeight) { + if ((fogOfWar == false && overridefogOfWarValue == false)) { + //(gameSettings->getFlagTypes1() & ft1_show_map_resources) != + // ft1_show_map_resources) { printf("Line: %d\n",__LINE__); + + float p0 = fowPixmap0->getPixelf(indexPixelWidth, indexPixelHeight); + float p1 = fowPixmap1->getPixelf(indexPixelWidth, indexPixelHeight); + if (p0 > p1) { + fowPixmap1->setPixel(indexPixelWidth, indexPixelHeight, p0); + } else { + fowPixmap1->setPixel(indexPixelWidth, indexPixelHeight, p1); + } + } else if ((fogOfWar && overridefogOfWarValue) || + (gameSettings->getFlagTypes1() & ft1_show_map_resources) == + ft1_show_map_resources) { + // printf("Line: %d\n",__LINE__); + + float p0 = fowPixmap0->getPixelf(indexPixelWidth, indexPixelHeight); + float p1 = fowPixmap1->getPixelf(indexPixelWidth, indexPixelHeight); + + if (p1 > exploredAlpha) { + fowPixmap1->setPixel(indexPixelWidth, indexPixelHeight, + exploredAlpha); + } + if (p0 > p1) { + fowPixmap1->setPixel(indexPixelWidth, indexPixelHeight, p0); + } + } else { + // printf("Line: %d\n",__LINE__); + fowPixmap1->setPixel(indexPixelWidth, indexPixelHeight, 1.f); + } + } + } + } } void Minimap::updateFowTex(float t) { - if(fowTex && fowPixmap0 && fowPixmap1) { - for(int indexPixelWidth = 0; - indexPixelWidth < fowPixmap0->getW(); - ++indexPixelWidth){ - for(int indexPixelHeight = 0; - indexPixelHeight < fowPixmap0->getH(); - ++indexPixelHeight){ - float p1 = fowPixmap1->getPixelf(indexPixelWidth, indexPixelHeight); - float p2 = fowTex->getPixmap()->getPixelf(indexPixelWidth, indexPixelHeight); - if(p1 != p2) { - float p0 = fowPixmap0->getPixelf(indexPixelWidth, indexPixelHeight); - fowTex->getPixmap()->setPixel(indexPixelWidth, indexPixelHeight, p0+(t*(p1-p0))); - } - } - } - } + if (fowTex && fowPixmap0 && fowPixmap1) { + for (int indexPixelWidth = 0; indexPixelWidth < fowPixmap0->getW(); + ++indexPixelWidth) { + for (int indexPixelHeight = 0; indexPixelHeight < fowPixmap0->getH(); + ++indexPixelHeight) { + float p1 = fowPixmap1->getPixelf(indexPixelWidth, indexPixelHeight); + float p2 = + fowTex->getPixmap()->getPixelf(indexPixelWidth, indexPixelHeight); + if (p1 != p2) { + float p0 = fowPixmap0->getPixelf(indexPixelWidth, indexPixelHeight); + fowTex->getPixmap()->setPixel(indexPixelWidth, indexPixelHeight, + p0 + (t * (p1 - p0))); + } + } + } + } } // ==================== PRIVATE ==================== void Minimap::computeTexture(const World *world) { - Vec3f color; - const Map *map= world->getMap(); - - if(tex) { - tex->getPixmap()->setPixels(Vec4f(1.f, 1.f, 1.f, 0.1f).ptr(),tex->getPixmap()->getComponents()); - - for(int j=0; jgetPixmap()->getH(); ++j){ - for(int i=0; igetPixmap()->getW(); ++i){ - SurfaceCell *sc= map->getSurfaceCell(i, j); - - if(sc->getObject()==NULL || sc->getObject()->getType()==NULL){ - const Pixmap2D *p= world->getTileset()->getSurfPixmap(sc->getSurfaceType(), 0); - color= p->getPixel3f(p->getW()/2, p->getH()/2); - color= color * static_cast(sc->getVertex().y/6.f); - - if(sc->getVertex().y<= world->getMap()->getWaterLevel()){ - color+= Vec3f(0.5f, 0.5f, 1.0f); - } - - if(color.x>1.f) color.x=1.f; - if(color.y>1.f) color.y=1.f; - if(color.z>1.f) color.z=1.f; - } - else{ - color= sc->getObject()->getType()->getColor(); - } - tex->getPixmap()->setPixel(i, j, color); - } - } - } + Vec3f color; + const Map *map = world->getMap(); + + if (tex) { + tex->getPixmap()->setPixels(Vec4f(1.f, 1.f, 1.f, 0.1f).ptr(), + tex->getPixmap()->getComponents()); + + for (int j = 0; j < tex->getPixmap()->getH(); ++j) { + for (int i = 0; i < tex->getPixmap()->getW(); ++i) { + SurfaceCell *sc = map->getSurfaceCell(i, j); + + if (sc->getObject() == NULL || sc->getObject()->getType() == NULL) { + const Pixmap2D *p = + world->getTileset()->getSurfPixmap(sc->getSurfaceType(), 0); + color = p->getPixel3f(p->getW() / 2, p->getH() / 2); + color = color * static_cast(sc->getVertex().y / 6.f); + + if (sc->getVertex().y <= world->getMap()->getWaterLevel()) { + color += Vec3f(0.5f, 0.5f, 1.0f); + } + + if (color.x > 1.f) + color.x = 1.f; + if (color.y > 1.f) + color.y = 1.f; + if (color.z > 1.f) + color.z = 1.f; + } else { + color = sc->getObject()->getType()->getColor(); + } + tex->getPixmap()->setPixel(i, j, color); + } + } + } } void Minimap::saveGame(XmlNode *rootNode) { - std::map mapTagReplacements; - XmlNode *minimapNode = rootNode->addChild("Minimap"); - - if(fowPixmap1 != NULL) { - for(std::size_t index = 0; index < fowPixmap1->getPixelByteCount(); ++index) { - if(fowPixmap1->getPixels()[index] != 0) { - XmlNode *fowPixmap1Node = minimapNode->addChild("fowPixmap1"); - fowPixmap1Node->addAttribute("index",intToStr(index), mapTagReplacements); - fowPixmap1Node->addAttribute("pixel",intToStr(fowPixmap1->getPixels()[index]), mapTagReplacements); - } - } - } + std::map mapTagReplacements; + XmlNode *minimapNode = rootNode->addChild("Minimap"); + + if (fowPixmap1 != NULL) { + for (std::size_t index = 0; index < fowPixmap1->getPixelByteCount(); + ++index) { + if (fowPixmap1->getPixels()[index] != 0) { + XmlNode *fowPixmap1Node = minimapNode->addChild("fowPixmap1"); + fowPixmap1Node->addAttribute("index", intToStr(index), + mapTagReplacements); + fowPixmap1Node->addAttribute("pixel", + intToStr(fowPixmap1->getPixels()[index]), + mapTagReplacements); + } + } + } } void Minimap::loadGame(const XmlNode *rootNode) { - const XmlNode *minimapNode = rootNode->getChild("Minimap"); - - if(minimapNode->hasChild("fowPixmap1") == true) { - vector fowPixmap1NodeList = minimapNode->getChildList("fowPixmap1"); - for(unsigned int i = 0; i < fowPixmap1NodeList.size(); ++i) { - XmlNode *fowPixmap1Node = fowPixmap1NodeList[i]; - - int pixelIndex = fowPixmap1Node->getAttribute("index")->getIntValue(); - fowPixmap1->getPixels()[pixelIndex] = fowPixmap1Node->getAttribute("pixel")->getIntValue(); - } - } + const XmlNode *minimapNode = rootNode->getChild("Minimap"); + + if (minimapNode->hasChild("fowPixmap1") == true) { + vector fowPixmap1NodeList = + minimapNode->getChildList("fowPixmap1"); + for (unsigned int i = 0; i < fowPixmap1NodeList.size(); ++i) { + XmlNode *fowPixmap1Node = fowPixmap1NodeList[i]; + + int pixelIndex = fowPixmap1Node->getAttribute("index")->getIntValue(); + fowPixmap1->getPixels()[pixelIndex] = + fowPixmap1Node->getAttribute("pixel")->getIntValue(); + } + } } -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/world/minimap.h b/source/glest_game/world/minimap.h index 0c8b9e9a1..1ad20381b 100644 --- a/source/glest_game/world/minimap.h +++ b/source/glest_game/world/minimap.h @@ -13,32 +13,29 @@ #define _GLEST_GAME_MINIMAP_H_ #ifdef WIN32 - #include - #include +#include +#include #endif +#include "leak_dumper.h" #include "pixmap.h" #include "texture.h" #include "xml_parser.h" -#include "leak_dumper.h" -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { -using Shared::Graphics::Vec4f; -using Shared::Graphics::Vec3f; -using Shared::Graphics::Vec2i; using Shared::Graphics::Pixmap2D; using Shared::Graphics::Texture2D; +using Shared::Graphics::Vec2i; +using Shared::Graphics::Vec3f; +using Shared::Graphics::Vec4f; using Shared::Xml::XmlNode; class World; class GameSettings; -enum ExplorationState{ - esNotExplored, - esExplored, - esVisible -}; +enum ExplorationState { esNotExplored, esExplored, esVisible }; // ===================================================== // class Minimap @@ -46,49 +43,51 @@ enum ExplorationState{ /// State of the in-game minimap // ===================================================== -class Minimap{ +class Minimap { private: - Pixmap2D *fowPixmap0; - Pixmap2D *fowPixmap1; - Pixmap2D *fowPixmap1_default; - Pixmap2D *fowPixmap0Copy; - Pixmap2D *fowPixmap1Copy; - Pixmap2D *fowPixmap1Copy_default; - - Texture2D *tex; - Texture2D *fowTex; //Fog Of War Texture2D - bool fogOfWar; - const GameSettings *gameSettings; + Pixmap2D *fowPixmap0; + Pixmap2D *fowPixmap1; + Pixmap2D *fowPixmap1_default; + Pixmap2D *fowPixmap0Copy; + Pixmap2D *fowPixmap1Copy; + Pixmap2D *fowPixmap1Copy_default; + + Texture2D *tex; + Texture2D *fowTex; // Fog Of War Texture2D + bool fogOfWar; + const GameSettings *gameSettings; private: - static const float exploredAlpha; + static const float exploredAlpha; public: - void init(int x, int y, const World *world, bool fogOfWar); - Minimap(); - ~Minimap(); + void init(int x, int y, const World *world, bool fogOfWar); + Minimap(); + ~Minimap(); - const Texture2D *getFowTexture() const {return fowTex;} - const Texture2D *getTexture() const {return tex;} + const Texture2D *getFowTexture() const { return fowTex; } + const Texture2D *getTexture() const { return tex; } - void incFowTextureAlphaSurface(const Vec2i sPos, float alpha, bool isIncrementalUpdate=false); - void resetFowTex(); - void updateFowTex(float t); - void setFogOfWar(bool value); + void incFowTextureAlphaSurface(const Vec2i sPos, float alpha, + bool isIncrementalUpdate = false); + void resetFowTex(); + void updateFowTex(float t); + void setFogOfWar(bool value); - void copyFowTex(); - void restoreFowTex(); + void copyFowTex(); + void restoreFowTex(); - void copyFowTexAlphaSurface(); - void restoreFowTexAlphaSurface(); + void copyFowTexAlphaSurface(); + void restoreFowTexAlphaSurface(); - void saveGame(XmlNode *rootNode); - void loadGame(const XmlNode *rootNode); + void saveGame(XmlNode *rootNode); + void loadGame(const XmlNode *rootNode); private: - void computeTexture(const World *world); + void computeTexture(const World *world); }; -}}//end namespace +} // namespace Game +} // namespace Glest #endif diff --git a/source/glest_game/world/scenario.cpp b/source/glest_game/world/scenario.cpp index 922d97c1f..8e6ba4325 100644 --- a/source/glest_game/world/scenario.cpp +++ b/source/glest_game/world/scenario.cpp @@ -11,572 +11,650 @@ #include "scenario.h" -#include -#include "logger.h" -#include "xml_parser.h" -#include "util.h" +#include "config.h" #include "game_util.h" -#include +#include "gen_uuid.h" +#include "lang.h" +#include "leak_dumper.h" +#include "logger.h" #include "platform_common.h" +#include "platform_util.h" #include "properties.h" -#include "lang.h" #include "socket.h" -#include "config.h" -#include "platform_util.h" -#include "gen_uuid.h" -#include "leak_dumper.h" +#include "util.h" +#include "xml_parser.h" +#include +#include using namespace Shared::Xml; using namespace Shared::Util; using namespace Shared::PlatformCommon; using namespace std; -namespace Glest{ namespace Game{ +namespace Glest { +namespace Game { // ===================================================== // class Scenario // ===================================================== -Scenario::~Scenario() { - -} +Scenario::~Scenario() {} Checksum Scenario::load(const string &path) { - //printf("[%s:%s] Line: %d path [%s]\n",__FILE__,__FUNCTION__,__LINE__,path.c_str()); - - Checksum scenarioChecksum; - try { - scenarioChecksum.addFile(path); - checksumValue.addFile(path); + // printf("[%s:%s] Line: %d path + // [%s]\n",__FILE__,__FUNCTION__,__LINE__,path.c_str()); - string name= cutLastExt(lastDir(path)); + Checksum scenarioChecksum; + try { + scenarioChecksum.addFile(path); + checksumValue.addFile(path); - char szBuf[8096]=""; - snprintf(szBuf,8096,Lang::getInstance().getString("LogScreenGameLoadingScenario","",true).c_str(),formatString(name).c_str()); - Logger::getInstance().add(szBuf, true); + string name = cutLastExt(lastDir(path)); - bool isTutorial = Scenario::isGameTutorial(path); + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + Lang::getInstance() + .getString("LogScreenGameLoadingScenario", "", true) + .c_str(), + formatString(name).c_str()); + Logger::getInstance().add(szBuf, true); - //Properties::setTechtreePath(); + bool isTutorial = Scenario::isGameTutorial(path); - //printf("path [%s]\n",path.c_str()); - string scenarioFolder = cutLastFile(formatPath(path)); - endPathWithSlash(scenarioFolder); + // Properties::setTechtreePath(); - if(isTutorial == false) { - Properties::setScenarioPath(scenarioFolder); + // printf("path [%s]\n",path.c_str()); + string scenarioFolder = cutLastFile(formatPath(path)); + endPathWithSlash(scenarioFolder); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("==> Set scenario path to [%s]\n",scenarioFolder.c_str()); - } - else { - Properties::setTutorialPath(scenarioFolder); + if (isTutorial == false) { + Properties::setScenarioPath(scenarioFolder); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("==> Set tutorial path to [%s]\n",scenarioFolder.c_str()); - } + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("==> Set scenario path to [%s]\n", scenarioFolder.c_str()); + } else { + Properties::setTutorialPath(scenarioFolder); - Scenario::loadScenarioInfo(path, &info, isTutorial); - - //parse xml - XmlTree xmlTree; - xmlTree.setSkipUpdatePathClimbingParts(true); - xmlTree.load(path,Properties::getTagReplacementValues()); - const XmlNode *scenarioNode= xmlTree.getRootNode(); - const XmlNode *scriptsNode= scenarioNode->getChild("scripts"); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("==> Set tutorial path to [%s]\n", scenarioFolder.c_str()); + } - for(int i= 0; i < (int)scriptsNode->getChildCount(); ++i){ - const XmlNode *scriptNode = scriptsNode->getChild(i); + Scenario::loadScenarioInfo(path, &info, isTutorial); - scripts.push_back(Script(getFunctionName(scriptNode), scriptNode->getText())); - } - } - //Exception handling (conversions and so on); - catch(const exception &ex) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"In [%s::%s %d]\nError loading scenario [%s]:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,path.c_str(),ex.what()); - SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); + // parse xml + XmlTree xmlTree; + xmlTree.setSkipUpdatePathClimbingParts(true); + xmlTree.load(path, Properties::getTagReplacementValues()); + const XmlNode *scenarioNode = xmlTree.getRootNode(); + const XmlNode *scriptsNode = scenarioNode->getChild("scripts"); - throw megaglest_runtime_error(szBuf); - } + for (int i = 0; i < (int)scriptsNode->getChildCount(); ++i) { + const XmlNode *scriptNode = scriptsNode->getChild(i); - return scenarioChecksum; + scripts.push_back( + Script(getFunctionName(scriptNode), scriptNode->getText())); + } + } + // Exception handling (conversions and so on); + catch (const exception &ex) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "In [%s::%s %d]\nError loading scenario [%s]:\n%s\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, path.c_str(), ex.what()); + SystemFlags::OutputDebug(SystemFlags::debugError, szBuf); + if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) + SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s", szBuf); + + throw megaglest_runtime_error(szBuf); + } + + return scenarioChecksum; } -int Scenario::getScenarioPathIndex(const vector dirList, const string &scenarioName) { - int iIndex = 0; - for(int idx = 0; idx < (int)dirList.size(); idx++) { - string currentPath = dirList[idx]; - endPathWithSlash(currentPath); - string scenarioFile = currentPath + scenarioName + "/" + scenarioName + ".xml"; - if(fileExists(scenarioFile) == true) { - iIndex = idx; - break; - } +int Scenario::getScenarioPathIndex(const vector dirList, + const string &scenarioName) { + int iIndex = 0; + for (int idx = 0; idx < (int)dirList.size(); idx++) { + string currentPath = dirList[idx]; + endPathWithSlash(currentPath); + string scenarioFile = + currentPath + scenarioName + "/" + scenarioName + ".xml"; + if (fileExists(scenarioFile) == true) { + iIndex = idx; + break; } + } - return iIndex; + return iIndex; } -string Scenario::getScenarioDir(const vector dir, const string &scenarioName) { - string scenarioDir = ""; - for(int idx = 0; idx < (int)dir.size(); idx++) { - string currentPath = dir[idx]; - endPathWithSlash(currentPath); - string scenarioFile = currentPath + scenarioName + "/" + scenarioName + ".xml"; - - //printf("\n[%s:%s] Line: %d scenarioName [%s] scenarioFile [%s]\n",__FILE__,__FUNCTION__,__LINE__,scenarioName.c_str(),scenarioFile.c_str()); - - if(fileExists(scenarioFile) == true) { - scenarioDir = currentPath + scenarioName + "/"; - break; - } +string Scenario::getScenarioDir(const vector dir, + const string &scenarioName) { + string scenarioDir = ""; + for (int idx = 0; idx < (int)dir.size(); idx++) { + string currentPath = dir[idx]; + endPathWithSlash(currentPath); + string scenarioFile = + currentPath + scenarioName + "/" + scenarioName + ".xml"; + + // printf("\n[%s:%s] Line: %d scenarioName [%s] scenarioFile + // [%s]\n",__FILE__,__FUNCTION__,__LINE__,scenarioName.c_str(),scenarioFile.c_str()); + + if (fileExists(scenarioFile) == true) { + scenarioDir = currentPath + scenarioName + "/"; + break; } + } - return scenarioDir; + return scenarioDir; } -string Scenario::getScenarioPath(const vector dirList, const string &scenarioName, bool getMatchingRootScenarioPathOnly){ - string scenarioFile = ""; - for(int idx = 0; idx < (int)dirList.size(); idx++) { - string currentPath = dirList[idx]; - endPathWithSlash(currentPath); - scenarioFile = currentPath + scenarioName + "/" + scenarioName + ".xml"; - //printf("\n[%s:%s] Line: %d scenarioName [%s] scenarioFile [%s]\n",__FILE__,__FUNCTION__,__LINE__,scenarioName.c_str(),scenarioFile.c_str()); - - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n[%s:%s] Line: %d scenarioName [%s] scenarioFile [%s]\n",__FILE__,__FUNCTION__,__LINE__,scenarioName.c_str(),scenarioFile.c_str()); - //printf("\n[%s:%s] Line: %d scenarioName [%s] scenarioFile [%s]\n",__FILE__,__FUNCTION__,__LINE__,scenarioName.c_str(),scenarioFile.c_str()); - - if(fileExists(scenarioFile) == true) { - //printf("\n[%s:%s] Line: %d scenarioName [%s] scenarioFile [%s]\n",__FILE__,__FUNCTION__,__LINE__,scenarioName.c_str(),scenarioFile.c_str()); - - if(getMatchingRootScenarioPathOnly == true) { - //printf("\n[%s:%s] Line: %d scenarioName [%s] scenarioFile [%s]\n",__FILE__,__FUNCTION__,__LINE__,scenarioName.c_str(),scenarioFile.c_str()); - scenarioFile = dirList[idx]; - } - break; - } - else { - //printf("\n[%s:%s] Line: %d scenarioName [%s] scenarioFile [%s]\n",__FILE__,__FUNCTION__,__LINE__,scenarioName.c_str(),scenarioFile.c_str()); - scenarioFile = ""; - } +string Scenario::getScenarioPath(const vector dirList, + const string &scenarioName, + bool getMatchingRootScenarioPathOnly) { + string scenarioFile = ""; + for (int idx = 0; idx < (int)dirList.size(); idx++) { + string currentPath = dirList[idx]; + endPathWithSlash(currentPath); + scenarioFile = currentPath + scenarioName + "/" + scenarioName + ".xml"; + // printf("\n[%s:%s] Line: %d scenarioName [%s] scenarioFile + // [%s]\n",__FILE__,__FUNCTION__,__LINE__,scenarioName.c_str(),scenarioFile.c_str()); + + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("\n[%s:%s] Line: %d scenarioName [%s] scenarioFile [%s]\n", + __FILE__, __FUNCTION__, __LINE__, scenarioName.c_str(), + scenarioFile.c_str()); + // printf("\n[%s:%s] Line: %d scenarioName [%s] scenarioFile + // [%s]\n",__FILE__,__FUNCTION__,__LINE__,scenarioName.c_str(),scenarioFile.c_str()); + + if (fileExists(scenarioFile) == true) { + // printf("\n[%s:%s] Line: %d scenarioName [%s] scenarioFile + // [%s]\n",__FILE__,__FUNCTION__,__LINE__,scenarioName.c_str(),scenarioFile.c_str()); + + if (getMatchingRootScenarioPathOnly == true) { + // printf("\n[%s:%s] Line: %d scenarioName [%s] scenarioFile + // [%s]\n",__FILE__,__FUNCTION__,__LINE__,scenarioName.c_str(),scenarioFile.c_str()); + scenarioFile = dirList[idx]; + } + break; + } else { + // printf("\n[%s:%s] Line: %d scenarioName [%s] scenarioFile + // [%s]\n",__FILE__,__FUNCTION__,__LINE__,scenarioName.c_str(),scenarioFile.c_str()); + scenarioFile = ""; } - //printf("\n[%s:%s] Line: %d scenarioName [%s] scenarioFile [%s]\n",__FILE__,__FUNCTION__,__LINE__,scenarioName.c_str(),scenarioFile.c_str()); - return scenarioFile; + } + // printf("\n[%s:%s] Line: %d scenarioName [%s] scenarioFile + // [%s]\n",__FILE__,__FUNCTION__,__LINE__,scenarioName.c_str(),scenarioFile.c_str()); + return scenarioFile; } -string Scenario::getScenarioPath(const string &dir, const string &scenarioName){ - string currentPath = dir; - endPathWithSlash(currentPath); - string scenarioFile = currentPath + scenarioName + "/" + scenarioName + ".xml"; - return scenarioFile; +string Scenario::getScenarioPath(const string &dir, + const string &scenarioName) { + string currentPath = dir; + endPathWithSlash(currentPath); + string scenarioFile = + currentPath + scenarioName + "/" + scenarioName + ".xml"; + return scenarioFile; } -string Scenario::getFunctionName(const XmlNode *scriptNode){ - string name= scriptNode->getName(); +string Scenario::getFunctionName(const XmlNode *scriptNode) { + string name = scriptNode->getName(); - for(int i= 0; i < (int)scriptNode->getAttributeCount(); ++i){ - name+= "_" + scriptNode->getAttribute(i)->getValue(); - } - return name; + for (int i = 0; i < (int)scriptNode->getAttributeCount(); ++i) { + name += "_" + scriptNode->getAttribute(i)->getValue(); + } + return name; } bool Scenario::isGameTutorial(string path) { - bool isTutorial = false; - Config &config = Config::getInstance(); - vector tutorialPaths = config.getPathListForType(ptTutorials); - if(tutorialPaths.empty() == false) { - for(unsigned int tutorialIndex = 0; tutorialIndex < tutorialPaths.size(); ++tutorialIndex) { - const string &tutorialPath = tutorialPaths[tutorialIndex]; - size_t pos = path.find( tutorialPath ); - if( pos != path.npos ) { - isTutorial = true; - break; - } - } + bool isTutorial = false; + Config &config = Config::getInstance(); + vector tutorialPaths = config.getPathListForType(ptTutorials); + if (tutorialPaths.empty() == false) { + for (unsigned int tutorialIndex = 0; tutorialIndex < tutorialPaths.size(); + ++tutorialIndex) { + const string &tutorialPath = tutorialPaths[tutorialIndex]; + size_t pos = path.find(tutorialPath); + if (pos != path.npos) { + isTutorial = true; + break; + } } + } - return isTutorial; + return isTutorial; } -void Scenario::loadScenarioInfo(string file, ScenarioInfo *scenarioInfo, bool isTutorial) { - //printf("[%s:%s] Line: %d file [%s]\n",__FILE__,__FUNCTION__,__LINE__,file.c_str()); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] file [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,file.c_str()); - //printf("In [%s::%s Line: %d] file [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,file.c_str()); - - //printf("[%s:%s] Line: %d file [%s]\n",__FILE__,__FUNCTION__,__LINE__,file.c_str()); - Lang &lang= Lang::getInstance(); - string scenarioDir = cutLastFile(formatPath(file)); - string scenarioName = extractLastDirectoryFromPath(scenarioDir); - scenarioDir = cutLastFile(scenarioDir); - //printf("[%s:%s] Line: %d scenarioDir [%s] scenarioName [%s]\n",__FILE__,__FUNCTION__,__LINE__,scenarioDir.c_str(),scenarioName.c_str()); - - XmlTree xmlTree; - xmlTree.load(file,Properties::getTagReplacementValues()); - - const XmlNode *scenarioNode= xmlTree.getRootNode(); - if(scenarioNode == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"scenarioNode == NULL for file [%s]\n",file.c_str()); - throw std::runtime_error(szBuf); - } - const XmlNode *difficultyNode= scenarioNode->getChild("difficulty"); - if(difficultyNode == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"difficultyNode == NULL for file [%s]\n",file.c_str()); - throw std::runtime_error(szBuf); - } - - scenarioInfo->difficulty = difficultyNode->getAttribute("value")->getIntValue(); - if( scenarioInfo->difficulty < dVeryEasy || scenarioInfo->difficulty > dInsane ) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Invalid difficulty value specified in scenario: %d must be between %d and %d",scenarioInfo->difficulty,dVeryEasy,dInsane); - throw std::runtime_error(szBuf); - } - - const XmlNode *playersNode= scenarioNode->getChild("players"); - if(playersNode == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"playersNode == NULL for file [%s]\n",file.c_str()); - throw std::runtime_error(szBuf); - } - - for(int i= 0; i < GameConstants::maxPlayers; ++i) { - XmlNode* playerNode=NULL; - //string factionTypeName=""; - ControlType factionControl; - - if(playersNode->hasChildAtIndex("player",i)) { - playerNode = playersNode->getChild("player", i); - if(playerNode == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"playerNode == NULL for index = %d for file [%s]\n",i,file.c_str()); - throw std::runtime_error(szBuf); - } - - factionControl = strToControllerType( playerNode->getAttribute("control")->getValue() ); - - if(playerNode->getAttribute("resource_multiplier",false) != NULL) { - // if a multiplier exists use it - scenarioInfo->resourceMultipliers[i]=playerNode->getAttribute("resource_multiplier")->getFloatValue(); - } - else { - // if no multiplier exists use defaults - scenarioInfo->resourceMultipliers[i]=GameConstants::normalMultiplier; - if(factionControl==ctCpuEasy) { - scenarioInfo->resourceMultipliers[i]=GameConstants::easyMultiplier; - } - if(factionControl==ctCpuUltra) { - scenarioInfo->resourceMultipliers[i]=GameConstants::ultraMultiplier; - } - else if(factionControl==ctCpuMega) { - scenarioInfo->resourceMultipliers[i]=GameConstants::megaMultiplier; - } - } - - } - else { - factionControl=ctClosed; - } - - scenarioInfo->factionControls[i] = factionControl; - - if(factionControl != ctClosed) { - int teamIndex = playerNode->getAttribute("team")->getIntValue(); - - if( teamIndex < 1 || teamIndex > GameConstants::maxPlayers + GameConstants::specialFactions) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"Invalid team value specified in scenario: %d must be between %d and %d",teamIndex,1,GameConstants::maxPlayers); - throw std::runtime_error(szBuf); - } - - scenarioInfo->teams[i]= teamIndex; - scenarioInfo->factionTypeNames[i]= playerNode->getAttribute("faction")->getValue(); - } - else { - scenarioInfo->teams[i]= 0; - scenarioInfo->factionTypeNames[i]= ""; - } - - if(scenarioNode->getChild("map") == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"map == NULL for file [%s]\n",file.c_str()); - throw std::runtime_error(szBuf); +void Scenario::loadScenarioInfo(string file, ScenarioInfo *scenarioInfo, + bool isTutorial) { + // printf("[%s:%s] Line: %d file + // [%s]\n",__FILE__,__FUNCTION__,__LINE__,file.c_str()); + if (SystemFlags::VERBOSE_MODE_ENABLED) + printf("In [%s::%s Line: %d] file [%s]\n", + extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, + __LINE__, file.c_str()); + // printf("In [%s::%s Line: %d] file + // [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,file.c_str()); + + // printf("[%s:%s] Line: %d file + // [%s]\n",__FILE__,__FUNCTION__,__LINE__,file.c_str()); + Lang &lang = Lang::getInstance(); + string scenarioDir = cutLastFile(formatPath(file)); + string scenarioName = extractLastDirectoryFromPath(scenarioDir); + scenarioDir = cutLastFile(scenarioDir); + // printf("[%s:%s] Line: %d scenarioDir [%s] scenarioName + // [%s]\n",__FILE__,__FUNCTION__,__LINE__,scenarioDir.c_str(),scenarioName.c_str()); + + XmlTree xmlTree; + xmlTree.load(file, Properties::getTagReplacementValues()); + + const XmlNode *scenarioNode = xmlTree.getRootNode(); + if (scenarioNode == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "scenarioNode == NULL for file [%s]\n", file.c_str()); + throw std::runtime_error(szBuf); + } + const XmlNode *difficultyNode = scenarioNode->getChild("difficulty"); + if (difficultyNode == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "difficultyNode == NULL for file [%s]\n", + file.c_str()); + throw std::runtime_error(szBuf); + } + + scenarioInfo->difficulty = + difficultyNode->getAttribute("value")->getIntValue(); + if (scenarioInfo->difficulty < dVeryEasy || + scenarioInfo->difficulty > dInsane) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "Invalid difficulty value specified in scenario: %d must be " + "between %d and %d", + scenarioInfo->difficulty, dVeryEasy, dInsane); + throw std::runtime_error(szBuf); + } + + const XmlNode *playersNode = scenarioNode->getChild("players"); + if (playersNode == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "playersNode == NULL for file [%s]\n", file.c_str()); + throw std::runtime_error(szBuf); + } + + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + XmlNode *playerNode = NULL; + // string factionTypeName=""; + ControlType factionControl; + + if (playersNode->hasChildAtIndex("player", i)) { + playerNode = playersNode->getChild("player", i); + if (playerNode == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "playerNode == NULL for index = %d for file [%s]\n", i, + file.c_str()); + throw std::runtime_error(szBuf); + } + + factionControl = + strToControllerType(playerNode->getAttribute("control")->getValue()); + + if (playerNode->getAttribute("resource_multiplier", false) != NULL) { + // if a multiplier exists use it + scenarioInfo->resourceMultipliers[i] = + playerNode->getAttribute("resource_multiplier")->getFloatValue(); + } else { + // if no multiplier exists use defaults + scenarioInfo->resourceMultipliers[i] = GameConstants::normalMultiplier; + if (factionControl == ctCpuEasy) { + scenarioInfo->resourceMultipliers[i] = GameConstants::easyMultiplier; } - if(scenarioNode->getChild("tileset") == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"tileset == NULL for file [%s]\n",file.c_str()); - throw std::runtime_error(szBuf); - } - if(scenarioNode->getChild("tech-tree") == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"tech-tree == NULL for file [%s]\n",file.c_str()); - throw std::runtime_error(szBuf); - } - if(scenarioNode->getChild("default-units") == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"default-units == NULL for file [%s]\n",file.c_str()); - throw std::runtime_error(szBuf); - } - if(scenarioNode->getChild("default-resources") == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"default-resources == NULL for file [%s]\n",file.c_str()); - throw std::runtime_error(szBuf); - } - if(scenarioNode->getChild("default-victory-conditions") == NULL) { - char szBuf[8096]=""; - snprintf(szBuf,8096,"default-victory-conditions == NULL for file [%s]\n",file.c_str()); - throw std::runtime_error(szBuf); + if (factionControl == ctCpuUltra) { + scenarioInfo->resourceMultipliers[i] = GameConstants::ultraMultiplier; + } else if (factionControl == ctCpuMega) { + scenarioInfo->resourceMultipliers[i] = GameConstants::megaMultiplier; } + } - scenarioInfo->mapName = scenarioNode->getChild("map")->getAttribute("value")->getValue(); - scenarioInfo->tilesetName = scenarioNode->getChild("tileset")->getAttribute("value")->getValue(); - scenarioInfo->techTreeName = scenarioNode->getChild("tech-tree")->getAttribute("value")->getValue(); - scenarioInfo->defaultUnits = scenarioNode->getChild("default-units")->getAttribute("value")->getBoolValue(); - scenarioInfo->defaultResources = scenarioNode->getChild("default-resources")->getAttribute("value")->getBoolValue(); - scenarioInfo->defaultVictoryConditions = scenarioNode->getChild("default-victory-conditions")->getAttribute("value")->getBoolValue(); + } else { + factionControl = ctClosed; } - //add player info - scenarioInfo->desc= lang.getString("PlayerFaction") + ": "; - for(int i=0; ifactionControls[i] == ctHuman) { - scenarioInfo->desc+= formatString(scenarioInfo->factionTypeNames[i]); - break; - } - } - - //add misc info - string difficultyString = "Difficulty" + intToStr(scenarioInfo->difficulty); - - scenarioInfo->desc+= "\n"; - scenarioInfo->desc+= lang.getString("Difficulty") + ": " + lang.getString(difficultyString) +"\n"; - scenarioInfo->desc+= lang.getString("Map") + ": " + formatString(scenarioInfo->mapName) + "\n"; - scenarioInfo->desc+= lang.getString("Tileset") + ": " + formatString(scenarioInfo->tilesetName) + "\n"; - scenarioInfo->desc+= lang.getString("TechTree") + ": " + formatString(scenarioInfo->techTreeName) + "\n"; - - - //look for description and append it - lang.loadScenarioStrings(scenarioDir,scenarioName.c_str(),isTutorial); - //string tmp_description = lang.getScenarioString("DESCRIPTION"); - string tmp_description = ""; - if(lang.hasScenarioString("DESCRIPTION") == true) { - tmp_description = lang.getScenarioString("DESCRIPTION"); - } - if( tmp_description != "") { - scenarioInfo->desc += lang.getString("Description") + ": \n" + tmp_description + "\n"; - } - - scenarioInfo->namei18n = ""; - if(lang.hasScenarioString("SCENARIO_NAME") == true) { - scenarioInfo->namei18n =lang.getScenarioString("SCENARIO_NAME"); - //printf("scenarioInfo->namei18n [%s]\n",scenarioInfo->namei18n.c_str()); - } - else if(lang.hasScenarioString("TUTORIAL_NAME") == true) { - scenarioInfo->namei18n =lang.getScenarioString("TUTORIAL_NAME"); - //printf("scenarioInfo->namei18n [%s]\n",scenarioInfo->namei18n.c_str()); - } - - if(scenarioNode->hasChild("fog-of-war") == true) { - if(scenarioNode->getChild("fog-of-war")->getAttribute("value")->getValue() == "explored") { - scenarioInfo->fogOfWar = true; - scenarioInfo->fogOfWar_exploredFlag = true; - } - else { - scenarioInfo->fogOfWar = scenarioNode->getChild("fog-of-war")->getAttribute("value")->getBoolValue(); - scenarioInfo->fogOfWar_exploredFlag = false; - } - //printf("\nFOG OF WAR is set to [%d]\n",scenarioInfo->fogOfWar); - } - else { - scenarioInfo->fogOfWar = true; - scenarioInfo->fogOfWar_exploredFlag = false; - } - - if(scenarioNode->hasChild("shared-team-units") == true) { - scenarioInfo->allowTeamUnitSharing=scenarioNode->getChild("shared-team-units")->getAttribute("value")->getBoolValue(); - //printf("\nallowTeamUnitSharing is set to [%s]\n",scenarioInfo->allowTeamUnitSharing); - } - else { - scenarioInfo->allowTeamUnitSharing = false; - } - - if(scenarioNode->hasChild("shared-team-resources") == true) { - scenarioInfo->allowTeamResourceSharing=scenarioNode->getChild("shared-team-resources")->getAttribute("value")->getBoolValue(); - //printf("\nallowTeamResourceSharing is set to [%s]\n",scenarioInfo->allowTeamResourceSharing); - } - else { - scenarioInfo->allowTeamResourceSharing = false; - } - - scenarioInfo->file = file; - scenarioInfo->name = extractFileFromDirectoryPath(file); - scenarioInfo->name = cutLastExt(scenarioInfo->name); - - //scenarioLogoTexture = NULL; - //cleanupPreviewTexture(); - //previewLoadDelayTimer=time(NULL); - //needToLoadTextures=true; -} + scenarioInfo->factionControls[i] = factionControl; + + if (factionControl != ctClosed) { + int teamIndex = playerNode->getAttribute("team")->getIntValue(); + + if (teamIndex < 1 || teamIndex > GameConstants::maxPlayers + + GameConstants::specialFactions) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "Invalid team value specified in scenario: %d must be between " + "%d and %d", + teamIndex, 1, GameConstants::maxPlayers); + throw std::runtime_error(szBuf); + } + + scenarioInfo->teams[i] = teamIndex; + scenarioInfo->factionTypeNames[i] = + playerNode->getAttribute("faction")->getValue(); + } else { + scenarioInfo->teams[i] = 0; + scenarioInfo->factionTypeNames[i] = ""; + } -ControlType Scenario::strToControllerType(const string &str) { - if(str=="closed"){ - return ctClosed; + if (scenarioNode->getChild("map") == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "map == NULL for file [%s]\n", file.c_str()); + throw std::runtime_error(szBuf); + } + if (scenarioNode->getChild("tileset") == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "tileset == NULL for file [%s]\n", file.c_str()); + throw std::runtime_error(szBuf); } - else if(str=="cpu-easy"){ - return ctCpuEasy; + if (scenarioNode->getChild("tech-tree") == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "tech-tree == NULL for file [%s]\n", file.c_str()); + throw std::runtime_error(szBuf); } - else if(str=="cpu"){ - return ctCpu; + if (scenarioNode->getChild("default-units") == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "default-units == NULL for file [%s]\n", + file.c_str()); + throw std::runtime_error(szBuf); } - else if(str=="cpu-ultra"){ - return ctCpuUltra; + if (scenarioNode->getChild("default-resources") == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, "default-resources == NULL for file [%s]\n", + file.c_str()); + throw std::runtime_error(szBuf); } - else if(str=="cpu-mega"){ - return ctCpuMega; + if (scenarioNode->getChild("default-victory-conditions") == NULL) { + char szBuf[8096] = ""; + snprintf(szBuf, 8096, + "default-victory-conditions == NULL for file [%s]\n", + file.c_str()); + throw std::runtime_error(szBuf); } - else if(str=="human"){ - return ctHuman; + + scenarioInfo->mapName = + scenarioNode->getChild("map")->getAttribute("value")->getValue(); + scenarioInfo->tilesetName = + scenarioNode->getChild("tileset")->getAttribute("value")->getValue(); + scenarioInfo->techTreeName = + scenarioNode->getChild("tech-tree")->getAttribute("value")->getValue(); + scenarioInfo->defaultUnits = scenarioNode->getChild("default-units") + ->getAttribute("value") + ->getBoolValue(); + scenarioInfo->defaultResources = scenarioNode->getChild("default-resources") + ->getAttribute("value") + ->getBoolValue(); + scenarioInfo->defaultVictoryConditions = + scenarioNode->getChild("default-victory-conditions") + ->getAttribute("value") + ->getBoolValue(); + } + + // add player info + scenarioInfo->desc = lang.getString("PlayerFaction") + ": "; + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + if (scenarioInfo->factionControls[i] == ctHuman) { + scenarioInfo->desc += formatString(scenarioInfo->factionTypeNames[i]); + break; } - else if(str=="network"){ - return ctNetwork; + } + + // add misc info + string difficultyString = "Difficulty" + intToStr(scenarioInfo->difficulty); + + scenarioInfo->desc += "\n"; + scenarioInfo->desc += lang.getString("Difficulty") + ": " + + lang.getString(difficultyString) + "\n"; + scenarioInfo->desc += + lang.getString("Map") + ": " + formatString(scenarioInfo->mapName) + "\n"; + scenarioInfo->desc += lang.getString("Tileset") + ": " + + formatString(scenarioInfo->tilesetName) + "\n"; + scenarioInfo->desc += lang.getString("TechTree") + ": " + + formatString(scenarioInfo->techTreeName) + "\n"; + + // look for description and append it + lang.loadScenarioStrings(scenarioDir, scenarioName.c_str(), isTutorial); + // string tmp_description = lang.getScenarioString("DESCRIPTION"); + string tmp_description = ""; + if (lang.hasScenarioString("DESCRIPTION") == true) { + tmp_description = lang.getScenarioString("DESCRIPTION"); + } + if (tmp_description != "") { + scenarioInfo->desc += + lang.getString("Description") + ": \n" + tmp_description + "\n"; + } + + scenarioInfo->namei18n = ""; + if (lang.hasScenarioString("SCENARIO_NAME") == true) { + scenarioInfo->namei18n = lang.getScenarioString("SCENARIO_NAME"); + // printf("scenarioInfo->namei18n [%s]\n",scenarioInfo->namei18n.c_str()); + } else if (lang.hasScenarioString("TUTORIAL_NAME") == true) { + scenarioInfo->namei18n = lang.getScenarioString("TUTORIAL_NAME"); + // printf("scenarioInfo->namei18n [%s]\n",scenarioInfo->namei18n.c_str()); + } + + if (scenarioNode->hasChild("fog-of-war") == true) { + if (scenarioNode->getChild("fog-of-war") + ->getAttribute("value") + ->getValue() == "explored") { + scenarioInfo->fogOfWar = true; + scenarioInfo->fogOfWar_exploredFlag = true; + } else { + scenarioInfo->fogOfWar = scenarioNode->getChild("fog-of-war") + ->getAttribute("value") + ->getBoolValue(); + scenarioInfo->fogOfWar_exploredFlag = false; } + // printf("\nFOG OF WAR is set to [%d]\n",scenarioInfo->fogOfWar); + } else { + scenarioInfo->fogOfWar = true; + scenarioInfo->fogOfWar_exploredFlag = false; + } + + if (scenarioNode->hasChild("shared-team-units") == true) { + scenarioInfo->allowTeamUnitSharing = + scenarioNode->getChild("shared-team-units") + ->getAttribute("value") + ->getBoolValue(); + // printf("\nallowTeamUnitSharing is set to + // [%s]\n",scenarioInfo->allowTeamUnitSharing); + } else { + scenarioInfo->allowTeamUnitSharing = false; + } + + if (scenarioNode->hasChild("shared-team-resources") == true) { + scenarioInfo->allowTeamResourceSharing = + scenarioNode->getChild("shared-team-resources") + ->getAttribute("value") + ->getBoolValue(); + // printf("\nallowTeamResourceSharing is set to + // [%s]\n",scenarioInfo->allowTeamResourceSharing); + } else { + scenarioInfo->allowTeamResourceSharing = false; + } + + scenarioInfo->file = file; + scenarioInfo->name = extractFileFromDirectoryPath(file); + scenarioInfo->name = cutLastExt(scenarioInfo->name); + + // scenarioLogoTexture = NULL; + // cleanupPreviewTexture(); + // previewLoadDelayTimer=time(NULL); + // needToLoadTextures=true; +} - char szBuf[8096]=""; - snprintf(szBuf,8096,"Invalid controller value specified in scenario: [%s] must be one of the following: closed, cpu-easy, cpu, cpu-ultra, cpu-mega, human",str.c_str()); - throw std::runtime_error(szBuf); +ControlType Scenario::strToControllerType(const string &str) { + if (str == "closed") { + return ctClosed; + } else if (str == "cpu-easy") { + return ctCpuEasy; + } else if (str == "cpu") { + return ctCpu; + } else if (str == "cpu-ultra") { + return ctCpuUltra; + } else if (str == "cpu-mega") { + return ctCpuMega; + } else if (str == "human") { + return ctHuman; + } else if (str == "network") { + return ctNetwork; + } + + char szBuf[8096] = ""; + snprintf( + szBuf, 8096, + "Invalid controller value specified in scenario: [%s] must be one of the " + "following: closed, cpu-easy, cpu, cpu-ultra, cpu-mega, human", + str.c_str()); + throw std::runtime_error(szBuf); } string Scenario::controllerTypeToStr(const ControlType &ct) { - string controlString = ""; - - Lang &lang= Lang::getInstance(); - switch(ct) { - case ctCpuEasy: - controlString= lang.getString("CpuEasy"); - break; - case ctCpu: - controlString= lang.getString("Cpu"); - break; - case ctCpuUltra: - controlString= lang.getString("CpuUltra"); - break; - case ctCpuMega: - controlString= lang.getString("CpuMega"); - break; - case ctNetwork: - controlString= lang.getString("Network"); - break; - case ctHuman: - controlString= lang.getString("Human"); - break; - - case ctNetworkCpuEasy: - controlString= lang.getString("NetworkCpuEasy"); - break; - case ctNetworkCpu: - controlString= lang.getString("NetworkCpu"); - break; - case ctNetworkCpuUltra: - controlString= lang.getString("NetworkCpuUltra"); - break; - case ctNetworkCpuMega: - controlString= lang.getString("NetworkCpuMega"); - break; - - default: - printf("Error control = %d\n",ct); - //assert(false); - break; - } - - return controlString; + string controlString = ""; + + Lang &lang = Lang::getInstance(); + switch (ct) { + case ctCpuEasy: + controlString = lang.getString("CpuEasy"); + break; + case ctCpu: + controlString = lang.getString("Cpu"); + break; + case ctCpuUltra: + controlString = lang.getString("CpuUltra"); + break; + case ctCpuMega: + controlString = lang.getString("CpuMega"); + break; + case ctNetwork: + controlString = lang.getString("Network"); + break; + case ctHuman: + controlString = lang.getString("Human"); + break; + + case ctNetworkCpuEasy: + controlString = lang.getString("NetworkCpuEasy"); + break; + case ctNetworkCpu: + controlString = lang.getString("NetworkCpu"); + break; + case ctNetworkCpuUltra: + controlString = lang.getString("NetworkCpuUltra"); + break; + case ctNetworkCpuMega: + controlString = lang.getString("NetworkCpuMega"); + break; + + default: + printf("Error control = %d\n", ct); + // assert(false); + break; + } + + return controlString; } void Scenario::loadGameSettings(const vector &dirList, - const ScenarioInfo *scenarioInfo, GameSettings *gameSettings, - string scenarioDescription) { - int factionCount= 0; - int AIPlayerCount=0; - Lang &lang= Lang::getInstance(); - - if(gameSettings->getGameUUID() == "") { - gameSettings->setGameUUID(getUUIDAsString()); - } - - gameSettings->setDescription(scenarioDescription); - gameSettings->setMap(scenarioInfo->mapName); - gameSettings->setTileset(scenarioInfo->tilesetName); - gameSettings->setTech(scenarioInfo->techTreeName); - gameSettings->setScenario(scenarioInfo->name); - gameSettings->setScenarioDir(Scenario::getScenarioPath(dirList, scenarioInfo->name)); - gameSettings->setDefaultUnits(scenarioInfo->defaultUnits); - gameSettings->setDefaultResources(scenarioInfo->defaultResources); - gameSettings->setDefaultVictoryConditions(scenarioInfo->defaultVictoryConditions); - - for(int i = 0; i < GameConstants::maxPlayers; ++i) { - ControlType ct= static_cast(scenarioInfo->factionControls[i]); - if(ct != ctClosed) { - if(ct == ctHuman) { - gameSettings->setThisFactionIndex(factionCount); - - if(gameSettings->getNetworkPlayerName(factionCount) == "") { - gameSettings->setNetworkPlayerName(factionCount,Config::getInstance().getString("NetPlayerName",Socket::getHostName().c_str())); - } - gameSettings->setNetworkPlayerUUID(factionCount,Config::getInstance().getString("PlayerId","")); - gameSettings->setNetworkPlayerPlatform(factionCount,getPlatformNameString()); - } - else if(ct == ctNetwork || ct == ctNetworkUnassigned){ - if(gameSettings->getNetworkPlayerName(factionCount) == "") { - gameSettings->setNetworkPlayerName(factionCount,controllerTypeToStr(ct)); - } - } - else {//this is a CPU player - AIPlayerCount++; - if(gameSettings->getNetworkPlayerName(factionCount) == "") { - gameSettings->setNetworkPlayerName(factionCount,lang.getString("AI") + intToStr(AIPlayerCount)); - } - } - gameSettings->setFactionControl(factionCount, ct); - gameSettings->setResourceMultiplierIndex(factionCount, (scenarioInfo->resourceMultipliers[i]-0.5f)/0.1f); - gameSettings->setTeam(factionCount, scenarioInfo->teams[i]-1); - gameSettings->setStartLocationIndex(factionCount, i); - gameSettings->setFactionTypeName(factionCount, scenarioInfo->factionTypeNames[i]); - factionCount++; - } + const ScenarioInfo *scenarioInfo, + GameSettings *gameSettings, + string scenarioDescription) { + int factionCount = 0; + int AIPlayerCount = 0; + Lang &lang = Lang::getInstance(); + + if (gameSettings->getGameUUID() == "") { + gameSettings->setGameUUID(getUUIDAsString()); + } + + gameSettings->setDescription(scenarioDescription); + gameSettings->setMap(scenarioInfo->mapName); + gameSettings->setTileset(scenarioInfo->tilesetName); + gameSettings->setTech(scenarioInfo->techTreeName); + gameSettings->setScenario(scenarioInfo->name); + gameSettings->setScenarioDir( + Scenario::getScenarioPath(dirList, scenarioInfo->name)); + gameSettings->setDefaultUnits(scenarioInfo->defaultUnits); + gameSettings->setDefaultResources(scenarioInfo->defaultResources); + gameSettings->setDefaultVictoryConditions( + scenarioInfo->defaultVictoryConditions); + + for (int i = 0; i < GameConstants::maxPlayers; ++i) { + ControlType ct = static_cast(scenarioInfo->factionControls[i]); + if (ct != ctClosed) { + if (ct == ctHuman) { + gameSettings->setThisFactionIndex(factionCount); + + if (gameSettings->getNetworkPlayerName(factionCount) == "") { + gameSettings->setNetworkPlayerName( + factionCount, + Config::getInstance().getString("NetPlayerName", + Socket::getHostName().c_str())); + } + gameSettings->setNetworkPlayerUUID( + factionCount, Config::getInstance().getString("PlayerId", "")); + gameSettings->setNetworkPlayerPlatform(factionCount, + getPlatformNameString()); + } else if (ct == ctNetwork || ct == ctNetworkUnassigned) { + if (gameSettings->getNetworkPlayerName(factionCount) == "") { + gameSettings->setNetworkPlayerName(factionCount, + controllerTypeToStr(ct)); + } + } else { // this is a CPU player + AIPlayerCount++; + if (gameSettings->getNetworkPlayerName(factionCount) == "") { + gameSettings->setNetworkPlayerName( + factionCount, lang.getString("AI") + intToStr(AIPlayerCount)); + } + } + gameSettings->setFactionControl(factionCount, ct); + gameSettings->setResourceMultiplierIndex( + factionCount, (scenarioInfo->resourceMultipliers[i] - 0.5f) / 0.1f); + gameSettings->setTeam(factionCount, scenarioInfo->teams[i] - 1); + gameSettings->setStartLocationIndex(factionCount, i); + gameSettings->setFactionTypeName(factionCount, + scenarioInfo->factionTypeNames[i]); + factionCount++; } - - gameSettings->setFactionCount(factionCount); - gameSettings->setFogOfWar(scenarioInfo->fogOfWar); - uint32 valueFlags1 = gameSettings->getFlagTypes1(); - if(scenarioInfo->fogOfWar == false || scenarioInfo->fogOfWar_exploredFlag) { - valueFlags1 |= ft1_show_map_resources; - gameSettings->setFlagTypes1(valueFlags1); - } - else { - valueFlags1 &= ~ft1_show_map_resources; - gameSettings->setFlagTypes1(valueFlags1); - } - - if(scenarioInfo->allowTeamUnitSharing == true) { - valueFlags1 |= ft1_allow_shared_team_units; - gameSettings->setFlagTypes1(valueFlags1); - } - else { - valueFlags1 &= ~ft1_allow_shared_team_units; - gameSettings->setFlagTypes1(valueFlags1); - } - - if(scenarioInfo->allowTeamResourceSharing == true) { - valueFlags1 |= ft1_allow_shared_team_resources; - gameSettings->setFlagTypes1(valueFlags1); - } - else { - valueFlags1 &= ~ft1_allow_shared_team_resources; - gameSettings->setFlagTypes1(valueFlags1); - } - - gameSettings->setPathFinderType(static_cast(Config::getInstance().getInt("ScenarioPathFinderType",intToStr(pfBasic).c_str()))); + } + + gameSettings->setFactionCount(factionCount); + gameSettings->setFogOfWar(scenarioInfo->fogOfWar); + uint32 valueFlags1 = gameSettings->getFlagTypes1(); + if (scenarioInfo->fogOfWar == false || scenarioInfo->fogOfWar_exploredFlag) { + valueFlags1 |= ft1_show_map_resources; + gameSettings->setFlagTypes1(valueFlags1); + } else { + valueFlags1 &= ~ft1_show_map_resources; + gameSettings->setFlagTypes1(valueFlags1); + } + + if (scenarioInfo->allowTeamUnitSharing == true) { + valueFlags1 |= ft1_allow_shared_team_units; + gameSettings->setFlagTypes1(valueFlags1); + } else { + valueFlags1 &= ~ft1_allow_shared_team_units; + gameSettings->setFlagTypes1(valueFlags1); + } + + if (scenarioInfo->allowTeamResourceSharing == true) { + valueFlags1 |= ft1_allow_shared_team_resources; + gameSettings->setFlagTypes1(valueFlags1); + } else { + valueFlags1 &= ~ft1_allow_shared_team_resources; + gameSettings->setFlagTypes1(valueFlags1); + } + + gameSettings->setPathFinderType( + static_cast(Config::getInstance().getInt( + "ScenarioPathFinderType", intToStr(pfBasic).c_str()))); } - -}}//end namespace +} // namespace Game +} // namespace Glest diff --git a/source/glest_game/world/scenario.h b/source/glest_game/world/scenario.h index 549cb62c9..b17f3ba53 100644 --- a/source/glest_game/world/scenario.h +++ b/source/glest_game/world/scenario.h @@ -13,93 +13,87 @@ #define _GLEST_GAME_SCENARIO_H_ #ifdef WIN32 - #include - #include +#include +#include #endif -#include -#include -#include "xml_parser.h" #include "checksum.h" #include "game_settings.h" +#include "xml_parser.h" +#include +#include #include "leak_dumper.h" +using std::pair; using std::string; using std::vector; -using std::pair; using Shared::Xml::XmlNode; using namespace Shared::Util; -namespace Glest { namespace Game { +namespace Glest { +namespace Game { -enum Difficulty { - dVeryEasy, - dEasy, - dMedium, - dHard, - dVeryHard, - dInsane -}; +enum Difficulty { dVeryEasy, dEasy, dMedium, dHard, dVeryHard, dInsane }; class ScenarioInfo { public: - ScenarioInfo() { - difficulty = 0; - for(unsigned int i = 0; i < (unsigned int)GameConstants::maxPlayers; ++i) { - factionControls[i] = ctClosed; - teams[i] = 0; - factionTypeNames[i] = ""; - resourceMultipliers[i] = 0; - } - - mapName = ""; - tilesetName = ""; - techTreeName = ""; - - defaultUnits = false; - defaultResources = false; - defaultVictoryConditions = false; - - desc = ""; - - fogOfWar = false; - fogOfWar_exploredFlag = false; - - allowTeamUnitSharing = false; - allowTeamResourceSharing = false; - - file = ""; - name = ""; - namei18n = ""; - } - int difficulty; - ControlType factionControls[GameConstants::maxPlayers]; - int teams[GameConstants::maxPlayers]; - string factionTypeNames[GameConstants::maxPlayers]; - float resourceMultipliers[GameConstants::maxPlayers]; - - string mapName; - string tilesetName; - string techTreeName; - - bool defaultUnits; - bool defaultResources; - bool defaultVictoryConditions; - - string desc; - - bool fogOfWar; - bool fogOfWar_exploredFlag; - - bool allowTeamUnitSharing; - bool allowTeamResourceSharing; - - string file; - string name; - string namei18n; + ScenarioInfo() { + difficulty = 0; + for (unsigned int i = 0; i < (unsigned int)GameConstants::maxPlayers; ++i) { + factionControls[i] = ctClosed; + teams[i] = 0; + factionTypeNames[i] = ""; + resourceMultipliers[i] = 0; + } + + mapName = ""; + tilesetName = ""; + techTreeName = ""; + + defaultUnits = false; + defaultResources = false; + defaultVictoryConditions = false; + + desc = ""; + + fogOfWar = false; + fogOfWar_exploredFlag = false; + + allowTeamUnitSharing = false; + allowTeamResourceSharing = false; + + file = ""; + name = ""; + namei18n = ""; + } + int difficulty; + ControlType factionControls[GameConstants::maxPlayers]; + int teams[GameConstants::maxPlayers]; + string factionTypeNames[GameConstants::maxPlayers]; + float resourceMultipliers[GameConstants::maxPlayers]; + + string mapName; + string tilesetName; + string techTreeName; + + bool defaultUnits; + bool defaultResources; + bool defaultVictoryConditions; + + string desc; + + bool fogOfWar; + bool fogOfWar_exploredFlag; + + bool allowTeamUnitSharing; + bool allowTeamResourceSharing; + + string file; + string name; + string namei18n; }; // ===================================================== @@ -108,14 +102,17 @@ class ScenarioInfo { class Script { private: - string name; - string code; + string name; + string code; public: - Script(const string &name, const string &code) {this->name= name; this->code= code;} + Script(const string &name, const string &code) { + this->name = name; + this->code = code; + } - const string &getName() const {return name;} - const string &getCode() const {return code;} + const string &getName() const { return name; } + const string &getCode() const { return code; } }; // ===================================================== @@ -124,39 +121,48 @@ class Script { class Scenario { private: - typedef pair NameScriptPair; - typedef vector